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): track Fleet creation blocks and qualification rejects (#7291)
Francesco Bonacci6afb707ab9a5
diff --git a/libs/fleet/backend/auth/authz_config.rego b/libs/fleet/backend/auth/authz_config.regoindex a01d7f69c0..53bf15622b 100644--- a/libs/fleet/backend/auth/authz_config.rego+++ b/libs/fleet/backend/auth/authz_config.rego@@ -22,3 +22,9 @@ allow {input.route == "/api/analytics/session"input.user.azp == "cyclops-cs-spa"}++allow {+ input.route == "/api/analytics/attribution"+ 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 eef5a0575c..10a3a1a64a 100644--- a/libs/fleet/backend/auth/authz_config_test.rego+++ b/libs/fleet/backend/auth/authz_config_test.rego@@ -44,3 +44,23 @@ test_user_key_analytics_session_denied if {"user": {"sub": "user-123", "azp": "ukey-test", "namespace": "", "email": ""},}}++test_spa_analytics_attribution_allowed if {+ route_allow with input as {+ "route": "/api/analytics/attribution",+ "method": "POST",+ "path": "/api/analytics/attribution",+ "params": {},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ }+}++test_user_key_analytics_attribution_denied if {+ not route_allow with input as {+ "route": "/api/analytics/attribution",+ "method": "POST",+ "path": "/api/analytics/attribution",+ "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.goindex ff768173bb..d678e3d985 100644--- a/libs/fleet/backend/auth/policy_characterization_test.go+++ b/libs/fleet/backend/auth/policy_characterization_test.go@@ -173,6 +173,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/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 fd778954eb..225b20cdb4 100644--- a/libs/fleet/backend/auth/policy_routes.go+++ b/libs/fleet/backend/auth/policy_routes.go@@ -278,6 +278,7 @@ var surfacePolicies = map[string]surfacePolicy{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",diff --git a/libs/fleet/backend/auth/testdata/route-authorization-table.txt b/libs/fleet/backend/auth/testdata/route-authorization-table.txtindex 0e3f516402..32e3a8b403 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/attribution | plain | DELETE | admin-spa = deny+/api/analytics/attribution | plain | DELETE | cua-cli = deny+/api/analytics/attribution | plain | DELETE | dcr-client = deny+/api/analytics/attribution | plain | DELETE | empty-sub = deny+/api/analytics/attribution | plain | DELETE | github-oidc = deny+/api/analytics/attribution | plain | DELETE | oauth2-proxy = deny+/api/analytics/attribution | plain | DELETE | per-key-other-ns = deny+/api/analytics/attribution | plain | DELETE | per-key-owned-ns = deny+/api/analytics/attribution | plain | DELETE | spa = deny+/api/analytics/attribution | plain | DELETE | user-key = deny+/api/analytics/attribution | plain | DELETE | user-key-verified = deny+/api/analytics/attribution | plain | GET | admin-spa = deny+/api/analytics/attribution | plain | GET | cua-cli = deny+/api/analytics/attribution | plain | GET | dcr-client = deny+/api/analytics/attribution | plain | GET | empty-sub = deny+/api/analytics/attribution | plain | GET | github-oidc = deny+/api/analytics/attribution | plain | GET | oauth2-proxy = deny+/api/analytics/attribution | plain | GET | per-key-other-ns = deny+/api/analytics/attribution | plain | GET | per-key-owned-ns = deny+/api/analytics/attribution | plain | GET | spa = deny+/api/analytics/attribution | plain | GET | user-key = deny+/api/analytics/attribution | plain | GET | user-key-verified = deny+/api/analytics/attribution | plain | PATCH | admin-spa = deny+/api/analytics/attribution | plain | PATCH | cua-cli = deny+/api/analytics/attribution | plain | PATCH | dcr-client = deny+/api/analytics/attribution | plain | PATCH | empty-sub = deny+/api/analytics/attribution | plain | PATCH | github-oidc = deny+/api/analytics/attribution | plain | PATCH | oauth2-proxy = deny+/api/analytics/attribution | plain | PATCH | per-key-other-ns = deny+/api/analytics/attribution | plain | PATCH | per-key-owned-ns = deny+/api/analytics/attribution | plain | PATCH | spa = deny+/api/analytics/attribution | plain | PATCH | user-key = deny+/api/analytics/attribution | plain | PATCH | user-key-verified = deny+/api/analytics/attribution | plain | POST | admin-spa = allow+/api/analytics/attribution | plain | POST | cua-cli = deny+/api/analytics/attribution | plain | POST | dcr-client = deny+/api/analytics/attribution | plain | POST | empty-sub = deny+/api/analytics/attribution | plain | POST | github-oidc = deny+/api/analytics/attribution | plain | POST | oauth2-proxy = deny+/api/analytics/attribution | plain | POST | per-key-other-ns = deny+/api/analytics/attribution | plain | POST | per-key-owned-ns = deny+/api/analytics/attribution | plain | POST | spa = allow+/api/analytics/attribution | plain | POST | user-key = deny+/api/analytics/attribution | plain | POST | user-key-verified = deny+/api/analytics/attribution | plain | QUERY | admin-spa = deny+/api/analytics/attribution | plain | QUERY | cua-cli = deny+/api/analytics/attribution | plain | QUERY | dcr-client = deny+/api/analytics/attribution | plain | QUERY | empty-sub = deny+/api/analytics/attribution | plain | QUERY | github-oidc = deny+/api/analytics/attribution | plain | QUERY | oauth2-proxy = deny+/api/analytics/attribution | plain | QUERY | per-key-other-ns = deny+/api/analytics/attribution | plain | QUERY | per-key-owned-ns = deny+/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/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_attribution.go b/libs/fleet/backend/handlers/analytics_attribution.gonew file mode 100644index 0000000000..fc98b08614--- /dev/null+++ b/libs/fleet/backend/handlers/analytics_attribution.go@@ -0,0 +1,120 @@+package handlers++import (+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "time"++ "cyclops-cs-backend/auth"+ "cyclops-cs-backend/productanalytics"+)++const (+ fleetAttributionBodyMaxBytes = 2048+ fleetAttributionTTL = 7 * 24 * time.Hour+)++var fleetAttributionProperties = map[string]string{+ "campaign_id": productanalytics.FirstTouchCampaignIDProperty,+ "content_id": productanalytics.FirstTouchContentIDProperty,+ "utm_source": productanalytics.FirstTouchUTMSourceProperty,+ "utm_medium": productanalytics.FirstTouchUTMMediumProperty,+ "utm_campaign": productanalytics.FirstTouchUTMCampaignProperty,+}++type fleetAttributionRecord struct {+ Version int `json:"version"`+ CapturedAt int64 `json:"capturedAt"`+ Values map[string]string `json:"values"`+}++func (h Handlers) RecordFleetAttribution(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+ }++ r.Body = http.MaxBytesReader(w, r.Body, fleetAttributionBodyMaxBytes)+ decoder := json.NewDecoder(r.Body)+ decoder.DisallowUnknownFields()+ var record fleetAttributionRecord+ if err := decoder.Decode(&record); err != nil {+ var maxBytesError *http.MaxBytesError+ if errors.As(err, &maxBytesError) {+ writeErr(w, http.StatusRequestEntityTooLarge, "attribution record is too large")+ return+ }+ writeErr(w, http.StatusBadRequest, "invalid attribution record")+ return+ }+ if err := decoder.Decode(&struct{}{}); err != io.EOF {+ writeErr(w, http.StatusBadRequest, "invalid attribution record")+ return+ }++ setOnce, valid := validateFleetAttribution(record, time.Now())+ if !valid {+ writeErr(w, http.StatusBadRequest, "invalid attribution record")+ return+ }+ if productanalytics.ClassifyIdentity(user) != productanalytics.IdentityExternal {+ w.WriteHeader(http.StatusNoContent)+ return+ }++ capturer := h.Analytics+ if capturer == nil {+ capturer = productanalytics.Nop()+ }+ capturer.Capture(productanalytics.Event{+ Name: productanalytics.EventAttributionBound,+ DistinctID: user.ID,+ Properties: map[string]any{+ "outcome": productanalytics.OutcomeSuccess,+ "source": source,+ "principal_type": auth.PrincipalTypeUser,+ "identity_class": productanalytics.IdentityExternal,+ },+ SetOnce: setOnce,+ })+ w.WriteHeader(http.StatusNoContent)+}++func validateFleetAttribution(record fleetAttributionRecord, now time.Time) (map[string]any, bool) {+ if record.Version != 1 || record.CapturedAt <= 0 || len(record.Values) == 0 {+ return nil, false+ }+ age := now.UnixMilli() - record.CapturedAt+ if age < 0 || age >= fleetAttributionTTL.Milliseconds() {+ return nil, false+ }+ setOnce := make(map[string]any, len(record.Values))+ for key, value := range record.Values {+ property, ok := fleetAttributionProperties[key]+ if !ok || !validFleetAttributionValue(value) {+ return nil, false+ }+ setOnce[property] = value+ }+ return setOnce, true+}++func validFleetAttributionValue(value string) bool {+ if value == "" || len(value) > 128 {+ return false+ }+ for _, b := range []byte(value) {+ if !(b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' || b == '.' || b == '_' || b == '~' || b == '-') {+ return false+ }+ }+ return true+}diff --git a/libs/fleet/backend/handlers/analytics_attribution_test.go b/libs/fleet/backend/handlers/analytics_attribution_test.gonew file mode 100644index 0000000000..e254593af6--- /dev/null+++ b/libs/fleet/backend/handlers/analytics_attribution_test.go@@ -0,0 +1,106 @@+package handlers++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "cyclops-cs-backend/auth"+ "cyclops-cs-backend/productanalytics"+)++func attributionRequest(t *testing.T, body any, user *auth.User) *http.Request {+ t.Helper()+ encoded, err := json.Marshal(body)+ if err != nil {+ t.Fatal(err)+ }+ request := httptest.NewRequest(http.MethodPost, "/api/analytics/attribution", bytes.NewReader(encoded))+ return request.WithContext(context.WithValue(request.Context(), auth.UserKey, user))+}++func TestRecordFleetAttributionBindsExternalFirstTouch(t *testing.T) {+ capture := &analyticsCapture{}+ h := Handlers{Analytics: capture, AuthCfg: configAuthForAnalytics()}+ request := attributionRequest(t, fleetAttributionRecord{+ Version: 1,+ CapturedAt: time.Now().Add(-time.Minute).UnixMilli(),+ Values: map[string]string{+ "utm_source": "x",+ "utm_medium": "organic-social",+ "utm_campaign": "openclaw-2-launch",+ },+ }, &auth.User{ID: "subject-1", Email: "[email protected]", EmailVerified: true, AZP: "cyclops-cs-spa", PrincipalType: auth.PrincipalTypeUser})+ response := httptest.NewRecorder()++ h.RecordFleetAttribution(response, request)++ 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.EventAttributionBound || event.DistinctID != "subject-1" {+ t.Fatalf("event = %#v", event)+ }+ if event.SetOnce[productanalytics.FirstTouchUTMSourceProperty] != "x" ||+ event.SetOnce[productanalytics.FirstTouchUTMMediumProperty] != "organic-social" ||+ event.SetOnce[productanalytics.FirstTouchUTMCampaignProperty] != "openclaw-2-launch" {+ t.Fatalf("set once = %#v", event.SetOnce)+ }+}++func TestRecordFleetAttributionExcludesInternalAndUnknownIdentities(t *testing.T) {+ for _, user := range []*auth.User{+ {ID: "internal-1", Email: "[email protected]", EmailVerified: true, AZP: "cyclops-cs-spa"},+ {ID: "unknown-1", AZP: "cyclops-cs-spa"},+ } {+ capture := &analyticsCapture{}+ h := Handlers{Analytics: capture, AuthCfg: configAuthForAnalytics()}+ response := httptest.NewRecorder()+ h.RecordFleetAttribution(response, attributionRequest(t, fleetAttributionRecord{+ Version: 1, CapturedAt: time.Now().UnixMilli(), Values: map[string]string{"utm_source": "x"},+ }, user))+ if response.Code != http.StatusNoContent || len(capture.events) != 0 {+ t.Fatalf("user/status/events = %#v/%d/%#v", user, response.Code, capture.events)+ }+ }+}++func TestRecordFleetAttributionRejectsUnsafeRecords(t *testing.T) {+ now := time.Now()+ tests := []struct {+ name string+ body any+ want int+ }{+ {name: "expired", body: fleetAttributionRecord{Version: 1, CapturedAt: now.Add(-fleetAttributionTTL).UnixMilli(), Values: map[string]string{"utm_source": "x"}}, want: http.StatusBadRequest},+ {name: "future", body: fleetAttributionRecord{Version: 1, CapturedAt: now.Add(time.Minute).UnixMilli(), Values: map[string]string{"utm_source": "x"}}, want: http.StatusBadRequest},+ {name: "unknown key", body: fleetAttributionRecord{Version: 1, CapturedAt: now.UnixMilli(), Values: map[string]string{"email": "person"}}, want: http.StatusBadRequest},+ {name: "unsafe value", body: fleetAttributionRecord{Version: 1, CapturedAt: now.UnixMilli(), Values: map[string]string{"utm_source": "x post"}}, want: http.StatusBadRequest},+ {name: "oversized", body: `{"version":1,"capturedAt":1,"values":{"utm_source":"` + strings.Repeat("x", fleetAttributionBodyMaxBytes) + `"}}`, want: http.StatusRequestEntityTooLarge},+ }+ user := &auth.User{ID: "subject-1", Email: "[email protected]", EmailVerified: true, AZP: "cyclops-cs-spa"}+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ capture := &analyticsCapture{}+ h := Handlers{Analytics: capture, AuthCfg: configAuthForAnalytics()}+ var request *http.Request+ if raw, ok := test.body.(string); ok {+ request = httptest.NewRequest(http.MethodPost, "/api/analytics/attribution", strings.NewReader(raw))+ request = request.WithContext(context.WithValue(request.Context(), auth.UserKey, user))+ } else {+ request = attributionRequest(t, test.body, user)+ }+ response := httptest.NewRecorder()+ h.RecordFleetAttribution(response, request)+ if response.Code != test.want || len(capture.events) != 0 {+ t.Fatalf("status/events = %d/%#v", response.Code, capture.events)+ }+ })+ }+}diff --git a/libs/fleet/backend/handlers/attribution.go b/libs/fleet/backend/handlers/attribution.goindex a33f3c5be2..0d4c21dd24 100644--- a/libs/fleet/backend/handlers/attribution.go+++ b/libs/fleet/backend/handlers/attribution.go@@ -21,9 +21,17 @@ type AttributionFactsReader interface {}func (h Handlers) FleetAttributionQualifier() productanalytics.SvcQualifier {- reader := fleetAttributionFactsReader{handlers: h}+ qualification := h.FleetAttributionQualification()return func(ctx context.Context, r *http.Request, status int) bool {- return QualifySvcRequest(ctx, r, status, reader)+ return qualification(ctx, r, status).Qualifies+ }+}++func (h Handlers) FleetAttributionQualification() productanalytics.SvcQualification {+ reader := fleetAttributionFactsReader{handlers: h}+ return func(ctx context.Context, r *http.Request, status int) productanalytics.SvcQualificationResult {+ result := QualifySvcRequestResult(ctx, r, status, reader)+ return productanalytics.SvcQualificationResult{Qualifies: result.Qualifies, Reason: result.Reason}}}@@ -92,24 +100,69 @@ func (reader fleetAttributionFactsReader) PoolExists(ctx context.Context, namesp}func QualifySvcRequest(ctx context.Context, r *http.Request, status int, reader AttributionFactsReader) bool {+ return QualifySvcRequestResult(ctx, r, status, reader).Qualifies+}++type QualificationResult struct {+ Qualifies bool+ Reason string+}++func QualifySvcRequestResult(ctx context.Context, r *http.Request, status int, reader AttributionFactsReader) QualificationResult {upgrade := isUpgradeRequest(r)- if reader == nil || r.Pattern == "" || !strings.HasPrefix(r.Pattern, "/api/svc/") || r.Method == "HEAD" || r.Method == "OPTIONS" || upgrade {- return false+ if reader == nil {+ return QualificationResult{Reason: "facts_unavailable"}+ }+ if r.Pattern == "" || !strings.HasPrefix(r.Pattern, "/api/svc/") {+ return QualificationResult{Reason: "not_svc_route"}+ }+ if r.Method == "HEAD" || r.Method == "OPTIONS" {+ return QualificationResult{Reason: "invalid_method"}+ }+ if upgrade {+ return QualificationResult{Reason: "upgrade_request"}}claim := r.Header.Get(FleetClaimHeader)- if claim == "" || len(r.Header.Values(FleetClaimHeader)) != 1 || len(claim) > 128 || !validAttributionClaim(claim) {- return false+ if len(r.Header.Values(FleetClaimHeader)) > 1 {+ return QualificationResult{Reason: "multiple_claims"}+ }+ if claim == "" {+ return QualificationResult{Reason: "missing_claim"}+ }+ if len(claim) > 128 || !validAttributionClaim(claim) {+ return QualificationResult{Reason: "invalid_claim"}}ns, service := r.PathValue("namespace"), r.PathValue("service")bound, err := reader.ReadBoundClaim(ctx, ns, claim)- if err != nil || bound.Claim != claim || !bound.Bound || bound.Sandbox == "" || service != bound.Sandbox+"-server" {- return false+ if err != nil {+ return QualificationResult{Reason: "claim_lookup_failed"}+ }+ if bound.Claim != claim {+ return QualificationResult{Reason: "claim_mismatch"}+ }+ if !bound.Bound {+ return QualificationResult{Reason: "claim_not_bound"}+ }+ if bound.Sandbox == "" {+ return QualificationResult{Reason: "sandbox_missing"}+ }+ if service != bound.Sandbox+"-server" {+ return QualificationResult{Reason: "service_mismatch"}}pool, err := reader.PoolExists(ctx, ns, ns)- if err != nil || !pool || status < 200 || status >= 300 {- return false+ if err != nil {+ return QualificationResult{Reason: "pool_lookup_failed"}+ }+ if !pool {+ return QualificationResult{Reason: "pool_missing"}+ }+ if status < 200 || status >= 300 {+ return QualificationResult{Reason: "non_2xx"}+ }+ if !QualifiesFleetAttribution(AttributionFacts{AuthenticatedNamespace: true, SDKClaim: claim, Claim: bound, Service: service, Namespace: ns, Route: r.Pattern, Path: r.PathValue("path"), Method: r.Method, NamespacePoolExists: pool, UpstreamStatus: status, Upgrade: upgrade}) {+ return QualificationResult{Reason: "probe_request"}}- return QualifiesFleetAttribution(AttributionFacts{AuthenticatedNamespace: true, SDKClaim: claim, Claim: bound, Service: service, Namespace: ns, Route: r.Pattern, Path: r.PathValue("path"), Method: r.Method, NamespacePoolExists: pool, UpstreamStatus: status, Upgrade: upgrade})+ return QualificationResult{Qualifies: true}}func isUpgradeRequest(r *http.Request) bool {diff --git a/libs/fleet/backend/handlers/attribution_test.go b/libs/fleet/backend/handlers/attribution_test.goindex f33f4710e3..ad28e25be8 100644--- a/libs/fleet/backend/handlers/attribution_test.go+++ b/libs/fleet/backend/handlers/attribution_test.go@@ -139,6 +139,20 @@ func TestQualifySvcRequestUsesOnlyValidatedExactClaimAndSvcRoutes(t *testing.T)}}+func TestQualifySvcRequestResultReportsBoundedReasons(t *testing.T) {+ reader := &fakeAttributionFactsReader{claim: BoundClaim{Claim: "claim-1", Sandbox: "sandbox-1", Bound: true}, pool: true}+ r := httptest.NewRequest("GET", "/api/svc/pool-1/sandbox-1-server/health", nil)+ r.Pattern = "/api/svc/{namespace}/{service}/{path...}"+ r.SetPathValue("namespace", "pool-1")+ r.SetPathValue("service", "sandbox-1-server")+ r.SetPathValue("path", "health")+ r.Header.Set(FleetClaimHeader, "claim-1")+ result := QualifySvcRequestResult(r.Context(), r, http.StatusOK, reader)+ if result.Qualifies || result.Reason != "probe_request" {+ t.Fatalf("result = %#v", result)+ }+}+func TestQualifySvcRequestRejectsUpgradeSignalsBeforeReadingFacts(t *testing.T) {for _, headers := range []http.Header{{"Upgrade": {"websocket"}},diff --git a/libs/fleet/backend/main.go b/libs/fleet/backend/main.goindex 8c353f9a51..b2e603ee20 100644--- a/libs/fleet/backend/main.go+++ b/libs/fleet/backend/main.go@@ -135,7 +135,7 @@ func setupRouter(c handlers.Handlers) http.Handler {auth.RegisterFactProvider(auth.CurrentMonthFactProvider, auth.CurrentMonthFacts(time.Now))r := http.NewServeMux()- svcQualifier := c.FleetAttributionQualifier()+ svcQualifier := c.FleetAttributionQualification()r.Handle("GET /healthz", onlyLog("/healthz", c.GetHealth))r.Handle("GET /readyz", onlyLog("/readyz", c.GetReadiness))@@ -145,6 +145,8 @@ func setupRouter(c handlers.Handlers) http.Handler {withAuthenticatedMiddlewares("/api/config", c.GetConfig))r.Handle("POST /api/analytics/session",withAuthenticatedMiddlewares("/api/analytics/session", c.RecordAnalyticsSession))+ r.Handle("POST /api/analytics/attribution",+ withAuthenticatedMiddlewares("/api/analytics/attribution", c.RecordFleetAttribution))r.Handle("POST /api/chat/conversations",withAuthenticatedMiddlewares("/api/chat/conversations", c.CreateConversation))@@ -228,10 +230,10 @@ func setupRouter(c handlers.Handlers) http.Handler {// policy reads as a fact — see auth/authz_ownership.rego.r.Handle("/api/svc/{namespace}/{service}",withAuthenticatedMiddlewares("/api/svc/{namespace}/{service}", c.Svc,- productanalytics.RouteObserver("/api/svc/{namespace}/{service}", c.Analytics, c.AuthCfg.SPAClientID, svcQualifier)))+ productanalytics.RouteObserverWithQualification("/api/svc/{namespace}/{service}", c.Analytics, c.AuthCfg.SPAClientID, svcQualifier)))r.Handle("/api/svc/{namespace}/{service}/{path...}",withAuthenticatedMiddlewares("/api/svc/{namespace}/{service}/{path...}", c.Svc,- productanalytics.RouteObserver("/api/svc/{namespace}/{service}/{path...}", c.Analytics, c.AuthCfg.SPAClientID, svcQualifier)))+ productanalytics.RouteObserverWithQualification("/api/svc/{namespace}/{service}/{path...}", c.Analytics, c.AuthCfg.SPAClientID, svcQualifier)))// K8s API access replaces the unauthenticated /k8s-api nginx location.r.Handle("/api/k8s/{path...}",diff --git a/libs/fleet/backend/productanalytics/client.go b/libs/fleet/backend/productanalytics/client.goindex a679bec9d3..ef543e0b44 100644--- a/libs/fleet/backend/productanalytics/client.go+++ b/libs/fleet/backend/productanalytics/client.go@@ -89,6 +89,9 @@ func (client *Client) Capture(event Event) {if event.Name == EventFleetActivation {event.InsertID = "fleet-activation:" + pseudonym}+ if event.Name == EventAttributionBound {+ event.InsertID = "fleet-attribution:" + pseudonym+ }copied := cloneEvent(event)copied.Properties["environment"] = client.config.Environmentcopied.Properties["instrumentation_version"] = Versiondiff --git a/libs/fleet/backend/productanalytics/client_test.go b/libs/fleet/backend/productanalytics/client_test.goindex 272a6ed009..74d4d1dc89 100644--- a/libs/fleet/backend/productanalytics/client_test.go+++ b/libs/fleet/backend/productanalytics/client_test.go@@ -88,3 +88,46 @@ func TestClientSuppressesExcludedSubject(t *testing.T) {defer cancel()_ = client.Shutdown(ctx)}++func TestClientPseudonymizesAttributionIdentityAndStableInsertID(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.Fatal(err)+ }+ requests <- payload+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()+ client := New(Config{+ Enabled: true, Host: server.URL, ProjectToken: "phc_test", IdentityKey: "identity-test-key", Environment: "production",+ QueueSize: 2, BatchSize: 1, FlushInterval: time.Hour, RequestTimeout: time.Second,+ })+ client.Capture(Event{+ Name: EventAttributionBound, DistinctID: "subject-1",+ Properties: map[string]any{"outcome": OutcomeSuccess, "source": SourceSPA, "principal_type": "user", "identity_class": IdentityExternal},+ SetOnce: map[string]any{FirstTouchUTMCampaignProperty: "openclaw-2-launch"},+ })+ 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-attribution:"+pseudonym {+ t.Fatalf("item = %#v", item)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("timed out waiting for attribution capture")+ }+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)+ defer cancel()+ if err := client.Shutdown(ctx); err != nil {+ t.Fatal(err)+ }+}diff --git a/libs/fleet/backend/productanalytics/events.go b/libs/fleet/backend/productanalytics/events.goindex 83a37110d0..6ef64ca851 100644--- a/libs/fleet/backend/productanalytics/events.go+++ b/libs/fleet/backend/productanalytics/events.go@@ -38,13 +38,22 @@ func PseudonymForUserID(userID, key string) string {}const (- EventLoginSucceeded = "fleet_login_succeeded"- EventPaymentMethodSetup = "fleet_payment_method_setup"- EventPoolCreate = "fleet_pool_create"- EventClaimCreate = "fleet_claim_create"- EventHTTPProxyRequest = "fleet_http_proxy_request"- EventFleetActivation = "first_pool_with_successful_request"- EventQualifyingWorkload = "fleet_qualifying_workload_succeeded"+ EventLoginSucceeded = "fleet_login_succeeded"+ EventPaymentMethodSetup = "fleet_payment_method_setup"+ EventPoolCreate = "fleet_pool_create"+ EventClaimCreate = "fleet_claim_create"+ EventHTTPProxyRequest = "fleet_http_proxy_request"+ EventFleetActivation = "first_pool_with_successful_request"+ EventQualifyingWorkload = "fleet_qualifying_workload_succeeded"+ EventResourceBlocked = "fleet_resource_creation_blocked"+ EventQualificationRejected = "fleet_workload_qualification_rejected"+ EventAttributionBound = "fleet_attribution_bound"++ FirstTouchCampaignIDProperty = "fleet_first_touch_campaign_id"+ FirstTouchContentIDProperty = "fleet_first_touch_content_id"+ FirstTouchUTMSourceProperty = "fleet_first_touch_utm_source"+ FirstTouchUTMMediumProperty = "fleet_first_touch_utm_medium"+ FirstTouchUTMCampaignProperty = "fleet_first_touch_utm_campaign"OutcomeSuccess = "success"OutcomeFailure = "failure"@@ -58,12 +67,31 @@ var allowedEvents = map[string]struct{}{EventClaimCreate: {}, EventHTTPProxyRequest: {},EventFleetActivation: {},EventQualifyingWorkload: {},+ EventResourceBlocked: {}, EventQualificationRejected: {},+ EventAttributionBound: {},}var allowedProperties = map[string]struct{}{"outcome": {}, "source": {}, "principal_type": {}, "status_code": {},"error_class": {}, "environment": {}, "instrumentation_version": {},"identity_class": {},+ "resource_type": {}, "reason": {},+}++var allowedResourceTypes = map[string]struct{}{"pool": {}, "template": {}, "claim": {}}+var allowedReasons = map[string]struct{}{+ "payment_required": {}, "authorization": {}, "validation": {}, "quota": {}, "timeout": {}, "internal": {},+ "not_svc_route": {}, "invalid_method": {}, "upgrade_request": {}, "missing_claim": {}, "multiple_claims": {},+ "invalid_claim": {}, "claim_lookup_failed": {}, "claim_mismatch": {}, "claim_not_bound": {}, "sandbox_missing": {},+ "service_mismatch": {}, "pool_lookup_failed": {}, "pool_missing": {}, "non_2xx": {}, "probe_request": {}, "facts_unavailable": {},+}++var allowedFirstTouchProperties = map[string]struct{}{+ FirstTouchCampaignIDProperty: {},+ FirstTouchContentIDProperty: {},+ FirstTouchUTMSourceProperty: {},+ FirstTouchUTMMediumProperty: {},+ FirstTouchUTMCampaignProperty: {},}type Event struct {@@ -111,8 +139,66 @@ func ValidateEvent(event Event) error {}for key := range event.SetOnce {if key != firstSeenProperty && key != firstActivationProperty {+ if _, ok := allowedFirstTouchProperties[key]; ok {+ continue+ }return fmt.Errorf("unsupported analytics set-once property %q", key)}}+ firstTouchCount := 0+ for key, value := range event.SetOnce {+ if _, ok := allowedFirstTouchProperties[key]; !ok {+ continue+ }+ text, ok := value.(string)+ if !ok || !validAttributionValue(text) {+ return fmt.Errorf("invalid first-touch attribution value")+ }+ firstTouchCount+++ }+ if event.Name == EventAttributionBound && firstTouchCount == 0 {+ return fmt.Errorf("attribution event requires first-touch properties")+ }+ if event.Name != EventAttributionBound && firstTouchCount > 0 {+ return fmt.Errorf("first-touch properties require attribution event")+ }+ resourceType, hasResourceType := event.Properties["resource_type"]+ if hasResourceType {+ value, ok := resourceType.(string)+ if !ok {+ return fmt.Errorf("resource type must be a string")+ }+ if _, valid := allowedResourceTypes[value]; !valid {+ return fmt.Errorf("unsupported resource type")+ }+ }+ reason, hasReason := event.Properties["reason"]+ if hasReason {+ value, ok := reason.(string)+ if !ok {+ return fmt.Errorf("analytics reason must be a string")+ }+ if _, valid := allowedReasons[value]; !valid {+ return fmt.Errorf("unsupported analytics reason")+ }+ }+ if event.Name == EventResourceBlocked && (!hasResourceType || !hasReason) {+ return fmt.Errorf("resource block event requires resource type and reason")+ }+ if event.Name == EventQualificationRejected && !hasReason {+ return fmt.Errorf("qualification rejection event requires reason")+ }return nil}++func validAttributionValue(value string) bool {+ if value == "" || len(value) > 128 {+ return false+ }+ for _, b := range []byte(value) {+ if !(b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' || strings.ContainsRune("._~-", rune(b))) {+ return false+ }+ }+ return true+}diff --git a/libs/fleet/backend/productanalytics/events_test.go b/libs/fleet/backend/productanalytics/events_test.goindex 89cb12f401..1ffee7469f 100644--- a/libs/fleet/backend/productanalytics/events_test.go+++ b/libs/fleet/backend/productanalytics/events_test.go@@ -92,4 +92,20 @@ func TestValidateEventRejectsUnsafeProperties(t *testing.T) {}})}++ attribution := Event{+ Name: EventAttributionBound, DistinctID: "subject-1",+ Properties: map[string]any{"outcome": OutcomeSuccess, "source": SourceSPA, "principal_type": auth.PrincipalTypeUser, "identity_class": IdentityExternal},+ SetOnce: map[string]any{FirstTouchUTMCampaignProperty: "openclaw-2-launch"},+ }+ if err := ValidateEvent(attribution); err != nil {+ t.Fatalf("ValidateEvent(attribution) error = %v", err)+ }+ for _, value := range []any{"has space", "", 42} {+ invalid := attribution+ invalid.SetOnce = map[string]any{FirstTouchUTMCampaignProperty: value}+ if err := ValidateEvent(invalid); err == nil {+ t.Fatalf("ValidateEvent() accepted attribution value %#v", value)+ }+ }}diff --git a/libs/fleet/backend/productanalytics/middleware.go b/libs/fleet/backend/productanalytics/middleware.goindex ca6af42422..48a5cc398c 100644--- a/libs/fleet/backend/productanalytics/middleware.go+++ b/libs/fleet/backend/productanalytics/middleware.go@@ -2,6 +2,7 @@ package productanalyticsimport ("bufio"+ "bytes""context""fmt""net"@@ -15,8 +16,27 @@ import ()type SvcQualifier func(context.Context, *http.Request, int) bool+type SvcQualificationResult struct {+ Qualifies bool+ Reason string+}+type SvcQualification func(context.Context, *http.Request, int) SvcQualificationResultfunc RouteObserver(route string, capturer Capturer, spaClientID string, qualifiers ...SvcQualifier) auth.Middleware {+ var qualifier SvcQualification+ if len(qualifiers) > 0 && qualifiers[0] != nil {+ qualifier = func(ctx context.Context, r *http.Request, status int) SvcQualificationResult {+ return SvcQualificationResult{Qualifies: qualifiers[0](ctx, r, status)}+ }+ }+ return routeObserver(route, capturer, spaClientID, qualifier)+}++func RouteObserverWithQualification(route string, capturer Capturer, spaClientID string, qualifier SvcQualification) auth.Middleware {+ return routeObserver(route, capturer, spaClientID, qualifier)+}++func routeObserver(route string, capturer Capturer, spaClientID string, qualifier SvcQualification) auth.Middleware {if capturer == nil {capturer = Nop()}@@ -36,13 +56,19 @@ func RouteObserver(route string, capturer Capturer, spaClientID string, qualifieif traceID == "00000000000000000000000000000000" {traceID, _ = r.Context().Value(middlewares.ContextKey("traceId")).(string)}- if activation.eventName == EventHTTPProxyRequest && ClassifyIdentity(user) == IdentityExternal && len(qualifiers) > 0 {- qualifier := qualifiers[0]+ if activation.eventName == EventHTTPProxyRequest && ClassifyIdentity(user) == IdentityExternal && qualifier != nil {go func() {defer func() { _ = recover() }()ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 250*time.Millisecond)defer cancel()- if !qualifier(ctx, r, status) {+ result := qualifier(ctx, r, status)+ if !result.Qualifies {+ if result.Reason != "" {+ capturer.Capture(Event{Name: EventQualificationRejected, DistinctID: user.ID, InsertID: traceID + ":qualification-rejected", Properties: map[string]any{+ "outcome": OutcomeFailure, "source": source, "principal_type": user.PrincipalType, "status_code": status,+ "error_class": errorClass(status), "identity_class": IdentityExternal, "reason": result.Reason,+ }})+ }return}properties := map[string]any{@@ -81,6 +107,13 @@ func RouteObserver(route string, capturer Capturer, spaClientID string, qualifie"identity_class": ClassifyIdentity(user),},})+ if activation.resourceType != "" && (status < 200 || status >= 300) {+ reason := blockedReason(status, rw.paymentRequired)+ capturer.Capture(Event{Name: EventResourceBlocked, DistinctID: user.ID, InsertID: traceID + ":resource-blocked", Properties: map[string]any{+ "outcome": OutcomeFailure, "source": source, "principal_type": principalType, "status_code": status,+ "error_class": errorClass(status), "identity_class": ClassifyIdentity(user), "resource_type": activation.resourceType, "reason": reason,+ }})+ }})}}@@ -88,6 +121,7 @@ func RouteObserver(route string, capturer Capturer, spaClientID string, qualifietype activationTarget struct {eventName stringsuppressSuccess bool+ resourceType string}func activationEvent(route string, r *http.Request) (activationTarget, bool) {@@ -103,18 +137,38 @@ func activationEvent(route string, r *http.Request) (activationTarget, bool) {}switch {case parts[1] == "cua.ai" && parts[2] == "v1" && parts[5] == "osgymworkspacepools":- return activationTarget{eventName: EventPoolCreate}, true+ return activationTarget{eventName: EventPoolCreate, resourceType: "pool"}, truecase parts[1] == "osgym.cua.ai" && parts[2] == "v1alpha1" && parts[5] == "osgymsandboxwarmpools":- return activationTarget{eventName: EventPoolCreate, suppressSuccess: true}, true+ return activationTarget{eventName: EventPoolCreate, suppressSuccess: true, resourceType: "pool"}, truecase parts[1] == "osgym.cua.ai" && parts[2] == "v1alpha1" && parts[5] == "osgymsandboxtemplates":- return activationTarget{eventName: EventPoolCreate}, true+ return activationTarget{eventName: EventPoolCreate, resourceType: "template"}, truecase parts[1] == "osgym.cua.ai" && parts[2] == "v1alpha1" && parts[5] == "osgymsandboxclaims":- return activationTarget{eventName: EventClaimCreate}, true+ return activationTarget{eventName: EventClaimCreate, resourceType: "claim"}, truedefault:return activationTarget{}, false}}+func blockedReason(status int, paymentRequired bool) string {+ if paymentRequired {+ return "payment_required"+ }+ switch {+ case status == http.StatusBadRequest || status == http.StatusUnprocessableEntity:+ return "validation"+ case status == http.StatusUnauthorized || status == http.StatusForbidden:+ return "authorization"+ case status == http.StatusTooManyRequests:+ return "quota"+ case status == http.StatusRequestTimeout || status == http.StatusGatewayTimeout:+ return "timeout"+ case status >= 500:+ return "internal"+ default:+ return "authorization"+ }+}+func successfulActivation(eventName string, status int) bool {if eventName == EventHTTPProxyRequest {return status >= 200 && status < 400@@ -145,8 +199,10 @@ func errorClass(status int) string {type analyticsResponseWriter struct {http.ResponseWriter- statusCode int- written bool+ statusCode int+ written bool+ paymentRequired bool+ bodySample []byte}func newAnalyticsResponseWriter(w http.ResponseWriter) *analyticsResponseWriter {@@ -162,6 +218,16 @@ func (rw *analyticsResponseWriter) WriteHeader(status int) {}func (rw *analyticsResponseWriter) Write(body []byte) (int, error) {+ if len(rw.bodySample) < 512 {+ remaining := 512 - len(rw.bodySample)+ if len(body) < remaining {+ 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")) {+ rw.paymentRequired = true+ }+ }if !rw.written {rw.WriteHeader(http.StatusOK)}diff --git a/libs/fleet/backend/productanalytics/middleware_test.go b/libs/fleet/backend/productanalytics/middleware_test.goindex 770ad09dbb..c216b246c9 100644--- a/libs/fleet/backend/productanalytics/middleware_test.go+++ b/libs/fleet/backend/productanalytics/middleware_test.go@@ -2,6 +2,7 @@ package productanalyticsimport ("bufio"+ "bytes""context""net""net/http"@@ -139,7 +140,11 @@ func TestRouteObserverCapturesActivationOutcomes(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 {+ wantEvents := 1+ if (test.status < 200 || test.status >= 300) && test.wantEvent != EventHTTPProxyRequest {+ wantEvents = 2+ }+ if len(sink.events) != wantEvents {t.Fatalf("events = %#v", sink.events)}event := sink.events[0]@@ -149,6 +154,12 @@ func TestRouteObserverCapturesActivationOutcomes(t *testing.T) {if event.Properties["outcome"] != test.wantOutcome || event.Properties["source"] != test.wantSource || event.Properties["error_class"] != test.wantClass {t.Fatalf("properties = %#v", event.Properties)}+ if wantEvents == 2 {+ blocked := sink.events[1]+ if blocked.Name != EventResourceBlocked || blocked.Properties["resource_type"] == "" || blocked.Properties["reason"] == "" {+ t.Fatalf("blocked event = %#v", blocked)+ }+ }})}}@@ -228,3 +239,42 @@ func TestAnalyticsResponseWriterPreservesProxyInterfaces(t *testing.T) {t.Fatal("missing http.Hijacker")}}++func TestRouteObserverClassifiesPaymentRequiredWithoutChangingResponse(t *testing.T) {+ sink := &captureSink{}+ handler := 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."}`))+ }))+ 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"}))+ if response.Code != http.StatusForbidden || !bytes.Contains(response.Body.Bytes(), []byte("A payment method is required")) {+ t.Fatalf("response changed: status=%d body=%q", response.Code, response.Body.String())+ }+ if len(sink.events) != 2 || sink.events[1].Name != EventResourceBlocked || sink.events[1].Properties["reason"] != "payment_required" {+ t.Fatalf("events = %#v", sink.events)+ }+}++func TestRouteObserverEmitsBoundedQualificationRejectionForExternalUsers(t *testing.T) {+ sink := make(eventChannel, 2)+ handler := RouteObserverWithQualification("/api/svc/{namespace}/{service}/{path...}", sink, "cyclops-cs-spa", func(context.Context, *http.Request, int) SvcQualificationResult {+ return SvcQualificationResult{Reason: "claim_mismatch"}+ })(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }))+ user := &auth.User{ID: "external-1", Email: "[email protected]", EmailVerified: true, AZP: "cyclops-cs-spa", PrincipalType: auth.PrincipalTypeUser}+ handler.ServeHTTP(httptest.NewRecorder(), observedRequest(http.MethodGet, "/api/svc/{namespace}/{service}/{path...}", "tools", user))+ var events []Event+ deadline := time.After(time.Second)+ for len(events) < 2 {+ select {+ case event := <-sink:+ events = append(events, event)+ case <-deadline:+ t.Fatalf("events = %#v", events)+ }+ }+ if events[1].Name != EventQualificationRejected || events[1].Properties["reason"] != "claim_mismatch" || events[1].DistinctID != user.ID {+ t.Fatalf("event = %#v", events[1])+ }+}diff --git a/libs/fleet/docs/fleet-attribution-phase1.md b/libs/fleet/docs/fleet-attribution-phase1.mdindex f244306463..4db3b06f2c 100644--- a/libs/fleet/docs/fleet-attribution-phase1.md+++ b/libs/fleet/docs/fleet-attribution-phase1.md@@ -1,6 +1,6 @@# Fleet Attribution Phase 1-This public contract defines a deliberately default-off qualification seam.+This public contract defines bounded first-touch campaign binding and workload qualification.## Browser capture@@ -10,6 +10,8 @@ The five stable fields are acquisition-channel neutral. They can represent email## Binding and qualification-The binder accepts only a validated, unexpired record and is disabled when no binder is supplied. It has no production endpoint or analytics emitter. `QualifiesFleetAttribution` is a deterministic, side-effect-free predicate over explicit facts. Qualification requires authenticated namespace authorization, an exact SDK-provided claim matching a Bound claim with a sandbox identity, service exactly `<sandbox>-server`, an exact namespace pool, and a 2xx upstream response. Probe paths, redirects, upgrades, HEAD/OPTIONS, non-service routes, and Kubernetes/orchestration routes are excluded.+After Keycloak authentication, the SPA submits the validated record to the authenticated `/api/analytics/attribution` endpoint. The backend repeats the version, size, age, key, and value checks and accepts only the Fleet SPA principal. Verified external identities emit `fleet_attribution_bound`; internal and unknown identities are discarded. PostHog receives the five fields only as set-once first-touch person properties under the keyed-HMAC pseudonym. The endpoint never accepts a URL, referrer, email, raw identity, arbitrary property, or provider payload, and attribution delivery cannot affect authentication or application readiness.++`QualifiesFleetAttribution` is a deterministic, side-effect-free predicate over explicit facts. Qualification requires authenticated namespace authorization, an exact SDK-provided claim matching a Bound claim with a sandbox identity, service exactly `<sandbox>-server`, an exact namespace pool, and a 2xx upstream response. Probe paths, redirects, upgrades, HEAD/OPTIONS, non-service routes, and Kubernetes/orchestration routes are excluded.The SDK supplies correlation using the exact claim already present on `Sandbox` in the `X-Cua-Fleet-Claim` request header. No claim lookup, user identity, cohort, recipient, or timestamp inference is performed. `qualifies` is a qualification verdict only; it is not an activation claim or emission.diff --git a/libs/fleet/src/auth/AuthProvider.tsx b/libs/fleet/src/auth/AuthProvider.tsxindex 52b870bad0..7271fe9d37 100644--- a/libs/fleet/src/auth/AuthProvider.tsx+++ b/libs/fleet/src/auth/AuthProvider.tsx@@ -5,7 +5,7 @@import { useEffect, useLayoutEffect, useState } from "react"import { initKc, kc } from "./keycloak"-import { recordFleetLogin } from "./analytics"+import { bindFleetAttribution, recordFleetLogin } from "./analytics"import { isLocalVisualPreview } from "../local-visual-preview"interface Props {@@ -30,7 +30,10 @@ export function AuthProvider({ children }: Props) {return}setReady(true)- void recordFleetLogin(kc.sessionId).catch(() => undefined)+ void Promise.allSettled([+ bindFleetAttribution(),+ recordFleetLogin(kc.sessionId),+ ])}).catch(e => setError(String(e)))}, [visualPreview])diff --git a/libs/fleet/src/auth/analytics.ts b/libs/fleet/src/auth/analytics.tsindex ca26b3853a..4a1972d783 100644--- a/libs/fleet/src/auth/analytics.ts+++ b/libs/fleet/src/auth/analytics.ts@@ -1,6 +1,9 @@+import { bindStoredFleetAttribution, type AttributionBinder } from "./fleet-attribution"+interface SessionStorageLike {getItem(key: string): string | nullsetItem(key: string, value: string): void+ removeItem?(key: string): void}interface AnalyticsDependencies {@@ -40,3 +43,27 @@ export async function recordFleetLogin(}dependencies.storage.setItem(marker, "true")}++export async function bindFleetAttribution(+ dependencies: AnalyticsDependencies = defaultDependencies(),+): Promise<void> {+ const binder: AttributionBinder = {+ bind: async (record, accessToken) => {+ const response = await dependencies.fetch("/api/analytics/attribution", {+ method: "POST",+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify(record),+ })+ if (!response.ok) {+ throw new Error(`Fleet attribution request failed: ${response.status}`)+ }+ },+ }+ await bindStoredFleetAttribution(binder, {+ storage: dependencies.storage,+ getAccessToken: dependencies.getToken,+ })+}diff --git a/libs/fleet/tests/auth-analytics.test.ts b/libs/fleet/tests/auth-analytics.test.tsindex 6e2fa6815e..0c3a9cd196 100644--- a/libs/fleet/tests/auth-analytics.test.ts+++ b/libs/fleet/tests/auth-analytics.test.ts@@ -1,6 +1,7 @@import assert from "node:assert/strict"import test from "node:test"-import { recordFleetLogin } from "../src/auth/analytics.ts"+import { bindFleetAttribution, recordFleetLogin } 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 () => {const stored = new Map<string, string>()@@ -40,3 +41,50 @@ test("analytics failure does not mark the session as recorded", async () => {await assert.rejects(recordFleetLogin("session-2", dependencies))assert.equal(stored.size, 0)})++test("binds validated first-touch attribution after authentication", async () => {+ const capturedAt = Date.now()+ const stored = new Map<string, string>([[ATTRIBUTION_STORAGE_KEY, JSON.stringify({+ version: 1,+ capturedAt,+ values: { utm_source: "x", utm_medium: "organic-social", utm_campaign: "openclaw-2-launch" },+ })]])+ const calls: Array<{ input: string; init?: RequestInit }> = []+ await bindFleetAttribution({+ 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),+ removeItem: key => stored.delete(key),+ },+ })++ assert.equal(calls.length, 1)+ assert.equal(calls[0]?.input, "/api/analytics/attribution")+ assert.equal((calls[0]?.init?.headers as Record<string, string>).Authorization, "Bearer token-1")+ assert.deepEqual(JSON.parse(String(calls[0]?.init?.body)), {+ version: 1,+ capturedAt,+ values: { utm_source: "x", utm_medium: "organic-social", utm_campaign: "openclaw-2-launch" },+ })+ assert.equal(stored.has(ATTRIBUTION_STORAGE_KEY), false)+})++test("retains attribution when authenticated binding fails", async () => {+ const record = JSON.stringify({ version: 1, capturedAt: Date.now(), values: { utm_source: "x" } })+ const stored = new Map<string, string>([[ATTRIBUTION_STORAGE_KEY, record]])+ await assert.rejects(bindFleetAttribution({+ getToken: async () => "token-1",+ fetch: async () => new Response(null, { status: 503 }),+ storage: {+ getItem: key => stored.get(key) ?? null,+ setItem: (key, value) => stored.set(key, value),+ removeItem: key => stored.delete(key),+ },+ }))+ assert.equal(stored.get(ATTRIBUTION_STORAGE_KEY), record)+})diff --git a/libs/fleet/tests/fleet-attribution-doc.test.mjs b/libs/fleet/tests/fleet-attribution-doc.test.mjsindex 07c9366759..18c776997d 100644--- a/libs/fleet/tests/fleet-attribution-doc.test.mjs+++ b/libs/fleet/tests/fleet-attribution-doc.test.mjs@@ -9,5 +9,7 @@ test("public contract is channel-neutral and says unknown query keys are ignoredassert.match(contract, /utm_source=x.*utm_medium=paid-social/s)assert.match(contract, /unknown query keys are ignored/i)assert.match(contract, /pixels.*optional downstream adapters/i)+ assert.match(contract, /keyed-HMAC pseudonym/i)+ assert.match(contract, /internal and unknown identities are discarded/i)assert.doesNotMatch(contract, /Unknown keys.*rejected/i)})