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.

Public Fleet attribution Phase 1 contract (#7271)

Francesco Bonacci1b1a0122aaa7
diff --git a/libs/fleet/backend/handlers/attribution.go b/libs/fleet/backend/handlers/attribution.go
new file mode 100644
index 0000000000..1fa105afa3
--- /dev/null
+++ b/libs/fleet/backend/handlers/attribution.go
@@ -0,0 +1,92 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+ "strings"
+)
+
+const FleetClaimHeader = "X-Cua-Fleet-Claim"
+
+type AttributionFactsReader interface {
+ ReadBoundClaim(context.Context, string, string) (BoundClaim, error)
+ PoolExists(context.Context, string, string) (bool, error)
+}
+
+func QualifySvcRequest(ctx context.Context, r *http.Request, status int, reader AttributionFactsReader) bool {
+ upgrade := isUpgradeRequest(r)
+ if reader == nil || r.Pattern == "" || !strings.HasPrefix(r.Pattern, "/api/svc/") || r.Method == "HEAD" || r.Method == "OPTIONS" || upgrade {
+ return false
+ }
+ claim := r.Header.Get(FleetClaimHeader)
+ if claim == "" || len(r.Header.Values(FleetClaimHeader)) != 1 || len(claim) > 128 || !validAttributionClaim(claim) {
+ return false
+ }
+ 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
+ }
+ pool, err := reader.PoolExists(ctx, ns, ns)
+ if err != nil || !pool || status < 200 || status >= 300 {
+ return false
+ }
+ 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})
+}
+
+func isUpgradeRequest(r *http.Request) bool {
+ if r.Header.Get("Upgrade") != "" {
+ return true
+ }
+ for _, value := range r.Header.Values("Connection") {
+ for _, token := range strings.Split(value, ",") {
+ if strings.EqualFold(strings.TrimSpace(token), "upgrade") {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func validAttributionClaim(value string) bool {
+ 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
+}
+
+// BoundClaim is the exact claim correlation supplied by the SDK.
+type BoundClaim struct {
+ Claim, Sandbox string
+ Bound bool
+}
+
+// AttributionFacts contains already-proven facts; qualification performs no I/O.
+type AttributionFacts struct {
+ AuthenticatedNamespace bool
+ SDKClaim string
+ Claim BoundClaim
+ Service, Namespace, Route, Path, Method string
+ NamespacePoolExists bool
+ UpstreamStatus int
+ Upgrade bool
+}
+
+// QualifiesFleetAttribution is a pure Phase 1 predicate, not an activation claim.
+func QualifiesFleetAttribution(f AttributionFacts) bool {
+ if !f.AuthenticatedNamespace || f.SDKClaim == "" || !f.Claim.Bound || f.Claim.Claim == "" || f.Claim.Claim != f.SDKClaim || f.Claim.Sandbox == "" || f.Service != f.Claim.Sandbox+"-server" || !f.NamespacePoolExists || f.UpstreamStatus < 200 || f.UpstreamStatus >= 300 || f.Upgrade || f.Method == "HEAD" || f.Method == "OPTIONS" {
+ return false
+ }
+ if f.Route == "/api/k8s" || f.Route == "/api/orch" || !strings.HasPrefix(f.Route, "/api/svc/") {
+ return false
+ }
+ probes := map[string]struct{}{"health": {}, "healthz": {}, "ready": {}, "readiness": {}, "readyz": {}, "live": {}, "liveness": {}, "livez": {}, "metrics": {}}
+ for _, segment := range strings.Split(strings.ToLower(strings.Trim(f.Path, "/")), "/") {
+ if _, excluded := probes[segment]; excluded {
+ return false
+ }
+ }
+ return true
+}
diff --git a/libs/fleet/backend/handlers/attribution_test.go b/libs/fleet/backend/handlers/attribution_test.go
new file mode 100644
index 0000000000..566f4ecc59
--- /dev/null
+++ b/libs/fleet/backend/handlers/attribution_test.go
@@ -0,0 +1,122 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+type fakeAttributionFactsReader struct {
+ claim BoundClaim
+ pool bool
+ calls int
+}
+
+func (f *fakeAttributionFactsReader) ReadBoundClaim(context.Context, string, string) (BoundClaim, error) {
+ f.calls++
+ return f.claim, nil
+}
+func (f *fakeAttributionFactsReader) PoolExists(context.Context, string, string) (bool, error) {
+ f.calls++
+ return f.pool, nil
+}
+
+func TestQualifiesFleetAttribution(t *testing.T) {
+ base := AttributionFacts{AuthenticatedNamespace: true, SDKClaim: "claim-1", Claim: BoundClaim{Claim: "claim-1", Sandbox: "sandbox-1", Bound: true}, Service: "sandbox-1-server", NamespacePoolExists: true, UpstreamStatus: 200, Method: "GET", Route: "/api/svc/ns/svc", Path: "/v1/tools"}
+ cases := []struct {
+ name string
+ mutate func(*AttributionFacts)
+ want bool
+ }{
+ {"all conjuncts", func(*AttributionFacts) {}, true},
+ {"auth missing", func(f *AttributionFacts) { f.AuthenticatedNamespace = false }, false},
+ {"sdk claim missing", func(f *AttributionFacts) { f.SDKClaim = "" }, false},
+ {"claim mismatch", func(f *AttributionFacts) { f.Claim.Claim = "other" }, false},
+ {"not bound", func(f *AttributionFacts) { f.Claim.Bound = false }, false},
+ {"sandbox missing", func(f *AttributionFacts) { f.Claim.Sandbox = "" }, false},
+ {"service mismatch", func(f *AttributionFacts) { f.Service = "sandbox-1-mcp" }, false},
+ {"pool absent", func(f *AttributionFacts) { f.NamespacePoolExists = false }, false},
+ {"199", func(f *AttributionFacts) { f.UpstreamStatus = 199 }, false},
+ {"300", func(f *AttributionFacts) { f.UpstreamStatus = 300 }, false},
+ {"health probe", func(f *AttributionFacts) { f.Path = "/health" }, false},
+ {"readiness probe", func(f *AttributionFacts) { f.Path = "/ready" }, false},
+ {"metrics probe", func(f *AttributionFacts) { f.Path = "/metrics" }, false},
+ {"health descendant", func(f *AttributionFacts) { f.Path = "/health/details" }, false},
+ {"metrics descendant", func(f *AttributionFacts) { f.Path = "/metrics/prometheus" }, false},
+ {"readiness descendant", func(f *AttributionFacts) { f.Path = "/readiness/dependencies" }, false},
+ {"liveness descendant", func(f *AttributionFacts) { f.Path = "/liveness/details" }, false},
+ {"ordinary healthy word", func(f *AttributionFacts) { f.Path = "/healthy-recipes" }, true},
+ {"ordinary metrics word", func(f *AttributionFacts) { f.Path = "/metrics-report" }, true},
+ {"head", func(f *AttributionFacts) { f.Method = "HEAD" }, false},
+ {"options", func(f *AttributionFacts) { f.Method = "OPTIONS" }, false},
+ {"upgrade", func(f *AttributionFacts) { f.Upgrade = true }, false},
+ {"k8s route", func(f *AttributionFacts) { f.Route = "/api/k8s" }, false},
+ {"orch route", func(f *AttributionFacts) { f.Route = "/api/orch" }, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ f := base
+ tc.mutate(&f)
+ if got := QualifiesFleetAttribution(f); got != tc.want {
+ t.Fatalf("got %v want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestQualifySvcRequestUsesOnlyValidatedExactClaimAndSvcRoutes(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/tools", nil)
+ r.Pattern = "/api/svc/{namespace}/{service}/{path...}"
+ r.SetPathValue("namespace", "pool-1")
+ r.SetPathValue("service", "sandbox-1-server")
+ r.SetPathValue("path", "tools")
+ r.Header.Set(FleetClaimHeader, "claim-1")
+ if !QualifySvcRequest(r.Context(), r, 204, reader) {
+ t.Fatal("expected exact claim to qualify")
+ }
+
+ for _, mutate := range []func(*http.Request){
+ func(r *http.Request) { r.Header.Set(FleetClaimHeader, "bad claim") },
+ func(r *http.Request) { r.Header.Add(FleetClaimHeader, "claim-2") },
+ func(r *http.Request) { r.Pattern = "/api/k8s/{path...}" },
+ } {
+ before := reader.calls
+ candidate := r.Clone(r.Context())
+ candidate.Header = r.Header.Clone()
+ mutate(candidate)
+ if QualifySvcRequest(candidate.Context(), candidate, 204, reader) {
+ t.Fatal("unexpected qualification")
+ }
+ if reader.calls != before {
+ t.Fatal("invalid or non-svc request reached facts reader")
+ }
+ }
+ if QualifySvcRequest(r.Context(), r, 204, nil) {
+ t.Fatal("nil reader must be default-off")
+ }
+}
+
+func TestQualifySvcRequestRejectsUpgradeSignalsBeforeReadingFacts(t *testing.T) {
+ for _, headers := range []http.Header{
+ {"Upgrade": {"websocket"}},
+ {"Connection": {"keep-alive, Upgrade"}},
+ {"Connection": {"UPGRADE"}},
+ } {
+ 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/tools", nil)
+ r.Pattern = "/api/svc/{namespace}/{service}/{path...}"
+ r.SetPathValue("namespace", "pool-1")
+ r.SetPathValue("service", "sandbox-1-server")
+ r.SetPathValue("path", "tools")
+ r.Header = headers
+ r.Header.Set(FleetClaimHeader, "claim-1")
+ if QualifySvcRequest(r.Context(), r, 200, reader) {
+ t.Fatal("upgrade request qualified")
+ }
+ if reader.calls != 0 {
+ t.Fatal("upgrade request reached facts reader")
+ }
+ }
+}
diff --git a/libs/fleet/docs/fleet-attribution-phase1.md b/libs/fleet/docs/fleet-attribution-phase1.md
new file mode 100644
index 0000000000..f244306463
--- /dev/null
+++ b/libs/fleet/docs/fleet-attribution-phase1.md
@@ -0,0 +1,15 @@
+# Fleet Attribution Phase 1
+
+This public contract defines a deliberately default-off qualification seam.
+
+## Browser capture
+
+Before Keycloak bootstrap, the SPA captures first-touch values from the current URL: `campaign_id`, `content_id`, `utm_source`, `utm_medium`, and `utm_campaign`. Values use a conservative ASCII set (`A-Z`, `a-z`, `0-9`, `.`, `_`, `~`, `-`), are non-empty, and are at most 128 characters. The serialized version-1 record is limited to 2048 UTF-8 bytes and expires after 7 days. Unknown query keys are ignored; repeated allowed keys, malformed values, and oversized records are rejected. The first valid record is write-once in browser `sessionStorage` and is removed after a successful bind.
+
+The five stable fields are acquisition-channel neutral. They can represent email, SEO, partners, future channels, and organic or paid social traffic without provider-specific behavior. For example, both `utm_source=x&utm_medium=organic-social` and `utm_source=x&utm_medium=paid-social` are ordinary valid values. Provider SDKs, pixels, credentials, arbitrary provider payloads, and provider-specific success semantics are outside this contract. Pixels are optional downstream adapters and are not part of Phase 1.
+
+## 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.
+
+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/sdk-bindings/examples/kotlin/AppControlled.kt b/libs/fleet/sdk-bindings/examples/kotlin/AppControlled.kt
index 46ee2cb467..a7878a8bb2 100644
--- a/libs/fleet/sdk-bindings/examples/kotlin/AppControlled.kt
+++ b/libs/fleet/sdk-bindings/examples/kotlin/AppControlled.kt
@@ -24,7 +24,7 @@ private class ScriptedHttpClient : HttpClient {
Expected("POST", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), "{\"apiVersion\":\"osgym.cua.ai/v1alpha1\",\"kind\":\"OSGymSandboxClaim\",\"metadata\":{\"namespace\":\"default\",\"name\":\"claim-1\",\"labels\":null},\"spec\":{\"sandboxTemplateRef\":{\"name\":\"default\"},\"bindDeadline\":900},\"status\":null}".encodeToByteArray(), 201u, "{\"apiVersion\":\"osgym.cua.ai/v1alpha1\",\"kind\":\"OSGymSandboxClaim\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"sandboxTemplateRef\":{\"name\":\"default\"}},\"status\":{\"phase\":\"Bound\",\"sandbox\":{\"name\":\"offline-sandbox\"}}}"),
Expected("GET", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), null, 200u, "{\"apiVersion\":\"osgym.cua.ai/v1alpha1\",\"kind\":\"OSGymSandboxClaim\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"sandboxTemplateRef\":{\"name\":\"default\"}},\"status\":{\"phase\":\"Bound\",\"sandbox\":{\"name\":\"offline-sandbox\"}}}"),
Expected("GET", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxtemplates/default", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), null, 200u, "{\"apiVersion\":\"osgym.cua.ai/v1alpha1\",\"kind\":\"OSGymSandboxTemplate\",\"metadata\":{\"namespace\":\"default\",\"name\":\"default\",\"labels\":null},\"spec\":{\"vmTemplate\":{\"containerDiskImage\":\"registry.example/desktop:offline\",\"services\":[{\"name\":\"mcp\",\"targetPort\":8080}]}}}"),
- Expected("POST", "https://cyclops.invalid/api/svc/default/offline-sandbox-mcp/mcp", listOf("authorization" to "Bearer offline-token"), "{\"offline\":true}".encodeToByteArray(), 202u, "offline service accepted"),
+ Expected("POST", "https://cyclops.invalid/api/svc/default/offline-sandbox-mcp/mcp", listOf("X-Cua-Fleet-Claim" to "default", "authorization" to "Bearer offline-token"), "{\"offline\":true}".encodeToByteArray(), 202u, "offline service accepted"),
Expected("DELETE", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), null, 204u, ""),
Expected("DELETE", "https://cyclops.invalid/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxwarmpools/default", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), null, 204u, ""),
Expected("DELETE", "https://cyclops.invalid/api/namespaces/default", listOf("accept" to "application/json", "content-type" to "application/json", "authorization" to "Bearer offline-token"), null, 204u, "")
diff --git a/libs/fleet/sdk-bindings/examples/ruby/app_controlled.rb b/libs/fleet/sdk-bindings/examples/ruby/app_controlled.rb
index 766e8447eb..d496fbe2ad 100644
--- a/libs/fleet/sdk-bindings/examples/ruby/app_controlled.rb
+++ b/libs/fleet/sdk-bindings/examples/ruby/app_controlled.rb
@@ -21,7 +21,7 @@ def template_json; { apiVersion:'osgym.cua.ai/v1alpha1',kind:'OSGymSandboxTempla
def claim_json(bound=false); value={apiVersion:'osgym.cua.ai/v1alpha1',kind:'OSGymSandboxClaim',metadata:{namespace:'default',name:'default',labels:nil},spec:{sandboxTemplateRef:{name:'default'}},status:nil}; value[:status]={phase:'Bound',sandbox:{name:'offline-sandbox'}} if bound; value; end
def queue
pool_url="#{BASE}/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxwarmpools/default"; template_url="#{BASE}/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxtemplates/default"; claim_url="#{BASE}/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/default/osgymsandboxclaims/default"; pool_body=JSON.generate(pool_json).b; claim_body='{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxClaim","metadata":{"namespace":"default","name":"claim-1","labels":null},"spec":{"sandboxTemplateRef":{"name":"default"},"bindDeadline":900},"status":null}'.b
- [Expected.new('POST',TOKEN,[['accept','application/json'],['content-type','application/x-www-form-urlencoded'],['authorization','Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=']], 'grant_type=client_credentials'.b,200,{access_token:'offline-token',expires_in:3600}),Expected.new('POST',"#{BASE}/api/namespaces",JSON_HEADERS,'{"name":"default"}'.b,201,{}),Expected.new('POST',pool_url.sub(%r{/default\z}, ''),JSON_HEADERS,pool_body,201,pool_json),Expected.new('POST',claim_url.sub(%r{/default\z}, ''),JSON_HEADERS,claim_body,201,claim_json),Expected.new('GET',claim_url,JSON_HEADERS,nil,200,claim_json(true)),Expected.new('GET',template_url,JSON_HEADERS,nil,200,template_json),Expected.new('POST',"#{BASE}/api/svc/default/offline-sandbox-mcp/mcp",[['authorization','Bearer offline-token']],'{"offline":true}'.b,202,'offline service accepted'),Expected.new('DELETE',claim_url,JSON_HEADERS,nil,204,''),Expected.new('DELETE',pool_url,JSON_HEADERS,nil,204,''),Expected.new('DELETE',"#{BASE}/api/namespaces/default",JSON_HEADERS,nil,204,'')]
+ [Expected.new('POST',TOKEN,[['accept','application/json'],['content-type','application/x-www-form-urlencoded'],['authorization','Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=']], 'grant_type=client_credentials'.b,200,{access_token:'offline-token',expires_in:3600}),Expected.new('POST',"#{BASE}/api/namespaces",JSON_HEADERS,'{"name":"default"}'.b,201,{}),Expected.new('POST',pool_url.sub(%r{/default\z}, ''),JSON_HEADERS,pool_body,201,pool_json),Expected.new('POST',claim_url.sub(%r{/default\z}, ''),JSON_HEADERS,claim_body,201,claim_json),Expected.new('GET',claim_url,JSON_HEADERS,nil,200,claim_json(true)),Expected.new('GET',template_url,JSON_HEADERS,nil,200,template_json),Expected.new('POST',"#{BASE}/api/svc/default/offline-sandbox-mcp/mcp",[['X-Cua-Fleet-Claim','default'],['authorization','Bearer offline-token']],'{"offline":true}'.b,202,'offline service accepted'),Expected.new('DELETE',claim_url,JSON_HEADERS,nil,204,''),Expected.new('DELETE',pool_url,JSON_HEADERS,nil,204,''),Expected.new('DELETE',"#{BASE}/api/namespaces/default",JSON_HEADERS,nil,204,'')]
end
class ScriptedHttpClient < FleetSdk::HttpClient
diff --git a/libs/fleet/sdk-bindings/kotlin/tests/TestAsyncClient.kt b/libs/fleet/sdk-bindings/kotlin/tests/TestAsyncClient.kt
index 8d73711b31..1628e41118 100644
--- a/libs/fleet/sdk-bindings/kotlin/tests/TestAsyncClient.kt
+++ b/libs/fleet/sdk-bindings/kotlin/tests/TestAsyncClient.kt
@@ -52,7 +52,7 @@ private fun tokenExpected() = textExpected(
private fun serviceExpected(body: ByteArray?, response: ByteArray) = Expected(
"POST",
"https://cyclops.invalid/api/svc/default/offline-sandbox-mcp/mcp",
- listOf("authorization" to "Bearer offline-token"),
+ listOf("X-Cua-Fleet-Claim" to "default", "authorization" to "Bearer offline-token"),
body,
202u,
response,
diff --git a/libs/fleet/sdk-bindings/python/contract_fixture.py b/libs/fleet/sdk-bindings/python/contract_fixture.py
index e112ed1240..7562ab7c72 100644
--- a/libs/fleet/sdk-bindings/python/contract_fixture.py
+++ b/libs/fleet/sdk-bindings/python/contract_fixture.py
@@ -10,7 +10,7 @@ from fleet_sdk import (ClaimSpec, CreateClaimRequest, CreatePoolRequest, Cyclops
BASE = 'https://cyclops.invalid'
TOKEN = 'https://keycloak.invalid/realms/offline/protocol/openid-connect/token'
JSON_HEADERS = [('accept', 'application/json'), ('content-type', 'application/json'), ('authorization', 'Bearer offline-token')]
-SERVICE_HEADERS = [('authorization', 'Bearer offline-token')]
+SERVICE_HEADERS = [('X-Cua-Fleet-Claim', 'default'), ('authorization', 'Bearer offline-token')]
SERVICE_URL = f'{BASE}/api/svc/default/offline-sandbox-mcp/mcp'
@dataclass(frozen=True)
diff --git a/libs/fleet/sdk-bindings/ruby/tests/test_async_client.rb b/libs/fleet/sdk-bindings/ruby/tests/test_async_client.rb
index 8c9a8becc8..7eee3680e2 100644
--- a/libs/fleet/sdk-bindings/ruby/tests/test_async_client.rb
+++ b/libs/fleet/sdk-bindings/ruby/tests/test_async_client.rb
@@ -36,7 +36,7 @@ def token_expected
end
def service_expected(body, response)
- Expected.new('POST', "#{BASE}/api/svc/default/offline-sandbox-mcp/mcp", [['authorization', 'Bearer offline-token']], body, 202, response)
+ Expected.new('POST', "#{BASE}/api/svc/default/offline-sandbox-mcp/mcp", [['X-Cua-Fleet-Claim', 'default'], ['authorization', 'Bearer offline-token']], body, 202, response)
end
def lifecycle_queue
diff --git a/libs/fleet/sdk-bindings/swift/tests/TestAsyncClient.swift b/libs/fleet/sdk-bindings/swift/tests/TestAsyncClient.swift
index dd536c0f2d..f3ae63b1ef 100644
--- a/libs/fleet/sdk-bindings/swift/tests/TestAsyncClient.swift
+++ b/libs/fleet/sdk-bindings/swift/tests/TestAsyncClient.swift
@@ -34,7 +34,7 @@ private func serviceExpected(body: Data?, response: Data) -> Expected {
Expected(
method: "POST",
url: "https://cyclops.invalid/api/svc/default/offline-sandbox-mcp/mcp",
- headers: [HttpHeader(name: "authorization", value: "Bearer offline-token")],
+ headers: [HttpHeader(name: "X-Cua-Fleet-Claim", value: "default"), HttpHeader(name: "authorization", value: "Bearer offline-token")],
body: body,
status: 202,
response: response
diff --git a/libs/fleet/sdk/src/services.rs b/libs/fleet/sdk/src/services.rs
index d33f7ec275..c3d0f533f7 100644
--- a/libs/fleet/sdk/src/services.rs
+++ b/libs/fleet/sdk/src/services.rs
@@ -27,7 +27,7 @@ impl CyclopsClient {
let request = HttpRequest {
method: request.method,
url: url.to_string(),
- headers: filtered_headers(request.headers),
+ headers: fleet_headers(filtered_headers(request.headers), &sandbox.claim),
body: request.body,
timeout_secs: request.timeout_secs,
};
@@ -35,6 +35,22 @@ impl CyclopsClient {
}
}
+fn fleet_headers(mut headers: Vec<HttpHeader>, claim: &str) -> Vec<HttpHeader> {
+ // Correlation is the exact claim returned in Sandbox; it is never inferred.
+ if !claim.is_empty()
+ && claim.len() <= 128
+ && claim
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b"._~-".contains(&b))
+ {
+ headers.push(HttpHeader {
+ name: "X-Cua-Fleet-Claim".into(),
+ value: claim.into(),
+ });
+ }
+ headers
+}
+
fn filtered_headers(headers: Vec<HttpHeader>) -> Vec<HttpHeader> {
let mut blocked: HashSet<String> = [
"connection",
@@ -48,6 +64,7 @@ fn filtered_headers(headers: Vec<HttpHeader>) -> Vec<HttpHeader> {
"transfer-encoding",
"upgrade",
"authorization",
+ "x-cua-fleet-claim",
]
.into_iter()
.map(str::to_owned)
diff --git a/libs/fleet/sdk/tests/service_flow.rs b/libs/fleet/sdk/tests/service_flow.rs
index 5362700cc6..47a2d1bfa7 100644
--- a/libs/fleet/sdk/tests/service_flow.rs
+++ b/libs/fleet/sdk/tests/service_flow.rs
@@ -36,6 +36,12 @@ async fn routes_known_service_under_base_prefix_and_forwards_query() {
"https://cyclops.example:8443/control/api/svc/pool-test/sandbox-1-mcp/tools?cursor=next"
);
assert_eq!(requests[1].method, "PATCH");
+ assert!(
+ requests[1]
+ .headers
+ .iter()
+ .any(|h| h.name == "X-Cua-Fleet-Claim" && h.value == "claim-1")
+ );
}
#[tokio::test]
@@ -203,6 +209,7 @@ async fn filters_hop_by_hop_and_connection_nominated_headers_without_reordering_
header("X-Keep", "first"),
header("x-keep", "second"),
header("Cookie", "session=kept"),
+ header("X-Cua-Fleet-Claim", "claim-1"),
header("authorization", "Bearer service-token"),
]
);
diff --git a/libs/fleet/src/auth/fleet-attribution.ts b/libs/fleet/src/auth/fleet-attribution.ts
new file mode 100644
index 0000000000..57a7e9a967
--- /dev/null
+++ b/libs/fleet/src/auth/fleet-attribution.ts
@@ -0,0 +1,57 @@
+export const ATTRIBUTION_STORAGE_KEY = "cua.fleet-attribution.v1"
+export const ATTRIBUTION_TTL_MS = 7 * 24 * 60 * 60 * 1000
+export const ATTRIBUTION_MAX_VALUE_LENGTH = 128
+export const ATTRIBUTION_MAX_RECORD_BYTES = 2048
+
+const allowedKeys = ["campaign_id", "content_id", "utm_source", "utm_medium", "utm_campaign"] as const
+type AttributionKey = (typeof allowedKeys)[number]
+export type AttributionRecord = { version: 1; capturedAt: number; values: Partial<Record<AttributionKey, string>> }
+export interface StorageLike { getItem(key: string): string | null; setItem(key: string, value: string): void; removeItem?(key: string): void }
+export interface AttributionBinder { bind(record: AttributionRecord, accessToken: string): Promise<void> | void }
+type Options = { storage?: StorageLike; now?: () => number; getAccessToken?: () => Promise<string | undefined> }
+
+const storageDefault = (): StorageLike | undefined => typeof window === "undefined" ? undefined : window.sessionStorage
+const validValue = (value: string) => value.length > 0 && value.length <= ATTRIBUTION_MAX_VALUE_LENGTH && /^[A-Za-z0-9._~-]+$/.test(value)
+const encode = (record: AttributionRecord) => JSON.stringify(record)
+
+export function captureFleetAttribution(href: string, options: Options = {}): void {
+ const storage = options.storage ?? storageDefault()
+ if (!storage || storage.getItem(ATTRIBUTION_STORAGE_KEY) !== null) return
+ let params: URLSearchParams
+ try { params = new URL(href).searchParams } catch { return }
+ const values: Partial<Record<AttributionKey, string>> = {}
+ for (const key of allowedKeys) {
+ const all = params.getAll(key)
+ if (all.length > 1 || (all.length === 1 && !validValue(all[0]!))) return
+ if (all.length === 1) values[key] = all[0]!
+ }
+ if (Object.keys(values).length === 0) return
+ const record: AttributionRecord = { version: 1, capturedAt: (options.now ?? Date.now)(), values }
+ const serialized = encode(record)
+ if (new TextEncoder().encode(serialized).length > ATTRIBUTION_MAX_RECORD_BYTES) return
+ try { storage.setItem(ATTRIBUTION_STORAGE_KEY, serialized) } catch { /* storage may be unavailable */ }
+}
+
+function readValid(storage: StorageLike, now: number): AttributionRecord | null {
+ const raw = storage.getItem(ATTRIBUTION_STORAGE_KEY)
+ if (!raw || new TextEncoder().encode(raw).length > ATTRIBUTION_MAX_RECORD_BYTES) return null
+ try {
+ const parsed = JSON.parse(raw) as AttributionRecord
+ if (parsed.version !== 1 || !Number.isFinite(parsed.capturedAt) || now - parsed.capturedAt < 0 || now - parsed.capturedAt >= ATTRIBUTION_TTL_MS) return null
+ const keys = Object.keys(parsed.values ?? {})
+ if (keys.length === 0 || keys.some(key => !allowedKeys.includes(key as AttributionKey))) return null
+ for (const key of keys) if (!validValue(parsed.values[key as AttributionKey] ?? "")) return null
+ return parsed
+ } catch { return null }
+}
+
+export async function bindStoredFleetAttribution(binder: AttributionBinder | undefined, options: Options = {}): Promise<void> {
+ const storage = options.storage ?? storageDefault()
+ if (!storage || !binder || !options.getAccessToken) return
+ const record = readValid(storage, (options.now ?? Date.now)())
+ if (!record) { storage.removeItem?.(ATTRIBUTION_STORAGE_KEY); return }
+ const accessToken = await options.getAccessToken()
+ if (!accessToken) return
+ await binder.bind(record, accessToken)
+ storage.removeItem?.(ATTRIBUTION_STORAGE_KEY)
+}
diff --git a/libs/fleet/src/main.tsx b/libs/fleet/src/main.tsx
index 7a7c72276d..e3294220b0 100644
--- a/libs/fleet/src/main.tsx
+++ b/libs/fleet/src/main.tsx
@@ -11,6 +11,10 @@ import { HelmetProvider } from "react-helmet-async"
import { App } from "./App"
import { AuthProvider } from "./auth/AuthProvider"
import "./shell.css"
+import { captureFleetAttribution } from "./auth/fleet-attribution"
+
+// Capture before React and Keycloak bootstrap so login-required preserves first touch.
+if (typeof window !== "undefined") captureFleetAttribution(window.location.href)
applyMode(Mode.Dark)
document.documentElement.classList.add("cua-dashboard-theme")
diff --git a/libs/fleet/tests/fleet-attribution-doc.test.mjs b/libs/fleet/tests/fleet-attribution-doc.test.mjs
new file mode 100644
index 0000000000..07c9366759
--- /dev/null
+++ b/libs/fleet/tests/fleet-attribution-doc.test.mjs
@@ -0,0 +1,13 @@
+import assert from "node:assert/strict"
+import { readFile } from "node:fs/promises"
+import test from "node:test"
+
+test("public contract is channel-neutral and says unknown query keys are ignored", async () => {
+ const contract = await readFile(new URL("../docs/fleet-attribution-phase1.md", import.meta.url), "utf8")
+ assert.match(contract, /acquisition-channel neutral/i)
+ assert.match(contract, /utm_source=x.*utm_medium=organic-social/s)
+ assert.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.doesNotMatch(contract, /Unknown keys.*rejected/i)
+})
diff --git a/libs/fleet/tests/fleet-attribution.test.ts b/libs/fleet/tests/fleet-attribution.test.ts
new file mode 100644
index 0000000000..1335e36ad1
--- /dev/null
+++ b/libs/fleet/tests/fleet-attribution.test.ts
@@ -0,0 +1,146 @@
+import assert from "node:assert/strict"
+import test from "node:test"
+import {
+ ATTRIBUTION_MAX_RECORD_BYTES,
+ ATTRIBUTION_MAX_VALUE_LENGTH,
+ ATTRIBUTION_STORAGE_KEY,
+ ATTRIBUTION_TTL_MS,
+ bindStoredFleetAttribution,
+ captureFleetAttribution,
+ type AttributionBinder,
+ type StorageLike,
+} from "../src/auth/fleet-attribution.ts"
+
+function memoryStorage(initial?: string): StorageLike & { values: Map<string, string> } {
+ const values = new Map<string, string>()
+ if (initial !== undefined) values.set(ATTRIBUTION_STORAGE_KEY, initial)
+ return {
+ values,
+ getItem: key => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, value),
+ removeItem: key => values.delete(key),
+ }
+}
+
+test("first touch survives a Keycloak round trip and only binds validated public fields", async () => {
+ const storage = memoryStorage()
+ const firstTouch = 1_700_000_000_000
+
+ captureFleetAttribution(
+ "https://run.example/pools?campaign_id=launch-1&content_id=docs.v2&utm_source=search&utm_medium=cpc&utm_campaign=fall&unknown=drop-me",
+ { storage, now: () => firstTouch },
+ )
+ captureFleetAttribution(
+ "https://run.example/pools?code=oidc-code&state=opaque&campaign_id=overwrite",
+ { storage, now: () => firstTouch + 1_000 },
+ )
+
+ const bound: unknown[] = []
+ const binder: AttributionBinder = {
+ bind: async record => {
+ bound.push(record)
+ },
+ }
+ await bindStoredFleetAttribution(binder, {
+ storage,
+ now: () => firstTouch + 2_000,
+ getAccessToken: async () => "access-token",
+ })
+
+ assert.deepEqual(bound, [
+ {
+ version: 1,
+ capturedAt: firstTouch,
+ values: {
+ campaign_id: "launch-1",
+ content_id: "docs.v2",
+ utm_source: "search",
+ utm_medium: "cpc",
+ utm_campaign: "fall",
+ },
+ },
+ ])
+})
+
+test("invalid, malformed, empty, oversized, and expired records never reach a binder", async () => {
+ const now = 1_700_000_000_000
+ const invalidStoredRecords = [
+ "not-json",
+ JSON.stringify({}),
+ JSON.stringify({ version: 1, capturedAt: now, values: {} }),
+ JSON.stringify({ version: 1, capturedAt: now, values: { campaign_id: "has space" } }),
+ JSON.stringify({ version: 1, capturedAt: now, values: { campaign_id: "x".repeat(ATTRIBUTION_MAX_VALUE_LENGTH + 1) } }),
+ JSON.stringify({ version: 1, capturedAt: now - ATTRIBUTION_TTL_MS, values: { campaign_id: "expired" } }),
+ "x".repeat(ATTRIBUTION_MAX_RECORD_BYTES + 1),
+ ]
+
+ for (const stored of invalidStoredRecords) {
+ const storage = memoryStorage(stored)
+ let calls = 0
+ await bindStoredFleetAttribution({ bind: async () => { calls += 1 } }, { storage, now: () => now, getAccessToken: async () => "access-token" })
+ assert.equal(calls, 0, stored.slice(0, 80))
+ assert.equal(storage.getItem(ATTRIBUTION_STORAGE_KEY), null)
+ }
+})
+
+test("capture rejects repeated, empty, invalid, and oversized values without truncation", () => {
+ const invalidQueries = [
+ "?campaign_id=",
+ "?campaign_id=one&campaign_id=two",
+ "?campaign_id=has%20space",
+ `?campaign_id=${"x".repeat(ATTRIBUTION_MAX_VALUE_LENGTH + 1)}`,
+ ]
+
+ for (const query of invalidQueries) {
+ const storage = memoryStorage()
+ captureFleetAttribution(`https://run.example/${query}`, { storage, now: () => 10 })
+ assert.equal(storage.values.size, 0, query)
+ }
+})
+
+test("capture accepts channel-neutral organic and paid social values without provider logic", () => {
+ for (const medium of ["organic-social", "paid-social"]) {
+ const storage = memoryStorage()
+ captureFleetAttribution(`https://run.example/?utm_source=x&utm_medium=${medium}`, {
+ storage,
+ now: () => 50,
+ })
+ const record = JSON.parse(storage.getItem(ATTRIBUTION_STORAGE_KEY) ?? "null")
+ assert.deepEqual(record.values, { utm_source: "x", utm_medium: medium })
+ }
+})
+
+test("TTL is valid immediately before the boundary and expired at the boundary", async () => {
+ const capturedAt = 1_000
+ const stored = JSON.stringify({
+ version: 1,
+ capturedAt,
+ values: { campaign_id: "boundary" },
+ })
+ let calls = 0
+ const binder: AttributionBinder = { bind: async () => { calls += 1 } }
+
+ await bindStoredFleetAttribution(binder, {
+ storage: memoryStorage(stored),
+ now: () => capturedAt + ATTRIBUTION_TTL_MS - 1,
+ getAccessToken: async () => "access-token",
+ })
+ await bindStoredFleetAttribution(binder, {
+ storage: memoryStorage(stored),
+ now: () => capturedAt + ATTRIBUTION_TTL_MS,
+ getAccessToken: async () => "access-token",
+ })
+
+ assert.equal(calls, 1)
+})
+
+test("the binder is disabled by default", async () => {
+ const storage = memoryStorage(JSON.stringify({
+ version: 1,
+ capturedAt: 100,
+ values: { utm_source: "docs" },
+ }))
+
+ await bindStoredFleetAttribution(undefined, { storage, now: () => 101 })
+ assert.notEqual(storage.getItem(ATTRIBUTION_STORAGE_KEY), null)
+})