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(auth): authorize tenant Image CRUD and gate mutations (#7749)
r33drichards7748b3ace755
diff --git a/libs/fleet/backend/auth/authz_k8s.rego b/libs/fleet/backend/auth/authz_k8s.regoindex b133480c75..bd65dfcb6a 100644--- a/libs/fleet/backend/auth/authz_k8s.rego+++ b/libs/fleet/backend/auth/authz_k8s.rego@@ -177,6 +177,44 @@ native_fleet_resources := {"osgymsandboxtemplates",}+k8s_request_allowed {+ parts := split(input.params.path, "/")+ image_request(parts)+}++image_request(parts) {+ apis_namespaced_group(parts, "images.cua.ai", "v1alpha1")+ authz.valid_dns_label(parts[4])+ parts[5] == "images"+ image_crud_shape(parts)+}++image_crud_shape(parts) {+ apis_collection(parts)+ input.method == "GET"+}++image_crud_shape(parts) {+ image_item(parts)+ input.method == "GET"+}++image_crud_shape(parts) {+ apis_collection(parts)+ input.method == "POST"+}++image_crud_shape(parts) {+ image_item(parts)+ {"PATCH", "DELETE"}[input.method]+}++image_item(parts) {+ apis_item(parts)+ count(parts[6]) <= 253+ regex.match(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`, parts[6])+}+k8s_request_allowed {parts := split(input.params.path, "/")apis_namespaced_group(parts, "osgym.cua.ai", "v1alpha1")@@ -589,6 +627,12 @@ is_infra_literal(path) {parts[3] == "tenants"}+github_k8s_request_allowed {+ parts := split(input.params.path, "/")+ image_request(parts)+ github_namespace_allowed(parts[4])+}+github_k8s_request_allowed {parts := split(input.params.path, "/")github_legacy_pool_request(parts)diff --git a/libs/fleet/backend/auth/authz_ownership.rego b/libs/fleet/backend/auth/authz_ownership.regoindex 0edfa2b0fd..5b818f6e67 100644--- a/libs/fleet/backend/auth/authz_ownership.rego+++ b/libs/fleet/backend/auth/authz_ownership.rego@@ -41,6 +41,21 @@ default probe_eligible = falsedefault rbac_allow = false+image_proxy_request {+ input.route == "/api/k8s/{path...}"+ parts := split(input.params.path, "/")+ count(parts) >= 6+ parts[0] == "apis"+ parts[1] == "images.cua.ai"+ parts[2] == "v1alpha1"+ parts[3] == "namespaces"+ parts[5] == "images"+}++applies {+ image_proxy_request+}+# ── Where the boundary applies ──────────────────────────────────────────────## These are exactly the remaining call sites requireNamespaceAccess had. The@@ -85,13 +100,20 @@ applies {# `not` in the second is false. Every rule below requires a non-empty namespace,# so the empty case denies rather than falling through to {name}.target_namespace = input.params.namespace {+ not image_proxy_requestinput.params.namespace}target_namespace = input.params.name {+ not image_proxy_requestnot input.params.namespace}+target_namespace = namespace {+ image_proxy_request+ namespace := split(input.params.path, "/")[4]+}+# ── The three cases ─────────────────────────────────────────────────────────# GitHub OIDC: the claim is the grant, and no probe could improve on it — thediff --git a/libs/fleet/backend/auth/custom_resource_creation_admission.rego b/libs/fleet/backend/auth/custom_resource_creation_admission.regoindex df59d37123..c9c8c88b49 100644--- a/libs/fleet/backend/auth/custom_resource_creation_admission.rego+++ b/libs/fleet/backend/auth/custom_resource_creation_admission.rego@@ -1,4 +1,4 @@-# Admission for direct creation of custom-resource instances through /api/k8s.+# Admission for custom-resource creation and Image rebuilds through /api/k8s.package custom_resource_creation_admissionimport data.authz@@ -17,6 +17,10 @@ custom_api_group(group) {group == "osgym.cua.ai"}+custom_api_group(group) {+ group == "images.cua.ai"+}+is_custom_resource_create {input.method == "POST"parts := split(input.params.path, "/")@@ -41,8 +45,22 @@ exempt {object.get(input.flags, "require_card_for_custom_resource_creation", false) != true}+is_image_patch {+ input.method == "PATCH"+ parts := split(input.params.path, "/")+ count(parts) == 7+ parts[0] == "apis"+ parts[1] == "images.cua.ai"+ parts[2] == "v1alpha1"+ parts[3] == "namespaces"+ parts[4] != ""+ parts[5] == "images"+ parts[6] != ""+}+exempt {not is_custom_resource_create+ not is_image_patch}exempt {diff --git a/libs/fleet/backend/auth/image_admission.rego b/libs/fleet/backend/auth/image_admission.regonew file mode 100644index 0000000000..4a567f54b3--- /dev/null+++ b/libs/fleet/backend/auth/image_admission.rego@@ -0,0 +1,44 @@+package image_admission++default allow = false++applies {+ input.route == "/api/k8s/{path...}"+ {"POST", "PUT", "PATCH"}[input.method]+ parts := split(input.params.path, "/")+ count(parts) >= 6+ parts[0] == "apis"+ parts[1] == "images.cua.ai"+ parts[2] == "v1alpha1"+ parts[3] == "namespaces"+ parts[5] == "images"+}++allow {+ not applies+}++allow {+ applies+ write_format_allowed+ request := json.unmarshal(input.body)+ is_object(request)+ object.keys(request) - {"apiVersion", "kind", "metadata", "spec"} == set()+ object.get(request, "apiVersion", "images.cua.ai/v1alpha1") == "images.cua.ai/v1alpha1"+ object.get(request, "kind", "Image") == "Image"+ metadata := object.get(request, "metadata", {})+ is_object(metadata)+ object.keys(metadata) - {"name", "namespace", "resourceVersion"} == set()+ namespace := split(input.params.path, "/")[4]+ object.get(metadata, "namespace", namespace) == namespace+ is_object(object.get(request, "spec", {}))+}++write_format_allowed {+ input.method == "POST"+}++write_format_allowed {+ input.method == "PATCH"+ input.content_types == ["application/merge-patch+json"]+}diff --git a/libs/fleet/backend/auth/middlewares.go b/libs/fleet/backend/auth/middlewares.goindex 1c70810ccf..2b81db0ad6 100644--- a/libs/fleet/backend/auth/middlewares.go+++ b/libs/fleet/backend/auth/middlewares.go@@ -59,6 +59,9 @@ var customResourceCreationAdmissionPolicy string//go:embed sandbox_services_admission.regovar sandboxServicesAdmissionPolicy string+//go:embed image_admission.rego+var imageAdmissionPolicy string+// authzOwnershipPolicy is the namespace-ownership boundary. Like// pool_admission.rego it is not a surface — it is a conjunct several surfaces// carry — so it is registered by name below rather than through@@ -390,6 +393,7 @@ func LoadOpa() {RegisterPolicyModule("pool-admission", "pool_admission.rego", poolAdmissionPolicy)RegisterPolicyModule("custom-resource-creation-admission", "custom_resource_creation_admission.rego", customResourceCreationAdmissionPolicy)RegisterPolicyModule("sandbox-services-admission", "sandbox_services_admission.rego", sandboxServicesAdmissionPolicy)+ RegisterPolicyModule("image-admission", "image_admission.rego", imageAdmissionPolicy)RegisterPolicyModule("authz-ownership", "authz_ownership.rego", authzOwnershipPolicy)for name, module := range surfacePolicySources {RegisterPolicyModule(name, module.filename, module.source)diff --git a/libs/fleet/backend/auth/ownership.go b/libs/fleet/backend/auth/ownership.goindex 241381c7e3..6778d890ec 100644--- a/libs/fleet/backend/auth/ownership.go+++ b/libs/fleet/backend/auth/ownership.go@@ -1,9 +1,12 @@package auth-import "context"+import (+ "context"+ "strings"+)// OwnedNamespace returns the namespace a request's ownership check is about:-// the {namespace} parameter where the route binds one, and {name} otherwise.+// the Image proxy path, {namespace} where the route binds one, or {name} otherwise.// It returns "" when the route names no namespace at all.//// This is the Go half of target_namespace in authz_ownership.rego. Two halves@@ -13,6 +16,12 @@ import "context"// function over the same parameter maps, so the two cannot drift apart quietly.func OwnedNamespace(ctx context.Context) string {params, _ := ctx.Value(paramsKey).(map[string]string)+ if route, _ := ctx.Value(routeKey).(string); route == "/api/k8s/{path...}" {+ parts := strings.Split(params["path"], "/")+ if len(parts) >= 6 && parts[0] == "apis" && parts[1] == "images.cua.ai" && parts[2] == "v1alpha1" && parts[3] == "namespaces" && parts[5] == "images" {+ return parts[4]+ }+ }if namespace, ok := params["namespace"]; ok {return namespace}diff --git a/libs/fleet/backend/auth/policy_images_test.go b/libs/fleet/backend/auth/policy_images_test.gonew file mode 100644index 0000000000..fae5ea0df4--- /dev/null+++ b/libs/fleet/backend/auth/policy_images_test.go@@ -0,0 +1,288 @@+package auth++import (+ "context"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func imagePolicyResponse(t *testing.T, method, path, body string, user *User) (*httptest.ResponseRecorder, bool) {+ t.Helper()+ contentType := "application/json"+ if method == http.MethodPatch {+ contentType = "application/merge-patch+json"+ }+ return imagePolicyResponseWithContentTypes(t, method, path, body, user, contentType)+}++func imagePolicyResponseWithContentTypes(t *testing.T, method, path, body string, user *User, contentTypes ...string) (*httptest.ResponseRecorder, bool) {+ t.Helper()+ reached := false+ mux := http.NewServeMux()+ mux.Handle("/api/k8s/{path...}", RouteContext("/api/k8s/{path...}")(PolicyMiddleware(K8sRoutePolicy(), WithPipeline())(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {+ reached = true+ forwarded, err := io.ReadAll(request.Body)+ if err != nil || string(forwarded) != body {+ t.Errorf("forwarded body = %q, %v; want %q", forwarded, err, body)+ }+ w.WriteHeader(http.StatusNoContent)+ }))))+ request := httptest.NewRequest(method, "/api/k8s/"+path, strings.NewReader(body))+ for _, contentType := range contentTypes {+ request.Header.Add("Content-Type", contentType)+ }+ request = request.WithContext(context.WithValue(request.Context(), UserKey, user))+ response := httptest.NewRecorder()+ mux.ServeHTTP(response, request)+ return response, reached+}++func TestImageTenantCRUD(t *testing.T) {+ t.Cleanup(resetFlagsCache)+ setCardAdmissionFlags(t, false)+ installCountingFacts(t, "tenant-a")+ for _, principal := range []struct {+ name string+ user *User+ }{+ {"interactive", &User{ID: "owner-a", AZP: "cyclops-cs-spa"}},+ {"cli", &User{ID: "owner-a", AZP: "cua-cli"}},+ {"desktop", &User{ID: "owner-a", AZP: "cua-desktop"}},+ {"user-key", &User{ID: "owner-a", AZP: "ukey-example", PrincipalType: PrincipalTypeUserKey}},+ {"github", &User{ID: "owner-a", PrincipalType: PrincipalTypeGitHubOIDC, AllowedNamespaces: []string{"tenant-a"}}},+ } {+ for _, operation := range []struct{ name, method, suffix, body string }{+ {"create", "POST", "", `{"apiVersion":"images.cua.ai/v1alpha1","kind":"Image","metadata":{"name":"image-a","namespace":"tenant-a"},"spec":{}}`},+ {"get", "GET", "/image-a", ""},+ {"list", "GET", "?limit=50&labelSelector=app%3Dbuilder", ""},+ {"watch", "GET", "?watch=true&resourceVersion=123", ""},+ {"update", "PATCH", "/image-a", `{"metadata":{"resourceVersion":"123"},"spec":{}}`},+ {"delete", "DELETE", "/image-a", ""},+ } {+ for _, namespace := range []string{"tenant-a", "tenant-b"} {+ t.Run(principal.name+"/"+operation.name+"/"+namespace, func(t *testing.T) {+ response, reached := imagePolicyResponse(t, operation.method, "apis/images.cua.ai/v1alpha1/namespaces/"+namespace+"/images"+operation.suffix, operation.body, principal.user)+ want := http.StatusForbidden+ if namespace == "tenant-a" {+ want = http.StatusNoContent+ }+ if response.Code != want || reached != (want == http.StatusNoContent) {+ t.Fatalf("status=%d reached=%v, want %d; %s", response.Code, reached, want, response.Body.String())+ }+ })+ }+ }+ }+}++func TestImageMutationBillingAdmission(t *testing.T) {+ t.Cleanup(resetFlagsCache)+ setCardAdmissionFlags(t, true)+ installCountingFacts(t, "tenant-a")+ stripe := &countingAdmissionFacts{cacheKey: StripeCardsFactProvider}+ installAdmissionFacts(t, StripeCardsFactProvider, stripe)+ installAdmissionFacts(t, CurrentYearFactProvider, &countingAdmissionFacts{cacheKey: CurrentYearFactProvider, facts: FactSet{"current_year": 2026}})+ installAdmissionFacts(t, CurrentMonthFactProvider, &countingAdmissionFacts{cacheKey: CurrentMonthFactProvider, facts: FactSet{"current_month": 9}})+ for _, principal := range []struct {+ name string+ user *User+ }{+ {"user", &User{ID: "owner-a", AZP: "cua-cli"}},+ {"github", &User{ID: "owner-a", PrincipalType: PrincipalTypeGitHubOIDC, AllowedNamespaces: []string{"tenant-a"}}},+ } {+ for _, hasCard := range []bool{false, true} {+ for _, operation := range []struct{ name, method, suffix, body string }{+ {"create", "POST", "", `{"metadata":{"name":"image-a"},"spec":{}}`},+ {"replace", "PUT", "/image-a", `{"metadata":{"name":"image-a","resourceVersion":"123"},"spec":{}}`},+ {"patch-spec", "PATCH", "/image-a", `{"spec":{"recipe":{"steps":["new-build"]}}}`},+ {"patch-metadata", "PATCH", "/image-a", `{"metadata":{"resourceVersion":"123"}}`},+ {"patch-create", "PATCH", "/new-image?fieldManager=kopf", `{"metadata":{"name":"new-image"},"spec":{}}`},+ {"get", "GET", "/image-a", ""},+ {"list", "GET", "", ""},+ {"delete", "DELETE", "/image-a", ""},+ } {+ cardState := "no-card"+ if hasCard {+ cardState = "card"+ }+ t.Run(principal.name+"/"+cardState+"/"+operation.name, func(t *testing.T) {+ stripe.facts = FactSet{"cards": []map[string]any{}}+ if hasCard {+ stripe.facts = FactSet{"cards": []map[string]any{{"exp_year": 2027, "exp_month": 1}}}+ }+ before := stripe.loads.Load()+ response, reached := imagePolicyResponse(t, operation.method, "apis/images.cua.ai/v1alpha1/namespaces/tenant-a/images"+operation.suffix, operation.body, principal.user)+ billed := operation.method == "POST" || operation.method == "PATCH"+ wantStatus, wantLoads := http.StatusNoContent, int64(0)+ if billed {+ wantLoads = 1+ }+ if operation.method == "PUT" || (billed && !hasCard) {+ wantStatus = http.StatusForbidden+ }+ if response.Code != wantStatus || reached != (wantStatus == http.StatusNoContent) || stripe.loads.Load()-before != wantLoads {+ t.Fatalf("status=%d reached=%v billing loads=%d, want %d loads=%d; %s", response.Code, reached, stripe.loads.Load()-before, wantStatus, wantLoads, response.Body.String())+ }+ })+ }+ }+ }+}++func TestImagePatchPreservesControllerMetadata(t *testing.T) {+ t.Cleanup(resetFlagsCache)+ setCardAdmissionFlags(t, false, "admin")+ installCountingFacts(t, "tenant-a")+ user := &User{ID: "admin", AZP: "cua-cli"}+ const collection = "apis/images.cua.ai/v1alpha1/namespaces/tenant-a/images"+ for _, body := range []string{+ `{"metadata":{"finalizers":[]}}`,+ `{"metadata":{"finalizers":null}}`,+ `{"metadata":{"finalizers":["attacker.example/finalizer"]}}`,+ `{"metadata":{"ownerReferences":[]}}`,+ `{"metadata":{"ownerReferences":null}}`,+ `{"metadata":{"managedFields":[]}}`,+ `{"metadata":{"managedFields":null}}`,+ `{"metadata":{"deletionTimestamp":null}}`,+ `{"metadata":{"uid":"forged"}}`,+ `{"metadata":{"generation":123}}`,+ `{"metadata":{"annotations":{"images.cua.ai/review":"caller-controlled"}}}`,+ `{"metadata":{"annotations":null}}`,+ `{"metadata":{"labels":null}}`,+ `{"metadata":null}`,+ } {+ for _, method := range []string{"POST", "PATCH"} {+ t.Run(method+"/"+body, func(t *testing.T) {+ path := collection+ if method == "PATCH" {+ path += "/image-a"+ }+ response, reached := imagePolicyResponse(t, method, path, body, user)+ if response.Code != http.StatusForbidden || reached {+ t.Fatalf("status=%d reached=%v; %s", response.Code, reached, response.Body.String())+ }+ })+ }+ }+ for _, body := range []string{+ `{"spec":{}}`,+ `{"metadata":{"name":"image-a","resourceVersion":"123"},"spec":{}}`,+ } {+ response, reached := imagePolicyResponse(t, "PUT", collection+"/image-a", body, user)+ if response.Code != http.StatusForbidden || reached {+ t.Errorf("PUT %s: status=%d reached=%v", body, response.Code, reached)+ }+ }+ response, reached := imagePolicyResponse(t, "PATCH", collection+"/image-a?fieldManager=kopf", `{"metadata":{"name":"image-a","namespace":"tenant-a","resourceVersion":"123"},"spec":{}}`, user)+ if response.Code != http.StatusNoContent || !reached {+ t.Fatalf("safe merge patch: status=%d reached=%v; %s", response.Code, reached, response.Body.String())+ }+}++func TestImagePatchRequiresExactMergePatchMediaType(t *testing.T) {+ t.Cleanup(resetFlagsCache)+ setCardAdmissionFlags(t, false, "admin")+ installCountingFacts(t, "tenant-a")+ for _, contentTypes := range [][]string{+ nil,+ {""},+ {"application/json"},+ {"application/json-patch+json"},+ {"application/strategic-merge-patch+json"},+ {"application/apply-patch+yaml"},+ {"application/apply-patch+cbor"},+ {"application/merge-patch+json; charset=utf-8"},+ {"application/merge-patch+json", "application/apply-patch+yaml"},+ {"application/apply-patch+yaml", "application/merge-patch+json"},+ {"application/merge-patch+json, application/apply-patch+yaml"},+ } {+ t.Run(strings.Join(contentTypes, ","), func(t *testing.T) {+ response, reached := imagePolicyResponseWithContentTypes(t, "PATCH", "apis/images.cua.ai/v1alpha1/namespaces/tenant-a/images/image-a?fieldManager=kopf&force=true", `{"apiVersion":"images.cua.ai/v1alpha1","kind":"Image","metadata":{"name":"image-a"},"spec":{}}`, &User{ID: "admin", AZP: "cua-cli"}, contentTypes...)+ if response.Code != http.StatusForbidden || reached {+ t.Fatalf("status=%d reached=%v; %s", response.Code, reached, response.Body.String())+ }+ })+ }+}++func TestImagePolicyBoundaries(t *testing.T) {+ t.Cleanup(resetFlagsCache)+ setCardAdmissionFlags(t, false, "admin")+ facts := installCountingFacts(t, "tenant-a")+ const collection = "apis/images.cua.ai/v1alpha1/namespaces/tenant-a/images"+ for _, testCase := range []struct{ name, method, path, body string }{+ {"cluster-list", "GET", "apis/images.cua.ai/v1alpha1/images", ""},+ {"wrong-version", "GET", "apis/images.cua.ai/v1/namespaces/tenant-a/images", ""},+ {"wrong-group", "GET", "apis/images.cua.ai.evil/v1alpha1/namespaces/tenant-a/images", ""},+ {"wrong-resource", "GET", collection + "builds", ""},+ {"delete-collection", "DELETE", collection, ""},+ {"patch-collection", "PATCH", collection, `{}`},+ {"put-collection", "PUT", collection, `{}`},+ {"post-item", "POST", collection + "/image-a", `{}`},+ {"status-read", "GET", collection + "/image-a/status", ""},+ {"status-patch", "PATCH", collection + "/image-a/status", `{"status":{}}`},+ {"status-put", "PUT", collection + "/image-a/status", `{"status":{}}`},+ {"encoded-status", "PATCH", collection + "/image-a%2Fstatus", `{}`},+ {"encoded-parent", "GET", collection + "/%2e%2e", ""},+ {"encoded-dot", "GET", collection + "/%2e", ""},+ {"trailing-slash", "GET", collection + "/", ""},+ {"encoded-cross-namespace", "GET", "apis/images.cua.ai/v1alpha1/namespaces/tenant-b%2Fimages/images", ""},+ {"finalizers", "PATCH", collection + "/image-a/finalizers", `{}`},+ {"create-status", "POST", collection, `{"spec":{},"status":{"phase":"Ready"}}`},+ {"patch-status", "PATCH", collection + "/image-a", `{"status":{"phase":"Ready"}}`},+ {"put-status", "PUT", collection + "/image-a", `{"spec":{},"status":{}}`},+ {"namespace-mismatch", "PATCH", collection + "/image-a", `{"metadata":{"namespace":"tenant-b"}}`},+ {"wrong-kind", "POST", collection, `{"kind":"Pod","spec":{}}`},+ {"wrong-api-version", "POST", collection, `{"apiVersion":"v1","spec":{}}`},+ {"unknown-root", "PATCH", collection + "/image-a", `{"data":{}}`},+ {"invalid-spec-shape", "PATCH", collection + "/image-a", `{"spec":[]}`},+ {"malformed-json", "POST", collection, `{`},+ {"json-patch-status", "PATCH", collection + "/image-a", `[{"op":"add","path":"/status","value":{}}]`},+ {"secrets", "GET", "api/v1/namespaces/tenant-a/secrets", ""},+ {"jobs", "POST", "apis/batch/v1/namespaces/tenant-a/jobs", `{}`},+ {"pvc", "POST", "api/v1/namespaces/tenant-a/persistentvolumeclaims", `{}`},+ {"snapshot", "DELETE", "apis/snapshot.storage.k8s.io/v1/namespaces/tenant-a/volumesnapshots/snapshot-a", ""},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ response, reached := imagePolicyResponse(t, testCase.method, testCase.path, testCase.body, &User{ID: "admin", AZP: "cyclops-cs-spa"})+ if response.Code != http.StatusForbidden || reached {+ t.Fatalf("status=%d reached=%v; %s", response.Code, reached, response.Body.String())+ }+ })+ }+ for _, user := range []*User{nil, {AZP: "cyclops-cs-spa"}, {ID: "owner-a", AZP: "key-tenant-a", Namespace: "tenant-a"}, {ID: "owner-a", AZP: "unrelated"}} {+ response, reached := imagePolicyResponse(t, "GET", collection, "", user)+ if response.Code != http.StatusForbidden || reached {+ t.Fatalf("principal %+v: status=%d reached=%v", user, response.Code, reached)+ }+ }+ facts.unreachable = "tenant-a"+ response, reached := imagePolicyResponse(t, "GET", collection, "", &User{ID: "owner-a", AZP: "cua-cli"})+ if response.Code < 500 || reached {+ t.Fatalf("unavailable ownership: status=%d reached=%v", response.Code, reached)+ }+}++func TestImageCreationRequiresBillingAdmission(t *testing.T) {+ t.Cleanup(resetFlagsCache)+ setCardAdmissionFlags(t, true)+ installCountingFacts(t, "tenant-a")+ stripe := &countingAdmissionFacts{cacheKey: StripeCardsFactProvider, facts: FactSet{"cards": []map[string]any{}}}+ installAdmissionFacts(t, StripeCardsFactProvider, stripe)+ installAdmissionFacts(t, CurrentYearFactProvider, &countingAdmissionFacts{cacheKey: CurrentYearFactProvider, facts: FactSet{"current_year": 2026}})+ installAdmissionFacts(t, CurrentMonthFactProvider, &countingAdmissionFacts{cacheKey: CurrentMonthFactProvider, facts: FactSet{"current_month": 9}})+ const path = "apis/images.cua.ai/v1alpha1/namespaces/tenant-a/images"+ user := &User{ID: "owner-a", AZP: "cua-cli"}+ response, reached := imagePolicyResponse(t, "POST", path, `{"spec":{}}`, user)+ if response.Code != http.StatusForbidden || reached || stripe.loads.Load() != 1 {+ t.Fatalf("without card: status=%d reached=%v stripe loads=%d", response.Code, reached, stripe.loads.Load())+ }+ stripe.facts = FactSet{"cards": []map[string]any{{"exp_year": 2027, "exp_month": 1}}}+ response, reached = imagePolicyResponse(t, "POST", path, `{"spec":{}}`, user)+ if response.Code != http.StatusNoContent || !reached {+ t.Fatalf("with card: status=%d reached=%v; %s", response.Code, reached, response.Body.String())+ }+}diff --git a/libs/fleet/backend/auth/policy_middleware.go b/libs/fleet/backend/auth/policy_middleware.goindex 50d68f8ed8..502ce5d90b 100644--- a/libs/fleet/backend/auth/policy_middleware.go+++ b/libs/fleet/backend/auth/policy_middleware.go@@ -242,12 +242,13 @@ func newRequestPolicyInput(request *http.Request, bodyBudget int64) *requestPolibodyBudget: bodyBudget,factCache: map[string]cachedFacts{},base: map[string]any{- "method": request.Method,- "path": request.URL.Path,- "route": route,- "params": params,- "user": buildUserInput(user),- "flags": authorizationFlags(request.Context()),+ "content_types": request.Header.Values("Content-Type"),+ "method": request.Method,+ "path": request.URL.Path,+ "route": route,+ "params": params,+ "user": buildUserInput(user),+ "flags": authorizationFlags(request.Context()),},}}diff --git a/libs/fleet/backend/auth/policy_ownership_test.go b/libs/fleet/backend/auth/policy_ownership_test.goindex cfd44308b3..81f7758bef 100644--- a/libs/fleet/backend/auth/policy_ownership_test.go+++ b/libs/fleet/backend/auth/policy_ownership_test.go@@ -354,6 +354,7 @@ func TestOwnedNamespaceMatchesRego(t *testing.T) {name stringparams map[string]stringwant string+ route string}{{name: "svc namespace", params: map[string]string{"namespace": "ns-a", "service": "svc-a"}, want: "ns-a"},{name: "namespaces name", params: map[string]string{"name": "ns-b"}, want: "ns-b"},@@ -361,14 +362,20 @@ func TestOwnedNamespaceMatchesRego(t *testing.T) {{name: "empty name stays empty", params: map[string]string{"name": ""}, want: ""},{name: "namespace wins over name", params: map[string]string{"namespace": "ns-a", "name": "ns-z"}, want: "ns-a"},{name: "no namespace parameter at all", params: map[string]string{"path": "x"}, want: ""},+ {name: "image collection", route: "/api/k8s/{path...}", params: map[string]string{"path": "apis/images.cua.ai/v1alpha1/namespaces/ns-a/images"}, want: "ns-a"},+ {name: "image item", route: "/api/k8s/{path...}", params: map[string]string{"path": "apis/images.cua.ai/v1alpha1/namespaces/ns-b/images/image-a"}, want: "ns-b"},+ {name: "image path wins", route: "/api/k8s/{path...}", params: map[string]string{"path": "apis/images.cua.ai/v1alpha1/namespaces/ns-b/images", "namespace": "ns-a", "name": "ns-c"}, want: "ns-b"},+ {name: "image cluster list", route: "/api/k8s/{path...}", params: map[string]string{"path": "apis/images.cua.ai/v1alpha1/images"}, want: ""},+ {name: "other proxy resource", route: "/api/k8s/{path...}", params: map[string]string{"path": "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims"}, want: ""},} {t.Run(testCase.name, func(t *testing.T) {ctx := context.WithValue(context.Background(), paramsKey, testCase.params)+ ctx = context.WithValue(ctx, routeKey, testCase.route)if got := OwnedNamespace(ctx); got != testCase.want {t.Fatalf("OwnedNamespace = %q, want %q", got, testCase.want)}- results, err := query.Eval(context.Background(), rego.EvalInput(map[string]any{"params": testCase.params}))+ results, err := query.Eval(context.Background(), rego.EvalInput(map[string]any{"params": testCase.params, "route": testCase.route}))if err != nil {t.Fatalf("eval target_namespace: %v", err)}diff --git a/libs/fleet/backend/auth/policy_routes.go b/libs/fleet/backend/auth/policy_routes.goindex 3efefd33f2..cb589934af 100644--- a/libs/fleet/backend/auth/policy_routes.go+++ b/libs/fleet/backend/auth/policy_routes.go@@ -186,12 +186,12 @@ func AccountLookupRoutePolicy() Node {}// K8sRoutePolicy guards /api/k8s/{path...}. It is the same base + surface shape-// as every other route, with three admission conjuncts: card-or-admin admission+// as every other route, with Image namespace ownership and four admission conjuncts: card-or-admin admission// for custom-resource creation, pool admission over the request body, and// sandbox-services admission over the body of the one Sandbox write the-// allowlist admits.+// allowlist admits, plus Image admission excluding status and mismatched identity.//-// Every conjunct must pass. The two body-reading leaves read the raw body+// Every conjunct must pass. The three body-reading leaves read the raw body// (bounded at 1 MiB) to inspect the object being created or patched, which is// why pool admission names pool_admission.rego alongside authz.rego —// pool_admission imports data.authz.is_admin. They stay separate leaves rather@@ -242,7 +242,13 @@ func K8sRoutePolicy() Node {ServiceWriteNotSupportedMessage,),surfaceLeaf("authz-k8s", "data.authz_k8s.allow"),+ NamespaceOwnershipPolicy(),Because(CustomResourceCreationAdmissionPolicy(), BillingSetupRequiredMessage),+ Policy(+ Registered("image-admission"),+ Query("data.image_admission.allow"),+ WithRawBody(1<<20),+ ),Policy(Modules(Registered("authz"),diff --git a/libs/fleet/backend/auth/policy_test.go b/libs/fleet/backend/auth/policy_test.goindex fff9cd8a6f..f6323b16bd 100644--- a/libs/fleet/backend/auth/policy_test.go+++ b/libs/fleet/backend/auth/policy_test.go@@ -37,6 +37,7 @@ func TestRouteModulesNeverReadInputFacts(t *testing.T) {"authz.rego": authzPolicy,"pool_admission.rego": poolAdmissionPolicy,"sandbox_services_admission.rego": sandboxServicesAdmissionPolicy,+ "image_admission.rego": imageAdmissionPolicy,}// Every base and surface module too, read from the same map LoadOpa// registers, so a surface added there is covered without being named here.diff --git a/libs/fleet/backend/auth/testdata/k8s-route-plan.txt b/libs/fleet/backend/auth/testdata/k8s-route-plan.txtindex 7c07966845..1ceb7b7932 100644--- a/libs/fleet/backend/auth/testdata/k8s-route-plan.txt+++ b/libs/fleet/backend/auth/testdata/k8s-route-plan.txt@@ -3,10 +3,16 @@ AllBecause reason="creating or modifying Kubernetes Services directly is not supported. Declare the port under spec.vmTemplate.services on the pool template, or PATCH spec.vmTemplate.services on your bound OSGymSandbox to expose it on a running sandbox; the matching Service is created for you."Leaf query=data.authz_k8s.not_direct_service_write source=multi["registered:authz","registered:authz-k8s"]Leaf query=data.authz_k8s.allow source=multi["registered:authz","registered:authz-k8s"]+ Any+ Leaf query=data.authz_ownership.claim_allow source=multi["registered:authz","registered:authz-ownership"]+ All+ Leaf query=data.authz_ownership.probe_eligible source=multi["registered:authz","registered:authz-ownership"]+ Leaf query=data.authz_ownership.rbac_allow source=multi["registered:authz","registered:authz-ownership"] facts=namespace_rbac@registered-facts:namespace-rbacBecause reason="A payment method is required to create this resource. Add one in Billing and try again."AnyLeaf query=data.custom_resource_creation_admission.exempt source=multi["registered:authz","registered:custom-resource-creation-admission"]Leaf query=data.custom_resource_creation_admission.billing_eligible source=multi["registered:authz","registered:custom-resource-creation-admission"] facts=stripe_cards@registered-facts:stripe-cards facts=time@registered-facts:current-year facts=time@registered-facts:current-month+ Leaf query=data.image_admission.allow source=registered:image-admission body=1048576Leaf query=data.pool_admission.allow source=multi["registered:authz","registered:pool-admission"] body=1048576Because reason="a sandbox PATCH may only modify spec.vmTemplate.services (an optional metadata.resourceVersion precondition is also accepted)"Leaf query=data.sandbox_services_admission.allow source=registered:sandbox-services-admission body=1048576