Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cyclops-cs): add Fleet activation funnel (#7225)

r33drichards6bf23d05a827
diff --git a/libs/fleet/backend/auth/authz_config.rego b/libs/fleet/backend/auth/authz_config.rego
index 0721c0d3e7..a01d7f69c0 100644
--- a/libs/fleet/backend/auth/authz_config.rego
+++ b/libs/fleet/backend/auth/authz_config.rego
@@ -17,3 +17,8 @@ allow {
input.route == "/api/config"
authz.is_user_key_client
}
+
+allow {
+ input.route == "/api/analytics/session"
+ 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.rego
index dbbd311e9c..eef5a0575c 100644
--- a/libs/fleet/backend/auth/authz_config_test.rego
+++ b/libs/fleet/backend/auth/authz_config_test.rego
@@ -24,3 +24,23 @@ test_user_api_key_config_allowed if {
"user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},
}
}
+
+test_spa_analytics_session_allowed if {
+ route_allow with input as {
+ "route": "/api/analytics/session",
+ "method": "POST",
+ "path": "/api/analytics/session",
+ "params": {},
+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},
+ }
+}
+
+test_user_key_analytics_session_denied if {
+ not route_allow with input as {
+ "route": "/api/analytics/session",
+ "method": "POST",
+ "path": "/api/analytics/session",
+ "params": {},
+ "user": {"sub": "user-123", "azp": "ukey-test", "namespace": "", "email": ""},
+ }
+}
diff --git a/libs/fleet/backend/auth/policy_characterization_test.go b/libs/fleet/backend/auth/policy_characterization_test.go
index 3d33426f91..ff768173bb 100644
--- a/libs/fleet/backend/auth/policy_characterization_test.go
+++ b/libs/fleet/backend/auth/policy_characterization_test.go
@@ -172,6 +172,7 @@ func characterizationCases() map[string][]routeCase {
cases[route] = []routeCase{{name: "plain", params: map[string]string{}, path: path}}
}
simple("/api/config", "/api/config")
+ simple("/api/analytics/session", "/api/analytics/session")
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.go
index 15fe2bde0c..fd778954eb 100644
--- a/libs/fleet/backend/auth/policy_routes.go
+++ b/libs/fleet/backend/auth/policy_routes.go
@@ -277,6 +277,7 @@ var surfacePolicies = map[string]surfacePolicy{
// and one compiled plan.
var routeSurfaces = map[string]string{
"/api/config": "config",
+ "/api/analytics/session": "config",
"/api/state/query": "state-query",
"/api/usage/overview": "usage",
"/api/usage/pool": "usage",
diff --git a/libs/fleet/backend/auth/testdata/route-authorization-table.txt b/libs/fleet/backend/auth/testdata/route-authorization-table.txt
index 5526cbf1a8..0e3f516402 100644
--- a/libs/fleet/backend/auth/testdata/route-authorization-table.txt
+++ b/libs/fleet/backend/auth/testdata/route-authorization-table.txt
@@ -108,6 +108,61 @@
/api/admin/feature-flags/{key} | key | QUERY | spa = deny
/api/admin/feature-flags/{key} | key | QUERY | user-key = deny
/api/admin/feature-flags/{key} | key | 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 = deny
+/api/analytics/session | plain | DELETE | empty-sub = deny
+/api/analytics/session | plain | DELETE | github-oidc = deny
+/api/analytics/session | plain | DELETE | oauth2-proxy = deny
+/api/analytics/session | plain | DELETE | per-key-other-ns = deny
+/api/analytics/session | plain | DELETE | per-key-owned-ns = deny
+/api/analytics/session | plain | DELETE | spa = allow
+/api/analytics/session | plain | DELETE | user-key = deny
+/api/analytics/session | plain | DELETE | user-key-verified = deny
+/api/analytics/session | plain | GET | admin-spa = allow
+/api/analytics/session | plain | GET | cua-cli = deny
+/api/analytics/session | plain | GET | dcr-client = deny
+/api/analytics/session | plain | GET | empty-sub = deny
+/api/analytics/session | plain | GET | github-oidc = deny
+/api/analytics/session | plain | GET | oauth2-proxy = deny
+/api/analytics/session | plain | GET | per-key-other-ns = deny
+/api/analytics/session | plain | GET | per-key-owned-ns = deny
+/api/analytics/session | plain | GET | spa = allow
+/api/analytics/session | plain | GET | user-key = deny
+/api/analytics/session | plain | GET | user-key-verified = deny
+/api/analytics/session | plain | PATCH | admin-spa = allow
+/api/analytics/session | plain | PATCH | cua-cli = deny
+/api/analytics/session | plain | PATCH | dcr-client = deny
+/api/analytics/session | plain | PATCH | empty-sub = deny
+/api/analytics/session | plain | PATCH | github-oidc = deny
+/api/analytics/session | plain | PATCH | oauth2-proxy = deny
+/api/analytics/session | plain | PATCH | per-key-other-ns = deny
+/api/analytics/session | plain | PATCH | per-key-owned-ns = deny
+/api/analytics/session | plain | PATCH | spa = allow
+/api/analytics/session | plain | PATCH | user-key = deny
+/api/analytics/session | plain | PATCH | user-key-verified = deny
+/api/analytics/session | plain | POST | admin-spa = allow
+/api/analytics/session | plain | POST | cua-cli = deny
+/api/analytics/session | plain | POST | dcr-client = deny
+/api/analytics/session | plain | POST | empty-sub = deny
+/api/analytics/session | plain | POST | github-oidc = deny
+/api/analytics/session | plain | POST | oauth2-proxy = deny
+/api/analytics/session | plain | POST | per-key-other-ns = deny
+/api/analytics/session | plain | POST | per-key-owned-ns = deny
+/api/analytics/session | plain | POST | spa = allow
+/api/analytics/session | plain | POST | user-key = deny
+/api/analytics/session | plain | POST | user-key-verified = deny
+/api/analytics/session | plain | QUERY | admin-spa = allow
+/api/analytics/session | plain | QUERY | cua-cli = deny
+/api/analytics/session | plain | QUERY | dcr-client = deny
+/api/analytics/session | plain | QUERY | empty-sub = deny
+/api/analytics/session | plain | QUERY | github-oidc = deny
+/api/analytics/session | plain | QUERY | oauth2-proxy = deny
+/api/analytics/session | plain | QUERY | per-key-other-ns = deny
+/api/analytics/session | plain | QUERY | per-key-owned-ns = deny
+/api/analytics/session | plain | QUERY | spa = allow
+/api/analytics/session | plain | QUERY | user-key = deny
+/api/analytics/session | plain | QUERY | user-key-verified = deny
/api/billing/portal-session | plain | DELETE | admin-spa = allow
/api/billing/portal-session | plain | DELETE | cua-cli = deny
/api/billing/portal-session | plain | DELETE | dcr-client = deny
diff --git a/libs/fleet/backend/billing/service.go b/libs/fleet/backend/billing/service.go
index 2a6701c152..c72096af5c 100644
--- a/libs/fleet/backend/billing/service.go
+++ b/libs/fleet/backend/billing/service.go
@@ -17,6 +17,7 @@ const (
CustomerIdempotencyPrefix = "fleet-customer-"
SetupPurpose = "fleet_default_card"
MetadataSetupGeneration = "fleet_setup_generation"
+ MetadataSetupSource = "fleet_source"
)
var (
@@ -41,6 +42,8 @@ type SetupSessionRequest struct {
SuccessURL string
CancelURL string
SetupGeneration string
+ Subject string
+ Source string
}
type PortalSessionRequest struct {
@@ -344,6 +347,7 @@ func (s *Service) Usage(ctx context.Context, subject string, months int, now tim
type SetupOptions struct {
SuccessURL string
CancelURL string
+ Source string
}
func (s *Service) CreateSetupSession(ctx context.Context, subject string, options SetupOptions) (string, error) {
@@ -360,6 +364,8 @@ func (s *Service) CreateSetupSession(ctx context.Context, subject string, option
SuccessURL: options.SuccessURL,
CancelURL: options.CancelURL,
SetupGeneration: generation,
+ Subject: subject,
+ Source: options.Source,
})
if err != nil {
return "", err
diff --git a/libs/fleet/backend/billing/service_test.go b/libs/fleet/backend/billing/service_test.go
index a42b97f92c..dbf63bb065 100644
--- a/libs/fleet/backend/billing/service_test.go
+++ b/libs/fleet/backend/billing/service_test.go
@@ -344,6 +344,7 @@ func TestCreateSetupSessionUsesServerRequestAndOwnedCustomer(t *testing.T) {
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",
})
if err != nil {
t.Fatalf("CreateSetupSession() error = %v", err)
@@ -356,6 +357,8 @@ func TestCreateSetupSessionUsesServerRequestAndOwnedCustomer(t *testing.T) {
SuccessURL: "https://run.example.test/billing?checkout=success",
CancelURL: "https://run.example.test/billing?checkout=cancelled",
SetupGeneration: gateway.updatedMetadata[MetadataSetupGeneration],
+ Subject: "subject-123",
+ Source: "spa",
}
if want.SetupGeneration == "" || !reflect.DeepEqual(gateway.setupRequest, want) {
t.Fatalf("setup request = %#v, want %#v", gateway.setupRequest, want)
diff --git a/libs/fleet/backend/billing/stripe_gateway.go b/libs/fleet/backend/billing/stripe_gateway.go
index 8ecfcd1dcf..79f189e4ae 100644
--- a/libs/fleet/backend/billing/stripe_gateway.go
+++ b/libs/fleet/backend/billing/stripe_gateway.go
@@ -165,6 +165,8 @@ func setupSessionParams(request SetupSessionRequest) *stripe.CheckoutSessionCrea
setupIntentData := &stripe.CheckoutSessionCreateSetupIntentDataParams{}
setupIntentData.AddMetadata("purpose", SetupPurpose)
setupIntentData.AddMetadata(MetadataSetupGeneration, request.SetupGeneration)
+ setupIntentData.AddMetadata(MetadataSubject, request.Subject)
+ setupIntentData.AddMetadata(MetadataSetupSource, request.Source)
return &stripe.CheckoutSessionCreateParams{
Mode: stripe.String(string(stripe.CheckoutSessionModeSetup)),
Customer: stripe.String(request.CustomerID),
diff --git a/libs/fleet/backend/billing/stripe_gateway_test.go b/libs/fleet/backend/billing/stripe_gateway_test.go
index 57a5030cc4..6458dc8a0d 100644
--- a/libs/fleet/backend/billing/stripe_gateway_test.go
+++ b/libs/fleet/backend/billing/stripe_gateway_test.go
@@ -119,11 +119,19 @@ func TestSetupSessionParamsCopyLatestCustomerGenerationToSetupIntent(t *testing.
SuccessURL: "https://run.example.test/settings?setup=success",
CancelURL: "https://run.example.test/settings?setup=cancelled",
SetupGeneration: "server-generated-token",
+ Subject: "subject-1",
+ Source: "spa",
})
if got := params.SetupIntentData.Metadata[MetadataSetupGeneration]; got != "server-generated-token" {
t.Fatalf("setup intent generation = %q, want server-generated-token", got)
}
+ if got := params.SetupIntentData.Metadata[MetadataSubject]; got != "subject-1" {
+ t.Fatalf("setup intent subject = %q, want subject-1", got)
+ }
+ if got := params.SetupIntentData.Metadata[MetadataSetupSource]; got != "spa" {
+ t.Fatalf("setup intent source = %q, want spa", got)
+ }
}
func TestCurrentSetupGenerationRejectsStaleAndMalformedValues(t *testing.T) {
diff --git a/libs/fleet/backend/billing/webhook.go b/libs/fleet/backend/billing/webhook.go
index ba41a96f55..7db140e2e0 100644
--- a/libs/fleet/backend/billing/webhook.go
+++ b/libs/fleet/backend/billing/webhook.go
@@ -3,6 +3,7 @@ package billing
import (
"encoding/json"
+ "cyclops-cs-backend/productanalytics"
"github.com/stripe/stripe-go/v85"
"github.com/stripe/stripe-go/v85/webhook"
)
@@ -11,6 +12,8 @@ type WebhookEvent struct {
ID string
Type string
Purpose string
+ Subject string
+ Source string
CustomerID string
PaymentMethodID string
SetupGeneration string
@@ -37,7 +40,7 @@ func (StripeWebhookVerifier) Verify(payload []byte, signature, secret string) (W
return WebhookEvent{}, nil
}
event := WebhookEvent{ID: envelope.ID, Type: envelope.Type}
- if envelope.Type != "setup_intent.succeeded" {
+ if envelope.Type != "setup_intent.succeeded" && envelope.Type != "setup_intent.setup_failed" {
return event, nil
}
@@ -47,6 +50,11 @@ func (StripeWebhookVerifier) Verify(payload []byte, signature, secret string) (W
}
event.Purpose = setupIntent.Metadata["purpose"]
event.SetupGeneration = setupIntent.Metadata[MetadataSetupGeneration]
+ source := setupIntent.Metadata[MetadataSetupSource]
+ if subject := setupIntent.Metadata[MetadataSubject]; subject != "" && (source == productanalytics.SourceSPA || source == productanalytics.SourceUserKey) {
+ event.Subject = subject
+ event.Source = source
+ }
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.go
index 8e85af7f10..97209b7546 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"}
+ "metadata":{"purpose":"fleet_default_card","fleet_subject":"subject-1","fleet_source":"spa"}
}}
}`)
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, CustomerID: "cus_owned", PaymentMethodID: "pm_card",
+ Purpose: SetupPurpose, Subject: "subject-1", Source: "spa", CustomerID: "cus_owned", PaymentMethodID: "pm_card",
}
if event != want {
t.Fatalf("event = %#v, want %#v", event, want)
@@ -86,3 +86,30 @@ func TestVerifyParsesServerSetupGeneration(t *testing.T) {
t.Fatalf("setup generation = %q, want server-generated-token", event.SetupGeneration)
}
}
+
+func TestVerifyParsesFleetSetupIntentFailedAttribution(t *testing.T) {
+ secret := "whsec_test"
+ payload := []byte(`{"id":"evt_failed","type":"setup_intent.setup_failed","data":{"object":{"id":"seti_123","object":"setup_intent","metadata":{"purpose":"fleet_default_card","fleet_subject":"subject-1","fleet_source":"spa","fleet_setup_generation":"generation-1"}}}}`)
+ signature := billingStripeSignature(payload, secret, time.Now().Unix())
+ event, err := NewStripeWebhookVerifier().Verify(payload, signature, secret)
+ if err != nil {
+ t.Fatalf("Verify() error = %v", err)
+ }
+ want := WebhookEvent{ID: "evt_failed", Type: "setup_intent.setup_failed", Purpose: SetupPurpose, Subject: "subject-1", Source: "spa", SetupGeneration: "generation-1"}
+ if event != want {
+ t.Fatalf("event = %#v, want %#v", event, want)
+ }
+}
+
+func TestVerifyDropsUnsupportedSetupSource(t *testing.T) {
+ secret := "whsec_test"
+ payload := []byte(`{"id":"evt_failed","type":"setup_intent.setup_failed","data":{"object":{"id":"seti_123","object":"setup_intent","metadata":{"purpose":"fleet_default_card","fleet_subject":"subject-1","fleet_source":"github"}}}}`)
+ signature := billingStripeSignature(payload, secret, time.Now().Unix())
+ event, err := NewStripeWebhookVerifier().Verify(payload, signature, secret)
+ if err != nil {
+ t.Fatalf("Verify() error = %v", err)
+ }
+ if event.Subject != "" || event.Source != "" {
+ t.Fatalf("untrusted attribution = subject %q source %q", event.Subject, event.Source)
+ }
+}
diff --git a/libs/fleet/backend/config/config.go b/libs/fleet/backend/config/config.go
index be35361c9d..5cd08ff781 100644
--- a/libs/fleet/backend/config/config.go
+++ b/libs/fleet/backend/config/config.go
@@ -27,16 +27,17 @@ import (
)
type Configuration struct {
- WebServer WebServerConfiguration
- Auth AuthConfiguration
- Keycloak KeycloakConfiguration
- Gateway GatewayConfiguration
- Database DatabaseConfiguration
- Stripe StripeConfiguration
- Chat ChatConfiguration
- Metrics MetricsConfiguration
- Telemetry TelemetryConfiguration
- Usage UsageConfiguration
+ WebServer WebServerConfiguration
+ Auth AuthConfiguration
+ Keycloak KeycloakConfiguration
+ Gateway GatewayConfiguration
+ Database DatabaseConfiguration
+ Stripe StripeConfiguration
+ Chat ChatConfiguration
+ Metrics MetricsConfiguration
+ Telemetry TelemetryConfiguration
+ Usage UsageConfiguration
+ ProductAnalytics ProductAnalyticsConfiguration
}
type WebServerConfiguration struct {
@@ -142,6 +143,14 @@ type MetricsConfiguration struct {
Addr string // METRICS_ADDR — Prometheus listen addr
}
+type ProductAnalyticsConfiguration struct {
+ Enabled bool
+ Host string
+ ProjectToken string
+ Environment string
+ ExcludedSubjects []string
+}
+
type TelemetryConfiguration struct {
Endpoint string // OTEL_EXPORTER_OTLP_ENDPOINT
Protocol string // OTEL_EXPORTER_OTLP_PROTOCOL
@@ -201,6 +210,10 @@ var specs = []flagSpec{
{"chat.api-key", "litellm-api-key", "LITELLM_API_KEY", "", "LiteLLM virtual key"},
{"chat.model", "litellm-model", "LITELLM_MODEL", "large", "LiteLLM model alias"},
{"metrics.addr", "metrics-addr", "METRICS_ADDR", ":9091", "Prometheus metrics listen address"},
+ {"product-analytics.enabled", "fleet-analytics-enabled", "FLEET_ANALYTICS_ENABLED", "false", "Enable Fleet product analytics delivery"},
+ {"product-analytics.host", "posthog-host", "POSTHOG_HOST", "https://eu.i.posthog.com", "PostHog capture host"},
+ {"product-analytics.project-token", "posthog-project-token", "POSTHOG_PROJECT_TOKEN", "", "PostHog project token"},
+ {"product-analytics.excluded-subjects", "fleet-analytics-excluded-subs", "FLEET_ANALYTICS_EXCLUDED_SUBS", "", "Comma-separated Keycloak subjects excluded from analytics"},
{"telemetry.endpoint", "otel-endpoint", "OTEL_EXPORTER_OTLP_ENDPOINT", "https://otel.cua.ai", "OTLP HTTP traces endpoint"},
{"telemetry.protocol", "otel-protocol", "OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf", "OTLP exporter protocol"},
{"telemetry.service-name", "otel-service-name", "OTEL_SERVICE_NAME", "cyclops-cs-backend", "OTEL service.name"},
@@ -323,6 +336,13 @@ func LoadConfig() (*Configuration, error) {
MaxResponseBytes: usageMaxResponseBytes,
},
Metrics: MetricsConfiguration{Addr: viper.GetString("metrics.addr")},
+ ProductAnalytics: ProductAnalyticsConfiguration{
+ Enabled: viper.GetBool("product-analytics.enabled"),
+ Host: strings.TrimSpace(viper.GetString("product-analytics.host")),
+ ProjectToken: strings.TrimSpace(viper.GetString("product-analytics.project-token")),
+ Environment: strings.TrimSpace(viper.GetString("telemetry.environment")),
+ ExcludedSubjects: splitCommaSeparated(viper.GetString("product-analytics.excluded-subjects")),
+ },
Telemetry: TelemetryConfiguration{
Endpoint: viper.GetString("telemetry.endpoint"),
Protocol: viper.GetString("telemetry.protocol"),
diff --git a/libs/fleet/backend/config/config_test.go b/libs/fleet/backend/config/config_test.go
index 66ba63ec2c..af74e70f1d 100644
--- a/libs/fleet/backend/config/config_test.go
+++ b/libs/fleet/backend/config/config_test.go
@@ -320,3 +320,29 @@ func TestLoadConfig_UsageConfiguration(t *testing.T) {
})
}
}
+
+func TestLoadConfig_ProductAnalyticsValues(t *testing.T) {
+ viper.Reset()
+ t.Cleanup(viper.Reset)
+ t.Setenv("KC_ADMIN_CLIENT_SECRET", "secret")
+ t.Setenv("FLEET_ANALYTICS_ENABLED", "true")
+ t.Setenv("POSTHOG_HOST", "https://eu.i.posthog.com")
+ t.Setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
+ t.Setenv("FLEET_ANALYTICS_EXCLUDED_SUBS", "internal-1, internal-2")
+ t.Setenv("OTEL_ENVIRONMENT", "production")
+ RegisterFlags(pflag.NewFlagSet("analytics-test", pflag.ContinueOnError))
+
+ cfg, err := LoadConfig()
+ if err != nil {
+ t.Fatalf("LoadConfig() error = %v", err)
+ }
+ if !cfg.ProductAnalytics.Enabled || cfg.ProductAnalytics.Host != "https://eu.i.posthog.com" || cfg.ProductAnalytics.ProjectToken != "phc_test" {
+ t.Fatalf("ProductAnalytics = %#v", cfg.ProductAnalytics)
+ }
+ if got, want := cfg.ProductAnalytics.Environment, "production"; got != want {
+ t.Fatalf("Environment = %q, want %q", got, want)
+ }
+ if got, want := cfg.ProductAnalytics.ExcludedSubjects, []string{"internal-1", "internal-2"}; !slices.Equal(got, want) {
+ t.Fatalf("ExcludedSubjects = %#v, want %#v", got, want)
+ }
+}
diff --git a/libs/fleet/backend/handlers/analytics.go b/libs/fleet/backend/handlers/analytics.go
new file mode 100644
index 0000000000..ba1dba8745
--- /dev/null
+++ b/libs/fleet/backend/handlers/analytics.go
@@ -0,0 +1,36 @@
+package handlers
+
+import (
+ "net/http"
+
+ "cyclops-cs-backend/auth"
+ "cyclops-cs-backend/middlewares"
+ "cyclops-cs-backend/productanalytics"
+)
+
+func (h Handlers) RecordAnalyticsSession(w http.ResponseWriter, r *http.Request) {
+ 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
+ }
+ traceID, _ := r.Context().Value(middlewares.ContextKey("traceId")).(string)
+ capturer := h.Analytics
+ if capturer == nil {
+ capturer = productanalytics.Nop()
+ }
+ capturer.Capture(productanalytics.Event{
+ Name: productanalytics.EventLoginSucceeded, DistinctID: user.ID, InsertID: traceID,
+ Properties: map[string]any{
+ "outcome": productanalytics.OutcomeSuccess,
+ "source": source,
+ "principal_type": auth.PrincipalTypeUser,
+ },
+ })
+ w.WriteHeader(http.StatusNoContent)
+}
diff --git a/libs/fleet/backend/handlers/analytics_test.go b/libs/fleet/backend/handlers/analytics_test.go
new file mode 100644
index 0000000000..5965989b91
--- /dev/null
+++ b/libs/fleet/backend/handlers/analytics_test.go
@@ -0,0 +1,58 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "cyclops-cs-backend/auth"
+ "cyclops-cs-backend/config"
+ "cyclops-cs-backend/middlewares"
+ "cyclops-cs-backend/productanalytics"
+)
+
+func configAuthForAnalytics() config.AuthConfiguration {
+ return config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"}
+}
+
+type analyticsCapture struct{ events []productanalytics.Event }
+
+func (capture *analyticsCapture) Capture(event productanalytics.Event) {
+ capture.events = append(capture.events, event)
+}
+
+func TestRecordAnalyticsSessionCapturesSuccessfulSPALogin(t *testing.T) {
+ capture := &analyticsCapture{}
+ h := Handlers{Analytics: capture, AuthCfg: configAuthForAnalytics()}
+ request := httptest.NewRequest(http.MethodPost, "/api/analytics/session", nil)
+ ctx := context.WithValue(request.Context(), auth.UserKey, &auth.User{ID: "subject-1", AZP: "cyclops-cs-spa", PrincipalType: auth.PrincipalTypeUser})
+ ctx = context.WithValue(ctx, middlewares.ContextKey("traceId"), "trace-1")
+ response := httptest.NewRecorder()
+
+ h.RecordAnalyticsSession(response, request.WithContext(ctx))
+
+ if response.Code != http.StatusNoContent {
+ t.Fatalf("status = %d", response.Code)
+ }
+ if len(capture.events) != 1 {
+ t.Fatalf("events = %#v", capture.events)
+ }
+ event := capture.events[0]
+ if event.Name != productanalytics.EventLoginSucceeded || event.DistinctID != "subject-1" || event.InsertID != "trace-1" {
+ t.Fatalf("event = %#v", event)
+ }
+ if event.Properties["outcome"] != productanalytics.OutcomeSuccess || event.Properties["source"] != productanalytics.SourceSPA {
+ t.Fatalf("properties = %#v", event.Properties)
+ }
+}
+
+func TestRecordAnalyticsSessionRequiresUser(t *testing.T) {
+ capture := &analyticsCapture{}
+ h := Handlers{Analytics: capture, AuthCfg: configAuthForAnalytics()}
+ response := httptest.NewRecorder()
+ h.RecordAnalyticsSession(response, httptest.NewRequest(http.MethodPost, "/api/analytics/session", nil))
+ if response.Code != http.StatusUnauthorized || len(capture.events) != 0 {
+ t.Fatalf("status/events = %d/%#v", response.Code, capture.events)
+ }
+}
diff --git a/libs/fleet/backend/handlers/billing.go b/libs/fleet/backend/handlers/billing.go
index 0f55bd6c46..46dabb0af4 100644
--- a/libs/fleet/backend/handlers/billing.go
+++ b/libs/fleet/backend/handlers/billing.go
@@ -12,6 +12,8 @@ import (
"cyclops-cs-backend/auth"
"cyclops-cs-backend/billing"
+ "cyclops-cs-backend/middlewares"
+ "cyclops-cs-backend/productanalytics"
)
type BillingService interface {
@@ -167,11 +169,28 @@ func (h Handlers) CreateBillingSetupSession(w http.ResponseWriter, r *http.Reque
writeErr(w, http.StatusServiceUnavailable, "Stripe card setup is not configured; redirect URLs are required")
return
}
+ source, sourceOK := productanalytics.SourceForUser(user, h.AuthCfg.SPAClientID)
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",
+ },
+ })
+ }
writeErr(w, http.StatusBadGateway, "could not create Stripe card setup Session")
return
}
diff --git a/libs/fleet/backend/handlers/billing_test.go b/libs/fleet/backend/handlers/billing_test.go
index c5456389db..fed751bf11 100644
--- a/libs/fleet/backend/handlers/billing_test.go
+++ b/libs/fleet/backend/handlers/billing_test.go
@@ -3,6 +3,7 @@ package handlers
import (
"context"
"encoding/json"
+ "errors"
"net/http"
"net/http/httptest"
"strings"
@@ -12,6 +13,7 @@ import (
"cyclops-cs-backend/auth"
"cyclops-cs-backend/billing"
"cyclops-cs-backend/config"
+ "cyclops-cs-backend/productanalytics"
"github.com/trycua/cloud/pkg/featureflags"
)
@@ -24,6 +26,7 @@ type fakeBillingService struct {
portalSubject string
portalReturnURL string
setupCalls int
+ setupErr error
portalCalls int
defaultCustomerID string
defaultPaymentMethodID string
@@ -59,6 +62,9 @@ func (f *fakeBillingService) CreateSetupSession(_ context.Context, subject strin
f.setupCalls++
f.setupSubject = subject
f.setupOptions = options
+ if f.setupErr != nil {
+ return "", f.setupErr
+ }
return "https://checkout.stripe.test/session", nil
}
@@ -75,7 +81,7 @@ func (f *fakeBillingService) Usage(_ context.Context, subject string, months int
return f.usageResponse, f.usageErr
}
-var billingAlice = &auth.User{ID: "user-alice"}
+var billingAlice = &auth.User{ID: "user-alice", AZP: "cyclops-cs-spa", PrincipalType: auth.PrincipalTypeUser}
func newBillingRequest(method, target, body string, user *auth.User) *http.Request {
var request *http.Request
@@ -192,6 +198,7 @@ func TestCreateSetupSessionUsesAuthenticatedSubjectAndNoClientInput(t *testing.T
service := &fakeBillingService{}
h := Handlers{
Billing: service,
+ AuthCfg: config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"},
Stripe: config.StripeConfiguration{
SecretKey: "sk_test",
CheckoutSuccessURL: "https://run.example.test/settings?setup=success",
@@ -216,6 +223,9 @@ func TestCreateSetupSessionUsesAuthenticatedSubjectAndNoClientInput(t *testing.T
if service.setupSubject != billingAlice.ID {
t.Fatalf("setup subject = %q, want %q", service.setupSubject, billingAlice.ID)
}
+ if service.setupOptions.Source != productanalytics.SourceSPA {
+ t.Fatalf("setup source = %q, want spa", service.setupOptions.Source)
+ }
var response BillingSessionResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatal(err)
@@ -311,3 +321,24 @@ func TestBillingEndpointsRejectWhenFlagDisabled(t *testing.T) {
})
}
}
+
+func TestCreateSetupSessionProviderFailureEmitsFailureEvent(t *testing.T) {
+ setBillingFlag(t, true)
+ service := &fakeBillingService{setupErr: errors.New("stripe unavailable")}
+ capture := &analyticsCapture{}
+ 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", "", billingAlice))
+ if response.Code != http.StatusBadGateway || 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 != billingAlice.ID || event.Properties["outcome"] != productanalytics.OutcomeFailure || event.Properties["error_class"] != "payment_provider" {
+ t.Fatalf("event = %#v", event)
+ }
+}
diff --git a/libs/fleet/backend/handlers/billing_webhook.go b/libs/fleet/backend/handlers/billing_webhook.go
index feac1b36bd..4924697fdc 100644
--- a/libs/fleet/backend/handlers/billing_webhook.go
+++ b/libs/fleet/backend/handlers/billing_webhook.go
@@ -5,8 +5,10 @@ import (
"io"
"net/http"
+ "cyclops-cs-backend/auth"
"cyclops-cs-backend/billing"
"cyclops-cs-backend/metrics"
+ "cyclops-cs-backend/productanalytics"
)
const stripeWebhookBodyLimit = 64 << 10
@@ -54,7 +56,23 @@ func (h Handlers) HandleBillingWebhook(w http.ResponseWriter, r *http.Request) {
return
}
- if event.Type != "setup_intent.succeeded" || event.Purpose != billing.SetupPurpose {
+ if event.Purpose != billing.SetupPurpose {
+ metrics.RecordBillingWebhook("ignored", event.Type)
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ if event.Type == "setup_intent.setup_failed" {
+ if event.Subject == "" || event.Source == "" || event.SetupGeneration == "" {
+ metrics.RecordBillingWebhook("malformed", event.Type)
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ capturePaymentSetup(h.Analytics, event, productanalytics.OutcomeFailure, "payment_provider")
+ metrics.RecordBillingWebhook("setup_failed", event.Type)
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ if event.Type != "setup_intent.succeeded" {
metrics.RecordBillingWebhook("ignored", event.Type)
w.WriteHeader(http.StatusNoContent)
return
@@ -80,6 +98,30 @@ func (h Handlers) HandleBillingWebhook(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
return
}
+ capturePaymentSetup(h.Analytics, event, productanalytics.OutcomeSuccess, "")
metrics.RecordBillingWebhook("configured", event.Type)
w.WriteHeader(http.StatusNoContent)
}
+
+func capturePaymentSetup(capturer productanalytics.Capturer, event billing.WebhookEvent, outcome, errorClass string) {
+ if event.Subject == "" || (event.Source != productanalytics.SourceSPA && event.Source != productanalytics.SourceUserKey) {
+ return
+ }
+ if capturer == nil {
+ capturer = productanalytics.Nop()
+ }
+ principalType := auth.PrincipalTypeUser
+ if event.Source == productanalytics.SourceUserKey {
+ principalType = auth.PrincipalTypeUserKey
+ }
+ properties := map[string]any{
+ "outcome": outcome, "source": event.Source, "principal_type": principalType,
+ }
+ if errorClass != "" {
+ properties["error_class"] = errorClass
+ }
+ capturer.Capture(productanalytics.Event{
+ Name: productanalytics.EventPaymentMethodSetup, DistinctID: event.Subject,
+ InsertID: event.ID, Properties: properties,
+ })
+}
diff --git a/libs/fleet/backend/handlers/billing_webhook_test.go b/libs/fleet/backend/handlers/billing_webhook_test.go
index 900b419728..bdd890f5ab 100644
--- a/libs/fleet/backend/handlers/billing_webhook_test.go
+++ b/libs/fleet/backend/handlers/billing_webhook_test.go
@@ -14,6 +14,7 @@ import (
"cyclops-cs-backend/billing"
"cyclops-cs-backend/config"
+ "cyclops-cs-backend/productanalytics"
)
func stripeTestSignature(payload []byte, secret string, timestamp int64) string {
@@ -193,3 +194,54 @@ func TestBillingWebhookIgnoresMissingSetupGeneration(t *testing.T) {
t.Fatalf("status/calls = %d/%d, want 204/0", response.Code, service.defaultCalls)
}
}
+
+func runBillingWebhookWithAnalytics(t *testing.T, service *fakeBillingService, event billing.WebhookEvent, capture *analyticsCapture) *httptest.ResponseRecorder {
+ t.Helper()
+ h := Handlers{Billing: service, Analytics: capture, Stripe: config.StripeConfiguration{WebhookSecret: "whsec_test"}, WebhookVerifier: fakeWebhookVerifier{event: event}}
+ request := httptest.NewRequest(http.MethodPost, "/api/billing/webhook", strings.NewReader("{}"))
+ response := httptest.NewRecorder()
+ h.HandleBillingWebhook(response, request)
+ return response
+}
+
+func 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)
+ 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 {
+ t.Fatalf("event = %#v", event)
+ }
+}
+
+func TestBillingWebhookDoesNotEmitForStaleGeneration(t *testing.T) {
+ service := &fakeBillingService{defaultApplied: false}
+ capture := &analyticsCapture{}
+ runBillingWebhookWithAnalytics(t, service, billing.WebhookEvent{ID: "evt_stale", Type: "setup_intent.succeeded", Purpose: billing.SetupPurpose, Subject: "subject-1", Source: productanalytics.SourceSPA, CustomerID: "cus_owned", PaymentMethodID: "pm_card", SetupGeneration: "old"}, capture)
+ if len(capture.events) != 0 {
+ t.Fatalf("events = %#v", capture.events)
+ }
+}
+
+func TestBillingWebhookEmitsTrustedTerminalPaymentFailure(t *testing.T) {
+ capture := &analyticsCapture{}
+ response := runBillingWebhookWithAnalytics(t, &fakeBillingService{}, billing.WebhookEvent{ID: "evt_failed", Type: "setup_intent.setup_failed", Purpose: billing.SetupPurpose, Subject: "subject-1", Source: productanalytics.SourceSPA, 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.InsertID != "evt_failed" || event.Properties["outcome"] != productanalytics.OutcomeFailure || event.Properties["error_class"] != "payment_provider" {
+ t.Fatalf("event = %#v", event)
+ }
+}
+
+func TestBillingWebhookMissingSubjectEmitsNothing(t *testing.T) {
+ capture := &analyticsCapture{}
+ runBillingWebhookWithAnalytics(t, &fakeBillingService{}, billing.WebhookEvent{ID: "evt_failed", Type: "setup_intent.setup_failed", Purpose: billing.SetupPurpose, Source: productanalytics.SourceSPA, SetupGeneration: "current"}, capture)
+ if len(capture.events) != 0 {
+ t.Fatalf("events = %#v", capture.events)
+ }
+}
diff --git a/libs/fleet/backend/handlers/handlers.go b/libs/fleet/backend/handlers/handlers.go
index 86afe90e15..42a7e62323 100644
--- a/libs/fleet/backend/handlers/handlers.go
+++ b/libs/fleet/backend/handlers/handlers.go
@@ -17,6 +17,7 @@ import (
"cyclops-cs-backend/config"
"cyclops-cs-backend/featureflagadmin"
"cyclops-cs-backend/keycloak"
+ "cyclops-cs-backend/productanalytics"
"cyclops-cs-backend/usage"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
@@ -35,6 +36,7 @@ type Handlers struct {
Billing BillingService
UserAccounts UserAccountService
WebhookVerifier WebhookVerifier
+ Analytics productanalytics.Capturer
// Features carries the database-backed dependencies (the state query
// executor and the GitHub trust policy store). It is a pointer because
@@ -71,6 +73,7 @@ func New(admin *keycloak.Admin, cfg *config.Configuration) Handlers {
AuthCfg: cfg.Auth,
KC: cfg.Keycloak,
Stripe: cfg.Stripe,
+ Analytics: productanalytics.Nop(),
chatLocks: newConversationLockRegistry(),
}
}
diff --git a/libs/fleet/backend/main.go b/libs/fleet/backend/main.go
index 3df596cff4..9d18de3da1 100644
--- a/libs/fleet/backend/main.go
+++ b/libs/fleet/backend/main.go
@@ -26,6 +26,8 @@ import (
"log/slog"
"net/http"
"os"
+ "os/signal"
+ "syscall"
"time"
"github.com/spf13/cobra"
@@ -42,6 +44,7 @@ import (
"cyclops-cs-backend/keycloak"
"cyclops-cs-backend/metrics"
"cyclops-cs-backend/middlewares"
+ "cyclops-cs-backend/productanalytics"
"cyclops-cs-backend/statequery"
"cyclops-cs-backend/telemetry"
"cyclops-cs-backend/usage"
@@ -103,15 +106,16 @@ func traceMiddleware(route string) auth.Middleware {
// that — PolicyMiddleware logs it at Error itself. Re-adding elapsed time per
// policy belongs on the policy library as a span, not on one middleware as an
// unreachable log line.
-func withAuthenticatedMiddlewares(route string, h http.HandlerFunc) http.Handler {
- return withMiddlewares(
- http.HandlerFunc(h),
+func withAuthenticatedMiddlewares(route string, h http.HandlerFunc, observers ...auth.Middleware) http.Handler {
+ chain := []auth.Middleware{
traceMiddleware(route),
middlewares.LogMiddleware,
auth.RouteContext(route),
auth.TokenAuthMiddleware,
- auth.RouteMiddleware(route),
- )
+ }
+ chain = append(chain, observers...)
+ chain = append(chain, auth.RouteMiddleware(route))
+ return withMiddlewares(http.HandlerFunc(h), chain...)
}
func onlyLog(route string, h http.HandlerFunc) http.Handler {
@@ -138,6 +142,8 @@ func setupRouter(c handlers.Handlers) http.Handler {
// Feature flags / per-user config. SPA-only (same auth as /api/keys).
r.Handle("GET /api/config",
withAuthenticatedMiddlewares("/api/config", c.GetConfig))
+ r.Handle("POST /api/analytics/session",
+ withAuthenticatedMiddlewares("/api/analytics/session", c.RecordAnalyticsSession))
r.Handle("POST /api/chat/conversations",
withAuthenticatedMiddlewares("/api/chat/conversations", c.CreateConversation))
@@ -220,13 +226,16 @@ func setupRouter(c handlers.Handlers) http.Handler {
// their claims, everyone else by an impersonated RoleBinding probe the
// policy reads as a fact — see auth/authz_ownership.rego.
r.Handle("/api/svc/{namespace}/{service}",
- withAuthenticatedMiddlewares("/api/svc/{namespace}/{service}", c.Svc))
+ withAuthenticatedMiddlewares("/api/svc/{namespace}/{service}", c.Svc,
+ productanalytics.RouteObserver("/api/svc/{namespace}/{service}", c.Analytics, c.AuthCfg.SPAClientID)))
r.Handle("/api/svc/{namespace}/{service}/{path...}",
- withAuthenticatedMiddlewares("/api/svc/{namespace}/{service}/{path...}", c.Svc))
+ withAuthenticatedMiddlewares("/api/svc/{namespace}/{service}/{path...}", c.Svc,
+ productanalytics.RouteObserver("/api/svc/{namespace}/{service}/{path...}", c.Analytics, c.AuthCfg.SPAClientID)))
// K8s API access replaces the unauthenticated /k8s-api nginx location.
r.Handle("/api/k8s/{path...}",
- withAuthenticatedMiddlewares("/api/k8s/{path...}", c.K8s))
+ withAuthenticatedMiddlewares("/api/k8s/{path...}", c.K8s,
+ productanalytics.RouteObserver("/api/k8s/{path...}", c.Analytics, c.AuthCfg.SPAClientID)))
// Wrap the entire mux in the metrics middleware so every request
// (including /healthz and unmatched routes) is recorded. This must be
@@ -270,6 +279,13 @@ func initializeTelemetry(ctx context.Context, cfg config.TelemetryConfiguration)
return shutdown, nil
}
+func productAnalyticsClientConfig(cfg config.ProductAnalyticsConfiguration) productanalytics.Config {
+ return productanalytics.Config{
+ Enabled: cfg.Enabled, Host: cfg.Host, ProjectToken: cfg.ProjectToken,
+ Environment: cfg.Environment, ExcludedSubjects: cfg.ExcludedSubjects,
+ }
+}
+
func initializeFeatureFlags(ctx context.Context, environment string, credentials featureflags.AWSCredentials) error {
err := featureflags.SetupProvider(ctx, environment, credentials)
if err != nil {
@@ -281,7 +297,8 @@ func initializeFeatureFlags(ctx context.Context, environment string, credentials
func run() error {
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))
- ctx := context.Background()
+ ctx, stopSignals := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stopSignals()
var startupErrors error
var telemetryErr error
@@ -291,6 +308,15 @@ func run() error {
}
configValues = cfg
+ analyticsClient := productanalytics.New(productAnalyticsClientConfig(cfg.ProductAnalytics))
+ defer func() {
+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ if err := analyticsClient.Shutdown(shutdownCtx); err != nil {
+ slog.Warn("product analytics shutdown failed")
+ }
+ }()
+
telemetryShutdown, telemetryErr := initializeTelemetry(ctx, cfg.Telemetry)
defer func() {
if err := telemetryShutdown(context.Background()); err != nil {
@@ -347,6 +373,7 @@ func run() error {
}
h := handlers.New(admin, cfg)
+ h.Analytics = analyticsClient
usageProvider, closeUsageProvider, err := initializeUsageProvider(ctx, cfg.Usage)
if err != nil {
return errors.Join(fmt.Errorf("initialize usage provider: %w", err), startupErrors, telemetryErr)
@@ -412,10 +439,31 @@ func run() error {
router := setupRouter(h)
srv := &http.Server{Addr: cfg.WebServer.Addr, Handler: router}
- if err := srv.ListenAndServe(); err != nil {
- return errors.Join(fmt.Errorf("server exited: %w", err), startupErrors, telemetryErr)
+ return errors.Join(serveUntilCanceled(ctx, srv), startupErrors, telemetryErr)
+}
+
+func serveUntilCanceled(ctx context.Context, server *http.Server) error {
+ serverErrors := make(chan error, 1)
+ go func() {
+ serverErrors <- server.ListenAndServe()
+ }()
+
+ select {
+ case err := <-serverErrors:
+ if errors.Is(err, http.ErrServerClosed) {
+ return nil
+ }
+ return fmt.Errorf("server exited: %w", err)
+ case <-ctx.Done():
+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ shutdownErr := server.Shutdown(shutdownCtx)
+ serverErr := <-serverErrors
+ if errors.Is(serverErr, http.ErrServerClosed) {
+ serverErr = nil
+ }
+ return errors.Join(shutdownErr, serverErr)
}
- return errors.Join(startupErrors, telemetryErr)
}
func newFeatureFlagAdminService(store featureflags.ManagementStore, lock featureflagadmin.MutationLock) *featureflagadmin.Service {
diff --git a/libs/fleet/backend/main_test.go b/libs/fleet/backend/main_test.go
index 41298691c5..45eb314f3e 100644
--- a/libs/fleet/backend/main_test.go
+++ b/libs/fleet/backend/main_test.go
@@ -18,6 +18,7 @@ import (
"net/http/httptest"
"os"
"os/exec"
+ "reflect"
"slices"
"strings"
"testing"
@@ -30,6 +31,7 @@ import (
"cyclops-cs-backend/githubtrust"
"cyclops-cs-backend/handlers"
"cyclops-cs-backend/metrics"
+ "cyclops-cs-backend/productanalytics"
"cyclops-cs-backend/statequery"
"cyclops-cs-backend/usage"
@@ -1276,3 +1278,29 @@ func TestInitializeUsageProviderQueryTransportOnlyIsDisabled(t *testing.T) {
t.Fatal("initializeUsageProvider() provider != nil, want disabled provider")
}
}
+
+func TestProductAnalyticsClientConfigPreservesRuntimeSettings(t *testing.T) {
+ cfg := productAnalyticsClientConfig(config.ProductAnalyticsConfiguration{
+ Enabled: true, Host: "https://eu.i.posthog.com", ProjectToken: "phc_test",
+ Environment: "production", ExcludedSubjects: []string{"internal-1"},
+ })
+ want := productanalytics.Config{
+ Enabled: true, Host: "https://eu.i.posthog.com", ProjectToken: "phc_test",
+ Environment: "production", ExcludedSubjects: []string{"internal-1"},
+ }
+ if !reflect.DeepEqual(cfg, want) {
+ t.Fatalf("config = %#v, want %#v", cfg, want)
+ }
+}
+
+func TestServeUntilCanceledShutsDownServer(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ server := &http.Server{Addr: "127.0.0.1:0", Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })}
+ go func() {
+ time.Sleep(20 * time.Millisecond)
+ cancel()
+ }()
+ if err := serveUntilCanceled(ctx, server); err != nil {
+ t.Fatalf("serveUntilCanceled() error = %v", err)
+ }
+}
diff --git a/libs/fleet/backend/metrics/metrics.go b/libs/fleet/backend/metrics/metrics.go
index 5ef24f9248..3e30b66223 100644
--- a/libs/fleet/backend/metrics/metrics.go
+++ b/libs/fleet/backend/metrics/metrics.go
@@ -69,6 +69,21 @@ var (
Help: "Total Stripe billing webhook requests by processing result and event type.",
}, []string{"result", "event_type"})
+ ProductAnalyticsEventsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
+ Name: "cyclops_cs_product_analytics_events_total",
+ Help: "Fleet product analytics events by event name and delivery result.",
+ }, []string{"event", "result"})
+
+ ProductAnalyticsQueueDepth = promauto.NewGauge(prometheus.GaugeOpts{
+ Name: "cyclops_cs_product_analytics_queue_depth",
+ Help: "Current Fleet product analytics delivery queue depth.",
+ })
+
+ ProductAnalyticsDeliveryDuration = promauto.NewHistogram(prometheus.HistogramOpts{
+ Name: "cyclops_cs_product_analytics_delivery_duration_seconds",
+ Help: "Fleet product analytics batch delivery duration.",
+ })
+
// DatabaseFeaturesReady reports whether the PostgreSQL-backed features
// came up at startup. The serving tier deliberately does NOT gate
// readiness on the database (see
@@ -267,3 +282,15 @@ func StartMetricsServer(addr string) error {
func RecordBillingWebhook(result, eventType string) {
BillingWebhookEventsTotal.WithLabelValues(result, eventType).Inc()
}
+
+func RecordProductAnalytics(event, result string) {
+ ProductAnalyticsEventsTotal.WithLabelValues(event, result).Inc()
+}
+
+func SetProductAnalyticsQueueDepth(depth int) {
+ ProductAnalyticsQueueDepth.Set(float64(depth))
+}
+
+func ObserveProductAnalyticsDelivery(duration time.Duration) {
+ ProductAnalyticsDeliveryDuration.Observe(duration.Seconds())
+}
diff --git a/libs/fleet/backend/productanalytics/client.go b/libs/fleet/backend/productanalytics/client.go
new file mode 100644
index 0000000000..6e79281acd
--- /dev/null
+++ b/libs/fleet/backend/productanalytics/client.go
@@ -0,0 +1,212 @@
+package productanalytics
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "cyclops-cs-backend/metrics"
+)
+
+const firstSeenProperty = "fleet_first_seen_at"
+
+type Config struct {
+ Enabled bool
+ Host string
+ ProjectToken string
+ Environment string
+ ExcludedSubjects []string
+ QueueSize int
+ BatchSize int
+ FlushInterval time.Duration
+ RequestTimeout time.Duration
+}
+
+type Client struct {
+ config Config
+ http *http.Client
+ queue chan Event
+ done chan struct{}
+ excluded map[string]struct{}
+ stopOnce sync.Once
+}
+
+func New(config Config) *Client {
+ if config.QueueSize <= 0 {
+ config.QueueSize = 256
+ }
+ if config.BatchSize <= 0 {
+ config.BatchSize = 20
+ }
+ if config.FlushInterval <= 0 {
+ config.FlushInterval = time.Second
+ }
+ if config.RequestTimeout <= 0 {
+ config.RequestTimeout = 2 * time.Second
+ }
+ config.Host = strings.TrimRight(config.Host, "/")
+ client := &Client{
+ config: config,
+ http: &http.Client{Timeout: config.RequestTimeout},
+ queue: make(chan Event, config.QueueSize),
+ done: make(chan struct{}),
+ excluded: make(map[string]struct{}, len(config.ExcludedSubjects)),
+ }
+ for _, subject := range config.ExcludedSubjects {
+ client.excluded[subject] = struct{}{}
+ }
+ if config.Enabled && config.ProjectToken != "" && config.Host != "" {
+ go client.run()
+ } else {
+ close(client.done)
+ }
+ return client
+}
+
+func (client *Client) Capture(event Event) {
+ if !client.config.Enabled || client.config.ProjectToken == "" || client.config.Host == "" {
+ metrics.RecordProductAnalytics(event.Name, "disabled")
+ return
+ }
+ if _, excluded := client.excluded[event.DistinctID]; excluded {
+ metrics.RecordProductAnalytics(event.Name, "excluded")
+ return
+ }
+ if err := ValidateEvent(event); err != nil {
+ metrics.RecordProductAnalytics(event.Name, "invalid")
+ return
+ }
+ copied := cloneEvent(event)
+ copied.Properties["environment"] = client.config.Environment
+ copied.Properties["instrumentation_version"] = Version
+ if copied.SetOnce == nil {
+ copied.SetOnce = map[string]any{}
+ }
+ copied.SetOnce[firstSeenProperty] = time.Now().UTC().Format(time.RFC3339)
+ select {
+ case client.queue <- copied:
+ metrics.SetProductAnalyticsQueueDepth(len(client.queue))
+ metrics.RecordProductAnalytics(event.Name, "accepted")
+ default:
+ metrics.RecordProductAnalytics(event.Name, "queue_full")
+ }
+}
+
+func cloneEvent(event Event) Event {
+ properties := make(map[string]any, len(event.Properties))
+ for key, value := range event.Properties {
+ properties[key] = value
+ }
+ setOnce := make(map[string]any, len(event.SetOnce))
+ for key, value := range event.SetOnce {
+ setOnce[key] = value
+ }
+ event.Properties = properties
+ event.SetOnce = setOnce
+ return event
+}
+
+func (client *Client) run() {
+ defer close(client.done)
+ ticker := time.NewTicker(client.config.FlushInterval)
+ defer ticker.Stop()
+ batch := make([]Event, 0, client.config.BatchSize)
+ flush := func() {
+ if len(batch) == 0 {
+ return
+ }
+ client.deliver(batch)
+ batch = batch[:0]
+ }
+ for {
+ select {
+ case event, ok := <-client.queue:
+ if !ok {
+ flush()
+ return
+ }
+ batch = append(batch, event)
+ metrics.SetProductAnalyticsQueueDepth(len(client.queue))
+ if len(batch) >= client.config.BatchSize {
+ flush()
+ }
+ case <-ticker.C:
+ flush()
+ }
+ }
+}
+
+func (client *Client) deliver(events []Event) {
+ started := time.Now()
+ defer metrics.ObserveProductAnalyticsDelivery(time.Since(started))
+ items := make([]map[string]any, 0, len(events))
+ for _, event := range events {
+ properties := cloneMap(event.Properties)
+ if event.InsertID != "" {
+ properties["$insert_id"] = event.InsertID
+ }
+ if len(event.SetOnce) > 0 {
+ properties["$set_once"] = cloneMap(event.SetOnce)
+ }
+ items = append(items, map[string]any{"event": event.Name, "distinct_id": event.DistinctID, "properties": properties})
+ }
+ body, err := json.Marshal(map[string]any{"api_key": client.config.ProjectToken, "batch": items})
+ if err != nil {
+ for _, event := range events {
+ metrics.RecordProductAnalytics(event.Name, "encode_failed")
+ }
+ return
+ }
+ request, err := http.NewRequestWithContext(context.Background(), http.MethodPost, client.config.Host+"/batch/", bytes.NewReader(body))
+ if err != nil {
+ for _, event := range events {
+ metrics.RecordProductAnalytics(event.Name, "delivery_failed")
+ }
+ return
+ }
+ request.Header.Set("Content-Type", "application/json")
+ response, err := client.http.Do(request)
+ if err != nil {
+ slog.Warn("product analytics delivery failed", "event_count", len(events))
+ for _, event := range events {
+ metrics.RecordProductAnalytics(event.Name, "delivery_failed")
+ }
+ return
+ }
+ _ = response.Body.Close()
+ result := "delivered"
+ if response.StatusCode < 200 || response.StatusCode >= 300 {
+ result = "delivery_failed"
+ }
+ for _, event := range events {
+ metrics.RecordProductAnalytics(event.Name, result)
+ }
+}
+
+func cloneMap(input map[string]any) map[string]any {
+ output := make(map[string]any, len(input))
+ for key, value := range input {
+ output[key] = value
+ }
+ return output
+}
+
+func (client *Client) Shutdown(ctx context.Context) error {
+ client.stopOnce.Do(func() {
+ if client.config.Enabled && client.config.ProjectToken != "" && client.config.Host != "" {
+ close(client.queue)
+ }
+ })
+ select {
+ case <-client.done:
+ return nil
+ case <-ctx.Done():
+ return errors.New("product analytics shutdown timed out")
+ }
+}
diff --git a/libs/fleet/backend/productanalytics/client_test.go b/libs/fleet/backend/productanalytics/client_test.go
new file mode 100644
index 0000000000..350de07f8f
--- /dev/null
+++ b/libs/fleet/backend/productanalytics/client_test.go
@@ -0,0 +1,85 @@
+package productanalytics
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+)
+
+func TestClientDeliversAllowlistedEvent(t *testing.T) {
+ requests := make(chan map[string]any, 1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer r.Body.Close()
+ var payload map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode payload: %v", err)
+ }
+ requests <- payload
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer server.Close()
+
+ client := New(Config{
+ Enabled: true, Host: server.URL, ProjectToken: "phc_test", Environment: "production",
+ QueueSize: 4, BatchSize: 1, FlushInterval: time.Hour, RequestTimeout: time.Second,
+ })
+ client.Capture(Event{
+ Name: EventPoolCreate, DistinctID: "subject-1", InsertID: "trace-1",
+ Properties: map[string]any{"outcome": OutcomeSuccess, "source": SourceSPA, "principal_type": "user", "status_code": 201},
+ })
+
+ select {
+ case payload := <-requests:
+ if payload["api_key"] != "phc_test" {
+ t.Fatalf("api_key = %#v", payload["api_key"])
+ }
+ batch := payload["batch"].([]any)
+ item := batch[0].(map[string]any)
+ if item["event"] != EventPoolCreate || item["distinct_id"] != "subject-1" {
+ t.Fatalf("event payload = %#v", item)
+ }
+ properties := item["properties"].(map[string]any)
+ if properties["environment"] != "production" || properties["instrumentation_version"] != Version || properties["$insert_id"] != "trace-1" {
+ t.Fatalf("properties = %#v", properties)
+ }
+ if _, ok := properties["$set_once"].(map[string]any)["fleet_first_seen_at"]; !ok {
+ t.Fatalf("$set_once = %#v", properties["$set_once"])
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("timed out waiting for capture")
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ if err := client.Shutdown(ctx); err != nil {
+ t.Fatalf("Shutdown() error = %v", err)
+ }
+}
+
+func TestClientSuppressesExcludedSubject(t *testing.T) {
+ requests := make(chan struct{}, 1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ requests <- struct{}{}
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer server.Close()
+
+ client := New(Config{
+ Enabled: true, Host: server.URL, ProjectToken: "phc_test", Environment: "production",
+ ExcludedSubjects: []string{"internal-1"}, QueueSize: 1, BatchSize: 1,
+ FlushInterval: 10 * time.Millisecond, RequestTimeout: time.Second,
+ })
+ client.Capture(Event{Name: EventLoginSucceeded, DistinctID: "internal-1", Properties: map[string]any{"outcome": OutcomeSuccess, "source": SourceSPA, "principal_type": "user"}})
+ time.Sleep(30 * time.Millisecond)
+ select {
+ case <-requests:
+ t.Fatal("excluded subject was delivered")
+ default:
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ _ = client.Shutdown(ctx)
+}
diff --git a/libs/fleet/backend/productanalytics/events.go b/libs/fleet/backend/productanalytics/events.go
new file mode 100644
index 0000000000..ed44c6b81c
--- /dev/null
+++ b/libs/fleet/backend/productanalytics/events.go
@@ -0,0 +1,83 @@
+package productanalytics
+
+import (
+ "fmt"
+ "strings"
+
+ "cyclops-cs-backend/auth"
+)
+
+const (
+ EventLoginSucceeded = "fleet_login_succeeded"
+ EventPaymentMethodSetup = "fleet_payment_method_setup"
+ EventPoolCreate = "fleet_pool_create"
+ EventClaimCreate = "fleet_claim_create"
+ EventHTTPProxyRequest = "fleet_http_proxy_request"
+
+ OutcomeSuccess = "success"
+ OutcomeFailure = "failure"
+ SourceSPA = "spa"
+ SourceUserKey = "user_key"
+ Version = "1"
+)
+
+var allowedEvents = map[string]struct{}{
+ EventLoginSucceeded: {}, EventPaymentMethodSetup: {}, EventPoolCreate: {},
+ EventClaimCreate: {}, EventHTTPProxyRequest: {},
+}
+
+var allowedProperties = map[string]struct{}{
+ "outcome": {}, "source": {}, "principal_type": {}, "status_code": {},
+ "error_class": {}, "environment": {}, "instrumentation_version": {},
+}
+
+type Event struct {
+ Name string
+ DistinctID string
+ InsertID string
+ Properties map[string]any
+ SetOnce map[string]any
+}
+
+type Capturer interface {
+ Capture(Event)
+}
+
+type nopCapturer struct{}
+
+func (nopCapturer) Capture(Event) {}
+
+func Nop() Capturer { return nopCapturer{} }
+
+func SourceForUser(user *auth.User, spaClientID string) (string, bool) {
+ if user == nil || user.ID == "" {
+ return "", false
+ }
+ if user.PrincipalType == auth.PrincipalTypeUserKey || strings.HasPrefix(user.AZP, "ukey-") {
+ return SourceUserKey, true
+ }
+ if user.AZP == spaClientID || user.AZP == "oauth2-proxy" {
+ return SourceSPA, true
+ }
+ return "", false
+}
+
+func ValidateEvent(event Event) error {
+ if _, ok := allowedEvents[event.Name]; !ok {
+ return fmt.Errorf("unsupported analytics event")
+ }
+ if event.DistinctID == "" {
+ return fmt.Errorf("distinct id is required")
+ }
+ for key := range event.Properties {
+ if _, ok := allowedProperties[key]; !ok {
+ return fmt.Errorf("unsupported analytics property %q", key)
+ }
+ }
+ for key := range event.SetOnce {
+ if key != firstSeenProperty {
+ return fmt.Errorf("unsupported analytics set-once property %q", key)
+ }
+ }
+ return nil
+}
diff --git a/libs/fleet/backend/productanalytics/events_test.go b/libs/fleet/backend/productanalytics/events_test.go
new file mode 100644
index 0000000000..0d74671228
--- /dev/null
+++ b/libs/fleet/backend/productanalytics/events_test.go
@@ -0,0 +1,63 @@
+package productanalytics
+
+import (
+ "testing"
+
+ "cyclops-cs-backend/auth"
+)
+
+func TestSourceForUser(t *testing.T) {
+ tests := []struct {
+ name string
+ user *auth.User
+ want string
+ ok bool
+ }{
+ {name: "spa", user: &auth.User{ID: "user-1", AZP: "cyclops-cs-spa", PrincipalType: auth.PrincipalTypeUser}, want: SourceSPA, ok: true},
+ {name: "oauth proxy", user: &auth.User{ID: "user-1", AZP: "oauth2-proxy"}, want: SourceSPA, ok: true},
+ {name: "user key", user: &auth.User{ID: "user-1", AZP: "ukey-demo", PrincipalType: auth.PrincipalTypeUserKey}, want: SourceUserKey, ok: true},
+ {name: "github", user: &auth.User{ID: "user-1", AZP: "github-oidc", PrincipalType: auth.PrincipalTypeGitHubOIDC}},
+ {name: "missing", user: nil},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ got, ok := SourceForUser(test.user, "cyclops-cs-spa")
+ if got != test.want || ok != test.ok {
+ t.Fatalf("SourceForUser() = %q, %v, want %q, %v", got, ok, test.want, test.ok)
+ }
+ })
+ }
+}
+
+func TestValidateEventRejectsUnsafeProperties(t *testing.T) {
+ valid := Event{
+ Name: EventPoolCreate,
+ DistinctID: "subject-1",
+ Properties: map[string]any{
+ "outcome": OutcomeSuccess,
+ "source": SourceSPA,
+ "principal_type": auth.PrincipalTypeUser,
+ "status_code": 201,
+ "error_class": "",
+ },
+ }
+ if err := ValidateEvent(valid); err != nil {
+ t.Fatalf("ValidateEvent(valid) error = %v", err)
+ }
+
+ invalidSetOnce := valid
+ invalidSetOnce.SetOnce = map[string]any{"email": "secret"}
+ if err := ValidateEvent(invalidSetOnce); err == nil {
+ t.Fatal("ValidateEvent() accepted unsafe set-once property")
+ }
+
+ for _, key := range []string{"error", "email", "namespace", "service", "path"} {
+ t.Run(key, func(t *testing.T) {
+ invalid := valid
+ invalid.Properties = map[string]any{key: "secret"}
+ if err := ValidateEvent(invalid); err == nil {
+ t.Fatalf("ValidateEvent() accepted unsafe property %q", key)
+ }
+ })
+ }
+}
diff --git a/libs/fleet/backend/productanalytics/middleware.go b/libs/fleet/backend/productanalytics/middleware.go
new file mode 100644
index 0000000000..4124a6b114
--- /dev/null
+++ b/libs/fleet/backend/productanalytics/middleware.go
@@ -0,0 +1,140 @@
+package productanalytics
+
+import (
+ "bufio"
+ "fmt"
+ "net"
+ "net/http"
+ "strings"
+
+ "cyclops-cs-backend/auth"
+ "cyclops-cs-backend/middlewares"
+)
+
+func RouteObserver(route string, capturer Capturer, spaClientID string) auth.Middleware {
+ if capturer == nil {
+ capturer = Nop()
+ }
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ user := auth.GetUser(r.Context())
+ source, ok := SourceForUser(user, spaClientID)
+ eventName, tracked := activationEvent(route, r)
+ if !ok || !tracked {
+ next.ServeHTTP(w, r)
+ return
+ }
+ rw := newAnalyticsResponseWriter(w)
+ next.ServeHTTP(rw, r)
+ status := rw.statusCode
+ outcome := OutcomeFailure
+ if successfulActivation(eventName, status) {
+ outcome = OutcomeSuccess
+ }
+ principalType := user.PrincipalType
+ if principalType == "" {
+ principalType = auth.PrincipalTypeUser
+ }
+ traceID, _ := r.Context().Value(middlewares.ContextKey("traceId")).(string)
+ capturer.Capture(Event{
+ Name: eventName, DistinctID: user.ID, InsertID: traceID,
+ Properties: map[string]any{
+ "outcome": outcome, "source": source, "principal_type": principalType,
+ "status_code": status, "error_class": errorClass(status),
+ },
+ })
+ })
+ }
+}
+
+func activationEvent(route string, r *http.Request) (string, bool) {
+ if strings.HasPrefix(route, "/api/svc/") {
+ return EventHTTPProxyRequest, true
+ }
+ if route != "/api/k8s/{path...}" || r.Method != http.MethodPost {
+ return "", false
+ }
+ parts := strings.Split(strings.Trim(r.PathValue("path"), "/"), "/")
+ if len(parts) != 6 || parts[0] != "apis" || parts[3] != "namespaces" || parts[4] == "" {
+ return "", false
+ }
+ switch {
+ case parts[1] == "cua.ai" && parts[2] == "v1" && parts[5] == "osgymworkspacepools":
+ return EventPoolCreate, true
+ case parts[1] == "osgym.cua.ai" && parts[2] == "v1alpha1" && parts[5] == "osgymsandboxclaims":
+ return EventClaimCreate, true
+ default:
+ return "", false
+ }
+}
+
+func successfulActivation(eventName string, status int) bool {
+ if eventName == EventHTTPProxyRequest {
+ return status >= 200 && status < 400
+ }
+ return status >= 200 && status < 300
+}
+
+func errorClass(status int) string {
+ switch {
+ case status >= 200 && status < 400:
+ return ""
+ case status == http.StatusBadRequest || status == http.StatusUnprocessableEntity:
+ return "validation"
+ case status == http.StatusUnauthorized || status == http.StatusForbidden:
+ return "authorization"
+ case status == http.StatusRequestTimeout || status == http.StatusGatewayTimeout:
+ return "timeout"
+ case status == 499:
+ return "network"
+ case status >= 400 && status < 500:
+ return "upstream_4xx"
+ case status >= 500:
+ return "upstream_5xx"
+ default:
+ return "internal"
+ }
+}
+
+type analyticsResponseWriter struct {
+ http.ResponseWriter
+ statusCode int
+ written bool
+}
+
+func newAnalyticsResponseWriter(w http.ResponseWriter) *analyticsResponseWriter {
+ return &analyticsResponseWriter{ResponseWriter: w, statusCode: http.StatusOK}
+}
+
+func (rw *analyticsResponseWriter) WriteHeader(status int) {
+ if !rw.written {
+ rw.statusCode = status
+ rw.written = true
+ }
+ rw.ResponseWriter.WriteHeader(status)
+}
+
+func (rw *analyticsResponseWriter) Write(body []byte) (int, error) {
+ if !rw.written {
+ rw.WriteHeader(http.StatusOK)
+ }
+ return rw.ResponseWriter.Write(body)
+}
+
+func (rw *analyticsResponseWriter) Flush() {
+ if flusher, ok := rw.ResponseWriter.(http.Flusher); ok {
+ flusher.Flush()
+ }
+}
+
+func (rw *analyticsResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
+ hijacker, ok := rw.ResponseWriter.(http.Hijacker)
+ if !ok {
+ return nil, nil, fmt.Errorf("underlying ResponseWriter does not implement http.Hijacker")
+ }
+ if !rw.written {
+ rw.statusCode = http.StatusSwitchingProtocols
+ rw.written = true
+ }
+ return hijacker.Hijack()
+}
diff --git a/libs/fleet/backend/productanalytics/middleware_test.go b/libs/fleet/backend/productanalytics/middleware_test.go
new file mode 100644
index 0000000000..2facdaf55e
--- /dev/null
+++ b/libs/fleet/backend/productanalytics/middleware_test.go
@@ -0,0 +1,108 @@
+package productanalytics
+
+import (
+ "bufio"
+ "context"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "cyclops-cs-backend/auth"
+ "cyclops-cs-backend/middlewares"
+)
+
+type captureSink struct{ events []Event }
+
+func (sink *captureSink) Capture(event Event) { sink.events = append(sink.events, event) }
+
+func observedRequest(method, route, path string, user *auth.User) *http.Request {
+ request := httptest.NewRequest(method, "http://example.test/api", nil)
+ request.SetPathValue("path", path)
+ ctx := context.WithValue(request.Context(), auth.UserKey, user)
+ ctx = context.WithValue(ctx, middlewares.ContextKey("traceId"), "trace-123")
+ return request.WithContext(ctx)
+}
+
+func TestRouteObserverCapturesActivationOutcomes(t *testing.T) {
+ tests := []struct {
+ name, route, method, path string
+ status int
+ user *auth.User
+ wantEvent, wantOutcome, wantSource, wantClass string
+ }{
+ {name: "pool success", route: "/api/k8s/{path...}", method: http.MethodPost, path: "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", status: 201, user: &auth.User{ID: "u-1", AZP: "cyclops-cs-spa", PrincipalType: auth.PrincipalTypeUser}, wantEvent: EventPoolCreate, wantOutcome: OutcomeSuccess, wantSource: SourceSPA},
+ {name: "claim authorization", route: "/api/k8s/{path...}", method: http.MethodPost, path: "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims", status: 403, user: &auth.User{ID: "u-1", AZP: "ukey-one", PrincipalType: auth.PrincipalTypeUserKey}, wantEvent: EventClaimCreate, wantOutcome: OutcomeFailure, wantSource: SourceUserKey, wantClass: "authorization"},
+ {name: "proxy redirect", route: "/api/svc/{namespace}/{service}/{path...}", method: http.MethodGet, status: 302, user: &auth.User{ID: "u-1", AZP: "cyclops-cs-spa", PrincipalType: auth.PrincipalTypeUser}, wantEvent: EventHTTPProxyRequest, wantOutcome: OutcomeSuccess, wantSource: SourceSPA},
+ {name: "proxy upstream", route: "/api/svc/{namespace}/{service}", method: http.MethodPost, status: 502, user: &auth.User{ID: "u-1", AZP: "ukey-one", PrincipalType: auth.PrincipalTypeUserKey}, wantEvent: EventHTTPProxyRequest, wantOutcome: OutcomeFailure, wantSource: SourceUserKey, wantClass: "upstream_5xx"},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ sink := &captureSink{}
+ handler := RouteObserver(test.route, sink, "cyclops-cs-spa")(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(test.status) }))
+ handler.ServeHTTP(httptest.NewRecorder(), observedRequest(test.method, test.route, test.path, test.user))
+ if len(sink.events) != 1 {
+ t.Fatalf("events = %#v", sink.events)
+ }
+ event := sink.events[0]
+ if event.Name != test.wantEvent || event.InsertID != "trace-123" {
+ t.Fatalf("event = %#v", event)
+ }
+ if event.Properties["outcome"] != test.wantOutcome || event.Properties["source"] != test.wantSource || event.Properties["error_class"] != test.wantClass {
+ t.Fatalf("properties = %#v", event.Properties)
+ }
+ })
+ }
+}
+
+func TestRouteObserverIgnoresNonActivationRequests(t *testing.T) {
+ tests := []struct {
+ method, route, path string
+ user *auth.User
+ }{
+ {method: http.MethodGet, route: "/api/k8s/{path...}", path: "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", user: &auth.User{ID: "u-1", AZP: "cyclops-cs-spa"}},
+ {method: http.MethodPost, route: "/api/k8s/{path...}", path: "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools/name", user: &auth.User{ID: "u-1", AZP: "cyclops-cs-spa"}},
+ {method: http.MethodPost, route: "/api/k8s/{path...}", path: "api/v1/namespaces/ns-a/pods", user: &auth.User{ID: "u-1", AZP: "cyclops-cs-spa"}},
+ {method: http.MethodGet, route: "/api/gateway/{name}/{path...}", user: &auth.User{ID: "u-1", AZP: "cyclops-cs-spa"}},
+ {method: http.MethodGet, route: "/api/svc/{namespace}/{service}", user: &auth.User{ID: "owner", AZP: "github-oidc", PrincipalType: auth.PrincipalTypeGitHubOIDC}},
+ }
+ for _, test := range tests {
+ sink := &captureSink{}
+ handler := RouteObserver(test.route, sink, "cyclops-cs-spa")(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) }))
+ handler.ServeHTTP(httptest.NewRecorder(), observedRequest(test.method, test.route, test.path, test.user))
+ if len(sink.events) != 0 {
+ t.Fatalf("request %#v captured %#v", test, sink.events)
+ }
+ }
+}
+
+type interfaceWriter struct {
+ header http.Header
+ status int
+}
+
+func (w *interfaceWriter) Header() http.Header {
+ if w.header == nil {
+ w.header = http.Header{}
+ }
+ return w.header
+}
+func (w *interfaceWriter) Write(body []byte) (int, error) {
+ if w.status == 0 {
+ w.status = 200
+ }
+ return len(body), nil
+}
+func (w *interfaceWriter) WriteHeader(status int) { w.status = status }
+func (w *interfaceWriter) Flush() {}
+func (w *interfaceWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return nil, nil, nil }
+
+func TestAnalyticsResponseWriterPreservesProxyInterfaces(t *testing.T) {
+ wrapped := newAnalyticsResponseWriter(&interfaceWriter{})
+ if _, ok := any(wrapped).(http.Flusher); !ok {
+ t.Fatal("missing http.Flusher")
+ }
+ if _, ok := any(wrapped).(http.Hijacker); !ok {
+ t.Fatal("missing http.Hijacker")
+ }
+}
diff --git a/libs/fleet/src/auth/AuthProvider.tsx b/libs/fleet/src/auth/AuthProvider.tsx
index a1645a0624..52b870bad0 100644
--- a/libs/fleet/src/auth/AuthProvider.tsx
+++ b/libs/fleet/src/auth/AuthProvider.tsx
@@ -4,7 +4,8 @@
// children once we have a valid session.
import { useEffect, useLayoutEffect, useState } from "react"
-import { initKc } from "./keycloak"
+import { initKc, kc } from "./keycloak"
+import { recordFleetLogin } from "./analytics"
import { isLocalVisualPreview } from "../local-visual-preview"
interface Props {
@@ -29,6 +30,7 @@ export function AuthProvider({ children }: Props) {
return
}
setReady(true)
+ void recordFleetLogin(kc.sessionId).catch(() => undefined)
})
.catch(e => setError(String(e)))
}, [visualPreview])
diff --git a/libs/fleet/src/auth/analytics.ts b/libs/fleet/src/auth/analytics.ts
new file mode 100644
index 0000000000..ca26b3853a
--- /dev/null
+++ b/libs/fleet/src/auth/analytics.ts
@@ -0,0 +1,42 @@
+interface SessionStorageLike {
+ getItem(key: string): string | null
+ setItem(key: string, value: string): void
+}
+
+interface AnalyticsDependencies {
+ getToken: () => Promise<string | undefined>
+ fetch: (input: string, init?: RequestInit) => Promise<Response>
+ storage: SessionStorageLike
+}
+
+const storagePrefix = "fleet-login-recorded:"
+
+function defaultDependencies(): AnalyticsDependencies {
+ return {
+ getToken: async () => {
+ const { getToken } = await import("./keycloak")
+ return getToken()
+ },
+ fetch: (input, init) => fetch(input, init),
+ storage: window.sessionStorage,
+ }
+}
+
+export async function recordFleetLogin(
+ sessionID: string | undefined,
+ dependencies: AnalyticsDependencies = defaultDependencies(),
+): Promise<void> {
+ const marker = `${storagePrefix}${sessionID || "authenticated"}`
+ if (dependencies.storage.getItem(marker) === "true") return
+
+ const token = await dependencies.getToken()
+ if (!token) throw new Error("Authentication token is unavailable")
+ const response = await dependencies.fetch("/api/analytics/session", {
+ method: "POST",
+ headers: { Authorization: `Bearer ${token}` },
+ })
+ if (!response.ok) {
+ throw new Error(`Fleet login analytics request failed: ${response.status}`)
+ }
+ dependencies.storage.setItem(marker, "true")
+}
diff --git a/libs/fleet/tests/auth-analytics.test.ts b/libs/fleet/tests/auth-analytics.test.ts
new file mode 100644
index 0000000000..6e2fa6815e
--- /dev/null
+++ b/libs/fleet/tests/auth-analytics.test.ts
@@ -0,0 +1,42 @@
+import assert from "node:assert/strict"
+import test from "node:test"
+import { recordFleetLogin } from "../src/auth/analytics.ts"
+
+test("records one Fleet login per Keycloak browser session", async () => {
+ const stored = new Map<string, string>()
+ const calls: Array<{ input: string; init?: RequestInit }> = []
+ const dependencies = {
+ getToken: async () => "token-1",
+ fetch: async (input: string, init?: RequestInit) => {
+ calls.push({ input, init })
+ return new Response(null, { status: 204 })
+ },
+ storage: {
+ getItem: (key: string) => stored.get(key) ?? null,
+ setItem: (key: string, value: string) => stored.set(key, value),
+ },
+ }
+
+ await recordFleetLogin("session-1", dependencies)
+ await recordFleetLogin("session-1", dependencies)
+
+ assert.equal(calls.length, 1)
+ assert.equal(calls[0]?.input, "/api/analytics/session")
+ assert.equal(calls[0]?.init?.method, "POST")
+ assert.equal((calls[0]?.init?.headers as Record<string, string>).Authorization, "Bearer token-1")
+})
+
+test("analytics failure does not mark the session as recorded", async () => {
+ const stored = new Map<string, string>()
+ const dependencies = {
+ getToken: async () => "token-1",
+ fetch: async () => new Response(null, { status: 503 }),
+ storage: {
+ getItem: (key: string) => stored.get(key) ?? null,
+ setItem: (key: string, value: string) => stored.set(key, value),
+ },
+ }
+
+ await assert.rejects(recordFleetLogin("session-2", dependencies))
+ assert.equal(stored.size, 0)
+})