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
refactor(cyclops): compose request policies as middleware (#6703)
r33drichards432682dc8f14
diff --git a/libs/fleet/backend/auth/auth.go b/libs/fleet/backend/auth/auth.goindex 41c3c1acbe..1205439fcc 100644--- a/libs/fleet/backend/auth/auth.go+++ b/libs/fleet/backend/auth/auth.go@@ -1,13 +1,39 @@-// Package auth — Keycloak JWT validation, adapted from r33drichards/grt.+// Package auth — Keycloak JWT validation and route authorization, adapted from+// r33drichards/grt.//-// Differences from upstream:-// - Keycloak validation uses the configured issuer because service-account-// tokens do not carry a useful `aud`; GitHub OIDC validates signed-// audiences separately.-// - OPA (Rego) is used for all route-level authorization via-// OpaMiddleware; see auth/authz.rego.-// - Three token families: exact interactive clients, per-key clients, and-// user-key clients; route policy enforces each family and required claims.+// Authentication. Keycloak validation uses the configured issuer because+// service-account tokens do not carry a useful `aud`; GitHub OIDC validates+// signed audiences separately. Three token families reach the policy — exact+// interactive clients, per-key clients, and user-key clients — plus principals+// whose azp cannot be enumerated (oauth2-proxy sessions, RFC 7591 dynamically+// registered MCP clients). authz.rego names the three families; a surface that+// accepts the fourth kind says so by not requiring a family.+//+// Authorization is OPA (Rego), composed rather than monolithic. Every+// authenticated route runs+//+// All(BasePolicy(), <its surface>)+//+// where the base is a non-empty subject — the one condition every rule of the+// former single-module policy shared — and the surface is one module per group+// of routes: authz_keys.rego, authz_k8s.rego, authz_svc.rego, and so on.+// /api/k8s adds pool_admission.rego as a third conjunct over the request body.+//+// Two conjuncts read something beyond the token. pool_admission.rego reads the+// request body; authz_ownership.rego — the namespace-tenancy boundary on+// /api/svc, /api/orch and GET /api/namespaces/{name} — reads a Kubernetes RBAC+// probe, delivered as input.facts by a FactProvider that handlers registers and+// main.go binds. Both are separate leaves rather than rules folded into a+// surface, so the expensive read only happens on the requests a cheap sibling+// has not already decided.+//+// Which surface a route runs is decided in exactly one place, the routeSurfaces+// table in policy_routes.go, which main.go reads through RouteMiddleware. That+// is what keeps the routes and the policy from drifting apart: a registered+// route the table does not name cannot start, and a surface naming routes that+// no longer exist fails route_policy_correspondence_test.go rather than sitting+// there looking like protection. Compiled plans are memoized per surface, so+// routes sharing a surface share one plan.package authimport (diff --git a/libs/fleet/backend/auth/authz.rego b/libs/fleet/backend/auth/authz.regoindex 3b0164e912..f3ba83ba87 100644--- a/libs/fleet/backend/auth/authz.rego+++ b/libs/fleet/backend/auth/authz.rego@@ -1,391 +1,86 @@-# Cyclops-CS authorization policy.+# Cyclops-CS principal vocabulary.#-# Surfaces, distinguished by `input.route`:+# This module answers "who is calling", and nothing else. It holds no allow+# rule and no route name: what a principal may do on a given surface is decided+# by that surface's own module (authz_keys.rego, authz_k8s.rego, …), each of+# which imports this one.#-# /api/keys, /api/k8s, /api/orch — interactive user surfaces. Require a-# non-empty subject and a token issued to one of the-# exact public interactive clients: cyclops-cs-spa or-# cua-cli. Other realm clients are not implicitly trusted.+# The split is what keeps route authorization honest. Until it existed, one+# module carried 30 route-gated allow rules and routes picked it up ad hoc, so a+# route could leave main.go with its rules still in place — which is exactly what+# happened when the /api/gateway route was deleted in #6702. A surface module is+# named by the routes that run it (see routeSurfaces in auth/policy_routes.go),+# so rules for a retired surface have nowhere to hide.#-# /api/batch/{pool}, /api/label/{pool}-# — DEPRECATED. The handler returns 410 Gone for-# every request. These rules remain so that-# unauthenticated callers still receive 401/403-# rather than 410, preserving the auth boundary-# even for a retired surface.+# Every route composes All(authz_base.allow, <surface>.allow):+# authz_base.rego requires a non-empty subject, which was the one condition all+# 30 rules shared, and the surface decides the rest. See policy_routes.go.#-# Data-visibility filtering (which events/env-vars the caller may see) lives-# in filters.rego, not here. authz.rego decides allow/deny only.+# is_admin is defined here because its two consumers sit on opposite sides of+# the split: pool_admission.rego, a conjunct over the request body, and+# auth.EvalIsAdmin, which answers off a User rather than a request. No surface+# module reads it any more — authz_k8s.rego did, as an escape hatch over its+# infra paths, until #6704 turned that surface into an allowlist and left admins+# with the same access as everyone else.package authz-default allow = false--# ── Admin helper ────────────────────────────────────────────────────────────-## is_admin is true when the calling user's JWT sub is in the admin set.# Flags arrive via `input.flags` (resolved per-request from the OpenFeature# provider and TTL-cached in auth/middlewares.go), NOT a static OPA data# store — so admin-membership changes take effect within flagsTTL without a-# pod restart. filters.rego reuses this via `data.authz.is_admin`.+# pod restart.is_admin {- input.flags.admin_subs[_] == input.user.sub+ input.flags.admin_subs[_] == input.user.sub}-# ── Route allow rules ───────────────────────────────────────────────────────+# ── Token families ──────────────────────────────────────────────────────────+#+# Three families reach the policy, distinguished by `azp`. A fourth kind of+# caller — oauth2-proxy cookie sessions and MCP connector clients registered+# through RFC 7591 — matches none of these predicates, which is deliberate: their+# azp cannot be enumerated, so surfaces that accept them say so by not requiring+# a family rather than by naming one.# Exact interactive clients. Keep this allowlist closed: accepting any# arbitrary public realm client would let unrelated clients call user APIs.is_interactive_client {- input.user.azp == "cyclops-cs-spa"+ input.user.azp == "cyclops-cs-spa"}is_interactive_client {- input.user.azp == "cua-cli"-}---# /api/keys (POST/GET) and /api/keys/{id} (DELETE).-allow {- input.route == "/api/keys"- input.user.sub != ""- is_interactive_client-}--allow {- input.route == "/api/keys/{id}"- input.user.sub != ""- is_interactive_client-}--# /api/config — per-user feature flags for exact interactive clients.-allow {- input.route == "/api/config"- input.user.sub != ""- is_interactive_client+ input.user.azp == "cua-cli"}-# Stripe-hosted billing browser endpoints. The backend derives the customer-# identity from input.user.sub and never accepts Stripe ownership identifiers.-allow {- startswith(input.route, "/api/billing/")- input.route != "/api/billing/webhook"- input.user.sub != ""- input.user.azp == "cyclops-cs-spa"+# Per-key clients are Keycloak service accounts bound to one namespace by a+# hardcoded `namespace` claim. Their sub owns nothing on its own, so every+# surface that accepts them checks that claim against the route's parameters.+is_per_key_client {+ startswith(input.user.azp, "key-")}-# /api/namespaces — namespace management (list, create, delete).-# Exact interactive clients may manage their own namespaces.-# Capsule enforces per-user scoping at the K8s API level via-# impersonation headers added by the backend.-allow {- input.route == "/api/namespaces"- input.user.sub != ""- is_interactive_client+# User-key tokens are Keycloak client_credentials JWTs with azp starting with+# "ukey-". The middleware overrides sub with the key owner's identity before the+# policy runs, so input.user.sub is the real user and these keys get SPA-like+# access for programmatic automation.+is_user_key_client {+ startswith(input.user.azp, "ukey-")}-allow {- input.route == "/api/namespaces/{name}"- input.user.sub != ""- is_interactive_client-}--allow {- input.route == "/api/namespaces"- input.user.sub != ""- input.user.principal_type == "github_oidc"-}--allow {- input.route == "/api/namespaces/{name}"- input.user.sub != ""- input.user.principal_type == "github_oidc"-}--allow {- input.route == "/api/github-trust-policies"- input.user.sub != ""- is_interactive_client-}--allow {- input.route == "/api/github-trust-policies/{id}"- input.user.sub != ""- is_interactive_client-}--allow {- input.route == "/api/github-trust-policies"- input.user.sub != ""- is_verified_user_key_client-}--allow {- input.route == "/api/github-trust-policies/{id}"- input.user.sub != ""- is_verified_user_key_client-}--# /api/k8s/{path...} — kubectl-proxy passthrough.-#-# Any exact interactive client may read customer-facing resources (their pools, the pods-# backing their VMs, pod logs, metrics, and the K8s event feed — the event-# *contents* are still redacted for non-admins by filters.rego's-# visible_events). Infra-only resources (cluster nodes, cluster-wide pod-# listings, batch Jobs, and the app's own cyclops-cs ConfigMaps) require-# admin — hiding them is enforced HERE, not just in the SPA nav. CUA-515.-allow {- input.route == "/api/k8s/{path...}"- input.user.sub != ""- is_interactive_client- not is_infra_k8s_path(input.params.path)-}--allow {- input.route == "/api/k8s/{path...}"- input.user.sub != ""- is_interactive_client- is_admin-}--allow {- input.route == "/api/k8s/{path...}"- input.user.sub != ""- input.user.principal_type == "github_oidc"- is_github_k8s_candidate(input.params.path)-}--# is_infra_k8s_path matches the kubectl-proxy paths that expose cluster-# internals. `input.params.path` is the captured {path...} segment with no-# leading slash (e.g. "api/v1/nodes"); query strings are not included.-#-# api/v1/nodes[/...] — NodesList (cluster capacity)-# api/v1/pods — cluster-wide pod listing-# (namespaced pods stay open)-# apis/batch/v1/... — batch Jobs-# api/v1/namespaces/cyclops-cs/configmaps — the app's own config-# apis/cua.ai/v1/osgymworkspacepools — cluster-wide pool listing-# (namespaced pools stay open)-# apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims-# — cluster-wide claim listing-# (namespaced claims stay open)-# apis/osgym.cua.ai/v1alpha1/{osgymsandboxwarmpools,osgymsandboxtemplates,osgymsandboxes}-# — cluster-wide listings of the-# native fleet CRDs (namespaced-# access stays open)-# apis/capsule.clastix.io/<version>/tenants-# — cluster-wide Tenant ownership-# and provisioning API, across-# every served API version-#-# These cluster-wide CRD paths are defence-in-depth: the SPA only ever reads-# pools/claims per-namespace, and Tenant lifecycle is an internal backend-# operation. Blocking them here prevents the SPA proxy from reaching the-# backend ServiceAccount's cluster-wide capabilities.-is_infra_k8s_path(path) { path == "api/v1/nodes" }-is_infra_k8s_path(path) { startswith(path, "api/v1/nodes/") }-is_infra_k8s_path(path) { path == "api/v1/pods" }-is_infra_k8s_path(path) { startswith(path, "apis/batch/v1") }-is_infra_k8s_path(path) { startswith(path, "api/v1/namespaces/cyclops-cs/configmaps") }-is_infra_k8s_path(path) { path == "apis/cua.ai/v1/osgymworkspacepools" }-is_infra_k8s_path(path) { path == "apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims" }-is_infra_k8s_path(path) { path == "apis/osgym.cua.ai/v1alpha1/osgymsandboxwarmpools" }-is_infra_k8s_path(path) { path == "apis/osgym.cua.ai/v1alpha1/osgymsandboxtemplates" }-is_infra_k8s_path(path) { path == "apis/osgym.cua.ai/v1alpha1/osgymsandboxes" }-is_infra_k8s_path(path) {- parts := split(path, "/")- count(parts) >= 4- parts[0] == "apis"- parts[1] == "capsule.clastix.io"- parts[2] != ""- parts[3] == "tenants"-}--is_github_k8s_candidate(path) { startswith(path, "apis/cua.ai/v1/namespaces/") }-is_github_k8s_candidate(path) { startswith(path, "apis/osgym.cua.ai/v1alpha1/namespaces/") }--# /api/orch/{namespace}/{service}/{path...} — per-namespace orchestrator-# catalog read. Exact interactive clients only; namespace + service must be DNS-1123 labels.-# Like /api/svc, this proxy dials Service DNS directly, so namespace-# ownership is enforced in Go (handlers.requireNamespaceAccess).-allow {- input.route == "/api/orch/{namespace}/{service}/{path...}"- input.user.sub != ""- is_interactive_client- valid_dns_label(input.params.namespace)- valid_dns_label(input.params.service)-}--# /api/batch/{pool}/* and /api/label/{pool}/* — DEPRECATED (410 Gone).-#-# These routes are permanently retired; the handler (DeprecatedBatchRoute)-# returns 410 for every request that passes auth. The allow rules below are-# retained so that unauthenticated or unauthorized callers still see-# 401/403 rather than 410, keeping the auth boundary intact on a dead-# surface. No business logic is exercised after OPA passes.-allow {- is_batch_route- input.user.sub != ""- is_interactive_client- valid_dns_label(input.params.pool)-}-allow {- is_batch_route- input.user.sub != ""- is_per_key_client- valid_dns_label(input.params.pool)- input.user.namespace == input.params.pool-}--is_batch_route { input.route == "/api/batch/{pool}/submit" }-is_batch_route { input.route == "/api/batch/{pool}/lanes" }-is_batch_route { input.route == "/api/batch/{pool}/{id}/status" }-is_batch_route { input.route == "/api/batch/{pool}/{id}/results" }-is_batch_route { input.route == "/api/batch/{pool}/{id}" }-is_batch_route { input.route == "/api/label/{pool}/{label}/batch" }-is_batch_route { input.route == "/api/label/{pool}/{label}/status" }-is_batch_route { input.route == "/api/label/{pool}/{label}/results" }-is_batch_route { input.route == "/api/label/{pool}/{label}" }--# /api/svc/{namespace}/{service}[/{path...}] — generic service proxy.-#-# OPA gates authentication + parameter shape ONLY. The proxy dials-# {service}.{namespace}.svc.cluster.local directly — it never traverses-# the K8s API — so Capsule CANNOT scope it, and OPA has no K8s data to-# check ownership itself. Namespace ownership is enforced in Go-# (handlers.requireNamespaceAccess) via an impersonated RoleBinding-# probe before any byte is proxied.-#-# Per-key clients: token's namespace claim must match the {namespace}-# param (enforced both here and in the handler).-allow {- is_svc_route- is_per_key_client- input.user.sub != ""- valid_dns_label(input.params.namespace)- valid_dns_label(input.params.service)- input.user.namespace == input.params.namespace-}-# Every other principal carries a real user identity in `sub`, and the-# handler's impersonated RoleBinding probe is the authorization boundary-# — so OPA only authenticates and shape-checks. This covers:-# • SPA users (azp == "cyclops-cs-spa")-# • user-keys (azp == "ukey-*"; sub overridden to the key owner)-# • oauth2-proxy cookie sessions (synthetic azp == "oauth2-proxy")-# • MCP connector clients minted via RFC 7591 dynamic client-# registration — their azp is a per-registration UUID, so it cannot-# be enumerated here-# Per-key clients are excluded: their rule above binds them to their-# namespace claim, and their sub is a service account that owns nothing.-allow {- is_svc_route- not is_per_key_client- input.user.sub != ""- valid_dns_label(input.params.namespace)- valid_dns_label(input.params.service)-}--is_svc_route { input.route == "/api/svc/{namespace}/{service}" }-is_svc_route { input.route == "/api/svc/{namespace}/{service}/{path...}" }--is_per_key_client { startswith(input.user.azp, "key-") }--# ── Per-user API keys (/api/user-keys) ─────────────────────────────────-#-# Create / list / revoke personal API keys. SPA-only — users manage-# their own keys through the dashboard.-allow {- input.route == "/api/user-keys"- input.user.sub != ""- is_interactive_client-}--allow {- input.route == "/api/user-keys/{id}"- input.user.sub != ""- is_interactive_client-}--# ── User API key access to SPA surfaces ────────────────────────────────-#-# User-key tokens are Keycloak client_credentials JWTs with azp starting-# with "ukey-". The middleware overrides sub with the key owner's-# identity before OPA runs, so input.user.sub is the real user. These-# keys get the same access as SPA users for programmatic automation.--is_user_key_client { startswith(input.user.azp, "ukey-") }-+# The verified form additionally requires the principal_type the middleware+# stamps only after resolving the owner. A token whose azp merely looks like a+# user key does not qualify.is_verified_user_key_client {- is_user_key_client- input.user.principal_type == "user_key"-}--# Namespace management-allow {- input.route == "/api/namespaces"- input.user.sub != ""- is_user_key_client-}--allow {- input.route == "/api/namespaces/{name}"- input.user.sub != ""- is_user_key_client-}--# K8s API proxy — user API keys get the same access as non-admin SPA users-# (infra paths are blocked).-allow {- input.route == "/api/k8s/{path...}"- input.user.sub != ""- is_user_key_client- not is_infra_k8s_path(input.params.path)+ is_user_key_client+ input.user.principal_type == "user_key"}-# Orchestrator catalog access-allow {- input.route == "/api/orch/{namespace}/{service}/{path...}"- input.user.sub != ""- is_user_key_client- valid_dns_label(input.params.namespace)- valid_dns_label(input.params.service)-}--# Batch endpoints — user API keys may target any pool (like SPA users).-# Routes are deprecated and return 410 Gone; rules kept for auth boundary.-allow {- is_batch_route- input.user.sub != ""- is_user_key_client- valid_dns_label(input.params.pool)-}--# Config endpoint-allow {- input.route == "/api/config"- input.user.sub != ""- is_user_key_client-}+# ── Parameter shapes ────────────────────────────────────────────────────────# DNS-1123 label: lowercase alphanumerics + dashes, 1..63 chars,# can't start or end with a dash. Belt-and-braces against a misconfigured# Keycloak mapper or a request that slipped past the Go regex.valid_dns_label(s) {- s != ""- count(s) <= 63- regex.match(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$`, s)-}--# Read-only state SQL. PostgreSQL RLS remains the row-visibility boundary.-allow {- input.route == "/api/state/query"- input.method == "QUERY"- input.user.sub != ""- is_interactive_client-}--allow {- input.route == "/api/state/query"- input.method == "QUERY"- input.user.sub != ""- is_user_key_client+ s != ""+ count(s) <= 63+ regex.match(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$`, s)}diff --git a/libs/fleet/backend/auth/authz_base.rego b/libs/fleet/backend/auth/authz_base.regonew file mode 100644index 0000000000..c27998b4aa--- /dev/null+++ b/libs/fleet/backend/auth/authz_base.rego@@ -0,0 +1,24 @@+# The check every authenticated route runs, whatever surface it belongs to.+#+# All 30 route-gated allow rules of the former monolith required a non-empty+# subject and nothing else in common, so hoisting that one condition out is what+# makes the rest decomposable: for a request on route R,+#+# All(authz_base.allow, surface_R.allow) ≡ the old authz.allow+#+# because every rule was route-gated, so no other surface's rules could have+# fired on R anyway, and each surviving rule is its old body minus this check.+#+# What "non-empty subject" means here is narrow, and worth being precise about:+# the request carries a validated token (TokenAuthMiddleware rejects it+# otherwise, with a 401, before this ever runs) whose identity resolved to+# something. An empty sub reaches this point from a token with no sub claim, or+# from a user-key whose owner could not be resolved — authenticated as a token,+# anonymous as a principal. Authorization proper is the surface's job.+package authz_base++default allow = false++allow {+ input.user.sub != ""+}diff --git a/libs/fleet/backend/auth/authz_base_test.rego b/libs/fleet/backend/auth/authz_base_test.regonew file mode 100644index 0000000000..868b463435--- /dev/null+++ b/libs/fleet/backend/auth/authz_base_test.rego@@ -0,0 +1,35 @@+# The one condition every authenticated route shares.+#+# These cases are the reason the base can be factored out at all: hoisting a+# check into a conjunct is only sound if the conjunct answers the same thing for+# every surface, so it is tested here once rather than re-tested per surface.+# What each surface still tests is that the composition denies an empty subject+# on its own routes, which is the property callers depend on.+package authz_base_test++import rego.v1++import data.authz_base++test_non_empty_subject_allowed if {+ authz_base.allow with input as {"user": {"sub": "user-123", "azp": "cyclops-cs-spa"}}+}++test_empty_subject_denied if {+ not authz_base.allow with input as {"user": {"sub": "", "azp": "cyclops-cs-spa"}}+}++test_missing_subject_denied if {+ not authz_base.allow with input as {"user": {"azp": "cyclops-cs-spa"}}+}++test_missing_user_denied if {+ not authz_base.allow with input as {"route": "/api/keys"}+}++# The base says nothing about which client the token came from. A surface that+# wants that says so itself — otherwise the check would be in two places and+# only one of them would get updated.+test_unknown_client_still_passes_the_base if {+ authz_base.allow with input as {"user": {"sub": "user-123", "azp": "untrusted-client"}}+}diff --git a/libs/fleet/backend/auth/authz_billing.rego b/libs/fleet/backend/auth/authz_billing.regonew file mode 100644index 0000000000..6095532f20--- /dev/null+++ b/libs/fleet/backend/auth/authz_billing.rego@@ -0,0 +1,25 @@+# Stripe-hosted billing browser endpoints: /api/billing/summary,+# /api/billing/setup-session, /api/billing/portal-session.+#+# The backend derives the customer identity from input.user.sub and never+# accepts Stripe ownership identifiers, so this rule authenticates and leaves+# ownership to the handler.+#+# SPA only — not cua-cli, not user keys. These endpoints hand back Stripe-hosted+# URLs meant to be opened in the browser session that asked for them.+#+# The prefix match rather than three literals is deliberate: a new billing+# browser route is covered the day it is registered. /api/billing/webhook is+# excluded because it is not an authenticated route at all — Stripe signature+# verification is its authentication boundary, and it is registered without the+# authorization stage. The exclusion is belt-and-braces for the day someone moves+# it, and route_policy_correspondence_test.go checks it still names a real route.+package authz_billing++default allow = false++allow {+ startswith(input.route, "/api/billing/")+ input.route != "/api/billing/webhook"+ input.user.azp == "cyclops-cs-spa"+}diff --git a/libs/fleet/backend/auth/authz_billing_test.rego b/libs/fleet/backend/auth/authz_billing_test.regonew file mode 100644index 0000000000..2ee1e0bcbd--- /dev/null+++ b/libs/fleet/backend/auth/authz_billing_test.rego@@ -0,0 +1,78 @@+# What the Stripe-hosted billing browser routes run:+# All(authz_base.allow, authz_billing.allow).+#+# This is the only surface whose module matches a route prefix rather than+# literals, so the cases below pin both halves of that: the three registered+# billing routes are covered, and the webhook — which is registered without an+# authorization stage at all, Stripe signature verification being its boundary —+# is not.+package authz_billing_test++import rego.v1++import data.authz_base+import data.authz_billing++route_allow if {+ authz_base.allow+ authz_billing.allow+}++billing_request(route, azp, sub) := {+ "route": route,+ "method": "GET",+ "path": route,+ "params": {},+ "user": {"sub": sub, "azp": azp, "namespace": "", "email": "[email protected]"},+}++test_summary_spa_allowed if {+ route_allow with input as billing_request("/api/billing/summary", "cyclops-cs-spa", "user-123")+}++test_setup_session_spa_allowed if {+ route_allow with input as billing_request("/api/billing/setup-session", "cyclops-cs-spa", "user-123")+}++test_portal_session_spa_allowed if {+ route_allow with input as billing_request("/api/billing/portal-session", "cyclops-cs-spa", "user-123")+}++# Not every interactive client: these endpoints hand back Stripe-hosted URLs+# meant for the browser session that asked, so cua-cli is out even though it is+# an exact interactive client everywhere else.+test_cua_cli_denied if {+ not route_allow with input as billing_request("/api/billing/summary", "cua-cli", "user-123")+}++test_user_key_denied if {+ not route_allow with input as billing_request("/api/billing/summary", "ukey-test123abc", "user-123")+}++test_per_key_denied if {+ not route_allow with input as billing_request("/api/billing/summary", "key-foo", "svc-123")+}++test_empty_subject_denied if {+ not route_allow with input as billing_request("/api/billing/summary", "cyclops-cs-spa", "")+}++# The webhook is excluded from the prefix explicitly. It is not registered behind+# the authorization stage, so this rule never runs for it in production — but a+# prefix that swept it in would be a policy claiming to guard a route it does+# not, and route_policy_correspondence_test.go would then report the exclusion as+# the only thing keeping the two honest.+test_webhook_not_covered_by_the_prefix if {+ not route_allow with input as billing_request("/api/billing/webhook", "cyclops-cs-spa", "user-123")+}++# A future billing browser route is covered the day it is registered, which is+# why the module matches a prefix rather than three literals.+test_unregistered_billing_route_covered_by_the_prefix if {+ route_allow with input as billing_request("/api/billing/invoices", "cyclops-cs-spa", "user-123")+}++# The prefix is anchored: a route that merely contains it is not billing.+test_lookalike_prefix_denied if {+ not route_allow with input as billing_request("/api/not-billing/summary", "cyclops-cs-spa", "user-123")+}diff --git a/libs/fleet/backend/auth/authz_config.rego b/libs/fleet/backend/auth/authz_config.regonew file mode 100644index 0000000000..0721c0d3e7--- /dev/null+++ b/libs/fleet/backend/auth/authz_config.rego@@ -0,0 +1,19 @@+# /api/config — the per-user feature flags the SPA reads at load.+#+# Interactive clients and user keys. The response is scoped to the caller's own+# sub, so a user key seeing it sees its owner's flags.+package authz_config++import data.authz++default allow = false++allow {+ input.route == "/api/config"+ authz.is_interactive_client+}++allow {+ input.route == "/api/config"+ authz.is_user_key_client+}diff --git a/libs/fleet/backend/auth/authz_config_test.rego b/libs/fleet/backend/auth/authz_config_test.regonew file mode 100644index 0000000000..dbbd311e9c--- /dev/null+++ b/libs/fleet/backend/auth/authz_config_test.rego@@ -0,0 +1,26 @@+# What /api/config runs: All(authz_base.allow, authz_config.allow).+#+# route_allow below is that composition, so every case asserts the verdict the+# route produces rather than one module's half of it. Splitting the policy must+# not turn a test of the whole check into a test of a fragment.+package authz_config_test++import rego.v1++import data.authz_base+import data.authz_config++route_allow if {+ authz_base.allow+ authz_config.allow+}++test_user_api_key_config_allowed if {+ route_allow with input as {+ "route": "/api/config",+ "method": "GET",+ "path": "/api/config",+ "params": {},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ }+}diff --git a/libs/fleet/backend/auth/authz_github_trust.rego b/libs/fleet/backend/auth/authz_github_trust.regonew file mode 100644index 0000000000..9ba23d1c9c--- /dev/null+++ b/libs/fleet/backend/auth/authz_github_trust.rego@@ -0,0 +1,37 @@+# /api/github-trust-policies and /api/github-trust-policies/{id} — the trust+# policies that decide which GitHub Actions repositories may mint a principal+# against which namespaces.+#+# Interactive clients, and user keys in their *verified* form only. This is the+# one surface that distinguishes the two: everywhere else a "ukey-" azp is+# enough, but a trust policy grants a repository the ability to act as its+# owner, so the token must also carry the principal_type the middleware stamps+# after resolving that owner.+#+# A github_oidc principal cannot reach this surface at all — a repository must+# not be able to widen the grant it was let in by.+package authz_github_trust++import data.authz++default allow = false++allow {+ input.route == "/api/github-trust-policies"+ authz.is_interactive_client+}++allow {+ input.route == "/api/github-trust-policies/{id}"+ authz.is_interactive_client+}++allow {+ input.route == "/api/github-trust-policies"+ authz.is_verified_user_key_client+}++allow {+ input.route == "/api/github-trust-policies/{id}"+ authz.is_verified_user_key_client+}diff --git a/libs/fleet/backend/auth/authz_github_trust_test.rego b/libs/fleet/backend/auth/authz_github_trust_test.regonew file mode 100644index 0000000000..ed4c13068a--- /dev/null+++ b/libs/fleet/backend/auth/authz_github_trust_test.rego@@ -0,0 +1,86 @@+# What the GitHub trust-policy routes runs: All(authz_base.allow, authz_github_trust.allow).+#+# route_allow below is that composition, so every case asserts the verdict the+# route produces rather than one module's half of it. Splitting the policy must+# not turn a test of the whole check into a test of a fragment.+package authz_github_trust_test++import rego.v1++import data.authz_base+import data.authz_github_trust++route_allow if {+ authz_base.allow+ authz_github_trust.allow+}++test_user_api_key_github_trust_policies_allowed if {+ route_allow with input as {+ "route": "/api/github-trust-policies",+ "method": "POST",+ "path": "/api/github-trust-policies",+ "params": {},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": "", "principal_type": "user_key"},+ }+}++test_user_api_key_github_trust_policy_allowed if {+ route_allow with input as {+ "route": "/api/github-trust-policies/{id}",+ "method": "PATCH",+ "path": "/api/github-trust-policies/policy-123",+ "params": {"id": "policy-123"},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": "", "principal_type": "user_key"},+ }+}++test_unverified_user_key_github_trust_policies_denied if {+ not route_allow with input as {+ "route": "/api/github-trust-policies",+ "method": "POST",+ "path": "/api/github-trust-policies",+ "params": {},+ "user": {"sub": "service-account-ukey-rogue", "azp": "ukey-rogue", "namespace": "", "email": "", "principal_type": "user"},+ }+}++test_per_key_github_trust_policies_denied if {+ not route_allow with input as {+ "route": "/api/github-trust-policies",+ "method": "POST",+ "path": "/api/github-trust-policies",+ "params": {},+ "user": {"sub": "svc-123", "azp": "key-pool-foo", "namespace": "pool-foo", "email": ""},+ }+}++test_per_key_github_trust_policy_denied if {+ not route_allow with input as {+ "route": "/api/github-trust-policies/{id}",+ "method": "DELETE",+ "path": "/api/github-trust-policies/policy-123",+ "params": {"id": "policy-123"},+ "user": {"sub": "svc-123", "azp": "key-pool-foo", "namespace": "pool-foo", "email": ""},+ }+}++test_untrusted_client_github_trust_policies_denied if {+ not route_allow with input as {+ "route": "/api/github-trust-policies",+ "method": "GET",+ "path": "/api/github-trust-policies",+ "params": {},+ "user": {"sub": "user-123", "azp": "untrusted-client", "namespace": "", "email": ""},+ }+}++test_untrusted_client_github_trust_policy_denied if {+ not route_allow with input as {+ "route": "/api/github-trust-policies/{id}",+ "method": "GET",+ "path": "/api/github-trust-policies/policy-123",+ "params": {"id": "policy-123"},+ "user": {"sub": "user-123", "azp": "untrusted-client", "namespace": "", "email": ""},+ }+}diff --git a/libs/fleet/backend/auth/authz_k8s.rego b/libs/fleet/backend/auth/authz_k8s.regonew file mode 100644index 0000000000..60d8be27cf--- /dev/null+++ b/libs/fleet/backend/auth/authz_k8s.rego@@ -0,0 +1,625 @@+# /api/k8s/{path...} — kubectl-proxy passthrough.+#+# This surface is an allowlist. A request names a group, a version, a resource,+# a scope and a method, and unless some rule below names that combination it is+# denied. A resource nobody thought about is not reachable.+#+# It was a denylist until #6704: everything reached the Kubernetes API except+# the paths is_infra_k8s_path and is_event_k8s_path excluded. That posture is+# only as good as the exclusion list is complete, and completeness is not a+# property anyone can check — the failure mode is a resource nobody thought to+# exclude being proxied to the apiserver under the pod ServiceAccount. GitHub+# OIDC tokens were already allowlisted (github_k8s_request_allowed, below), so+# the file held two postures at once; this makes them one.+#+# What the allowlist admits was not guessed. It is the intersection of four+# sources of evidence, and the comment on each block says which:+#+# 1. 30 days of production traffic (335,742 requests over 60 distinct path+# shapes), read from the backend's own request log and split by response+# status so that requests the policy already denied are not mistaken for+# working traffic.+# 2. cyclops-cs/sdk/src/routes.rs — the Rust SDK behind every sdk-bindings+# language, which constructs these paths directly.+# 3. github_k8s_request_allowed, a reviewed statement of legitimate access.+# 4. The route tests and characterization cases in this repo.+#+# Admin is deliberately not a way around any of this. Under the denylist,+# is_admin was an escape hatch over the infra paths; an allowlist with an+# escape hatch is a denylist wearing a hat. Admins get the same paths everyone+# else does.+#+# Two denies still sit in front of the allowlist rather than being expressed as+# its absence. Both are redundant today — nothing below would admit an event or+# an infra path — and both are kept on purpose, so that widening the allowlist+# later cannot reopen them by accident.+#+# This surface also runs pool_admission.rego over the request body; see+# K8sRoutePolicy in policy_routes.go. That is a separate leaf, not a rule here,+# because it needs the raw body and nothing else on this surface does.+package authz_k8s++import data.authz++default allow = false++allow {+ not is_event_k8s_path(input.params.path)+ not is_infra_k8s_path(input.params.path)+ surface_allow+}++surface_allow {+ input.route == "/api/k8s/{path...}"+ authz.is_interactive_client+ k8s_request_allowed+}++# User API keys reach exactly what an interactive client reaches. They did+# before too — the difference is that "exactly what" is now enumerated.+surface_allow {+ input.route == "/api/k8s/{path...}"+ authz.is_user_key_client+ k8s_request_allowed+}++surface_allow {+ input.route == "/api/k8s/{path...}"+ input.user.principal_type == "github_oidc"+ github_k8s_request_allowed+}++# is_event_k8s_path matches every kubectl-proxy path that addresses the Event+# resource. `path` is `input.params.path`: the captured {path...} segment, no+# leading slash, no query string.+#+# There are eight such paths, not one, and all eight were checked against a live+# apiserver rather than inferred — two API groups serve the same objects, each+# under a cluster-scoped and a namespaced form, and each of those also has a+# legacy /watch/ alias that streams the same data:+#+# api/v1/events[/name] apis/events.k8s.io/{v}/events[/name]+# api/v1/namespaces/{ns}/events[/name] apis/events.k8s.io/{v}/namespaces/{ns}/events[/name]+# api/v1/watch/events apis/events.k8s.io/{v}/watch/events+# api/v1/watch/namespaces/{ns}/events apis/events.k8s.io/{v}/watch/namespaces/{ns}/events+#+# So this is not a substring test for "api/v1/events": that string occurs in one+# of the eight. Nor is it a test for the core group alone — events.k8s.io serves+# the identical objects, and a deny that named only core/v1 would read as+# "events are not proxied" while proxying them.+#+# The two axes are factored apart: event_api_prefix decides how many leading+# segments name the group and version, and the four rules below are the four+# addressing forms, written against that offset. Adding an API group is one more+# prefix rule; the forms do not have to be restated for it.+#+# Nothing here reads the query string, so ?watch=true is denied along with the+# list it decorates — as is the /watch/ path form, which is the same read under+# a different spelling.++# event_api_prefix reports how many leading segments a path spends naming a+# group and version that serves Events, and is undefined for a path that names+# neither. The version is matched positionally rather than against a literal, so+# a cluster serving v1beta1 — or a version that does not exist yet — is covered.+#+# parts[1] is compared whole, exactly as the Capsule rule above compares its+# group: "events.k8s.io.evil" is a different segment, not a prefix match.+event_api_prefix(parts) = 2 {+ parts[0] == "api"+ parts[1] == "v1"+}++event_api_prefix(parts) = 3 {+ parts[0] == "apis"+ parts[1] == "events.k8s.io"+ parts[2] != ""+}++# <prefix>/events[/name] — cluster-scoped collection or item.+is_event_k8s_path(path) {+ parts := split(path, "/")+ base := event_api_prefix(parts)+ count(parts) > base+ parts[base] == "events"+}++# <prefix>/namespaces/{ns}/events[/name] — namespaced collection or item. The+# namespace segment is matched positionally, so any value in it — including+# empty — still addresses an Event collection.+is_event_k8s_path(path) {+ parts := split(path, "/")+ base := event_api_prefix(parts)+ count(parts) > base + 2+ parts[base] == "namespaces"+ parts[base + 2] == "events"+}++# <prefix>/watch/events — the legacy cluster-scoped watch alias. Deprecated+# since Kubernetes 1.11 and still served: it returns a stream of whole Event+# objects, verified against the cluster this backend proxies to.+is_event_k8s_path(path) {+ parts := split(path, "/")+ base := event_api_prefix(parts)+ count(parts) > base + 1+ parts[base] == "watch"+ parts[base + 1] == "events"+}++# <prefix>/watch/namespaces/{ns}/events — the legacy namespaced watch alias.+is_event_k8s_path(path) {+ parts := split(path, "/")+ base := event_api_prefix(parts)+ count(parts) > base + 3+ parts[base] == "watch"+ parts[base + 1] == "namespaces"+ parts[base + 3] == "events"+}++# ── The allowlist ───────────────────────────────────────────────────────────+#+# k8s_request_allowed is the whole of what an interactive client or a user API+# key may ask the Kubernetes API for. Each block below names its evidence; a+# block with no evidence does not belong here.+#+# The shape helpers are shared with github_k8s_request_allowed further down,+# which has always worked this way — group, version, resource, scope, method.++# ── Fleet CRDs, native group ────────────────────────────────────────────────+#+# apis/osgym.cua.ai/v1alpha1/namespaces/{ns}/{claims,warmpools,templates}+#+# The resources this system exists to manage, and 99% of all observed traffic.+# Attested by all four sources: the SDK builds exactly these paths, the GitHub+# allowlist already names the same three, and production shows the full CRUD+# matrix succeeding.+native_fleet_resources := {+ "osgymsandboxclaims",+ "osgymsandboxwarmpools",+ "osgymsandboxtemplates",+}++k8s_request_allowed {+ parts := split(input.params.path, "/")+ apis_namespaced_group(parts, "osgym.cua.ai", "v1alpha1")+ native_fleet_resources[parts[5]]+ fleet_crud_shape(parts)+}++# ── Fleet CRDs, legacy group ────────────────────────────────────────────────+#+# apis/cua.ai/v1/namespaces/{ns}/osgymworkspacepools+#+# The pre-osgym pool API, still carrying 22,926 GETs and a full write matrix in+# the last 30 days — it is not dead. PUT is included because production shows+# 40 successful PUTs: no rule ever named that verb, and it worked only because+# the denylist never asked. Naming it here is the first time anyone has decided+# it rather than defaulted into it.+k8s_request_allowed {+ parts := split(input.params.path, "/")+ apis_namespaced_group(parts, "cua.ai", "v1")+ parts[5] == "osgymworkspacepools"+ legacy_pool_shape(parts)+}++# ── Core workload reads ─────────────────────────────────────────────────────+#+# api/v1/namespaces/{ns}/{pods,services}+#+# Pods and their logs are what a customer looks at to see their own sandbox;+# policy_test.go has asserted them customer-facing since CUA-515. Reads only:+# nothing in traffic or in this repo writes a core resource through this proxy.+k8s_request_allowed {+ parts := split(input.params.path, "/")+ core_namespaced_resource(parts, "pods")+ core_read_shape(parts)+ input.method == "GET"+}++# Pod logs are a subresource, so they need the one extra segment.+k8s_request_allowed {+ parts := split(input.params.path, "/")+ core_namespaced_resource(parts, "pods")+ core_subresource(parts, "log")+ input.method == "GET"+}++k8s_request_allowed {+ parts := split(input.params.path, "/")+ core_namespaced_resource(parts, "services")+ core_read_shape(parts)+ input.method == "GET"+}++# ── Pod metrics ─────────────────────────────────────────────────────────────+#+# apis/metrics.k8s.io/v1beta1/namespaces/{ns}/pods — the CPU/memory numbers+# shown next to a sandbox. Asserted customer-facing by policy_test.go.+k8s_request_allowed {+ parts := split(input.params.path, "/")+ apis_namespaced_group(parts, "metrics.k8s.io", "v1beta1")+ parts[5] == "pods"+ apis_read_shape(parts)+ input.method == "GET"+}++# ── KubeVirt reads ──────────────────────────────────────────────────────────+#+# apis/kubevirt.io/v1/namespaces/{ns}/{virtualmachines,virtualmachineinstances}+#+# The VMs behind the sandboxes; Capsule scopes the caller to their own+# namespaces. Reads only. Production also shows one DELETE of a VM and one+# /restart, both single occurrences that look like a person intervening by+# hand rather than a client's path — those stay denied until someone says+# otherwise, which is a smaller mistake than admitting a destructive verb on+# the strength of one call.+kubevirt_resources := {"virtualmachines", "virtualmachineinstances"}++k8s_request_allowed {+ parts := split(input.params.path, "/")+ apis_namespaced_group(parts, "kubevirt.io", "v1")+ kubevirt_resources[parts[5]]+ apis_read_shape(parts)+ input.method == "GET"+}++# ── Discovery ───────────────────────────────────────────────────────────────+#+# openapi/v2, openapi/v3/... and the bare group/version documents. This is+# kubectl's opening handshake and the SDKs' schema check: read-only, no object+# data, and denying it makes a client fail in a way that looks like an outage+# rather than a policy decision.+k8s_request_allowed {+ startswith(input.params.path, "openapi/")+ input.method == "GET"+}++k8s_request_allowed {+ parts := split(input.params.path, "/")+ count(parts) <= 3+ parts[0] == "apis"+ input.method == "GET"+}++# ── Permission self-check ───────────────────────────────────────────────────+#+# POST apis/authorization.k8s.io/v1/selfsubjectaccessreviews — asks the+# apiserver what the impersonated caller may do. It creates nothing and+# discloses only that answer, which the caller could establish anyway by+# trying. 12 successes in the last 30 days.+k8s_request_allowed {+ input.params.path == "apis/authorization.k8s.io/v1/selfsubjectaccessreviews"+ input.method == "POST"+}++# ── Shape helpers ───────────────────────────────────────────────────────────+#+# `input.params.path` is the captured {path...} segment: no leading slash, no+# query string. Segment indices are fixed because both path grammars are:+#+# apis/{group}/{version}/namespaces/{ns}/{resource}[/{name}[/{sub}]]+# 0 1 2 3 4 5 6 7+# api/v1/namespaces/{ns}/{resource}[/{name}[/{sub}]]+# 0 1 2 3 4 5 6++apis_namespaced_group(parts, group, version) {+ count(parts) >= 6+ parts[0] == "apis"+ parts[1] == group+ parts[2] == version+ parts[3] == "namespaces"+ parts[4] != ""+}++core_namespaced_resource(parts, resource) {+ count(parts) >= 5+ parts[0] == "api"+ parts[1] == "v1"+ parts[2] == "namespaces"+ parts[3] != ""+ parts[4] == resource+}++apis_collection(parts) {+ count(parts) == 6+}++apis_item(parts) {+ count(parts) == 7+ parts[6] != ""+}++apis_subresource(parts, name) {+ count(parts) == 8+ parts[6] != ""+ parts[7] == name+}++apis_read_shape(parts) {+ apis_collection(parts)+}++apis_read_shape(parts) {+ apis_item(parts)+}++core_read_shape(parts) {+ count(parts) == 5+}++core_read_shape(parts) {+ count(parts) == 6+ parts[5] != ""+}++core_subresource(parts, name) {+ count(parts) == 7+ parts[5] != ""+ parts[6] == name+}++# ── Verb matrices ───────────────────────────────────────────────────────────++fleet_crud_shape(parts) {+ apis_collection(parts)+ input.method == "GET"+}++fleet_crud_shape(parts) {+ apis_collection(parts)+ input.method == "POST"+}++fleet_crud_shape(parts) {+ apis_item(parts)+ input.method == "GET"+}++fleet_crud_shape(parts) {+ apis_item(parts)+ input.method == "PATCH"+}++fleet_crud_shape(parts) {+ apis_item(parts)+ input.method == "DELETE"+}++# The status subresource. 9,882 PATCHes in 30 days, every one of them refused+# — by Capsule's RBAC downstream, not by this policy, since the denylist+# admitted the shape. Enumerating it here changes nothing about that refusal;+# it is here so that the allowlist describes what callers actually ask for,+# and so the 403 stays a question about RBAC rather than becoming a question+# about this file.+fleet_crud_shape(parts) {+ apis_subresource(parts, "status")+ input.method == "PATCH"+}++legacy_pool_shape(parts) {+ fleet_crud_shape(parts)+}++legacy_pool_shape(parts) {+ apis_item(parts)+ input.method == "PUT"+}++# is_infra_k8s_path matches the kubectl-proxy paths that expose cluster+# internals. `input.params.path` is the captured {path...} segment with no+# leading slash (e.g. "api/v1/nodes"); query strings are not included.+#+# Every path it names is already outside the allowlist above, so this is+# redundant — deliberately. It is the conjunct that keeps a future widening of+# the allowlist from reopening the cluster's internals by accident, and it costs+# one predicate.+#+# api/v1/nodes[/...] — NodesList (cluster capacity)+# api/v1/pods — cluster-wide pod listing+# (namespaced pods stay open)+# apis/batch/v1/... — batch Jobs+# api/v1/namespaces/cyclops-cs/configmaps — the app's own config+# apis/cua.ai/v1/osgymworkspacepools — cluster-wide pool listing+# (namespaced pools stay open)+# apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims+# — cluster-wide claim listing+# (namespaced claims stay open)+# apis/osgym.cua.ai/v1alpha1/{osgymsandboxwarmpools,osgymsandboxtemplates,osgymsandboxes}+# — cluster-wide listings of the+# native fleet CRDs (namespaced+# access stays open)+# apis/capsule.clastix.io/<version>/tenants+# — cluster-wide Tenant ownership+# and provisioning API, across+# every served API version+#+# These cluster-wide CRD paths are defence-in-depth: the SPA only ever reads+# pools/claims per-namespace, and Tenant lifecycle is an internal backend+# operation. Blocking them here prevents the SPA proxy from reaching the+# backend ServiceAccount's cluster-wide capabilities.+# The legacy /watch/ alias serves the same collection as the path it aliases —+# api/v1/watch/pods streams exactly what api/v1/pods lists — so a deny that+# matched only the literal spelling did not cover it. Rather than restate every+# rule below in its watch form, the alias is rewritten to the path it aliases+# and the literal rules answer it. That makes agreement structural: a path and+# its alias cannot disagree, and an infra path added later is covered in both+# spellings without anyone remembering to.+#+# It also keeps the distinction that matters: api/v1/watch/namespaces/{ns}/pods+# rewrites to api/v1/namespaces/{ns}/pods, which is not an infra path and stays+# open. Namespaced pods are customer-facing in either spelling.+is_infra_k8s_path(path) {+ is_infra_literal(watch_alias_target(path))+}++is_infra_k8s_path(path) {+ is_infra_literal(path)+}++# watch_alias_target strips the /watch/ infix, in the two positions the K8s API+# puts it: after api/v1 for core resources, and after apis/{group}/{version} for+# everything else. Undefined for a path that is not a watch alias, which leaves+# the rule above undefined too.+watch_alias_target(path) = target {+ parts := split(path, "/")+ count(parts) > 3+ parts[0] == "api"+ parts[1] == "v1"+ parts[2] == "watch"+ target := concat("/", array.concat(["api", "v1"], array.slice(parts, 3, count(parts))))+}++watch_alias_target(path) = target {+ parts := split(path, "/")+ count(parts) > 4+ parts[0] == "apis"+ parts[3] == "watch"+ target := concat("/", array.concat(array.slice(parts, 0, 3), array.slice(parts, 4, count(parts))))+}++is_infra_literal(path) {+ path == "api/v1/nodes"+}++is_infra_literal(path) {+ startswith(path, "api/v1/nodes/")+}++is_infra_literal(path) {+ path == "api/v1/pods"+}++is_infra_literal(path) {+ startswith(path, "apis/batch/v1")+}++is_infra_literal(path) {+ startswith(path, "api/v1/namespaces/cyclops-cs/configmaps")+}++is_infra_literal(path) {+ path == "apis/cua.ai/v1/osgymworkspacepools"+}++is_infra_literal(path) {+ path == "apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims"+}++is_infra_literal(path) {+ path == "apis/osgym.cua.ai/v1alpha1/osgymsandboxwarmpools"+}++is_infra_literal(path) {+ path == "apis/osgym.cua.ai/v1alpha1/osgymsandboxtemplates"+}++is_infra_literal(path) {+ path == "apis/osgym.cua.ai/v1alpha1/osgymsandboxes"+}++is_infra_literal(path) {+ parts := split(path, "/")+ count(parts) >= 4+ parts[0] == "apis"+ parts[1] == "capsule.clastix.io"+ parts[2] != ""+ parts[3] == "tenants"+}++github_k8s_request_allowed {+ parts := split(input.params.path, "/")+ github_legacy_pool_request(parts)+ github_namespace_allowed(parts[4])+}++github_k8s_request_allowed {+ parts := split(input.params.path, "/")+ github_native_fleet_request(parts)+ github_namespace_allowed(parts[4])+}++github_namespace_allowed(namespace) {+ input.user.allowed_namespaces[_] == namespace+}++github_legacy_pool_request(parts) {+ github_namespaced_resource(parts, "cua.ai", "v1", "osgymworkspacepools")+ github_collection_or_item(parts)+ input.method == "GET"+}++github_legacy_pool_request(parts) {+ github_namespaced_resource(parts, "cua.ai", "v1", "osgymworkspacepools")+ github_collection_or_item(parts)+ input.method == "POST"+}++github_legacy_pool_request(parts) {+ github_namespaced_resource(parts, "cua.ai", "v1", "osgymworkspacepools")+ github_collection_or_item(parts)+ input.method == "PATCH"+}++github_legacy_pool_request(parts) {+ github_namespaced_resource(parts, "cua.ai", "v1", "osgymworkspacepools")+ github_collection_or_item(parts)+ input.method == "DELETE"+}++github_native_fleet_request(parts) {+ github_namespaced_resource(parts, "osgym.cua.ai", "v1alpha1", "osgymsandboxclaims")+ github_native_crud_shape(parts)+}++github_native_fleet_request(parts) {+ github_namespaced_resource(parts, "osgym.cua.ai", "v1alpha1", "osgymsandboxwarmpools")+ github_native_crud_shape(parts)+}++github_native_fleet_request(parts) {+ github_namespaced_resource(parts, "osgym.cua.ai", "v1alpha1", "osgymsandboxtemplates")+ github_collection_or_item(parts)+ input.method == "GET"+}++github_native_crud_shape(parts) {+ github_collection_or_item(parts)+ input.method == "GET"+}++github_native_crud_shape(parts) {+ count(parts) == 6+ input.method == "POST"+}++github_native_crud_shape(parts) {+ github_nonempty_item(parts)+ input.method == "PATCH"+}++github_native_crud_shape(parts) {+ github_nonempty_item(parts)+ input.method == "DELETE"+}++github_namespaced_resource(parts, group, version, resource) {+ count(parts) >= 6+ parts[0] == "apis"+ parts[1] == group+ parts[2] == version+ parts[3] == "namespaces"+ parts[4] != ""+ parts[5] == resource+}++github_collection_or_item(parts) {+ count(parts) == 6+}++github_collection_or_item(parts) {+ github_nonempty_item(parts)+}++github_nonempty_item(parts) {+ count(parts) == 7+ parts[6] != ""+}diff --git a/libs/fleet/backend/auth/authz_k8s_test.rego b/libs/fleet/backend/auth/authz_k8s_test.regonew file mode 100644index 0000000000..c2782ca7cb--- /dev/null+++ b/libs/fleet/backend/auth/authz_k8s_test.rego@@ -0,0 +1,868 @@+# What /api/k8s/{path...} runs: All(authz_base.allow, authz_k8s.allow).+#+# route_allow below is that composition, so every case asserts the verdict the+# route produces rather than one module's half of it. Splitting the policy must+# not turn a test of the whole check into a test of a fragment.+#+# route_allow here is base + authz_k8s only. The route also runs+# pool_admission.rego over the request body, which has its own suite in+# pool_admission_test.rego; these cases are about route authorization, which is+# exactly what they were about before the split.+package authz_k8s_test++import rego.v1++import data.authz_base+import data.authz_k8s++route_allow if {+ authz_base.allow+ authz_k8s.allow+}++# Both of these named "api/v1/namespaces" — the bare namespace list — when the+# surface was a denylist and any path it did not exclude was admitted. That+# path is not on the allowlist and nothing observed in production asks for it,+# so these now use a path that is: a namespaced pod list. What they are for is+# unchanged, which is that these two azp values reach the surface at all.+test_k8s_spa_allowed if {+ route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/namespaces/foo/pods",+ "params": {"path": "api/v1/namespaces/foo/pods"},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_k8s_cua_cli_allowed if {+ route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/namespaces/foo/pods",+ "params": {"path": "api/v1/namespaces/foo/pods"},+ "user": {"sub": "user-123", "azp": "cua-cli", "namespace": "", "email": "[email protected]"},+ }+}++# The bare namespace list itself, which used to be the example of an allowed+# path and is now the example of an unenumerated one.+test_k8s_namespace_list_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/namespaces",+ "params": {"path": "api/v1/namespaces"},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_k8s_nodes_non_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/nodes",+ "params": {"path": "api/v1/nodes"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++# Admin used to be an escape hatch over the infra paths. Under an allowlist it+# is not an escape hatch over anything: an allowlist with a bypass is a denylist+# wearing a hat. This is the test that used to assert the opposite.+test_k8s_nodes_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/nodes",+ "params": {"path": "api/v1/nodes"},+ "user": {"sub": "admin-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": ["admin-1"]},+ }+}++test_k8s_cluster_pods_non_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/pods",+ "params": {"path": "api/v1/pods"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_batch_jobs_non_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/batch/v1/namespaces/foo/jobs",+ "params": {"path": "apis/batch/v1/namespaces/foo/jobs"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_cyclops_configmaps_non_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/namespaces/cyclops-cs/configmaps/batch-configs",+ "params": {"path": "api/v1/namespaces/cyclops-cs/configmaps/batch-configs"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_namespaced_pods_non_admin_allowed if {+ route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/namespaces/foo/pods",+ "params": {"path": "api/v1/namespaces/foo/pods"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++# ── K8s events are denied outright ──────────────────────────────────────────+#+# All eight paths that serve Events, both ends of the collection/item split, and+# every principal family this surface otherwise admits. The eight were read off+# a live apiserver, not guessed: two API groups (core/v1 and events.k8s.io),+# each cluster-scoped and namespaced, each with a legacy /watch/ alias that+# streams the same objects. A deny covering only "api/v1/events" would leave+# seven doors open.++test_k8s_cluster_events_non_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/events",+ "params": {"path": "api/v1/events"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++# Admin is the escape hatch over is_infra_k8s_path. It is not one over events:+# the deny sits above the whole disjunction.+test_k8s_cluster_events_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/events",+ "params": {"path": "api/v1/events"},+ "user": {"sub": "admin-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": ["admin-1"]},+ }+}++test_k8s_cluster_event_item_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/events/evt-1",+ "params": {"path": "api/v1/events/evt-1"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_namespaced_events_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/namespaces/foo/events",+ "params": {"path": "api/v1/namespaces/foo/events"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_namespaced_events_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/namespaces/foo/events",+ "params": {"path": "api/v1/namespaces/foo/events"},+ "user": {"sub": "admin-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": ["admin-1"]},+ }+}++test_k8s_namespaced_event_item_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/namespaces/foo/events/evt-1",+ "params": {"path": "api/v1/namespaces/foo/events/evt-1"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++# A user API key is the other family that reaches customer-facing paths.+test_user_api_key_k8s_events_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/namespaces/foo/events",+ "params": {"path": "api/v1/namespaces/foo/events"},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++# A GitHub OIDC token is granted ns-a, and the grant does not reach events.+# This one holds twice over — github_k8s_request_allowed only ever matches+# apis/<group>/... CRD paths, so it would deny a core/v1 event path anyway. It is+# here so that widening that grant cannot open events by accident.+test_github_k8s_events_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "params": {"path": "api/v1/namespaces/ns-a/events"},+ "user": {+ "sub": "owner-1",+ "principal_type": "github_oidc",+ "allowed_namespaces": ["ns-a"],+ },+ "flags": {"admin_subs": []},+ }+}++# ── The events.k8s.io group serves the same objects ─────────────────────────++test_k8s_group_cluster_events_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/events.k8s.io/v1/events",+ "params": {"path": "apis/events.k8s.io/v1/events"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_group_cluster_events_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/events.k8s.io/v1/events",+ "params": {"path": "apis/events.k8s.io/v1/events"},+ "user": {"sub": "admin-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": ["admin-1"]},+ }+}++test_k8s_group_namespaced_events_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/events.k8s.io/v1/namespaces/foo/events",+ "params": {"path": "apis/events.k8s.io/v1/namespaces/foo/events"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_group_event_item_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/events.k8s.io/v1/namespaces/foo/events/evt-1",+ "params": {"path": "apis/events.k8s.io/v1/namespaces/foo/events/evt-1"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++# The version is matched positionally, so a cluster serving the older group+# version is covered without naming it.+test_k8s_group_other_version_events_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/events.k8s.io/v1beta1/events",+ "params": {"path": "apis/events.k8s.io/v1beta1/events"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++# ── The legacy /watch/ aliases stream the same objects ──────────────────────+#+# Deprecated since 1.11 and still served. The response is a stream of whole+# Event objects, so a deny that missed these would be a deny in name only.++test_k8s_legacy_watch_cluster_events_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/watch/events",+ "params": {"path": "api/v1/watch/events"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_legacy_watch_namespaced_events_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/watch/namespaces/foo/events",+ "params": {"path": "api/v1/watch/namespaces/foo/events"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_legacy_watch_group_events_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/events.k8s.io/v1/watch/events",+ "params": {"path": "apis/events.k8s.io/v1/watch/events"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_legacy_watch_group_namespaced_events_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/events.k8s.io/v1/watch/namespaces/foo/events",+ "params": {"path": "apis/events.k8s.io/v1/watch/namespaces/foo/events"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++# ── Predicate precision ─────────────────────────────────────────────────────+#+# These assert is_event_k8s_path and is_infra_k8s_path directly rather than+# through route_allow, and they have to. Both predicates exist to be *exact*:+# an event path is denied, a path that merely resembles one is not. Under the+# old denylist that distinction was visible in the route verdict, because a+# non-event path fell through to "allowed". Under an allowlist everything+# unenumerated is denied either way, so a route-level test can no longer tell a+# precise predicate from a hopelessly broad one -- both produce a deny.+#+# Asserting the predicate keeps the property under test. A prefix match instead+# of a segment comparison still fails here, which is what the mutation runs+# check.++test_event_predicate_does_not_match_lookalikes if {+ not authz_k8s.is_event_k8s_path("api/v1/eventsources")+ not authz_k8s.is_event_k8s_path("api/v1/namespaces/foo/eventsources")++ # "events" as the namespace, not as the resource.+ not authz_k8s.is_event_k8s_path("api/v1/namespaces/events/pods")++ # A namespaced resource whose name happens to be "events".+ not authz_k8s.is_event_k8s_path("api/v1/namespaces/foo/configmaps/events")++ # A group that merely starts with the events group is a different group.+ not authz_k8s.is_event_k8s_path("apis/events.k8s.io.evil/v1/events")+ not authz_k8s.is_event_k8s_path("apis/notevents.k8s.io/v1/events")++ # A neighbouring resource inside the events group is not the Event resource.+ not authz_k8s.is_event_k8s_path("apis/events.k8s.io/v1/eventsources")++ # A watch on something that is not an event.+ not authz_k8s.is_event_k8s_path("api/v1/watch/namespaces/foo/pods")+}++test_event_predicate_matches_every_served_shape if {+ authz_k8s.is_event_k8s_path("api/v1/events")+ authz_k8s.is_event_k8s_path("api/v1/events/evt-1")+ authz_k8s.is_event_k8s_path("api/v1/namespaces/foo/events")+ authz_k8s.is_event_k8s_path("api/v1/namespaces/foo/events/evt-1")+ authz_k8s.is_event_k8s_path("api/v1/watch/events")+ authz_k8s.is_event_k8s_path("api/v1/watch/namespaces/foo/events")+ authz_k8s.is_event_k8s_path("apis/events.k8s.io/v1/events")+ authz_k8s.is_event_k8s_path("apis/events.k8s.io/v1beta1/events")+ authz_k8s.is_event_k8s_path("apis/events.k8s.io/v1/namespaces/foo/events")+ authz_k8s.is_event_k8s_path("apis/events.k8s.io/v1/watch/events")+ authz_k8s.is_event_k8s_path("apis/events.k8s.io/v1/watch/namespaces/foo/events")+}++# The Capsule group is likewise compared whole, and "tenantowners" is a+# different resource from "tenants".+test_infra_predicate_does_not_match_lookalikes if {+ not authz_k8s.is_infra_k8s_path("apis/capsule.clastix.io/v1beta2/tenantowners")+ not authz_k8s.is_infra_k8s_path("apis/capsule.clastix.io.evil/v1beta2/tenants")+ not authz_k8s.is_infra_k8s_path("api/v1/namespaces/foo/pods")+}++# Cluster-wide CRD lists leak every tenant's pools/claims. Nobody gets them:+# the allowlist admits the namespaced form only.+test_k8s_cluster_pools_non_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/cua.ai/v1/osgymworkspacepools",+ "params": {"path": "apis/cua.ai/v1/osgymworkspacepools"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_cluster_pools_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/cua.ai/v1/osgymworkspacepools",+ "params": {"path": "apis/cua.ai/v1/osgymworkspacepools"},+ "user": {"sub": "admin-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": ["admin-1"]},+ }+}++test_k8s_cluster_claims_non_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims",+ "params": {"path": "apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_capsule_tenants_non_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "POST",+ "path": "/api/k8s/apis/capsule.clastix.io/v1beta2/tenants",+ "params": {"path": "apis/capsule.clastix.io/v1beta2/tenants"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_capsule_tenants_user_key_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "POST",+ "path": "/api/k8s/apis/capsule.clastix.io/v1beta2/tenants",+ "params": {"path": "apis/capsule.clastix.io/v1beta2/tenants"},+ "user": {"sub": "user-1", "azp": "ukey-user-1", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_capsule_tenant_item_non_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/capsule.clastix.io/v1beta2/tenants/user-user-1",+ "params": {"path": "apis/capsule.clastix.io/v1beta2/tenants/user-user-1"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_capsule_tenants_other_versions_non_admin_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "POST",+ "path": "/api/k8s/apis/capsule.clastix.io/v1beta1/tenants",+ "params": {"path": "apis/capsule.clastix.io/v1beta1/tenants"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }++ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/capsule.clastix.io/v99/tenants/user-user-1/status",+ "params": {"path": "apis/capsule.clastix.io/v99/tenants/user-user-1/status"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++# These two used to assert that the Capsule neighbours fall through to allowed.+# They are denied now, like everything unenumerated, so the property they were+# guarding -- that is_infra_k8s_path is exact -- moved to+# test_infra_predicate_does_not_match_lookalikes above.+test_k8s_capsule_neighbor_paths_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/capsule.clastix.io/v1beta2/tenantowners",+ "params": {"path": "apis/capsule.clastix.io/v1beta2/tenantowners"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++# Namespaced pool/claim lists are how the SPA reads them — stay open+# (Capsule RBAC scopes the caller to their own namespaces).+test_k8s_namespaced_pools_non_admin_allowed if {+ route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/cua.ai/v1/namespaces/foo/osgymworkspacepools",+ "params": {"path": "apis/cua.ai/v1/namespaces/foo/osgymworkspacepools"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_k8s_namespaced_claims_non_admin_allowed if {+ route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/foo/osgymsandboxclaims",+ "params": {"path": "apis/osgym.cua.ai/v1alpha1/namespaces/foo/osgymsandboxclaims"},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++# Non-SPA tokens are denied on /api/k8s even if listed as admin.+test_k8s_non_spa_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/namespaces/foo/pods",+ "params": {"path": "api/v1/namespaces/foo/pods"},+ "user": {"sub": "admin-1", "azp": "key-foo", "namespace": "foo", "email": ""},+ "flags": {"admin_subs": ["admin-1"]},+ }+}++test_user_api_key_k8s_customer_path_allowed if {+ route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/namespaces/foo/pods",+ "params": {"path": "api/v1/namespaces/foo/pods"},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_user_api_key_k8s_infra_path_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": "/api/k8s/api/v1/nodes",+ "params": {"path": "api/v1/nodes"},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+ }+}++test_github_k8s_allowed_namespace_collection_get if {+ route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "params": {"path": "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools"},+ "user": {+ "sub": "owner-1",+ "principal_type": "github_oidc",+ "allowed_namespaces": ["ns-a"],+ },+ "flags": {"admin_subs": []},+ }+}++test_github_k8s_outside_namespace_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "params": {"path": "apis/cua.ai/v1/namespaces/ns-b/osgymworkspacepools"},+ "user": {+ "sub": "owner-1",+ "principal_type": "github_oidc",+ "allowed_namespaces": ["ns-a"],+ },+ "flags": {"admin_subs": []},+ }+}++test_github_k8s_template_write_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "POST",+ "params": {"path": "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxtemplates"},+ "user": {+ "sub": "owner-1",+ "principal_type": "github_oidc",+ "allowed_namespaces": ["ns-a"],+ },+ "flags": {"admin_subs": []},+ }+}++test_github_k8s_claim_subresource_denied if {+ not route_allow with input as {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "params": {"path": "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims/claim-a/status"},+ "user": {+ "sub": "owner-1",+ "principal_type": "github_oidc",+ "allowed_namespaces": ["ns-a"],+ },+ "flags": {"admin_subs": []},+ }+}++# ── The allowlist ───────────────────────────────────────────────────────────+#+# One test per admitted block, and then the denials that make it an allowlist+# rather than a longer denylist. `spa` stands for the interactive family+# throughout; test_user_key_gets_the_same_allowlist pins that user keys reach+# the same set.++spa_request(method, path) := {+ "route": "/api/k8s/{path...}",+ "method": method,+ "path": sprintf("/api/k8s/%s", [path]),+ "params": {"path": path},+ "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ "flags": {"admin_subs": []},+}++# Fleet CRDs, native group: the full matrix, on all three resources.+test_native_fleet_crud_allowed if {+ every resource in ["osgymsandboxclaims", "osgymsandboxwarmpools", "osgymsandboxtemplates"] {+ collection := sprintf("apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/%s", [resource])+ item := sprintf("%s/thing-1", [collection])++ route_allow with input as spa_request("GET", collection)+ route_allow with input as spa_request("POST", collection)+ route_allow with input as spa_request("GET", item)+ route_allow with input as spa_request("PATCH", item)+ route_allow with input as spa_request("DELETE", item)+ route_allow with input as spa_request("PATCH", sprintf("%s/status", [item]))+ }+}++# Legacy pools, including the PUT that production shows succeeding and no rule+# had ever named.+test_legacy_pool_crud_allowed if {+ collection := "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools"+ item := sprintf("%s/pool-1", [collection])++ route_allow with input as spa_request("GET", collection)+ route_allow with input as spa_request("POST", collection)+ route_allow with input as spa_request("GET", item)+ route_allow with input as spa_request("PATCH", item)+ route_allow with input as spa_request("DELETE", item)+ route_allow with input as spa_request("PUT", item)+}++# Core reads: pods, pod logs, services.+test_core_reads_allowed if {+ route_allow with input as spa_request("GET", "api/v1/namespaces/ns-a/pods")+ route_allow with input as spa_request("GET", "api/v1/namespaces/ns-a/pods/pod-1")+ route_allow with input as spa_request("GET", "api/v1/namespaces/ns-a/pods/pod-1/log")+ route_allow with input as spa_request("GET", "api/v1/namespaces/ns-a/services")+ route_allow with input as spa_request("GET", "api/v1/namespaces/ns-a/services/svc-1")+}++test_pod_metrics_allowed if {+ route_allow with input as spa_request("GET", "apis/metrics.k8s.io/v1beta1/namespaces/ns-a/pods")+ route_allow with input as spa_request("GET", "apis/metrics.k8s.io/v1beta1/namespaces/ns-a/pods/pod-1")+}++test_kubevirt_reads_allowed if {+ route_allow with input as spa_request("GET", "apis/kubevirt.io/v1/namespaces/ns-a/virtualmachines")+ route_allow with input as spa_request("GET", "apis/kubevirt.io/v1/namespaces/ns-a/virtualmachineinstances/vmi-1")+}++test_discovery_allowed if {+ route_allow with input as spa_request("GET", "openapi/v2")+ route_allow with input as spa_request("GET", "openapi/v3/apis/cua.ai/v1")+ route_allow with input as spa_request("GET", "apis/cua.ai/v1")+ route_allow with input as spa_request("GET", "apis")+}++test_self_subject_access_review_allowed if {+ route_allow with input as spa_request("POST", "apis/authorization.k8s.io/v1/selfsubjectaccessreviews")+}++test_user_key_gets_the_same_allowlist if {+ request := object.union(+ spa_request("GET", "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims"),+ {"user": {"sub": "user-1", "azp": "ukey-abc", "namespace": "", "email": ""}},+ )++ route_allow with input as request+}++# ── Denials: the point of the posture ───────────────────────────────────────+#+# None of these is on any exclusion list. They are denied because nothing+# admits them, which is the whole difference from the denylist this replaced.++test_unenumerated_core_resources_denied if {+ not route_allow with input as spa_request("GET", "api/v1/namespaces/ns-a/secrets")+ not route_allow with input as spa_request("GET", "api/v1/namespaces/ns-a/secrets/ecr-credentials")+ not route_allow with input as spa_request("GET", "api/v1/namespaces/ns-a/configmaps")+ not route_allow with input as spa_request("GET", "api/v1/namespaces/ns-a/serviceaccounts/default")+ not route_allow with input as spa_request("GET", "api/v1/namespaces/ns-a/persistentvolumeclaims")+ not route_allow with input as spa_request("GET", "api/v1/namespaces/ns-a/resourcequotas")+}++# A resource may be readable without being writable. Nothing in traffic or in+# this repo writes a core resource through this proxy.+test_core_writes_denied if {+ not route_allow with input as spa_request("POST", "api/v1/namespaces/ns-a/pods")+ not route_allow with input as spa_request("DELETE", "api/v1/namespaces/ns-a/pods/pod-1")+ not route_allow with input as spa_request("POST", "api/v1/namespaces/ns-a/persistentvolumeclaims")+}++# Known group, unknown resource; and known resource, unknown verb.+test_unenumerated_resource_and_verb_denied if {+ not route_allow with input as spa_request("GET", "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxes")+ not route_allow with input as spa_request("PUT", "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims/claim-1")+}++# An entire API group nobody enumerated. These three all succeeded in+# production as single one-off calls; they are the tail the allowlist+# deliberately drops.+test_unenumerated_groups_denied if {+ not route_allow with input as spa_request("GET", "apis/storage.k8s.io/v1/storageclasses")+ not route_allow with input as spa_request("GET", "apis/external-secrets.io/v1beta1/namespaces/ns-a/externalsecrets")+ not route_allow with input as spa_request("GET", "apis/cdi.kubevirt.io/v1beta1/namespaces/ns-a/datavolumes")+}++# KubeVirt is readable, not drivable.+test_kubevirt_writes_denied if {+ not route_allow with input as spa_request("DELETE", "apis/kubevirt.io/v1/namespaces/ns-a/virtualmachines/vm-1")+ not route_allow with input as spa_request("PUT", "apis/subresources.kubevirt.io/v1/namespaces/ns-a/virtualmachines/vm-1/restart")+}++# The cluster-scoped form of an admitted resource is not admitted: every rule+# above requires the namespaces/{ns} segment.+test_cluster_scoped_forms_denied if {+ not route_allow with input as spa_request("GET", "apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims")+ not route_allow with input as spa_request("GET", "api/v1/pods")+ not route_allow with input as spa_request("GET", "apis/metrics.k8s.io/v1beta1/nodes")+}++# An empty namespace segment addresses the cluster-wide collection on a real+# apiserver, so it must not satisfy a namespaced rule.+test_empty_namespace_segment_denied if {+ not route_allow with input as spa_request("GET", "apis/osgym.cua.ai/v1alpha1/namespaces//osgymsandboxclaims")+ not route_allow with input as spa_request("GET", "api/v1/namespaces//pods")+}++# ── The legacy /watch/ alias agrees with the path it aliases ────────────────+#+# api/v1/watch/pods streams exactly what api/v1/pods lists, so the two must+# answer the same. They did not: is_infra_k8s_path matched the literal spelling+# and the alias walked past it. The bar here is agreement, not "the alias is+# denied" -- a rule that denied every watch path would pass the second and be+# wrong, because namespaced pod watches are customer-facing.++infra_pairs := [+ ["api/v1/pods", "api/v1/watch/pods"],+ ["api/v1/nodes", "api/v1/watch/nodes"],+ ["api/v1/nodes/ip-10-0-0-1", "api/v1/watch/nodes/ip-10-0-0-1"],+ ["api/v1/namespaces/cyclops-cs/configmaps", "api/v1/watch/namespaces/cyclops-cs/configmaps"],+ ["apis/cua.ai/v1/osgymworkspacepools", "apis/cua.ai/v1/watch/osgymworkspacepools"],+ ["apis/capsule.clastix.io/v1beta2/tenants", "apis/capsule.clastix.io/v1beta2/watch/tenants"],+]++# Both spellings are infra.+test_watch_alias_agrees_with_literal_on_infra_paths if {+ every pair in infra_pairs {+ authz_k8s.is_infra_k8s_path(pair[0])+ authz_k8s.is_infra_k8s_path(pair[1])+ }+}++# And both spellings are not, where the literal is not. Namespaced pods are the+# case that matters: a blanket "deny anything with /watch/" would break them.+open_pairs := [+ ["api/v1/namespaces/foo/pods", "api/v1/watch/namespaces/foo/pods"],+ ["api/v1/namespaces/foo/services", "api/v1/watch/namespaces/foo/services"],+ ["apis/osgym.cua.ai/v1alpha1/namespaces/foo/osgymsandboxclaims", "apis/osgym.cua.ai/v1alpha1/watch/namespaces/foo/osgymsandboxclaims"],+]++test_watch_alias_agrees_with_literal_on_open_paths if {+ every pair in open_pairs {+ not authz_k8s.is_infra_k8s_path(pair[0])+ not authz_k8s.is_infra_k8s_path(pair[1])+ }+}++# The rewrite must not fire on a path that merely contains the word. "watch" as+# a namespace name, or as a resource name, is not the alias infix.+test_watch_rewrite_does_not_overreach if {+ not authz_k8s.is_infra_k8s_path("api/v1/namespaces/watch/pods")+ not authz_k8s.is_infra_k8s_path("api/v1/watchdogs")+ not authz_k8s.is_infra_k8s_path("apis/cua.ai/v1/namespaces/foo/watch")++ # The infix has to be "watch" specifically. A rewrite that stripped whatever+ # segment sat in that position would map these onto "api/v1/pods" and+ # "api/v1/nodes" and deny them as infra aliases, which they are not.+ not authz_k8s.is_infra_k8s_path("api/v1/foo/pods")+ not authz_k8s.is_infra_k8s_path("api/v1/namespaces/nodes")+ not authz_k8s.is_infra_k8s_path("apis/cua.ai/v1/proxy/osgymworkspacepools")+}++# At the route level, for every principal family this surface admits: the alias+# and the literal produce the same verdict. Both are denied today -- the alias+# because nothing enumerates it, the literal because nothing enumerates it+# either -- and this pins that they cannot come apart.+test_watch_alias_and_literal_agree_for_every_principal if {+ every azp in ["cyclops-cs-spa", "cua-cli", "ukey-abc"] {+ not route_allow with input as watch_request(azp, "api/v1/pods", false)+ not route_allow with input as watch_request(azp, "api/v1/watch/pods", false)+ not route_allow with input as watch_request(azp, "api/v1/nodes", false)+ not route_allow with input as watch_request(azp, "api/v1/watch/nodes", false)+ }+}++# Admin too. Under the denylist is_admin bypassed the infra list, so the alias+# and the literal could have disagreed for exactly this principal; the allowlist+# removed that bypass and this is what pins it.+test_watch_alias_and_literal_agree_for_admin if {+ not route_allow with input as watch_request("cyclops-cs-spa", "api/v1/pods", true)+ not route_allow with input as watch_request("cyclops-cs-spa", "api/v1/watch/pods", true)+ not route_allow with input as watch_request("cyclops-cs-spa", "api/v1/nodes", true)+ not route_allow with input as watch_request("cyclops-cs-spa", "api/v1/watch/nodes", true)+}++# Namespaced pods stay reachable in both spellings for a normal caller... or+# rather, the literal does; the watch spelling is not on the allowlist, which is+# a separate decision from the infra deny and is recorded as such.+test_namespaced_pod_literal_still_allowed if {+ route_allow with input as watch_request("cyclops-cs-spa", "api/v1/namespaces/foo/pods", false)+}++watch_request(azp, path, admin) := {+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "path": sprintf("/api/k8s/%s", [path]),+ "params": {"path": path},+ "user": {"sub": watch_sub(admin), "azp": azp, "namespace": "", "email": ""},+ "flags": {"admin_subs": watch_admin_subs(admin)},+}++watch_sub(admin) := "admin-1" if {+ admin+}++watch_sub(admin) := "user-1" if {+ not admin+}++watch_admin_subs(admin) := ["admin-1"] if {+ admin+}++watch_admin_subs(admin) := [] if {+ not admin+}diff --git a/libs/fleet/backend/auth/authz_keys.rego b/libs/fleet/backend/auth/authz_keys.regonew file mode 100644index 0000000000..ffb9cac3bd--- /dev/null+++ b/libs/fleet/backend/auth/authz_keys.rego@@ -0,0 +1,21 @@+# /api/keys (POST/GET) and /api/keys/{id} (DELETE) — CRUD on the per-pool+# service-account clients in Keycloak.+#+# Exact interactive clients only. A per-key client must not be able to mint more+# per-key clients, and a user key must not either: key issuance is a dashboard+# action, so it stays on a token a human obtained interactively.+package authz_keys++import data.authz++default allow = false++allow {+ input.route == "/api/keys"+ authz.is_interactive_client+}++allow {+ input.route == "/api/keys/{id}"+ authz.is_interactive_client+}diff --git a/libs/fleet/backend/auth/authz_keys_test.rego b/libs/fleet/backend/auth/authz_keys_test.regonew file mode 100644index 0000000000..c71fd52fca--- /dev/null+++ b/libs/fleet/backend/auth/authz_keys_test.rego@@ -0,0 +1,56 @@+# What /api/keys and /api/keys/{id} runs: All(authz_base.allow, authz_keys.allow).+#+# route_allow below is that composition, so every case asserts the verdict the+# route produces rather than one module's half of it. Splitting the policy must+# not turn a test of the whole check into a test of a fragment.+package authz_keys_test++import rego.v1++import data.authz_base+import data.authz_keys++route_allow if {+ authz_base.allow+ authz_keys.allow+}++test_keys_spa_allowed if {+ route_allow with input as {+ "route": "/api/keys",+ "method": "POST",+ "path": "/api/keys",+ "params": {},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_keys_cua_cli_allowed if {+ route_allow with input as {+ "route": "/api/keys",+ "method": "POST",+ "path": "/api/keys",+ "params": {},+ "user": {"sub": "user-123", "azp": "cua-cli", "namespace": "", "email": "[email protected]"},+ }+}++test_keys_other_interactive_client_denied if {+ not route_allow with input as {+ "route": "/api/keys",+ "method": "POST",+ "path": "/api/keys",+ "params": {},+ "user": {"sub": "user-123", "azp": "kubernetes", "namespace": "", "email": "[email protected]"},+ }+}++test_keys_non_spa_denied if {+ not route_allow with input as {+ "route": "/api/keys",+ "method": "POST",+ "path": "/api/keys",+ "params": {},+ "user": {"sub": "user-123", "azp": "key-some-pool", "namespace": "some-pool", "email": "[email protected]"},+ }+}diff --git a/libs/fleet/backend/auth/authz_namespaces.rego b/libs/fleet/backend/auth/authz_namespaces.regonew file mode 100644index 0000000000..5f3f6a0afe--- /dev/null+++ b/libs/fleet/backend/auth/authz_namespaces.rego@@ -0,0 +1,51 @@+# /api/namespaces and /api/namespaces/{name} — namespace management+# (list, create, get, delete).+#+# Three principal families reach this surface, and none of them is scoped here:+# Capsule enforces per-user ownership at the K8s API level, via the impersonation+# headers the backend adds. So these rules authenticate the family and leave+# ownership to Capsule.+#+# With one exception, which is not in this module: GET /api/namespaces/{name}+# also runs the ownership conjunct (authz_ownership.rego), because it used to+# run the same check in Go after reading the namespace back. The other three+# routes on this surface pass that conjunct unconditionally.+#+# Per-key clients are absent on purpose. Their sub is a service account that owns+# no namespace, so impersonating it would produce an empty list rather than a+# denial, which reads as "you have none" instead of "you may not ask".+package authz_namespaces++import data.authz++default allow = false++allow {+ input.route == "/api/namespaces"+ authz.is_interactive_client+}++allow {+ input.route == "/api/namespaces/{name}"+ authz.is_interactive_client+}++allow {+ input.route == "/api/namespaces"+ input.user.principal_type == "github_oidc"+}++allow {+ input.route == "/api/namespaces/{name}"+ input.user.principal_type == "github_oidc"+}++allow {+ input.route == "/api/namespaces"+ authz.is_user_key_client+}++allow {+ input.route == "/api/namespaces/{name}"+ authz.is_user_key_client+}diff --git a/libs/fleet/backend/auth/authz_namespaces_test.rego b/libs/fleet/backend/auth/authz_namespaces_test.regonew file mode 100644index 0000000000..174707e828--- /dev/null+++ b/libs/fleet/backend/auth/authz_namespaces_test.rego@@ -0,0 +1,120 @@+# What /api/namespaces and /api/namespaces/{name} runs: All(authz_base.allow, authz_namespaces.allow).+#+# route_allow below is that composition, so every case asserts the verdict the+# route produces rather than one module's half of it. Splitting the policy must+# not turn a test of the whole check into a test of a fragment.+package authz_namespaces_test++import rego.v1++import data.authz_base+import data.authz_namespaces++route_allow if {+ authz_base.allow+ authz_namespaces.allow+}++test_namespaces_spa_list_allowed if {+ route_allow with input as {+ "route": "/api/namespaces",+ "method": "GET",+ "path": "/api/namespaces",+ "params": {},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_namespaces_spa_create_allowed if {+ route_allow with input as {+ "route": "/api/namespaces/{name}",+ "method": "POST",+ "path": "/api/namespaces/my-ns",+ "params": {"name": "my-ns"},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_namespaces_spa_delete_allowed if {+ route_allow with input as {+ "route": "/api/namespaces/{name}",+ "method": "DELETE",+ "path": "/api/namespaces/my-ns",+ "params": {"name": "my-ns"},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++# Per-key clients (key-*) CANNOT access namespace routes.+test_namespaces_per_key_list_denied if {+ not route_allow with input as {+ "route": "/api/namespaces",+ "method": "GET",+ "path": "/api/namespaces",+ "params": {},+ "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},+ }+}++test_namespaces_per_key_by_name_denied if {+ not route_allow with input as {+ "route": "/api/namespaces/{name}",+ "method": "DELETE",+ "path": "/api/namespaces/my-ns",+ "params": {"name": "my-ns"},+ "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},+ }+}++# Empty sub denied on namespace routes.+test_namespaces_empty_sub_denied if {+ not route_allow with input as {+ "route": "/api/namespaces",+ "method": "GET",+ "path": "/api/namespaces",+ "params": {},+ "user": {"sub": "", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++# Missing azp denied on namespace routes.+test_namespaces_missing_azp_denied if {+ not route_allow with input as {+ "route": "/api/namespaces",+ "method": "GET",+ "path": "/api/namespaces",+ "params": {},+ "user": {"sub": "user-123", "azp": "", "namespace": "", "email": "[email protected]"},+ }+}++test_user_api_key_namespaces_allowed if {+ route_allow with input as {+ "route": "/api/namespaces",+ "method": "GET",+ "path": "/api/namespaces",+ "params": {},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ }+}++test_user_api_key_namespaces_delete_allowed if {+ route_allow with input as {+ "route": "/api/namespaces/{name}",+ "method": "DELETE",+ "path": "/api/namespaces/my-ns",+ "params": {"name": "my-ns"},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ }+}++# User-key clients with empty sub are denied.+test_user_api_key_no_sub_denied if {+ not route_allow with input as {+ "route": "/api/namespaces",+ "method": "GET",+ "path": "/api/namespaces",+ "params": {},+ "user": {"sub": "", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ }+}diff --git a/libs/fleet/backend/auth/authz_orch.rego b/libs/fleet/backend/auth/authz_orch.regonew file mode 100644index 0000000000..9928e6ebb2--- /dev/null+++ b/libs/fleet/backend/auth/authz_orch.rego@@ -0,0 +1,31 @@+# /api/orch/{namespace}/{service}/{path...} — per-namespace orchestrator+# catalog read.+#+# Like /api/svc, this proxy dials Service DNS directly rather than traversing the+# K8s API, so Capsule cannot scope it. This module authenticates the family and+# shape-checks the parameters; namespace ownership is the third conjunct of+# OrchRoutePolicy, authz_ownership.rego, which reads the impersonated RoleBinding+# probe as input.facts.namespace_rbac.+#+# Per-key clients match neither rule below, so they never reach that conjunct:+# their sub is a service account that owns nothing, and their namespace claim is+# not what this surface is scoped by.+package authz_orch++import data.authz++default allow = false++allow {+ input.route == "/api/orch/{namespace}/{service}/{path...}"+ authz.is_interactive_client+ authz.valid_dns_label(input.params.namespace)+ authz.valid_dns_label(input.params.service)+}++allow {+ input.route == "/api/orch/{namespace}/{service}/{path...}"+ authz.is_user_key_client+ authz.valid_dns_label(input.params.namespace)+ authz.valid_dns_label(input.params.service)+}diff --git a/libs/fleet/backend/auth/authz_orch_test.rego b/libs/fleet/backend/auth/authz_orch_test.regonew file mode 100644index 0000000000..7a5b3d6df6--- /dev/null+++ b/libs/fleet/backend/auth/authz_orch_test.rego@@ -0,0 +1,46 @@+# What /api/orch/{namespace}/{service}/{path...} runs: All(authz_base.allow, authz_orch.allow).+#+# route_allow below is that composition, so every case asserts the verdict the+# route produces rather than one module's half of it. Splitting the policy must+# not turn a test of the whole check into a test of a fragment.+package authz_orch_test++import rego.v1++import data.authz_base+import data.authz_orch++route_allow if {+ authz_base.allow+ authz_orch.allow+}++test_orch_spa_allowed if {+ route_allow with input as {+ "route": "/api/orch/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/orch/mypool/mypool-orchestrator/status",+ "params": {"namespace": "mypool", "service": "mypool-orchestrator", "path": "status"},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_orch_cua_cli_allowed if {+ route_allow with input as {+ "route": "/api/orch/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/orch/mypool/mypool-orchestrator/status",+ "params": {"namespace": "mypool", "service": "mypool-orchestrator", "path": "status"},+ "user": {"sub": "user-123", "azp": "cua-cli", "namespace": "", "email": "[email protected]"},+ }+}++test_user_api_key_orch_allowed if {+ route_allow with input as {+ "route": "/api/orch/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/orch/mypool/mypool-orchestrator/status",+ "params": {"namespace": "mypool", "service": "mypool-orchestrator", "path": "status"},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ }+}diff --git a/libs/fleet/backend/auth/authz_ownership.rego b/libs/fleet/backend/auth/authz_ownership.regonew file mode 100644index 0000000000..0f69846cda--- /dev/null+++ b/libs/fleet/backend/auth/authz_ownership.rego@@ -0,0 +1,139 @@+# Namespace ownership — the tenancy boundary for the routes that name a+# namespace in their path.+#+# This is the one authorization question the policy could not answer before,+# because answering it needs something no token carries: whether Kubernetes+# would let this subject act in that namespace. It lived in Go+# (handlers.requireNamespaceAccess) for exactly that reason. It lives here now+# because the missing half arrives as `input.facts.namespace_rbac`, loaded by a+# FactProvider that wraps the same impersonated RoleBinding probe the handler+# ran — see NamespaceOwnershipPolicy in policy_routes.go.+#+# The decision is three cases, and they are three rules rather than one because+# only the third costs a network round trip:+#+# 1. GitHub OIDC principals — the trust policy's allowed_namespaces claim IS+# the grant. The token was minted against a policy that named them.+# 2. Per-key clients — bound to one namespace by their `namespace` claim.+# 3. Everyone else (SPA users, user keys, oauth2-proxy sessions, MCP+# connector clients) — must hold RBAC in the namespace.+#+# Cases 1 and 2 are claim_allow; case 3 is probe_eligible AND rbac_allow. The+# split is what keeps the probe off the request path for everyone the claims+# already answer for: the plan is Any(claim_allow, All(probe_eligible,+# rbac_allow)), and a fold that stops at the first `true` never evaluates the+# leaf carrying the fact provider, so the fact is never loaded. probe_eligible+# is the same trick in the other direction — a principal the probe cannot speak+# for (a GitHub token, a per-key service account) denies the conjunction before+# the loader is reached.+#+# The order of the cases matters and matches the Go code it replaces: a GitHub+# principal is judged by its claim even if its azp also looked like a per-key+# client's, which is why cases 2 and 3 exclude it explicitly rather than relying+# on the families being disjoint.+package authz_ownership++import data.authz++default claim_allow = false++default probe_eligible = false++default rbac_allow = false++# ── Where the boundary applies ──────────────────────────────────────────────+#+# These are exactly the call sites requireNamespaceAccess had. The /api/svc and+# /api/orch proxies dial {service}.{namespace}.svc.cluster.local directly, so+# Capsule cannot scope them; /api/namespaces/{name} GET reads one namespace+# through the K8s API and wants the same answer without trusting the read.+#+# DELETE on /api/namespaces/{name} is deliberately absent: it never ran this+# check. It goes to the K8s API impersonated, where Capsule is the boundary, and+# its own GitHub-claim check lives in the handler.+applies {+ input.route == "/api/svc/{namespace}/{service}"+}++applies {+ input.route == "/api/svc/{namespace}/{service}/{path...}"+}++applies {+ input.route == "/api/orch/{namespace}/{service}/{path...}"+}++applies {+ input.route == "/api/namespaces/{name}"+ input.method == "GET"+}++# target_namespace is the namespace this request is about: /api/svc and+# /api/orch name it {namespace}, /api/namespaces/{name} names it {name}. Keyed+# off which parameter the route bound rather than off the route itself, so the+# two lists cannot disagree — and mirrored in Go by auth.OwnedNamespace, which+# is what the fact provider probes and what TestOwnedNamespaceMatchesRego pins+# against these rules.+#+# An empty {namespace} still takes the first rule: "" is a defined value, so the+# `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 {+ input.params.namespace+}++target_namespace = input.params.name {+ not input.params.namespace+}++# ── The three cases ─────────────────────────────────────────────────────────++# GitHub OIDC: the claim is the grant, and no probe could improve on it — the+# impersonated subject is the owner who installed the trust policy, not the+# workflow calling through it.+claim_allow {+ applies+ is_github_principal+ input.user.allowed_namespaces[_] == target_namespace+}++# Per-key clients: the claim IS the grant. Their sub is a Keycloak service+# account that owns nothing, so a probe would deny a legitimate caller.+claim_allow {+ applies+ not is_github_principal+ authz.is_per_key_client+ target_namespace != ""+ input.user.namespace == target_namespace+}++# A route this boundary does not cover passes it unconditionally. The conjunct+# is attached per surface, and a surface can hold routes on both sides of the+# boundary — /api/namespaces is one — so "does not apply" has to be an allow+# here rather than an absence there.+claim_allow {+ not applies+}++# probe_eligible reports whether a K8s RBAC probe can speak for this principal+# at all. It is a leaf of its own so that All(probe_eligible, rbac_allow) can+# deny before the fact provider is asked: this is the cheap check the optimizer+# sinks the loader behind.+probe_eligible {+ applies+ not is_github_principal+ not authz.is_per_key_client+ target_namespace != ""+}++# The probe's answer. probe_eligible is restated rather than assumed, because a+# rule that reads a fact must be safe to evaluate on its own — the plan's+# ordering is a performance property, not a correctness one.+rbac_allow {+ probe_eligible+ input.facts.namespace_rbac.allowed == true+}++is_github_principal {+ input.user.principal_type == "github_oidc"+}diff --git a/libs/fleet/backend/auth/authz_ownership_test.rego b/libs/fleet/backend/auth/authz_ownership_test.regonew file mode 100644index 0000000000..92f72c9677--- /dev/null+++ b/libs/fleet/backend/auth/authz_ownership_test.rego@@ -0,0 +1,202 @@+package authz_ownership++svc_input(user, namespace) = {+ "route": "/api/svc/{namespace}/{service}",+ "method": "GET",+ "params": {"namespace": namespace, "service": "novnc"},+ "user": user,+}++spa_user = {"sub": "u-1", "azp": "cyclops-cs-spa"}++github_user = {+ "sub": "owner-1",+ "azp": "github-oidc",+ "principal_type": "github_oidc",+ "allowed_namespaces": ["ns-a"],+}++per_key_user = {"sub": "svc-1", "azp": "key-ns-a", "namespace": "ns-a"}++# ── GitHub OIDC: the claim is the grant, and no probe is eligible ───────────++test_github_claim_allows {+ claim_allow with input as svc_input(github_user, "ns-a")+}++test_github_claim_denies_other_namespace {+ not claim_allow with input as svc_input(github_user, "ns-b")+}++# The half that keeps a GitHub token off the probe path entirely: even with a+# fact saying "allowed", the conjunction the fact sits behind is closed.+test_github_is_not_probe_eligible {+ not probe_eligible with input as svc_input(github_user, "ns-b")+}++test_github_cannot_be_allowed_by_a_fact {+ not rbac_allow with input as object.union(+ svc_input(github_user, "ns-b"),+ {"facts": {"namespace_rbac": {"allowed": true}}},+ )+}++# ── Per-key clients: bound to their namespace claim, never probed ───────────++test_per_key_claim_allows_its_namespace {+ claim_allow with input as svc_input(per_key_user, "ns-a")+}++test_per_key_claim_denies_other_namespace {+ not claim_allow with input as svc_input(per_key_user, "ns-b")+}++test_per_key_is_not_probe_eligible {+ not probe_eligible with input as svc_input(per_key_user, "ns-b")+}++test_per_key_cannot_be_allowed_by_a_fact {+ not rbac_allow with input as object.union(+ svc_input(per_key_user, "ns-b"),+ {"facts": {"namespace_rbac": {"allowed": true}}},+ )+}++# A per-key token with no namespace claim must not match an empty parameter.+test_per_key_empty_claim_denies {+ not claim_allow with input as svc_input({"sub": "svc-1", "azp": "key-x", "namespace": ""}, "")+}++# ── Everyone else: the fact decides ────────────────────────────────────────++test_spa_has_no_claim {+ not claim_allow with input as svc_input(spa_user, "ns-a")+}++test_spa_is_probe_eligible {+ probe_eligible with input as svc_input(spa_user, "ns-a")+}++test_spa_allowed_by_fact {+ rbac_allow with input as object.union(+ svc_input(spa_user, "ns-a"),+ {"facts": {"namespace_rbac": {"allowed": true}}},+ )+}++test_spa_denied_by_fact {+ not rbac_allow with input as object.union(+ svc_input(spa_user, "ns-a"),+ {"facts": {"namespace_rbac": {"allowed": false}}},+ )+}++# A missing facts document is a deny, not an allow: this is what the leaf+# evaluates to if a future edit drops its WithFacts option.+test_spa_denied_without_facts {+ not rbac_allow with input as svc_input(spa_user, "ns-a")+}++# And so is a fact of the wrong type — `== true` rather than a bare reference,+# so a provider returning a string or a number cannot authorize anything.+test_non_boolean_fact_denies {+ not rbac_allow with input as object.union(+ svc_input(spa_user, "ns-a"),+ {"facts": {"namespace_rbac": {"allowed": "true"}}},+ )+}++# An empty namespace parameter is never probed: the probe path would be+# .../namespaces//rolebindings, which is not a question about anything.+test_empty_namespace_is_not_probe_eligible {+ not probe_eligible with input as svc_input(spa_user, "")+}++# ── Where the boundary applies ─────────────────────────────────────────────++test_orch_applies {+ probe_eligible with input as {+ "route": "/api/orch/{namespace}/{service}/{path...}",+ "method": "GET",+ "params": {"namespace": "ns-a", "service": "catalog", "path": "items"},+ "user": spa_user,+ }+}++test_namespace_get_applies_and_reads_the_name_param {+ probe_eligible with input as {+ "route": "/api/namespaces/{name}",+ "method": "GET",+ "params": {"name": "ns-a"},+ "user": spa_user,+ }+}++test_namespace_get_denied_by_fact {+ not rbac_allow with input as {+ "route": "/api/namespaces/{name}",+ "method": "GET",+ "params": {"name": "ns-a"},+ "user": spa_user,+ "facts": {"namespace_rbac": {"allowed": false}},+ }+}++# DELETE on the same route never ran this check, so the conjunct has to pass+# unconditionally rather than deny — otherwise moving the check into the policy+# would have quietly locked namespace deletion.+test_namespace_delete_does_not_apply {+ claim_allow with input as {+ "route": "/api/namespaces/{name}",+ "method": "DELETE",+ "params": {"name": "ns-b"},+ "user": spa_user,+ }+}++test_namespace_delete_is_not_probe_eligible {+ not probe_eligible with input as {+ "route": "/api/namespaces/{name}",+ "method": "DELETE",+ "params": {"name": "ns-b"},+ "user": spa_user,+ }+}++# The list route shares the namespaces surface, and names no namespace at all.+test_namespace_list_does_not_apply {+ claim_allow with input as {+ "route": "/api/namespaces",+ "method": "GET",+ "params": {},+ "user": spa_user,+ }+}++test_namespace_list_is_not_probe_eligible {+ not probe_eligible with input as {+ "route": "/api/namespaces",+ "method": "GET",+ "params": {},+ "user": spa_user,+ }+}++# ── target_namespace ───────────────────────────────────────────────────────++test_target_namespace_prefers_the_namespace_param {+ target_namespace == "ns-a" with input as svc_input(spa_user, "ns-a")+}++test_target_namespace_falls_back_to_the_name_param {+ target_namespace == "ns-b" with input as {+ "route": "/api/namespaces/{name}",+ "method": "GET",+ "params": {"name": "ns-b"},+ "user": spa_user,+ }+}++test_target_namespace_empty_param_stays_empty {+ target_namespace == "" with input as svc_input(spa_user, "")+}diff --git a/libs/fleet/backend/auth/authz_state_query.rego b/libs/fleet/backend/auth/authz_state_query.regonew file mode 100644index 0000000000..e43dd11e3a--- /dev/null+++ b/libs/fleet/backend/auth/authz_state_query.rego@@ -0,0 +1,25 @@+# /api/state/query — read-only state SQL.+#+# PostgreSQL row-level security remains the row-visibility boundary; this module+# decides only who may ask.+#+# The method check is part of the surface, not incidental: the route is+# registered as QUERY only, so a request arriving under any other method reached+# it some other way and is denied here as well as by the mux.+package authz_state_query++import data.authz++default allow = false++allow {+ input.route == "/api/state/query"+ input.method == "QUERY"+ authz.is_interactive_client+}++allow {+ input.route == "/api/state/query"+ input.method == "QUERY"+ authz.is_user_key_client+}diff --git a/libs/fleet/backend/auth/authz_state_query_test.rego b/libs/fleet/backend/auth/authz_state_query_test.regonew file mode 100644index 0000000000..4dfac26628--- /dev/null+++ b/libs/fleet/backend/auth/authz_state_query_test.rego@@ -0,0 +1,66 @@+# What /api/state/query runs: All(authz_base.allow, authz_state_query.allow).+#+# route_allow below is that composition, so every case asserts the verdict the+# route produces rather than one module's half of it. Splitting the policy must+# not turn a test of the whole check into a test of a fragment.+package authz_state_query_test++import rego.v1++import data.authz_base+import data.authz_state_query++route_allow if {+ authz_base.allow+ authz_state_query.allow+}++test_state_query_spa_allowed if {+ route_allow with input as {+ "route": "/api/state/query",+ "method": "QUERY",+ "path": "/api/state/query",+ "params": {},+ "user": {"sub": "alice", "azp": "cyclops-cs-spa"},+ }+}++test_state_query_user_key_allowed if {+ route_allow with input as {+ "route": "/api/state/query",+ "method": "QUERY",+ "path": "/api/state/query",+ "params": {},+ "user": {"sub": "alice", "azp": "ukey-alice"},+ }+}++test_state_query_untrusted_client_denied if {+ not route_allow with input as {+ "route": "/api/state/query",+ "method": "QUERY",+ "path": "/api/state/query",+ "params": {},+ "user": {"sub": "alice", "azp": "untrusted"},+ }+}++test_state_query_empty_subject_denied if {+ not route_allow with input as {+ "route": "/api/state/query",+ "method": "QUERY",+ "path": "/api/state/query",+ "params": {},+ "user": {"sub": "", "azp": "cyclops-cs-spa"},+ }+}++test_state_query_post_denied if {+ not route_allow with input as {+ "route": "/api/state/query",+ "method": "POST",+ "path": "/api/state/query",+ "params": {},+ "user": {"sub": "alice", "azp": "cyclops-cs-spa"},+ }+}diff --git a/libs/fleet/backend/auth/authz_svc.rego b/libs/fleet/backend/auth/authz_svc.regonew file mode 100644index 0000000000..23c006c846--- /dev/null+++ b/libs/fleet/backend/auth/authz_svc.rego@@ -0,0 +1,51 @@+# /api/svc/{namespace}/{service}[/{path...}] — generic service proxy.+#+# This module gates authentication + parameter shape. The proxy dials+# {service}.{namespace}.svc.cluster.local directly — it never traverses the K8s+# API — so Capsule CANNOT scope it. Namespace ownership is the third conjunct of+# SvcRoutePolicy, authz_ownership.rego, which reads the impersonated RoleBinding+# probe as input.facts.namespace_rbac.+package authz_svc++import data.authz++default allow = false++# Per-key clients: the token's namespace claim must match the {namespace} param.+# authz_ownership.rego says the same thing for the same principals; this is the+# rule that keeps a per-key token from reaching the ownership conjunct at all,+# and the duplication is what makes the surface readable on its own.+allow {+ is_svc_route+ authz.is_per_key_client+ authz.valid_dns_label(input.params.namespace)+ authz.valid_dns_label(input.params.service)+ input.user.namespace == input.params.namespace+}++# Every other principal carries a real user identity in `sub`, and the ownership+# conjunct is the authorization boundary — so this only authenticates and+# shape-checks. It covers:+# • SPA users (azp == "cyclops-cs-spa")+# • user-keys (azp == "ukey-*"; sub overridden to the key owner)+# • oauth2-proxy cookie sessions (synthetic azp == "oauth2-proxy")+# • MCP connector clients minted via RFC 7591 dynamic client registration —+# their azp is a per-registration UUID, so it cannot be enumerated here+#+# Per-key clients are excluded rather than folded in: the rule above binds them+# to their namespace claim, and their sub is a service account that owns nothing,+# so a catch-all that included them would hand them every namespace.+allow {+ is_svc_route+ not authz.is_per_key_client+ authz.valid_dns_label(input.params.namespace)+ authz.valid_dns_label(input.params.service)+}++is_svc_route {+ input.route == "/api/svc/{namespace}/{service}"+}++is_svc_route {+ input.route == "/api/svc/{namespace}/{service}/{path...}"+}diff --git a/libs/fleet/backend/auth/authz_svc_test.rego b/libs/fleet/backend/auth/authz_svc_test.regonew file mode 100644index 0000000000..b6ad04c71f--- /dev/null+++ b/libs/fleet/backend/auth/authz_svc_test.rego@@ -0,0 +1,137 @@+# What /api/svc/{namespace}/{service}[/{path...}] runs: All(authz_base.allow, authz_svc.allow).+#+# route_allow below is that composition, so every case asserts the verdict the+# route produces rather than one module's half of it. Splitting the policy must+# not turn a test of the whole check into a test of a fragment.+#+# The catch-all rule accepts principals whose azp cannot be enumerated —+# oauth2-proxy sessions and RFC 7591 dynamically registered MCP clients — so the+# cases below pin both that it accepts them and that it does not thereby relax+# the per-key namespace binding.+package authz_svc_test++import rego.v1++import data.authz_base+import data.authz_svc++route_allow if {+ authz_base.allow+ authz_svc.allow+}++test_svc_per_key_matching_namespace_allowed if {+ route_allow with input as {+ "route": "/api/svc/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/svc/mypool/mypool-orchestrator/status",+ "params": {"namespace": "mypool", "service": "mypool-orchestrator", "path": "status"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},+ }+}++test_svc_per_key_no_trailing_path_allowed if {+ route_allow with input as {+ "route": "/api/svc/{namespace}/{service}",+ "method": "GET",+ "path": "/api/svc/mypool/my-svc",+ "params": {"namespace": "mypool", "service": "my-svc"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},+ }+}++test_svc_per_key_wrong_namespace_denied if {+ not route_allow with input as {+ "route": "/api/svc/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/svc/other/my-svc/health",+ "params": {"namespace": "other", "service": "my-svc", "path": "health"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},+ }+}++test_svc_spa_allowed if {+ route_allow with input as {+ "route": "/api/svc/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/svc/mypool/my-svc/health",+ "params": {"namespace": "mypool", "service": "my-svc", "path": "health"},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_svc_invalid_namespace_denied if {+ not route_allow with input as {+ "route": "/api/svc/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/svc/Pool-MyPool/my-svc/health",+ "params": {"namespace": "Pool-MyPool", "service": "my-svc", "path": "health"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "Pool-MyPool", "email": ""},+ }+}++test_svc_invalid_service_denied if {+ not route_allow with input as {+ "route": "/api/svc/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/svc/mypool/My-Svc/health",+ "params": {"namespace": "mypool", "service": "My-Svc", "path": "health"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},+ }+}++test_svc_user_key_allowed if {+ route_allow with input as {+ "route": "/api/svc/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/svc/yup/yup-7766583b-mcpjs/api/exec",+ "params": {"namespace": "yup", "service": "yup-7766583b-mcpjs", "path": "api/exec"},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ }+}++test_svc_oauth2_proxy_allowed if {+ route_allow with input as {+ "route": "/api/svc/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/svc/mypool/mypool-abc-mcp/health",+ "params": {"namespace": "mypool", "service": "mypool-abc-mcp", "path": "health"},+ "user": {"sub": "user-123", "azp": "oauth2-proxy", "namespace": "", "email": "[email protected]"},+ }+}++# MCP connector clients (RFC 7591 dynamic registration) — azp is a+# per-registration UUID; the handler's RoleBinding probe against sub is+# the authorization boundary.+test_svc_dcr_client_allowed if {+ route_allow with input as {+ "route": "/api/svc/{namespace}/{service}/{path...}",+ "method": "POST",+ "path": "/api/svc/mypool/mypool-abc-cua-driver/mcp",+ "params": {"namespace": "mypool", "service": "mypool-abc-cua-driver", "path": "mcp"},+ "user": {"sub": "user-123", "azp": "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "namespace": "", "email": "[email protected]"},+ }+}++test_svc_dcr_client_empty_sub_denied if {+ not route_allow with input as {+ "route": "/api/svc/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/svc/mypool/my-svc/health",+ "params": {"namespace": "mypool", "service": "my-svc", "path": "health"},+ "user": {"sub": "", "azp": "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "namespace": "", "email": ""},+ }+}++# The catch-all must NOT relax the per-key namespace binding: a key-*+# client targeting a foreign namespace stays denied even though it is+# authenticated.+test_svc_per_key_not_covered_by_catchall if {+ not route_allow with input as {+ "route": "/api/svc/{namespace}/{service}/{path...}",+ "method": "GET",+ "path": "/api/svc/other/my-svc/health",+ "params": {"namespace": "other", "service": "my-svc", "path": "health"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},+ }+}diff --git a/libs/fleet/backend/auth/authz_test.rego b/libs/fleet/backend/auth/authz_test.regoindex 78cffd9334..1f6a87d7d8 100644--- a/libs/fleet/backend/auth/authz_test.rego+++ b/libs/fleet/backend/auth/authz_test.rego@@ -1,354 +1,12 @@+# The shared principal vocabulary: is_admin, the token-family predicates, and the+# DNS-label shape check. No route names appear here, because authz.rego holds no+# allow rule — what a principal may do on a surface is that surface's test file.package authz_testimport rego.v1import data.authz-# ── /api/keys ────────────────────────────────────────────────────────────────--test_keys_spa_allowed if {- authz.allow with input as {- "route": "/api/keys",- "method": "POST",- "path": "/api/keys",- "params": {},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--test_keys_cua_cli_allowed if {- authz.allow with input as {- "route": "/api/keys",- "method": "POST",- "path": "/api/keys",- "params": {},- "user": {"sub": "user-123", "azp": "cua-cli", "namespace": "", "email": "[email protected]"},- }-}--test_keys_other_interactive_client_denied if {- not authz.allow with input as {- "route": "/api/keys",- "method": "POST",- "path": "/api/keys",- "params": {},- "user": {"sub": "user-123", "azp": "kubernetes", "namespace": "", "email": "[email protected]"},- }-}--test_keys_non_spa_denied if {- not authz.allow with input as {- "route": "/api/keys",- "method": "POST",- "path": "/api/keys",- "params": {},- "user": {"sub": "user-123", "azp": "key-some-pool", "namespace": "some-pool", "email": "[email protected]"},- }-}--# ── /api/k8s ──────────────────────────────────────────────────────────────────--test_k8s_spa_allowed if {- authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/api/v1/namespaces",- "params": {"path": "api/v1/namespaces"},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--test_k8s_cua_cli_allowed if {- authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/api/v1/namespaces",- "params": {"path": "api/v1/namespaces"},- "user": {"sub": "user-123", "azp": "cua-cli", "namespace": "", "email": "[email protected]"},- }-}--# ── /api/orch ─────────────────────────────────────────────────────────────────--test_orch_spa_allowed if {- authz.allow with input as {- "route": "/api/orch/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/orch/mypool/mypool-orchestrator/status",- "params": {"namespace": "mypool", "service": "mypool-orchestrator", "path": "status"},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--test_orch_cua_cli_allowed if {- authz.allow with input as {- "route": "/api/orch/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/orch/mypool/mypool-orchestrator/status",- "params": {"namespace": "mypool", "service": "mypool-orchestrator", "path": "status"},- "user": {"sub": "user-123", "azp": "cua-cli", "namespace": "", "email": "[email protected]"},- }-}--# ── /api/batch and /api/label ────────────────────────────────────────────────-#-# Pool is in the URL path. A per-key token's `namespace` claim MUST equal-# the pool name. SPA tokens can target any pool.--test_batch_submit_spa_allowed if {- authz.allow with input as {- "route": "/api/batch/{pool}/submit",- "method": "POST",- "path": "/api/batch/foo/submit",- "params": {"pool": "foo"},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--test_batch_submit_spa_allowed_any_pool if {- authz.allow with input as {- "route": "/api/batch/{pool}/submit",- "method": "POST",- "path": "/api/batch/bar/submit",- "params": {"pool": "bar"},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--test_batch_submit_per_key_matching_namespace_allowed if {- authz.allow with input as {- "route": "/api/batch/{pool}/submit",- "method": "POST",- "path": "/api/batch/foo/submit",- "params": {"pool": "foo"},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--test_batch_submit_per_key_mismatched_namespace_denied if {- not authz.allow with input as {- "route": "/api/batch/{pool}/submit",- "method": "POST",- "path": "/api/batch/bar/submit",- "params": {"pool": "bar"},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--test_batch_submit_per_key_empty_namespace_denied if {- not authz.allow with input as {- "route": "/api/batch/{pool}/submit",- "method": "POST",- "path": "/api/batch/foo/submit",- "params": {"pool": "foo"},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "", "email": ""},- }-}--test_batch_submit_invalid_pool_denied if {- not authz.allow with input as {- "route": "/api/batch/{pool}/submit",- "method": "POST",- "path": "/api/batch/Foo/submit",- "params": {"pool": "Foo"},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--test_batch_lanes_per_key_matching_namespace_allowed if {- authz.allow with input as {- "route": "/api/batch/{pool}/lanes",- "method": "POST",- "path": "/api/batch/foo/lanes",- "params": {"pool": "foo"},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--test_batch_lanes_per_key_cross_pool_denied if {- not authz.allow with input as {- "route": "/api/batch/{pool}/lanes",- "method": "DELETE",- "path": "/api/batch/bar/lanes",- "params": {"pool": "bar"},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--test_batch_status_per_key_matching_namespace_allowed if {- authz.allow with input as {- "route": "/api/batch/{pool}/{id}/status",- "method": "GET",- "path": "/api/batch/foo/abc-123/status",- "params": {"pool": "foo", "id": "abc-123"},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--test_batch_status_per_key_cross_pool_denied if {- not authz.allow with input as {- "route": "/api/batch/{pool}/{id}/status",- "method": "GET",- "path": "/api/batch/bar/abc-123/status",- "params": {"pool": "bar", "id": "abc-123"},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--test_label_submit_per_key_matching_namespace_allowed if {- authz.allow with input as {- "route": "/api/label/{pool}/{label}/batch",- "method": "POST",- "path": "/api/label/foo/run-1/batch",- "params": {"pool": "foo", "label": "run-1"},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--test_label_submit_per_key_cross_pool_denied if {- not authz.allow with input as {- "route": "/api/label/{pool}/{label}/batch",- "method": "POST",- "path": "/api/label/bar/run-1/batch",- "params": {"pool": "bar", "label": "run-1"},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--test_label_status_spa_allowed if {- authz.allow with input as {- "route": "/api/label/{pool}/{label}/status",- "method": "GET",- "path": "/api/label/foo/run-1/status",- "params": {"pool": "foo", "label": "run-1"},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--# ── /api/svc — generic per-key service proxy ─────────────────────────────────--test_svc_per_key_matching_namespace_allowed if {- authz.allow with input as {- "route": "/api/svc/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/svc/mypool/mypool-orchestrator/status",- "params": {"namespace": "mypool", "service": "mypool-orchestrator", "path": "status"},- "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},- }-}--test_svc_per_key_no_trailing_path_allowed if {- authz.allow with input as {- "route": "/api/svc/{namespace}/{service}",- "method": "GET",- "path": "/api/svc/mypool/my-svc",- "params": {"namespace": "mypool", "service": "my-svc"},- "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},- }-}--test_svc_per_key_wrong_namespace_denied if {- not authz.allow with input as {- "route": "/api/svc/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/svc/other/my-svc/health",- "params": {"namespace": "other", "service": "my-svc", "path": "health"},- "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},- }-}--test_svc_spa_allowed if {- authz.allow with input as {- "route": "/api/svc/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/svc/mypool/my-svc/health",- "params": {"namespace": "mypool", "service": "my-svc", "path": "health"},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--test_svc_invalid_namespace_denied if {- not authz.allow with input as {- "route": "/api/svc/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/svc/Pool-MyPool/my-svc/health",- "params": {"namespace": "Pool-MyPool", "service": "my-svc", "path": "health"},- "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "Pool-MyPool", "email": ""},- }-}--test_svc_invalid_service_denied if {- not authz.allow with input as {- "route": "/api/svc/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/svc/mypool/My-Svc/health",- "params": {"namespace": "mypool", "service": "My-Svc", "path": "health"},- "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},- }-}--test_svc_user_key_allowed if {- authz.allow with input as {- "route": "/api/svc/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/svc/yup/yup-7766583b-mcpjs/api/exec",- "params": {"namespace": "yup", "service": "yup-7766583b-mcpjs", "path": "api/exec"},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},- }-}--test_svc_oauth2_proxy_allowed if {- authz.allow with input as {- "route": "/api/svc/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/svc/mypool/mypool-abc-mcp/health",- "params": {"namespace": "mypool", "service": "mypool-abc-mcp", "path": "health"},- "user": {"sub": "user-123", "azp": "oauth2-proxy", "namespace": "", "email": "[email protected]"},- }-}--# MCP connector clients (RFC 7591 dynamic registration) — azp is a-# per-registration UUID; the handler's RoleBinding probe against sub is-# the authorization boundary.-test_svc_dcr_client_allowed if {- authz.allow with input as {- "route": "/api/svc/{namespace}/{service}/{path...}",- "method": "POST",- "path": "/api/svc/mypool/mypool-abc-cua-driver/mcp",- "params": {"namespace": "mypool", "service": "mypool-abc-cua-driver", "path": "mcp"},- "user": {"sub": "user-123", "azp": "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "namespace": "", "email": "[email protected]"},- }-}--test_svc_dcr_client_empty_sub_denied if {- not authz.allow with input as {- "route": "/api/svc/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/svc/mypool/my-svc/health",- "params": {"namespace": "mypool", "service": "my-svc", "path": "health"},- "user": {"sub": "", "azp": "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "namespace": "", "email": ""},- }-}--# The catch-all must NOT relax the per-key namespace binding: a key-*-# client targeting a foreign namespace stays denied even though it is-# authenticated.-test_svc_per_key_not_covered_by_catchall if {- not authz.allow with input as {- "route": "/api/svc/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/svc/other/my-svc/health",- "params": {"namespace": "other", "service": "my-svc", "path": "health"},- "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},- }-}--# ── CUA-515: admin flag + infra-path gating on /api/k8s ───────────────────────-#-# Admin membership comes from input.flags.admin_subs (resolved per-request,-# TTL-cached). Infra-only kubectl-proxy paths require admin; customer-facing-# paths stay open to any SPA user.-test_is_admin_true if {authz.is_admin with input as {"user": {"sub": "admin-1"},@@ -367,605 +25,55 @@ test_is_admin_false_no_flags if {not authz.is_admin with input as {"user": {"sub": "admin-1"}}}-# Infra-only paths — denied for non-admins, allowed for admins.--test_k8s_nodes_non_admin_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/api/v1/nodes",- "params": {"path": "api/v1/nodes"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_k8s_nodes_admin_allowed if {- authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/api/v1/nodes",- "params": {"path": "api/v1/nodes"},- "user": {"sub": "admin-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": ["admin-1"]},- }-}--test_k8s_cluster_pods_non_admin_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/api/v1/pods",- "params": {"path": "api/v1/pods"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_k8s_batch_jobs_non_admin_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/apis/batch/v1/namespaces/foo/jobs",- "params": {"path": "apis/batch/v1/namespaces/foo/jobs"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_k8s_cyclops_configmaps_non_admin_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/api/v1/namespaces/cyclops-cs/configmaps/batch-configs",- "params": {"path": "api/v1/namespaces/cyclops-cs/configmaps/batch-configs"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--# Customer-facing paths — allowed for non-admins (event contents are still-# redacted downstream by filters.visible_events).--test_k8s_namespaced_pods_non_admin_allowed if {- authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/api/v1/namespaces/foo/pods",- "params": {"path": "api/v1/namespaces/foo/pods"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_k8s_events_non_admin_allowed if {- authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/api/v1/events",- "params": {"path": "api/v1/events"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--# Cluster-wide CRD lists leak every tenant's pools/claims — admin only.-test_k8s_cluster_pools_non_admin_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/apis/cua.ai/v1/osgymworkspacepools",- "params": {"path": "apis/cua.ai/v1/osgymworkspacepools"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_k8s_cluster_pools_admin_allowed if {- authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/apis/cua.ai/v1/osgymworkspacepools",- "params": {"path": "apis/cua.ai/v1/osgymworkspacepools"},- "user": {"sub": "admin-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": ["admin-1"]},- }-}--test_k8s_cluster_claims_non_admin_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims",- "params": {"path": "apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_k8s_capsule_tenants_non_admin_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "POST",- "path": "/api/k8s/apis/capsule.clastix.io/v1beta2/tenants",- "params": {"path": "apis/capsule.clastix.io/v1beta2/tenants"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_k8s_capsule_tenants_user_key_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "POST",- "path": "/api/k8s/apis/capsule.clastix.io/v1beta2/tenants",- "params": {"path": "apis/capsule.clastix.io/v1beta2/tenants"},- "user": {"sub": "user-1", "azp": "ukey-user-1", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_k8s_capsule_tenant_item_non_admin_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/apis/capsule.clastix.io/v1beta2/tenants/user-user-1",- "params": {"path": "apis/capsule.clastix.io/v1beta2/tenants/user-user-1"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_k8s_capsule_tenants_other_versions_non_admin_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "POST",- "path": "/api/k8s/apis/capsule.clastix.io/v1beta1/tenants",- "params": {"path": "apis/capsule.clastix.io/v1beta1/tenants"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/apis/capsule.clastix.io/v99/tenants/user-user-1/status",- "params": {"path": "apis/capsule.clastix.io/v99/tenants/user-user-1/status"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_k8s_capsule_neighbor_paths_non_admin_allowed if {- authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/apis/capsule.clastix.io/v1beta2/tenantowners",- "params": {"path": "apis/capsule.clastix.io/v1beta2/tenantowners"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-- authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/apis/capsule.clastix.io.evil/v1beta2/tenants",- "params": {"path": "apis/capsule.clastix.io.evil/v1beta2/tenants"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--# Namespaced pool/claim lists are how the SPA reads them — stay open-# (Capsule RBAC scopes the caller to their own namespaces).-test_k8s_namespaced_pools_non_admin_allowed if {- authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/apis/cua.ai/v1/namespaces/foo/osgymworkspacepools",- "params": {"path": "apis/cua.ai/v1/namespaces/foo/osgymworkspacepools"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_k8s_namespaced_claims_non_admin_allowed if {- authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/foo/osgymsandboxclaims",- "params": {"path": "apis/osgym.cua.ai/v1alpha1/namespaces/foo/osgymsandboxclaims"},- "user": {"sub": "user-1", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--# Non-SPA tokens are denied on /api/k8s even if listed as admin.-test_k8s_non_spa_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/api/v1/namespaces/foo/pods",- "params": {"path": "api/v1/namespaces/foo/pods"},- "user": {"sub": "admin-1", "azp": "key-foo", "namespace": "foo", "email": ""},- "flags": {"admin_subs": ["admin-1"]},- }-}--# ── /api/namespaces — namespace management ──────────────────────────────────--test_namespaces_spa_list_allowed if {- authz.allow with input as {- "route": "/api/namespaces",- "method": "GET",- "path": "/api/namespaces",- "params": {},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--test_namespaces_spa_create_allowed if {- authz.allow with input as {- "route": "/api/namespaces/{name}",- "method": "POST",- "path": "/api/namespaces/my-ns",- "params": {"name": "my-ns"},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--test_namespaces_spa_delete_allowed if {- authz.allow with input as {- "route": "/api/namespaces/{name}",- "method": "DELETE",- "path": "/api/namespaces/my-ns",- "params": {"name": "my-ns"},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--# Per-key clients (key-*) CANNOT access namespace routes.-test_namespaces_per_key_list_denied if {- not authz.allow with input as {- "route": "/api/namespaces",- "method": "GET",- "path": "/api/namespaces",- "params": {},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--test_namespaces_per_key_by_name_denied if {- not authz.allow with input as {- "route": "/api/namespaces/{name}",- "method": "DELETE",- "path": "/api/namespaces/my-ns",- "params": {"name": "my-ns"},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--# Empty sub denied on namespace routes.-test_namespaces_empty_sub_denied if {- not authz.allow with input as {- "route": "/api/namespaces",- "method": "GET",- "path": "/api/namespaces",- "params": {},- "user": {"sub": "", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--# Missing azp denied on namespace routes.-test_namespaces_missing_azp_denied if {- not authz.allow with input as {- "route": "/api/namespaces",- "method": "GET",- "path": "/api/namespaces",- "params": {},- "user": {"sub": "user-123", "azp": "", "namespace": "", "email": "[email protected]"},- }-}--# ── /api/user-keys — per-user API key management ────────────────────────────--test_user_keys_spa_create_allowed if {- authz.allow with input as {- "route": "/api/user-keys",- "method": "POST",- "path": "/api/user-keys",- "params": {},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--test_user_keys_spa_list_allowed if {- authz.allow with input as {- "route": "/api/user-keys",- "method": "GET",- "path": "/api/user-keys",- "params": {},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--test_user_keys_spa_delete_allowed if {- authz.allow with input as {- "route": "/api/user-keys/{id}",- "method": "DELETE",- "path": "/api/user-keys/abc123",- "params": {"id": "abc123"},- "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},- }-}--# User-key clients cannot manage other user API keys (must use SPA).-test_user_keys_api_key_denied if {- not authz.allow with input as {- "route": "/api/user-keys",- "method": "GET",- "path": "/api/user-keys",- "params": {},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},- }-}--# Per-key clients cannot manage user API keys.-test_user_keys_per_key_denied if {- not authz.allow with input as {- "route": "/api/user-keys",- "method": "POST",- "path": "/api/user-keys",- "params": {},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--# Empty sub denied on user-key management routes.-test_user_keys_empty_sub_denied if {- not authz.allow with input as {- "route": "/api/user-keys",- "method": "GET",- "path": "/api/user-keys",- "params": {},- "user": {"sub": "", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},- }-}--# Missing azp denied on user-key management routes.-test_user_keys_missing_azp_denied if {- not authz.allow with input as {- "route": "/api/user-keys",- "method": "POST",- "path": "/api/user-keys",- "params": {},- "user": {"sub": "user-123", "azp": "", "namespace": "", "email": "[email protected]"},- }-}--# Per-key client cannot delete user API keys.-test_user_keys_per_key_delete_denied if {- not authz.allow with input as {- "route": "/api/user-keys/{id}",- "method": "DELETE",- "path": "/api/user-keys/abc123",- "params": {"id": "abc123"},- "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},- }-}--# User-key client cannot delete user API keys (only SPA).-test_user_keys_user_key_delete_denied if {- not authz.allow with input as {- "route": "/api/user-keys/{id}",- "method": "DELETE",- "path": "/api/user-keys/abc123",- "params": {"id": "abc123"},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},- }-}--# ── User-key client (azp starts with "ukey-") access to SPA surfaces ────────--test_user_api_key_namespaces_allowed if {- authz.allow with input as {- "route": "/api/namespaces",- "method": "GET",- "path": "/api/namespaces",- "params": {},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},- }-}--test_user_api_key_namespaces_delete_allowed if {- authz.allow with input as {- "route": "/api/namespaces/{name}",- "method": "DELETE",- "path": "/api/namespaces/my-ns",- "params": {"name": "my-ns"},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},- }-}--test_user_api_key_github_trust_policies_allowed if {- authz.allow with input as {- "route": "/api/github-trust-policies",- "method": "POST",- "path": "/api/github-trust-policies",- "params": {},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": "", "principal_type": "user_key"},- }-}--test_user_api_key_github_trust_policy_allowed if {- authz.allow with input as {- "route": "/api/github-trust-policies/{id}",- "method": "PATCH",- "path": "/api/github-trust-policies/policy-123",- "params": {"id": "policy-123"},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": "", "principal_type": "user_key"},- }-}--test_unverified_user_key_github_trust_policies_denied if {- not authz.allow with input as {- "route": "/api/github-trust-policies",- "method": "POST",- "path": "/api/github-trust-policies",- "params": {},- "user": {"sub": "service-account-ukey-rogue", "azp": "ukey-rogue", "namespace": "", "email": "", "principal_type": "user"},- }-}--test_per_key_github_trust_policies_denied if {- not authz.allow with input as {- "route": "/api/github-trust-policies",- "method": "POST",- "path": "/api/github-trust-policies",- "params": {},- "user": {"sub": "svc-123", "azp": "key-pool-foo", "namespace": "pool-foo", "email": ""},- }-}--test_per_key_github_trust_policy_denied if {- not authz.allow with input as {- "route": "/api/github-trust-policies/{id}",- "method": "DELETE",- "path": "/api/github-trust-policies/policy-123",- "params": {"id": "policy-123"},- "user": {"sub": "svc-123", "azp": "key-pool-foo", "namespace": "pool-foo", "email": ""},- }-}--test_untrusted_client_github_trust_policies_denied if {- not authz.allow with input as {- "route": "/api/github-trust-policies",- "method": "GET",- "path": "/api/github-trust-policies",- "params": {},- "user": {"sub": "user-123", "azp": "untrusted-client", "namespace": "", "email": ""},- }-}--test_untrusted_client_github_trust_policy_denied if {- not authz.allow with input as {- "route": "/api/github-trust-policies/{id}",- "method": "GET",- "path": "/api/github-trust-policies/policy-123",- "params": {"id": "policy-123"},- "user": {"sub": "user-123", "azp": "untrusted-client", "namespace": "", "email": ""},- }-}--test_user_api_key_k8s_customer_path_allowed if {- authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/api/v1/namespaces/foo/pods",- "params": {"path": "api/v1/namespaces/foo/pods"},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_user_api_key_k8s_infra_path_denied if {- not authz.allow with input as {- "route": "/api/k8s/{path...}",- "method": "GET",- "path": "/api/k8s/api/v1/nodes",- "params": {"path": "api/v1/nodes"},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},- "flags": {"admin_subs": []},- }-}--test_user_api_key_orch_allowed if {- authz.allow with input as {- "route": "/api/orch/{namespace}/{service}/{path...}",- "method": "GET",- "path": "/api/orch/mypool/mypool-orchestrator/status",- "params": {"namespace": "mypool", "service": "mypool-orchestrator", "path": "status"},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},- }-}--test_user_api_key_batch_allowed if {- authz.allow with input as {- "route": "/api/batch/{pool}/submit",- "method": "POST",- "path": "/api/batch/foo/submit",- "params": {"pool": "foo"},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},- }-}+# ── Token families ──────────────────────────────────────────────────────────+#+# These predicates decided route access from inside one module before the split;+# now every surface imports them, so a change here reaches ten modules at+# once. That is the point of the shared vocabulary, and the reason it is worth+# testing directly rather than only through the surfaces that happen to use it.-test_user_api_key_config_allowed if {- authz.allow with input as {- "route": "/api/config",- "method": "GET",- "path": "/api/config",- "params": {},- "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},- }+test_interactive_clients_are_exactly_two if {+ authz.is_interactive_client with input as {"user": {"azp": "cyclops-cs-spa"}}+ authz.is_interactive_client with input as {"user": {"azp": "cua-cli"}}+ not authz.is_interactive_client with input as {"user": {"azp": "kubernetes"}}+ not authz.is_interactive_client with input as {"user": {"azp": ""}}}-# User-key clients with empty sub are denied.-test_user_api_key_no_sub_denied if {- not authz.allow with input as {- "route": "/api/namespaces",- "method": "GET",- "path": "/api/namespaces",- "params": {},- "user": {"sub": "", "azp": "ukey-test123abc", "namespace": "", "email": ""},- }+test_per_key_client_recognised_by_prefix if {+ authz.is_per_key_client with input as {"user": {"azp": "key-foo"}}+ not authz.is_per_key_client with input as {"user": {"azp": "cyclops-cs-spa"}}+ not authz.is_per_key_client with input as {"user": {"azp": "ukey-foo"}}}-test_state_query_spa_allowed if {- authz.allow with input as {- "route": "/api/state/query",- "method": "QUERY",- "path": "/api/state/query",- "params": {},- "user": {"sub": "alice", "azp": "cyclops-cs-spa"},- }+test_user_key_client_recognised_by_prefix if {+ authz.is_user_key_client with input as {"user": {"azp": "ukey-foo"}}+ not authz.is_user_key_client with input as {"user": {"azp": "key-foo"}}}-test_state_query_user_key_allowed if {- authz.allow with input as {- "route": "/api/state/query",- "method": "QUERY",- "path": "/api/state/query",- "params": {},- "user": {"sub": "alice", "azp": "ukey-alice"},- }+# The verified form needs the principal_type the middleware stamps only after it+# has resolved the key's owner. An azp that merely looks like a user key is not+# enough — /api/github-trust-policies is the surface that relies on this.+test_verified_user_key_needs_the_resolved_principal_type if {+ authz.is_verified_user_key_client with input as {"user": {"azp": "ukey-foo", "principal_type": "user_key"}}+ not authz.is_verified_user_key_client with input as {"user": {"azp": "ukey-foo", "principal_type": "user"}}+ not authz.is_verified_user_key_client with input as {"user": {"azp": "ukey-foo"}}+ not authz.is_verified_user_key_client with input as {"user": {"azp": "cyclops-cs-spa", "principal_type": "user_key"}}}-test_state_query_untrusted_client_denied if {- not authz.allow with input as {- "route": "/api/state/query",- "method": "QUERY",- "path": "/api/state/query",- "params": {},- "user": {"sub": "alice", "azp": "untrusted"},- }-}+# ── Parameter shapes ────────────────────────────────────────────────────────-test_state_query_empty_subject_denied if {- not authz.allow with input as {- "route": "/api/state/query",- "method": "QUERY",- "path": "/api/state/query",- "params": {},- "user": {"sub": "", "azp": "cyclops-cs-spa"},- }+test_valid_dns_label_accepts_labels if {+ authz.valid_dns_label("a")+ authz.valid_dns_label("my-pool")+ authz.valid_dns_label("pool123")}-test_state_query_post_denied if {- not authz.allow with input as {- "route": "/api/state/query",- "method": "POST",- "path": "/api/state/query",- "params": {},- "user": {"sub": "alice", "azp": "cyclops-cs-spa"},- }+test_valid_dns_label_rejects_non_labels if {+ not authz.valid_dns_label("")+ not authz.valid_dns_label("My-Pool")+ not authz.valid_dns_label("-pool")+ not authz.valid_dns_label("pool-")+ not authz.valid_dns_label("pool_a")+ not authz.valid_dns_label("a/b")+ not authz.valid_dns_label(concat("", ["a" | some _ in numbers.range(1, 64)]))}diff --git a/libs/fleet/backend/auth/authz_user_keys.rego b/libs/fleet/backend/auth/authz_user_keys.regonew file mode 100644index 0000000000..3ac4ebefe0--- /dev/null+++ b/libs/fleet/backend/auth/authz_user_keys.rego@@ -0,0 +1,21 @@+# /api/user-keys and /api/user-keys/{id} — create, list and revoke personal API+# keys.+#+# Interactive clients only. A user key must not manage user keys: that would let+# a leaked key mint replacements for itself and revoke the ones a human would use+# to shut it off.+package authz_user_keys++import data.authz++default allow = false++allow {+ input.route == "/api/user-keys"+ authz.is_interactive_client+}++allow {+ input.route == "/api/user-keys/{id}"+ authz.is_interactive_client+}diff --git a/libs/fleet/backend/auth/authz_user_keys_test.rego b/libs/fleet/backend/auth/authz_user_keys_test.regonew file mode 100644index 0000000000..863363ae2e--- /dev/null+++ b/libs/fleet/backend/auth/authz_user_keys_test.rego@@ -0,0 +1,112 @@+# What /api/user-keys and /api/user-keys/{id} runs: All(authz_base.allow, authz_user_keys.allow).+#+# route_allow below is that composition, so every case asserts the verdict the+# route produces rather than one module's half of it. Splitting the policy must+# not turn a test of the whole check into a test of a fragment.+package authz_user_keys_test++import rego.v1++import data.authz_base+import data.authz_user_keys++route_allow if {+ authz_base.allow+ authz_user_keys.allow+}++test_user_keys_spa_create_allowed if {+ route_allow with input as {+ "route": "/api/user-keys",+ "method": "POST",+ "path": "/api/user-keys",+ "params": {},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_user_keys_spa_list_allowed if {+ route_allow with input as {+ "route": "/api/user-keys",+ "method": "GET",+ "path": "/api/user-keys",+ "params": {},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_user_keys_spa_delete_allowed if {+ route_allow with input as {+ "route": "/api/user-keys/{id}",+ "method": "DELETE",+ "path": "/api/user-keys/abc123",+ "params": {"id": "abc123"},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++# User-key clients cannot manage other user API keys (must use SPA).+test_user_keys_api_key_denied if {+ not route_allow with input as {+ "route": "/api/user-keys",+ "method": "GET",+ "path": "/api/user-keys",+ "params": {},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ }+}++# Per-key clients cannot manage user API keys.+test_user_keys_per_key_denied if {+ not route_allow with input as {+ "route": "/api/user-keys",+ "method": "POST",+ "path": "/api/user-keys",+ "params": {},+ "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},+ }+}++# Empty sub denied on user-key management routes.+test_user_keys_empty_sub_denied if {+ not route_allow with input as {+ "route": "/api/user-keys",+ "method": "GET",+ "path": "/api/user-keys",+ "params": {},+ "user": {"sub": "", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ }+}++# Missing azp denied on user-key management routes.+test_user_keys_missing_azp_denied if {+ not route_allow with input as {+ "route": "/api/user-keys",+ "method": "POST",+ "path": "/api/user-keys",+ "params": {},+ "user": {"sub": "user-123", "azp": "", "namespace": "", "email": "[email protected]"},+ }+}++# Per-key client cannot delete user API keys.+test_user_keys_per_key_delete_denied if {+ not route_allow with input as {+ "route": "/api/user-keys/{id}",+ "method": "DELETE",+ "path": "/api/user-keys/abc123",+ "params": {"id": "abc123"},+ "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},+ }+}++# User-key client cannot delete user API keys (only SPA).+test_user_keys_user_key_delete_denied if {+ not route_allow with input as {+ "route": "/api/user-keys/{id}",+ "method": "DELETE",+ "path": "/api/user-keys/abc123",+ "params": {"id": "abc123"},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ }+}diff --git a/libs/fleet/backend/auth/event_filter.go b/libs/fleet/backend/auth/event_filter.godeleted file mode 100644index 8f2760d3be..0000000000--- a/libs/fleet/backend/auth/event_filter.go+++ /dev/null@@ -1,157 +0,0 @@-package auth--import (- "bytes"- "context"- "encoding/json"- "log/slog"- "net/http"- "strings"-)--// k8sEventListPath returns true when the upstream K8s API path targets the-// core/v1 Event resource — either cluster-scoped (/api/v1/events[/name]) or-// namespaced (/api/v1/namespaces/{ns}/events[/name]). Other K8s API verbs-// and resources pass through the K8s reverse proxy unfiltered.-//-// `path` has a leading slash and no query string (the caller derives it-// from r.PathValue("path")). A substring check is deliberately avoided: it-// would miss the namespaced form (which does not contain "/api/v1/events")-// and so would let namespaced event lists bypass the visibility filter.-func k8sEventListPath(path string) bool {- if path == "/api/v1/events" || strings.HasPrefix(path, "/api/v1/events/") {- return true- }- if rest, ok := strings.CutPrefix(path, "/api/v1/namespaces/"); ok {- if _, after, ok := strings.Cut(rest, "/"); ok {- return after == "events" || strings.HasPrefix(after, "events/")- }- }- return false-}--// isWatch reports whether the request is a K8s watch (streaming) request,-// which must not be buffered by the event filter.-func isWatch(r *http.Request) bool {- v := r.URL.Query().Get("watch")- return v == "true" || v == "1"-}--// K8sEventFilterMiddleware applies filters.rego's visible_events rule-// to K8s EventList responses returned by the /api/k8s reverse proxy.-// Requests whose upstream path is not an EventList pass through with-// zero overhead; matching responses get buffered, parsed as JSON,-// filtered through OPA, and rewritten before reaching the client.-//-// Mount this after RouteContext (so r.PathValue("path") is populated)-// and after TokenAuthMiddleware (so GetUser returns the caller). The-// filter is opt-in per-route: the K8s handler is the only consumer-// today.-//-// Non-200, non-JSON, OPA-error, and gzip-encoded responses pass through-// unchanged — the original behaviour of filterEventListResponse before-// this was extracted from handlers/k8s.go.-func K8sEventFilterMiddleware(next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- upstream := "/" + strings.TrimPrefix(r.PathValue("path"), "/")- if !k8sEventListPath(upstream) {- next.ServeHTTP(w, r)- return- }- // A watch is a long-lived chunked stream, not a single EventList.- // Buffering it would hang the request and grow memory unboundedly,- // so stream it straight through (the SPA only polls list GETs).- if isWatch(r) {- next.ServeHTTP(w, r)- return- }- user := GetUser(r.Context())- buf := &eventFilterBuffer{ResponseWriter: w, filter: EvalVisibleEvents}- next.ServeHTTP(buf, r)- buf.flush(r.Context(), user)- })-}--// eventFilterBuffer captures status + body so the middleware can decide-// whether to forward the original bytes or replace them with a filtered-// EventList. Header() returns the underlying writer's map (via the-// embedded ResponseWriter), so the inner handler keeps setting headers-// as usual; only the WriteHeader commit is delayed until flush().-//-// filter is the OPA-backed visibility function (EvalVisibleEvents in-// production); it is a field so tests can inject a stub — in particular to-// exercise the fail-closed path when it returns an error.-type eventFilterBuffer struct {- http.ResponseWriter- filter func(context.Context, *User, []interface{}) ([]interface{}, error)- status int- wroteOnce bool- body bytes.Buffer-}--func (b *eventFilterBuffer) WriteHeader(status int) {- if b.wroteOnce {- return- }- b.status = status- b.wroteOnce = true-}--func (b *eventFilterBuffer) Write(p []byte) (int, error) {- if !b.wroteOnce {- b.WriteHeader(http.StatusOK)- }- return b.body.Write(p)-}--func (b *eventFilterBuffer) flush(ctx context.Context, user *User) {- h := b.ResponseWriter.Header()- status := b.status- if status == 0 {- status = http.StatusOK- }- passthrough := func() {- b.ResponseWriter.WriteHeader(status)- if _, err := b.ResponseWriter.Write(b.body.Bytes()); err != nil {- slog.Debug("k8s event filter: passthrough write error", "err", err)- }- }- if status != http.StatusOK {- passthrough()- return- }- var eventList map[string]interface{}- if err := json.Unmarshal(b.body.Bytes(), &eventList); err != nil {- // Not JSON (e.g. gzip-encoded upstream) — forward as-is so the- // client decodes it normally.- passthrough()- return- }- items, _ := eventList["items"].([]interface{})- if items == nil {- passthrough()- return- }- filtered, err := b.filter(ctx, user, items)- if err != nil {- // Fail closed: on policy-eval error we cannot tell whether the- // caller is an admin, so redact ALL events rather than risk- // leaking internal K8s event data to a non-admin. The SPA renders- // an empty (rather than unfiltered) list.- slog.Warn("opa: visible_events eval failed; redacting all events (fail-closed)", "err", err)- filtered = []interface{}{}- }- eventList["items"] = filtered- out, err := json.Marshal(eventList)- if err != nil {- passthrough()- return- }- h.Del("Content-Length")- h.Del("Content-Encoding") // we replaced the body with plain JSON- h.Set("Content-Type", "application/json")- b.ResponseWriter.WriteHeader(status)- if _, err := b.ResponseWriter.Write(out); err != nil {- slog.Debug("k8s event filter: filtered write error", "err", err)- }-}diff --git a/libs/fleet/backend/auth/event_filter_test.go b/libs/fleet/backend/auth/event_filter_test.godeleted file mode 100644index 74e6efe5d0..0000000000--- a/libs/fleet/backend/auth/event_filter_test.go+++ /dev/null@@ -1,161 +0,0 @@-package auth--import (- "context"- "encoding/json"- "errors"- "io"- "net/http"- "net/http/httptest"- "testing"-)--func eventListJSON(t *testing.T, reasons ...string) []byte {- t.Helper()- items := make([]any, 0, len(reasons))- for _, r := range reasons {- items = append(items, map[string]any{"reason": r})- }- b, err := json.Marshal(map[string]any{"kind": "EventList", "items": items})- if err != nil {- t.Fatalf("marshal event list: %v", err)- }- return b-}--// runFlush drives an eventFilterBuffer the way the middleware does: write the-// upstream status+body, then flush through the injected filter. It returns the-// committed status and body seen by the client.-func runFlush(status int, body []byte, filter func(context.Context, *User, []any) ([]any, error)) (int, []byte, http.Header) {- rec := httptest.NewRecorder()- buf := &eventFilterBuffer{ResponseWriter: rec, filter: filter}- if status != 0 {- buf.WriteHeader(status)- }- _, _ = buf.Write(body)- buf.flush(context.Background(), &User{ID: "u-1"})- res := rec.Result()- defer res.Body.Close()- out, _ := io.ReadAll(res.Body)- return res.StatusCode, out, res.Header-}--func itemsLen(t *testing.T, body []byte) int {- t.Helper()- var m map[string]any- if err := json.Unmarshal(body, &m); err != nil {- t.Fatalf("output not JSON: %v (%s)", err, body)- }- items, ok := m["items"].([]any)- if !ok {- t.Fatalf("output items missing/not array: %s", body)- }- return len(items)-}--func TestEventFilter_FailClosedOnError(t *testing.T) {- // The crux: if the policy eval errors, the client must NOT receive the- // unfiltered events. We expect an empty items array, not a passthrough.- called := false- stub := func(context.Context, *User, []any) ([]any, error) {- called = true- return nil, errors.New("opa boom")- }- status, body, _ := runFlush(http.StatusOK, eventListJSON(t, "PoolCreated", "InternalScaleDecision"), stub)- if !called {- t.Fatal("filter was not invoked")- }- if status != http.StatusOK {- t.Fatalf("status = %d, want 200", status)- }- if n := itemsLen(t, body); n != 0 {- t.Fatalf("fail-closed should redact all events, got %d items", n)- }-}--func TestEventFilter_AdminPassthroughAndSubset(t *testing.T) {- all := func(_ context.Context, _ *User, items []any) ([]any, error) {- return items, nil- }- _, body, _ := runFlush(http.StatusOK, eventListJSON(t, "A", "B", "C"), all)- if n := itemsLen(t, body); n != 3 {- t.Fatalf("admin passthrough = %d items, want 3", n)- }-- firstOnly := func(_ context.Context, _ *User, items []any) ([]any, error) {- if len(items) == 0 {- return items, nil- }- return items[:1], nil- }- _, body, _ = runFlush(http.StatusOK, eventListJSON(t, "A", "B", "C"), firstOnly)- if n := itemsLen(t, body); n != 1 {- t.Fatalf("subset filter = %d items, want 1", n)- }-}--func TestEventFilter_NonOKPassesThroughUnfiltered(t *testing.T) {- called := false- stub := func(context.Context, *User, []any) ([]any, error) {- called = true- return nil, nil- }- original := []byte(`{"kind":"Status","status":"Failure","code":500}`)- status, body, _ := runFlush(http.StatusInternalServerError, original, stub)- if called {- t.Fatal("filter must not run on non-200 responses")- }- if status != http.StatusInternalServerError {- t.Fatalf("status = %d, want 500", status)- }- if string(body) != string(original) {- t.Fatalf("body altered on passthrough: %s", body)- }-}--func TestEventFilter_NonJSONPassesThrough(t *testing.T) {- called := false- stub := func(context.Context, *User, []any) ([]any, error) {- called = true- return nil, nil- }- original := []byte("\x1f\x8b not json (e.g. gzip)")- _, body, _ := runFlush(http.StatusOK, original, stub)- if called {- t.Fatal("filter must not run on non-JSON bodies")- }- if string(body) != string(original) {- t.Fatalf("body altered: %s", body)- }-}--func TestEventFilter_NoItemsFieldPassesThrough(t *testing.T) {- called := false- stub := func(context.Context, *User, []any) ([]any, error) {- called = true- return nil, nil- }- original := []byte(`{"kind":"Pod","metadata":{"name":"p"}}`)- _, body, _ := runFlush(http.StatusOK, original, stub)- if called {- t.Fatal("filter must not run when there is no items array")- }- if string(body) != string(original) {- t.Fatalf("body altered: %s", body)- }-}--func TestK8sEventListPath(t *testing.T) {- cases := map[string]bool{- "/api/v1/events": true,- "/api/v1/namespaces/pool-foo/events": true,- "/api/v1/nodes": false,- "/api/v1/namespaces/pool-foo/pods": false,- "/apis/cua.ai/v1/osgymworkspacepools": false,- }- for path, want := range cases {- if got := k8sEventListPath(path); got != want {- t.Fatalf("k8sEventListPath(%q) = %v, want %v", path, got, want)- }- }-}diff --git a/libs/fleet/backend/auth/facts.go b/libs/fleet/backend/auth/facts.gonew file mode 100644index 0000000000..837a9f8ff0--- /dev/null+++ b/libs/fleet/backend/auth/facts.go@@ -0,0 +1,90 @@+package auth++import (+ "context"+ "fmt"+ "net/http"+ "sync"+)++// A FactProvider answers a question the token cannot: whether some other+// system — Kubernetes, a database, an API — says yes. The policy trees in+// policy_routes.go are pure data built before any of those systems has a+// client, which is the same problem RegisterPolicyModule solves for Rego text,+// and this file solves it the same way: a tree names a provider, and whatever+// owns the client registers one under that name at startup.+//+// The indirection is not only about construction order. handlers imports auth;+// auth cannot import handlers, and the namespace-RBAC probe is a handlers+// method. A registry is the seam that lets the policy depend on the probe+// without the packages depending on each other.++var factProviderRegistry = struct {+ sync.RWMutex+ providers map[string]FactProvider+}{providers: map[string]FactProvider{}}++// RegisterFactProvider binds a provider to a name that policy trees can refer+// to. Registering twice under one name replaces the earlier provider, which is+// what lets a test stand in for the production one — and what lets setupRouter+// be called more than once in a process.+func RegisterFactProvider(name string, provider FactProvider) {+ if name == "" || provider == nil {+ panic("registered fact provider requires a name and a provider")+ }+ factProviderRegistry.Lock()+ defer factProviderRegistry.Unlock()+ factProviderRegistry.providers[name] = provider+}++// RegisteredFacts returns a provider that resolves through the registry at+// request time. Nothing is looked up here: a tree is built during route+// construction, and the whole point is that the real provider need not exist+// yet.+func RegisteredFacts(name string) FactProvider {+ if name == "" {+ panic("registered fact provider requires a name")+ }+ return registeredFactProvider{name: name}+}++type registeredFactProvider struct {+ name string+}++// CacheKey answers from the name alone, without consulting the registry. It has+// to: the key is read while the plan is compiled — by Leaf.key for dedupe and by+// the cost model for ordering — and at that point the registry may still be+// empty. It also means the key is stable across a re-registration, which is+// correct, because what the key identifies is the load, not the loader.+func (provider registeredFactProvider) CacheKey() string {+ return "registered-facts:" + provider.name+}++// LoadFacts resolves the provider and delegates. An unregistered name is a+// plain error rather than a FactUnavailableError: nothing was unreachable, the+// process was assembled wrong, and the difference is a 500 that pages someone+// against a 502 that says "retry".+func (provider registeredFactProvider) LoadFacts(ctx context.Context, request *http.Request) (FactSet, error) {+ factProviderRegistry.RLock()+ delegate, ok := factProviderRegistry.providers[provider.name]+ factProviderRegistry.RUnlock()+ if !ok {+ return nil, fmt.Errorf("fact provider %q is not registered", provider.name)+ }+ return delegate.LoadFacts(ctx, request)+}++// The namespace-ownership fact: the name the probe is registered under, and the+// document it lands in. Both are consts rather than literals because three+// files have to agree on them — the tree in policy_routes.go, the provider in+// handlers, and authz_ownership.rego, which is the one that cannot be checked+// by the compiler.+const (+ // NamespaceRBACFactProvider is the registry name of the impersonated+ // RoleBinding probe. handlers registers it; NamespaceOwnershipPolicy names it.+ NamespaceRBACFactProvider = "namespace-rbac"+ // NamespaceRBACFactNamespace is where the probe's answer lands in the policy+ // input: authz_ownership.rego reads input.facts.namespace_rbac.allowed.+ NamespaceRBACFactNamespace = "namespace_rbac"+)diff --git a/libs/fleet/backend/auth/filters.rego b/libs/fleet/backend/auth/filters.regodeleted file mode 100644index 949657c565..0000000000--- a/libs/fleet/backend/auth/filters.rego+++ /dev/null@@ -1,46 +0,0 @@-# Cyclops-CS data-visibility filters.-#-# This file is intentionally separate from authz.rego. authz.rego decides-# whether a request is *allowed*; this file decides *what data* an allowed-# request may see. The two concerns are kept apart so each can evolve,-# be tested, and be reasoned about independently.-#-# Currently covers one endpoint: /api/k8s (kubectl-proxy passthrough).-# The K8s event-filter middleware calls visible_events after receiving the-# upstream EventList and before forwarding it to the SPA, passing the event-# items as part of `input`.-#-# Flags arrive via input.flags (resolved per-request from the OpenFeature-# provider and TTL-cached in auth/middlewares.go — NOT a static OPA data-# store):-# admin_subs — Keycloak sub UUIDs with admin data access-# event_reason_allowlist — K8s event reasons visible to non-admins-#-# Admin membership (input.flags.admin_subs) is decided by data.authz.is_admin;-# this package reuses it rather than redefining the rule.-package filters--# ── K8s EventList filter ────────────────────────────────────────────────────-#-# visible_events filters the K8s EventList items array returned by the-# kubectl-proxy before the SPA receives it.-#-# Input fields used:-# input.user.sub — caller's JWT subject-# input.flags — resolved feature flags (admin_subs, event_reason_allowlist)-# input.events — []EventObject from the upstream EventList.items-#-# Admins: all events pass through.-# Non-admins: only events whose `reason` field is in-# input.flags.event_reason_allowlist.--visible_events[event] {- event := input.events[_]- data.authz.is_admin-}--visible_events[event] {- event := input.events[_]- not data.authz.is_admin- input.flags.event_reason_allowlist[_] == event.reason-}diff --git a/libs/fleet/backend/auth/filters_test.rego b/libs/fleet/backend/auth/filters_test.regodeleted file mode 100644index a1965ecadf..0000000000--- a/libs/fleet/backend/auth/filters_test.rego+++ /dev/null@@ -1,46 +0,0 @@-package filters_test--import rego.v1--import data.filters--events := [- {"reason": "PoolCreated"},- {"reason": "PoolReady"},- {"reason": "InternalScaleDecision"},-]--# Admins see every event for the pool.-test_admin_sees_all_events if {- count(filters.visible_events) == 3 with input as {- "user": {"sub": "admin-1"},- "flags": {"admin_subs": ["admin-1"], "event_reason_allowlist": ["PoolCreated"]},- "events": events,- }-}--# Non-admins see only events whose reason is in the allowlist.-test_non_admin_sees_allowlisted_only if {- count(filters.visible_events) == 2 with input as {- "user": {"sub": "nobody"},- "flags": {"admin_subs": ["admin-1"], "event_reason_allowlist": ["PoolCreated", "PoolReady"]},- "events": events,- }-}--# Empty allowlist → non-admins see nothing.-test_non_admin_empty_allowlist_sees_none if {- count(filters.visible_events) == 0 with input as {- "user": {"sub": "nobody"},- "flags": {"admin_subs": ["admin-1"], "event_reason_allowlist": []},- "events": events,- }-}--# Missing flags doc → fail closed (non-admins see nothing).-test_non_admin_missing_flags_sees_none if {- count(filters.visible_events) == 0 with input as {- "user": {"sub": "nobody"},- "events": events,- }-}diff --git a/libs/fleet/backend/auth/flags_test.go b/libs/fleet/backend/auth/flags_test.goindex d09ebe9747..b0e7ad3c19 100644--- a/libs/fleet/backend/auth/flags_test.go+++ b/libs/fleet/backend/auth/flags_test.go@@ -18,12 +18,11 @@ func resetFlagsCache() {}// TestExportedEvalsEndToEnd wires the real path: SimpleEnvProvider →-// flagsData() → input.flags → the prepared OPA queries. It guards the-// glue (flag discovery, env→key mapping, set-result decoding) that the+// flagsData() → input.flags → the prepared OPA query. It guards the+// glue (flag discovery, env→key mapping, result decoding) that the// pure-policy tests in policy_test.go don't touch.func TestExportedEvalsEndToEnd(t *testing.T) {t.Setenv("CYCLOPS_CS_ADMIN_SUBS", `["admin-sub"]`)- t.Setenv("CYCLOPS_CS_EVENT_REASON_ALLOWLIST", `["PoolCreated","PoolReady"]`)if err := featureflags.SetupProvider(context.Background(), "development", featureflags.AWSCredentials{}); err != nil {t.Fatalf("setup dev provider: %v", err)@@ -48,29 +47,6 @@ func TestExportedEvalsEndToEnd(t *testing.T) {}})- t.Run("EvalVisibleEvents", func(t *testing.T) {- items := []interface{}{- map[string]interface{}{"reason": "PoolCreated"},- map[string]interface{}{"reason": "PoolReady"},- map[string]interface{}{"reason": "InternalScaleDecision"},- }-- out, err := EvalVisibleEvents(ctx, &User{ID: "nobody"}, items)- if err != nil {- t.Fatalf("EvalVisibleEvents(non-admin): %v", err)- }- if len(out) != 2 {- t.Fatalf("non-admin visible events = %d, want 2 (allowlisted reasons only)", len(out))- }-- out, err = EvalVisibleEvents(ctx, &User{ID: "admin-sub"}, items)- if err != nil {- t.Fatalf("EvalVisibleEvents(admin): %v", err)- }- if len(out) != 3 {- t.Fatalf("admin visible events = %d, want 3 (all)", len(out))- }- })}// TestFlagsDataCachedAndRefreshes confirms the TTL cache serves a stablediff --git a/libs/fleet/backend/auth/middlewares.go b/libs/fleet/backend/auth/middlewares.goindex c901e1a88a..40ae16b243 100644--- a/libs/fleet/backend/auth/middlewares.go+++ b/libs/fleet/backend/auth/middlewares.go@@ -24,28 +24,88 @@ type ctxKey intconst UserKey ctxKey = 1-var opaQuery *rego.PreparedEvalQuery-var opaEventQuery *rego.PreparedEvalQueryvar opaAdminQuery *rego.PreparedEvalQuery-var opaPoolAdmissionQuery *rego.PreparedEvalQuery+// authzPolicy is the shared principal vocabulary every surface module imports.+// It holds no allow rule of its own; see authz.rego.+////go:embed authz.regovar authzPolicy string-//go:embed filters.rego-var filtersPolicy string-//go:embed pool_admission.regovar poolAdmissionPolicy 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+// surfacePolicySources.+//+//go:embed authz_ownership.rego+var authzOwnershipPolicy string++// surfacePolicySources is the base module plus one module per authorization+// surface, keyed by the name policy_routes.go registers it under. Registration+// is a loop over this map rather than a call per module so that adding a surface+// is one entry in one place — and so that a module added here but bound to no+// route is caught by the correspondence test rather than sitting compiled and+// unreachable.+var surfacePolicySources = map[string]struct {+ filename string+ source string+}{+ "authz-base": {"authz_base.rego", authzBasePolicy},+ "authz-keys": {"authz_keys.rego", authzKeysPolicy},+ "authz-config": {"authz_config.rego", authzConfigPolicy},+ "authz-billing": {"authz_billing.rego", authzBillingPolicy},+ "authz-namespaces": {"authz_namespaces.rego", authzNamespacesPolicy},+ "authz-github-trust": {"authz_github_trust.rego", authzGitHubTrustPolicy},+ "authz-user-keys": {"authz_user_keys.rego", authzUserKeysPolicy},+ "authz-k8s": {"authz_k8s.rego", authzK8sPolicy},+ "authz-orch": {"authz_orch.rego", authzOrchPolicy},+ "authz-svc": {"authz_svc.rego", authzSvcPolicy},+ "authz-state-query": {"authz_state_query.rego", authzStateQueryPolicy},+}++//go:embed authz_base.rego+var authzBasePolicy string++//go:embed authz_keys.rego+var authzKeysPolicy string++//go:embed authz_config.rego+var authzConfigPolicy string++//go:embed authz_billing.rego+var authzBillingPolicy string++//go:embed authz_namespaces.rego+var authzNamespacesPolicy string++//go:embed authz_github_trust.rego+var authzGitHubTrustPolicy string++//go:embed authz_user_keys.rego+var authzUserKeysPolicy string++//go:embed authz_k8s.rego+var authzK8sPolicy string++//go:embed authz_orch.rego+var authzOrchPolicy string++//go:embed authz_svc.rego+var authzSvcPolicy string++//go:embed authz_state_query.rego+var authzStateQueryPolicy string+// flagPrefix is the OpenFeature path under which the auth package's OPA// flags live. The dev SimpleEnvProvider maps it to env vars prefixed// CYCLOPS_CS_ (stripping "/feature-flags/", lowercasing nothing,// replacing "/" and "-" with "_"); the aws-ssm provider uses the path// as the SSM Parameter Store prefix directly.//-// /feature-flags/cyclops-cs/admin-subs → CYCLOPS_CS_ADMIN_SUBS-// /feature-flags/cyclops-cs/event-reason-allowlist → CYCLOPS_CS_EVENT_REASON_ALLOWLIST+// /feature-flags/cyclops-cs/admin-subs → CYCLOPS_CS_ADMIN_SUBS//// Values are JSON string arrays (e.g. '["sub1","sub2"]').const flagPrefix = "/feature-flags/cyclops-cs/"@@ -54,9 +114,9 @@ const flagPrefix = "/feature-flags/cyclops-cs/"// before re-resolving via OpenFeature. Refresh is lazy and ad-hoc: the// next caller that arrives after expiry triggers a re-resolve on the// request path — there is no background ticker. Flags are passed into-// each OPA evaluation as `input.flags` (see OpaMiddleware / EvalIsAdmin /-// EvalVisibleEvents), so a refreshed value takes effect on the very next-// request without rebuilding any prepared query or restarting the pod.+// each OPA evaluation as `input.flags` (see newRequestPolicyInput /+// EvalIsAdmin), so a refreshed value takes effect on the very next request+// without rebuilding any prepared query or restarting the pod.const flagsTTL = 1 * time.Minutevar (@@ -77,14 +137,13 @@ var (ffClient *openfeature.Client)-// flagsData returns the resolved feature-flag map (admin_subs,-// event_reason_allowlist, …), TTL-cached at flagsTTL. On a hit it returns-// the cached map under the lock; on a miss it resolves via OpenFeature-// behind a singleflight so only one goroutine fans out to SSM while the-// rest share the result. The map is meant to be placed under input.flags-// for OPA; the policy references a subset of keys (admin_subs /-// event_reason_allowlist), extras are ignored, and absent keys evaluate as-// undefined (implicitly denying / redacting).+// flagsData returns the resolved feature-flag map (admin_subs, …), TTL-cached+// at flagsTTL. On a hit it returns the cached map under the lock; on a miss it+// resolves via OpenFeature behind a singleflight so only one goroutine fans out+// to SSM while the rest share the result. The map is meant to be placed under+// input.flags for OPA; the policy references a subset of keys (admin_subs),+// extras are ignored, and absent keys evaluate as undefined (implicitly+// denying).//// The OpenFeature provider is installed by featureflags.SetupProvider at// startup (main.go) — aws-ssm in prod, SimpleEnvProvider in dev, with the@@ -187,42 +246,30 @@ func loadStringList(ctx context.Context, client *openfeature.Client, flagKey str// valid across flag refreshes. The OpenFeature provider must be installed// by featureflags.SetupProvider before this runs.func LoadOpa() {- // authz queries only need authz.rego (is_admin lives there too).- prepareAuthzQuery := func(q string) *rego.PreparedEvalQuery {- pq, err := rego.New(- rego.Query(q),- rego.Module("authz.rego", authzPolicy),- ).PrepareForEval(context.Background())- if err != nil {- log.Fatalf("opa: prepare authz %q: %v", q, err)- }- return &pq+ RegisterPolicyModule("authz", "authz.rego", authzPolicy)+ RegisterPolicyModule("pool-admission", "pool_admission.rego", poolAdmissionPolicy)+ RegisterPolicyModule("authz-ownership", "authz_ownership.rego", authzOwnershipPolicy)+ for name, module := range surfacePolicySources {+ RegisterPolicyModule(name, module.filename, module.source)}- // filter queries need both authz.rego (for data.authz.is_admin) and filters.rego- prepareFilterQuery := func(q string) *rego.PreparedEvalQuery {+ // authz queries only need authz.rego. Route authorization is not one of+ // them — that runs through the policy library, which composes the base+ // module with one surface module per route from the registry above. What is+ // left is is_admin, a decision EvalIsAdmin makes off a User rather than a+ // request, which is why it is not a policy-library node.+ prepareAuthzQuery := func(q string) *rego.PreparedEvalQuery {pq, err := rego.New(rego.Query(q),rego.Module("authz.rego", authzPolicy),- rego.Module("filters.rego", filtersPolicy),).PrepareForEval(context.Background())if err != nil {- log.Fatalf("opa: prepare filter %q: %v", q, err)+ log.Fatalf("opa: prepare authz %q: %v", q, err)}return &pq}- opaQuery = prepareAuthzQuery("data.authz.allow")opaAdminQuery = prepareAuthzQuery("data.authz.is_admin")- opaEventQuery = prepareFilterQuery("data.filters.visible_events")- poolAdmissionQuery, err := rego.New(- rego.Query("data.pool_admission.allow"),- rego.Module("pool_admission.rego", poolAdmissionPolicy),- ).PrepareForEval(context.Background())- if err != nil {- log.Fatalf("opa: prepare pool admission policy: %v", err)- }- opaPoolAdmissionQuery = &poolAdmissionQuery// Warm the flag cache once so the first request isn't slowed by the// initial resolve and any SSM/provider misconfiguration surfaces in the@@ -230,50 +277,6 @@ func LoadOpa() {_ = flagsData()}-// EvalPoolAdmission validates an OSGymWorkspacePool write body before it is-// forwarded to Kubernetes.-func EvalPoolAdmission(ctx context.Context, method string, object map[string]any) (bool, error) {- res, err := opaPoolAdmissionQuery.Eval(ctx, rego.EvalInput(map[string]any{- "method": method,- "object": object,- }))- if err != nil {- return false, err- }- return res.Allowed(), nil-}--// EvalVisibleEvents runs the data.filters.visible_events query against the-// provided events slice and user sub. Returns the filtered slice.-// items must be a []interface{} (the raw JSON-unmarshalled K8s event objects).-func EvalVisibleEvents(ctx context.Context, user *User, items []interface{}) ([]interface{}, error) {- input := map[string]interface{}{- "user": buildUserInput(user),- "flags": flagsData(),- "events": items,- }- res, err := opaEventQuery.Eval(ctx, rego.EvalInput(input))- if err != nil {- return nil, err- }- if len(res) == 0 || len(res[0].Expressions) == 0 {- return []interface{}{}, nil- }- // visible_events is a set rule — the result is a set of event objects.- switch v := res[0].Expressions[0].Value.(type) {- case []interface{}:- return v, nil- case map[string]interface{}:- // OPA may return a set as a map when the set is non-empty.- out := make([]interface{}, 0, len(v))- for _, ev := range v {- out = append(out, ev)- }- return out, nil- }- return []interface{}{}, nil-}-// EvalIsAdmin returns true if the user's JWT sub is in input.flags.admin_subs// (data.authz.is_admin). is_admin only reads input.user and input.flags, so// no route/method/path is needed.@@ -394,51 +397,6 @@ func applyUserKeyIdentity(user *User, userKeyPfx string) error {return nil}-// OpaMiddleware evaluates `data.authz.allow` against-//-// { method, path, route, params, user: { sub, azp, namespace, email } }-//-// The `route` and `params` map are filled by RouteContext below before-// this middleware runs; they let policy reason about the matched-// route ("/api/orch/{namespace}/{service}/{path...}") and its parameters-// separately from the-// raw URL path.-func OpaMiddleware(next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- start := time.Now()- result := "allowed"- defer func() {- slog.Debug("opa", "elapsed", time.Since(start), "result", result,- "traceId", r.Context().Value(middlewares.ContextKey("traceId")))- }()-- user, _ := r.Context().Value(UserKey).(*User)- userInput := buildUserInput(user)- route, _ := r.Context().Value(routeKey).(string)- params, _ := r.Context().Value(paramsKey).(map[string]string)- input := map[string]any{- "method": r.Method,- "path": r.URL.Path,- "route": route,- "params": params,- "user": userInput,- "flags": flagsData(),- }- res, err := opaQuery.Eval(r.Context(), rego.EvalInput(input))- if err != nil {- result = err.Error()- writeJSONErr(w, http.StatusInternalServerError, "policy evaluation failed")- return- }- if !res.Allowed() {- result = "forbidden"- writeJSONErr(w, http.StatusForbidden, "forbidden")- return- }- next.ServeHTTP(w, r)- })-}-func buildUserInput(user *User) map[string]any {if user == nil {return map[string]any{}@@ -466,9 +424,42 @@ const (paramsKey routeCtxKey = 2)+// routeParamNames returns the wildcard names in a route pattern, in the order+// they appear: "/api/svc/{namespace}/{service}/{path...}" yields namespace,+// service, path. These are the names r.PathValue is keyed by, so the trailing+// "..." of a multi-segment wildcard is not part of the name.+//+// This scans the Go 1.22 ServeMux pattern grammar and nothing wider: a wildcard+// is a whole path segment wrapped in braces, and "{$}" — the end-of-path anchor+// — binds no value.+func routeParamNames(route string) []string {+ var names []string+ for _, segment := range strings.Split(route, "/") {+ if len(segment) < 2 || segment[0] != '{' || segment[len(segment)-1] != '}' {+ continue+ }+ name := strings.TrimSuffix(segment[1:len(segment)-1], "...")+ if name == "" || name == "$" {+ continue+ }+ names = append(names, name)+ }+ return names+}+// RouteContext stamps the matched route name + params onto the request-// context before TokenAuthMiddleware/OpaMiddleware run.-func RouteContext(route string, paramKeys ...string) func(http.Handler) http.Handler {+// context before TokenAuthMiddleware and the authorization stage run.+//+// The parameter names come from the route pattern rather than from a list the+// caller supplies alongside it. A caller-supplied list is a second copy of what+// the pattern already says, and the two can disagree silently: drop a name and+// the policy's input.params.X is undefined, its rule body fails, `default allow+// = false` answers, and the route returns 403 for every request — no compile+// error, no log, and the cause is a deleted string in a different file and a+// different language from the policy that needed it. Deriving them means there+// is no second list to disagree with.+func RouteContext(route string) func(http.Handler) http.Handler {+ paramKeys := routeParamNames(route)return func(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {params := map[string]string{}diff --git a/libs/fleet/backend/auth/ownership.go b/libs/fleet/backend/auth/ownership.gonew file mode 100644index 0000000000..241381c7e3--- /dev/null+++ b/libs/fleet/backend/auth/ownership.go@@ -0,0 +1,20 @@+package auth++import "context"++// OwnedNamespace returns the namespace a request's ownership check is about:+// the {namespace} parameter where the route binds one, and {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+// exist because the answer is needed on both sides — the Rego compares it+// against the token's claims, and the fact provider probes it — and neither can+// read the other's. TestOwnedNamespaceMatchesRego evaluates the rule and this+// 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 namespace, ok := params["namespace"]; ok {+ return namespace+ }+ return params["name"]+}diff --git a/libs/fleet/backend/auth/policy_ast.go b/libs/fleet/backend/auth/policy_ast.gonew file mode 100644index 0000000000..6e5cce84f7--- /dev/null+++ b/libs/fleet/backend/auth/policy_ast.go@@ -0,0 +1,148 @@+package auth++import (+ "fmt"+ "slices"+ "strings"+)++// Node is the policy AST. It is pure data: no compiled Rego, no fs.FS+// handles, no I/O. Optimizers rewrite Node trees; Compile turns a Node into+// an executable plan.+type Node interface{ node() }++// PolicyExpression is the historical name for Node, kept so existing call+// sites and tests continue to compile.+type PolicyExpression = Node++// Leaf is a single Rego query over one or more modules.+type Leaf struct {+ Source PolicySource+ Query string+ Facts []factProviderConfig+ MaxBody int64+}++func (Leaf) node() {}++// AllNode is conjunction.+type AllNode struct{ Children []Node }++func (AllNode) node() {}++// AnyNode is disjunction.+type AnyNode struct{ Children []Node }++func (AnyNode) node() {}++func All(children ...Node) Node {+ if len(children) == 0 {+ panic("OPA All requires at least one policy")+ }+ return AllNode{Children: children}+}++func Any(children ...Node) Node {+ if len(children) == 0 {+ panic("OPA Any requires at least one policy")+ }+ return AnyNode{Children: children}+}++// Policy builds a leaf. It performs no I/O and no compilation; both happen in+// Compile. It still panics on a missing query because that is a pure-data+// programming error detectable without touching the filesystem.+func Policy(source PolicySource, options ...PolicyOption) Node {+ config := policyConfig{}+ for _, option := range options {+ option(&config)+ }+ if config.query == "" {+ panic("OPA policy requires a query")+ }+ if source == nil {+ panic("OPA policy requires a source")+ }+ return Leaf{+ Source: source,+ Query: config.query,+ Facts: config.factProviders,+ MaxBody: config.maxBodyBytes,+ }+}++// key is the structural identity Dedupe uses to decide whether two leaves may+// be merged. It returns "" when the leaf has no stable identity, and any caller+// comparing keys must treat "" as never equal to anything, including itself.+//+// Every component is quoted before joining, for the same reason+// multiPolicySource.sourceKey quotes its children: without it the separators+// are ambiguous and two different leaves can encode to one key. That is not+// theoretical here — a source name and a query are both arbitrary strings, so+// Policy(Registered("x"), Query("y|z")) and Policy(Registered("x|y"),+// Query("z")) collide under an unquoted encoding, and a collision means Dedupe+// deletes one of two policies that check different things.+func (leaf Leaf) key() string {+ if leaf.Source == nil {+ return ""+ }+ sourceKey := leaf.Source.sourceKey()+ if sourceKey == "" {+ return ""+ }+ facts := make([]string, 0, len(leaf.Facts))+ for _, configured := range leaf.Facts {+ facts = append(facts, fmt.Sprintf("%q=%q", configured.namespace, configured.provider.CacheKey()))+ }+ // Sorted so that two leaves listing the same providers in different orders+ // are one key: forPolicy builds a map from them, so order is not meaning.+ slices.Sort(facts)+ return fmt.Sprintf("leaf|%q|%q|%q|%d", sourceKey, leaf.Query, strings.Join(facts, ","), leaf.MaxBody)+}++// Explain renders a Node as an indented tree, for debugging, for golden-plan+// snapshots, and for the optimizer's fixpoint detection.+//+// A leaf whose source has no stable identity prints its Go type rather than+// its path, so two distinct fs sources can render identically. Fixpoint+// detection tolerates a false "equal" (it stops optimizing early, which is+// safe); deciding whether two leaves may be merged must not, which is why+// that decision belongs to key() instead.+func Explain(n Node) string {+ var builder strings.Builder+ explainInto(&builder, n, 0)+ return builder.String()+}++func explainInto(builder *strings.Builder, n Node, depth int) {+ indent := strings.Repeat(" ", depth)+ switch node := n.(type) {+ case Leaf:+ source := "<nil>"+ if node.Source != nil {+ if source = node.Source.sourceKey(); source == "" {+ source = fmt.Sprintf("%T", node.Source)+ }+ }+ fmt.Fprintf(builder, "%sLeaf query=%s source=%s", indent, node.Query, source)+ for _, configured := range node.Facts {+ fmt.Fprintf(builder, " facts=%s@%s", configured.namespace, configured.provider.CacheKey())+ }+ if node.MaxBody > 0 {+ fmt.Fprintf(builder, " body=%d", node.MaxBody)+ }+ builder.WriteString("\n")+ case AllNode:+ fmt.Fprintf(builder, "%sAll\n", indent)+ for _, child := range node.Children {+ explainInto(builder, child, depth+1)+ }+ case AnyNode:+ fmt.Fprintf(builder, "%sAny\n", indent)+ for _, child := range node.Children {+ explainInto(builder, child, depth+1)+ }+ default:+ fmt.Fprintf(builder, "%s<unknown %T>\n", indent, n)+ }+}diff --git a/libs/fleet/backend/auth/policy_ast_test.go b/libs/fleet/backend/auth/policy_ast_test.gonew file mode 100644index 0000000000..bec4283f24--- /dev/null+++ b/libs/fleet/backend/auth/policy_ast_test.go@@ -0,0 +1,260 @@+package auth++import (+ "fmt"+ "strings"+ "testing"+ "testing/fstest"+)++func TestASTIsPureDataAndDoesNotCompile(t *testing.T) {+ // Invalid Rego must NOT panic at construction. Compilation is deferred.+ node := Policy(+ Inline("broken.rego", "this is not valid rego at all"),+ Query("data.broken.allow"),+ )++ leaf, ok := node.(Leaf)+ if !ok {+ t.Fatalf("Policy returned %T, want Leaf", node)+ }+ if leaf.Query != "data.broken.allow" {+ t.Fatalf("Query = %q, want data.broken.allow", leaf.Query)+ }++ if _, err := Compile(node); err == nil {+ t.Fatal("Compile succeeded on invalid Rego, want error")+ }+}++func TestCompileReportsLeafFailuresAsErrors(t *testing.T) {+ // Rewrite passes build Leaf values directly, so Compile must stay+ // fallible for leaves that Policy's constructor guards would have caught.+ cases := []struct {+ name string+ leaf Leaf+ want string+ }{+ {+ name: "nil source",+ leaf: Leaf{Query: "data.p.allow"},+ want: `policy "data.p.allow" has no source`,+ },+ {+ name: "source fails to load",+ leaf: Leaf{Source: Registered("never-registered"), Query: "data.p.allow"},+ want: `load modules for policy "data.p.allow"`,+ },+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ _, err := Compile(testCase.leaf)+ if err == nil {+ t.Fatal("Compile succeeded, want error")+ }+ if !strings.Contains(err.Error(), testCase.want) {+ t.Fatalf("error = %q, want it to contain %q", err, testCase.want)+ }+ })+ }+}++func TestCompileRejectsEmptyCompositeNodes(t *testing.T) {+ // All() and Any() panic on zero children, so this is unreachable today.+ // It stops being unreachable in the optimizer work: Children is exported+ // and rewrite passes build AllNode/AnyNode directly. A fold over zero+ // children returns the identity, so an empty AllNode compiled to an+ // unconditional allow — verified before this guard existed, an empty+ // AllNode served 200 from the downstream handler on every request.+ cases := []struct {+ name string+ node Node+ want string+ }{+ {name: "empty all", node: AllNode{}, want: "policy node auth.AllNode has no children"},+ {name: "empty any", node: AnyNode{}, want: "policy node auth.AnyNode has no children"},+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ _, err := Compile(testCase.node)+ if err == nil {+ t.Fatal("Compile succeeded on an empty node, want error")+ }+ if !strings.Contains(err.Error(), testCase.want) {+ t.Fatalf("error = %q, want it to contain %q", err, testCase.want)+ }+ })+ }+}++func TestCompileWrapsSourceErrorForUnwrapping(t *testing.T) {+ _, err := Compile(Leaf{Source: Registered("never-registered"), Query: "data.p.allow"})+ if err == nil {+ t.Fatal("Compile succeeded, want error")+ }+ // %w, not %v: the underlying cause must survive the added context.+ if !strings.Contains(err.Error(), `OPA policy module "never-registered" is not registered`) {+ t.Fatalf("error = %q, want it to retain the underlying cause", err)+ }+}++func TestPolicyMiddlewarePanicsOnUncompilablePolicy(t *testing.T) {+ // Compilation moved out of Policy, so PolicyMiddleware is now the point+ // that fails fast during route construction.+ defer func() {+ recovered := recover()+ if recovered == nil {+ t.Fatal("PolicyMiddleware did not panic on invalid Rego")+ }+ if !strings.Contains(fmt.Sprint(recovered), "compile policy") {+ t.Fatalf("panic = %v, want it to mention compile policy", recovered)+ }+ }()++ PolicyMiddleware(Policy(+ Inline("broken.rego", "this is not valid rego at all"),+ Query("data.broken.allow"),+ ))+}++func TestExplainRendersTree(t *testing.T) {+ // Registered sources need no registration here: Explain only calls+ // sourceKey(), never modules(), and a registered key is a plain string+ // with no digest in it, so the expected output is stable.+ node := All(+ Policy(Registered("a"), Query("data.a.allow")),+ Any(+ Policy(Registered("b"), Query("data.b.allow"), WithRawBody(1024)),+ Policy(Registered("c"), Query("data.c.allow")),+ ),+ )++ // Compared whole rather than by substring: indentation, child order, and+ // the nesting of Any inside All are the behavior under test.+ want := strings.Join([]string{+ "All",+ " Leaf query=data.a.allow source=registered:a",+ " Any",+ " Leaf query=data.b.allow source=registered:b body=1024",+ " Leaf query=data.c.allow source=registered:c",+ "",+ }, "\n")++ if got := Explain(node); got != want {+ t.Fatalf("Explain output:\n%s\nwant:\n%s", got, want)+ }+}++func TestExplainRendersFactsAndUnstableSources(t *testing.T) {+ node := Policy(+ FromFS(fstest.MapFS{}, "p.rego"),+ Query("data.p.allow"),+ WithFacts("user", &testFactProvider{cacheKey: "user-facts"}),+ )++ // An fs source has no stable identity, so Explain falls back to the Go+ // type rather than inventing one.+ want := "Leaf query=data.p.allow source=auth.fsPolicySource facts=user@user-facts\n"+ if got := Explain(node); got != want {+ t.Fatalf("Explain output:\n%s\nwant:\n%s", got, want)+ }+}++func TestSourceKeyIdentity(t *testing.T) {+ // Registered and inline sources have stable identity; fs sources do not.+ if got := Registered("x").sourceKey(); got != "registered:x" {+ t.Fatalf("registered sourceKey = %q", got)+ }+ a := Inline("n.rego", "package n\n").sourceKey()+ b := Inline("n.rego", "package n\n").sourceKey()+ c := Inline("n.rego", "package n\nallow { true }\n").sourceKey()+ if a != b {+ t.Fatal("identical inline sources produced different keys")+ }+ if a == c {+ t.Fatal("inline sources with different bodies produced the same key")+ }+ if got := FromFS(fstest.MapFS{}, "p.rego").sourceKey(); got != "" {+ t.Fatalf("fs sourceKey = %q, want \"\" (no stable identity)", got)+ }+}++func TestMultiSourceKeyPoisonsOnUnstableChild(t *testing.T) {+ // One child without stable identity makes the whole multi unidentifiable.+ // Anything weaker would let a dedupe pass merge a multi whose fs child+ // might resolve to different Rego.+ stable := Modules(Registered("a"), Registered("b"))+ if stable.sourceKey() == "" {+ t.Fatal("multi of registered sources has no key, want a stable one")+ }+ poisoned := Modules(Registered("a"), FromFS(fstest.MapFS{}, "p.rego"))+ if got := poisoned.sourceKey(); got != "" {+ t.Fatalf("multi with fs child sourceKey = %q, want \"\"", got)+ }+}++func TestMultiSourceKeyIsOrderSensitive(t *testing.T) {+ // Module order is part of what gets compiled, so it must be part of the+ // identity.+ forward := Modules(Registered("a"), Registered("b")).sourceKey()+ reverse := Modules(Registered("b"), Registered("a")).sourceKey()+ if forward == reverse {+ t.Fatalf("Modules(a,b) and Modules(b,a) share key %q", forward)+ }+}++func TestLeafKeyIsInjective(t *testing.T) {+ // key() joins source, query, facts and body limit with separators, so every+ // component has to be quoted or a component containing a separator can be+ // mistaken for the boundary between two of them. A collision here is not a+ // cosmetic bug: Dedupe merges leaves with equal keys, so two policies that+ // check different things would become one, and the one that disappears is+ // never enforced again.+ //+ // Both pairs below are reachable through the public API. Registered takes+ // an arbitrary name, Query takes an arbitrary query, and WithFacts takes an+ // arbitrary namespace; none of them reject a separator.+ cases := []struct {+ name string+ left Leaf+ right Leaf+ }{+ {+ // Unquoted, both encode as leaf|registered:x|y|z||0.+ name: "the boundary between source and query",+ left: Policy(Registered("x"), Query("y|z")).(Leaf),+ right: Policy(Registered("x|y"), Query("z")).(Leaf),+ },+ {+ // Unquoted, both encode the facts field as a=b=c.+ name: "the boundary between a fact namespace and its cache key",+ left: Policy(Registered("s"), Query("q"), WithFacts("a", &testFactProvider{cacheKey: "b=c"})).(Leaf),+ right: Policy(Registered("s"), Query("q"), WithFacts("a=b", &testFactProvider{cacheKey: "c"})).(Leaf),+ },+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ left, right := testCase.left.key(), testCase.right.key()+ if left == "" || right == "" {+ t.Fatalf("a leaf under test has no stable identity: %q and %q", left, right)+ }+ if left == right {+ t.Fatalf("two different leaves share key %q", left)+ }+ })+ }+}++func TestMultiSourceKeyIsInjective(t *testing.T) {+ // Children are quoted before joining, so a separator inside one child's+ // key cannot be confused for the boundary between two children.+ // Unquoted, both of these join to "registered:x,registered:y,registered:z".+ left := Modules(Registered("x,registered:y"), Registered("z")).sourceKey()+ right := Modules(Registered("x"), Registered("y,registered:z")).sourceKey()+ if left == right {+ t.Fatalf("multi keys collide across different groupings: %q", left)+ }+}diff --git a/libs/fleet/backend/auth/policy_characterization_test.go b/libs/fleet/backend/auth/policy_characterization_test.gonew file mode 100644index 0000000000..83c87affe3--- /dev/null+++ b/libs/fleet/backend/auth/policy_characterization_test.go@@ -0,0 +1,503 @@+package auth++import (+ "context"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "testing"++ "github.com/trycua/cloud/pkg/featureflags"+)++// This file records what the authorization stage answers, for every route it+// guards, crossed with every principal shape TokenAuthMiddleware can put on a+// request. The record is a checked-in table.+//+// It exists to make a refactor of the policy provable rather than plausible.+// Splitting one route-aware module into a shared base composed with per-surface+// modules is only correct if no cell of this table moves; a table captured+// against the monolith first is evidence of that, whereas one written afterwards+// would only restate whatever the new modules happen to do.+//+// So: if a cell moves, the change is wrong. Do not regenerate to match it. The+// regeneration flag is here for the case where a row is *added* — a new route,+// a new principal shape, a new parameter case — which is the only edit that+// should ever produce a diff with a clear conscience.+//+// What it drives is the real thing: RouteTree(route) is what main.go dispatches+// that route to, compiled through the same optimizer pipeline PolicyMiddleware+// uses, evaluated over an input built by newRequestPolicyInput. So a route that+// changes surface, or a surface that changes tree, shows up here.+//+// What it does not cover:+//+// - Which HTTP status a verdict becomes. That is PolicyMiddleware's mapping and+// policy_middleware_test.go's subject; this table records allow / deny /+// error, the three values the plan can produce.+// - Anything downstream of the policy. An "allow" in this table means "the+// policy stage let it through", never "the request succeeds". It used to+// mean considerably less than that on /api/svc, /api/orch and GET+// /api/namespaces/{name}, where the namespace-ownership boundary was a Go+// check in the handler and invisible here; those routes now carry it as a+// policy conjunct, and this table records it.+// - Token validation. Every principal here is already authenticated; what+// varies is what the token turned out to be.++// characterizationMethods is the method dimension. It is applied to every route+// rather than only to the methods that route registers: RouteContext stamps the+// route name before the mux has any say, and the policy reads input.method+// directly, so a rule that silently depends on a method the route never serves+// is exactly the kind of thing worth pinning.+var characterizationMethods = []string{+ http.MethodGet,+ http.MethodPost,+ http.MethodPatch,+ http.MethodDelete,+ "QUERY",+}++// characterizationAdminSub is the one sub in admin_subs while this table is+// generated. Every other shape's sub is deliberately different, so the admin row+// is the only one that can satisfy is_admin.+const characterizationAdminSub = "admin-1"++// The three answers the namespace-RBAC probe can give, encoded as namespaces so+// that a route case selects one. A fact provider is a request-time input to the+// policy exactly like the token is, and a table that only ever fed it "allowed"+// would record half a boundary: the deny is what the boundary is *for*, and the+// error is a third verdict — the one that decides between a 502 and a 500.+const (+ characterizationOwnedNamespace = "ns-a"+ characterizationUnownedNamespace = "ns-b"+ characterizationUnreachableNamespace = "ns-err"+)++// characterizationFacts stands in for handlers.NamespaceRBACFacts. It answers+// from the namespace alone and asks nothing about the principal, which is the+// production provider's contract too — which principals are worth probing is+// authz_ownership.rego's decision, and pinning it here is part of the point.+type characterizationFacts struct{}++func (characterizationFacts) CacheKey() string { return NamespaceRBACFactProvider }++func (characterizationFacts) LoadFacts(_ context.Context, request *http.Request) (FactSet, error) {+ switch OwnedNamespace(request.Context()) {+ case characterizationOwnedNamespace:+ return FactSet{"allowed": true}, nil+ case characterizationUnreachableNamespace:+ return nil, &FactUnavailableError{+ Namespace: NamespaceRBACFactNamespace,+ Err: errors.New("apiserver unavailable"),+ }+ default:+ return FactSet{"allowed": false}, nil+ }+}++type principalShape struct {+ name string+ user *User+}++// characterizationPrincipals is every shape a request can carry by the time the+// policy runs. The set is drawn from what TokenAuthMiddleware and+// applyUserKeyIdentity actually produce, not from what the policy happens to+// name — which is the point, since a shape the policy does not name is a shape+// whose verdict nobody chose.+func characterizationPrincipals() []principalShape {+ return []principalShape{+ {name: "spa", user: &User{ID: "u-1", AZP: "cyclops-cs-spa", PrincipalType: PrincipalTypeUser}},+ {name: "cua-cli", user: &User{ID: "u-1", AZP: "cua-cli", PrincipalType: PrincipalTypeUser}},+ {name: "admin-spa", user: &User{ID: characterizationAdminSub, AZP: "cyclops-cs-spa", PrincipalType: PrincipalTypeUser}},+ {name: "per-key-owned-ns", user: &User{ID: "svc-1", AZP: "key-ns-a", Namespace: "ns-a", PrincipalType: PrincipalTypeUser}},+ {name: "per-key-other-ns", user: &User{ID: "svc-1", AZP: "key-ns-z", Namespace: "ns-z", PrincipalType: PrincipalTypeUser}},+ {name: "user-key", user: &User{ID: "u-1", AZP: "ukey-u-1", PrincipalType: PrincipalTypeUser}},+ {name: "user-key-verified", user: &User{ID: "u-1", AZP: "ukey-u-1", PrincipalType: PrincipalTypeUserKey}},+ {name: "github-oidc", user: &User{+ ID: "owner-1",+ AZP: "github-oidc",+ PrincipalType: PrincipalTypeGitHubOIDC,+ Repository: "trycua/cloud",+ AllowedNamespaces: []string{"ns-a"},+ }},+ {name: "oauth2-proxy", user: &User{ID: "u-1", AZP: "oauth2-proxy"}},+ {name: "dcr-client", user: &User{ID: "u-1", AZP: "7c1d9f2a-0e3b-4a51-9c8e-2f6b1d7a4c05", PrincipalType: PrincipalTypeUser}},+ {name: "empty-sub", user: &User{ID: "", AZP: "cyclops-cs-spa", PrincipalType: PrincipalTypeUser}},+ }+}++// routeCase is one route with one set of path parameters. Several cases per+// route is how the parameter-shaped rules — DNS-label validation, the per-key+// namespace binding, the infra k8s path list, the GitHub namespace grant — get+// both of their answers recorded rather than just whichever one a single+// example happened to hit.+type routeCase struct {+ name string+ params map[string]string+ // path is the request URL. Only /api/k8s reads it (through+ // pool_admission's own params.path), but PolicyMiddleware builds an+ // input.path for every leaf, so every case sets one.+ path string+ body string+}++// characterizationCases lists the parameter cases for every route. A route with+// no entry fails the test rather than being skipped — an unlisted route is one+// whose verdicts nobody recorded.+func characterizationCases() map[string][]routeCase {+ cases := map[string][]routeCase{}++ simple := func(route, path string) {+ cases[route] = []routeCase{{name: "plain", params: map[string]string{}, path: path}}+ }+ simple("/api/config", "/api/config")+ simple("/api/state/query", "/api/state/query")+ simple("/api/billing/summary", "/api/billing/summary")+ simple("/api/billing/setup-session", "/api/billing/setup-session")+ simple("/api/billing/portal-session", "/api/billing/portal-session")+ simple("/api/keys", "/api/keys")+ simple("/api/namespaces", "/api/namespaces")+ simple("/api/user-keys", "/api/user-keys")+ simple("/api/github-trust-policies", "/api/github-trust-policies")++ withID := func(route, prefix string) {+ cases[route] = []routeCase{{+ name: "id",+ params: map[string]string{"id": "id-1"},+ path: prefix + "/id-1",+ }}+ }+ withID("/api/keys/{id}", "/api/keys")+ withID("/api/user-keys/{id}", "/api/user-keys")+ withID("/api/github-trust-policies/{id}", "/api/github-trust-policies")++ // /api/namespaces/{name} needs all three fact answers, and only on GET: the+ // ownership conjunct binds to that one method, and DELETE sharing the route+ // is what makes the method dimension load-bearing here rather than merely+ // thorough.+ cases["/api/namespaces/{name}"] = []routeCase{+ {+ name: "name",+ params: map[string]string{"name": characterizationOwnedNamespace},+ path: "/api/namespaces/" + characterizationOwnedNamespace,+ },+ {+ name: "unowned-name",+ params: map[string]string{"name": characterizationUnownedNamespace},+ path: "/api/namespaces/" + characterizationUnownedNamespace,+ },+ {+ name: "unreachable-name",+ params: map[string]string{"name": characterizationUnreachableNamespace},+ path: "/api/namespaces/" + characterizationUnreachableNamespace,+ },+ }++ // /api/svc and /api/orch gate on the DNS-label shape of their parameters,+ // on the namespace claim matching the path for per-key and GitHub tokens,+ // and on the RBAC fact for everyone else. owned-ns / other-ns / unreachable-ns+ // are the three answers the fact provider gives.+ proxyCases := func(withPath bool) []routeCase {+ suffix := ""+ params := func(namespace, service string) map[string]string {+ out := map[string]string{"namespace": namespace, "service": service}+ if withPath {+ out["path"] = "v1/status"+ }+ return out+ }+ if withPath {+ suffix = "/v1/status"+ }+ return []routeCase{+ {name: "owned-ns", params: params(characterizationOwnedNamespace, "svc-a"), path: "/api/svc/ns-a/svc-a" + suffix},+ {name: "other-ns", params: params(characterizationUnownedNamespace, "svc-a"), path: "/api/svc/ns-b/svc-a" + suffix},+ {name: "unreachable-ns", params: params(characterizationUnreachableNamespace, "svc-a"), path: "/api/svc/ns-err/svc-a" + suffix},+ {name: "invalid-ns", params: params("Not_A_Label", "svc-a"), path: "/api/svc/Not_A_Label/svc-a" + suffix},+ {name: "invalid-service", params: params(characterizationOwnedNamespace, "Svc_A"), path: "/api/svc/ns-a/Svc_A" + suffix},+ {name: "empty-ns", params: params("", "svc-a"), path: "/api/svc//svc-a" + suffix},+ }+ }+ cases["/api/svc/{namespace}/{service}"] = proxyCases(false)+ cases["/api/svc/{namespace}/{service}/{path...}"] = proxyCases(true)++ orchCase := func(name, namespace string) routeCase {+ return routeCase{+ name: name,+ params: map[string]string{"namespace": namespace, "service": "svc-a", "path": "catalog"},+ path: "/api/orch/" + namespace + "/svc-a/catalog",+ }+ }+ cases["/api/orch/{namespace}/{service}/{path...}"] = []routeCase{+ orchCase("owned-ns", characterizationOwnedNamespace),+ orchCase("other-ns", characterizationUnownedNamespace),+ orchCase("unreachable-ns", characterizationUnreachableNamespace),+ orchCase("invalid-ns", "Not_A_Label"),+ }++ // /api/k8s carries the richest parameter logic in the policy: the infra-path+ // list, the admin escape hatch over it, the GitHub namespace grant, and the+ // pool-admission leaf reading the body.+ k8sPaths := []struct {+ name string+ path string+ body string+ }{+ {name: "namespaced-pods", path: "api/v1/namespaces/ns-a/pods"},+ {name: "cluster-nodes", path: "api/v1/nodes"},+ {name: "cluster-pods", path: "api/v1/pods"},+ {name: "cyclops-configmaps", path: "api/v1/namespaces/cyclops-cs/configmaps/batch-configs"},+ {name: "capsule-tenants", path: "apis/capsule.clastix.io/v1beta2/tenants"},+ {name: "cluster-claims", path: "apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims"},+ {name: "granted-ns-pools", path: "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools"},+ {name: "ungranted-ns-pools", path: "apis/cua.ai/v1/namespaces/ns-b/osgymworkspacepools"},+ {name: "granted-ns-claims", path: "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims"},+ // The event feed, in each of the four addressing forms the apiserver+ // serves it under, crossed with the two API groups that serve it. These+ // are the only k8s paths every principal shape is denied on — including+ // admin-spa, which the infra-path rows show getting an escape hatch — so+ // a deny that stopped covering one of them shows up here as an allow+ // appearing in a column that has none.+ {name: "cluster-events", path: "api/v1/events"},+ {name: "namespaced-events", path: "api/v1/namespaces/ns-a/events"},+ {name: "group-cluster-events", path: "apis/events.k8s.io/v1/events"},+ {name: "group-namespaced-events", path: "apis/events.k8s.io/v1/namespaces/ns-a/events"},+ {name: "legacy-watch-events", path: "api/v1/watch/events"},+ {name: "legacy-watch-namespaced-events", path: "api/v1/watch/namespaces/ns-a/events"},+ // The same legacy alias over the cluster-wide collections the infra deny+ // exists to hide. These stream what api/v1/pods and api/v1/nodes list, so+ // their rows must read exactly like those two do.+ {name: "legacy-watch-cluster-pods", path: "api/v1/watch/pods"},+ {name: "legacy-watch-cluster-nodes", path: "api/v1/watch/nodes"},+ // A group whose name merely starts with the events group. It recorded an+ // allow when this surface was a denylist, which is what made the event+ // deny falsifiable; under the allowlist it is denied like anything else+ // nobody enumerated, and the precision of is_event_k8s_path is pinned+ // directly in authz_k8s_test.rego instead.+ {name: "event-group-collision", path: "apis/events.k8s.io.evil/v1/events"},++ // The allowlist's own shapes. The collection cases above cover GET and+ // POST; these cover the item and subresource forms, the one core read+ // that is a subresource, and a discovery path.+ {name: "claim-item", path: "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims/claim-1"},+ {name: "claim-status", path: "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims/claim-1/status"},+ {name: "pod-logs", path: "api/v1/namespaces/ns-a/pods/pod-1/log"},+ {name: "discovery", path: "openapi/v2"},+ // And the decision the allowlist makes that a reader is most likely to+ // want to check: reading a Secret through the proxy is not on it.+ {name: "namespaced-secrets", path: "api/v1/namespaces/ns-a/secrets/ecr-credentials"},+ {+ name: "pool-create-allowed-image",+ path: "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools",+ body: `{"spec":{"template":{"containerDiskImage":"296062593712.dkr.ecr.us-west-2.amazonaws.com/osgym-workspace:latest","imagePullSecret":"ecr-credentials"}}}`,+ },+ {+ name: "pool-create-disallowed-image",+ path: "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools",+ body: `{"spec":{"template":{"containerDiskImage":"evil.example/workspace:latest","imagePullSecret":"ecr-credentials"}}}`,+ },+ }+ k8s := make([]routeCase, 0, len(k8sPaths))+ for _, k8sPath := range k8sPaths {+ body := k8sPath.body+ if body == "" {+ body = "{}"+ }+ k8s = append(k8s, routeCase{+ name: k8sPath.name,+ params: map[string]string{"path": k8sPath.path},+ path: "/api/k8s/" + k8sPath.path,+ body: body,+ })+ }+ cases["/api/k8s/{path...}"] = k8s++ return cases+}++// characterizationRequest rebuilds what the authorization stage is handed:+// RouteContext's route and params, TokenAuthMiddleware's User, and a body the+// raw-body leaves can read.+func characterizationRequest(route string, testCase routeCase, method string, user *User) *http.Request {+ request := httptest.NewRequest(method, "http://cyclops-cs.test"+testCase.path, strings.NewReader(testCase.body))+ if testCase.body == "" {+ request.Body = io.NopCloser(strings.NewReader(""))+ }+ ctx := request.Context()+ ctx = context.WithValue(ctx, routeKey, route)+ ctx = context.WithValue(ctx, paramsKey, testCase.params)+ ctx = context.WithValue(ctx, UserKey, user)+ return request.WithContext(ctx)+}++func verdictName(value truth) string {+ switch value {+ case truthTrue:+ return "allow"+ case truthFalse:+ return "deny"+ default:+ return "error"+ }+}++const characterizationGoldenPath = "testdata/route-authorization-table.txt"++// TestRouteAuthorizationCharacterization is the acceptance criterion for any+// change to how routes are bound to policies or how those policies are+// factored. It fails on any moved cell, and its message says so rather than+// suggesting a regeneration.+func TestRouteAuthorizationCharacterization(t *testing.T) {+ t.Setenv("CYCLOPS_CS_ADMIN_SUBS", fmt.Sprintf(`[%q]`, characterizationAdminSub))+ if err := featureflags.SetupProvider(context.Background(), "development", featureflags.AWSCredentials{}); err != nil {+ t.Fatalf("setup dev provider: %v", err)+ }+ LoadOpa()+ // The ownership conjunct reaches a FactProvider through the registry, so the+ // table is only reproducible if the provider answering it is. Registered for+ // the whole test rather than per case: what varies is the namespace asked+ // about, which is a route case, not a different provider.+ RegisterFactProvider(NamespaceRBACFactProvider, characterizationFacts{})+ resetFlagsCache()+ // The resolved flags outlive t.Setenv, so drop them again rather than leaving+ // a cached admin_subs behind for whichever test runs next.+ t.Cleanup(resetFlagsCache)++ routes := AuthenticatedRoutes()+ cases := characterizationCases()+ for _, route := range routes {+ if len(cases[route]) == 0 {+ t.Fatalf(`route %q has no entry in characterizationCases, so no verdict of its is+recorded. Add at least one parameter case for it.`, route)+ }+ }+ for route := range cases {+ if _, ok := RouteSurface(route); !ok {+ t.Fatalf("characterizationCases lists %q, which is not an authenticated route", route)+ }+ }++ // One compiled plan per surface, exactly as production shares them.+ plans := map[string]*CompiledPolicy{}+ for _, name := range SurfaceNames() {+ tree, ok := SurfaceTree(name)+ if !ok {+ t.Fatalf("SurfaceNames returned %q, which SurfaceTree does not resolve", name)+ }+ compiled, err := Compile(Optimize(tree, DefaultPipeline()))+ if err != nil {+ t.Fatalf("compile surface %q: %v", name, err)+ }+ plans[name] = compiled+ }++ principals := characterizationPrincipals()+ var lines []string+ for _, route := range routes {+ surface, _ := RouteSurface(route)+ plan := plans[surface]+ for _, testCase := range cases[route] {+ for _, method := range characterizationMethods {+ for _, principal := range principals {+ request := characterizationRequest(route, testCase, method, principal.user)+ result := plan.eval(request.Context(), newRequestPolicyInput(request, plan.bodyBudget))+ lines = append(lines, fmt.Sprintf("%s | %s | %s | %s = %s",+ route, testCase.name, method, principal.name, verdictName(result.truth)))+ }+ }+ }+ }+ sort.Strings(lines)+ got := strings.Join(lines, "\n") + "\n"++ if *updateGolden {+ if err := os.MkdirAll(filepath.Dir(characterizationGoldenPath), 0o755); err != nil {+ t.Fatalf("mkdir testdata: %v", err)+ }+ if err := os.WriteFile(characterizationGoldenPath, []byte(got), 0o644); err != nil {+ t.Fatalf("write %s: %v", characterizationGoldenPath, err)+ }+ return+ }++ want, err := os.ReadFile(characterizationGoldenPath)+ if err != nil {+ t.Fatalf("read %s (generate with: go test ./auth/ -run TestRouteAuthorizationCharacterization -update-golden): %v",+ characterizationGoldenPath, err)+ }+ if got == string(want) {+ return+ }++ diff := characterizationDiff(strings.Split(strings.TrimSuffix(string(want), "\n"), "\n"), lines)+ t.Fatalf(`the route authorization table changed:++%s+Every line above is a request the policy stage answers differently than it did+when this table was recorded. If you are refactoring how the policy is+structured, that is the refactor being wrong, and the fix is in the policy, not+in this file. Regenerate only when the diff is purely added or removed rows —+a new route, principal shape, or parameter case:++ go test ./auth/ -run TestRouteAuthorizationCharacterization -update-golden`, diff)+}++// characterizationDiff reports moved cells separately from added and removed+// rows, because the two mean opposite things: a moved cell is an authorization+// change, and an added or removed row is usually just a wider table.+func characterizationDiff(want, got []string) string {+ split := func(lines []string) map[string]string {+ out := make(map[string]string, len(lines))+ for _, line := range lines {+ key, verdict, found := strings.Cut(line, " = ")+ if !found {+ continue+ }+ out[key] = verdict+ }+ return out+ }+ wanted, current := split(want), split(got)++ var moved, added, removed []string+ for key, verdict := range current {+ previous, existed := wanted[key]+ switch {+ case !existed:+ added = append(added, fmt.Sprintf(" + %s = %s", key, verdict))+ case previous != verdict:+ moved = append(moved, fmt.Sprintf(" ! %s: %s -> %s", key, previous, verdict))+ }+ }+ for key, verdict := range wanted {+ if _, ok := current[key]; !ok {+ removed = append(removed, fmt.Sprintf(" - %s = %s", key, verdict))+ }+ }+ sort.Strings(moved)+ sort.Strings(added)+ sort.Strings(removed)++ var builder strings.Builder+ section := func(title string, entries []string) {+ if len(entries) == 0 {+ return+ }+ fmt.Fprintf(&builder, "%s (%d):\n", title, len(entries))+ for _, entry := range entries {+ builder.WriteString(entry)+ builder.WriteString("\n")+ }+ }+ section("MOVED VERDICTS", moved)+ section("ADDED ROWS", added)+ section("REMOVED ROWS", removed)+ return builder.String()+}diff --git a/libs/fleet/backend/auth/policy_cost.go b/libs/fleet/backend/auth/policy_cost.gonew file mode 100644index 0000000000..f89dffcdd6--- /dev/null+++ b/libs/fleet/backend/auth/policy_cost.go@@ -0,0 +1,273 @@+package auth++import "slices"++// This file gives the optimizer a reason to prefer one child order over+// another, and the pass that acts on it.+//+// Reordering children is legal because All is min and Any is max over+// truthFalse < truthError < truthTrue (see policy_plan.go), and min and max are+// commutative. That says every order computes the same answer; it says nothing+// about what each order costs to compute. The cost model below is what turns+// "any order will do" into "this order is the cheap one", and sinkFactLoaders+// is what applies it: cheap request-attribute checks move in front of leaves+// that would buffer a body or call a database, so a cheap deny can+// short-circuit an expensive call away entirely.++// costClass is the coarse tier of a leaf's evaluation cost, ordered cheapest+// first. The tier dominates the comparison, so a class boundary is a promise:+// no weight, however large or however nonsensical a provider reports, can float+// a database call in front of a pure check.+type costClass uint8++const (+ costPure costClass = iota // method, path, route, params, user, flags+ costBody // buffers the raw request body+ costFacts // calls a FactProvider: a database or an API+)++// Compile-time assertions on the ordering, in the same spirit as the lattice+// assertions in policy_plan.go. costLess compares classes with <, so permuting+// the block above does not produce a compile error anywhere — it silently+// inverts what the pass considers cheap. These fail to compile instead.+//+// The subtraction is what overflows; the uint conversion is belt-and-braces so+// the assertions keep working if costClass ever becomes a signed type, where a+// negative difference would otherwise be legal. Written the same way as+// policy_plan.go's for the same reason, so the two blocks stay recognisably one+// idiom.+const (+ _ = uint(costBody - costPure)+ _ = uint(costFacts - costBody)++ // costPure must be the zero value, so that a cost{} — the answer for a node+ // kind this file does not recognise, and for a childless composite — reads+ // as "free" rather than as an accidental tier.+ _ = uint(0 - costPure)+)++// cost is an estimate of what evaluating a node costs. class is the tier;+// weight only ever breaks ties within one tier.+type cost struct {+ class costClass+ weight int+}++func costLess(left, right cost) bool {+ if left.class != right.class {+ return left.class < right.class+ }+ return left.weight < right.weight+}++// costCompare orders two costs for a stable sort: negative when left is+// cheaper, zero when neither is cheaper than the other. Returning 0 for ties+// rather than 1 is what lets the stable sort see them as ties at all.+func costCompare(left, right cost) int {+ switch {+ case costLess(left, right):+ return -1+ case costLess(right, left):+ return 1+ default:+ return 0+ }+}++// costModel estimates a leaf's cost. It is an interface so that adaptive,+// statistics-driven planning can arrive later as a second implementation+// rather than as a rewrite of sinkFactLoaders.+//+// The seam is narrower than that sentence suggests, and the limit is worth+// knowing before anyone relies on it: a model prices leaves. How an interior+// node is priced from its children is sinkChildren's rule — the minimum — not+// the model's. An adaptive model is exactly the one that would want a say+// there, pricing a subtree from observed short-circuit rates rather than from+// its cheapest child, and it would have to change sinkChildren to get it.+//+// It is unexported, with an unexported method, because nothing outside this+// package can supply one: the design doc reserves a WithCostModel plan option+// for the adaptive case, and until that option exists an exported interface+// would be one nobody could pass anywhere. The shape is what matters and the+// shape is preserved; exporting it later is a rename.+type costModel interface {+ leafCost(Leaf) cost+}++// CostReporter is an optional interface a FactProvider may implement to declare+// that it is dearer than the default. Implementing it is optional in the+// strongest sense: staticTiers type-asserts it, so a provider that does not+// implement it is weighed as one unit and is otherwise unaffected. That is why+// FactProvider itself did not have to change, and why providers living outside+// this package — the reason this one interface is exported — can opt in one at+// a time.+//+// The number is a relative weight, not a latency or a currency. It orders+// fact-loading leaves against each other and nothing else: costFacts is still+// costFacts, so a provider reporting 0 does not become as cheap as a path+// check, and one reporting a huge number cannot push a body-reading sibling+// below a pure one. A negative number is accepted and does the same thing in+// the other direction — it can only move a leaf earlier among fact leaves — so+// there is nothing to guard, but there is also no reason to return one.+//+// FactCost is asked while the plan is built, never while a request runs: it is+// called from Optimize during route construction, and Optimize repeats its+// pipeline to a fixpoint, so one provider may be asked several times for one+// route. Return a constant. A value derived from live statistics — a rolling+// p99, a queue depth — would be read at startup and then frozen into the plan+// anyway, and if it drifted between calls within one Optimize it would keep+// changing the tree and burn sweeps against the fixpoint cap to no purpose.+// Adaptive planning is a costModel's job, not a provider's.+//+// Weights add up across the distinct cache keys on one leaf. A leaf carrying+// one plain provider and one reporting 50 weighs 51, so a provider is declaring+// its own share of a total rather than the whole leaf's cost.+type CostReporter interface {+ FactCost() int+}++// staticTiers derives cost purely from a leaf's declared configuration. It+// reads nothing but the Leaf, so it is deterministic and needs no request.+type staticTiers struct{}++// leafCost tiers a leaf by the dearest thing it needs.+//+// Facts are checked first, so a leaf carrying both fact providers and a body+// limit classifies as costFacts: it will do both, and the dearer of the two is+// what the tier is for. Ordering the checks the other way would hide a database+// call behind a body limit.+//+// Within costFacts the weight is the number of *distinct* cache keys, not the+// number of providers. Fact results are cached per request across the whole+// tree (see requestPolicyInput.resolveFacts), so a second consumer of a key+// already loaded costs nothing, and counting it would make a leaf that reuses+// one provider look dearer than one that loads two.+//+// The first provider listed for a cache key is the one charged; later ones are+// skipped before their CostReporter is consulted. That only becomes visible if+// two *different* provider values share a CacheKey and disagree about their+// cost, in which case the weight depends on their order in leaf.Facts. Sharing+// a cache key already asserts they are the same load — resolveFacts will call+// exactly one of them and hand the result to both — so declaring different+// costs for it is a contradiction in the input rather than a case to arbitrate.+// It is written down because it is the one answer this model gives that depends+// on something the author did not know they were choosing.+func (staticTiers) leafCost(leaf Leaf) cost {+ if len(leaf.Facts) > 0 {+ seen := make(map[string]bool, len(leaf.Facts))+ weight := 0+ for _, configured := range leaf.Facts {+ key := configured.provider.CacheKey()+ if seen[key] {+ continue+ }+ seen[key] = true+ if reporter, ok := configured.provider.(CostReporter); ok {+ weight += reporter.FactCost()+ continue+ }+ weight+++ }+ return cost{class: costFacts, weight: weight}+ }+ if leaf.MaxBody > 0 {+ return cost{class: costBody, weight: 1}+ }+ return cost{class: costPure}+}++// defaultCostModel is the model every pipeline uses today. It is a package+// variable rather than a constant expression so that the future WithCostModel+// option has something to displace.+var defaultCostModel costModel = staticTiers{}++// sinkFactLoaders stable-sorts each node's children by ascending cost, so that+// cheap request-attribute checks get the chance to short-circuit expensive fact+// loads away.+//+// Ascending is correct for both node kinds, with no special case: All stops at+// the first false, so a cheap deny in front saves the expensive leaf, and Any+// stops at the first true, so a cheap allow in front does. Either way the+// cheapest child is the one lazy evaluation is guaranteed to pay for.+//+// This is sound only because of the lattice in policy_plan.go. Under the+// earlier abort-on-error semantics the verdict depended on which child failed+// first, and moving a fallible leaf could turn a 500 into a 200.+func sinkFactLoaders(n Node) Node {+ sunk, _ := sinkNode(n, defaultCostModel)+ return sunk+}++// sinkNode returns the rewritten node and what it costs, in one pass. The cost+// travels back up with the node because a parent needs its children's costs to+// sort them, and computing them separately would walk each subtree once per+// comparison.+func sinkNode(n Node, model costModel) (Node, cost) {+ switch node := n.(type) {+ case Leaf:+ // Returned as-is, never rebuilt. Compile rejects a Leaf with a nil+ // Source, and a pass that reassembled one from parts is how that+ // happens; there is nothing here this pass needs to change.+ return node, model.leafCost(node)+ case AllNode:+ children, lowest := sinkChildren(node.Children, model)+ return AllNode{Children: children}, lowest+ case AnyNode:+ children, lowest := sinkChildren(node.Children, model)+ return AnyNode{Children: children}, lowest+ }+ // An unknown node kind is not something to guess a cost for. cost{} is the+ // cheapest value, so it sorts first and is evaluated first — and Compile+ // then refuses the tree by name.+ return n, cost{}+}++// sinkChildren rewrites each child bottom-up, sorts the results by ascending+// cost, and reports the minimum.+//+// The minimum is the right cost for the interior node because the recursion is+// bottom-up: by the time this returns, the cheapest child is the one sitting in+// front, and under lazy evaluation that is the only child the parent is certain+// to pay for. Reporting the maximum would price a subtree by work it may well+// short-circuit past.+//+// Sorting permutes; it cannot empty a composite, so no childless node is+// created here. An input that was already childless is passed through with+// cost{} — malformed input that compileChildren rejects by name, and not+// something to invent a tier for.+func sinkChildren(children []Node, model costModel) ([]Node, cost) {+ type priced struct {+ node Node+ cost cost+ }++ // The minimum is accumulated here rather than read off sorted[0] afterwards,+ // which the ascending sort makes the same value. Two separate claims — "the+ // pass sorts ascending" and "an interior node is priced at its minimum" —+ // are worth being able to break, and test, one at a time.+ sorted := make([]priced, len(children))+ lowest := cost{}+ for index, child := range children {+ node, childCost := sinkNode(child, model)+ sorted[index] = priced{node: node, cost: childCost}+ if index == 0 || costLess(childCost, lowest) {+ lowest = childCost+ }+ }++ // Stable, so declaration order is the tiebreak. That preserves author+ // intent among equally cheap checks, makes the pass idempotent — an+ // unstable sort could permute ties differently on a second run, and+ // Optimize's fixpoint loop runs every pass at least twice — and keeps a+ // plan reproducible across replicas rather than depending on a sort's+ // internal pivot choices.+ slices.SortStableFunc(sorted, func(left, right priced) int {+ return costCompare(left.cost, right.cost)+ })++ nodes := make([]Node, len(sorted))+ for index, child := range sorted {+ nodes[index] = child.node+ }+ return nodes, lowest+}diff --git a/libs/fleet/backend/auth/policy_cost_test.go b/libs/fleet/backend/auth/policy_cost_test.gonew file mode 100644index 0000000000..ffcc808ce1--- /dev/null+++ b/libs/fleet/backend/auth/policy_cost_test.go@@ -0,0 +1,523 @@+package auth++import (+ "context"+ "fmt"+ "math/rand"+ "net/http"+ "slices"+ "strings"+ "testing"+)++// These tests measure the cost model and the pass that sorts by it.+//+// The differential harness in policy_equivalence_test.go cannot help here. It+// proves sinkFactLoaders does not change what a policy decides, and a pass that+// returned its input would satisfy that perfectly — measured with every pass+// stubbed out to the identity, TestOptimizerPreservesSemantics was green across+// all 300 seeds. Soundness and effectiveness are separate questions and only+// the tests below ask the second one.+//+// The leaf builders — allowLeaf, denyLeaf, bodyLeaf, factLeaf, loadingFacts —+// live in policy_optimize_test.go's shared helpers block.++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++// pricyProvider declares itself dearer than the default through the optional+// CostReporter interface.+type pricyProvider struct{ key string }++func (provider pricyProvider) CacheKey() string { return provider.key }+func (pricyProvider) FactCost() int { return 50 }+func (pricyProvider) LoadFacts(context.Context, *http.Request) (FactSet, error) {+ return FactSet{"ok": true}, nil+}++func leafOf(t *testing.T, n Node) Leaf {+ t.Helper()+ leaf, ok := n.(Leaf)+ if !ok {+ t.Fatalf("node is %T, want a Leaf", n)+ }+ return leaf+}++// queryOrder returns the leaf queries in the order Explain renders them, which+// for a tree of composites is the order lazy evaluation visits them.+func queryOrder(n Node) []string {+ var queries []string+ for _, line := range strings.Split(Explain(n), "\n") {+ _, rest, found := strings.Cut(line, "Leaf query=")+ if !found {+ continue+ }+ query, _, _ := strings.Cut(rest, " ")+ queries = append(queries, query)+ }+ return queries+}++// leafMultiset renders every leaf in a tree and sorts the renderings, so two+// trees compare equal exactly when they hold the same leaves with the same+// multiplicities, whatever the order or the nesting.+func leafMultiset(n Node) []string {+ var leaves []string+ for _, line := range strings.Split(Explain(n), "\n") {+ trimmed := strings.TrimSpace(line)+ if strings.HasPrefix(trimmed, "Leaf ") {+ leaves = append(leaves, trimmed)+ }+ }+ slices.Sort(leaves)+ return leaves+}++// ---------------------------------------------------------------------------+// The cost model+// ---------------------------------------------------------------------------++func TestStaticTiersClassifiesLeavesByWhatTheyNeed(t *testing.T) {+ pure := staticTiers{}.leafCost(leafOf(t, allowLeaf("p")))+ body := staticTiers{}.leafCost(leafOf(t, bodyLeaf("b")))+ facts := staticTiers{}.leafCost(leafOf(t, factLeaf("f", loadingFacts("tier"))))++ if pure.class != costPure {+ t.Errorf("a leaf reading only request attributes = class %d, want costPure (%d)", pure.class, costPure)+ }+ if body.class != costBody {+ t.Errorf("a WithRawBody leaf = class %d, want costBody (%d)", body.class, costBody)+ }+ if facts.class != costFacts {+ t.Errorf("a WithFacts leaf = class %d, want costFacts (%d)", facts.class, costFacts)+ }++ // The ordering itself, not just the labels. costLess compares classes with+ // <, so a permuted const block would keep every assertion above true while+ // inverting what the pass calls cheap.+ if !costLess(pure, body) {+ t.Errorf("pure %+v is not cheaper than body %+v", pure, body)+ }+ if !costLess(body, facts) {+ t.Errorf("body %+v is not cheaper than facts %+v", body, facts)+ }+ if !costLess(pure, facts) {+ t.Errorf("pure %+v is not cheaper than facts %+v", pure, facts)+ }+}++func TestStaticTiersClassifiesAFactsAndBodyLeafAsFacts(t *testing.T) {+ // A leaf that does both is priced by the dearer of the two. Checking the+ // body limit first would hide a database call behind it.+ both := Policy(+ Inline("both.rego", "package both\nallow { input.facts.u0.ok }\n"),+ Query("data.both.allow"),+ WithFacts("u0", loadingFacts("both")),+ WithRawBody(costBodyLimit),+ )+ if got := (staticTiers{}).leafCost(leafOf(t, both)); got.class != costFacts {+ t.Fatalf("a leaf with facts and a body limit = class %d, want costFacts (%d)", got.class, costFacts)+ }+}++func TestStaticTiersWeighsDistinctCacheKeysOnly(t *testing.T) {+ // Fact results are cached per request across the whole tree, so a second+ // consumer of a key already loaded costs nothing. Counting providers+ // instead of keys would price the two leaves below the same, and would make+ // a leaf that reuses one provider look as dear as one that loads two.+ shared := loadingFacts("shared")+ other := loadingFacts("other")++ repeated := staticTiers{}.leafCost(leafOf(t, factLeaf("repeat", shared, shared)))+ distinct := staticTiers{}.leafCost(leafOf(t, factLeaf("distinct", shared, other)))+ single := staticTiers{}.leafCost(leafOf(t, factLeaf("single", shared)))++ if repeated.weight != 1 {+ t.Errorf("two providers sharing a cache key weigh %d, want 1", repeated.weight)+ }+ if distinct.weight != 2 {+ t.Errorf("two providers with distinct cache keys weigh %d, want 2", distinct.weight)+ }+ if repeated.weight != single.weight {+ t.Errorf("reusing a provider changed the weight: %d vs %d", repeated.weight, single.weight)+ }+ if !costLess(repeated, distinct) {+ t.Errorf("one cache key %+v is not cheaper than two %+v", repeated, distinct)+ }++ // The first provider listed for a key is the one charged, so when two+ // different provider values share a cache key and disagree about their cost,+ // the weight follows declaration order. Sharing a key asserts they are the+ // same load, so disagreeing about its cost is a contradiction in the input —+ // but the model still has to answer, and this is the answer. Pinned so that+ // changing which one wins is a decision someone makes on purpose.+ plainFirst := staticTiers{}.leafCost(leafOf(t, factLeaf("plainfirst",+ &testFactProvider{cacheKey: "collide", facts: FactSet{"ok": true}},+ pricyProvider{key: "collide"})))+ reporterFirst := staticTiers{}.leafCost(leafOf(t, factLeaf("reporterfirst",+ pricyProvider{key: "collide"},+ &testFactProvider{cacheKey: "collide", facts: FactSet{"ok": true}})))++ if plainFirst.weight != 1 {+ t.Errorf("plain provider declared first weighs %d, want 1 (the first provider for a key is charged)", plainFirst.weight)+ }+ if reporterFirst.weight != 50 {+ t.Errorf("reporting provider declared first weighs %d, want 50 (the first provider for a key is charged)", reporterFirst.weight)+ }+}++func TestStaticTiersHonorsOptionalCostReporter(t *testing.T) {+ cheap := staticTiers{}.leafCost(leafOf(t, factLeaf("c", loadingFacts("cheap"))))+ pricey := staticTiers{}.leafCost(leafOf(t, factLeaf("d", pricyProvider{key: "pricy"})))++ if !costLess(cheap, pricey) {+ t.Fatalf("weights = %d, %d; a CostReporter provider should outweigh a default one", cheap.weight, pricey.weight)+ }+ if pricey.weight != 50 {+ t.Errorf("declared weight = %d, want the reported 50", pricey.weight)+ }+ // Opting in must not move a provider between tiers, in either direction.+ // The weight orders fact leaves against each other and nothing else.+ if pricey.class != costFacts {+ t.Errorf("a CostReporter provider = class %d, want costFacts (%d)", pricey.class, costFacts)+ }+ if !costLess(staticTiers{}.leafCost(leafOf(t, bodyLeaf("bb"))), pricey) {+ t.Error("a body leaf is no longer cheaper than a self-declared expensive fact leaf")+ }+}++func TestStaticTiersLeavesNonReportingProvidersAlone(t *testing.T) {+ // The control for the case above: a provider that does not implement+ // CostReporter must weigh one unit, so "optional" means optional rather+ // than "required, defaulting to whatever the last reporter said".+ if got := (staticTiers{}).leafCost(leafOf(t, factLeaf("n", loadingFacts("plain")))); got.weight != 1 {+ t.Fatalf("a plain FactProvider weighs %d, want 1", got.weight)+ }+ mixed := staticTiers{}.leafCost(leafOf(t, factLeaf("m", loadingFacts("plain-2"), pricyProvider{key: "pricy-2"})))+ if mixed.weight != 51 {+ t.Fatalf("a plain provider beside a reporting one weighs %d, want 51", mixed.weight)+ }+}++func TestCostCompareIsAProperOrdering(t *testing.T) {+ // slices.SortStableFunc's contract is a comparison that is antisymmetric and+ // reports ties as 0. Pinned directly, because the sort does not enforce it:+ // a costCompare that answered 1 for a tie — plausible, since costLess-style+ // helpers often return "not less" as "greater" — violates the contract while+ // leaving every ordering test above green, measured. Go's stable sort only+ // ever swaps on a strictly negative answer, so today it happens to survive a+ // comparator that never returns 0. That is an implementation detail of the+ // sort, not a promise, and it is the whole basis of the stability the plan+ // depends on.+ costs := []cost{+ {class: costPure},+ {class: costPure, weight: 3},+ {class: costBody, weight: 1},+ {class: costFacts, weight: 1},+ {class: costFacts, weight: 50},+ }++ for _, left := range costs {+ if got := costCompare(left, left); got != 0 {+ t.Errorf("costCompare(%+v, itself) = %d, want 0", left, got)+ }+ for _, right := range costs {+ forward, backward := costCompare(left, right), costCompare(right, left)+ if forward != -backward {+ t.Errorf("costCompare(%+v, %+v) = %d but the reverse = %d; the comparison is not antisymmetric",+ left, right, forward, backward)+ }+ if (forward < 0) != costLess(left, right) {+ t.Errorf("costCompare(%+v, %+v) = %d disagrees with costLess = %t",+ left, right, forward, costLess(left, right))+ }+ }+ }+}++// ---------------------------------------------------------------------------+// Effectiveness: the calls the pass removes+// ---------------------------------------------------------------------------++func TestSinkFactLoadersSkipsProviderBehindCheapDeny(t *testing.T) {+ // The test the whole plan exists for. Everything in the differential+ // harness is green against a pass that does nothing; this is not.+ //+ // The baseline is in here rather than beside it, because on its own the+ // zero proves nothing — a provider that was never wired up also loads zero+ // times. Only the same tree with optimization off, loading exactly once,+ // makes the zero attributable to the pass. Split across two test functions+ // the assertion could be run by -run without its control, which is the+ // wrong failure mode for a pair whose whole point is that one half is what+ // gives the other meaning.+ optimized := loadingFacts("sink-effectiveness")+ if status := runPolicyStatus(t, All(factLeaf("expensive", optimized), denyLeaf("cheapdeny"))); status != http.StatusForbidden {+ t.Fatalf("optimized status = %d, want %d", status, http.StatusForbidden)+ }+ if optimized.loads != 0 {+ t.Fatalf("fact provider called %d times, want 0 (it should have been sunk behind the cheap deny)", optimized.loads)+ }++ baseline := loadingFacts("sink-baseline")+ if status := runPolicyStatus(t, All(factLeaf("expensive2", baseline), denyLeaf("cheapdeny2")), WithPipeline()); status != http.StatusForbidden {+ t.Fatalf("baseline status = %d, want %d", status, http.StatusForbidden)+ }+ if baseline.loads != 1 {+ t.Fatalf("baseline fact provider called %d times, want 1 (this is what proves the pass is what saves the call)", baseline.loads)+ }+}++func TestSinkFactLoadersSkipsProviderBehindCheapAllowUnderAny(t *testing.T) {+ // Ascending order is correct for Any too, and for the mirror-image reason:+ // a disjunction stops at the first true, so the cheap allow in front is+ // what removes the load. A pass that special-cased All would leave this one+ // loading. Paired with its own baseline for the same reason as above.+ optimized := loadingFacts("sink-any-optimized")+ if status := runPolicyStatus(t, Any(factLeaf("anyexpensive", optimized), allowLeaf("cheapallow"))); status != http.StatusNoContent {+ t.Fatalf("optimized status = %d, want %d", status, http.StatusNoContent)+ }+ if calls := optimized.loads; calls != 0 {+ t.Fatalf("fact provider called %d times, want 0 (it should have been sunk behind the cheap allow)", calls)+ }++ baseline := loadingFacts("sink-any-baseline")+ if status := runPolicyStatus(t, Any(factLeaf("anyexpensive2", baseline), allowLeaf("cheapallow2")), WithPipeline()); status != http.StatusNoContent {+ t.Fatalf("baseline status = %d, want %d", status, http.StatusNoContent)+ }+ if calls := baseline.loads; calls != 1 {+ t.Fatalf("baseline fact provider called %d times, want 1", calls)+ }+}++// ---------------------------------------------------------------------------+// What the pass does to the tree+// ---------------------------------------------------------------------------++func TestSinkSortsAscendingInBothKinds(t *testing.T) {+ provider := loadingFacts("ascending")+ cases := []struct {+ name string+ node Node+ }{+ {"conjunction", All(factLeaf("facts", provider), bodyLeaf("body"), allowLeaf("pure"))},+ {"disjunction", Any(factLeaf("facts", provider), bodyLeaf("body"), allowLeaf("pure"))},+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ got := queryOrder(Optimize(testCase.node, []string{"sink-facts"}))+ want := []string{"data.pure.allow", "data.body.allow", "data.facts.allow"}+ if !slices.Equal(got, want) {+ t.Fatalf("order = %v, want %v (cheapest first)", got, want)+ }+ })+ }+}++func TestSinkIsStableForEqualCosts(t *testing.T) {+ // This test can only fail if the input satisfies two conditions at once:+ // more than twelve children, and costs that are not all equal. Both are+ // deliberate, and both were measured against slices.SortFunc standing in for+ // an unstable sort.+ //+ // More than twelve, because sort.Slice and slices.SortFunc are unstable in+ // principle but dispatch to insertion sort — which is stable — for short+ // inputs. pdqsort's cutoff is twelve, so declaration order survives up to+ // twelve children and is scrambled from thirteen. A deterministic threshold,+ // not a probability: a short test does not flake, it simply always passes.+ //+ // Not all equal, because when every comparison returns 0 pdqsort's+ // already-sorted detection short-circuits unconditionally and the input is+ // never permuted — at any size. All-equal input is inert whether it is 3+ // children or 200, so scaling an all-equal test up past twelve fixes+ // nothing. The costs below alternate pure and facts to give the sort real+ // work to do.+ //+ // Both conditions, or the test proves nothing. This is not hypothetical: the+ // version in the plan was three equal-cost leaves, and it was run verbatim+ // under an unstable sort and passed.+ //+ // Twenty-four rather than thirteen for margin, because the cutoff is a Go+ // runtime internal: if a future toolchain raises it past the child count,+ // this test goes quietly green against an unstable sort.+ const children = 24++ var declared []Node+ var wantPure, wantFacts []string+ for index := 0; index < children; index++ {+ name := fmt.Sprintf("s%02d", index)+ if index%2 == 0 {+ declared = append(declared, denyLeaf(name))+ wantPure = append(wantPure, "data."+name+".allow")+ continue+ }+ declared = append(declared, factLeaf(name, loadingFacts(name)))+ wantFacts = append(wantFacts, "data."+name+".allow")+ }++ got := queryOrder(Optimize(All(declared...), []string{"sink-facts"}))+ want := append(append([]string{}, wantPure...), wantFacts...)+ if !slices.Equal(got, want) {+ t.Fatalf("order =\n%v\nwant\n%v\n(equal-cost leaves must keep declaration order)", got, want)+ }+}++func TestSinkUsesTheMinimumChildCostForInteriorNodes(t *testing.T) {+ // An interior node is priced at its cheapest child, because after the+ // bottom-up sort that child is in front and is the only one lazy evaluation+ // is certain to pay for.+ //+ // The sibling sits strictly between the subtree's minimum and its maximum,+ // which is what makes min and max distinguishable here: priced at its+ // minimum the subtree is pure and moves in front of the body leaf; priced+ // at its maximum it is facts and stays behind it.+ //+ // The subtree is declared dearest-first so that its own sort has to happen+ // too. A subtree already in cheap-first order would let a pass that priced+ // interior nodes correctly but never recursed pass this.+ provider := loadingFacts("interior")+ node := All(bodyLeaf("sibling"), Any(factLeaf("dearinner", provider), allowLeaf("cheapinner")))++ got := queryOrder(Optimize(node, []string{"sink-facts"}))+ want := []string{"data.cheapinner.allow", "data.dearinner.allow", "data.sibling.allow"}+ if !slices.Equal(got, want) {+ t.Fatalf("order = %v, want %v (the subtree costs its minimum, so it sorts ahead of the body leaf)", got, want)+ }+}++func TestSinkRecursesIntoNestedNodes(t *testing.T) {+ // Two levels below the root, and under both kinds, so a pass that sorted+ // only the node it was handed — or only one composite kind — is caught.+ provider := loadingFacts("nested")+ node := All(+ Any(+ factLeaf("deepfacts", provider),+ All(bodyLeaf("deepbody"), allowLeaf("deeppure")),+ ),+ )++ got := queryOrder(Optimize(node, []string{"sink-facts"}))+ want := []string{"data.deeppure.allow", "data.deepbody.allow", "data.deepfacts.allow"}+ if !slices.Equal(got, want) {+ t.Fatalf("order = %v, want %v", got, want)+ }+}++func TestSinkLeavesChildlessCompositesForCompileToReject(t *testing.T) {+ // Sorting permutes, so it cannot empty a composite — but it also must not+ // swallow one it was handed. A childless conjunction is the one rewrite+ // outcome that turns into an unconditional allow rather than a wrong+ // answer, and only compileChildren stands between it and a 200.+ node := AllNode{Children: []Node{allowLeaf("a"), AnyNode{}}}+ got := Optimize(node, []string{"sink-facts"})++ if empty := emptyCompositeIn(got); empty == nil {+ t.Fatalf("sink-facts swallowed the childless composite:\n%s", Explain(got))+ }+ if _, err := Compile(got); err == nil {+ t.Fatalf("Compile accepted a tree with a childless composite:\n%s", Explain(got))+ }+}++// ---------------------------------------------------------------------------+// Pass ordering+// ---------------------------------------------------------------------------++func TestFlattenAndSinkDoNotCommuteWithinOneSweep(t *testing.T) {+ // TestStructuralPassesCommuteToTheSameFixpoint records that flatten,+ // collapse and dedupe can be run in any order because each only exposes+ // work for the others. sink-facts is the pass that ends that: its output is+ // not a normal form, and a nested composite is a wall it cannot sort+ // across.+ //+ // All(All(facts, pureA), pureB): flattened first, all three leaves are+ // siblings and pureB gets in front of the fact loader. Sunk first, the+ // nesting still separates them, and flattening afterwards leaves the fact+ // load ahead of a pure check that could have short-circuited it.+ provider := loadingFacts("ordering")+ node := All(All(factLeaf("ordfacts", provider), allowLeaf("puream")), allowLeaf("purebee"))++ flattenFirst := queryOrder(sinkFactLoaders(flatten(node)))+ sinkFirst := queryOrder(flatten(sinkFactLoaders(node)))++ wantFlattenFirst := []string{"data.puream.allow", "data.purebee.allow", "data.ordfacts.allow"}+ if !slices.Equal(flattenFirst, wantFlattenFirst) {+ t.Fatalf("flatten then sink = %v, want %v", flattenFirst, wantFlattenFirst)+ }+ wantSinkFirst := []string{"data.puream.allow", "data.ordfacts.allow", "data.purebee.allow"}+ if !slices.Equal(sinkFirst, wantSinkFirst) {+ t.Fatalf("sink then flatten = %v, want %v", sinkFirst, wantSinkFirst)+ }+ if slices.Equal(flattenFirst, sinkFirst) {+ t.Fatalf("the two orders agree (%v); this test no longer pins an ordering dependence", flattenFirst)+ }++ // Optimize's fixpoint loop rescues the wrong order — it re-runs sink after+ // flatten on the next sweep — but it pays a sweep for it. That is the+ // concrete cost of the ordering in defaultPipeline, so it is measured+ // rather than asserted in prose. The counter is appended, so it runs once+ // per sweep without changing what converges.+ sweeps := func(pipeline ...string) int {+ count := 0+ name := fmt.Sprintf("test-sweep-%s", strings.Join(pipeline, "-"))+ registerTestPass(t, name, func(n Node) Node {+ count+++ return n+ })+ Optimize(node, append(slices.Clone(pipeline), name))+ return count+ }++ rightOrder := sweeps("flatten", "sink-facts")+ wrongOrder := sweeps("sink-facts", "flatten")+ t.Logf("sweeps to converge: flatten-then-sink %d, sink-then-flatten %d", rightOrder, wrongOrder)+ if rightOrder >= wrongOrder {+ t.Fatalf("flatten-then-sink took %d sweeps and sink-then-flatten took %d; the default pipeline's order buys nothing",+ rightOrder, wrongOrder)+ }+}++// ---------------------------------------------------------------------------+// Invariants over the generated corpus+// ---------------------------------------------------------------------------++func TestSinkPreservesTheLeafMultisetOverGeneratedTrees(t *testing.T) {+ // A reordering pass may permute; it may not add, drop or substitute. Run+ // over the whole generated corpus rather than one hand-built tree, because+ // the failure mode is a slice-handling slip that only some shapes reach.+ for seed := int64(1); seed <= equivalenceSeeds; seed++ {+ node := genTree(rand.New(rand.NewSource(seed)), equivalenceDepth).astNode()+ sunk := sinkFactLoaders(node)++ before, after := leafMultiset(node), leafMultiset(sunk)+ if !slices.Equal(before, after) {+ t.Fatalf("seed %d: leaf multiset changed\n--- before ---\n%s\n--- after ---\n%s",+ seed, Explain(node), Explain(sunk))+ }+ if again := sinkFactLoaders(sunk); Explain(again) != Explain(sunk) {+ t.Fatalf("seed %d: sink-facts is not idempotent\n--- once ---\n%s\n--- twice ---\n%s",+ seed, Explain(sunk), Explain(again))+ }+ }+}++func TestSinkRewritesAFairShareOfGeneratedTrees(t *testing.T) {+ // The floor that says the pass does something on real input. Measured, it+ // reorders 213 of 300 generated trees on its own.+ const wantAtLeast = equivalenceSeeds / 4++ rewritten := 0+ for seed := int64(1); seed <= equivalenceSeeds; seed++ {+ node := genTree(rand.New(rand.NewSource(seed)), equivalenceDepth).astNode()+ if Explain(sinkFactLoaders(node)) != Explain(node) {+ rewritten+++ }+ }++ t.Logf("sink-facts reordered %d of %d generated trees", rewritten, equivalenceSeeds)+ if rewritten < wantAtLeast {+ t.Errorf("sink-facts reordered %d of %d trees, want at least %d", rewritten, equivalenceSeeds, wantAtLeast)+ }+}diff --git a/libs/fleet/backend/auth/policy_equivalence_test.go b/libs/fleet/backend/auth/policy_equivalence_test.gonew file mode 100644index 0000000000..9f321f8f53--- /dev/null+++ b/libs/fleet/backend/auth/policy_equivalence_test.go@@ -0,0 +1,880 @@+package auth++import (+ "errors"+ "fmt"+ "math/rand"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++// This file is the oracle the optimizer is measured against. It compares the+// real evaluator with a naive reference interpreter over randomly generated+// policy trees, so that a pass which reorders leaves has something to be wrong+// against.+//+// The reference is total: it visits every child and folds with min (All) and+// max (Any). The real evaluator short-circuits on the annihilating value. The+// two nonetheless agree on the *set* of errors, for a reason worth stating+// because the whole harness rests on it: a verdict carries errors only when its+// truth is truthError, and a fold reaches truthError only when no child+// returned the annihilator — which means the loop ran to completion and visited+// every child. So whenever errors are observable at all, the lazy evaluator saw+// exactly the set the total one did. When an annihilator does win, both throw+// the errors away.+//+// The file reads in dependency order: the reference model, then the AST the+// model is turned into, then the generator, then the comparison harness, then+// the tests that drive it.++// ---------------------------------------------------------------------------+// Reference model+//+// The specification. Everything here is written to be checkable by reading it,+// and deliberately shares no code with the evaluator it judges.+// ---------------------------------------------------------------------------++// refTruth is the reference lattice, ordered refFalse < refError < refTrue.+// It is spelled out here rather than reusing the evaluator's truth type on+// purpose: an oracle that imports its subject's definition of the answer can+// only ever confirm it. evaluatorTruth is the one place the two representations+// are allowed to meet.+type refTruth uint8++const (+ refFalse refTruth = iota+ refError+ refTrue+)++// Compile-time assertions on the reference lattice, mirroring the ones truth+// carries in policy_plan.go. refCombine is min and max over this order, so the+// order is not decoration: reorder the block above and the oracle quietly+// becomes a different specification, one that would then accuse the evaluator+// of the oracle's own bug. The subtraction is what overflows; the uint+// conversion keeps the assertions working if refTruth ever becomes signed.+const (+ _ = uint(refError - refFalse)+ _ = uint(refTrue - refError)++ // refFalse must be the zero value, so that a refVerdict{} left unfilled+ // reads as a deny rather than an allow.+ _ = uint(0 - refFalse)+)++// evaluatorTruth maps a reference value onto the evaluator's. The switch is+// exhaustive with a panicking default so that adding a value to either lattice+// is a change someone has to make here on purpose, rather than one that+// silently lands on truthError and makes the comparison agree by accident.+func (value refTruth) evaluatorTruth() truth {+ switch value {+ case refFalse:+ return truthFalse+ case refError:+ return truthError+ case refTrue:+ return truthTrue+ default:+ panic(fmt.Sprintf("no evaluator truth for reference truth %d", uint8(value)))+ }+}++// behavior is a scripted leaf outcome. Each one exercises a distinct path into+// a verdict: two definite answers, the two independent ways a leaf becomes+// undecidable (fact loading and Rego evaluation), and the two body outcomes.+//+// Every switch over a behavior in this file is exhaustive and panics on an+// unknown one. That is load-bearing rather than tidy: a new behavior absorbed+// by a default arm would be scripted by the oracle and by the AST builder as+// the same thing, so the two would agree about a leaf nobody implemented and+// the per-behavior test would report success for it.+type behavior uint8++const (+ behaviorAllow behavior = iota+ behaviorDeny+ behaviorFactError+ behaviorRegoError+ behaviorBodyOK+ behaviorBodyOverLimit+ behaviorCount+)++// sourceVariant selects which Rego module a leaf's behavior is scripted in.+// The reference evaluator ignores it entirely — a leaf's verdict comes from its+// behavior and nothing else — so it changes only the shape of the AST the+// evaluator is handed.+//+// It exists because of a measured hole. The first version of this generator+// derived a leaf's module, its query, its facts and its body limit all from the+// behavior, which made source ↔ (query, facts, MaxBody) a bijection: no two+// generated leaves could share a module while differing in anything else.+// Mutating dedupeChildren to key on Leaf.Source.sourceKey() alone — an unsound+// merge, since leaves sharing a module can ask different questions of it — left+// all 300 seeds green. variantSharedSource is the shape that was missing.+type sourceVariant uint8++const (+ // variantOwnSource gives each behavior a module of its own, so a source+ // implies the rest of the leaf. The zero value, and the only variant the+ // 300-seed corpus draws, which is what keeps those trees exactly what they+ // were.+ variantOwnSource sourceVariant = iota++ // variantSharedSource puts every behavior in one module, so two leaves+ // drawn this way share a source and differ only in the query they name, the+ // facts they carry or the body limit they declare. Every one of those three+ // axes has a pair that differs in it alone, which is what a dedupe keyed on+ // any proper subset of Leaf.key() gets wrong:+ //+ // query only: behaviorAllow vs behaviorRegoError+ // facts only: behaviorDeny vs behaviorFactError+ // body only: behaviorAllow vs behaviorBodyOverLimit+ //+ // The last two are the narrow ones — those pairs agree on source and query+ // and differ in a single field of the leaf.+ variantSharedSource++ sourceVariantCount+)++type refKind uint8++const (+ refLeaf refKind = iota+ refAll+ refAny+)++type refTree struct {+ kind refKind+ leaf behavior+ source sourceVariant+ kids []refTree+}++// refVerdict is a reference result. bodyErr and otherErr track which kinds of+// error survive, because the middleware maps a surviving body error to 400 and+// anything else to 500.+type refVerdict struct {+ truth refTruth+ bodyErr bool+ otherErr bool+}++func (result refVerdict) status() int {+ switch result.truth {+ case refTrue:+ return http.StatusNoContent+ case refFalse:+ return http.StatusForbidden+ case refError:+ if result.bodyErr {+ return http.StatusBadRequest+ }+ return http.StatusInternalServerError+ default:+ panic(fmt.Sprintf("no status for reference truth %d", uint8(result.truth)))+ }+}++// verdict is the reference evaluator. It never short-circuits: every child is+// visited and combined, so the result is a plain fold of min (All) or max (Any)+// over the lattice and is order-independent by construction rather than by+// argument.+func (tree refTree) verdict() refVerdict {+ if tree.kind == refLeaf {+ switch tree.leaf {+ case behaviorAllow, behaviorBodyOK:+ return refVerdict{truth: refTrue}+ case behaviorDeny:+ return refVerdict{truth: refFalse}+ case behaviorFactError, behaviorRegoError:+ return refVerdict{truth: refError, otherErr: true}+ case behaviorBodyOverLimit:+ return refVerdict{truth: refError, bodyErr: true}+ default:+ panic(fmt.Sprintf("reference evaluator scripts no verdict for behavior %d", uint8(tree.leaf)))+ }+ }++ result := refVerdict{truth: refTrue}+ if tree.kind == refAny {+ result = refVerdict{truth: refFalse}+ }+ for _, kid := range tree.kids {+ result = refCombine(tree.kind, result, kid.verdict())+ }+ return result+}++// refCombine is min for All and max for Any, carrying the union of both+// operands' error kinds. The union is dropped whenever the result is not+// refError, which is what makes an annihilator discard its siblings' errors —+// the same thing the real fold does, arrived at without a special case.+func refCombine(kind refKind, left, right refVerdict) refVerdict {+ combined := refVerdict{+ bodyErr: left.bodyErr || right.bodyErr,+ otherErr: left.otherErr || right.otherErr,+ }+ if kind == refAll {+ combined.truth = min(left.truth, right.truth)+ } else {+ combined.truth = max(left.truth, right.truth)+ }+ if combined.truth != refError {+ combined.bodyErr, combined.otherErr = false, false+ }+ return combined+}++// ---------------------------------------------------------------------------+// AST construction+//+// Turning a scripted tree into the real Node the evaluator runs, and building+// the request it runs against.+// ---------------------------------------------------------------------------++const (+ // equivalenceRequestBody is the body every generated request carries.+ equivalenceRequestBody = "0123456789"++ // The two raw-body limits the body behaviors use. Wide sits above the+ // request body and narrow below it, which is the whole reason+ // behaviorBodyOK allows and behaviorBodyOverLimit errors. Because the plan+ // reads once against the widest limit in the tree, each leaf's own limit+ // then decides its own outcome, so neither behavior depends on which of+ // them ran first.+ equivalenceWideBodyLimit = 1024+ equivalenceNarrowBodyLimit = 2+)++// The relationship the comment above describes, made executable. Retuning+// either limit past the request body silently turns a body behavior into its+// opposite, and every expectation in the reference would follow it.+const (+ _ = uint(equivalenceWideBodyLimit - len(equivalenceRequestBody))+ _ = uint(len(equivalenceRequestBody) - equivalenceNarrowBodyLimit - 1)+)++// equivalenceModule is the Rego every generated leaf runs: one rule per+// behavior, in whichever package the leaf's sourceVariant asks for.+//+// One template rather than a module per behavior, because a leaf's source has to+// be free to vary independently of its behavior. If a module contained only the+// rule its leaf needs, the module would give the behavior away and two leaves+// could never share one while asking different questions of it — the hole+// sourceVariant documents.+//+// Only the rule a leaf's query names is evaluated, which is why the conflicting+// pair can sit in every package without spoiling any other behavior scripted+// beside it. behaviorRegoError depends on that conflict being an+// evaluation-time error rather than a compile-time one: it is the one path to+// truthError that a broken fact provider does not cover, and a module that+// failed to compile would take every behavior in it down instead.+func equivalenceModule(pkg string) string {+ return fmt.Sprintf(`package %s+allow { true }+needsfacts { input.facts.u.ok }+conflict = 1 { true }+conflict = 2 { true }+conflicted { conflict == 1 }+bodymatch { input.body == %q }+`, pkg, equivalenceRequestBody)+}++// packageName is the module a leaf of this variant puts its behavior in.+func (variant sourceVariant) packageName(scripted behavior) string {+ switch variant {+ case variantOwnSource:+ return fmt.Sprintf("eq%d", scripted)+ case variantSharedSource:+ return "eqshared"+ default:+ panic(fmt.Sprintf("no package scripted for source variant %d", uint8(variant)))+ }+}++// leafPolicy is what a behavior is made of: the rule that decides it, and the+// leaf configuration it needs to decide that way. Which module the rule lives in+// is deliberately not here — that is the sourceVariant's business, and keeping+// the two apart is what lets a source and a behavior vary independently.+type leafPolicy struct {+ rule string+ options []PolicyOption+}++func (scripted behavior) policy() leafPolicy {+ switch scripted {+ case behaviorAllow:+ return leafPolicy{rule: "allow"}+ case behaviorDeny:+ // needsfacts with nothing to load. input.facts.u.ok is then an+ // undefined reference, which makes the rule undefined and the leaf a+ // deny — an undefined path in Rego is not an error.+ //+ // Deliberately the same rule as behaviorFactError, and deliberately+ // without its provider: under variantSharedSource these two agree on+ // source, on query and on MaxBody, and differ in Facts alone. That is+ // the third axis a leaf can differ on, and until this pairing existed+ // nothing generated could reach it — behaviorFactError was the only+ // scripted leaf carrying a provider and also the only one naming this+ // rule, so a facts difference never appeared without a query difference+ // beside it. A dedupe keyed on everything but Facts merges these two,+ // and 403 becomes 500 or the reverse.+ return leafPolicy{rule: "needsfacts"}+ case behaviorFactError:+ return leafPolicy{rule: "needsfacts", options: []PolicyOption{+ WithFacts("u", &testFactProvider{+ cacheKey: "equivalence-broken",+ err: errors.New("database unavailable"),+ }),+ }}+ case behaviorRegoError:+ return leafPolicy{rule: "conflicted"}+ case behaviorBodyOK:+ return leafPolicy{rule: "bodymatch", options: []PolicyOption{WithRawBody(equivalenceWideBodyLimit)}}+ case behaviorBodyOverLimit:+ // Deliberately the same rule as behaviorAllow. Under+ // variantSharedSource these two leaves then agree on source and on+ // query and differ in MaxBody alone, so a dedupe that ignored MaxBody+ // would merge a leaf that allows with one that must 400.+ return leafPolicy{rule: "allow", options: []PolicyOption{WithRawBody(equivalenceNarrowBodyLimit)}}+ default:+ panic(fmt.Sprintf("no policy scripted for behavior %d", uint8(scripted)))+ }+}++// astNode builds the real AST. Two leaves are structurally identical exactly+// when they share a behavior and a source variant, which is what a dedupe pass+// has to merge — and nothing weaker, which is what it has to refuse.+func (tree refTree) astNode() Node {+ if tree.kind != refLeaf {+ kids := make([]Node, 0, len(tree.kids))+ for _, kid := range tree.kids {+ kids = append(kids, kid.astNode())+ }+ if tree.kind == refAll {+ return All(kids...)+ }+ return Any(kids...)+ }++ pkg := tree.source.packageName(tree.leaf)+ scripted := tree.leaf.policy()+ options := append(+ []PolicyOption{Query(fmt.Sprintf("data.%s.%s", pkg, scripted.rule))},+ scripted.options...,+ )+ return Policy(Inline(pkg+".rego", equivalenceModule(pkg)), options...)+}++// newEquivalenceRequest builds the request every comparison runs against. The+// harness evaluates each tree twice, through Compile and through+// PolicyMiddleware, and the two must see the same request: two construction+// sites that have to agree is the desync harnessMode exists to prevent, and+// there is no reason to leave it unprevented for the request.+func newEquivalenceRequest() *http.Request {+ return httptest.NewRequest(http.MethodPost, "/", strings.NewReader(equivalenceRequestBody))+}++// ---------------------------------------------------------------------------+// Generator+// ---------------------------------------------------------------------------++const (+ // equivalenceSeeds is the fixed seed range. Fixed rather than time-seeded+ // so a failure is reproducible from the seed printed in the message alone.+ equivalenceSeeds = 300++ // equivalenceDepth bounds generated trees. The generator and the assertion+ // that every depth appears both read it, so the two cannot drift.+ equivalenceDepth = 4+)++// drawSource is where the generator's decisions come from. The seed corpus+// draws from math/rand; the fuzz target in policy_fuzz_test.go draws from the+// fuzzer's byte string. One generator behind both is what makes a shape+// reachable by one reachable by the other.+type drawSource interface {+ // intn returns a value in [0, n) for a positive n.+ intn(n int) int+}++// randDraws is the math/rand implementation, and the only one the fixed seed+// range uses.+type randDraws struct{ rng *rand.Rand }++func (source randDraws) intn(n int) int { return source.rng.Intn(n) }++// genConfig is the whole of what the seed corpus and the fuzz target disagree+// about.+type genConfig struct {+ depth int++ // sourceVariants bounds the sourceVariant values leaves may be drawn from.+ // One means variantOwnSource and — this is the part that matters — no draw+ // at all, so the fixed seed range consumes exactly the random stream it+ // consumed before variants existed and the floors in+ // TestEquivalenceGeneratorProducesDistinctTrees still describe the same 300+ // trees.+ sourceVariants int+}++// genTree builds a random tree of at most the given depth from the fixed seed+// range's generator: one source variant, so a leaf is its behavior.+func genTree(rng *rand.Rand, depth int) refTree {+ return genTreeFrom(randDraws{rng: rng}, genConfig{depth: depth, sourceVariants: 1})+}++// genTreeFrom builds a random tree. The root is always a composite. A bare leaf+// has nothing for an optimizer to get wrong, and with only six behaviors it+// collapses whatever fraction of the draws produce it onto six trees —+// measured, that cost a third of the seeds and a third of the distinct shapes.+// TestReferenceMatchesEveryLeafBehavior covers leaves alone.+func genTreeFrom(draw drawSource, config genConfig) refTree {+ return genComposite(draw, config, config.depth)+}++func genComposite(draw drawSource, config genConfig, depth int) refTree {+ kind := refAll+ if draw.intn(2) == 0 {+ kind = refAny+ }+ kids := make([]refTree, 1+draw.intn(3))+ for index := range kids {+ kids[index] = genSubtree(draw, config, depth-1)+ }+ return refTree{kind: kind, kids: kids}+}++func genSubtree(draw drawSource, config genConfig, depth int) refTree {+ if depth == 0 || draw.intn(3) == 0 {+ return genLeaf(draw, config)+ }+ return genComposite(draw, config, depth)+}++func genLeaf(draw drawSource, config genConfig) refTree {+ leaf := refTree{kind: refLeaf, leaf: behavior(draw.intn(int(behaviorCount)))}+ if config.sourceVariants > 1 {+ leaf.source = sourceVariant(draw.intn(config.sourceVariants))+ }+ return leaf+}++// signature is a structural identity for a generated tree, used to prove the+// generator is not emitting the same handful of trees under every seed.+func (tree refTree) signature() string {+ var builder strings.Builder+ tree.signatureInto(&builder)+ return builder.String()+}++func (tree refTree) signatureInto(builder *strings.Builder) {+ if tree.kind == refLeaf {+ fmt.Fprintf(builder, "L%d", tree.leaf)+ if tree.source != variantOwnSource {+ // Only when it is not the default, so that the fixed seed range's+ // signatures — and the distinct-tree floor counted from them — are+ // the strings they were before variants existed. A leaf's source+ // still has to appear, because two leaves differing only in it+ // build different ASTs.+ fmt.Fprintf(builder, "@%d", tree.source)+ }+ return+ }+ if tree.kind == refAll {+ builder.WriteString("All(")+ } else {+ builder.WriteString("Any(")+ }+ for index, kid := range tree.kids {+ if index > 0 {+ builder.WriteString(",")+ }+ kid.signatureInto(builder)+ }+ builder.WriteString(")")+}++func treeDepth(tree refTree) int {+ deepest := 0+ for _, kid := range tree.kids {+ if depth := treeDepth(kid) + 1; depth > deepest {+ deepest = depth+ }+ }+ return deepest+}++func collectVariety(tree refTree, kinds map[refKind]bool, leaves map[behavior]bool) {+ if tree.kind == refLeaf {+ leaves[tree.leaf] = true+ return+ }+ kinds[tree.kind] = true+ for _, kid := range tree.kids {+ collectVariety(kid, kinds, leaves)+ }+}++// ---------------------------------------------------------------------------+// Comparison harness+// ---------------------------------------------------------------------------++// harnessMode says how the plan under test is built. The comparison looks at+// the plan twice — once through Compile for the verdict and once through+// PolicyMiddleware for the status — and those two have to be the same plan. If+// the verdict half tested an unoptimized tree while the status half tested an+// optimized one, the comparison would still be green and would be comparing+// nothing.+type harnessMode struct {+ plan func(Node) Node+ options []MiddlewareOption+}++// modeRunning derives both halves of a mode from one list of pass names, so+// they cannot disagree. Written as two literals, "these options reproduce that+// rewrite" was a claim in a comment; here it is the only thing either half is+// built from.+func modeRunning(passes ...string) harnessMode {+ return harnessMode{+ plan: func(node Node) Node { return Optimize(node, passes) },+ options: []MiddlewareOption{WithPipeline(passes...)},+ }+}++var (+ unoptimizedMode = modeRunning()+ optimizedMode = modeRunning(DefaultPipeline()...)+)++func runPolicyStatus(t *testing.T, node Node, options ...MiddlewareOption) int {+ t.Helper()+ handler := PolicyMiddleware(node, options...)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, newEquivalenceRequest())+ return response.Code+}++// errorKinds splits a verdict's error into the two classes the middleware+// distinguishes. It walks the whole error graph rather than asking errors.As+// twice, because errors.As can only answer "is there a body error in here" and+// the harness also needs "is there anything else in here" — otherwise a fold+// that dropped every non-body error would still look right.+//+// Both unwrap shapes have to be followed. A join gives Unwrap() []error and a+// %w chain gives Unwrap() error, and stopping at a single-error wrapper would+// hand the rest of the question to errors.As, which reports the first body+// error it finds and says nothing about what sits beside it. Nothing in the+// evaluator wraps today — fold only joins, and leaves return raw errors — but+// the cost of being wrong here is the classifier silently agreeing with a+// misclassification it exists to catch, so it does not depend on that.+//+// An unwrap that yields nothing is not evidence of nothing. Implementing the+// interface is not a promise of a cause: OPA's *topdown.Error has Unwrap()+// error and returns nil from it, so descending unconditionally would classify+// every Rego evaluation error as no error at all. Both arms therefore fall+// through to the leaf handling below when they come back empty.+func errorKinds(err error) (bodyErr, otherErr bool) {+ switch unwrappable := err.(type) {+ case nil:+ return false, false+ case interface{ Unwrap() []error }:+ if children := unwrappable.Unwrap(); len(children) > 0 {+ for _, child := range children {+ childBody, childOther := errorKinds(child)+ bodyErr, otherErr = bodyErr || childBody, otherErr || childOther+ }+ return bodyErr, otherErr+ }+ case interface{ Unwrap() error }:+ // Annotation, not a second failure: a wrapped body error is still one+ // body error, so this reports the cause rather than counting the+ // wrapper as an "other". Classifying the wrapper separately would make+ // every leaf that gained a context string look like two errors and put+ // the reference's per-behavior flags permanently out of step.+ if cause := unwrappable.Unwrap(); cause != nil {+ return errorKinds(cause)+ }+ }+ var body policyBodyError+ if errors.As(err, &body) {+ return true, false+ }+ return false, true+}++// assertMatchesReference is the differential comparison. It checks the plan's+// verdict — truth, and which kinds of error survived — and then the status the+// middleware derives from it, because a harness that only compared statuses+// would let three distinct verdicts collapse onto 500.+func assertMatchesReference(t *testing.T, mode harnessMode, label string, tree refTree) {+ t.Helper()+ want := tree.verdict()+ node := mode.plan(tree.astNode())++ compiled, err := Compile(node)+ if err != nil {+ t.Fatalf("%s: compile: %v\n%s", label, err, Explain(node))+ }+ request := newEquivalenceRequest()+ got := compiled.eval(request.Context(), newRequestPolicyInput(request, compiled.bodyBudget))++ if got.truth != want.truth.evaluatorTruth() {+ t.Errorf("%s: truth = %d, want %d\n%s", label, got.truth, want.truth.evaluatorTruth(), Explain(node))+ }+ // verdict documents err as non-nil if and only if truth is truthError.+ // Nothing else asserts that invariant over generated input.+ if (got.err != nil) != (got.truth == truthError) {+ t.Errorf("%s: truth = %d with err = %v, want an error exactly when undecided\n%s", label, got.truth, got.err, Explain(node))+ }+ gotBodyErr, gotOtherErr := errorKinds(got.err)+ if gotBodyErr != want.bodyErr || gotOtherErr != want.otherErr {+ t.Errorf("%s: error kinds = (body %t, other %t), want (body %t, other %t); err = %v\n%s",+ label, gotBodyErr, gotOtherErr, want.bodyErr, want.otherErr, got.err, Explain(node))+ }+ // A freshly built tree, not the rewritten one: PolicyMiddleware runs the+ // pipeline itself, so handing it mode.plan's output would optimize twice and+ // quietly turn this into a test of idempotence. Rebuilding also means a pass+ // that rewrites in place cannot reach the verdict half above.+ if status := runPolicyStatus(t, tree.astNode(), mode.options...); status != want.status() {+ t.Errorf("%s: status = %d, want %d\n%s", label, status, want.status(), Explain(node))+ }+}++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++// hollowWrapper implements Unwrap() error with no cause, the shape+// *topdown.Error has.+type hollowWrapper struct{ message string }++func (err hollowWrapper) Error() string { return err.message }+func (hollowWrapper) Unwrap() error { return nil }++// hollowJoin is the same shape in the multi-error arm.+type hollowJoin struct{ message string }++func (err hollowJoin) Error() string { return err.message }+func (hollowJoin) Unwrap() []error { return nil }++// TestErrorKindsWalksWrappedAndJoinedErrors pins the classifier the whole+// comparison rests on, rather than leaving it to whichever shapes the generated+// trees happen to produce. See errorKinds' doc for why each shape below matters.+func TestErrorKindsWalksWrappedAndJoinedErrors(t *testing.T) {+ body := policyBodyError{message: "request body exceeds policy limit"}+ other := errors.New("database unavailable")++ cases := []struct {+ name string+ err error+ wantBody bool+ wantOtherErr bool+ }{+ {"nil", nil, false, false},+ {"bare body error", body, true, false},+ {"bare other error", other, false, true},+ {"join of both", errors.Join(body, other), true, true},+ {"nested joins", errors.Join(errors.Join(body), errors.Join(other)), true, true},+ {"wrapped body error", fmt.Errorf("leaf: %w", body), true, false},+ {"wrapped other error", fmt.Errorf("leaf: %w", other), false, true},+ {"wrapped join of both", fmt.Errorf("subtree: %w", errors.Join(body, other)), true, true},+ {"join containing a wrapped body error", errors.Join(fmt.Errorf("leaf: %w", body), other), true, true},+ {"doubly wrapped join", fmt.Errorf("plan: %w", fmt.Errorf("subtree: %w", errors.Join(body, other))), true, true},+ // Not hypothetical: this is the shape every Rego evaluation error+ // arrives in.+ {"wrapper with no cause", hollowWrapper{message: "eval_conflict_error"}, false, true},+ {"joiner with no children", hollowJoin{message: "empty join"}, false, true},+ {"join beside a wrapper with no cause", errors.Join(body, hollowWrapper{message: "eval_conflict_error"}), true, true},+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ gotBody, gotOther := errorKinds(testCase.err)+ if gotBody != testCase.wantBody || gotOther != testCase.wantOtherErr {+ t.Fatalf("errorKinds(%v) = (body %t, other %t), want (body %t, other %t)",+ testCase.err, gotBody, gotOther, testCase.wantBody, testCase.wantOtherErr)+ }+ })+ }+}++func TestReferenceEvaluatorMatchesHandDerivedVerdicts(t *testing.T) {+ leaf := func(scripted behavior) refTree { return refTree{kind: refLeaf, leaf: scripted} }+ allOf := func(kids ...refTree) refTree { return refTree{kind: refAll, kids: kids} }+ anyOf := func(kids ...refTree) refTree { return refTree{kind: refAny, kids: kids} }++ // The reference is the specification, so it gets pinned by hand rather than+ // by agreement with the code it is supposed to judge. Each case states the+ // fold that produces it.+ cases := []struct {+ name string+ tree refTree+ want refVerdict+ }{+ {+ // min(true, false) = false.+ name: "all of allow and deny denies",+ tree: allOf(leaf(behaviorAllow), leaf(behaviorDeny)),+ want: refVerdict{truth: refFalse},+ },+ {+ // max(error{other}, error{body}) = error carrying both.+ name: "any of two error kinds keeps both",+ tree: anyOf(leaf(behaviorFactError), leaf(behaviorBodyOverLimit)),+ want: refVerdict{truth: refError, bodyErr: true, otherErr: true},+ },+ {+ // inner max(false, error{other}) = error{other};+ // outer min(true, error{other}) = error{other}.+ name: "all of body allow and any of deny and fact error is undecided",+ tree: allOf(leaf(behaviorBodyOK), anyOf(leaf(behaviorDeny), leaf(behaviorFactError))),+ want: refVerdict{truth: refError, otherErr: true},+ },+ {+ // left min(error{other}, false) = false;+ // right min(error{body}, true) = error{body};+ // outer max(false, error{body}) = error{body}.+ name: "any of a denying branch and a body-erroring branch keeps the body error",+ tree: anyOf(+ allOf(leaf(behaviorFactError), leaf(behaviorDeny)),+ allOf(leaf(behaviorBodyOverLimit), leaf(behaviorAllow)),+ ),+ want: refVerdict{truth: refError, bodyErr: true},+ },+ {+ // inner max(error{body}, true) = true, which discards the body+ // error; outer min(true, false) = false. The discard is the point:+ // without it this would be 400 rather than 403.+ name: "an annihilated body error does not reach the outer fold",+ tree: allOf(anyOf(leaf(behaviorBodyOverLimit), leaf(behaviorAllow)), leaf(behaviorDeny)),+ want: refVerdict{truth: refFalse},+ },+ {+ // max(error{other}, false) = error{other}: no disjunct allowed, so+ // the Rego conflict survives as a 500.+ name: "any of rego error and deny stays undecided",+ tree: anyOf(leaf(behaviorRegoError), leaf(behaviorDeny)),+ want: refVerdict{truth: refError, otherErr: true},+ },+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ if got := testCase.tree.verdict(); got != testCase.want {+ t.Fatalf("reference verdict = %+v, want %+v", got, testCase.want)+ }+ // Having pinned the reference by hand, hold the real evaluator to+ // it too, so these stay readable worked examples of the whole+ // comparison and not just of the oracle.+ assertMatchesReference(t, unoptimizedMode, testCase.name, testCase.tree)+ })+ }+}++func TestEquivalenceGeneratorProducesDistinctTrees(t *testing.T) {+ // A differential test over a degenerate generator is the worst kind of+ // green: hundreds of passing seeds proving one tree. This is the floor that+ // keeps the seed range meaningful. The count observed is 278 of 300, so+ // ordinary churn in the generator will not trip this but a collapse to a+ // handful of shapes will.+ const wantAtLeast = 240++ signatures := map[string]bool{}+ depths := map[int]bool{}+ kinds := map[refKind]bool{}+ leaves := map[behavior]bool{}+ statuses := map[int]int{}+ for seed := int64(1); seed <= equivalenceSeeds; seed++ {+ tree := genTree(rand.New(rand.NewSource(seed)), equivalenceDepth)+ signatures[tree.signature()] = true+ depths[treeDepth(tree)] = true+ statuses[tree.verdict().status()]+++ collectVariety(tree, kinds, leaves)+ }++ t.Logf("%d distinct trees over %d seeds; depths %v; %d of %d leaf behaviors; statuses %v",+ len(signatures), equivalenceSeeds, depths, len(leaves), behaviorCount, statuses)+ if len(signatures) < wantAtLeast {+ t.Errorf("distinct trees = %d over %d seeds, want at least %d", len(signatures), equivalenceSeeds, wantAtLeast)+ }+ // Distinctness alone does not prove coverage: a generator could emit+ // hundreds of distinct all-allow conjunctions. Every leaf behavior, both+ // composite kinds and every depth up to the limit must actually appear.+ if len(leaves) != int(behaviorCount) {+ t.Errorf("leaf behaviors generated = %d, want %d", len(leaves), behaviorCount)+ }+ if !kinds[refAll] || !kinds[refAny] {+ t.Errorf("composite kinds generated = %v, want both All and Any", kinds)+ }+ for depth := 1; depth <= equivalenceDepth; depth++ {+ if !depths[depth] {+ t.Errorf("no tree of depth %d generated; depths = %v", depth, depths)+ }+ }+ // Structural variety is still not outcome variety, and outcomes are what+ // the differential test compares. If every seed expected 403, a mutation+ // that only ever turns a 500 into a 400 would sail through. Each of the four+ // statuses the middleware can produce needs a real share of the range.+ for _, status := range []int{+ http.StatusNoContent,+ http.StatusForbidden,+ http.StatusBadRequest,+ http.StatusInternalServerError,+ } {+ if statuses[status]*20 < equivalenceSeeds {+ t.Errorf("status %d expected by %d of %d seeds, want at least 5%%", status, statuses[status], equivalenceSeeds)+ }+ }+}++func TestReferenceMatchesEveryLeafBehavior(t *testing.T) {+ // The scripted behaviors are the alphabet the generator draws from, so a+ // leaf that quietly stopped doing what its name says would corrupt every+ // tree above it while the differential test stayed green — the reference+ // table and the Rego would be wrong in the same direction. This is the one+ // place each behavior is checked on its own.+ //+ // Every behavior in every source variant, because a variant is a different+ // module: the shared one scripts all six behaviors side by side and picks+ // between them by rule name, so a rule that named the wrong thing there+ // would make the fuzz target fail against leaves nobody implemented rather+ // than against a bug in the optimizer.+ for variant := sourceVariant(0); variant < sourceVariantCount; variant++ {+ for scripted := behavior(0); scripted < behaviorCount; scripted++ {+ assertMatchesReference(t, unoptimizedMode, fmt.Sprintf("behavior %d from source %d", scripted, variant),+ refTree{kind: refLeaf, leaf: scripted, source: variant})+ }+ }+}++func TestEvaluatorMatchesReferenceSemantics(t *testing.T) {+ for seed := int64(1); seed <= equivalenceSeeds; seed++ {+ tree := genTree(rand.New(rand.NewSource(seed)), equivalenceDepth)+ // Errorf inside assertMatchesReference, so a systematic disagreement+ // reports every seed it affects rather than only the lowest one.+ assertMatchesReference(t, unoptimizedMode, fmt.Sprintf("seed %d", seed), tree)+ }+}++// TestOptimizerPreservesSemantics is the point of everything above: the same+// comparison with the optimizer left on. It was written before any pass+// existed and parked as a comment until Optimize landed, because an oracle+// added alongside the thing it judges is an oracle fitted to it.+//+// It cannot tell a working optimizer from one that returns its input — a no-op+// preserves semantics perfectly. TestDefaultPipelineRewritesGeneratedTrees in+// policy_optimize_test.go is the other half of that pair.+func TestOptimizerPreservesSemantics(t *testing.T) {+ for seed := int64(1); seed <= equivalenceSeeds; seed++ {+ tree := genTree(rand.New(rand.NewSource(seed)), equivalenceDepth)+ assertMatchesReference(t, optimizedMode, fmt.Sprintf("seed %d", seed), tree)+ }+}diff --git a/libs/fleet/backend/auth/policy_fuzz_test.go b/libs/fleet/backend/auth/policy_fuzz_test.gonew file mode 100644index 0000000000..d3d3baef63--- /dev/null+++ b/libs/fleet/backend/auth/policy_fuzz_test.go@@ -0,0 +1,400 @@+package auth++import (+ "fmt"+ "math/rand"+ "slices"+ "testing"+)++// The optimizer's differential harness, driven by the fuzzer instead of by a+// fixed seed range. It reuses the reference oracle and the comparison in+// policy_equivalence_test.go wholesale; the only thing this file adds is a+// second way to reach a generated tree.+//+// Not run in CI as a fuzzing campaign — `go test` runs a fuzz target over its+// seed corpus and stops, which is what keeps the committed crashers in+// testdata/fuzz working as ordinary regression tests. Soaking it is a local+// step when changing a pass:+//+// go test ./auth/ -run FuzzOptimizerEquivalence -fuzz FuzzOptimizerEquivalence -fuzztime 60s+//+// testdata/fuzz holds the two crashers that soak has produced so far, each+// found under a mutated key and each replaying as a two-leaf tree over the+// shared module:+//+// 01011001 Any(deny, allow), found in 7.5s against a dedupe keyed on the+// source alone: the merge keeps the deny and+// answers 403 where the policy says 204.+// 11021011 All(factError, deny), found in 4.6s against a Leaf.key() with the+// facts component dropped: the merge keeps the+// error and answers 500 where it says 403.+//+// Eight bytes each, and between them the smallest statement of what this file+// is for.+//+// What it can and cannot show is worth stating, because the seed range next+// door has the same limit: like every test that compares an optimized plan with+// an unoptimized reference, this cannot tell a working optimizer from one that+// returns its input. A pass that does nothing preserves semantics perfectly.+// TestDefaultPipelineRewritesGeneratedTrees is the other half of that pair.++// tape turns the fuzzer's byte string into the generator's decisions, one byte+// per decision.+//+// That is why the target takes a byte string rather than the int64 seed the+// plan sketched. A seed has no structure to mutate: flipping one of its bits+// redraws the entire tree, so coverage-guided mutation has no gradient to+// follow and the fuzzer is reduced to sampling the same generator the fixed+// seed range already samples exhaustively. Against a tape, flipping a byte+// moves one decision and leaves the rest of the tree standing.+type tape struct {+ bytes []byte+ at int+}++// intn consumes one byte. A tape that has run out answers 0 forever, which is+// what makes every tape finite: genSubtree reads 0 as "stop here and emit a+// leaf", so running off the end closes the tree off instead of looping. The+// modulo is biased towards low values for an n that does not divide 256; the+// bias costs nothing here, because the fuzzer is free to reach any value of any+// draw by mutating its byte.+func (source *tape) intn(n int) int {+ if source.at >= len(source.bytes) {+ return 0+ }+ value := int(source.bytes[source.at]) % n+ source.at+++ return value+}++// recordingDraws writes down every decision another source makes, so that a+// tape can be produced from math/rand rather than assembled by hand. Recording+// the *result* rather than the raw byte is what makes the replay exact: every n+// the generator asks for is far below 256, so value % n is value again.+type recordingDraws struct {+ inner drawSource+ tape []byte+}++func (source *recordingDraws) intn(n int) int {+ value := source.inner.intn(n)+ source.tape = append(source.tape, byte(value))+ return value+}++// fuzzGenConfig is the widened generator. Every source variant, so leaves that+// share a module while differing in query, facts or body limit are reachable —+// see sourceVariant for the measured hole that shape closes. The depth is the+// seed range's, so a tape can express anything a seed can.+var fuzzGenConfig = genConfig{depth: equivalenceDepth, sourceVariants: int(sourceVariantCount)}++// fuzzSeedTapes is how many math/rand-drawn tapes seed the corpus. Small on+// purpose: every entry is replayed in full by an ordinary `go test` run, and one+// entry costs a tree build, an Optimize — which renders the whole tree once per+// sweep — and two Rego compilations of every surviving leaf.+const fuzzSeedTapes = 20++// fuzzSearchSeeds bounds the search below. The two shapes it looks for are rare+// among random draws — the narrower one needs two particular behaviors landing+// under one parent, both drawn from the shared module — so the bound is far+// above where they are actually found, and a search that runs out is a+// generator that lost the shape rather than a search that was unlucky.+const fuzzSearchSeeds = 1000++// recordTape draws a tree from a fixed seed and returns it beside the tape that+// reproduces it.+func recordTape(seed int64) (refTree, []byte) {+ source := &recordingDraws{inner: randDraws{rng: rand.New(rand.NewSource(seed))}}+ tree := genTreeFrom(source, fuzzGenConfig)+ return tree, source.tape+}++// searchTape looks for the lowest seed whose tree puts a pair of leaves+// matching wanted under one parent, and returns the tape for it.+//+// Searched rather than written out as bytes. A hand-written tape is a magic+// number that says nothing about why those bytes were chosen and quietly stops+// meaning it the moment the generator draws in a different order; a search says+// what the entry is for and fails loudly when the shape becomes unreachable.+func searchTape(wanted func(one, other Leaf) bool) (script []byte, seed int64, found bool) {+ for candidate := int64(1); candidate <= fuzzSearchSeeds; candidate++ {+ tree, recorded := recordTape(candidate)+ for _, pair := range siblingLeafPairs(tree.astNode()) {+ if wanted(pair[0], pair[1]) {+ return recorded, candidate, true+ }+ }+ }+ return nil, 0, false+}++// fuzzWantedShapes is one entry per way two sibling leaves can differ, and the+// corpus carries a tape for each. Enumerated rather than sampled: a differential+// harness is blind to an unsound merge it never generates the operands for, so+// "which differences can the generator produce" is the question that decides+// what this target can catch, and it deserves a list rather than a hope.+var fuzzWantedShapes = []struct {+ name string+ match func(one, other Leaf) bool+}{+ {"two leaves sharing a source and differing", sharesSourceAndDiffers},+ {"two leaves differing in nothing but their query", differsOnlyInQuery},+ {"two leaves differing in nothing but their facts", differsOnlyInFacts},+ {"two leaves differing in nothing but their body limit", differsOnlyInBodyLimit},+}++// fuzzSeedCorpus is the corpus the fuzz target starts from, built once so that+// the target and the test that measures it cannot be looking at different sets+// of tapes.+//+// It fails rather than returning a smaller corpus, because the searched entries+// are the entire reason this file is not a re-run of the fixed seed range.+// Silently seeding without them would leave a target that passes, soaks, and+// proves what the 300 seeds already proved.+func fuzzSeedCorpus(fail func(format string, args ...any)) [][]byte {+ corpus := [][]byte{+ // The empty tape, which no recording produces: every draw runs off its+ // end. It is the smallest input the fuzzer has to grow from, and it pins+ // that an exhausted tape still yields a tree the harness can run rather+ // than a panic or an empty composite Compile refuses.+ {},+ }+ for seed := int64(1); seed <= fuzzSeedTapes; seed++ {+ _, script := recordTape(seed)+ corpus = append(corpus, script)+ }+ for _, wanted := range fuzzWantedShapes {+ script, _, found := searchTape(wanted.match)+ if !found {+ fail("no tape in %d seeds puts %s under one parent; the generator has lost the shape this target exists to reach",+ fuzzSearchSeeds, wanted.name)+ continue+ }+ corpus = append(corpus, script)+ }+ return corpus+}++func FuzzOptimizerEquivalence(f *testing.F) {+ for _, script := range fuzzSeedCorpus(f.Fatalf) {+ f.Add(script)+ }++ f.Fuzz(func(t *testing.T, script []byte) {+ tree := genTreeFrom(&tape{bytes: script}, fuzzGenConfig)+ // The tree's signature, not the tape: it is what a failure has to be+ // read against, and two tapes differing only past the point the+ // generator stopped reading describe the same tree.+ assertMatchesReference(t, optimizedMode, tree.signature(), tree)+ })+}++func TestFuzzSeedTapesReplayTheirTrees(t *testing.T) {+ // The seed corpus is only as good as this: a tape has to make the same+ // decisions on replay that math/rand made when it was recorded. If it did+ // not, the corpus would be a set of trees nobody chose, and the claim that+ // fuzzing starts where the fixed seed range starts would be empty.+ for seed := int64(1); seed <= fuzzSeedTapes; seed++ {+ recorded, script := recordTape(seed)+ replayed := genTreeFrom(&tape{bytes: script}, fuzzGenConfig)+ if replayed.signature() != recorded.signature() {+ t.Errorf("seed %d: tape %x replays as %s, want %s", seed, script, replayed.signature(), recorded.signature())+ }+ }+}++// siblingLeafPairs returns every pair of leaves the tree puts under one parent.+// Siblings are the unit that matters: dedupe compares a node's children with+// each other and nothing else, so two leaves that never meet under one parent+// are two leaves it will never be asked to merge.+func siblingLeafPairs(n Node) [][2]Leaf {+ var children []Node+ switch node := n.(type) {+ case AllNode:+ children = node.Children+ case AnyNode:+ children = node.Children+ default:+ return nil+ }++ pairs := [][2]Leaf{}+ leaves := []Leaf{}+ for _, child := range children {+ leaf, ok := child.(Leaf)+ if !ok {+ pairs = append(pairs, siblingLeafPairs(child)...)+ continue+ }+ for _, earlier := range leaves {+ pairs = append(pairs, [2]Leaf{earlier, leaf})+ }+ leaves = append(leaves, leaf)+ }+ return pairs+}++// A leaf can differ from another on four axes, one per component of+// Leaf.key(): source, query, facts, body limit. The predicates below name the+// coarse shape and then a pair differing in exactly one axis, which is what a+// dedupe keyed on any proper subset of the key would merge.+//+// Three of the four are pinned, each measured by dropping that one component+// from key() and watching this target go red while all 300 fixed seeds stayed+// green:+//+// query: seed#6 fails (behaviorAllow vs behaviorRegoError)+// facts: crasher 35f2b0c92e371f36 fails (behaviorDeny vs behaviorFactError)+// body: seed#24 fails (behaviorAllow vs behaviorBodyOverLimit)+//+// The source component is deliberately not pinned that way, and the reason is+// worth having written down rather than rediscovered. Dropping it alone from+// key() survives a 90s soak — 40823 execs, green — because no generated pair+// can differ in source alone: every leaf's query names its own package, so a+// source difference always drags a query difference along with it.+//+// Reaching it would take two modules sharing a package name, differing in text,+// and *disagreeing about the rule being queried* — anything less and the merge+// is invisible to the oracle, which compares verdicts. That last requirement is+// the disqualifying one: the reference would then have to know which module a+// leaf came from, and "the oracle is a function of behavior alone" is the+// property this whole harness rests on. Trading it for one more axis is a bad+// bargain.+//+// What covers the source axis instead is the direction that actually threatens+// an authorization plan. Dedupe's failure mode is over-merging, and the coarse+// mutation for that — keying on the source *alone* — is caught here in 0.12s.+// Under-discriminating on source is left to the hand-written cases in+// TestDedupeKeepsLeavesThatAreNotProvablyIdentical ("different sources", "same+// source name, different text") and TestDedupeNeverMergesLeavesWithoutStableIdentity,+// which is the right home for it: those are claims about identity, not about+// what a tree decides.+//+// They compare the leaf's fields directly rather than asking key() whether two+// leaves collide, and that is load-bearing rather than laborious. A predicate+// written in terms of key() cannot judge key(): with the facts component+// dropped from it — the mutation that put this axis here — the facts-only pair+// stops being visible to its own search, and the target then fails by claiming+// the generator lost a shape instead of by catching the unsound merge. The cost+// is a second encoding of what a fact list means, and it is the same trade+// refTruth makes against truth in policy_equivalence_test.go: an oracle that+// imports its subject's definition of the answer can only ever confirm it.+//+// The exposure that buys is drift in the other direction. If Leaf gains a fifth+// component, key() will compare it and these will not, so "differs only in X"+// becomes "differs in X and possibly the new field". The new axis would then be+// unpinned rather than wrongly pinned, and TestLeafKeyIsInjective is where a+// fifth component gets noticed.++// sharesSource reports whether two leaves come from the same module. An empty+// source key means "no stable identity", which is never equal to anything,+// including another empty one. No generated leaf has one — they are all Inline+// — but treating two of them as a match would be the opposite of what this asks.+func sharesSource(one, other Leaf) bool {+ key := one.Source.sourceKey()+ return key != "" && key == other.Source.sourceKey()+}++// sameFacts reports whether two leaves declare the same fact loads: the same+// namespaces bound to the same cache keys, in any order, because forPolicy+// builds a map from them and order is not meaning.+func sameFacts(one, other Leaf) bool {+ return slices.Equal(factIdentities(one), factIdentities(other))+}++func factIdentities(leaf Leaf) []string {+ identities := make([]string, 0, len(leaf.Facts))+ for _, configured := range leaf.Facts {+ identities = append(identities, fmt.Sprintf("%q=%q", configured.namespace, configured.provider.CacheKey()))+ }+ slices.Sort(identities)+ return identities+}++// sharesSourceAndDiffers is the coarsest shape the fixed seed range cannot+// reach: two leaves that agree on their module and disagree about what to ask+// it. It is exactly what a dedupe keyed on Leaf.Source.sourceKey() alone would+// merge, and merging it deletes an authorization check.+func sharesSourceAndDiffers(one, other Leaf) bool {+ return sharesSource(one, other) &&+ (one.Query != other.Query || !sameFacts(one, other) || one.MaxBody != other.MaxBody)+}++func differsOnlyInQuery(one, other Leaf) bool {+ return sharesSource(one, other) &&+ one.Query != other.Query && sameFacts(one, other) && one.MaxBody == other.MaxBody+}++// differsOnlyInFacts is the axis that went missing when this file was first+// written, and the reason the axes are now enumerated rather than hoped for:+// behaviorFactError was the only scripted leaf carrying a provider and also the+// only one naming its rule, so a facts difference could not arise without a+// query difference beside it. Measured, a Leaf.key() with the facts component+// dropped passed this target and all 300 fixed seeds; only hand-written unit+// tests caught it. behaviorDeny now names the same rule with nothing to load,+// which closes it.+func differsOnlyInFacts(one, other Leaf) bool {+ return sharesSource(one, other) &&+ one.Query == other.Query && !sameFacts(one, other) && one.MaxBody == other.MaxBody+}++// differsOnlyInBodyLimit reaches one leaf that allows beside one that must+// answer 400, identical in every other respect. A dedupe that compared+// everything but MaxBody would answer 204 for both.+func differsOnlyInBodyLimit(one, other Leaf) bool {+ return sharesSource(one, other) &&+ one.Query == other.Query && sameFacts(one, other) && one.MaxBody != other.MaxBody+}++func TestFuzzSeedCorpusReachesWhatTheFixedSeedRangeCannot(t *testing.T) {+ // The reason this file is not a second run of the 300 seeds. Measured, not+ // assumed: mutating dedupeChildren to key on the source alone — a merge that+ // is genuinely unsound — leaves every one of those 300 seeds green, because+ // there a source implies the query, the facts and the body limit. Both+ // shapes below break that implication, and the corpus has to contain them+ // before the target is worth soaking.+ //+ // Counted over the corpus the target actually seeds itself with, so an entry+ // that stopped carrying its shape — or a tape that replayed as some other+ // tree — is caught here rather than assumed away.+ //+ // What this does *not* establish is that the seed corpus catches an unsound+ // merge of each shape, and the distinction is not academic: a pair has to sit+ // somewhere the merge changes the fold before any verdict moves. All(deny,+ // factError) folds to false either way, because false annihilates a+ // conjunction whether or not the error beside it survived — so the facts-only+ // pair was in the corpus, was merged by a key with the facts dropped, and+ // changed nothing. Only Any(deny, factError), or the same pair the other way+ // round under All, is observable. Placing a pair is the fuzzer's job; having+ // the operands at all is this test's.+ corpus := fuzzSeedCorpus(t.Fatalf)+ found := make([]int, len(fuzzWantedShapes))+ for _, script := range corpus {+ tree := genTreeFrom(&tape{bytes: script}, fuzzGenConfig)+ for _, pair := range siblingLeafPairs(tree.astNode()) {+ for index, wanted := range fuzzWantedShapes {+ if wanted.match(pair[0], pair[1]) {+ found[index]+++ }+ }+ }+ }++ for index, wanted := range fuzzWantedShapes {+ t.Logf("%d sibling leaf pairs are %s, over %d seed tapes", found[index], wanted.name, len(corpus))+ if found[index] == 0 {+ t.Errorf("no seed tape puts %s under a single parent", wanted.name)+ }+ }+}++func TestFuzzSearchTapeReportsWhenNothingMatches(t *testing.T) {+ // searchTape is what puts the two sharp entries in the corpus, and a version+ // that reported success for a predicate nothing satisfies would seed an+ // arbitrary tape while fuzzSeedCorpus's failure path went untested. Nothing+ // else in this file ever asks it a question with no answer.+ if script, seed, found := searchTape(func(Leaf, Leaf) bool { return false }); found {+ t.Fatalf("searchTape found seed %d (tape %x) for a predicate that matches nothing", seed, script)+ }+}diff --git a/libs/fleet/backend/auth/policy_golden_test.go b/libs/fleet/backend/auth/policy_golden_test.gonew file mode 100644index 0000000000..fc41946f2a--- /dev/null+++ b/libs/fleet/backend/auth/policy_golden_test.go@@ -0,0 +1,218 @@+package auth++import (+ "flag"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++// This file pins the optimized shape of the policy trees that real routes are+// built from. The optimizer is free to reorder authorization checks — that is+// its whole purpose, and the lattice in policy_plan.go is why it is allowed to+// — but "free to reorder" must not mean "reorders without anyone noticing".+//+// The plans below are read out of the surface table in policy_routes.go, which+// is the same table main.go's route builders resolve through. There is no copy+// to drift: reorder a tree's children and this file diffs, because the snapshot+// holds the production value rather than a likeness. What it pins is the+// optimizer's output for those trees, so a changed pass or cost model diffs too.+//+// The pinning stops at PolicyMiddleware's door, though: which surface a route+// is bound to, and with which options, is not covered here. A route moved to a+// different surface, or a surface that starts passing WithPipeline, changes what+// that route runs without any plan here changing — TestPolicyAndRouterAgreeOnRoutes+// and the characterization table are what watch that axis.+//+// What is not pinned at all, so nobody mistakes this for more than it is:+//+// - Policy meaning. A source renders as its key, and Registered("authz")+// is the literal string "registered:authz". Rewrite authz.rego to allow+// everything and every test in this file still passes. Rego semantics are+// policy_test.go's job.+// - Everything below the AST. Compile and fold are unrendered, so a change+// to the body budget or to how the fold treats errors leaves the snapshot+// byte-identical.+// - Everything above it. Whether PolicyMiddleware still routes through+// DefaultPipeline() at all is invisible here, because these tests call+// Optimize directly with DefaultPipeline themselves.+// - Which file an fs-backed leaf reads. Explain renders those as their Go+// type and drops the path, so two FromFS leaves on different paths share+// one rendering.+// - Fact-provider behaviour behind an equal CacheKey.+//+// Note also that the optimizer is still a no-op on every plan here, measured+// across all ten — so this file gives no coverage of the optimizer+// whatsoever. Run it with an empty pipeline and it still passes.+//+// That survived the arrival of the first fact loader, which is worth stating+// rather than assuming. svc, orch and namespaces now carry a leaf that calls a+// FactProvider — precisely what sinkFactLoaders exists to move — and it moves+// nothing, because NamespaceOwnershipPolicy already declares its cheap children+// first and the sort is stable. The pass is load-bearing in the sense that+// matters (it is what keeps that order true if the declaration changes) and+// invisible in the sense this file measures. What the order buys is counted as+// probes in policy_ownership_test.go, not read off a shape here. Until a pinned+// plan exists that the optimizer actually rewrites, this is production-order+// documentation with a regeneration workflow, and the optimizer's own coverage+// lives in policy_equivalence_test.go and policy_fuzz_test.go.+//+// The snapshots are one file per plan, named by the surface. One combined file+// would also work, but a failure then prints every plan when one changed;+// per-plan files keep the failure message down to the plan that actually moved+// and keep each file's git history about one surface. Adding a surface needs no+// entry here at all — only one -update-golden run to write its snapshot.+//+// Explain does not sort a leaf's Facts, though key() does. Fact order carries+// no meaning — forPolicy builds a map — so a pass that permutes Facts produces+// a golden diff with no semantic change behind it.++var updateGolden = flag.Bool("update-golden", false, "rewrite golden plan files")++// goldenPlans is every policy tree whose optimized shape is pinned: one per+// authorization surface. Each entry owns testdata/<name>-plan.txt.+//+// The list is derived from the surface table in policy_routes.go rather than+// written out here, so a surface added there is pinned from the moment it exists+// — the failure is a missing snapshot file, which -update-golden fixes, rather+// than a plan nobody pinned. The trees are rebuilt per call rather than stored,+// so that a pass which mutated its input could not leak that mutation from one+// test into the next.+func goldenPlans(t *testing.T) []struct {+ name string+ tree func() Node+} {+ t.Helper()+ names := SurfaceNames()+ plans := make([]struct {+ name string+ tree func() Node+ }, 0, len(names))+ for _, name := range names {+ if _, ok := SurfaceTree(name); !ok {+ t.Fatalf("SurfaceNames returned %q, which SurfaceTree does not resolve", name)+ }+ plans = append(plans, struct {+ name string+ tree func() Node+ }{+ name: name + "-route",+ tree: func() Node {+ tree, _ := SurfaceTree(name)+ return tree+ },+ })+ }+ return plans+}++func goldenPlanPath(name string) string {+ return filepath.Join("testdata", name+"-plan.txt")+}++// TestGoldenPlansAreStable is the tripwire: it fails when the optimized plan+// for a real route stops looking exactly like the checked-in snapshot, whether+// because the tree here drifted from main.go, because a pass changed, or+// because the cost model started ordering leaves differently.+func TestGoldenPlansAreStable(t *testing.T) {+ for _, plan := range goldenPlans(t) {+ t.Run(plan.name, func(t *testing.T) {+ got := Explain(Optimize(plan.tree(), DefaultPipeline()))+ path := goldenPlanPath(plan.name)++ if *updateGolden {+ if err := os.MkdirAll("testdata", 0o755); err != nil {+ t.Fatalf("mkdir testdata: %v", err)+ }+ if err := os.WriteFile(path, []byte(got), 0o644); err != nil {+ t.Fatalf("write %s: %v", path, err)+ }+ return+ }++ want, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s (regenerate with: go test ./auth/ -run TestGoldenPlansAreStable -update-golden): %v", path, err)+ }+ if got != string(want) {+ t.Fatalf(`the optimized %q plan changed.++--- want (%s) ---+%s--- got ---+%s+This is the order authorization checks run in on a production route. The+lattice guarantees the verdict is the same either way, so do not go hunting+for an allow that became a deny — what an order change moves is which leaves+run at all, and so which fact loads and body reads happen, and which errors+fold discards once a sibling has decided. Read the two trees above and satisfy+yourself the new order is what you meant, then regenerate the snapshot with:++ go test ./auth/ -run TestGoldenPlansAreStable -update-golden`,+ plan.name, path, want, got)+ }+ })+ }+}++// TestGoldenPlansCompile checks that the pinned trees are not just stable but+// buildable: Compile is what loads each source's modules and prepares the Rego,+// so a snapshot naming a module nobody registered would otherwise stay green.+//+// LoadOpa is what registers "authz" and "pool-admission". There is no init in+// this package that does it, so the test has to call it — and calling the real+// registrar rather than re-registering the modules here is the point: a+// production module renamed in LoadOpa fails this test instead of passing+// against a private copy.+func TestGoldenPlansCompile(t *testing.T) {+ LoadOpa()+ for _, plan := range goldenPlans(t) {+ t.Run(plan.name, func(t *testing.T) {+ if _, err := Compile(Optimize(plan.tree(), DefaultPipeline())); err != nil {+ t.Fatalf("compile %q plan: %v", plan.name, err)+ }+ })+ }+}++// TestGoldenPlanFilesHaveNoOrphans catches the other direction of drift: a plan+// renamed or deleted from the table leaves its old snapshot behind, and a stale+// snapshot is worse than none — it looks like a pinned plan that no test reads.+func TestGoldenPlanFilesHaveNoOrphans(t *testing.T) {+ plans := goldenPlans(t)+ expected := make(map[string]bool, len(plans))+ for _, plan := range plans {+ expected[goldenPlanPath(plan.name)] = true+ }+ // Scoped to *-plan.txt so unrelated fixtures may share testdata/.+ found, err := filepath.Glob(filepath.Join("testdata", "*-plan.txt"))+ if err != nil {+ t.Fatalf("glob testdata: %v", err)+ }+ for _, path := range found {+ if !expected[path] {+ t.Errorf("%s is not produced by any entry in goldenPlans; delete it or add the plan back", path)+ }+ }+}++// TestGoldenPlanNamesAreUniqueAndPathSafe guards the axis the orphan check+// cannot see. Two entries sharing a name both write one file, and under+// -update-golden the second silently overwrites the first — so the pinned plan+// is lost before the collision is noticed, and a confusing golden failure is+// exactly when someone reaches for -update-golden. A name carrying a path+// separator fails the write instead with a bare ENOENT, because the snapshot+// writer creates testdata/ but not subdirectories under it.+func TestGoldenPlanNamesAreUniqueAndPathSafe(t *testing.T) {+ plans := goldenPlans(t)+ seen := make(map[string]bool, len(plans))+ for _, plan := range plans {+ if plan.name == "" || strings.ContainsAny(plan.name, `/\`) {+ t.Errorf("plan name %q is empty or contains a path separator", plan.name)+ }+ if seen[plan.name] {+ t.Errorf("duplicate plan name %q; each entry owns one testdata file", plan.name)+ }+ seen[plan.name] = true+ }+}diff --git a/libs/fleet/backend/auth/policy_middleware.go b/libs/fleet/backend/auth/policy_middleware.gonew file mode 100644index 0000000000..59501fee9a--- /dev/null+++ b/libs/fleet/backend/auth/policy_middleware.go@@ -0,0 +1,464 @@+package auth++import (+ "bytes"+ "context"+ "crypto/sha256"+ "errors"+ "fmt"+ "io"+ "io/fs"+ "log/slog"+ "net/http"+ "slices"+ "strings"+ "sync"++ "cyclops-cs-backend/middlewares"+)++type Middleware func(http.Handler) http.Handler++// PolicySource describes where Rego text comes from. modules() performs the+// I/O; sourceKey() is a stable structural identity for telling whether two+// leaves are provably the same, which a future dedupe pass will need.+// sourceKey returns "" to mean "no stable identity", and any caller comparing+// keys must treat "" as never equal to anything.+type PolicySource interface {+ policySource()+ modules() ([]policyModule, error)+ sourceKey() string+}++type policyModule struct {+ name string+ source string+}++type inlinePolicySource struct {+ name string+ source string+}++func (inlinePolicySource) policySource() {}++func (source inlinePolicySource) modules() ([]policyModule, error) {+ if source.name == "" || source.source == "" {+ return nil, fmt.Errorf("inline policy requires a name and source")+ }+ return []policyModule{{name: source.name, source: source.source}}, nil+}++// sourceKey digests the policy text with SHA-256 rather than a fast+// non-cryptographic hash: a collision here would let a future dedupe pass+// merge two leaves that run different Rego, which in authorization code is a+// correctness bug. The cost is paid once, at startup.+func (source inlinePolicySource) sourceKey() string {+ digest := sha256.Sum256([]byte(source.source))+ return fmt.Sprintf("inline:%s:%x", source.name, digest)+}++func Inline(name, source string) PolicySource {+ return inlinePolicySource{name: name, source: source}+}++type fsPolicySource struct {+ filesystem fs.FS+ path string+}++func (fsPolicySource) policySource() {}++func (source fsPolicySource) modules() ([]policyModule, error) {+ contents, err := fs.ReadFile(source.filesystem, source.path)+ if err != nil {+ return nil, fmt.Errorf("read policy %q: %w", source.path, err)+ }+ return []policyModule{{name: source.path, source: string(contents)}}, nil+}++// sourceKey is empty because two different fs.FS values can share a path, so+// a path alone cannot prove two leaves are the same. A false merge would be a+// correctness bug.+func (fsPolicySource) sourceKey() string { return "" }++func FromFS(filesystem fs.FS, path string) PolicySource {+ return fsPolicySource{filesystem: filesystem, path: path}+}++var policyModuleRegistry = struct {+ sync.RWMutex+ modules map[string]policyModule+}{modules: map[string]policyModule{}}++func RegisterPolicyModule(name, filename, source string) {+ if name == "" || filename == "" || source == "" {+ panic("registered OPA policy requires a name, filename, and source")+ }+ policyModuleRegistry.Lock()+ defer policyModuleRegistry.Unlock()+ policyModuleRegistry.modules[name] = policyModule{name: filename, source: source}+}++type registeredPolicySource struct {+ name string+}++func (registeredPolicySource) policySource() {}++func (source registeredPolicySource) modules() ([]policyModule, error) {+ policyModuleRegistry.RLock()+ module, ok := policyModuleRegistry.modules[source.name]+ policyModuleRegistry.RUnlock()+ if !ok {+ return nil, fmt.Errorf("OPA policy module %q is not registered", source.name)+ }+ return []policyModule{module}, nil+}++func (source registeredPolicySource) sourceKey() string {+ return "registered:" + source.name+}++func Registered(name string) PolicySource {+ return registeredPolicySource{name: name}+}++type multiPolicySource struct {+ sources []PolicySource+}++func (multiPolicySource) policySource() {}++func (source multiPolicySource) modules() ([]policyModule, error) {+ var modules []policyModule+ for _, child := range source.sources {+ childModules, err := child.modules()+ if err != nil {+ return nil, err+ }+ modules = append(modules, childModules...)+ }+ return modules, nil+}++// sourceKey is order-sensitive, because module order is part of what gets+// compiled. Children are quoted before joining so the encoding stays+// injective: without quoting, children {"X,Y", "Z"} and {"X", "Y,Z"} would+// produce the same key.+func (source multiPolicySource) sourceKey() string {+ keys := make([]string, 0, len(source.sources))+ for _, child := range source.sources {+ key := child.sourceKey()+ if key == "" {+ return ""+ }+ keys = append(keys, fmt.Sprintf("%q", key))+ }+ return "multi[" + strings.Join(keys, ",") + "]"+}++func Modules(sources ...PolicySource) PolicySource {+ if len(sources) == 0 {+ panic("OPA Modules requires at least one source")+ }+ return multiPolicySource{sources: sources}+}++type PolicyOption func(*policyConfig)++type FactSet map[string]any++type FactProvider interface {+ CacheKey() string+ LoadFacts(context.Context, *http.Request) (FactSet, error)+}++type factProviderConfig struct {+ namespace string+ provider FactProvider+}++type policyConfig struct {+ query string+ factProviders []factProviderConfig+ maxBodyBytes int64+}++func Query(query string) PolicyOption {+ return func(config *policyConfig) {+ config.query = query+ }+}++func WithFacts(namespace string, provider FactProvider) PolicyOption {+ return func(config *policyConfig) {+ if namespace == "" || provider == nil || provider.CacheKey() == "" {+ panic("OPA fact provider requires a namespace and cache key")+ }+ config.factProviders = append(config.factProviders, factProviderConfig{+ namespace: namespace,+ provider: provider,+ })+ }+}++func WithRawBody(maxBytes int64) PolicyOption {+ return func(config *policyConfig) {+ if maxBytes <= 0 {+ panic("OPA raw body limit must be positive")+ }+ config.maxBodyBytes = maxBytes+ }+}++type cachedFacts struct {+ facts FactSet+ err error+}++type requestPolicyInput struct {+ request *http.Request+ base map[string]any+ // bodyBudget is the whole plan's largest raw-body limit, computed at+ // compile time. Every leaf reads against it rather than against its own+ // limit, so no leaf's limit leaks into what its siblings can see.+ bodyBudget int64+ factCache map[string]cachedFacts+ bodyRead bool+ body []byte+ bodyErr error+}++func newRequestPolicyInput(request *http.Request, bodyBudget int64) *requestPolicyInput {+ user, _ := request.Context().Value(UserKey).(*User)+ route, _ := request.Context().Value(routeKey).(string)+ params, _ := request.Context().Value(paramsKey).(map[string]string)+ return &requestPolicyInput{+ request: request,+ bodyBudget: bodyBudget,+ factCache: map[string]cachedFacts{},+ base: map[string]any{+ "method": request.Method,+ "path": request.URL.Path,+ "route": route,+ "params": params,+ "user": buildUserInput(user),+ "flags": flagsData(),+ },+ }+}++func (input *requestPolicyInput) forPolicy(ctx context.Context, config policyConfig) (map[string]any, error) {+ document := make(map[string]any, len(input.base)+2)+ for key, value := range input.base {+ document[key] = value+ }++ facts := map[string]any{}+ for _, configured := range config.factProviders {+ value, err := input.resolveFacts(ctx, configured.provider)+ if err != nil {+ return nil, err+ }+ facts[configured.namespace] = value+ }+ document["facts"] = facts++ if config.maxBodyBytes > 0 {+ body, err := input.loadBody(config.maxBodyBytes)+ if err != nil {+ return nil, err+ }+ document["body"] = string(body)+ }+ return document, nil+}++func (input *requestPolicyInput) resolveFacts(ctx context.Context, provider FactProvider) (FactSet, error) {+ cacheKey := provider.CacheKey()+ if cached, ok := input.factCache[cacheKey]; ok {+ return cached.facts, cached.err+ }+ facts, err := provider.LoadFacts(ctx, input.request)+ input.factCache[cacheKey] = cachedFacts{facts: facts, err: err}+ return facts, err+}++type policyBodyError struct {+ message string+}++func (err policyBodyError) Error() string {+ return err.message+}++// FactUnavailableError is how a FactProvider says "the system I ask was+// unreachable", as opposed to "it answered no" — which is a FactSet, not an+// error — or "this process is misassembled", which is a plain error.+//+// The distinction is the response. Both are undecidable and both fail closed,+// but an unreachable dependency is a 502 the caller should retry, and anything+// else is a 500 somebody should look at. Before the namespace-ownership check+// moved into the policy, the Go handler answered its probe failures with+// exactly that 502; routing it through the lattice would otherwise have turned+// every apiserver hiccup into a 500 and pointed the alert at the wrong system.+//+// It is exported because providers live outside this package — the one that+// exists is a handlers method — and errors.As is how PolicyMiddleware+// recognises it, through whatever the fold's errors.Join wrapped it in.+type FactUnavailableError struct {+ // Namespace is the input.facts key the provider was loading, so the log+ // names which fact could not be answered rather than only which route.+ Namespace string+ Err error+}++func (err *FactUnavailableError) Error() string {+ return fmt.Sprintf("fact %q unavailable: %v", err.Namespace, err.Err)+}++func (err *FactUnavailableError) Unwrap() error { return err.Err }++// splicedBody reads a prefix already consumed from a request body and then the+// rest of that body, while Close still targets the original.+type splicedBody struct {+ io.Reader+ io.Closer+}++// spliceBody rebuilds the body the downstream handler will read: the bytes+// already consumed, followed by whatever is left of the original.+//+// It is unconditional on purpose. Whenever the prefix is the whole body the+// original is drained and the splice reads exactly like a reader over the+// prefix, so there is nothing to gain from a special case — while every+// condition that could guard it is a way for the handler to receive a stream+// with its first bytes missing. That includes the read-error path: replaying+// the prefix and letting the original re-surface its error is more faithful+// than discarding bytes that were read successfully.+//+// Close passes through rather than being swallowed by a NopCloser because this+// wrapper does not own the original's lifetime and the original may still hold+// unread bytes. Under net/http nothing leaks either way — the server closes the+// reqBody it captured, whatever a handler or middleware substitutes — but a+// wrapper that silently drops Close is wrong for any caller that is not the+// server.+func spliceBody(prefix []byte, original io.ReadCloser) io.ReadCloser {+ return splicedBody{+ Reader: io.MultiReader(bytes.NewReader(prefix), original),+ Closer: original,+ }+}++// loadBody reads the request body at most once, always up to the plan-wide+// budget, and never mutates shared state based on the calling leaf's limit.+// Reading stays lazy: a short-circuited branch never triggers it.+func (input *requestPolicyInput) loadBody(maxBytes int64) ([]byte, error) {+ if !input.bodyRead {+ input.bodyRead = true+ if input.request.Body != nil {+ original := input.request.Body+ input.body, input.bodyErr = io.ReadAll(io.LimitReader(original, input.bodyBudget+1))+ input.request.Body = spliceBody(input.body, original)+ }+ }+ if input.bodyErr != nil {+ return input.body, input.bodyErr+ }+ if int64(len(input.body)) > maxBytes {+ return input.body, policyBodyError{message: "request body exceeds policy limit"}+ }+ return input.body, nil+}++type MiddlewareOption func(*middlewareConfig)++type middlewareConfig struct {+ deniedMessage string+ // pipeline names the optimizer passes to run before compiling. pipelineSet+ // distinguishes "run the default pipeline" from "run nothing": the two are+ // both an empty slice, and only the flag tells them apart.+ pipeline []string+ pipelineSet bool+}++func WithDeniedMessage(message string) MiddlewareOption {+ return func(config *middlewareConfig) {+ config.deniedMessage = message+ }+}++// WithPipeline overrides the optimizer passes for this middleware.+// WithPipeline() with no arguments disables optimization entirely.+//+// Names are checked against the optimizer registry when the pipeline runs, so+// a typo panics during route construction rather than silently skipping a pass.+func WithPipeline(names ...string) MiddlewareOption {+ return func(config *middlewareConfig) {+ // Copied, not aliased. Spreading an existing slice into a variadic+ // parameter shares its backing array, so storing names directly would+ // leave the config holding a live view of the caller's slice.+ config.pipeline = slices.Clone(names)+ config.pipelineSet = true+ }+}++// PolicyMiddleware optimizes the policy AST, compiles it into an executable+// plan, and enforces that plan on every request. Compilation failures panic so+// a bad policy aborts the process during route construction, before it serves+// traffic; so does a pipeline naming a pass that does not exist.+func PolicyMiddleware(expression Node, options ...MiddlewareOption) Middleware {+ config := middlewareConfig{deniedMessage: "forbidden"}+ for _, option := range options {+ option(&config)+ }+ pipeline := DefaultPipeline()+ if config.pipelineSet {+ pipeline = config.pipeline+ }+ compiled, err := Compile(Optimize(expression, pipeline))+ if err != nil {+ panic(fmt.Sprintf("compile policy: %v", err))+ }+ return func(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {+ verdict := compiled.eval(request.Context(), newRequestPolicyInput(request, compiled.bodyBudget))+ switch verdict.truth {+ case truthTrue:+ next.ServeHTTP(w, request)+ case truthFalse:+ writeJSONErr(w, http.StatusForbidden, config.deniedMessage)+ default:+ // truthError, and deliberately also any truth value a future+ // change adds: an undecidable policy must fail closed rather+ // than fall through to the handler.+ //+ // Every arm here answers with a fixed string, so these are the+ // only places the actual failure is named. Without them an+ // undecidable policy is a 5xx with no cause recorded anywhere,+ // at any level.+ var bodyErr policyBodyError+ var factErr *FactUnavailableError+ switch {+ case errors.As(verdict.err, &bodyErr):+ writeJSONErr(w, http.StatusBadRequest, "could not inspect request")+ case errors.As(verdict.err, &factErr):+ // A dependency the policy consults is down. Warn rather than+ // Error: nothing here is broken, and the alert this should+ // raise is the dependency's, not ours.+ slog.Warn("opa: authorization fact unavailable", "err", verdict.err,+ "facts", factErr.Namespace,+ "route", request.Context().Value(routeKey),+ "traceId", request.Context().Value(middlewares.ContextKey("traceId")))+ writeJSONErr(w, http.StatusBadGateway, "authorization check unavailable")+ default:+ slog.Error("opa: policy evaluation failed", "err", verdict.err,+ "route", request.Context().Value(routeKey),+ "traceId", request.Context().Value(middlewares.ContextKey("traceId")))+ writeJSONErr(w, http.StatusInternalServerError, "policy evaluation failed")+ }+ }+ })+ }+}diff --git a/libs/fleet/backend/auth/policy_middleware_test.go b/libs/fleet/backend/auth/policy_middleware_test.gonew file mode 100644index 0000000000..957aec6121--- /dev/null+++ b/libs/fleet/backend/auth/policy_middleware_test.go@@ -0,0 +1,803 @@+package auth++import (+ "bytes"+ "context"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "slices"+ "strings"+ "testing"+ "testing/fstest"+ "testing/iotest"+)++func TestPolicyMiddlewareInlinePolicyAllowsRequest(t *testing.T) {+ expression := Policy(+ Inline("inline-allow.rego", `+package inline_allow++default allow = false++allow {+ input.method == "GET"+}+`),+ Query("data.inline_allow.allow"),+ )++ called := false+ handler := PolicyMiddleware(expression)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ called = true+ w.WriteHeader(http.StatusNoContent)+ }))++ request := httptest.NewRequest(http.MethodGet, "/resource", nil)+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, request)++ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusNoContent, response.Body.String())+ }+ if !called {+ t.Fatal("allowed request did not reach downstream handler")+ }+}++func TestPolicyExpressionComposition(t *testing.T) {+ allow := Policy(Inline("allow.rego", `package allow_policy+allow { true }+`), Query("data.allow_policy.allow"))+ deny := Policy(Inline("deny.rego", `package deny_policy+default allow = false+`), Query("data.deny_policy.allow"))++ cases := []struct {+ name string+ expression PolicyExpression+ wantStatus int+ }{+ {+ name: "nested any groups satisfy all",+ expression: All(Any(deny, allow), Any(allow, deny)),+ wantStatus: http.StatusNoContent,+ },+ {+ name: "all denies when one child denies",+ expression: All(allow, deny),+ wantStatus: http.StatusForbidden,+ },+ {+ name: "any denies when every child denies",+ expression: Any(deny, deny),+ wantStatus: http.StatusForbidden,+ },+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ handler := PolicyMiddleware(testCase.expression)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))+ if response.Code != testCase.wantStatus {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, testCase.wantStatus, response.Body.String())+ }+ })+ }+}++func TestPolicySourceFromFS(t *testing.T) {+ filesystem := fstest.MapFS{+ "policies/fs.rego": {Data: []byte(`package fs_policy+allow { input.path == "/from-fs" }+`)},+ }+ expression := Policy(+ FromFS(filesystem, "policies/fs.rego"),+ Query("data.fs_policy.allow"),+ )+ handler := PolicyMiddleware(expression)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/from-fs", nil))+ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusNoContent, response.Body.String())+ }+}++func TestPolicyModulesCanImportRegisteredModule(t *testing.T) {+ RegisterPolicyModule("test-base", "base.rego", `package test_base+is_get { input.method == "GET" }+`)+ expression := Policy(+ Modules(+ Registered("test-base"),+ Inline("consumer.rego", `package consumer+import data.test_base+allow { test_base.is_get }+`),+ ),+ Query("data.consumer.allow"),+ )+ handler := PolicyMiddleware(expression)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))+ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusNoContent, response.Body.String())+ }+}++type testFactProvider struct {+ cacheKey string+ facts FactSet+ err error+ loads int+}++func (provider *testFactProvider) CacheKey() string {+ return provider.cacheKey+}++func (provider *testFactProvider) LoadFacts(context.Context, *http.Request) (FactSet, error) {+ provider.loads+++ return provider.facts, provider.err+}++func TestPolicyMiddlewareLoadsAndCachesFacts(t *testing.T) {+ provider := &testFactProvider{+ cacheKey: "user-facts",+ facts: FactSet{+ "age": 24,+ "groups": []string{"customers", "verified-users"},+ },+ }+ agePolicy := Policy(+ Inline("age.rego", `package age_policy+allow { input.facts.user.age >= 21 }+`),+ Query("data.age_policy.allow"),+ WithFacts("user", provider),+ )+ groupPolicy := Policy(+ Inline("group.rego", `package group_policy+allow { input.facts.user.groups[_] == "verified-users" }+`),+ Query("data.group_policy.allow"),+ WithFacts("user", provider),+ )++ handler := PolicyMiddleware(All(agePolicy, groupPolicy))(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))++ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusNoContent, response.Body.String())+ }+ if provider.loads != 1 {+ t.Fatalf("provider loads = %d, want 1", provider.loads)+ }+}++func TestPolicyMiddlewareSkipsFactsInShortCircuitedBranch(t *testing.T) {+ provider := &testFactProvider{cacheKey: "unused", facts: FactSet{"age": 24}}+ allow := Policy(Inline("fast.rego", `package fast+allow { true }+`), Query("data.fast.allow"))+ unused := Policy(+ Inline("unused.rego", `package unused+allow { input.facts.user.age >= 21 }+`),+ Query("data.unused.allow"),+ WithFacts("user", provider),+ )++ handler := PolicyMiddleware(Any(allow, unused))(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))++ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d", response.Code, http.StatusNoContent)+ }+ if provider.loads != 0 {+ t.Fatalf("provider loads = %d, want 0", provider.loads)+ }+}++func TestPolicyMiddlewareFactProviderErrorFailsClosed(t *testing.T) {+ provider := &testFactProvider{cacheKey: "broken", err: errors.New("database unavailable")}+ expression := Policy(+ Inline("facts.rego", `package facts+allow { input.facts.user.age >= 21 }+`),+ Query("data.facts.allow"),+ WithFacts("user", provider),+ )++ called := false+ handler := PolicyMiddleware(expression)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ called = true+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))++ if response.Code != http.StatusInternalServerError {+ t.Fatalf("status = %d, want %d", response.Code, http.StatusInternalServerError)+ }+ if called {+ t.Fatal("provider error reached downstream handler")+ }+}++func TestPolicyMiddlewareProvidesAndRestoresRawBody(t *testing.T) {+ const body = `{"spec":{"runtime":"macos"}}`+ expression := Policy(+ Inline("body.rego", `package body_policy+allow { contains(input.body, "macos") }+`),+ Query("data.body_policy.allow"),+ WithRawBody(1024),+ )++ var downstreamBody string+ handler := PolicyMiddleware(expression, WithDeniedMessage("body denied"))(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {+ contents, err := io.ReadAll(request.Body)+ if err != nil {+ t.Fatalf("read downstream body: %v", err)+ }+ downstreamBody = string(contents)+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ request := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))+ handler.ServeHTTP(response, request)++ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusNoContent, response.Body.String())+ }+ if downstreamBody != body {+ t.Fatalf("downstream body = %q, want %q", downstreamBody, body)+ }+}++func TestPolicyMiddlewareAnySatisfiedDisjunctSurvivesSiblingError(t *testing.T) {+ provider := &testFactProvider{cacheKey: "broken-any-allow", err: errors.New("database unavailable")}+ broken := Policy(+ Inline("broken-any.rego", `package broken_any+allow { input.facts.user.age >= 21 }+`),+ Query("data.broken_any.allow"),+ WithFacts("user", provider),+ )+ allow := Policy(Inline("fallback.rego", `package fallback+allow { true }+`), Query("data.fallback.allow"))++ handler := PolicyMiddleware(Any(broken, allow))(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))++ // A disjunction with a satisfied disjunct is true regardless of whether a+ // sibling could be evaluated. True annihilates max.+ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusNoContent, response.Body.String())+ }+}++func TestPolicyMiddlewareAnyFailsClosedWhenNothingAllows(t *testing.T) {+ provider := &testFactProvider{cacheKey: "broken-any-deny", err: errors.New("database unavailable")}+ broken := Policy(+ Inline("broken-any-deny.rego", `package broken_any_deny+allow { input.facts.user.age >= 21 }+`),+ Query("data.broken_any_deny.allow"),+ WithFacts("user", provider),+ )+ deny := Policy(Inline("deny-any.rego", `package deny_any+default allow = false+`), Query("data.deny_any.allow"))++ handler := PolicyMiddleware(Any(broken, deny))(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))++ // No disjunct allowed, so the error survives and the request fails closed.+ if response.Code != http.StatusInternalServerError {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusInternalServerError, response.Body.String())+ }+}++func TestPolicyMiddlewareAllDenyBeatsSiblingError(t *testing.T) {+ provider := &testFactProvider{cacheKey: "broken-all", err: errors.New("database unavailable")}+ broken := Policy(+ Inline("broken-all.rego", `package broken_all+allow { input.facts.user.age >= 21 }+`),+ Query("data.broken_all.allow"),+ WithFacts("user", provider),+ )+ deny := Policy(Inline("deny-all.rego", `package deny_all+default allow = false+`), Query("data.deny_all.allow"))++ handler := PolicyMiddleware(All(broken, deny))(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))++ // False annihilates min: a definite deny outranks an unevaluable sibling.+ if response.Code != http.StatusForbidden {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusForbidden, response.Body.String())+ }+}++// permutations returns every ordering of values. It is used to assert that+// evaluation is order-independent, which is the property that licenses the+// optimizer to reorder children — over policy nodes here, and over optimizer+// pass names in policy_optimize_test.go, where the same question is asked of+// the pipeline.+func permutations[T any](values []T) [][]T {+ if len(values) <= 1 {+ return [][]T{slices.Clone(values)}+ }+ var result [][]T+ for index := range values {+ rest := make([]T, 0, len(values)-1)+ rest = append(rest, values[:index]...)+ rest = append(rest, values[index+1:]...)+ for _, tail := range permutations(rest) {+ result = append(result, append([]T{values[index]}, tail...))+ }+ }+ return result+}++func TestPolicyMiddlewareEvaluationIsOrderIndependent(t *testing.T) {+ // Leaves with differing WithRawBody limits belong here. The plan-wide body+ // budget makes each leaf's limit check a pure function of the body length+ // and that leaf's own limit, so a small limit somewhere in the tree can no+ // longer decide what a wide-limit sibling sees. Every request below carries+ // the same body so the body-reading leaves actually exercise that.+ const requestBody = "0123456789"++ allow := Policy(Inline("comm-allow.rego", `package comm_allow+allow { true }+`), Query("data.comm_allow.allow"))+ deny := Policy(Inline("comm-deny.rego", `package comm_deny+default allow = false+`), Query("data.comm_deny.allow"))+ broken := Policy(+ Inline("comm-broken.rego", `package comm_broken+allow { input.facts.user.age >= 21 }+`),+ Query("data.comm_broken.allow"),+ WithFacts("user", &testFactProvider{cacheKey: "comm-broken", err: errors.New("database unavailable")}),+ )+ alsoBroken := Policy(+ Inline("comm-broken-2.rego", `package comm_broken_2+allow { input.facts.other.age >= 21 }+`),+ Query("data.comm_broken_2.allow"),+ WithFacts("other", &testFactProvider{cacheKey: "comm-broken-2", err: errors.New("api unavailable")}),+ )+ // Three body-reading leaves at differing limits. bodyOverLimit's limit is+ // smaller than the request body, so it is the leaf that used to poison the+ // shared read for its siblings whenever it ran first.+ bodyAllow := Policy(+ // Built from requestBody rather than repeating the literal, so the+ // const really is the single source it claims to be: change the request+ // body and this leaf follows it instead of silently going false.+ Inline("comm-body-allow.rego", fmt.Sprintf(`package comm_body_allow+allow { input.body == %q }+`, requestBody)),+ Query("data.comm_body_allow.allow"),+ WithRawBody(1024),+ )+ bodyDeny := Policy(+ Inline("comm-body-deny.rego", `package comm_body_deny+allow { input.body == "not the request body" }+`),+ Query("data.comm_body_deny.allow"),+ WithRawBody(512),+ )+ bodyOverLimit := Policy(+ Inline("comm-body-over.rego", `package comm_body_over+allow { true }+`),+ Query("data.comm_body_over.allow"),+ WithRawBody(2),+ )++ cases := []struct {+ name string+ children []Node+ // min: any False -> deny, else any Error -> error status, else allow.+ // max: any True -> allow, else any Error -> error status, else deny.+ // A surviving error is 400 when a policyBodyError is anywhere in the+ // join and 500 otherwise.+ wantAll int+ wantAny int+ }{+ {"allow and deny", []Node{allow, deny}, http.StatusForbidden, http.StatusNoContent},+ {"broken and allow", []Node{broken, allow}, http.StatusInternalServerError, http.StatusNoContent},+ {"broken and deny", []Node{broken, deny}, http.StatusForbidden, http.StatusInternalServerError},+ {"broken allow and deny", []Node{broken, allow, deny}, http.StatusForbidden, http.StatusNoContent},+ {"two broken and allow", []Node{broken, alsoBroken, allow}, http.StatusInternalServerError, http.StatusNoContent},+ {"two broken and deny", []Node{broken, alsoBroken, deny}, http.StatusForbidden, http.StatusInternalServerError},+ {"body allow and body over limit", []Node{bodyAllow, bodyOverLimit}, http.StatusBadRequest, http.StatusNoContent},+ {"body deny and body over limit", []Node{bodyDeny, bodyOverLimit}, http.StatusForbidden, http.StatusBadRequest},+ {"body allow body deny and body over limit", []Node{bodyAllow, bodyDeny, bodyOverLimit}, http.StatusForbidden, http.StatusNoContent},+ {"body over limit and bodyless allow", []Node{bodyOverLimit, allow}, http.StatusBadRequest, http.StatusNoContent},+ {"body over limit and broken facts", []Node{bodyOverLimit, broken}, http.StatusBadRequest, http.StatusBadRequest},+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ for _, operator := range []struct {+ name string+ build func(...Node) Node+ status int+ }{+ {"All", All, testCase.wantAll},+ {"Any", Any, testCase.wantAny},+ } {+ t.Run(operator.name, func(t *testing.T) {+ // Errorf, not Fatalf: which subset of orderings disagrees+ // is the whole diagnosis. Stopping at the first one throws+ // that away.+ for _, ordering := range permutations(testCase.children) {+ handler := PolicyMiddleware(operator.build(ordering...))(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(requestBody)))+ if response.Code != operator.status {+ t.Errorf("status = %d, want %d; body = %s; plan:\n%s",+ response.Code, operator.status, strings.TrimSpace(response.Body.String()),+ Explain(operator.build(ordering...)))+ }+ }+ })+ }+ })+ }+}++func TestPolicyMiddlewarePanicsOnEmptyConjunction(t *testing.T) {+ // The guard has to surface at route construction, not at request time:+ // a route that cannot be authorized must never serve traffic at all.+ defer func() {+ recovered := recover()+ if recovered == nil {+ t.Fatal("PolicyMiddleware built a route from an empty conjunction, which would allow every request")+ }+ // Assert why it panicked. A test satisfied by any panic keeps passing+ // once it is no longer the guard doing the panicking.+ if message := fmt.Sprint(recovered); !strings.Contains(message, "auth.AllNode has no children") {+ t.Fatalf("panic = %v, want it to name the childless node", message)+ }+ }()++ PolicyMiddleware(AllNode{})+}++// undecidablePolicy compiles and then fails at evaluation: two complete rules+// assigning different values to the same name is an eval_conflict_error, and+// making both bodies depend on input keeps OPA from resolving the conflict+// before a request arrives.+const undecidablePolicy = `package undecidable++allow = true {+ input.method != ""+}++allow = false {+ input.method != ""+}+`++// TestPolicyMiddlewareLogsTheEvaluationError pins the one thing the 500 does+// not carry. The response body is the fixed string "policy evaluation failed",+// so unless the middleware logs verdict.err an undecidable policy is an error+// with its cause recorded nowhere, at no level — which is what this code did+// until the test existed.+//+// slog.Default is swapped rather than injected because PolicyMiddleware has no+// logger seam, and this package forbids t.Parallel (see policy_optimize.go),+// which is what makes swapping a global safe here.+func TestPolicyMiddlewareLogsTheEvaluationError(t *testing.T) {+ var logged bytes.Buffer+ restore := slog.Default()+ slog.SetDefault(slog.New(slog.NewJSONHandler(&logged, nil)))+ t.Cleanup(func() { slog.SetDefault(restore) })++ called := false+ handler := PolicyMiddleware(Policy(+ Inline("undecidable.rego", undecidablePolicy),+ Query("data.undecidable.allow"),+ ))(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ called = true+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))++ if response.Code != http.StatusInternalServerError {+ t.Fatalf("status = %d, want %d", response.Code, http.StatusInternalServerError)+ }+ if called {+ t.Fatal("an evaluation error reached the downstream handler")+ }+ // The specific OPA error code, not merely that something was logged: a+ // record naming only the route would satisfy a laxer check while still+ // losing the cause.+ if !strings.Contains(logged.String(), "eval_conflict_error") {+ t.Fatalf("the evaluation error was not logged; got:\n%s", logged.String())+ }+}++func TestPolicyMiddlewareBodyErrorClassificationIsOrderIndependent(t *testing.T) {+ // Exactly one leaf reads the body, so this exercises error accumulation:+ // a joined error is classified by the body error inside it whichever+ // sibling produced it. The separate hazard of leaves at differing limits+ // sharing one read belongs to TestPolicyBodyIsRestoredForDownstreamHandler+ // and to the body rows of TestPolicyMiddlewareEvaluationIsOrderIndependent.+ tooLarge := Policy(+ Inline("order-body.rego", `package order_body+allow { input.body == "12345" }+`),+ Query("data.order_body.allow"),+ WithRawBody(4),+ )+ broken := Policy(+ Inline("order-facts.rego", `package order_facts+allow { input.facts.user.age >= 21 }+`),+ Query("data.order_facts.allow"),+ WithFacts("user", &testFactProvider{cacheKey: "order-facts", err: errors.New("database unavailable")}),+ )++ // Both siblings error, one with a policyBodyError. Errors are joined, so+ // errors.As finds the body error whichever sibling produced it first.+ for _, ordering := range [][]Node{{tooLarge, broken}, {broken, tooLarge}} {+ for _, build := range []func(...Node) Node{All, Any} {+ handler := PolicyMiddleware(build(ordering...))(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/", strings.NewReader("12345")))+ if response.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want %d; body = %s; plan:\n%s",+ response.Code, http.StatusBadRequest, strings.TrimSpace(response.Body.String()),+ Explain(build(ordering...)))+ }+ }+ }+}++func TestPolicyBodyIsRestoredForDownstreamHandler(t *testing.T) {+ const requestBody = "0123456789"++ // narrow's own limit is under the body length, so it errors; wide's is well+ // over it and its Rego checks the bytes, so a satisfied disjunct proves the+ // wide leaf saw the body intact. Running both orderings is what shows the+ // narrow leaf can no longer decide what its sibling reads.+ narrow := Policy(+ Inline("narrow-restore.rego", `package narrow_restore+allow { true }+`),+ Query("data.narrow_restore.allow"),+ WithRawBody(2),+ )+ wide := Policy(+ Inline("wide-restore.rego", fmt.Sprintf(`package wide_restore+allow { input.body == %q }+`, requestBody)),+ Query("data.wide_restore.allow"),+ WithRawBody(1024),+ )++ for _, testCase := range []struct {+ name string+ node Node+ }{+ {"narrow first", Any(narrow, wide)},+ {"wide first", Any(wide, narrow)},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ tracked := &closeTrackingBody{Reader: strings.NewReader(requestBody)}+ var seen string+ handler := PolicyMiddleware(testCase.node)(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {+ body, err := io.ReadAll(request.Body)+ if err != nil {+ t.Fatalf("read downstream body: %v", err)+ }+ seen = string(body)+ if err := request.Body.Close(); err != nil {+ t.Fatalf("close downstream body: %v", err)+ }+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/", tracked))++ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusNoContent, response.Body.String())+ }+ if seen != requestBody {+ t.Fatalf("downstream body = %q, want the full request body", seen)+ }+ // The replacement body wraps the original rather than a NopCloser+ // over a detached buffer, so the handler's Close reaches it. This+ // is the assertion that keeps that deliberate.+ if tracked.closes != 1 {+ t.Fatalf("original body closes = %d, want 1", tracked.closes)+ }+ })+ }+}++func TestPolicyBodyReadErrorStillGivesHandlerTheBytesItRead(t *testing.T) {+ // A body that yields some bytes and then fails. The reading leaf latches+ // the transport error and is undecidable, but a body-less sibling allows+ // the request anyway — and the handler must then get the bytes that were+ // read plus the same error, not a stream with its first bytes eaten. This+ // is the read-error corner of the restore, the one place the old code+ // still skipped it.+ failure := errors.New("connection reset mid-body")+ reading := Policy(Inline("read-error.rego", `package read_error+allow { true }+`), Query("data.read_error.allow"), WithRawBody(1024))+ bodyless := Policy(Inline("read-error-allow.rego", `package read_error_allow+allow { true }+`), Query("data.read_error_allow.allow"))++ tracked := &closeTrackingBody{+ Reader: io.MultiReader(strings.NewReader("0123"), iotest.ErrReader(failure)),+ }+ var seen string+ var readErr error+ handler := PolicyMiddleware(Any(reading, bodyless))(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {+ body, err := io.ReadAll(request.Body)+ seen, readErr = string(body), err+ if err := request.Body.Close(); err != nil {+ t.Fatalf("close downstream body: %v", err)+ }+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/", tracked))++ // The satisfied disjunct annihilates the reading leaf's error.+ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusNoContent, response.Body.String())+ }+ if seen != "0123" {+ t.Fatalf("downstream body = %q, want the bytes read before the failure", seen)+ }+ if !errors.Is(readErr, failure) {+ t.Fatalf("downstream read error = %v, want it to surface %v", readErr, failure)+ }+ if tracked.closes != 1 {+ t.Fatalf("original body closes = %d, want 1", tracked.closes)+ }+}++// closeTrackingBody is a request body that counts Close calls, so a test can+// tell whether the ReadCloser the middleware substitutes still releases the+// original.+type closeTrackingBody struct {+ io.Reader+ closes int+}++func (body *closeTrackingBody) Close() error {+ body.closes+++ return nil+}++func TestPolicyBodyOverBudgetReachesHandlerIntact(t *testing.T) {+ // The body is larger than every limit in the plan, so the leaf that reads+ // it errors. A body-less sibling can still allow the request, and once it+ // does, the handler is entitled to the body exactly as sent. The bytes+ // loadBody consumed to make its own limit decision must be spliced back in+ // front of the remainder, not silently dropped: a proxied request arriving+ // with a hole at the front is worse than no request at all.+ overLimit := Policy(+ Inline("over-budget.rego", `package over_budget+allow { true }+`),+ Query("data.over_budget.allow"),+ WithRawBody(2),+ )+ bodyless := Policy(Inline("over-budget-allow.rego", `package over_budget_allow+allow { true }+`), Query("data.over_budget_allow.allow"))++ // The allowing sibling annihilates the disjunction, so ordering decides+ // whether the body is read at all: with it first, nothing touches the body+ // and the handler gets the original untouched. Both orderings must hand the+ // handler the same bytes and close the original exactly once.+ for _, testCase := range []struct {+ name string+ node Node+ }{+ {"reading leaf first", Any(overLimit, bodyless)},+ {"allowing leaf first", Any(bodyless, overLimit)},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ tracked := &closeTrackingBody{Reader: strings.NewReader("0123456789")}+ var seen string+ handler := PolicyMiddleware(testCase.node)(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {+ body, err := io.ReadAll(request.Body)+ if err != nil {+ t.Fatalf("read downstream body: %v", err)+ }+ seen = string(body)+ if err := request.Body.Close(); err != nil {+ t.Fatalf("close downstream body: %v", err)+ }+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/", tracked))++ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusNoContent, response.Body.String())+ }+ if seen != "0123456789" {+ t.Fatalf("downstream body = %q, want the full request body", seen)+ }+ // The original still holds unread bytes here, so the substituted+ // ReadCloser must not swallow Close: it does not own that stream.+ if tracked.closes != 1 {+ t.Fatalf("original body closes = %d, want 1", tracked.closes)+ }+ })+ }+}++func TestPolicyMiddlewareCachedBodyHonorsEachLeafLimit(t *testing.T) {+ wide := Policy(+ Inline("wide.rego", `package wide+allow { input.body == "12345" }+`),+ Query("data.wide.allow"),+ WithRawBody(1024),+ )+ narrow := Policy(+ Inline("narrow.rego", `package narrow+allow { input.body == "12345" }+`),+ Query("data.narrow.allow"),+ WithRawBody(4),+ )++ handler := PolicyMiddleware(All(wide, narrow))(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/", strings.NewReader("12345")))++ if response.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusBadRequest, response.Body.String())+ }+}diff --git a/libs/fleet/backend/auth/policy_optimize.go b/libs/fleet/backend/auth/policy_optimize.gonew file mode 100644index 0000000000..65aa5c6b2c--- /dev/null+++ b/libs/fleet/backend/auth/policy_optimize.go@@ -0,0 +1,259 @@+package auth++import (+ "fmt"+ "slices"+)++// This file rewrites policy trees. Every pass here is justified by an algebraic+// property of the evaluator's lattice rather than by inspection: All is min and+// Any is max over truthFalse < truthError < truthTrue (see policy_plan.go), and+// min and max are associative, idempotent and commutative. flatten is+// associativity, collapseUnary is a fold over one element, dedupe is+// idempotence, and sinkFactLoaders — in policy_cost.go, with the cost model it+// sorts by — is commutativity.+//+// None of the four was legal before that lattice existed. Under the earlier+// short-circuit-on-error semantics the verdict depended on which child failed+// first, so merging, dropping or reordering children could change the answer.+// The differential harness in policy_equivalence_test.go is what keeps that+// honest: it runs the whole default pipeline against a total reference+// evaluator over 300 generated trees.++// optimizer rewrites a policy AST. Optimizers are total: a pass that cannot+// safely apply a rewrite returns its input unchanged rather than failing, so a+// buggy or over-cautious pass can never take down startup.+//+// Passes are unexported because a pipeline selects them by name and there is+// no way to register one from outside. An exported pass would be a function+// nothing could ask this package to run.+type optimizer func(Node) Node++// optimizerRegistry maps pass names to implementations. Pipelines are ordered+// name lists because pass order changes the result.+//+// It is written at init and, in this package's tests, by registerTestPass;+// Optimize only reads it. That is safe only while no test runs in parallel, so+// nothing in this package may call t.Parallel.+var optimizerRegistry = map[string]optimizer{+ "flatten": flatten,+ "collapse": collapseUnary,+ "dedupe": dedupe,+ "sink-facts": sinkFactLoaders,+}++// defaultPipeline is ordered deliberately. flatten must precede sink-facts,+// because All(cheap, All(needsDB, cheap)) cannot hoist the inner cheap leaf+// past the DB leaf until the nesting is gone. sink-facts runs last because its+// output is not a normal form.+var defaultPipeline = []string{"flatten", "collapse", "dedupe", "sink-facts"}++// DefaultPipeline is the pass list PolicyMiddleware runs when no pipeline is+// given. It returns a fresh slice: the default decides which rewrites every+// route's authorization plan receives, and an exported []string could be+// rewritten from anywhere with nothing to report it.+func DefaultPipeline() []string { return slices.Clone(defaultPipeline) }++const optimizeFixpointLimit = 8++// Optimize runs the named passes in order, repeating until the tree stops+// changing or the sweep cap is reached. One sweep is not always enough:+// collapse can expose a merge for flatten, so the two only settle when run to a+// fixpoint.+//+// Exhausting the cap does not imply a broken pass. A correct pipeline needs+// roughly one sweep per level of alternating All/Any nesting, because each+// sweep only unwraps one, so a tree deeper than the cap returns correct but+// not fully optimized — and silently, since a partly-optimized plan decides+// exactly what a fully optimized one would. The cap is there for the other+// case: a pass that never converges must not hang route construction.+//+// Convergence is detected by rendering rather than by comparing, because a Node+// is not comparable — a Leaf holds a []factProviderConfig and its Source may+// wrap an fs.FS, so == does not compile and reflect.DeepEqual would descend+// into whatever a filesystem value happens to contain. Explain cannot tell two+// distinct fs sources apart, and that direction of imprecision is safe: a false+// "equal" only stops optimizing early. Deciding that two leaves may be *merged*+// tolerates no such thing, which is why dedupe asks key() instead.+//+// An unknown pass name panics, like every other route-construction mistake in+// this package: a mistyped name is a pipeline nobody asked for, with nothing+// downstream to notice. Names are resolved before any rewriting starts, so a+// bad name late in the list cannot leave a half-run pipeline behind.+func Optimize(n Node, pipeline []string) Node {+ passes := make([]optimizer, 0, len(pipeline))+ for _, name := range pipeline {+ pass, ok := optimizerRegistry[name]+ if !ok {+ panic(fmt.Sprintf("unknown policy optimizer pass %q", name))+ }+ passes = append(passes, pass)+ }+ if len(passes) == 0 {+ // No optimization means none: no rewriting, and no rendering to detect+ // that nothing was rewritten.+ return n+ }++ current := n+ rendered := Explain(current)+ for iteration := 0; iteration < optimizeFixpointLimit; iteration++ {+ for _, pass := range passes {+ current = pass(current)+ }+ next := Explain(current)+ if next == rendered {+ break+ }+ rendered = next+ }+ return current+}++// mapChildren applies a rewrite to a node's children, which is what makes every+// pass in this file bottom-up: a pass calls it first and then rewrites the node+// it is looking at, so it sees children that have already settled.+//+// A Leaf is returned as-is rather than rebuilt. No pass here constructs a Leaf,+// so Source, Facts and MaxBody survive by construction rather than by each pass+// remembering to copy them.+func mapChildren(n Node, rewrite func(Node) Node) Node {+ switch node := n.(type) {+ case AllNode:+ return AllNode{Children: rewriteChildren(node.Children, rewrite)}+ case AnyNode:+ return AnyNode{Children: rewriteChildren(node.Children, rewrite)}+ }+ return n+}++func rewriteChildren(children []Node, rewrite func(Node) Node) []Node {+ rewritten := make([]Node, len(children))+ for index, child := range children {+ rewritten[index] = rewrite(child)+ }+ return rewritten+}++// flatten merges a node's same-kind children into it: All(a, All(b, c)) becomes+// All(a, b, c). Legal because min and max are associative.+//+// Only within one kind. All(a, Any(b, c)) stays as it is: no distributive law+// is available here, and absorbing the disjunction would turn "b or c" into "b+// and c".+func flatten(n Node) Node {+ n = mapChildren(n, flatten)+ switch node := n.(type) {+ case AllNode:+ return AllNode{Children: flattenChildren(node.Children, func(child Node) ([]Node, bool) {+ inner, ok := child.(AllNode)+ return inner.Children, ok+ })}+ case AnyNode:+ return AnyNode{Children: flattenChildren(node.Children, func(child Node) ([]Node, bool) {+ inner, ok := child.(AnyNode)+ return inner.Children, ok+ })}+ }+ return n+}++// flattenChildren returns a new child list with the children of same-kind+// children spliced in. sameKind reports whether a child is the parent's kind+// and, if so, what its children are.+func flattenChildren(children []Node, sameKind func(Node) ([]Node, bool)) []Node {+ merged := make([]Node, 0, len(children))+ for _, child := range children {+ inner, ok := sameKind(child)+ if !ok {+ merged = append(merged, child)+ continue+ }+ if len(inner) == 0 {+ // Deliberately not spliced. A childless composite is malformed+ // input, and splicing its zero children would delete the evidence:+ // All(a, AllNode{}) would silently become All(a), and+ // All(AllNode{}) would leave the parent childless as well. Either+ // way a named startup error from compileChildren becomes a plan+ // that is wrong with nothing to report it, so pass it through and+ // let Compile refuse it.+ merged = append(merged, child)+ continue+ }+ merged = append(merged, inner...)+ }+ return merged+}++// collapseUnary rewrites All(a) and Any(a) to a. Legal because a fold over a+// single element is that element, for either combinator: min(identity, a) and+// max(identity, a) are both a.+func collapseUnary(n Node) Node {+ n = mapChildren(n, collapseUnary)+ switch node := n.(type) {+ case AllNode:+ if len(node.Children) == 1 {+ return node.Children[0]+ }+ case AnyNode:+ if len(node.Children) == 1 {+ return node.Children[0]+ }+ }+ return n+}++// dedupe removes repeated identical leaves from a node's children. Legal+// because min and max are idempotent: min(a, a) = a and max(a, a) = a, whatever+// a is — including truthError, so a leaf that fails is no more informative for+// having failed twice.+func dedupe(n Node) Node {+ n = mapChildren(n, dedupe)+ switch node := n.(type) {+ case AllNode:+ return AllNode{Children: dedupeChildren(node.Children)}+ case AnyNode:+ return AnyNode{Children: dedupeChildren(node.Children)}+ }+ return n+}++// dedupeChildren keeps the first occurrence of each leaf key and drops later+// ones. It always keeps that first occurrence, so it cannot empty a composite:+// the output is shorter than the input only when the input had at least two+// children.+//+// Identity comes from Leaf.key(), never from Explain. Explain renders a source+// with no stable identity as its Go type, so two distinct filesystems sharing a+// path render identically — good enough to stop optimizing early, and a silent+// authorization change if it decided a merge. key() returns "" for exactly+// those leaves, and "" is never equal to anything, including itself. It also+// quotes what it joins, so a separator inside a query or a source name cannot+// make two different leaves look like one.+func dedupeChildren(children []Node) []Node {+ seen := make(map[string]bool, len(children))+ kept := make([]Node, 0, len(children))+ for _, child := range children {+ leaf, ok := child.(Leaf)+ if !ok {+ // Only leaves are compared. Two structurally identical subtrees are+ // left alone: proving them equal means proving every leaf under+ // them equal, and nothing here needs that yet.+ kept = append(kept, child)+ continue+ }+ key := leaf.key()+ if key == "" {+ // No stable identity: never equal to anything, so never merged and+ // never recorded as something a later leaf could be merged into.+ kept = append(kept, child)+ continue+ }+ if seen[key] {+ continue+ }+ seen[key] = true+ kept = append(kept, child)+ }+ return kept+}diff --git a/libs/fleet/backend/auth/policy_optimize_test.go b/libs/fleet/backend/auth/policy_optimize_test.gonew file mode 100644index 0000000000..888d1d5af1--- /dev/null+++ b/libs/fleet/backend/auth/policy_optimize_test.go@@ -0,0 +1,880 @@+package auth++import (+ "fmt"+ "math/rand"+ "net/http"+ "strings"+ "testing"+ "testing/fstest"+)++// These tests pin what each pass does. The differential harness in+// policy_equivalence_test.go pins that the passes do not change what a policy+// decides — but it cannot tell an optimizer that works from one that returns+// its input, because a no-op preserves semantics perfectly. Everything below+// asserts the rewrites actually happen, and that they stop where they must.++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++// The leaf builders every test in this package draws from. One per thing the+// cost model tiers, so a test can say what a leaf costs by which builder made+// it: allowLeaf and denyLeaf are costPure, bodyLeaf is costBody, factLeaf is+// costFacts.++func allowLeaf(name string) Node {+ return Policy(+ Inline(name+".rego", "package "+name+"\nallow { true }\n"),+ Query("data."+name+".allow"),+ )+}++func denyLeaf(name string) Node {+ return Policy(+ Inline(name+".rego", "package "+name+"\ndefault allow = false\n"),+ Query("data."+name+".allow"),+ )+}++// costBodyLimit is the raw-body limit bodyLeaf declares. Its own constant+// rather than a borrowed one: the harness's equivalenceWideBodyLimit is tied by+// a compile-time assertion to the length of the request body those tests send,+// and nothing here depends on that relationship. Any positive limit tiers a+// leaf as costBody.+const costBodyLimit = 1024++func bodyLeaf(name string) Node {+ return Policy(+ Inline(name+".rego", "package "+name+"\nallow { true }\n"),+ Query("data."+name+".allow"),+ WithRawBody(costBodyLimit),+ )+}++// factLeaf allows when its facts loaded, so it is cheap to reason about and+// expensive to evaluate — the shape sink-facts exists to move. Each provider+// gets its own namespace, but the Rego only reads the first: what the leaf+// decides is not the point, what it had to load to decide is.+func factLeaf(name string, providers ...FactProvider) Node {+ options := []PolicyOption{Query("data." + name + ".allow")}+ for index, provider := range providers {+ options = append(options, WithFacts(fmt.Sprintf("u%d", index), provider))+ }+ return Policy(+ Inline(name+".rego", "package "+name+"\nallow { input.facts.u0.ok }\n"),+ options...,+ )+}++// loadingFacts is the provider factLeaf is usually given: it succeeds, and+// testFactProvider counts the loads. That count is the whole point of the pass+// — a fact load is a database or API call, and sinking the leaf that needs it+// behind a cheap check is what removes the call rather than merely reordering+// it.+func loadingFacts(cacheKey string) *testFactProvider {+ return &testFactProvider{cacheKey: cacheKey, facts: FactSet{"ok": true}}+}++// dedupeFS is a filesystem whose one module is byte-identical to every other+// dedupeFS. Two of these are indistinguishable by path and by content, and+// still must not be merged: fs.FS has no identity a pass can compare.+func dedupeFS() fstest.MapFS {+ return fstest.MapFS{"p.rego": {Data: []byte("package p\nallow { true }\n")}}+}++// countingPolicySource counts how often its Rego is loaded. Compile loads each+// surviving leaf's source exactly once, which is what makes "did the middleware+// run the pipeline" observable: PolicyMiddleware's only other output is an HTTP+// status, and dropping a duplicate leaf does not change one.+type countingPolicySource struct {+ name string+ text string+ loads *int+}++func (countingPolicySource) policySource() {}++func (source countingPolicySource) modules() ([]policyModule, error) {+ *source.loads+++ return []policyModule{{name: source.name, source: source.text}}, nil+}++func (source countingPolicySource) sourceKey() string { return "counting:" + source.name }++func countingAllow(name string, loads *int) Node {+ return Policy(+ countingPolicySource{name: name + ".rego", text: "package " + name + "\nallow { true }\n", loads: loads},+ Query("data."+name+".allow"),+ )+}++// registerTestPass installs a pass for the duration of one test. It refuses to+// shadow a real pass, so a test cannot quietly replace flatten with a recorder+// and then assert about flatten.+func registerTestPass(t *testing.T, name string, pass optimizer) {+ t.Helper()+ if _, exists := optimizerRegistry[name]; exists {+ t.Fatalf("pass %q is already registered; pick a name that is not a real pass", name)+ }+ optimizerRegistry[name] = pass+ t.Cleanup(func() { delete(optimizerRegistry, name) })+}++// emptyCompositeIn finds a childless All or Any, the shape compileChildren+// rejects by name. Before that guard existed an empty conjunction compiled to+// an unconditional allow, so a pass that produced one would turn a startup+// error into a 200 if the guard were ever relaxed.+func emptyCompositeIn(n Node) Node {+ var children []Node+ switch node := n.(type) {+ case AllNode:+ children = node.Children+ case AnyNode:+ children = node.Children+ default:+ return nil+ }+ if len(children) == 0 {+ return n+ }+ for _, child := range children {+ if found := emptyCompositeIn(child); found != nil {+ return found+ }+ }+ return nil+}++func childrenOf(t *testing.T, n Node) []Node {+ t.Helper()+ switch node := n.(type) {+ case AllNode:+ return node.Children+ case AnyNode:+ return node.Children+ default:+ t.Fatalf("node is %T, want a composite\n%s", n, Explain(n))+ return nil+ }+}++// ---------------------------------------------------------------------------+// Flatten+// ---------------------------------------------------------------------------++func TestFlattenCollapsesNestedSameKindNodes(t *testing.T) {+ node := All(allowLeaf("a"), All(allowLeaf("b"), allowLeaf("c")))+ got := Optimize(node, []string{"flatten"})++ // Compared whole: the count alone would not notice a pass that merged the+ // right number of children in the wrong order or lost one to a duplicate.+ want := Explain(All(allowLeaf("a"), allowLeaf("b"), allowLeaf("c")))+ if Explain(got) != want {+ t.Fatalf("Explain output:\n%s\nwant:\n%s", Explain(got), want)+ }+}++func TestFlattenMergesRecursively(t *testing.T) {+ // mapChildren rewrites bottom-up, so a chain deeper than one level must+ // collapse in a single application of the pass.+ node := All(allowLeaf("a"), All(allowLeaf("b"), All(allowLeaf("c"), allowLeaf("d"))))+ got := flatten(node)+ if children := childrenOf(t, got); len(children) != 4 {+ t.Fatalf("children = %d, want 4\n%s", len(children), Explain(got))+ }+}++func TestFlattenLeavesMixedKindsAlone(t *testing.T) {+ // Only associativity within one combinator is available: min distributes+ // over nothing here, so All must not absorb an Any's children.+ node := All(allowLeaf("a"), Any(allowLeaf("b"), allowLeaf("c")))+ got := Optimize(node, []string{"flatten"})++ children := childrenOf(t, got)+ if len(children) != 2 {+ t.Fatalf("children = %d, want 2\n%s", len(children), Explain(got))+ }+ if _, ok := children[1].(AnyNode); !ok {+ t.Fatalf("second child = %T, want AnyNode\n%s", children[1], Explain(got))+ }++ // The mirror image, so that a pass hard-coded to one kind is caught too.+ mirrored := Optimize(Any(allowLeaf("a"), All(allowLeaf("b"), allowLeaf("c"))), []string{"flatten"})+ mirroredChildren := childrenOf(t, mirrored)+ if len(mirroredChildren) != 2 {+ t.Fatalf("mirrored children = %d, want 2\n%s", len(mirroredChildren), Explain(mirrored))+ }+ if _, ok := mirroredChildren[1].(AllNode); !ok {+ t.Fatalf("mirrored second child = %T, want AllNode\n%s", mirroredChildren[1], Explain(mirrored))+ }+}++func TestFlattenLeavesChildlessCompositesForCompileToReject(t *testing.T) {+ // A childless composite is malformed input, not something to absorb.+ // Absorbing its zero children would erase the evidence, and for+ // All(AllNode{}) it would leave the parent childless as well.+ cases := []struct {+ name string+ node Node+ }{+ {"empty inner conjunction", AllNode{Children: []Node{allowLeaf("a"), AllNode{}}}},+ {"empty sole child", AllNode{Children: []Node{AllNode{}}}},+ {"empty inner disjunction", AnyNode{Children: []Node{allowLeaf("a"), AnyNode{}}}},+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ got := flatten(testCase.node)+ // Compared whole rather than asking whether an empty composite+ // survives somewhere. The first draft asked the weaker question,+ // and for "empty sole child" splicing merely moves the childless+ // node up to the root — where emptyCompositeIn still finds it, so+ // that subcase detected nothing. "Unchanged" is what the guard+ // actually promises, and it is the same promise for all three.+ if Explain(got) != Explain(testCase.node) {+ t.Fatalf("Flatten rewrote a tree containing a childless composite:\n%s\nwant it untouched:\n%s",+ Explain(got), Explain(testCase.node))+ }+ if emptyCompositeIn(got) == nil {+ t.Fatalf("Flatten swallowed the childless composite:\n%s", Explain(got))+ }+ if _, err := Compile(got); err == nil {+ t.Fatalf("Compile accepted a tree with a childless composite:\n%s", Explain(got))+ }+ })+ }+}++// ---------------------------------------------------------------------------+// CollapseUnary+// ---------------------------------------------------------------------------++func TestCollapseUnaryRemovesSingleChildNodes(t *testing.T) {+ node := All(Any(allowLeaf("a")))+ got := Optimize(node, []string{"collapse"})+ if _, ok := got.(Leaf); !ok {+ t.Fatalf("got %T, want Leaf\n%s", got, Explain(got))+ }+}++func TestCollapseUnaryKeepsMultiChildNodes(t *testing.T) {+ // A fold over one element is that element; a fold over two is not either of+ // them. Both kinds, so a pass that checked the wrong length for one of them+ // is caught.+ cases := []struct {+ name string+ node Node+ }{+ {"conjunction", All(allowLeaf("a"), allowLeaf("b"))},+ {"disjunction", Any(allowLeaf("a"), allowLeaf("b"))},+ {"nested", All(allowLeaf("a"), Any(allowLeaf("b"), allowLeaf("c")))},+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ got := Optimize(testCase.node, []string{"collapse"})+ if Explain(got) != Explain(testCase.node) {+ t.Fatalf("collapse rewrote a multi-child node:\n%s\nwant:\n%s", Explain(got), Explain(testCase.node))+ }+ })+ }+}++// ---------------------------------------------------------------------------+// Dedupe+// ---------------------------------------------------------------------------++func TestDedupeRemovesIdenticalLeaves(t *testing.T) {+ node := All(allowLeaf("a"), allowLeaf("b"), allowLeaf("a"))+ got := Optimize(node, []string{"dedupe"})++ // The whole rendering, not the child count: dropping the duplicate and+ // dropping "b" both leave two children.+ want := Explain(All(allowLeaf("a"), allowLeaf("b")))+ if Explain(got) != want {+ t.Fatalf("Explain output:\n%s\nwant:\n%s", Explain(got), want)+ }+}++func TestDedupeAppliesInsideNestedNodes(t *testing.T) {+ node := All(allowLeaf("a"), Any(allowLeaf("b"), allowLeaf("b")))+ got := Optimize(node, []string{"dedupe"})++ children := childrenOf(t, got)+ if len(children) != 2 {+ t.Fatalf("outer children = %d, want 2\n%s", len(children), Explain(got))+ }+ if inner := childrenOf(t, children[1]); len(inner) != 1 {+ t.Fatalf("inner children = %d, want 1\n%s", len(inner), Explain(got))+ }+}++func TestDedupeKeepsLeavesThatAreNotProvablyIdentical(t *testing.T) {+ // Every component of Leaf.key() gets a pair that differs in it alone. A+ // dedupe keyed on any subset of them would merge one of these pairs, which+ // silently removes an authorization check.+ facts := &testFactProvider{cacheKey: "facts-a", facts: FactSet{"ok": true}}+ otherFacts := &testFactProvider{cacheKey: "facts-b", facts: FactSet{"ok": true}}+ source := Inline("p.rego", "package p\nallow { true }\n")++ cases := []struct {+ name string+ node Node+ }{+ {+ name: "different queries",+ node: All(Policy(source, Query("data.p.allow")), Policy(source, Query("data.p.other"))),+ },+ {+ name: "different sources",+ node: All(allowLeaf("a"), allowLeaf("b")),+ },+ {+ name: "same source name, different text",+ node: All(+ Policy(Inline("p.rego", "package p\nallow { true }\n"), Query("data.p.allow")),+ Policy(Inline("p.rego", "package p\nallow { false }\n"), Query("data.p.allow")),+ ),+ },+ {+ name: "different facts",+ node: All(+ Policy(source, Query("data.p.allow"), WithFacts("u", facts)),+ Policy(source, Query("data.p.allow"), WithFacts("u", otherFacts)),+ ),+ },+ {+ name: "different fact namespaces",+ node: All(+ Policy(source, Query("data.p.allow"), WithFacts("u", facts)),+ Policy(source, Query("data.p.allow"), WithFacts("v", facts)),+ ),+ },+ {+ // A separator inside a component, which an unquoted encoding would+ // let cross a field boundary: both of these encode as+ // leaf|registered:x|y|z||0 unless key() quotes what it joins. See+ // TestLeafKeyIsInjective.+ name: "a source and query that collide unless the key is quoted",+ node: All(+ Policy(Registered("x"), Query("y|z")),+ Policy(Registered("x|y"), Query("z")),+ ),+ },+ {+ name: "different body limits",+ node: All(+ Policy(source, Query("data.p.allow"), WithRawBody(16)),+ Policy(source, Query("data.p.allow"), WithRawBody(32)),+ ),+ },+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ got := Optimize(testCase.node, []string{"dedupe"})+ if children := childrenOf(t, got); len(children) != 2 {+ t.Fatalf("children = %d, want 2 (these leaves are not identical)\n%s", len(children), Explain(got))+ }+ })+ }+}++func TestDedupeNeverMergesLeavesWithoutStableIdentity(t *testing.T) {+ // key() returns "" for a source with no stable identity, and "" means+ // "never equal to anything, including itself". fs.FS is the case that+ // matters: two filesystems can share a path and serve different Rego, so+ // merging them would swap one policy for another with no visible change.+ //+ // The generated trees in the differential harness are all Inline, so this+ // rule is exercised nowhere else.+ shared := FromFS(dedupeFS(), "p.rego")++ cases := []struct {+ name string+ node Node+ want int+ }{+ {+ name: "the very same fs source twice",+ node: All(Policy(shared, Query("data.p.allow")), Policy(shared, Query("data.p.allow"))),+ want: 2,+ },+ {+ name: "two filesystems with identical contents at the same path",+ node: All(+ Policy(FromFS(dedupeFS(), "p.rego"), Query("data.p.allow")),+ Policy(FromFS(dedupeFS(), "p.rego"), Query("data.p.allow")),+ ),+ want: 2,+ },+ {+ name: "a multi source poisoned by an fs child",+ node: All(+ Policy(Modules(Registered("r"), shared), Query("data.p.allow")),+ Policy(Modules(Registered("r"), shared), Query("data.p.allow")),+ ),+ want: 2,+ },+ {+ // The control. Without it, a Dedupe that merged nothing at all would+ // pass every case above.+ name: "identical inline leaves still merge",+ node: All(allowLeaf("a"), allowLeaf("a")),+ want: 1,+ },+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ got := Optimize(testCase.node, []string{"dedupe"})+ if children := childrenOf(t, got); len(children) != testCase.want {+ t.Fatalf("children = %d, want %d\n%s", len(children), testCase.want, Explain(got))+ }+ })+ }+}++func TestDedupeLeavesOneChildBehind(t *testing.T) {+ // Dedupe keeps the first occurrence of every key, so it cannot empty a+ // composite. Asserted rather than assumed: a childless conjunction is the+ // one rewrite outcome that fails as a startup error instead of a wrong+ // answer, and only because compileChildren rejects it.+ node := All(allowLeaf("a"), allowLeaf("a"), allowLeaf("a"))+ got := Optimize(node, []string{"dedupe"})++ if empty := emptyCompositeIn(got); empty != nil {+ t.Fatalf("dedupe produced a childless composite:\n%s", Explain(got))+ }+ if children := childrenOf(t, got); len(children) != 1 {+ t.Fatalf("children = %d, want 1\n%s", len(children), Explain(got))+ }+ if _, err := Compile(got); err != nil {+ t.Fatalf("Compile: %v\n%s", err, Explain(got))+ }+}++// ---------------------------------------------------------------------------+// The registry and the fixpoint loop+// ---------------------------------------------------------------------------++func TestOptimizeRunsPassesInPipelineOrder(t *testing.T) {+ var calls []string+ recorder := func(name string) optimizer {+ return func(n Node) Node {+ calls = append(calls, name)+ return n+ }+ }+ registerTestPass(t, "test-record-1", recorder("test-record-1"))+ registerTestPass(t, "test-record-2", recorder("test-record-2"))+ registerTestPass(t, "test-record-3", recorder("test-record-3"))++ // Deliberately not a palindrome: a first draft used one, and reversing the+ // loop that runs the passes then changed nothing this test could see.+ // A name appears twice as well, because a pipeline is a list, not a set.+ Optimize(allowLeaf("a"), []string{"test-record-2", "test-record-1", "test-record-1", "test-record-3"})++ // Exactly one iteration, because nothing changed. Both halves matter: the+ // order proves the pipeline is a sequence rather than a set, and the count+ // proves a converged tree is not re-optimized eight times.+ want := "test-record-2 test-record-1 test-record-1 test-record-3"+ if got := strings.Join(calls, " "); got != want {+ t.Fatalf("passes ran as %q, want %q", got, want)+ }+}++func TestOptimizeRepeatsUntilFixpoint(t *testing.T) {+ // collapse turns Any(All(b, c)) into All(b, c), which hands flatten a merge+ // it could not see on the first sweep. One pipeline sweep is therefore not+ // enough, and the assertion below spells out what one sweep would leave.+ node := All(allowLeaf("a"), Any(All(allowLeaf("b"), allowLeaf("c"))))++ oneSweep := dedupe(collapseUnary(flatten(node)))+ if children := childrenOf(t, oneSweep); len(children) != 2 {+ t.Fatalf("a single sweep gave %d children, want 2; the test no longer tests iteration\n%s",+ len(children), Explain(oneSweep))+ }++ got := Optimize(node, DefaultPipeline())+ if children := childrenOf(t, got); len(children) != 3 {+ t.Fatalf("children = %d, want 3 (a, b, c)\n%s", len(children), Explain(got))+ }+}++func TestOptimizeStopsAtTheIterationCap(t *testing.T) {+ // A pass that never converges must not hang route construction. Wrapping+ // the tree in a fresh node changes Explain every time, so only the cap can+ // end this.+ runs := 0+ registerTestPass(t, "test-grow", func(n Node) Node {+ runs+++ return AllNode{Children: []Node{n}}+ })++ got := Optimize(allowLeaf("a"), []string{"test-grow"})++ if runs != optimizeFixpointLimit {+ t.Fatalf("pass ran %d times, want the cap of %d", runs, optimizeFixpointLimit)+ }+ depth := 0+ for current := got; ; depth++ {+ node, ok := current.(AllNode)+ if !ok {+ break+ }+ current = node.Children[0]+ }+ if depth != optimizeFixpointLimit {+ t.Fatalf("result is %d levels deep, want %d", depth, optimizeFixpointLimit)+ }+}++func TestOptimizeIsIdempotent(t *testing.T) {+ node := All(+ allowLeaf("a"),+ All(allowLeaf("b"), allowLeaf("a")),+ Any(allowLeaf("c")),+ )+ once := Optimize(node, DefaultPipeline())+ twice := Optimize(once, DefaultPipeline())++ if Explain(once) != Explain(twice) {+ t.Fatalf("pipeline is not idempotent:\n--- once ---\n%s\n--- twice ---\n%s", Explain(once), Explain(twice))+ }+ // Idempotence is satisfied by an optimizer that does nothing, so pin that+ // this tree really is rewritten.+ if Explain(once) == Explain(node) {+ t.Fatalf("pipeline left a reducible tree untouched:\n%s", Explain(node))+ }+}++func TestOptimizeWithAnEmptyPipelineIsTheIdentity(t *testing.T) {+ node := All(allowLeaf("a"), All(allowLeaf("b"), allowLeaf("a")))+ if got := Optimize(node, nil); Explain(got) != Explain(node) {+ t.Fatalf("empty pipeline rewrote the tree:\n%s\nwant:\n%s", Explain(got), Explain(node))+ }++ // Returning the tree unchanged is not the same as doing nothing: without+ // the early return, an empty pipeline still renders the whole tree twice to+ // discover that no pass changed it. Nothing about the result can show that,+ // so the work itself is what gets measured.+ //+ // The threshold is loose on purpose — the claim is "no tree-sized work",+ // not an exact allocation count. Rendering this tree costs well over a+ // dozen allocations, so a mutation that drops the early return cannot slip+ // under it, and ordinary churn cannot trip it.+ if allocs := testing.AllocsPerRun(50, func() { Optimize(node, nil) }); allocs >= 3 {+ t.Fatalf("a disabled pipeline made %v allocations, want it to do no work", allocs)+ }+}++func TestOptimizePanicsOnUnknownPassName(t *testing.T) {+ // Everything else in this package fails loudly at route construction. A+ // mistyped pass name that merely skipped the pass would ship a route+ // running a pipeline nobody asked for, and nothing downstream would notice.+ defer func() {+ recovered := recover()+ if recovered == nil {+ t.Fatal("Optimize accepted an unknown pass name")+ }+ if !strings.Contains(fmt.Sprint(recovered), "dedupe-typo") {+ t.Fatalf("panic = %v, want it to name the unknown pass", recovered)+ }+ }()++ Optimize(allowLeaf("a"), []string{"flatten", "dedupe-typo"})+}++func TestOptimizeValidatesEveryNameBeforeRewriting(t *testing.T) {+ // Resolution happens up front, so a bad name late in the pipeline aborts+ // before any earlier pass has run. Not because a pass would corrupt the+ // tree — the passes here are pure, and a rewritten tree from an aborted+ // pipeline is simply discarded — but because a pass is free to have side+ // effects of its own, and route construction should not half-run a+ // pipeline it is about to reject.+ ran := false+ registerTestPass(t, "test-should-not-run", func(n Node) Node {+ ran = true+ return n+ })++ func() {+ defer func() { _ = recover() }()+ Optimize(allowLeaf("a"), []string{"test-should-not-run", "no-such-pass"})+ }()++ if ran {+ t.Fatal("a pass ran before the pipeline was validated")+ }+}++func TestDefaultPipelineNamesRegisteredPasses(t *testing.T) {+ for _, name := range DefaultPipeline() {+ if _, ok := optimizerRegistry[name]; !ok {+ t.Errorf("DefaultPipeline names %q, which is not in the registry", name)+ }+ }+}++func TestDefaultPipelineHandsOutAFreshSlice(t *testing.T) {+ // The pipeline decides which rewrites every route's plan receives. If+ // callers shared one slice, anything holding it could rewrite the default+ // for every route built afterwards, and nothing in this package checks a+ // pipeline against what someone meant to configure.+ // Joined into a string, not held as a slice. A first draft kept the+ // original as []string, which aliases the shared slice under exactly the+ // bug this test exists to find — so it compared a value with itself and+ // could not fail.+ original := strings.Join(DefaultPipeline(), ",")+ if original == "" {+ t.Fatal("DefaultPipeline is empty")+ }++ tampered := DefaultPipeline()+ for index := range tampered {+ tampered[index] = "no-such-pass"+ }++ if after := strings.Join(DefaultPipeline(), ","); after != original {+ t.Fatalf("DefaultPipeline is now %q, want %q", after, original)+ }+}++func TestStructuralPassesCommuteToTheSameFixpoint(t *testing.T) {+ // Documented rather than assumed: over flatten, collapse and dedupe the+ // order within a pipeline does not change the fixpoint, because each pass+ // only ever exposes work for the others. This is why reordering these three+ // names is not observable in the output tree — order starts to matter with+ // sink-facts, whose output is not a normal form.+ node := All(+ allowLeaf("a"),+ All(allowLeaf("b"), allowLeaf("a")),+ Any(All(allowLeaf("c"), allowLeaf("c"))),+ )++ names := []string{"flatten", "collapse", "dedupe"}+ want := Explain(Optimize(node, names))+ for _, permuted := range permutations(names) {+ if got := Explain(Optimize(node, permuted)); got != want {+ t.Fatalf("pipeline %v converged to:\n%s\nbut %v converged to:\n%s", permuted, got, names, want)+ }+ }+ if want == Explain(node) {+ t.Fatalf("the tree under test is already in normal form:\n%s", Explain(node))+ }+}++// ---------------------------------------------------------------------------+// The pipeline over generated trees+// ---------------------------------------------------------------------------++func TestDefaultPipelineRewritesGeneratedTrees(t *testing.T) {+ // TestOptimizerPreservesSemantics runs the pipeline over these same trees+ // and would be perfectly green against an optimizer that returned its+ // input. This is the floor that says the optimizer does something, and that+ // what it produces is still a compilable tree.+ //+ // The floor is a third of the range; measured, the pipeline rewrites 294 of+ // 300, so ordinary churn in the generator will not trip it but an optimizer+ // that quietly stopped rewriting will.+ const wantAtLeast = equivalenceSeeds / 3++ rewritten := 0+ for seed := int64(1); seed <= equivalenceSeeds; seed++ {+ tree := genTree(rand.New(rand.NewSource(seed)), equivalenceDepth)+ node := tree.astNode()+ optimized := Optimize(node, DefaultPipeline())++ if Explain(optimized) != Explain(node) {+ rewritten+++ }+ // Optimize stops after optimizeFixpointLimit sweeps whether or not the+ // tree has settled, and a tree that needed more comes back correct,+ // partly optimized, and silent about it. Nothing else would notice:+ // TestOptimizerPreservesSemantics is green either way, because a+ // partly-optimized plan decides exactly what a finished one decides.+ //+ // Re-running the pipeline on the result must therefore change nothing.+ // The corpus needs at most 3 sweeps today — measured directly by+ // TestDefaultPipelineConvergesWellInsideTheSweepCap below, and unchanged+ // by sink-facts, which sorts within a node and so exposes no new merges+ // for the other three passes.+ if again := Optimize(optimized, DefaultPipeline()); Explain(again) != Explain(optimized) {+ t.Fatalf("seed %d: not a fixpoint after %d sweeps; another pipeline run changed it\n--- after Optimize ---\n%s\n--- after a second Optimize ---\n%s",+ seed, optimizeFixpointLimit, Explain(optimized), Explain(again))+ }+ if empty := emptyCompositeIn(optimized); empty != nil {+ t.Fatalf("seed %d: pipeline produced a childless %T\n%s", seed, empty, Explain(optimized))+ }+ if _, err := Compile(optimized); err != nil {+ t.Fatalf("seed %d: optimized tree does not compile: %v\n%s", seed, err, Explain(optimized))+ }+ }++ t.Logf("pipeline rewrote %d of %d generated trees", rewritten, equivalenceSeeds)+ if rewritten < wantAtLeast {+ t.Errorf("pipeline rewrote %d of %d trees, want at least %d", rewritten, equivalenceSeeds, wantAtLeast)+ }+}++func TestDefaultPipelineConvergesWellInsideTheSweepCap(t *testing.T) {+ // Optimize stops after optimizeFixpointLimit sweeps whether or not the tree+ // has settled, and a tree that needed more comes back correct, partly+ // optimized, and silent about it. The fixpoint assertion above catches the+ // moment that starts happening; this reports how much room is left before it+ // does, so the headroom is a number in a log rather than an assumption.+ //+ // The count comes from a pass appended to the real pipeline, not from a+ // reimplementation of the loop here: a copy of Optimize's loop could drift+ // from it and would then measure the wrong thing.+ //+ // One pass registered once and reset per seed, rather than one per seed.+ // registerTestPass is the only way a test may touch the registry — it+ // refuses to shadow a real pass and unregisters through t.Cleanup, so a+ // panic inside Optimize cannot leak an entry into every later test in the+ // package — but three hundred registrations would queue three hundred+ // cleanups to say the same thing. A counter the loop resets says it once.+ const wantHeadroom = 2++ sweeps := 0+ registerTestPass(t, "test-sweep-count", func(n Node) Node {+ sweeps+++ return n+ })+ counted := append(DefaultPipeline(), "test-sweep-count")++ worst, worstSeed := 0, int64(0)+ for seed := int64(1); seed <= equivalenceSeeds; seed++ {+ node := genTree(rand.New(rand.NewSource(seed)), equivalenceDepth).astNode()++ sweeps = 0+ Optimize(node, counted)++ if sweeps > worst {+ worst, worstSeed = sweeps, seed+ }+ }++ t.Logf("worst case %d sweeps (seed %d) against a cap of %d", worst, worstSeed, optimizeFixpointLimit)+ if worst > optimizeFixpointLimit-wantHeadroom {+ t.Errorf("worst case %d sweeps (seed %d) leaves less than %d spare under the cap of %d; raise the cap deliberately or find out why a pass stopped converging",+ worst, worstSeed, wantHeadroom, optimizeFixpointLimit)+ }+}++func TestOptimizeLeavesTheCallersTreeAlone(t *testing.T) {+ // Every pass builds new composites and returns leaves untouched, so+ // Optimize is a pure function of its input and one AST may safely be shared+ // between routes — each getting its own plan from it, and a later+ // PolicyMiddleware seeing what its caller wrote rather than what an earlier+ // one left behind.+ //+ // That was a property of the code and of nothing else until now. It is easy+ // to lose by accident: a pass that sorted or spliced a child slice in place+ // would reach through the Node value into the caller's backing array, and+ // every other test here reads only the returned tree, so all of them would+ // stay green. sink-facts is the first pass that reorders, which is what+ // makes an in-place slip possible at all.+ //+ // Each pass alone, and then the whole pipeline. Running only the pipeline+ // is not enough, and measurably so: with sink-facts mutated to sort the+ // caller's slice in place, the pipeline case still passed. flatten runs+ // first and rebuilds every composite, so by the time sink-facts sees the+ // tree it is holding copies and can no longer reach what the caller wrote.+ // A pipeline test therefore proves the property for whichever pass happens+ // to run first and asserts nothing about the rest.+ pipelines := [][]string{}+ for _, name := range DefaultPipeline() {+ pipelines = append(pipelines, []string{name})+ }+ pipelines = append(pipelines, DefaultPipeline())++ for _, pipeline := range pipelines {+ label := strings.Join(pipeline, ",")+ for seed := int64(1); seed <= equivalenceSeeds; seed++ {+ // A fresh tree per run: a pass that did mutate its input would+ // otherwise hand the next pipeline a tree already rewritten, and the+ // failure would be reported against the wrong pass.+ node := genTree(rand.New(rand.NewSource(seed)), equivalenceDepth).astNode()++ before := Explain(node)+ Optimize(node, pipeline)+ if after := Explain(node); after != before {+ t.Fatalf("seed %d: pipeline %q mutated the tree it was given\n--- before ---\n%s\n--- after ---\n%s",+ seed, label, before, after)+ }+ }+ }+}++// ---------------------------------------------------------------------------+// Middleware wiring+// ---------------------------------------------------------------------------++func TestWithPipelineCopiesItsNames(t *testing.T) {+ // Spreading a slice into a variadic parameter shares the backing array, so+ // without a copy the config would hold a live view of the caller's slice.+ names := []string{"flatten", "collapse"}+ config := middlewareConfig{}+ WithPipeline(names...)(&config)+ names[0] = "no-such-pass"++ if got := strings.Join(config.pipeline, ","); got != "flatten,collapse" {+ t.Fatalf("stored pipeline = %q, want %q", got, "flatten,collapse")+ }+}++func TestPolicyMiddlewareOptimizesByDefault(t *testing.T) {+ // Compile loads each surviving leaf's source once, so the load count is a+ // direct readout of how many leaves the plan kept.+ loads := 0+ node := All(countingAllow("a", &loads), countingAllow("a", &loads))++ if status := runPolicyStatus(t, node); status != http.StatusNoContent {+ t.Fatalf("status = %d, want %d", status, http.StatusNoContent)+ }+ if loads != 1 {+ t.Fatalf("compiled %d leaves, want 1: the default pipeline did not dedupe", loads)+ }+}++func TestPolicyMiddlewareWithPipelineDisablesOptimization(t *testing.T) {+ loads := 0+ node := All(countingAllow("a", &loads), countingAllow("a", &loads))++ if status := runPolicyStatus(t, node, WithPipeline()); status != http.StatusNoContent {+ t.Fatalf("status = %d, want %d", status, http.StatusNoContent)+ }+ if loads != 2 {+ t.Fatalf("compiled %d leaves, want 2: WithPipeline() must disable optimization", loads)+ }+}++func TestPolicyMiddlewareRunsTheNamedPipeline(t *testing.T) {+ loads := 0+ node := All(countingAllow("a", &loads), countingAllow("a", &loads))++ if status := runPolicyStatus(t, node, WithPipeline("flatten")); status != http.StatusNoContent {+ t.Fatalf("status = %d, want %d", status, http.StatusNoContent)+ }+ if loads != 2 {+ t.Fatalf("compiled %d leaves, want 2: a flatten-only pipeline must not dedupe", loads)+ }+}++func TestPolicyMiddlewarePanicsOnUnknownPipelineName(t *testing.T) {+ defer func() {+ recovered := recover()+ if recovered == nil {+ t.Fatal("PolicyMiddleware accepted an unknown pass name")+ }+ if !strings.Contains(fmt.Sprint(recovered), "no-such-pass") {+ t.Fatalf("panic = %v, want it to name the unknown pass", recovered)+ }+ }()++ PolicyMiddleware(allowLeaf("a"), WithPipeline("no-such-pass"))+}diff --git a/libs/fleet/backend/auth/policy_ownership_test.go b/libs/fleet/backend/auth/policy_ownership_test.gonew file mode 100644index 0000000000..7da145c963--- /dev/null+++ b/libs/fleet/backend/auth/policy_ownership_test.go@@ -0,0 +1,475 @@+package auth++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "sync/atomic"+ "testing"++ "github.com/open-policy-agent/opa/ast"+ "github.com/open-policy-agent/opa/dependencies"+ "github.com/open-policy-agent/opa/rego"+)++// The namespace-ownership conjunct is the first policy in this repo that needs+// something no token carries, so it is the first one whose cost is not a+// constant. What it costs is the number of times its FactProvider is asked, and+// that number is what these tests measure — not because a slow authorization+// stage is untidy, but because /api/svc serves every noVNC asset, and a probe+// per asset request is an apiserver incident.+//+// Everything here is measured against the production trees from+// policy_routes.go, through Compile and the real fold. A count taken against a+// tree written out in this file would only say what this file does.++// countingFacts records how many times it was asked, and answers from the+// namespace so a test can pick allow, deny, or unavailable by choosing one.+type countingFacts struct {+ loads atomic.Int64+ unreachable string+ allowed string+}++func (facts *countingFacts) CacheKey() string { return NamespaceRBACFactProvider }++func (facts *countingFacts) LoadFacts(_ context.Context, request *http.Request) (FactSet, error) {+ facts.loads.Add(1)+ namespace := OwnedNamespace(request.Context())+ if facts.unreachable != "" && namespace == facts.unreachable {+ return nil, &FactUnavailableError{Namespace: NamespaceRBACFactNamespace, Err: errors.New("apiserver unavailable")}+ }+ return FactSet{"allowed": namespace == facts.allowed}, nil+}++// installCountingFacts registers a counting provider for the duration of a test+// and restores whatever was there before, so tests in this package that share+// the registry do not depend on running order.+func installCountingFacts(t *testing.T, allowed string) *countingFacts {+ t.Helper()+ LoadOpa()+ facts := &countingFacts{allowed: allowed}+ factProviderRegistry.RLock()+ previous, existed := factProviderRegistry.providers[NamespaceRBACFactProvider]+ factProviderRegistry.RUnlock()+ RegisterFactProvider(NamespaceRBACFactProvider, facts)+ t.Cleanup(func() {+ if existed {+ RegisterFactProvider(NamespaceRBACFactProvider, previous)+ return+ }+ factProviderRegistry.Lock()+ delete(factProviderRegistry.providers, NamespaceRBACFactProvider)+ factProviderRegistry.Unlock()+ })+ return facts+}++func svcCase(namespace string) routeCase {+ return routeCase{+ name: namespace,+ params: map[string]string{"namespace": namespace, "service": "svc-a", "path": "v1/status"},+ path: "/api/svc/" + namespace + "/svc-a/v1/status",+ }+}++const svcPathRoute = "/api/svc/{namespace}/{service}/{path...}"++// evalSurface runs a route's production plan over one request, exactly as+// PolicyMiddleware would.+func evalSurface(t *testing.T, route string, request *http.Request) verdict {+ t.Helper()+ tree, ok := RouteTree(route)+ if !ok {+ t.Fatalf("route %q is bound to no surface", route)+ }+ compiled, err := Compile(Optimize(tree, DefaultPipeline()))+ if err != nil {+ t.Fatalf("compile %q: %v", route, err)+ }+ return compiled.eval(request.Context(), newRequestPolicyInput(request, compiled.bodyBudget))+}++// TestOwnershipProbesOncePerRequest pins the shape of the cost: the fact is+// loaded once for the request that needs it, not once per leaf that mentions it+// and not once per evaluation of the tree.+func TestOwnershipProbesOncePerRequest(t *testing.T) {+ facts := installCountingFacts(t, "ns-a")+ user := &User{ID: "u-1", AZP: "cyclops-cs-spa", PrincipalType: PrincipalTypeUser}++ result := evalSurface(t, svcPathRoute,+ characterizationRequest(svcPathRoute, svcCase("ns-a"), http.MethodGet, user))+ if result.truth != truthTrue {+ t.Fatalf("verdict = %v, want allow", verdictName(result.truth))+ }+ if got := facts.loads.Load(); got != 1 {+ t.Fatalf("fact loads = %d, want exactly 1 per request", got)+ }+}++// The per-request cache is what makes "once per request" hold when more than+// one leaf reads the same provider. The production ownership tree has a single+// fact leaf, so the property is pinned on a tree that has two — otherwise+// nothing would notice the cache disappearing until a second consumer arrived.+func TestOwnershipFactCacheIsPerRequestNotPerLeaf(t *testing.T) {+ facts := installCountingFacts(t, "ns-a")+ leaf := func() Node {+ return Policy(+ Modules(Registered("authz"), Registered("authz-ownership")),+ Query("data.authz_ownership.rbac_allow"),+ WithFacts(NamespaceRBACFactNamespace, RegisteredFacts(NamespaceRBACFactProvider)),+ )+ }+ compiled, err := Compile(All(leaf(), leaf(), leaf()))+ if err != nil {+ t.Fatalf("compile: %v", err)+ }+ request := characterizationRequest(svcPathRoute, svcCase("ns-a"), http.MethodGet,+ &User{ID: "u-1", AZP: "cyclops-cs-spa", PrincipalType: PrincipalTypeUser})+ if result := compiled.eval(request.Context(), newRequestPolicyInput(request, compiled.bodyBudget)); result.truth != truthTrue {+ t.Fatalf("verdict = %v, want allow", verdictName(result.truth))+ }+ if got := facts.loads.Load(); got != 1 {+ t.Fatalf("fact loads = %d across three leaves sharing a cache key, want 1", got)+ }+}++// TestOwnershipCheapDenyProbesNothing is the effectiveness the planner was+// built for, on a production route. Each of these principals is denied by a+// leaf that costs nothing — the base policy, the surface's DNS-label check, or+// the ownership conjunct's own probe_eligible — and every one of them must cost+// zero probes, because the lazy fold never reaches the leaf carrying the+// provider.+//+// The provider is set to allow the namespace being asked about, so a probe that+// did happen would be visible as a verdict change as well as a count.+func TestOwnershipCheapDenyProbesNothing(t *testing.T) {+ for _, testCase := range []struct {+ name string+ user *User+ routeCase routeCase+ deniedBy string+ }{+ {+ name: "empty subject",+ user: &User{ID: "", AZP: "cyclops-cs-spa", PrincipalType: PrincipalTypeUser},+ routeCase: svcCase("ns-b"),+ deniedBy: "authz_base",+ },+ {+ name: "invalid namespace label",+ user: &User{ID: "u-1", AZP: "cyclops-cs-spa", PrincipalType: PrincipalTypeUser},+ routeCase: svcCase("Not_A_Label"),+ deniedBy: "authz_svc",+ },+ {+ name: "per-key token outside its namespace",+ user: &User{ID: "svc-1", AZP: "key-ns-z", Namespace: "ns-z", PrincipalType: PrincipalTypeUser},+ // ns-b is neither the claim nor a namespace the provider allows.+ routeCase: svcCase("ns-b"),+ deniedBy: "authz_svc",+ },+ {+ name: "GitHub token outside its grant",+ user: &User{+ ID: "owner-1",+ AZP: "github-oidc",+ PrincipalType: PrincipalTypeGitHubOIDC,+ AllowedNamespaces: []string{"ns-a"},+ },+ routeCase: svcCase("ns-b"),+ deniedBy: "authz_ownership.probe_eligible",+ },+ } {+ t.Run(testCase.name, func(t *testing.T) {+ facts := installCountingFacts(t, testCase.routeCase.params["namespace"])+ result := evalSurface(t, svcPathRoute,+ characterizationRequest(svcPathRoute, testCase.routeCase, http.MethodGet, testCase.user))+ if result.truth != truthFalse {+ t.Fatalf("verdict = %v, want deny (denied by %s)", verdictName(result.truth), testCase.deniedBy)+ }+ if got := facts.loads.Load(); got != 0 {+ t.Fatalf("fact loads = %d, want 0: %s decides this request before the loader is reached",+ got, testCase.deniedBy)+ }+ })+ }+}++// And the same for a claim that allows: an Any that stops at its first true+// never reaches the branch holding the provider.+func TestOwnershipClaimAllowProbesNothing(t *testing.T) {+ for _, testCase := range []struct {+ name string+ user *User+ }{+ {+ name: "per-key token in its namespace",+ user: &User{ID: "svc-1", AZP: "key-ns-a", Namespace: "ns-a", PrincipalType: PrincipalTypeUser},+ },+ {+ name: "GitHub token inside its grant",+ user: &User{+ ID: "owner-1",+ AZP: "github-oidc",+ PrincipalType: PrincipalTypeGitHubOIDC,+ AllowedNamespaces: []string{"ns-a"},+ },+ },+ } {+ t.Run(testCase.name, func(t *testing.T) {+ // Deliberately answers "no" for ns-a: if a probe happened at all,+ // the verdict would flip as well as the count.+ facts := installCountingFacts(t, "nothing")+ result := evalSurface(t, svcPathRoute,+ characterizationRequest(svcPathRoute, svcCase("ns-a"), http.MethodGet, testCase.user))+ if result.truth != truthTrue {+ t.Fatalf("verdict = %v, want allow from the claim alone", verdictName(result.truth))+ }+ if got := facts.loads.Load(); got != 0 {+ t.Fatalf("fact loads = %d, want 0: the claim decides before the loader is reached", got)+ }+ })+ }+}++// TestSinkFactLoadersRemovesAProbeFromTheProductionTree is the measurement with+// its baseline. Production declares the cheap children first, so the pass moves+// nothing there and its effect cannot be seen by comparing the plan to itself.+// Reversing every composite's children models the same tree written the other+// way round: unoptimized it costs a probe, and the pass takes it back to zero.+// Same verdict throughout — that is the lattice's promise, and what makes the+// reordering legal in the first place.+func TestSinkFactLoadersRemovesAProbeFromTheProductionTree(t *testing.T) {+ tree, ok := RouteTree(svcPathRoute)+ if !ok {+ t.Fatalf("route %q is bound to no surface", svcPathRoute)+ }+ user := &User{+ ID: "owner-1",+ AZP: "github-oidc",+ PrincipalType: PrincipalTypeGitHubOIDC,+ AllowedNamespaces: []string{"ns-a"},+ }++ run := func(t *testing.T, plan Node) (truth, int64) {+ t.Helper()+ facts := installCountingFacts(t, "ns-b")+ compiled, err := Compile(plan)+ if err != nil {+ t.Fatalf("compile: %v", err)+ }+ request := characterizationRequest(svcPathRoute, svcCase("ns-b"), http.MethodGet, user)+ result := compiled.eval(request.Context(), newRequestPolicyInput(request, compiled.bodyBudget))+ return result.truth, facts.loads.Load()+ }++ reversed := reverseChildren(tree)++ baselineTruth, baselineLoads := run(t, reversed)+ if baselineLoads != 1 {+ t.Fatalf("unoptimized reversed plan loaded facts %d times, want 1 — the baseline this pass is measured against", baselineLoads)+ }++ sunkTruth, sunkLoads := run(t, Optimize(reversed, DefaultPipeline()))+ if sunkLoads != 0 {+ t.Fatalf("optimized plan loaded facts %d times, want 0", sunkLoads)+ }+ if baselineTruth != sunkTruth {+ t.Fatalf("optimizing changed the verdict: %v -> %v", verdictName(baselineTruth), verdictName(sunkTruth))+ }+}++// reverseChildren rewrites a tree with every composite's children in reverse+// order. It is a way to write "the same policy, declared the other way round"+// without a second copy of the policy.+func reverseChildren(n Node) Node {+ reverse := func(children []Node) []Node {+ out := make([]Node, 0, len(children))+ for index := len(children) - 1; index >= 0; index-- {+ out = append(out, reverseChildren(children[index]))+ }+ return out+ }+ switch node := n.(type) {+ case AllNode:+ return AllNode{Children: reverse(node.Children)}+ case AnyNode:+ return AnyNode{Children: reverse(node.Children)}+ default:+ return n+ }+}++// TestUnregisteredFactProviderFailsClosedAsAnInternalError pins the other half+// of the failure-mode split. An unreachable apiserver is a FactUnavailableError+// and a 502; a provider nobody registered is a plain error and a 500, because+// nothing was unreachable — the process was assembled wrong, and a retry will+// not help.+func TestUnregisteredFactProviderFailsClosedAsAnInternalError(t *testing.T) {+ LoadOpa()+ factProviderRegistry.RLock()+ previous, existed := factProviderRegistry.providers[NamespaceRBACFactProvider]+ factProviderRegistry.RUnlock()+ factProviderRegistry.Lock()+ delete(factProviderRegistry.providers, NamespaceRBACFactProvider)+ factProviderRegistry.Unlock()+ t.Cleanup(func() {+ if existed {+ RegisterFactProvider(NamespaceRBACFactProvider, previous)+ }+ })++ tree, _ := RouteTree(svcPathRoute)+ middleware := PolicyMiddleware(Optimize(tree, DefaultPipeline()))+ handler := middleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ t.Error("an undecidable policy reached the handler")+ w.WriteHeader(http.StatusOK)+ }))++ response := httptest.NewRecorder()+ handler.ServeHTTP(response, characterizationRequest(svcPathRoute, svcCase("ns-a"), http.MethodGet,+ &User{ID: "u-1", AZP: "cyclops-cs-spa", PrincipalType: PrincipalTypeUser}))++ if response.Code != http.StatusInternalServerError {+ t.Fatalf("status = %d, want 500; body = %s", response.Code, response.Body.String())+ }+}++// TestOwnedNamespaceMatchesRego holds the two halves of target_namespace+// together. The Go half is what the provider probes and the Rego half is what+// the claims are compared against; if they ever disagreed, a token could be+// checked against one namespace and a probe run for another, which is a+// confused-deputy bug rather than a tidiness one.+func TestOwnedNamespaceMatchesRego(t *testing.T) {+ query := prepareQuery(t, "data.authz_ownership.target_namespace", map[string]string{+ "authz.rego": authzPolicy,+ "authz_ownership.rego": authzOwnershipPolicy,+ })++ for _, testCase := range []struct {+ name string+ params map[string]string+ want 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"},+ {name: "empty namespace stays empty", params: map[string]string{"namespace": "", "service": "svc-a"}, want: ""},+ {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: ""},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ ctx := context.WithValue(context.Background(), paramsKey, testCase.params)+ 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}))+ if err != nil {+ t.Fatalf("eval target_namespace: %v", err)+ }+ // An undefined rule and "" are the same answer for every rule that+ // reads it: all of them require a non-empty namespace.+ got := ""+ if len(results) > 0 && len(results[0].Expressions) > 0 {+ got, _ = results[0].Expressions[0].Value.(string)+ }+ if got != testCase.want {+ t.Fatalf("target_namespace = %q, want %q (OwnedNamespace said %q)",+ got, testCase.want, OwnedNamespace(ctx))+ }+ })+ }+}++// TestLeavesReadingFactsDeclareAProvider is the invariant+// TestRouteModulesNeverReadInputFacts stated while no module read facts, in the+// form that survives one of them starting to. It is asked per leaf rather than+// per module, and transitively rather than syntactically, because+// authz_ownership.rego is compiled into three leaves and only one of them+// queries the rule that reaches input.facts — a module-level answer would+// condemn the other two, and a syntactic one would miss a fact read behind a+// helper rule.+//+// A leaf whose query depends on input.facts and declares no provider is handed+// {}: an undefined lookup that denies, silently, on every request.+func TestLeavesReadingFactsDeclareAProvider(t *testing.T) {+ LoadOpa()+ factsRef := ast.MustParseRef("input.facts")++ for _, route := range AuthenticatedRoutes() {+ tree, ok := RouteTree(route)+ if !ok {+ t.Fatalf("route %q is bound to no surface", route)+ }+ for _, leaf := range allLeaves(tree) {+ modules, err := leaf.Source.modules()+ if err != nil {+ t.Fatalf("load modules for %q: %v", leaf.Query, err)+ }+ parsed := map[string]*ast.Module{}+ for _, module := range modules {+ module, err := ast.ParseModule(module.name, module.source)+ if err != nil {+ t.Fatalf("parse %s: %v", module.Package.Location.File, err)+ }+ parsed[module.Package.Path.String()] = module+ }+ compiler := ast.NewCompiler()+ if compiler.Compile(parsed); compiler.Failed() {+ t.Fatalf("compile modules for %q: %v", leaf.Query, compiler.Errors)+ }++ query, err := ast.ParseBody(leaf.Query)+ if err != nil {+ t.Fatalf("parse query %q: %v", leaf.Query, err)+ }+ refs, err := dependencies.Base(compiler, query)+ if err != nil {+ t.Fatalf("dependencies of %q: %v", leaf.Query, err)+ }+ readsFacts := false+ for _, ref := range refs {+ if ref.HasPrefix(factsRef) {+ readsFacts = true+ }+ }+ if readsFacts && len(leaf.Facts) == 0 {+ t.Errorf(`route %q runs a leaf querying %q, which depends on input.facts but+declares no fact provider. That leaf is evaluated against an empty facts+document, so the lookup is undefined and the leaf denies every request.`,+ route, leaf.Query)+ }+ if !readsFacts && len(leaf.Facts) > 0 {+ t.Errorf(`route %q runs a leaf querying %q, which declares a fact provider+its query never reads. The load is paid for on every request that reaches the+leaf and its result is discarded.`, route, leaf.Query)+ }+ }+ }+}++// allLeaves flattens a tree into its leaves whatever the combinators are —+// unlike conjunctiveLeaves in policy_test.go, which refuses a disjunction+// because it is folding one.+func allLeaves(n Node) []Leaf {+ switch node := n.(type) {+ case Leaf:+ return []Leaf{node}+ case AllNode:+ var leaves []Leaf+ for _, child := range node.Children {+ leaves = append(leaves, allLeaves(child)...)+ }+ return leaves+ case AnyNode:+ var leaves []Leaf+ for _, child := range node.Children {+ leaves = append(leaves, allLeaves(child)...)+ }+ return leaves+ }+ return nil+}diff --git a/libs/fleet/backend/auth/policy_plan.go b/libs/fleet/backend/auth/policy_plan.gonew file mode 100644index 0000000000..dab6053e5c--- /dev/null+++ b/libs/fleet/backend/auth/policy_plan.go@@ -0,0 +1,242 @@+package auth++import (+ "context"+ "errors"+ "fmt"+ "log/slog"++ "github.com/open-policy-agent/opa/rego"+)++// truth is a three-valued logic value ordered truthFalse < truthError <+// truthTrue. All is min over this order and Any is max, so both are+// commutative, associative and idempotent. That is precisely what makes+// optimizer reordering sound; see the design doc.+type truth uint8++// The three values a policy can evaluate to. truthError means the policy could+// not be decided, not that it denied: it sits between the two definite answers+// so that a definite answer from a sibling outranks it in either direction.+const (+ truthFalse truth = iota+ truthError+ truthTrue+)++// Compile-time assertions on the lattice. The order truthFalse < truthError <+// truthTrue is not read by any code today — the combinators below encode+// min/max through their annihilator and identity. These fail to compile if the+// const block is reordered, so the documented lattice cannot silently drift+// from the executable one, and they become load-bearing the moment a pass+// compares truth values directly.+//+// The subtraction is what overflows; the uint conversion is belt-and-braces so+// the assertions keep working if truth ever becomes a signed type, where a+// negative difference would otherwise be legal.+const (+ _ = uint(truthError - truthFalse)+ _ = uint(truthTrue - truthError)++ // truthFalse must be the zero value. A verdict{} left unfilled by some+ // future code path has to read as a deny with no error, so that forgetting+ // to set a truth fails closed rather than open.+ _ = uint(0 - truthFalse)+)++// verdict is the result of evaluating a policy against one request.+type verdict struct {+ truth truth+ err error // non-nil if and only if truth == truthError+}++// A combinator is a fold over truth: All is min, Any is max. annihilator must+// be truthFalse or truthTrue, never truthError — fold's switch matches the+// annihilator before the error arm, so an error annihilator would shadow it+// and errors would stop being remembered. The two values below are the only+// combinators that exist, which is what keeps that precondition true.+type combinator struct{ annihilator, identity truth }++var (+ conjunction = combinator{annihilator: truthFalse, identity: truthTrue} // min+ disjunction = combinator{annihilator: truthTrue, identity: truthFalse} // max+)++type compiledNode interface {+ eval(context.Context, *requestPolicyInput) verdict+ // bodyBudget is the largest raw-body limit in this subtree. Reading the+ // request once against the root's budget makes each leaf's own limit check+ // a pure function of (len(body), leaf.MaxBody), independent of evaluation+ // order. Answering it here rather than in a switch over Node makes the+ // question unanswerable-by-omission: a node kind that does not implement+ // it does not satisfy compiledNode and does not compile.+ bodyBudget() int64+}++// CompiledPolicy is an executable plan produced from an optimized AST.+type CompiledPolicy struct {+ root compiledNode+ bodyBudget int64+}++// eval runs the plan against one request. It is the plan's whole execution+// surface; nothing outside this file should reach for root.+func (policy *CompiledPolicy) eval(ctx context.Context, input *requestPolicyInput) verdict {+ return policy.root.eval(ctx, input)+}++// Compile turns a policy AST into an executable plan. It performs the source+// I/O and the Rego compilation that Policy deliberately defers.+func Compile(n Node) (*CompiledPolicy, error) {+ root, err := compileNode(n)+ if err != nil {+ return nil, err+ }+ return &CompiledPolicy{root: root, bodyBudget: root.bodyBudget()}, nil+}++func maxChildBudget(children []compiledNode) int64 {+ var budget int64+ for _, child := range children {+ if candidate := child.bodyBudget(); candidate > budget {+ budget = candidate+ }+ }+ return budget+}++func compileNode(n Node) (compiledNode, error) {+ switch node := n.(type) {+ case Leaf:+ return compileLeaf(node)+ case AllNode:+ children, err := compileChildren(node, node.Children)+ if err != nil {+ return nil, err+ }+ return &compiledAll{children: children}, nil+ case AnyNode:+ children, err := compileChildren(node, node.Children)+ if err != nil {+ return nil, err+ }+ return &compiledAny{children: children}, nil+ default:+ return nil, fmt.Errorf("cannot compile unknown policy node %T", n)+ }+}++func compileChildren(parent Node, nodes []Node) ([]compiledNode, error) {+ // A childless composite folds to its identity, which for a conjunction is+ // an unconditional allow. All() and Any() reject zero arguments, but+ // Children is an exported field and rewrite passes build these values+ // directly, so a pass that filtered a conjunction down to nothing must+ // fail here rather than authorize every request on the route.+ if len(nodes) == 0 {+ return nil, fmt.Errorf("policy node %T has no children", parent)+ }+ compiled := make([]compiledNode, 0, len(nodes))+ for _, child := range nodes {+ node, err := compileNode(child)+ if err != nil {+ return nil, err+ }+ compiled = append(compiled, node)+ }+ return compiled, nil+}++func compileLeaf(leaf Leaf) (compiledNode, error) {+ // Policy rejects a nil source, but it is not the only way to build a+ // Leaf: rewrite passes construct them directly, and one that rebuilt a+ // Leaf from parts and dropped Source must get an error, not a panic.+ if leaf.Source == nil {+ return nil, fmt.Errorf("policy %q has no source", leaf.Query)+ }+ modules, err := leaf.Source.modules()+ if err != nil {+ return nil, fmt.Errorf("load modules for policy %q: %w", leaf.Query, err)+ }+ options := []func(*rego.Rego){rego.Query(leaf.Query)}+ for _, module := range modules {+ options = append(options, rego.Module(module.name, module.source))+ }+ prepared, err := rego.New(options...).PrepareForEval(context.Background())+ if err != nil {+ return nil, fmt.Errorf("prepare OPA policy %q: %w", leaf.Query, err)+ }+ return &compiledLeaf{+ query: prepared,+ config: policyConfig{+ query: leaf.Query,+ factProviders: leaf.Facts,+ maxBodyBytes: leaf.MaxBody,+ },+ }, nil+}++type compiledLeaf struct {+ query rego.PreparedEvalQuery+ config policyConfig+}++func (leaf *compiledLeaf) eval(ctx context.Context, input *requestPolicyInput) verdict {+ document, err := input.forPolicy(ctx, leaf.config)+ if err != nil {+ return verdict{truth: truthError, err: err}+ }+ result, err := leaf.query.Eval(ctx, rego.EvalInput(document))+ if err != nil {+ return verdict{truth: truthError, err: err}+ }+ if result.Allowed() {+ return verdict{truth: truthTrue}+ }+ return verdict{truth: truthFalse}+}++func (leaf *compiledLeaf) bodyBudget() int64 { return leaf.config.maxBodyBytes }++type compiledAll struct{ children []compiledNode }++func (node *compiledAll) eval(ctx context.Context, input *requestPolicyInput) verdict {+ return fold(ctx, input, node.children, conjunction)+}++func (node *compiledAll) bodyBudget() int64 { return maxChildBudget(node.children) }++type compiledAny struct{ children []compiledNode }++func (node *compiledAny) eval(ctx context.Context, input *requestPolicyInput) verdict {+ return fold(ctx, input, node.children, disjunction)+}++func (node *compiledAny) bodyBudget() int64 { return maxChildBudget(node.children) }++// fold evaluates children left to right, short-circuiting on the annihilating+// value only. Errors are remembered rather than aborting, so a later+// annihilator can still win — that is what makes the fold order-independent.+func fold(ctx context.Context, input *requestPolicyInput, children []compiledNode, over combinator) verdict {+ var errs []error+ for _, child := range children {+ result := child.eval(ctx, input)+ switch result.truth {+ case over.annihilator:+ if len(errs) > 0 {+ // The lattice drops these on purpose: an annihilator decides+ // the fold whatever its siblings did. Correct, but it is the+ // only trace that a fact provider is failing, and the request+ // still gets a clean 200 or 403, so record it before it goes.+ slog.Warn("opa: policy error discarded; a sibling decided the verdict",+ "allowed", over.annihilator == truthTrue, "err", errors.Join(errs...))+ }+ return verdict{truth: over.annihilator}+ case truthError:+ errs = append(errs, result.err)+ }+ }+ if len(errs) > 0 {+ return verdict{truth: truthError, err: errors.Join(errs...)}+ }+ return verdict{truth: over.identity}+}diff --git a/libs/fleet/backend/auth/policy_routes.go b/libs/fleet/backend/auth/policy_routes.gonew file mode 100644index 0000000000..5ecc843f91--- /dev/null+++ b/libs/fleet/backend/auth/policy_routes.go@@ -0,0 +1,372 @@+package auth++import (+ "fmt"+ "slices"+ "sync"+)++// The policy trees production routes are built from.+//+// They live here rather than in main.go so that exactly one definition exists:+// main.go's route constructors call these, and policy_golden_test.go's snapshot+// table names these same functions. A tree defined in main.go and copied into+// the test would let production authorization be reordered with the golden+// still green — the copy, not the route, is what such a snapshot pins.+//+// Registered() resolves through the module registry that LoadOpa populates, so+// these constructors stay pure data: no I/O, no compilation, safe to call+// before LoadOpa. A name that was never registered surfaces at Compile time,+// which for a route means PolicyMiddleware panicking during construction.++// Every route policy is All(BasePolicy(), <its surface>). That is not a+// convention imposed on the Rego — it is the Rego's own structure, made visible.+// All 30 route-gated allow rules of the former monolith shared exactly one+// condition, a non-empty subject, and each was gated to a route belonging to one+// surface. So for a request on route R,+//+// All(base, surface_R) ≡ the old authz.allow+//+// with base the shared condition and surface_R the disjunction of R's rules+// minus it. Rules of another surface could not have fired on R in the first+// place, because their route gates would not match; the surfaces' route sets are+// pairwise disjoint, the only prefix rule (billing) overlapping no other+// surface's literals. auth/testdata/route-authorization-table.txt is the+// executable form of that argument: it was recorded against the monolith, and+// the split had to leave every cell of it unmoved.++// BasePolicy is the check every authenticated route runs whatever its surface:+// a non-empty subject. Denies are a 403 and an undecidable evaluation is a 500,+// both from PolicyMiddleware.+func BasePolicy() Node {+ return Policy(+ Registered("authz-base"),+ Query("data.authz_base.allow"),+ )+}++// surfaceLeaf builds the leaf for one surface module. Every surface names+// authz.rego alongside its own module, because every surface module imports the+// principal vocabulary defined there.+func surfaceLeaf(module, query string) Node {+ return Policy(+ Modules(+ Registered("authz"),+ Registered(module),+ ),+ Query(query),+ )+}++// KeysRoutePolicy guards /api/keys and /api/keys/{id}.+func KeysRoutePolicy() Node {+ return All(BasePolicy(), surfaceLeaf("authz-keys", "data.authz_keys.allow"))+}++// ConfigRoutePolicy guards /api/config.+func ConfigRoutePolicy() Node {+ return All(BasePolicy(), surfaceLeaf("authz-config", "data.authz_config.allow"))+}++// BillingRoutePolicy guards the Stripe-hosted billing browser routes. Its module+// matches a prefix rather than three literals, so a billing route added to+// main.go and bound here is covered without a policy change.+func BillingRoutePolicy() Node {+ return All(BasePolicy(), surfaceLeaf("authz-billing", "data.authz_billing.allow"))+}++// NamespaceOwnershipPolicy is the tenancy boundary for routes that name a+// namespace in their path. It is a conjunct rather than a surface, because+// three surfaces carry it and one of them (namespaces) holds routes on both+// sides of it — authz_ownership.rego decides which.+//+// The shape is the point:+//+// Any(claim_allow, All(probe_eligible, rbac_allow))+//+// Only rbac_allow declares a fact provider, and it is the only leaf that costs+// a network round trip. Both combinators are lazy and both are guarded by a+// cheap sibling, so the probe runs exactly when neither the token's claims nor+// the principal's family has already answered:+//+// - Any stops at the first true, so a GitHub or per-key principal whose claim+// matches never reaches the second child at all.+// - All stops at the first false, so a principal a K8s probe cannot speak for+// — a GitHub token, a per-key service account — denies before the loader.+//+// That laziness is what sinkFactLoaders exists to guarantee: the declaration+// order below already puts the cheap child first, and the pass is what keeps it+// there under any future rewrite. policy_ownership_test.go measures both claims+// as probe counts rather than restating them.+func NamespaceOwnershipPolicy() Node {+ leaf := func(query string, options ...PolicyOption) Node {+ return Policy(+ Modules(+ Registered("authz"),+ Registered("authz-ownership"),+ ),+ append([]PolicyOption{Query(query)}, options...)...,+ )+ }+ return Any(+ leaf("data.authz_ownership.claim_allow"),+ All(+ leaf("data.authz_ownership.probe_eligible"),+ leaf(+ "data.authz_ownership.rbac_allow",+ WithFacts(NamespaceRBACFactNamespace, RegisteredFacts(NamespaceRBACFactProvider)),+ ),+ ),+ )+}++// NamespacesRoutePolicy guards /api/namespaces and /api/namespaces/{name}. The+// ownership conjunct only binds on GET /api/namespaces/{name}; the list, create+// and delete routes pass it unconditionally, which is where the Go handler left+// them.+func NamespacesRoutePolicy() Node {+ return All(+ BasePolicy(),+ surfaceLeaf("authz-namespaces", "data.authz_namespaces.allow"),+ NamespaceOwnershipPolicy(),+ )+}++// GitHubTrustRoutePolicy guards the GitHub trust-policy routes.+func GitHubTrustRoutePolicy() Node {+ return All(BasePolicy(), surfaceLeaf("authz-github-trust", "data.authz_github_trust.allow"))+}++// UserKeysRoutePolicy guards /api/user-keys and /api/user-keys/{id}.+func UserKeysRoutePolicy() Node {+ return All(BasePolicy(), surfaceLeaf("authz-user-keys", "data.authz_user_keys.allow"))+}++// OrchRoutePolicy guards the per-namespace orchestrator catalog proxy. This+// proxy dials Service DNS directly, so Capsule cannot scope it — the ownership+// conjunct is the whole tenancy boundary.+func OrchRoutePolicy() Node {+ return All(+ BasePolicy(),+ surfaceLeaf("authz-orch", "data.authz_orch.allow"),+ NamespaceOwnershipPolicy(),+ )+}++// SvcRoutePolicy guards the generic service proxy, both with and without a+// trailing path. Same direct-dial tenancy boundary as OrchRoutePolicy.+func SvcRoutePolicy() Node {+ return All(+ BasePolicy(),+ surfaceLeaf("authz-svc", "data.authz_svc.allow"),+ NamespaceOwnershipPolicy(),+ )+}++// StateQueryRoutePolicy guards /api/state/query.+func StateQueryRoutePolicy() Node {+ return All(BasePolicy(), surfaceLeaf("authz-state-query", "data.authz_state_query.allow"))+}++// K8sRoutePolicy guards /api/k8s/{path...}. It is the same base + surface shape+// as every other route, with one extra conjunct: admission control over the+// request body.+//+// All three must pass. The admission leaf reads the raw body (bounded at 1 MiB)+// to inspect the object being created or patched, which is why it names+// pool_admission.rego alongside authz.rego — pool_admission imports+// data.authz.is_admin. It stays a separate leaf rather than rules inside+// authz_k8s.rego because it is the only thing on this surface that needs the+// body, and folding it in would put every k8s request's verdict behind a body+// read.+func K8sRoutePolicy() Node {+ return All(+ BasePolicy(),+ surfaceLeaf("authz-k8s", "data.authz_k8s.allow"),+ Policy(+ Modules(+ Registered("authz"),+ Registered("pool-admission"),+ ),+ Query("data.pool_admission.allow"),+ WithRawBody(1<<20),+ ),+ )+}++// ── Route → surface binding ─────────────────────────────────────────────────+//+// A route's authorization is chosen here, by name, rather than at its+// registration site. Before this table existed, main.go decided which policy a+// route ran and authz.rego decided which routes it reasoned about, and nothing+// held the two together — #6702 deleted the /api/gateway route and its+// authorization rules outlived it, because there was no place where the two+// facts met. The table is that place: it is what main.go reads, what+// policy_route_correspondence_test.go checks against the registered routes and+// against the Rego, and what the characterization table in+// policy_characterization_test.go enumerates.+//+// A route missing from this table cannot serve traffic — RouteMiddleware panics+// during route construction rather than falling back to a default, because the+// only safe default for "no policy named" is refusing to start.++// surfacePolicy is one authorization surface: the tree its routes run and the+// middleware options that tree is installed with. Options live here rather than+// at the call site so that two routes on one surface cannot disagree about, say,+// the denial message.+type surfacePolicy struct {+ tree func() Node+ options []MiddlewareOption+}++// surfacePolicies is every surface, by name. A surface owning no route fails+// TestEveryPolicySurfaceOwnsARoute; a route naming no surface cannot start.+var surfacePolicies = map[string]surfacePolicy{+ "keys": {tree: KeysRoutePolicy},+ "config": {tree: ConfigRoutePolicy},+ "billing": {tree: BillingRoutePolicy},+ "namespaces": {tree: NamespacesRoutePolicy},+ "github-trust": {tree: GitHubTrustRoutePolicy},+ "user-keys": {tree: UserKeysRoutePolicy},+ "orch": {tree: OrchRoutePolicy},+ "svc": {tree: SvcRoutePolicy},+ "state-query": {tree: StateQueryRoutePolicy},+ "k8s": {+ tree: K8sRoutePolicy,+ options: []MiddlewareOption{WithDeniedMessage("k8s request is not allowed")},+ },+}++// routeSurfaces maps every authenticated route pattern to its surface. The keys+// are the route names main.go stamps via RouteContext, which is also what the+// policy matches on as input.route.+//+// Several routes to one surface is the normal case, and is why plans are+// memoized per surface: the three billing routes share one module, one tree,+// and one compiled plan.+var routeSurfaces = map[string]string{+ "/api/config": "config",+ "/api/state/query": "state-query",++ "/api/billing/summary": "billing",+ "/api/billing/setup-session": "billing",+ "/api/billing/portal-session": "billing",++ "/api/keys": "keys",+ "/api/keys/{id}": "keys",++ "/api/namespaces": "namespaces",+ "/api/namespaces/{name}": "namespaces",++ "/api/user-keys": "user-keys",+ "/api/user-keys/{id}": "user-keys",++ "/api/github-trust-policies": "github-trust",+ "/api/github-trust-policies/{id}": "github-trust",++ "/api/svc/{namespace}/{service}": "svc",+ "/api/svc/{namespace}/{service}/{path...}": "svc",++ "/api/orch/{namespace}/{service}/{path...}": "orch",+ "/api/k8s/{path...}": "k8s",+}++// AuthenticatedRoutes returns every route the policy layer covers, sorted.+func AuthenticatedRoutes() []string {+ routes := make([]string, 0, len(routeSurfaces))+ for route := range routeSurfaces {+ routes = append(routes, route)+ }+ slices.Sort(routes)+ return routes+}++// SurfaceNames returns every surface name, sorted.+func SurfaceNames() []string {+ names := make([]string, 0, len(surfacePolicies))+ for name := range surfacePolicies {+ names = append(names, name)+ }+ slices.Sort(names)+ return names+}++// RouteSurface returns the surface a route's authorization belongs to.+func RouteSurface(route string) (string, bool) {+ name, ok := routeSurfaces[route]+ return name, ok+}++// SurfaceTree returns the policy tree a surface runs. The tree is rebuilt per+// call, like every other constructor here, so a caller that rewrites one cannot+// leak the rewrite into the next.+func SurfaceTree(name string) (Node, bool) {+ surface, ok := surfacePolicies[name]+ if !ok {+ return nil, false+ }+ return surface.tree(), true+}++// RouteTree returns the policy tree a route runs.+func RouteTree(route string) (Node, bool) {+ name, ok := RouteSurface(route)+ if !ok {+ return nil, false+ }+ return SurfaceTree(name)+}++// surfaceMiddlewares memoizes one compiled plan per surface. PolicyMiddleware+// optimizes and compiles eagerly, so building it per route would prepare the+// same Rego once per route sharing a surface — 17 plans rather than 10.+//+// What matters for a long-lived sidecar is the heap, because each plan holds a+// prepared query for the whole of the process's life. Measured on this tree:+// 10 plans retain 3.18 MiB, one retains 0.24 MiB, and memoizing per route+// instead would retain 4.95 MiB for the same 17 routes. The split into surfaces+// cost 0.75 MiB against the single-module policy's two plans (2.43 MiB) and+// nothing in compile time — 11.6ms against 12.6ms, because the same Rego is+// prepared either way, just cut into ten pieces. Memoization also saves main_test.go+// the redundant compiles of building a router four times.+//+// Memoization is lazy rather than a package-level var because Registered("authz")+// resolves through the module registry at compile time and LoadOpa is what+// populates that registry. Deferring to first use puts the compile after LoadOpa,+// and a name still unregistered by then panics during route construction rather+// than failing a request.+var (+ surfaceMiddlewareMu sync.Mutex+ surfaceMiddlewares = map[string]Middleware{}+)++// SurfaceMiddleware returns the authorization middleware for a surface,+// compiling its plan at most once per process. An unknown name panics: it can+// only come from a route bound to a surface nobody defined, which is a+// construction-time mistake with nothing downstream to notice it.+func SurfaceMiddleware(name string) Middleware {+ surfaceMiddlewareMu.Lock()+ defer surfaceMiddlewareMu.Unlock()+ if middleware, ok := surfaceMiddlewares[name]; ok {+ return middleware+ }+ surface, ok := surfacePolicies[name]+ if !ok {+ panic(fmt.Sprintf("no policy surface named %q", name))+ }+ middleware := PolicyMiddleware(surface.tree(), surface.options...)+ surfaceMiddlewares[name] = middleware+ return middleware+}++// RouteMiddleware returns the authorization middleware a route runs. A route+// with no surface panics during route construction — an authenticated route+// whose authorization nobody chose must not start, and there is no safe default+// to fall back to.+func RouteMiddleware(route string) Middleware {+ name, ok := RouteSurface(route)+ if !ok {+ panic(fmt.Sprintf("route %q has no authorization surface; add it to routeSurfaces in auth/policy_routes.go", route))+ }+ return SurfaceMiddleware(name)+}diff --git a/libs/fleet/backend/auth/policy_routes_test.go b/libs/fleet/backend/auth/policy_routes_test.gonew file mode 100644index 0000000000..ce01a12f0e--- /dev/null+++ b/libs/fleet/backend/auth/policy_routes_test.go@@ -0,0 +1,100 @@+package auth++import (+ "context"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++// routeRequest builds a request the way RouteContext and TokenAuthMiddleware+// leave it for the authorization stage: the matched route and its params+// stamped on the context, and the User stamped on it. Params are a non-nil map+// because that is what RouteContext always stamps — it ranges the route's+// declared parameter names into a map it just made.+func routeRequest(method, path, route string, params map[string]string, body string) *http.Request {+ request := httptest.NewRequest(method, path, nil)+ if params == nil {+ params = map[string]string{}+ }+ if body != "" {+ request.Body = io.NopCloser(strings.NewReader(body))+ }+ ctx := request.Context()+ ctx = context.WithValue(ctx, routeKey, route)+ ctx = context.WithValue(ctx, paramsKey, params)+ ctx = context.WithValue(ctx, UserKey, &User{ID: "u-1", AZP: "cyclops-cs-spa"})+ return request.WithContext(ctx)+}++// TestRoutePoliciesLeaveTheRequestBodyIntact covers the axis a verdict-only+// test cannot see: whether the handler downstream of the policy stage still+// receives the bytes the client sent.+//+// PolicyMiddleware reads the body when a leaf declares maxBodyBytes, and hands+// the handler a spliced reader that replays what it consumed. The route+// policies sit on opposite sides of that:+//+// - K8sRoutePolicy declares 1 MiB for pool admission, so it reads the body on+// every request and this exercises the splice for real today.+// - Every other surface declares nothing, so it never reaches loadBody and+// passes trivially. That row is here for the day someone adds WithRawBody to+// BasePolicy — which would put every authenticated route on the splice path+// at once, with no verdict changing and nothing else noticing.+func TestRoutePoliciesLeaveTheRequestBodyIntact(t *testing.T) {+ LoadOpa()+ const payload = `{"spec":{"replicas":3}}`++ cases := []struct {+ name string+ policy Node+ request func() *http.Request+ }{+ {+ name: "keys route reads no body",+ policy: KeysRoutePolicy(),+ request: func() *http.Request {+ return routeRequest(http.MethodPost, "/api/keys", "/api/keys", nil, payload)+ },+ },+ {+ // The path has to be one the allowlist admits, or this stops testing+ // the splice and starts testing the deny: PolicyMiddleware answers 403+ // before the handler ever reads a byte. It named a ConfigMap write+ // until #6704 made /api/k8s an allowlist, which does not admit one.+ name: "k8s route reads the body for pool admission",+ policy: K8sRoutePolicy(),+ request: func() *http.Request {+ const path = "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims"+ return routeRequest(http.MethodPost, "/api/k8s/"+path, "/api/k8s/{path...}",+ map[string]string{"path": path}, payload)+ },+ },+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ var seen string+ handler := PolicyMiddleware(testCase.policy)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, err := io.ReadAll(r.Body)+ if err != nil {+ t.Errorf("handler read body: %v", err)+ }+ seen = string(body)+ w.WriteHeader(http.StatusNoContent)+ }))++ response := httptest.NewRecorder()+ handler.ServeHTTP(response, testCase.request())++ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d; body = %q", response.Code, http.StatusNoContent, response.Body.String())+ }+ if seen != payload {+ t.Fatalf("handler read body %q, want %q", seen, payload)+ }+ })+ }+}diff --git a/libs/fleet/backend/auth/policy_test.go b/libs/fleet/backend/auth/policy_test.goindex 81330bf09d..218a19a8e1 100644--- a/libs/fleet/backend/auth/policy_test.go+++ b/libs/fleet/backend/auth/policy_test.go@@ -2,18 +2,68 @@ package authimport ("context"+ "encoding/json"+ "fmt""net/http""testing"+ "github.com/open-policy-agent/opa/ast""github.com/open-policy-agent/opa/rego")-// These tests exercise the embedded Rego policies directly (authzPolicy /-// filtersPolicy) with a controlled input.flags document, so they verify the+// These tests exercise the embedded Rego policies directly (authzPolicy and the+// surface modules) with a controlled input.flags document, so they verify the// security logic without depending on the OpenFeature provider. The// production code feeds the same documents via flagsData() — see// flags_test.go for the end-to-end path.+// TestRouteModulesNeverReadInputFacts pins an invariant the route policies rely+// on: PolicyMiddleware always puts a facts document in the input, built only+// from the fact providers the evaluating leaf declared, and neither leaf in+// policy_routes.go declares any. So input.facts is always {} for these modules,+// and a rule that reads it is reading an empty object — undefined lookups,+// silently.+//+// It is an assertion over the parsed module rather than a set of requests on+// purpose. The equivalence harness this replaced sampled the routes its table+// listed, which was 14 of 34 — a rule reading input.facts under any other route+// was invisible to it. Walking the refs holds for every route, method, and+// input at once, and it cost nothing to keep when that harness was deleted.+//+// If a leaf in policy_routes.go ever gains WithFacts, the module it names stops+// belonging in this table — reading input.facts is the point of that option.+func TestRouteModulesNeverReadInputFacts(t *testing.T) {+ modules := map[string]string{+ "authz.rego": authzPolicy,+ "pool_admission.rego": poolAdmissionPolicy,+ }+ // Every base and surface module too, read from the same map LoadOpa+ // registers, so a surface added there is covered without being named here.+ for _, module := range surfacePolicySources {+ modules[module.filename] = module.source+ }+ factsRef := ast.MustParseRef("input.facts")++ for name, source := range modules {+ t.Run(name, func(t *testing.T) {+ module, err := ast.ParseModule(name, source)+ if err != nil {+ t.Fatalf("parse %s: %v", name, err)+ }+ ast.WalkRefs(module, func(ref ast.Ref) bool {+ if ref.HasPrefix(factsRef) {+ t.Errorf(`%s reads %v, but the leaf that compiles it declares no fact+providers, so input.facts is always {} and this lookup is undefined. Either+give that leaf a WithFacts provider in policy_routes.go, or read the value+from somewhere that is actually populated.`, name, ref)+ }+ // Keep walking: report every offending ref, not just the first.+ return false+ })+ })+ }+}+func prepareQuery(t *testing.T, query string, modules map[string]string) rego.PreparedEvalQuery {t.Helper()opts := []func(*rego.Rego){rego.Query(query)}@@ -27,55 +77,83 @@ func prepareQuery(t *testing.T, query string, modules map[string]string) rego.Prreturn pq}+// evalAllow answers what the route's production policy would, over a raw input+// document. There is no single module to query any more: a route runs+// All(base, surface), so this resolves the tree main.go dispatches input.route+// to and folds its leaves the way compiledAll does.+//+// Leaves that read the request body are skipped — pool admission is one, and it+// has evalPoolAdmission for its own coverage. So an "allow" here means the route+// *authorization* allowed it, which is what every caller of this helper is+// asking about.func evalAllow(t *testing.T, input map[string]any) bool {t.Helper()- pq := prepareQuery(t, "data.authz.allow", map[string]string{"authz.rego": authzPolicy})- rs, err := pq.Eval(context.Background(), rego.EvalInput(input))- if err != nil {- t.Fatalf("eval allow: %v", err)+ LoadOpa()++ route, _ := input["route"].(string)+ tree, ok := RouteTree(route)+ if !ok {+ t.Fatalf("input names route %q, which is bound to no authorization surface", route)}- return rs.Allowed()++ allowed := true+ for _, leaf := range conjunctiveLeaves(t, tree) {+ if leaf.MaxBody > 0 {+ continue+ }+ modules, err := leaf.Source.modules()+ if err != nil {+ t.Fatalf("load modules for %q: %v", leaf.Query, err)+ }+ sources := make(map[string]string, len(modules))+ for _, module := range modules {+ sources[module.name] = module.source+ }+ result, err := prepareQuery(t, leaf.Query, sources).Eval(context.Background(), rego.EvalInput(input))+ if err != nil {+ t.Fatalf("eval %q: %v", leaf.Query, err)+ }+ if !result.Allowed() {+ allowed = false+ }+ }+ return allowed}-func evalIsAdmin(t *testing.T, input map[string]any) bool {+// conjunctiveLeaves flattens a route tree into its leaves, refusing anything but+// conjunction. Every route policy is All(...) today; a disjunction would make+// "AND the leaves" the wrong fold, and silently so.+func conjunctiveLeaves(t *testing.T, n Node) []Leaf {t.Helper()- pq := prepareQuery(t, "data.authz.is_admin", map[string]string{"authz.rego": authzPolicy})- rs, err := pq.Eval(context.Background(), rego.EvalInput(input))- if err != nil {- t.Fatalf("eval is_admin: %v", err)+ switch node := n.(type) {+ case Leaf:+ return []Leaf{node}+ case AllNode:+ var leaves []Leaf+ for _, child := range node.Children {+ leaves = append(leaves, conjunctiveLeaves(t, child)...)+ }+ return leaves+ default:+ t.Fatalf("route policy contains a %T; this helper folds conjunctions only", n)+ return nil}- return rs.Allowed()}-func evalVisibleEvents(t *testing.T, input map[string]any) []any {+func evalIsAdmin(t *testing.T, input map[string]any) bool {t.Helper()- pq := prepareQuery(t, "data.filters.visible_events", map[string]string{- "authz.rego": authzPolicy,- "filters.rego": filtersPolicy,- })+ pq := prepareQuery(t, "data.authz.is_admin", map[string]string{"authz.rego": authzPolicy})rs, err := pq.Eval(context.Background(), rego.EvalInput(input))if err != nil {- t.Fatalf("eval visible_events: %v", err)- }- if len(rs) == 0 || len(rs[0].Expressions) == 0 {- return nil- }- switch v := rs[0].Expressions[0].Value.(type) {- case []any:- return v- case map[string]any:- out := make([]any, 0, len(v))- for _, e := range v {- out = append(out, e)- }- return out+ t.Fatalf("eval is_admin: %v", err)}- return nil+ return rs.Allowed()}func evalPoolAdmission(t *testing.T, input map[string]any) bool {t.Helper()pq := prepareQuery(t, "data.pool_admission.allow", map[string]string{+ "authz.rego": authzPolicy,"pool_admission.rego": poolAdmissionPolicy,})rs, err := pq.Eval(context.Background(), rego.EvalInput(input))@@ -106,9 +184,16 @@ func TestPoolAdmissionImagePullSecret(t *testing.T) {}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {+ body, err := json.Marshal(map[string]any{"spec": map[string]any{"template": tc.template}})+ if err != nil {+ t.Fatalf("marshal body: %v", err)+ }input := map[string]any{"method": tc.method,- "object": map[string]any{"spec": map[string]any{"template": tc.template}},+ "params": map[string]any{"path": "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools"},+ "body": string(body),+ "user": map[string]any{"sub": "user-1"},+ "flags": flagsFor(false, "user-1"),}if got := evalPoolAdmission(t, input); got != tc.want {t.Fatalf("pool admission = %v, want %v", got, tc.want)@@ -141,53 +226,96 @@ func k8sInput(path string, admin bool) map[string]any {}}-func TestK8sAllow_InfraPathsRequireAdmin(t *testing.T) {+// TestK8sAllow_AllowlistVerdicts records what the allowlist admits and what it+// refuses. Since #6704 there is no "requires admin" tier: admin is not a way+// around the allowlist, so a path is either enumerated or it is denied, and the+// admin column exists here only to show that it changes nothing.+func TestK8sAllow_AllowlistVerdicts(t *testing.T) {cases := []struct {name stringpath stringadmin boolwant bool}{- // Infra-only: denied for non-admins, allowed for admins.+ // Cluster-scoped and infra paths: denied for everyone. These rows used+ // to read non-admin deny / admin allow.{"nodes / non-admin", "api/v1/nodes", false, false},- {"nodes / admin", "api/v1/nodes", true, true},- {"node subpath / non-admin", "api/v1/nodes/ip-10-0-0-1", false, false},- {"node subpath / admin", "api/v1/nodes/ip-10-0-0-1", true, true},- {"cluster-wide pods / non-admin", "api/v1/pods", false, false},- {"cluster-wide pods / admin", "api/v1/pods", true, true},- {"batch jobs / non-admin", "apis/batch/v1/namespaces/pool-foo/jobs", false, false},- {"batch jobs / admin", "apis/batch/v1/namespaces/pool-foo/jobs", true, true},- {"cyclops-cs configmaps / non-admin", "api/v1/namespaces/cyclops-cs/configmaps/batch-configs", false, false},- {"cyclops-cs configmaps / admin", "api/v1/namespaces/cyclops-cs/configmaps/batch-configs", true, true},- // Cluster-wide CRD lists leak every tenant's pools/claims — admin only.- {"cluster-wide pools / non-admin", "apis/cua.ai/v1/osgymworkspacepools", false, false},- {"cluster-wide pools / admin", "apis/cua.ai/v1/osgymworkspacepools", true, true},- {"cluster-wide claims / non-admin", "apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims", false, false},- {"cluster-wide claims / admin", "apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims", true, true},- {"cluster-wide warm pools / non-admin", "apis/osgym.cua.ai/v1alpha1/osgymsandboxwarmpools", false, false},- {"cluster-wide warm pools / admin", "apis/osgym.cua.ai/v1alpha1/osgymsandboxwarmpools", true, true},+ {"nodes / admin", "api/v1/nodes", true, false},+ {"node subpath / admin", "api/v1/nodes/ip-10-0-0-1", true, false},+ {"cluster-wide pods / admin", "api/v1/pods", true, false},+ {"batch jobs / admin", "apis/batch/v1/namespaces/pool-foo/jobs", true, false},+ {"cyclops-cs configmaps / admin", "api/v1/namespaces/cyclops-cs/configmaps/batch-configs", true, false},+ {"cluster-wide pools / admin", "apis/cua.ai/v1/osgymworkspacepools", true, false},+ {"cluster-wide claims / admin", "apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims", true, false},+ {"cluster-wide warm pools / admin", "apis/osgym.cua.ai/v1alpha1/osgymsandboxwarmpools", true, false},{"cluster-wide templates / non-admin", "apis/osgym.cua.ai/v1alpha1/osgymsandboxtemplates", false, false},{"cluster-wide sandboxes / non-admin", "apis/osgym.cua.ai/v1alpha1/osgymsandboxes", false, false},- {"Capsule tenants / non-admin", "apis/capsule.clastix.io/v1beta2/tenants", false, false},+ {"Capsule tenants / admin", "apis/capsule.clastix.io/v1beta2/tenants", true, false},{"Capsule tenant item / non-admin", "apis/capsule.clastix.io/v1beta2/tenants/user-u-1", false, false},{"Capsule legacy tenants / non-admin", "apis/capsule.clastix.io/v1beta1/tenants", false, false},- {"Capsule future tenant subresource / non-admin", "apis/capsule.clastix.io/v99/tenants/user-u-1/status", false, false},- {"Capsule tenants / admin", "apis/capsule.clastix.io/v1beta2/tenants", true, true},- {"Capsule neighboring resource / non-admin", "apis/capsule.clastix.io/v1beta2/tenantowners", false, true},- {"Capsule group prefix collision / non-admin", "apis/capsule.clastix.io.evil/v1beta2/tenants", false, true},+ // The lookalikes that used to prove is_infra_k8s_path is exact. They are+ // denied now for the ordinary reason -- nobody enumerated them -- so the+ // precision they were guarding is asserted against the predicate itself+ // in authz_k8s_test.rego, where a route verdict can no longer see it.+ {"Capsule neighboring resource / non-admin", "apis/capsule.clastix.io/v1beta2/tenantowners", false, false},+ {"Capsule group prefix collision / non-admin", "apis/capsule.clastix.io.evil/v1beta2/tenants", false, false},- // Customer-facing: allowed regardless of admin.+ // Enumerated and therefore admitted. k8sInput drives GET, which is the+ // only verb every one of these shares; the per-verb matrix lives in+ // authz_k8s_test.rego.{"namespaced pods / non-admin", "api/v1/namespaces/pool-foo/pods", false, true},{"pod logs / non-admin", "api/v1/namespaces/pool-foo/pods/p-1/log", false, true},{"pod metrics / non-admin", "apis/metrics.k8s.io/v1beta1/namespaces/pool-foo/pods/p-1", false, true},- // Namespaced pool/claim lists are how the SPA reads them — stay open+ {"namespaced services / non-admin", "api/v1/namespaces/pool-foo/services", false, true},+ {"kubevirt VMs / non-admin", "apis/kubevirt.io/v1/namespaces/pool-foo/virtualmachines", false, true},+ {"discovery / non-admin", "openapi/v2", false, true},+ // Namespaced pool/claim lists are how the SDK reads them// (Capsule RBAC scopes the user to their own namespaces).{"namespaced pools / non-admin", "apis/cua.ai/v1/namespaces/pool-foo/osgymworkspacepools", false, true},{"namespaced claims / non-admin", "apis/osgym.cua.ai/v1alpha1/namespaces/pool-foo/osgymsandboxclaims", false, true},{"namespaced warm pools / non-admin", "apis/osgym.cua.ai/v1alpha1/namespaces/pool-foo/osgymsandboxwarmpools", false, true},{"namespaced templates / non-admin", "apis/osgym.cua.ai/v1alpha1/namespaces/pool-foo/osgymsandboxtemplates", false, true},- {"events list / non-admin (contents filtered elsewhere)", "api/v1/events", false, true},- {"namespaced events / non-admin", "api/v1/namespaces/pool-foo/events", false, true},++ // Unenumerated, and denied for that reason alone -- no exclusion list+ // mentions any of them. The Secret read is the one a reviewer is most+ // likely to want to argue about: it succeeded in production, from the+ // SDK live-test flow, and the allowlist drops it.+ {"namespaced secrets / non-admin", "api/v1/namespaces/pool-foo/secrets/ecr-credentials", false, false},+ {"namespaced configmaps / non-admin", "api/v1/namespaces/pool-foo/configmaps", false, false},+ {"storage classes / non-admin", "apis/storage.k8s.io/v1/storageclasses", false, false},+ {"sandboxes CRD / admin", "apis/osgym.cua.ai/v1alpha1/namespaces/pool-foo/osgymsandboxes", true, false},++ // Events: denied for everyone, admins included. Unlike every infra path+ // above, the admin row here is a deny too — that asymmetry is the whole+ // difference between "hidden from the nav" and "not proxied".+ //+ // All eight served shapes: two API groups, each cluster-scoped and+ // namespaced, each with a legacy /watch/ alias.+ {"cluster events / non-admin", "api/v1/events", false, false},+ {"cluster events / admin", "api/v1/events", true, false},+ {"cluster event item / non-admin", "api/v1/events/evt-1", false, false},+ {"namespaced events / non-admin", "api/v1/namespaces/pool-foo/events", false, false},+ {"namespaced events / admin", "api/v1/namespaces/pool-foo/events", true, false},+ {"namespaced event item / non-admin", "api/v1/namespaces/pool-foo/events/evt-1", false, false},+ {"group cluster events / non-admin", "apis/events.k8s.io/v1/events", false, false},+ {"group cluster events / admin", "apis/events.k8s.io/v1/events", true, false},+ {"group namespaced events / non-admin", "apis/events.k8s.io/v1/namespaces/pool-foo/events", false, false},+ {"group event item / non-admin", "apis/events.k8s.io/v1/namespaces/pool-foo/events/evt-1", false, false},+ {"group other version events / non-admin", "apis/events.k8s.io/v1beta1/events", false, false},+ {"legacy watch cluster events / non-admin", "api/v1/watch/events", false, false},+ {"legacy watch namespaced events / non-admin", "api/v1/watch/namespaces/pool-foo/events", false, false},+ {"legacy watch group events / non-admin", "apis/events.k8s.io/v1/watch/events", false, false},+ {"legacy watch group namespaced events / non-admin", "apis/events.k8s.io/v1/watch/namespaces/pool-foo/events", false, false},+ // Neighbours of the event paths. Only one is still an allow: "events" as+ // a namespace name, on a resource the allowlist admits. The rest are+ // denied because they are unenumerated, not because the event predicate+ // matched them -- which is exactly why that predicate's precision is now+ // asserted directly in authz_k8s_test.rego instead of here.+ {"namespace named events / non-admin", "api/v1/namespaces/events/pods", false, true},+ {"event lookalike resource / non-admin", "api/v1/namespaces/pool-foo/eventsources", false, false},+ {"event group prefix collision / non-admin", "apis/events.k8s.io.evil/v1/events", false, false},+ {"events group neighbour resource / non-admin", "apis/events.k8s.io/v1/eventsources", false, false},+ {"watch on non-events / non-admin", "api/v1/watch/namespaces/pool-foo/pods", false, false},}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {@@ -242,53 +370,143 @@ func TestIsAdmin(t *testing.T) {}}-func TestVisibleEvents(t *testing.T) {- events := []any{- map[string]any{"reason": "PoolCreated"},- map[string]any{"reason": "PoolReady"},- map[string]any{"reason": "InternalScaleDecision"},- }-- t.Run("admin sees all", func(t *testing.T) {- in := map[string]any{- "user": map[string]any{"sub": "admin"},- "flags": map[string]any{"admin_subs": []any{"admin"}, "event_reason_allowlist": []any{"PoolCreated"}},- "events": events,+func TestK8sAllow_GitHubExactScope(t *testing.T) {+ githubInput := func(method, path string, namespaces ...string) map[string]any {+ allowed := make([]any, len(namespaces))+ for index, namespace := range namespaces {+ allowed[index] = namespace}- if got := len(evalVisibleEvents(t, in)); got != 3 {- t.Fatalf("admin visible_events = %d, want 3", got)+ return map[string]any{+ "route": "/api/k8s/{path...}",+ "method": method,+ "params": map[string]any{"path": path},+ "user": map[string]any{+ "sub": "owner-1",+ "azp": "github-oidc",+ "principal_type": "github_oidc",+ "allowed_namespaces": allowed,+ },+ "flags": flagsFor(false, "owner-1"),}- })+ }- t.Run("non-admin sees only allowlisted reasons", func(t *testing.T) {- in := map[string]any{- "user": map[string]any{"sub": "nobody"},- "flags": map[string]any{"admin_subs": []any{"admin"}, "event_reason_allowlist": []any{"PoolCreated", "PoolReady"}},- "events": events,- }- if got := len(evalVisibleEvents(t, in)); got != 2 {- t.Fatalf("non-admin visible_events = %d, want 2", got)- }- })+ cases := []struct {+ name string+ method string+ path string+ namespaces []string+ want bool+ }{+ {"legacy collection get", http.MethodGet, "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", []string{"ns-a"}, true},+ {"legacy collection post", http.MethodPost, "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", []string{"ns-a"}, true},+ {"legacy collection patch", http.MethodPatch, "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", []string{"ns-a"}, true},+ {"legacy collection delete", http.MethodDelete, "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", []string{"ns-a"}, true},+ {"legacy item post", http.MethodPost, "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools/pool-a", []string{"ns-a"}, true},+ {"legacy item patch", http.MethodPatch, "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools/pool-a", []string{"ns-a"}, true},+ {"native warm pool item get", http.MethodGet, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxwarmpools/pool-a", []string{"ns-a"}, true},+ {"native warm pool item patch", http.MethodPatch, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxwarmpools/pool-a", []string{"ns-a"}, true},+ {"native warm pool item post denied", http.MethodPost, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxwarmpools/pool-a", []string{"ns-a"}, false},+ {"native warm pool collection patch denied", http.MethodPatch, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxwarmpools", []string{"ns-a"}, false},+ {"native claim collection post", http.MethodPost, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims", []string{"ns-a"}, true},+ {"native claim item delete", http.MethodDelete, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims/claim-a", []string{"ns-a"}, true},+ {"native template get", http.MethodGet, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxtemplates/template-a", []string{"ns-a"}, true},+ {"namespace outside grant", http.MethodGet, "apis/cua.ai/v1/namespaces/ns-b/osgymworkspacepools", []string{"ns-a"}, false},+ {"template write denied", http.MethodPost, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxtemplates", []string{"ns-a"}, false},+ {"claim item post denied", http.MethodPost, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims/claim-a", []string{"ns-a"}, false},+ {"claim collection patch denied", http.MethodPatch, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims", []string{"ns-a"}, false},+ {"claim item patch", http.MethodPatch, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims/claim-a", []string{"ns-a"}, true},+ {"claim subresource denied", http.MethodGet, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims/claim-a/status", []string{"ns-a"}, false},+ {"cluster path denied", http.MethodGet, "apis/osgym.cua.ai/v1alpha1/osgymsandboxclaims", []string{"ns-a"}, false},+ {"empty item denied", http.MethodGet, "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools/", []string{"ns-a"}, false},+ }- t.Run("non-admin with empty allowlist sees none", func(t *testing.T) {- in := map[string]any{- "user": map[string]any{"sub": "nobody"},- "flags": map[string]any{"admin_subs": []any{"admin"}, "event_reason_allowlist": []any{}},- "events": events,- }- if got := len(evalVisibleEvents(t, in)); got != 0 {- t.Fatalf("non-admin empty allowlist visible_events = %d, want 0", got)- }- })+ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ input := githubInput(testCase.method, testCase.path, testCase.namespaces...)+ if got := evalAllow(t, input); got != testCase.want {+ t.Fatalf("allow(%s %s) = %v, want %v", testCase.method, testCase.path, got, testCase.want)+ }+ })+ }+}- t.Run("non-admin with missing flags sees none", func(t *testing.T) {- in := map[string]any{- "user": map[string]any{"sub": "nobody"},- "events": events,- }- if got := len(evalVisibleEvents(t, in)); got != 0 {- t.Fatalf("non-admin missing flags visible_events = %d, want 0", got)+func TestPoolAdmissionRequestPolicy(t *testing.T) {+ const allowedImage = "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace-duo:latest"+ input := func(method, path, body, sub string, admin bool) map[string]any {+ return map[string]any{+ "method": method,+ "params": map[string]any{"path": path},+ "body": body,+ "user": map[string]any{"sub": sub},+ "flags": flagsFor(admin, sub),}- })+ }++ cases := []struct {+ name string+ input map[string]any+ wanted bool+ }{+ {+ name: "unrelated request allowed",+ input: input(http.MethodPost, "api/v1/namespaces/ns-a/configmaps", `not json`, "user-1", false),+ wanted: true,+ },+ {+ name: "malformed pool body denied",+ input: input(http.MethodPost, "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", `not json`, "user-1", false),+ wanted: false,+ },+ {+ name: "disallowed image denied",+ input: input(http.MethodPost, "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", `{"spec":{"template":{"containerDiskImage":"evil.example/image:latest","imagePullSecret":"ecr-credentials"}}}`, "user-1", false),+ wanted: false,+ },+ {+ name: "allowed image accepted",+ input: input(http.MethodPost, "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", fmt.Sprintf(`{"spec":{"template":{"containerDiskImage":%q,"imagePullSecret":"ecr-credentials"}}}`, allowedImage), "user-1", false),+ wanted: true,+ },+ {+ name: "mixed-case macos denied for non-admin",+ input: input(http.MethodPost, "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", `{"spec":{"template":{"runtime":"MacOS"}}}`, "user-1", false),+ wanted: false,+ },+ {+ name: "macos runtime class denied for non-admin",+ input: input(http.MethodPost, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxtemplates", `{"spec":{"vmTemplate":{"runtimeClassName":"cua-macos-native"}}}`, "user-1", false),+ wanted: false,+ },+ {+ name: "macos node selector denied for non-admin",+ input: input(http.MethodPatch, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxtemplates/template-a", `{"spec":{"vmTemplate":{"nodeSelector":{"cua.ai/macos":"true"}}}}`, "user-1", false),+ wanted: false,+ },+ {+ name: "macos accepted for admin",+ input: input(http.MethodPost, "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxtemplates", `{"spec":{"vmTemplate":{"runtime":"macos"}}}`, "admin-1", true),+ wanted: true,+ },+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ if got := evalPoolAdmission(t, testCase.input); got != testCase.wanted {+ t.Fatalf("pool admission = %v, want %v", got, testCase.wanted)+ }+ })+ }+}++func TestPoolAdmissionIgnoresLookalikeResourceGroups(t *testing.T) {+ input := map[string]any{+ "method": http.MethodPost,+ "params": map[string]any{"path": "apis/evil.example/v1/namespaces/ns-a/osgymworkspacepools"},+ "body": `not json`,+ "user": map[string]any{"sub": "user-1"},+ "flags": flagsFor(false, "user-1"),+ }+ if !evalPoolAdmission(t, input) {+ t.Fatal("lookalike resource group should be outside pool admission policy scope")+ }}diff --git a/libs/fleet/backend/auth/pool_admission.rego b/libs/fleet/backend/auth/pool_admission.regoindex 2d9376f120..ba8f11a2b3 100644--- a/libs/fleet/backend/auth/pool_admission.rego+++ b/libs/fleet/backend/auth/pool_admission.rego@@ -1,5 +1,7 @@package pool_admission+import data.authz+default allow = falseecr_pull_secret := "ecr-credentials"@@ -15,12 +17,82 @@ allowed_image_repositories := {"296062593712.dkr.ecr.us-west-2.amazonaws.com/ubuntu-vnc-cua-kubevirt",}-# The VM shape lives at spec.vmTemplate on the native OSGymSandboxTemplate-# and at spec.template on the retired legacy OSGymWorkspacePool (still-# evaluated so a stale client cannot slip past the gate).-vm_template := object.get(object.get(input.object, "spec", {}), "vmTemplate", {})+write_method {+ input.method == "POST"+}++write_method {+ input.method == "PUT"+}++write_method {+ input.method == "PATCH"+}++pool_resource_path {+ parts := split(input.params.path, "/")+ count(parts) == 6+ parts[0] == "apis"+ parts[1] == "osgym.cua.ai"+ parts[2] == "v1alpha1"+ parts[3] == "namespaces"+ parts[4] != ""+ parts[5] == "osgymsandboxtemplates"+}++pool_resource_path {+ parts := split(input.params.path, "/")+ count(parts) == 7+ parts[0] == "apis"+ parts[1] == "osgym.cua.ai"+ parts[2] == "v1alpha1"+ parts[3] == "namespaces"+ parts[4] != ""+ parts[5] == "osgymsandboxtemplates"+ parts[6] != ""+}++pool_resource_path {+ parts := split(input.params.path, "/")+ count(parts) == 6+ parts[0] == "apis"+ parts[1] == "cua.ai"+ parts[2] == "v1"+ parts[3] == "namespaces"+ parts[4] != ""+ parts[5] == "osgymworkspacepools"+}++pool_resource_path {+ parts := split(input.params.path, "/")+ count(parts) == 7+ parts[0] == "apis"+ parts[1] == "cua.ai"+ parts[2] == "v1"+ parts[3] == "namespaces"+ parts[4] != ""+ parts[5] == "osgymworkspacepools"+ parts[6] != ""+}++applies {+ write_method+ pool_resource_path+}++allow {+ not applies+}++request_object := json.unmarshal(input.body) {+ applies+}++spec := object.get(request_object, "spec", {})++vm_template := object.get(spec, "vmTemplate", {})-legacy_template := object.get(object.get(input.object, "spec", {}), "template", {})+legacy_template := object.get(spec, "template", {})template := vm_template {vm_template != {}@@ -56,30 +128,59 @@ allowed_image {startswith(image, sprintf("%s@", [repository]))}-allow {+image_configuration_allowed {input.method != "PATCH"not has_pull_secret}-allow {+image_configuration_allowed {input.method != "PATCH"template.imagePullSecret == ecr_pull_secretallowed_image}-allow {+image_configuration_allowed {input.method == "PATCH"not has_pull_secretnot has_image}-allow {+image_configuration_allowed {input.method == "PATCH"object.get(template, "imagePullSecret", "missing") == null}-allow {+image_configuration_allowed {input.method == "PATCH"template.imagePullSecret == ecr_pull_secretallowed_image}++requests_macos {+ lower(object.get(template, "runtime", "")) == "macos"+}++requests_macos {+ object.get(template, "runtimeClassName", "") == "cua-macos-native"+}++requests_macos {+ node_selector := object.get(template, "nodeSelector", {})+ object.get(node_selector, "cua.ai/macos", null) != null+}++macos_allowed {+ not requests_macos+}++macos_allowed {+ requests_macos+ authz.is_admin+}++allow {+ applies+ is_object(request_object)+ image_configuration_allowed+ macos_allowed+}diff --git a/libs/fleet/backend/auth/pool_admission_test.rego b/libs/fleet/backend/auth/pool_admission_test.regoindex 3f8a0c7878..7feb12c111 100644--- a/libs/fleet/backend/auth/pool_admission_test.rego+++ b/libs/fleet/backend/auth/pool_admission_test.rego@@ -2,149 +2,168 @@ package pool_admission_testimport data.pool_admission+legacy_path := "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools"++native_path := "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxtemplates"+allowed_image := "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace-duo:latest"+osworld_v2_digest := "296062593712.dkr.ecr.us-west-2.amazonaws.com/osworld-v2-ubuntu-x86@sha256:6f981825c5970027df510006fcfc1ef7a502d2911f69ed9884f7f217007931dd"-test_no_pull_secret_allowed {+non_admin := {"sub": "user-1"}++non_admin_flags := {"admin_subs": []}++admin := {"sub": "admin-1"}++admin_flags := {"admin_subs": ["admin-1"]}++test_unrelated_request_allowed {pool_admission.allow with input as {"method": "POST",- "object": {"spec": {"template": {"containerDiskImage": "docker.io/library/alpine:3.20"}}},+ "params": {"path": "api/v1/namespaces/ns-a/configmaps"},+ "body": "not json",+ "user": non_admin,+ "flags": non_admin_flags,}}-test_non_ecr_secret_denied {+test_malformed_pool_body_denied {not pool_admission.allow with input as {"method": "POST",- "object": {"spec": {"template": {- "containerDiskImage": allowed_image,- "imagePullSecret": "other-secret",- }}},+ "params": {"path": legacy_path},+ "body": "not json",+ "user": non_admin,+ "flags": non_admin_flags,}}-test_ecr_secret_allowlisted_image_allowed {+test_no_pull_secret_allowed {pool_admission.allow with input as {"method": "POST",- "object": {"spec": {"template": {- "containerDiskImage": allowed_image,- "imagePullSecret": "ecr-credentials",- }}},+ "params": {"path": legacy_path},+ "body": `{"spec":{"template":{"containerDiskImage":"docker.io/library/alpine:3.20"}}}`,+ "user": non_admin,+ "flags": non_admin_flags,}}-test_ecr_secret_osworld_v2_digest_allowed {- pool_admission.allow with input as {+test_non_ecr_secret_denied {+ not pool_admission.allow with input as {"method": "POST",- "object": {"spec": {"template": {- "containerDiskImage": osworld_v2_digest,- "imagePullSecret": "ecr-credentials",- }}},+ "params": {"path": legacy_path},+ "body": sprintf(`{"spec":{"template":{"containerDiskImage":%q,"imagePullSecret":"other-secret"}}}`, [allowed_image]),+ "user": non_admin,+ "flags": non_admin_flags,}}-test_osworld_v2_repository_prefix_collision_denied {- not pool_admission.allow with input as {+test_ecr_secret_allowlisted_image_allowed {+ pool_admission.allow with input as {"method": "POST",- "object": {"spec": {"template": {- "containerDiskImage": "296062593712.dkr.ecr.us-west-2.amazonaws.com/osworld-v2-ubuntu-x86-evil:latest",- "imagePullSecret": "ecr-credentials",- }}},+ "params": {"path": legacy_path},+ "body": sprintf(`{"spec":{"template":{"containerDiskImage":%q,"imagePullSecret":"ecr-credentials"}}}`, [allowed_image]),+ "user": non_admin,+ "flags": non_admin_flags,}}-test_ecr_secret_gymdriver_dev_image_allowed {+test_ecr_secret_osworld_v2_digest_allowed {pool_admission.allow with input as {"method": "POST",- "object": {"spec": {"template": {- "containerDiskImage": "296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-gymdriver-dev:latest",- "imagePullSecret": "ecr-credentials",- }}},+ "params": {"path": legacy_path},+ "body": sprintf(`{"spec":{"template":{"containerDiskImage":%q,"imagePullSecret":"ecr-credentials"}}}`, [osworld_v2_digest]),+ "user": non_admin,+ "flags": non_admin_flags,}}-test_ecr_secret_disallowed_image_denied {- not pool_admission.allow with input as {+test_ecr_secret_gymdriver_dev_image_allowed {+ pool_admission.allow with input as {"method": "POST",- "object": {"spec": {"template": {- "containerDiskImage": "evil.example/workspace:latest",- "imagePullSecret": "ecr-credentials",- }}},+ "params": {"path": legacy_path},+ "body": sprintf(`{"spec":{"template":{"containerDiskImage":%q,"imagePullSecret":"ecr-credentials"}}}`, ["296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-gymdriver-dev:latest"]),+ "user": non_admin,+ "flags": non_admin_flags,}}test_repository_prefix_collision_denied {not pool_admission.allow with input as {"method": "POST",- "object": {"spec": {"template": {- "containerDiskImage": "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace-evil:latest",- "imagePullSecret": "ecr-credentials",- }}},+ "params": {"path": legacy_path},+ "body": `{"spec":{"template":{"containerDiskImage":"296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace-evil:latest","imagePullSecret":"ecr-credentials"}}}`,+ "user": non_admin,+ "flags": non_admin_flags,}}test_unrelated_patch_allowed {pool_admission.allow with input as {"method": "PATCH",- "object": {"spec": {"services": [{"name": "server", "targetPort": 8000}]}},+ "params": {"path": legacy_path},+ "body": `{"spec":{"template":{"cpuCores":8}}}`,+ "user": non_admin,+ "flags": non_admin_flags,}}test_image_only_patch_denied {not pool_admission.allow with input as {"method": "PATCH",- "object": {"spec": {"template": {"containerDiskImage": allowed_image}}},- }-}--test_secret_only_patch_denied {- not pool_admission.allow with input as {- "method": "PATCH",- "object": {"spec": {"template": {"imagePullSecret": "ecr-credentials"}}},+ "params": {"path": legacy_path},+ "body": sprintf(`{"spec":{"template":{"containerDiskImage":%q}}}`, [allowed_image]),+ "user": non_admin,+ "flags": non_admin_flags,}}-# ── Native OSGymSandboxTemplate shape (spec.vmTemplate) ─────────────────--test_vm_template_no_pull_secret_allowed {+test_vm_template_ecr_secret_allowlisted_image_allowed {pool_admission.allow with input as {"method": "POST",- "object": {"spec": {"vmTemplate": {"containerDiskImage": "docker.io/library/alpine:3.20"}}},+ "params": {"path": native_path},+ "body": sprintf(`{"spec":{"vmTemplate":{"containerDiskImage":%q,"imagePullSecret":"ecr-credentials"}}}`, [allowed_image]),+ "user": non_admin,+ "flags": non_admin_flags,}}-test_vm_template_non_ecr_secret_denied {+test_macos_runtime_denied_for_non_admin {not pool_admission.allow with input as {"method": "POST",- "object": {"spec": {"vmTemplate": {- "containerDiskImage": allowed_image,- "imagePullSecret": "other-secret",- }}},+ "params": {"path": native_path},+ "body": `{"spec":{"vmTemplate":{"runtime":"MacOS"}}}`,+ "user": non_admin,+ "flags": non_admin_flags,}}-test_vm_template_ecr_secret_allowlisted_image_allowed {- pool_admission.allow with input as {+test_macos_runtime_class_denied_for_non_admin {+ not pool_admission.allow with input as {"method": "POST",- "object": {"spec": {"vmTemplate": {- "containerDiskImage": allowed_image,- "imagePullSecret": "ecr-credentials",- }}},+ "params": {"path": native_path},+ "body": `{"spec":{"vmTemplate":{"runtimeClassName":"cua-macos-native"}}}`,+ "user": non_admin,+ "flags": non_admin_flags,}}-test_vm_template_ecr_secret_unlisted_image_denied {+test_macos_node_selector_denied_for_non_admin {not pool_admission.allow with input as {- "method": "POST",- "object": {"spec": {"vmTemplate": {- "containerDiskImage": "docker.io/evil/image:latest",- "imagePullSecret": "ecr-credentials",- }}},+ "method": "PATCH",+ "params": {"path": sprintf("%s/template-a", [native_path])},+ "body": `{"spec":{"vmTemplate":{"nodeSelector":{"cua.ai/macos":"true"}}}}`,+ "user": non_admin,+ "flags": non_admin_flags,}}-test_vm_template_patch_pull_secret_swap_denied {- not pool_admission.allow with input as {- "method": "PATCH",- "object": {"spec": {"vmTemplate": {"imagePullSecret": "other-secret"}}},+test_macos_allowed_for_admin {+ pool_admission.allow with input as {+ "method": "POST",+ "params": {"path": native_path},+ "body": `{"spec":{"vmTemplate":{"runtime":"macos"}}}`,+ "user": admin,+ "flags": admin_flags,}}diff --git a/libs/fleet/backend/auth/route_params_test.go b/libs/fleet/backend/auth/route_params_test.gonew file mode 100644index 0000000000..c69f82cd7d--- /dev/null+++ b/libs/fleet/backend/auth/route_params_test.go@@ -0,0 +1,63 @@+package auth++import (+ "net/http"+ "net/http/httptest"+ "slices"+ "testing"+)++// TestRouteParamNamesReadsThePattern pins the scan RouteContext derives its+// parameter names with. The names are what r.PathValue is keyed by, so the two+// cases that would silently break policy input are the ones a hand-written list+// used to get right by hand: a trailing "{x...}" is keyed "x", and a pattern+// with no wildcards contributes no keys at all rather than an empty-named one.+func TestRouteParamNamesReadsThePattern(t *testing.T) {+ cases := []struct {+ route string+ want []string+ }{+ {"/api/keys", nil},+ {"/healthz", nil},+ {"/api/keys/{id}", []string{"id"}},+ {"/api/k8s/{path...}", []string{"path"}},+ {"/api/svc/{namespace}/{service}", []string{"namespace", "service"}},+ {"/api/svc/{namespace}/{service}/{path...}", []string{"namespace", "service", "path"}},+ // "{$}" anchors a pattern to the end of the path and binds no value,+ // so it must not become a parameter the policy sees as undefined.+ {"/api/keys/{$}", nil},+ }++ for _, testCase := range cases {+ got := routeParamNames(testCase.route)+ if !slices.Equal(got, testCase.want) {+ t.Errorf("routeParamNames(%q) = %v, want %v", testCase.route, got, testCase.want)+ }+ }+}++// TestRouteContextStampsTheWildcardsTheMuxMatched runs the derivation through a+// real ServeMux: the names the scan produces have to be the names the mux+// actually bound, or every PathValue lookup returns "" and the policy reads a+// map of empty strings.+func TestRouteContextStampsTheWildcardsTheMuxMatched(t *testing.T) {+ const route = "/api/svc/{namespace}/{service}/{path...}"++ var got map[string]string+ mux := http.NewServeMux()+ mux.Handle(route, RouteContext(route)(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {+ got, _ = r.Context().Value(paramsKey).(map[string]string)+ })))++ mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/svc/ns-a/svc-a/v1/status", nil))++ want := map[string]string{"namespace": "ns-a", "service": "svc-a", "path": "v1/status"}+ if len(got) != len(want) {+ t.Fatalf("params = %v, want %v", got, want)+ }+ for key, value := range want {+ if got[key] != value {+ t.Errorf("params[%q] = %q, want %q (full: %v)", key, got[key], value, got)+ }+ }+}diff --git a/libs/fleet/backend/auth/testdata/billing-route-plan.txt b/libs/fleet/backend/auth/testdata/billing-route-plan.txtnew file mode 100644index 0000000000..ab729dfa80--- /dev/null+++ b/libs/fleet/backend/auth/testdata/billing-route-plan.txt@@ -0,0 +1,3 @@+All+ Leaf query=data.authz_base.allow source=registered:authz-base+ Leaf query=data.authz_billing.allow source=multi["registered:authz","registered:authz-billing"]diff --git a/libs/fleet/backend/auth/testdata/config-route-plan.txt b/libs/fleet/backend/auth/testdata/config-route-plan.txtnew file mode 100644index 0000000000..47365dac93--- /dev/null+++ b/libs/fleet/backend/auth/testdata/config-route-plan.txt@@ -0,0 +1,3 @@+All+ Leaf query=data.authz_base.allow source=registered:authz-base+ Leaf query=data.authz_config.allow source=multi["registered:authz","registered:authz-config"]diff --git a/libs/fleet/backend/auth/testdata/fuzz/FuzzOptimizerEquivalence/35f2b0c92e371f36 b/libs/fleet/backend/auth/testdata/fuzz/FuzzOptimizerEquivalence/35f2b0c92e371f36new file mode 100644index 0000000000..46e3d38d48--- /dev/null+++ b/libs/fleet/backend/auth/testdata/fuzz/FuzzOptimizerEquivalence/35f2b0c92e371f36@@ -0,0 +1,2 @@+go test fuzz v1+[]byte("11021011")diff --git a/libs/fleet/backend/auth/testdata/fuzz/FuzzOptimizerEquivalence/66ecb07bcbdbbe19 b/libs/fleet/backend/auth/testdata/fuzz/FuzzOptimizerEquivalence/66ecb07bcbdbbe19new file mode 100644index 0000000000..099f11c76e--- /dev/null+++ b/libs/fleet/backend/auth/testdata/fuzz/FuzzOptimizerEquivalence/66ecb07bcbdbbe19@@ -0,0 +1,2 @@+go test fuzz v1+[]byte("01011001")diff --git a/libs/fleet/backend/auth/testdata/github-trust-route-plan.txt b/libs/fleet/backend/auth/testdata/github-trust-route-plan.txtnew file mode 100644index 0000000000..eb41dc2469--- /dev/null+++ b/libs/fleet/backend/auth/testdata/github-trust-route-plan.txt@@ -0,0 +1,3 @@+All+ Leaf query=data.authz_base.allow source=registered:authz-base+ Leaf query=data.authz_github_trust.allow source=multi["registered:authz","registered:authz-github-trust"]diff --git a/libs/fleet/backend/auth/testdata/k8s-route-plan.txt b/libs/fleet/backend/auth/testdata/k8s-route-plan.txtnew file mode 100644index 0000000000..9069c597eb--- /dev/null+++ b/libs/fleet/backend/auth/testdata/k8s-route-plan.txt@@ -0,0 +1,4 @@+All+ Leaf query=data.authz_base.allow source=registered:authz-base+ Leaf query=data.authz_k8s.allow source=multi["registered:authz","registered:authz-k8s"]+ Leaf query=data.pool_admission.allow source=multi["registered:authz","registered:pool-admission"] body=1048576diff --git a/libs/fleet/backend/auth/testdata/keys-route-plan.txt b/libs/fleet/backend/auth/testdata/keys-route-plan.txtnew file mode 100644index 0000000000..a73d1296c2--- /dev/null+++ b/libs/fleet/backend/auth/testdata/keys-route-plan.txt@@ -0,0 +1,3 @@+All+ Leaf query=data.authz_base.allow source=registered:authz-base+ Leaf query=data.authz_keys.allow source=multi["registered:authz","registered:authz-keys"]diff --git a/libs/fleet/backend/auth/testdata/namespaces-route-plan.txt b/libs/fleet/backend/auth/testdata/namespaces-route-plan.txtnew file mode 100644index 0000000000..96ca90163d--- /dev/null+++ b/libs/fleet/backend/auth/testdata/namespaces-route-plan.txt@@ -0,0 +1,8 @@+All+ Leaf query=data.authz_base.allow source=registered:authz-base+ Leaf query=data.authz_namespaces.allow source=multi["registered:authz","registered:authz-namespaces"]+ 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-rbacdiff --git a/libs/fleet/backend/auth/testdata/orch-route-plan.txt b/libs/fleet/backend/auth/testdata/orch-route-plan.txtnew file mode 100644index 0000000000..3edb95044f--- /dev/null+++ b/libs/fleet/backend/auth/testdata/orch-route-plan.txt@@ -0,0 +1,8 @@+All+ Leaf query=data.authz_base.allow source=registered:authz-base+ Leaf query=data.authz_orch.allow source=multi["registered:authz","registered:authz-orch"]+ 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-rbacdiff --git a/libs/fleet/backend/auth/testdata/route-authorization-table.txt b/libs/fleet/backend/auth/testdata/route-authorization-table.txtnew file mode 100644index 0000000000..41ad947db2--- /dev/null+++ b/libs/fleet/backend/auth/testdata/route-authorization-table.txt@@ -0,0 +1,3080 @@+/api/billing/portal-session | plain | DELETE | admin-spa = allow+/api/billing/portal-session | plain | DELETE | cua-cli = deny+/api/billing/portal-session | plain | DELETE | dcr-client = deny+/api/billing/portal-session | plain | DELETE | empty-sub = deny+/api/billing/portal-session | plain | DELETE | github-oidc = deny+/api/billing/portal-session | plain | DELETE | oauth2-proxy = deny+/api/billing/portal-session | plain | DELETE | per-key-other-ns = deny+/api/billing/portal-session | plain | DELETE | per-key-owned-ns = deny+/api/billing/portal-session | plain | DELETE | spa = allow+/api/billing/portal-session | plain | DELETE | user-key = deny+/api/billing/portal-session | plain | DELETE | user-key-verified = deny+/api/billing/portal-session | plain | GET | admin-spa = allow+/api/billing/portal-session | plain | GET | cua-cli = deny+/api/billing/portal-session | plain | GET | dcr-client = deny+/api/billing/portal-session | plain | GET | empty-sub = deny+/api/billing/portal-session | plain | GET | github-oidc = deny+/api/billing/portal-session | plain | GET | oauth2-proxy = deny+/api/billing/portal-session | plain | GET | per-key-other-ns = deny+/api/billing/portal-session | plain | GET | per-key-owned-ns = deny+/api/billing/portal-session | plain | GET | spa = allow+/api/billing/portal-session | plain | GET | user-key = deny+/api/billing/portal-session | plain | GET | user-key-verified = deny+/api/billing/portal-session | plain | PATCH | admin-spa = allow+/api/billing/portal-session | plain | PATCH | cua-cli = deny+/api/billing/portal-session | plain | PATCH | dcr-client = deny+/api/billing/portal-session | plain | PATCH | empty-sub = deny+/api/billing/portal-session | plain | PATCH | github-oidc = deny+/api/billing/portal-session | plain | PATCH | oauth2-proxy = deny+/api/billing/portal-session | plain | PATCH | per-key-other-ns = deny+/api/billing/portal-session | plain | PATCH | per-key-owned-ns = deny+/api/billing/portal-session | plain | PATCH | spa = allow+/api/billing/portal-session | plain | PATCH | user-key = deny+/api/billing/portal-session | plain | PATCH | user-key-verified = deny+/api/billing/portal-session | plain | POST | admin-spa = allow+/api/billing/portal-session | plain | POST | cua-cli = deny+/api/billing/portal-session | plain | POST | dcr-client = deny+/api/billing/portal-session | plain | POST | empty-sub = deny+/api/billing/portal-session | plain | POST | github-oidc = deny+/api/billing/portal-session | plain | POST | oauth2-proxy = deny+/api/billing/portal-session | plain | POST | per-key-other-ns = deny+/api/billing/portal-session | plain | POST | per-key-owned-ns = deny+/api/billing/portal-session | plain | POST | spa = allow+/api/billing/portal-session | plain | POST | user-key = deny+/api/billing/portal-session | plain | POST | user-key-verified = deny+/api/billing/portal-session | plain | QUERY | admin-spa = allow+/api/billing/portal-session | plain | QUERY | cua-cli = deny+/api/billing/portal-session | plain | QUERY | dcr-client = deny+/api/billing/portal-session | plain | QUERY | empty-sub = deny+/api/billing/portal-session | plain | QUERY | github-oidc = deny+/api/billing/portal-session | plain | QUERY | oauth2-proxy = deny+/api/billing/portal-session | plain | QUERY | per-key-other-ns = deny+/api/billing/portal-session | plain | QUERY | per-key-owned-ns = deny+/api/billing/portal-session | plain | QUERY | spa = allow+/api/billing/portal-session | plain | QUERY | user-key = deny+/api/billing/portal-session | plain | QUERY | user-key-verified = deny+/api/billing/setup-session | plain | DELETE | admin-spa = allow+/api/billing/setup-session | plain | DELETE | cua-cli = deny+/api/billing/setup-session | plain | DELETE | dcr-client = deny+/api/billing/setup-session | plain | DELETE | empty-sub = deny+/api/billing/setup-session | plain | DELETE | github-oidc = deny+/api/billing/setup-session | plain | DELETE | oauth2-proxy = deny+/api/billing/setup-session | plain | DELETE | per-key-other-ns = deny+/api/billing/setup-session | plain | DELETE | per-key-owned-ns = deny+/api/billing/setup-session | plain | DELETE | spa = allow+/api/billing/setup-session | plain | DELETE | user-key = deny+/api/billing/setup-session | plain | DELETE | user-key-verified = deny+/api/billing/setup-session | plain | GET | admin-spa = allow+/api/billing/setup-session | plain | GET | cua-cli = deny+/api/billing/setup-session | plain | GET | dcr-client = deny+/api/billing/setup-session | plain | GET | empty-sub = deny+/api/billing/setup-session | plain | GET | github-oidc = deny+/api/billing/setup-session | plain | GET | oauth2-proxy = deny+/api/billing/setup-session | plain | GET | per-key-other-ns = deny+/api/billing/setup-session | plain | GET | per-key-owned-ns = deny+/api/billing/setup-session | plain | GET | spa = allow+/api/billing/setup-session | plain | GET | user-key = deny+/api/billing/setup-session | plain | GET | user-key-verified = deny+/api/billing/setup-session | plain | PATCH | admin-spa = allow+/api/billing/setup-session | plain | PATCH | cua-cli = deny+/api/billing/setup-session | plain | PATCH | dcr-client = deny+/api/billing/setup-session | plain | PATCH | empty-sub = deny+/api/billing/setup-session | plain | PATCH | github-oidc = deny+/api/billing/setup-session | plain | PATCH | oauth2-proxy = deny+/api/billing/setup-session | plain | PATCH | per-key-other-ns = deny+/api/billing/setup-session | plain | PATCH | per-key-owned-ns = deny+/api/billing/setup-session | plain | PATCH | spa = allow+/api/billing/setup-session | plain | PATCH | user-key = deny+/api/billing/setup-session | plain | PATCH | user-key-verified = deny+/api/billing/setup-session | plain | POST | admin-spa = allow+/api/billing/setup-session | plain | POST | cua-cli = deny+/api/billing/setup-session | plain | POST | dcr-client = deny+/api/billing/setup-session | plain | POST | empty-sub = deny+/api/billing/setup-session | plain | POST | github-oidc = deny+/api/billing/setup-session | plain | POST | oauth2-proxy = deny+/api/billing/setup-session | plain | POST | per-key-other-ns = deny+/api/billing/setup-session | plain | POST | per-key-owned-ns = deny+/api/billing/setup-session | plain | POST | spa = allow+/api/billing/setup-session | plain | POST | user-key = deny+/api/billing/setup-session | plain | POST | user-key-verified = deny+/api/billing/setup-session | plain | QUERY | admin-spa = allow+/api/billing/setup-session | plain | QUERY | cua-cli = deny+/api/billing/setup-session | plain | QUERY | dcr-client = deny+/api/billing/setup-session | plain | QUERY | empty-sub = deny+/api/billing/setup-session | plain | QUERY | github-oidc = deny+/api/billing/setup-session | plain | QUERY | oauth2-proxy = deny+/api/billing/setup-session | plain | QUERY | per-key-other-ns = deny+/api/billing/setup-session | plain | QUERY | per-key-owned-ns = deny+/api/billing/setup-session | plain | QUERY | spa = allow+/api/billing/setup-session | plain | QUERY | user-key = deny+/api/billing/setup-session | plain | QUERY | user-key-verified = deny+/api/billing/summary | plain | DELETE | admin-spa = allow+/api/billing/summary | plain | DELETE | cua-cli = deny+/api/billing/summary | plain | DELETE | dcr-client = deny+/api/billing/summary | plain | DELETE | empty-sub = deny+/api/billing/summary | plain | DELETE | github-oidc = deny+/api/billing/summary | plain | DELETE | oauth2-proxy = deny+/api/billing/summary | plain | DELETE | per-key-other-ns = deny+/api/billing/summary | plain | DELETE | per-key-owned-ns = deny+/api/billing/summary | plain | DELETE | spa = allow+/api/billing/summary | plain | DELETE | user-key = deny+/api/billing/summary | plain | DELETE | user-key-verified = deny+/api/billing/summary | plain | GET | admin-spa = allow+/api/billing/summary | plain | GET | cua-cli = deny+/api/billing/summary | plain | GET | dcr-client = deny+/api/billing/summary | plain | GET | empty-sub = deny+/api/billing/summary | plain | GET | github-oidc = deny+/api/billing/summary | plain | GET | oauth2-proxy = deny+/api/billing/summary | plain | GET | per-key-other-ns = deny+/api/billing/summary | plain | GET | per-key-owned-ns = deny+/api/billing/summary | plain | GET | spa = allow+/api/billing/summary | plain | GET | user-key = deny+/api/billing/summary | plain | GET | user-key-verified = deny+/api/billing/summary | plain | PATCH | admin-spa = allow+/api/billing/summary | plain | PATCH | cua-cli = deny+/api/billing/summary | plain | PATCH | dcr-client = deny+/api/billing/summary | plain | PATCH | empty-sub = deny+/api/billing/summary | plain | PATCH | github-oidc = deny+/api/billing/summary | plain | PATCH | oauth2-proxy = deny+/api/billing/summary | plain | PATCH | per-key-other-ns = deny+/api/billing/summary | plain | PATCH | per-key-owned-ns = deny+/api/billing/summary | plain | PATCH | spa = allow+/api/billing/summary | plain | PATCH | user-key = deny+/api/billing/summary | plain | PATCH | user-key-verified = deny+/api/billing/summary | plain | POST | admin-spa = allow+/api/billing/summary | plain | POST | cua-cli = deny+/api/billing/summary | plain | POST | dcr-client = deny+/api/billing/summary | plain | POST | empty-sub = deny+/api/billing/summary | plain | POST | github-oidc = deny+/api/billing/summary | plain | POST | oauth2-proxy = deny+/api/billing/summary | plain | POST | per-key-other-ns = deny+/api/billing/summary | plain | POST | per-key-owned-ns = deny+/api/billing/summary | plain | POST | spa = allow+/api/billing/summary | plain | POST | user-key = deny+/api/billing/summary | plain | POST | user-key-verified = deny+/api/billing/summary | plain | QUERY | admin-spa = allow+/api/billing/summary | plain | QUERY | cua-cli = deny+/api/billing/summary | plain | QUERY | dcr-client = deny+/api/billing/summary | plain | QUERY | empty-sub = deny+/api/billing/summary | plain | QUERY | github-oidc = deny+/api/billing/summary | plain | QUERY | oauth2-proxy = deny+/api/billing/summary | plain | QUERY | per-key-other-ns = deny+/api/billing/summary | plain | QUERY | per-key-owned-ns = deny+/api/billing/summary | plain | QUERY | spa = allow+/api/billing/summary | plain | QUERY | user-key = deny+/api/billing/summary | plain | QUERY | user-key-verified = deny+/api/config | plain | DELETE | admin-spa = allow+/api/config | plain | DELETE | cua-cli = allow+/api/config | plain | DELETE | dcr-client = deny+/api/config | plain | DELETE | empty-sub = deny+/api/config | plain | DELETE | github-oidc = deny+/api/config | plain | DELETE | oauth2-proxy = deny+/api/config | plain | DELETE | per-key-other-ns = deny+/api/config | plain | DELETE | per-key-owned-ns = deny+/api/config | plain | DELETE | spa = allow+/api/config | plain | DELETE | user-key = allow+/api/config | plain | DELETE | user-key-verified = allow+/api/config | plain | GET | admin-spa = allow+/api/config | plain | GET | cua-cli = allow+/api/config | plain | GET | dcr-client = deny+/api/config | plain | GET | empty-sub = deny+/api/config | plain | GET | github-oidc = deny+/api/config | plain | GET | oauth2-proxy = deny+/api/config | plain | GET | per-key-other-ns = deny+/api/config | plain | GET | per-key-owned-ns = deny+/api/config | plain | GET | spa = allow+/api/config | plain | GET | user-key = allow+/api/config | plain | GET | user-key-verified = allow+/api/config | plain | PATCH | admin-spa = allow+/api/config | plain | PATCH | cua-cli = allow+/api/config | plain | PATCH | dcr-client = deny+/api/config | plain | PATCH | empty-sub = deny+/api/config | plain | PATCH | github-oidc = deny+/api/config | plain | PATCH | oauth2-proxy = deny+/api/config | plain | PATCH | per-key-other-ns = deny+/api/config | plain | PATCH | per-key-owned-ns = deny+/api/config | plain | PATCH | spa = allow+/api/config | plain | PATCH | user-key = allow+/api/config | plain | PATCH | user-key-verified = allow+/api/config | plain | POST | admin-spa = allow+/api/config | plain | POST | cua-cli = allow+/api/config | plain | POST | dcr-client = deny+/api/config | plain | POST | empty-sub = deny+/api/config | plain | POST | github-oidc = deny+/api/config | plain | POST | oauth2-proxy = deny+/api/config | plain | POST | per-key-other-ns = deny+/api/config | plain | POST | per-key-owned-ns = deny+/api/config | plain | POST | spa = allow+/api/config | plain | POST | user-key = allow+/api/config | plain | POST | user-key-verified = allow+/api/config | plain | QUERY | admin-spa = allow+/api/config | plain | QUERY | cua-cli = allow+/api/config | plain | QUERY | dcr-client = deny+/api/config | plain | QUERY | empty-sub = deny+/api/config | plain | QUERY | github-oidc = deny+/api/config | plain | QUERY | oauth2-proxy = deny+/api/config | plain | QUERY | per-key-other-ns = deny+/api/config | plain | QUERY | per-key-owned-ns = deny+/api/config | plain | QUERY | spa = allow+/api/config | plain | QUERY | user-key = allow+/api/config | plain | QUERY | user-key-verified = allow+/api/github-trust-policies | plain | DELETE | admin-spa = allow+/api/github-trust-policies | plain | DELETE | cua-cli = allow+/api/github-trust-policies | plain | DELETE | dcr-client = deny+/api/github-trust-policies | plain | DELETE | empty-sub = deny+/api/github-trust-policies | plain | DELETE | github-oidc = deny+/api/github-trust-policies | plain | DELETE | oauth2-proxy = deny+/api/github-trust-policies | plain | DELETE | per-key-other-ns = deny+/api/github-trust-policies | plain | DELETE | per-key-owned-ns = deny+/api/github-trust-policies | plain | DELETE | spa = allow+/api/github-trust-policies | plain | DELETE | user-key = deny+/api/github-trust-policies | plain | DELETE | user-key-verified = allow+/api/github-trust-policies | plain | GET | admin-spa = allow+/api/github-trust-policies | plain | GET | cua-cli = allow+/api/github-trust-policies | plain | GET | dcr-client = deny+/api/github-trust-policies | plain | GET | empty-sub = deny+/api/github-trust-policies | plain | GET | github-oidc = deny+/api/github-trust-policies | plain | GET | oauth2-proxy = deny+/api/github-trust-policies | plain | GET | per-key-other-ns = deny+/api/github-trust-policies | plain | GET | per-key-owned-ns = deny+/api/github-trust-policies | plain | GET | spa = allow+/api/github-trust-policies | plain | GET | user-key = deny+/api/github-trust-policies | plain | GET | user-key-verified = allow+/api/github-trust-policies | plain | PATCH | admin-spa = allow+/api/github-trust-policies | plain | PATCH | cua-cli = allow+/api/github-trust-policies | plain | PATCH | dcr-client = deny+/api/github-trust-policies | plain | PATCH | empty-sub = deny+/api/github-trust-policies | plain | PATCH | github-oidc = deny+/api/github-trust-policies | plain | PATCH | oauth2-proxy = deny+/api/github-trust-policies | plain | PATCH | per-key-other-ns = deny+/api/github-trust-policies | plain | PATCH | per-key-owned-ns = deny+/api/github-trust-policies | plain | PATCH | spa = allow+/api/github-trust-policies | plain | PATCH | user-key = deny+/api/github-trust-policies | plain | PATCH | user-key-verified = allow+/api/github-trust-policies | plain | POST | admin-spa = allow+/api/github-trust-policies | plain | POST | cua-cli = allow+/api/github-trust-policies | plain | POST | dcr-client = deny+/api/github-trust-policies | plain | POST | empty-sub = deny+/api/github-trust-policies | plain | POST | github-oidc = deny+/api/github-trust-policies | plain | POST | oauth2-proxy = deny+/api/github-trust-policies | plain | POST | per-key-other-ns = deny+/api/github-trust-policies | plain | POST | per-key-owned-ns = deny+/api/github-trust-policies | plain | POST | spa = allow+/api/github-trust-policies | plain | POST | user-key = deny+/api/github-trust-policies | plain | POST | user-key-verified = allow+/api/github-trust-policies | plain | QUERY | admin-spa = allow+/api/github-trust-policies | plain | QUERY | cua-cli = allow+/api/github-trust-policies | plain | QUERY | dcr-client = deny+/api/github-trust-policies | plain | QUERY | empty-sub = deny+/api/github-trust-policies | plain | QUERY | github-oidc = deny+/api/github-trust-policies | plain | QUERY | oauth2-proxy = deny+/api/github-trust-policies | plain | QUERY | per-key-other-ns = deny+/api/github-trust-policies | plain | QUERY | per-key-owned-ns = deny+/api/github-trust-policies | plain | QUERY | spa = allow+/api/github-trust-policies | plain | QUERY | user-key = deny+/api/github-trust-policies | plain | QUERY | user-key-verified = allow+/api/github-trust-policies/{id} | id | DELETE | admin-spa = allow+/api/github-trust-policies/{id} | id | DELETE | cua-cli = allow+/api/github-trust-policies/{id} | id | DELETE | dcr-client = deny+/api/github-trust-policies/{id} | id | DELETE | empty-sub = deny+/api/github-trust-policies/{id} | id | DELETE | github-oidc = deny+/api/github-trust-policies/{id} | id | DELETE | oauth2-proxy = deny+/api/github-trust-policies/{id} | id | DELETE | per-key-other-ns = deny+/api/github-trust-policies/{id} | id | DELETE | per-key-owned-ns = deny+/api/github-trust-policies/{id} | id | DELETE | spa = allow+/api/github-trust-policies/{id} | id | DELETE | user-key = deny+/api/github-trust-policies/{id} | id | DELETE | user-key-verified = allow+/api/github-trust-policies/{id} | id | GET | admin-spa = allow+/api/github-trust-policies/{id} | id | GET | cua-cli = allow+/api/github-trust-policies/{id} | id | GET | dcr-client = deny+/api/github-trust-policies/{id} | id | GET | empty-sub = deny+/api/github-trust-policies/{id} | id | GET | github-oidc = deny+/api/github-trust-policies/{id} | id | GET | oauth2-proxy = deny+/api/github-trust-policies/{id} | id | GET | per-key-other-ns = deny+/api/github-trust-policies/{id} | id | GET | per-key-owned-ns = deny+/api/github-trust-policies/{id} | id | GET | spa = allow+/api/github-trust-policies/{id} | id | GET | user-key = deny+/api/github-trust-policies/{id} | id | GET | user-key-verified = allow+/api/github-trust-policies/{id} | id | PATCH | admin-spa = allow+/api/github-trust-policies/{id} | id | PATCH | cua-cli = allow+/api/github-trust-policies/{id} | id | PATCH | dcr-client = deny+/api/github-trust-policies/{id} | id | PATCH | empty-sub = deny+/api/github-trust-policies/{id} | id | PATCH | github-oidc = deny+/api/github-trust-policies/{id} | id | PATCH | oauth2-proxy = deny+/api/github-trust-policies/{id} | id | PATCH | per-key-other-ns = deny+/api/github-trust-policies/{id} | id | PATCH | per-key-owned-ns = deny+/api/github-trust-policies/{id} | id | PATCH | spa = allow+/api/github-trust-policies/{id} | id | PATCH | user-key = deny+/api/github-trust-policies/{id} | id | PATCH | user-key-verified = allow+/api/github-trust-policies/{id} | id | POST | admin-spa = allow+/api/github-trust-policies/{id} | id | POST | cua-cli = allow+/api/github-trust-policies/{id} | id | POST | dcr-client = deny+/api/github-trust-policies/{id} | id | POST | empty-sub = deny+/api/github-trust-policies/{id} | id | POST | github-oidc = deny+/api/github-trust-policies/{id} | id | POST | oauth2-proxy = deny+/api/github-trust-policies/{id} | id | POST | per-key-other-ns = deny+/api/github-trust-policies/{id} | id | POST | per-key-owned-ns = deny+/api/github-trust-policies/{id} | id | POST | spa = allow+/api/github-trust-policies/{id} | id | POST | user-key = deny+/api/github-trust-policies/{id} | id | POST | user-key-verified = allow+/api/github-trust-policies/{id} | id | QUERY | admin-spa = allow+/api/github-trust-policies/{id} | id | QUERY | cua-cli = allow+/api/github-trust-policies/{id} | id | QUERY | dcr-client = deny+/api/github-trust-policies/{id} | id | QUERY | empty-sub = deny+/api/github-trust-policies/{id} | id | QUERY | github-oidc = deny+/api/github-trust-policies/{id} | id | QUERY | oauth2-proxy = deny+/api/github-trust-policies/{id} | id | QUERY | per-key-other-ns = deny+/api/github-trust-policies/{id} | id | QUERY | per-key-owned-ns = deny+/api/github-trust-policies/{id} | id | QUERY | spa = allow+/api/github-trust-policies/{id} | id | QUERY | user-key = deny+/api/github-trust-policies/{id} | id | QUERY | user-key-verified = allow+/api/k8s/{path...} | capsule-tenants | DELETE | admin-spa = deny+/api/k8s/{path...} | capsule-tenants | DELETE | cua-cli = deny+/api/k8s/{path...} | capsule-tenants | DELETE | dcr-client = deny+/api/k8s/{path...} | capsule-tenants | DELETE | empty-sub = deny+/api/k8s/{path...} | capsule-tenants | DELETE | github-oidc = deny+/api/k8s/{path...} | capsule-tenants | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | capsule-tenants | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | capsule-tenants | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | capsule-tenants | DELETE | spa = deny+/api/k8s/{path...} | capsule-tenants | DELETE | user-key = deny+/api/k8s/{path...} | capsule-tenants | DELETE | user-key-verified = deny+/api/k8s/{path...} | capsule-tenants | GET | admin-spa = deny+/api/k8s/{path...} | capsule-tenants | GET | cua-cli = deny+/api/k8s/{path...} | capsule-tenants | GET | dcr-client = deny+/api/k8s/{path...} | capsule-tenants | GET | empty-sub = deny+/api/k8s/{path...} | capsule-tenants | GET | github-oidc = deny+/api/k8s/{path...} | capsule-tenants | GET | oauth2-proxy = deny+/api/k8s/{path...} | capsule-tenants | GET | per-key-other-ns = deny+/api/k8s/{path...} | capsule-tenants | GET | per-key-owned-ns = deny+/api/k8s/{path...} | capsule-tenants | GET | spa = deny+/api/k8s/{path...} | capsule-tenants | GET | user-key = deny+/api/k8s/{path...} | capsule-tenants | GET | user-key-verified = deny+/api/k8s/{path...} | capsule-tenants | PATCH | admin-spa = deny+/api/k8s/{path...} | capsule-tenants | PATCH | cua-cli = deny+/api/k8s/{path...} | capsule-tenants | PATCH | dcr-client = deny+/api/k8s/{path...} | capsule-tenants | PATCH | empty-sub = deny+/api/k8s/{path...} | capsule-tenants | PATCH | github-oidc = deny+/api/k8s/{path...} | capsule-tenants | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | capsule-tenants | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | capsule-tenants | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | capsule-tenants | PATCH | spa = deny+/api/k8s/{path...} | capsule-tenants | PATCH | user-key = deny+/api/k8s/{path...} | capsule-tenants | PATCH | user-key-verified = deny+/api/k8s/{path...} | capsule-tenants | POST | admin-spa = deny+/api/k8s/{path...} | capsule-tenants | POST | cua-cli = deny+/api/k8s/{path...} | capsule-tenants | POST | dcr-client = deny+/api/k8s/{path...} | capsule-tenants | POST | empty-sub = deny+/api/k8s/{path...} | capsule-tenants | POST | github-oidc = deny+/api/k8s/{path...} | capsule-tenants | POST | oauth2-proxy = deny+/api/k8s/{path...} | capsule-tenants | POST | per-key-other-ns = deny+/api/k8s/{path...} | capsule-tenants | POST | per-key-owned-ns = deny+/api/k8s/{path...} | capsule-tenants | POST | spa = deny+/api/k8s/{path...} | capsule-tenants | POST | user-key = deny+/api/k8s/{path...} | capsule-tenants | POST | user-key-verified = deny+/api/k8s/{path...} | capsule-tenants | QUERY | admin-spa = deny+/api/k8s/{path...} | capsule-tenants | QUERY | cua-cli = deny+/api/k8s/{path...} | capsule-tenants | QUERY | dcr-client = deny+/api/k8s/{path...} | capsule-tenants | QUERY | empty-sub = deny+/api/k8s/{path...} | capsule-tenants | QUERY | github-oidc = deny+/api/k8s/{path...} | capsule-tenants | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | capsule-tenants | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | capsule-tenants | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | capsule-tenants | QUERY | spa = deny+/api/k8s/{path...} | capsule-tenants | QUERY | user-key = deny+/api/k8s/{path...} | capsule-tenants | QUERY | user-key-verified = deny+/api/k8s/{path...} | claim-item | DELETE | admin-spa = allow+/api/k8s/{path...} | claim-item | DELETE | cua-cli = allow+/api/k8s/{path...} | claim-item | DELETE | dcr-client = deny+/api/k8s/{path...} | claim-item | DELETE | empty-sub = deny+/api/k8s/{path...} | claim-item | DELETE | github-oidc = allow+/api/k8s/{path...} | claim-item | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | claim-item | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | claim-item | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | claim-item | DELETE | spa = allow+/api/k8s/{path...} | claim-item | DELETE | user-key = allow+/api/k8s/{path...} | claim-item | DELETE | user-key-verified = allow+/api/k8s/{path...} | claim-item | GET | admin-spa = allow+/api/k8s/{path...} | claim-item | GET | cua-cli = allow+/api/k8s/{path...} | claim-item | GET | dcr-client = deny+/api/k8s/{path...} | claim-item | GET | empty-sub = deny+/api/k8s/{path...} | claim-item | GET | github-oidc = allow+/api/k8s/{path...} | claim-item | GET | oauth2-proxy = deny+/api/k8s/{path...} | claim-item | GET | per-key-other-ns = deny+/api/k8s/{path...} | claim-item | GET | per-key-owned-ns = deny+/api/k8s/{path...} | claim-item | GET | spa = allow+/api/k8s/{path...} | claim-item | GET | user-key = allow+/api/k8s/{path...} | claim-item | GET | user-key-verified = allow+/api/k8s/{path...} | claim-item | PATCH | admin-spa = allow+/api/k8s/{path...} | claim-item | PATCH | cua-cli = allow+/api/k8s/{path...} | claim-item | PATCH | dcr-client = deny+/api/k8s/{path...} | claim-item | PATCH | empty-sub = deny+/api/k8s/{path...} | claim-item | PATCH | github-oidc = allow+/api/k8s/{path...} | claim-item | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | claim-item | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | claim-item | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | claim-item | PATCH | spa = allow+/api/k8s/{path...} | claim-item | PATCH | user-key = allow+/api/k8s/{path...} | claim-item | PATCH | user-key-verified = allow+/api/k8s/{path...} | claim-item | POST | admin-spa = deny+/api/k8s/{path...} | claim-item | POST | cua-cli = deny+/api/k8s/{path...} | claim-item | POST | dcr-client = deny+/api/k8s/{path...} | claim-item | POST | empty-sub = deny+/api/k8s/{path...} | claim-item | POST | github-oidc = deny+/api/k8s/{path...} | claim-item | POST | oauth2-proxy = deny+/api/k8s/{path...} | claim-item | POST | per-key-other-ns = deny+/api/k8s/{path...} | claim-item | POST | per-key-owned-ns = deny+/api/k8s/{path...} | claim-item | POST | spa = deny+/api/k8s/{path...} | claim-item | POST | user-key = deny+/api/k8s/{path...} | claim-item | POST | user-key-verified = deny+/api/k8s/{path...} | claim-item | QUERY | admin-spa = deny+/api/k8s/{path...} | claim-item | QUERY | cua-cli = deny+/api/k8s/{path...} | claim-item | QUERY | dcr-client = deny+/api/k8s/{path...} | claim-item | QUERY | empty-sub = deny+/api/k8s/{path...} | claim-item | QUERY | github-oidc = deny+/api/k8s/{path...} | claim-item | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | claim-item | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | claim-item | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | claim-item | QUERY | spa = deny+/api/k8s/{path...} | claim-item | QUERY | user-key = deny+/api/k8s/{path...} | claim-item | QUERY | user-key-verified = deny+/api/k8s/{path...} | claim-status | DELETE | admin-spa = deny+/api/k8s/{path...} | claim-status | DELETE | cua-cli = deny+/api/k8s/{path...} | claim-status | DELETE | dcr-client = deny+/api/k8s/{path...} | claim-status | DELETE | empty-sub = deny+/api/k8s/{path...} | claim-status | DELETE | github-oidc = deny+/api/k8s/{path...} | claim-status | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | claim-status | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | claim-status | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | claim-status | DELETE | spa = deny+/api/k8s/{path...} | claim-status | DELETE | user-key = deny+/api/k8s/{path...} | claim-status | DELETE | user-key-verified = deny+/api/k8s/{path...} | claim-status | GET | admin-spa = deny+/api/k8s/{path...} | claim-status | GET | cua-cli = deny+/api/k8s/{path...} | claim-status | GET | dcr-client = deny+/api/k8s/{path...} | claim-status | GET | empty-sub = deny+/api/k8s/{path...} | claim-status | GET | github-oidc = deny+/api/k8s/{path...} | claim-status | GET | oauth2-proxy = deny+/api/k8s/{path...} | claim-status | GET | per-key-other-ns = deny+/api/k8s/{path...} | claim-status | GET | per-key-owned-ns = deny+/api/k8s/{path...} | claim-status | GET | spa = deny+/api/k8s/{path...} | claim-status | GET | user-key = deny+/api/k8s/{path...} | claim-status | GET | user-key-verified = deny+/api/k8s/{path...} | claim-status | PATCH | admin-spa = allow+/api/k8s/{path...} | claim-status | PATCH | cua-cli = allow+/api/k8s/{path...} | claim-status | PATCH | dcr-client = deny+/api/k8s/{path...} | claim-status | PATCH | empty-sub = deny+/api/k8s/{path...} | claim-status | PATCH | github-oidc = deny+/api/k8s/{path...} | claim-status | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | claim-status | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | claim-status | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | claim-status | PATCH | spa = allow+/api/k8s/{path...} | claim-status | PATCH | user-key = allow+/api/k8s/{path...} | claim-status | PATCH | user-key-verified = allow+/api/k8s/{path...} | claim-status | POST | admin-spa = deny+/api/k8s/{path...} | claim-status | POST | cua-cli = deny+/api/k8s/{path...} | claim-status | POST | dcr-client = deny+/api/k8s/{path...} | claim-status | POST | empty-sub = deny+/api/k8s/{path...} | claim-status | POST | github-oidc = deny+/api/k8s/{path...} | claim-status | POST | oauth2-proxy = deny+/api/k8s/{path...} | claim-status | POST | per-key-other-ns = deny+/api/k8s/{path...} | claim-status | POST | per-key-owned-ns = deny+/api/k8s/{path...} | claim-status | POST | spa = deny+/api/k8s/{path...} | claim-status | POST | user-key = deny+/api/k8s/{path...} | claim-status | POST | user-key-verified = deny+/api/k8s/{path...} | claim-status | QUERY | admin-spa = deny+/api/k8s/{path...} | claim-status | QUERY | cua-cli = deny+/api/k8s/{path...} | claim-status | QUERY | dcr-client = deny+/api/k8s/{path...} | claim-status | QUERY | empty-sub = deny+/api/k8s/{path...} | claim-status | QUERY | github-oidc = deny+/api/k8s/{path...} | claim-status | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | claim-status | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | claim-status | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | claim-status | QUERY | spa = deny+/api/k8s/{path...} | claim-status | QUERY | user-key = deny+/api/k8s/{path...} | claim-status | QUERY | user-key-verified = deny+/api/k8s/{path...} | cluster-claims | DELETE | admin-spa = deny+/api/k8s/{path...} | cluster-claims | DELETE | cua-cli = deny+/api/k8s/{path...} | cluster-claims | DELETE | dcr-client = deny+/api/k8s/{path...} | cluster-claims | DELETE | empty-sub = deny+/api/k8s/{path...} | cluster-claims | DELETE | github-oidc = deny+/api/k8s/{path...} | cluster-claims | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | cluster-claims | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | cluster-claims | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-claims | DELETE | spa = deny+/api/k8s/{path...} | cluster-claims | DELETE | user-key = deny+/api/k8s/{path...} | cluster-claims | DELETE | user-key-verified = deny+/api/k8s/{path...} | cluster-claims | GET | admin-spa = deny+/api/k8s/{path...} | cluster-claims | GET | cua-cli = deny+/api/k8s/{path...} | cluster-claims | GET | dcr-client = deny+/api/k8s/{path...} | cluster-claims | GET | empty-sub = deny+/api/k8s/{path...} | cluster-claims | GET | github-oidc = deny+/api/k8s/{path...} | cluster-claims | GET | oauth2-proxy = deny+/api/k8s/{path...} | cluster-claims | GET | per-key-other-ns = deny+/api/k8s/{path...} | cluster-claims | GET | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-claims | GET | spa = deny+/api/k8s/{path...} | cluster-claims | GET | user-key = deny+/api/k8s/{path...} | cluster-claims | GET | user-key-verified = deny+/api/k8s/{path...} | cluster-claims | PATCH | admin-spa = deny+/api/k8s/{path...} | cluster-claims | PATCH | cua-cli = deny+/api/k8s/{path...} | cluster-claims | PATCH | dcr-client = deny+/api/k8s/{path...} | cluster-claims | PATCH | empty-sub = deny+/api/k8s/{path...} | cluster-claims | PATCH | github-oidc = deny+/api/k8s/{path...} | cluster-claims | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | cluster-claims | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | cluster-claims | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-claims | PATCH | spa = deny+/api/k8s/{path...} | cluster-claims | PATCH | user-key = deny+/api/k8s/{path...} | cluster-claims | PATCH | user-key-verified = deny+/api/k8s/{path...} | cluster-claims | POST | admin-spa = deny+/api/k8s/{path...} | cluster-claims | POST | cua-cli = deny+/api/k8s/{path...} | cluster-claims | POST | dcr-client = deny+/api/k8s/{path...} | cluster-claims | POST | empty-sub = deny+/api/k8s/{path...} | cluster-claims | POST | github-oidc = deny+/api/k8s/{path...} | cluster-claims | POST | oauth2-proxy = deny+/api/k8s/{path...} | cluster-claims | POST | per-key-other-ns = deny+/api/k8s/{path...} | cluster-claims | POST | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-claims | POST | spa = deny+/api/k8s/{path...} | cluster-claims | POST | user-key = deny+/api/k8s/{path...} | cluster-claims | POST | user-key-verified = deny+/api/k8s/{path...} | cluster-claims | QUERY | admin-spa = deny+/api/k8s/{path...} | cluster-claims | QUERY | cua-cli = deny+/api/k8s/{path...} | cluster-claims | QUERY | dcr-client = deny+/api/k8s/{path...} | cluster-claims | QUERY | empty-sub = deny+/api/k8s/{path...} | cluster-claims | QUERY | github-oidc = deny+/api/k8s/{path...} | cluster-claims | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | cluster-claims | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | cluster-claims | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-claims | QUERY | spa = deny+/api/k8s/{path...} | cluster-claims | QUERY | user-key = deny+/api/k8s/{path...} | cluster-claims | QUERY | user-key-verified = deny+/api/k8s/{path...} | cluster-events | DELETE | admin-spa = deny+/api/k8s/{path...} | cluster-events | DELETE | cua-cli = deny+/api/k8s/{path...} | cluster-events | DELETE | dcr-client = deny+/api/k8s/{path...} | cluster-events | DELETE | empty-sub = deny+/api/k8s/{path...} | cluster-events | DELETE | github-oidc = deny+/api/k8s/{path...} | cluster-events | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | cluster-events | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | cluster-events | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-events | DELETE | spa = deny+/api/k8s/{path...} | cluster-events | DELETE | user-key = deny+/api/k8s/{path...} | cluster-events | DELETE | user-key-verified = deny+/api/k8s/{path...} | cluster-events | GET | admin-spa = deny+/api/k8s/{path...} | cluster-events | GET | cua-cli = deny+/api/k8s/{path...} | cluster-events | GET | dcr-client = deny+/api/k8s/{path...} | cluster-events | GET | empty-sub = deny+/api/k8s/{path...} | cluster-events | GET | github-oidc = deny+/api/k8s/{path...} | cluster-events | GET | oauth2-proxy = deny+/api/k8s/{path...} | cluster-events | GET | per-key-other-ns = deny+/api/k8s/{path...} | cluster-events | GET | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-events | GET | spa = deny+/api/k8s/{path...} | cluster-events | GET | user-key = deny+/api/k8s/{path...} | cluster-events | GET | user-key-verified = deny+/api/k8s/{path...} | cluster-events | PATCH | admin-spa = deny+/api/k8s/{path...} | cluster-events | PATCH | cua-cli = deny+/api/k8s/{path...} | cluster-events | PATCH | dcr-client = deny+/api/k8s/{path...} | cluster-events | PATCH | empty-sub = deny+/api/k8s/{path...} | cluster-events | PATCH | github-oidc = deny+/api/k8s/{path...} | cluster-events | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | cluster-events | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | cluster-events | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-events | PATCH | spa = deny+/api/k8s/{path...} | cluster-events | PATCH | user-key = deny+/api/k8s/{path...} | cluster-events | PATCH | user-key-verified = deny+/api/k8s/{path...} | cluster-events | POST | admin-spa = deny+/api/k8s/{path...} | cluster-events | POST | cua-cli = deny+/api/k8s/{path...} | cluster-events | POST | dcr-client = deny+/api/k8s/{path...} | cluster-events | POST | empty-sub = deny+/api/k8s/{path...} | cluster-events | POST | github-oidc = deny+/api/k8s/{path...} | cluster-events | POST | oauth2-proxy = deny+/api/k8s/{path...} | cluster-events | POST | per-key-other-ns = deny+/api/k8s/{path...} | cluster-events | POST | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-events | POST | spa = deny+/api/k8s/{path...} | cluster-events | POST | user-key = deny+/api/k8s/{path...} | cluster-events | POST | user-key-verified = deny+/api/k8s/{path...} | cluster-events | QUERY | admin-spa = deny+/api/k8s/{path...} | cluster-events | QUERY | cua-cli = deny+/api/k8s/{path...} | cluster-events | QUERY | dcr-client = deny+/api/k8s/{path...} | cluster-events | QUERY | empty-sub = deny+/api/k8s/{path...} | cluster-events | QUERY | github-oidc = deny+/api/k8s/{path...} | cluster-events | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | cluster-events | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | cluster-events | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-events | QUERY | spa = deny+/api/k8s/{path...} | cluster-events | QUERY | user-key = deny+/api/k8s/{path...} | cluster-events | QUERY | user-key-verified = deny+/api/k8s/{path...} | cluster-nodes | DELETE | admin-spa = deny+/api/k8s/{path...} | cluster-nodes | DELETE | cua-cli = deny+/api/k8s/{path...} | cluster-nodes | DELETE | dcr-client = deny+/api/k8s/{path...} | cluster-nodes | DELETE | empty-sub = deny+/api/k8s/{path...} | cluster-nodes | DELETE | github-oidc = deny+/api/k8s/{path...} | cluster-nodes | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | cluster-nodes | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | cluster-nodes | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-nodes | DELETE | spa = deny+/api/k8s/{path...} | cluster-nodes | DELETE | user-key = deny+/api/k8s/{path...} | cluster-nodes | DELETE | user-key-verified = deny+/api/k8s/{path...} | cluster-nodes | GET | admin-spa = deny+/api/k8s/{path...} | cluster-nodes | GET | cua-cli = deny+/api/k8s/{path...} | cluster-nodes | GET | dcr-client = deny+/api/k8s/{path...} | cluster-nodes | GET | empty-sub = deny+/api/k8s/{path...} | cluster-nodes | GET | github-oidc = deny+/api/k8s/{path...} | cluster-nodes | GET | oauth2-proxy = deny+/api/k8s/{path...} | cluster-nodes | GET | per-key-other-ns = deny+/api/k8s/{path...} | cluster-nodes | GET | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-nodes | GET | spa = deny+/api/k8s/{path...} | cluster-nodes | GET | user-key = deny+/api/k8s/{path...} | cluster-nodes | GET | user-key-verified = deny+/api/k8s/{path...} | cluster-nodes | PATCH | admin-spa = deny+/api/k8s/{path...} | cluster-nodes | PATCH | cua-cli = deny+/api/k8s/{path...} | cluster-nodes | PATCH | dcr-client = deny+/api/k8s/{path...} | cluster-nodes | PATCH | empty-sub = deny+/api/k8s/{path...} | cluster-nodes | PATCH | github-oidc = deny+/api/k8s/{path...} | cluster-nodes | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | cluster-nodes | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | cluster-nodes | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-nodes | PATCH | spa = deny+/api/k8s/{path...} | cluster-nodes | PATCH | user-key = deny+/api/k8s/{path...} | cluster-nodes | PATCH | user-key-verified = deny+/api/k8s/{path...} | cluster-nodes | POST | admin-spa = deny+/api/k8s/{path...} | cluster-nodes | POST | cua-cli = deny+/api/k8s/{path...} | cluster-nodes | POST | dcr-client = deny+/api/k8s/{path...} | cluster-nodes | POST | empty-sub = deny+/api/k8s/{path...} | cluster-nodes | POST | github-oidc = deny+/api/k8s/{path...} | cluster-nodes | POST | oauth2-proxy = deny+/api/k8s/{path...} | cluster-nodes | POST | per-key-other-ns = deny+/api/k8s/{path...} | cluster-nodes | POST | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-nodes | POST | spa = deny+/api/k8s/{path...} | cluster-nodes | POST | user-key = deny+/api/k8s/{path...} | cluster-nodes | POST | user-key-verified = deny+/api/k8s/{path...} | cluster-nodes | QUERY | admin-spa = deny+/api/k8s/{path...} | cluster-nodes | QUERY | cua-cli = deny+/api/k8s/{path...} | cluster-nodes | QUERY | dcr-client = deny+/api/k8s/{path...} | cluster-nodes | QUERY | empty-sub = deny+/api/k8s/{path...} | cluster-nodes | QUERY | github-oidc = deny+/api/k8s/{path...} | cluster-nodes | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | cluster-nodes | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | cluster-nodes | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-nodes | QUERY | spa = deny+/api/k8s/{path...} | cluster-nodes | QUERY | user-key = deny+/api/k8s/{path...} | cluster-nodes | QUERY | user-key-verified = deny+/api/k8s/{path...} | cluster-pods | DELETE | admin-spa = deny+/api/k8s/{path...} | cluster-pods | DELETE | cua-cli = deny+/api/k8s/{path...} | cluster-pods | DELETE | dcr-client = deny+/api/k8s/{path...} | cluster-pods | DELETE | empty-sub = deny+/api/k8s/{path...} | cluster-pods | DELETE | github-oidc = deny+/api/k8s/{path...} | cluster-pods | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | cluster-pods | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | cluster-pods | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-pods | DELETE | spa = deny+/api/k8s/{path...} | cluster-pods | DELETE | user-key = deny+/api/k8s/{path...} | cluster-pods | DELETE | user-key-verified = deny+/api/k8s/{path...} | cluster-pods | GET | admin-spa = deny+/api/k8s/{path...} | cluster-pods | GET | cua-cli = deny+/api/k8s/{path...} | cluster-pods | GET | dcr-client = deny+/api/k8s/{path...} | cluster-pods | GET | empty-sub = deny+/api/k8s/{path...} | cluster-pods | GET | github-oidc = deny+/api/k8s/{path...} | cluster-pods | GET | oauth2-proxy = deny+/api/k8s/{path...} | cluster-pods | GET | per-key-other-ns = deny+/api/k8s/{path...} | cluster-pods | GET | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-pods | GET | spa = deny+/api/k8s/{path...} | cluster-pods | GET | user-key = deny+/api/k8s/{path...} | cluster-pods | GET | user-key-verified = deny+/api/k8s/{path...} | cluster-pods | PATCH | admin-spa = deny+/api/k8s/{path...} | cluster-pods | PATCH | cua-cli = deny+/api/k8s/{path...} | cluster-pods | PATCH | dcr-client = deny+/api/k8s/{path...} | cluster-pods | PATCH | empty-sub = deny+/api/k8s/{path...} | cluster-pods | PATCH | github-oidc = deny+/api/k8s/{path...} | cluster-pods | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | cluster-pods | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | cluster-pods | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-pods | PATCH | spa = deny+/api/k8s/{path...} | cluster-pods | PATCH | user-key = deny+/api/k8s/{path...} | cluster-pods | PATCH | user-key-verified = deny+/api/k8s/{path...} | cluster-pods | POST | admin-spa = deny+/api/k8s/{path...} | cluster-pods | POST | cua-cli = deny+/api/k8s/{path...} | cluster-pods | POST | dcr-client = deny+/api/k8s/{path...} | cluster-pods | POST | empty-sub = deny+/api/k8s/{path...} | cluster-pods | POST | github-oidc = deny+/api/k8s/{path...} | cluster-pods | POST | oauth2-proxy = deny+/api/k8s/{path...} | cluster-pods | POST | per-key-other-ns = deny+/api/k8s/{path...} | cluster-pods | POST | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-pods | POST | spa = deny+/api/k8s/{path...} | cluster-pods | POST | user-key = deny+/api/k8s/{path...} | cluster-pods | POST | user-key-verified = deny+/api/k8s/{path...} | cluster-pods | QUERY | admin-spa = deny+/api/k8s/{path...} | cluster-pods | QUERY | cua-cli = deny+/api/k8s/{path...} | cluster-pods | QUERY | dcr-client = deny+/api/k8s/{path...} | cluster-pods | QUERY | empty-sub = deny+/api/k8s/{path...} | cluster-pods | QUERY | github-oidc = deny+/api/k8s/{path...} | cluster-pods | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | cluster-pods | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | cluster-pods | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | cluster-pods | QUERY | spa = deny+/api/k8s/{path...} | cluster-pods | QUERY | user-key = deny+/api/k8s/{path...} | cluster-pods | QUERY | user-key-verified = deny+/api/k8s/{path...} | cyclops-configmaps | DELETE | admin-spa = deny+/api/k8s/{path...} | cyclops-configmaps | DELETE | cua-cli = deny+/api/k8s/{path...} | cyclops-configmaps | DELETE | dcr-client = deny+/api/k8s/{path...} | cyclops-configmaps | DELETE | empty-sub = deny+/api/k8s/{path...} | cyclops-configmaps | DELETE | github-oidc = deny+/api/k8s/{path...} | cyclops-configmaps | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | cyclops-configmaps | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | cyclops-configmaps | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | cyclops-configmaps | DELETE | spa = deny+/api/k8s/{path...} | cyclops-configmaps | DELETE | user-key = deny+/api/k8s/{path...} | cyclops-configmaps | DELETE | user-key-verified = deny+/api/k8s/{path...} | cyclops-configmaps | GET | admin-spa = deny+/api/k8s/{path...} | cyclops-configmaps | GET | cua-cli = deny+/api/k8s/{path...} | cyclops-configmaps | GET | dcr-client = deny+/api/k8s/{path...} | cyclops-configmaps | GET | empty-sub = deny+/api/k8s/{path...} | cyclops-configmaps | GET | github-oidc = deny+/api/k8s/{path...} | cyclops-configmaps | GET | oauth2-proxy = deny+/api/k8s/{path...} | cyclops-configmaps | GET | per-key-other-ns = deny+/api/k8s/{path...} | cyclops-configmaps | GET | per-key-owned-ns = deny+/api/k8s/{path...} | cyclops-configmaps | GET | spa = deny+/api/k8s/{path...} | cyclops-configmaps | GET | user-key = deny+/api/k8s/{path...} | cyclops-configmaps | GET | user-key-verified = deny+/api/k8s/{path...} | cyclops-configmaps | PATCH | admin-spa = deny+/api/k8s/{path...} | cyclops-configmaps | PATCH | cua-cli = deny+/api/k8s/{path...} | cyclops-configmaps | PATCH | dcr-client = deny+/api/k8s/{path...} | cyclops-configmaps | PATCH | empty-sub = deny+/api/k8s/{path...} | cyclops-configmaps | PATCH | github-oidc = deny+/api/k8s/{path...} | cyclops-configmaps | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | cyclops-configmaps | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | cyclops-configmaps | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | cyclops-configmaps | PATCH | spa = deny+/api/k8s/{path...} | cyclops-configmaps | PATCH | user-key = deny+/api/k8s/{path...} | cyclops-configmaps | PATCH | user-key-verified = deny+/api/k8s/{path...} | cyclops-configmaps | POST | admin-spa = deny+/api/k8s/{path...} | cyclops-configmaps | POST | cua-cli = deny+/api/k8s/{path...} | cyclops-configmaps | POST | dcr-client = deny+/api/k8s/{path...} | cyclops-configmaps | POST | empty-sub = deny+/api/k8s/{path...} | cyclops-configmaps | POST | github-oidc = deny+/api/k8s/{path...} | cyclops-configmaps | POST | oauth2-proxy = deny+/api/k8s/{path...} | cyclops-configmaps | POST | per-key-other-ns = deny+/api/k8s/{path...} | cyclops-configmaps | POST | per-key-owned-ns = deny+/api/k8s/{path...} | cyclops-configmaps | POST | spa = deny+/api/k8s/{path...} | cyclops-configmaps | POST | user-key = deny+/api/k8s/{path...} | cyclops-configmaps | POST | user-key-verified = deny+/api/k8s/{path...} | cyclops-configmaps | QUERY | admin-spa = deny+/api/k8s/{path...} | cyclops-configmaps | QUERY | cua-cli = deny+/api/k8s/{path...} | cyclops-configmaps | QUERY | dcr-client = deny+/api/k8s/{path...} | cyclops-configmaps | QUERY | empty-sub = deny+/api/k8s/{path...} | cyclops-configmaps | QUERY | github-oidc = deny+/api/k8s/{path...} | cyclops-configmaps | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | cyclops-configmaps | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | cyclops-configmaps | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | cyclops-configmaps | QUERY | spa = deny+/api/k8s/{path...} | cyclops-configmaps | QUERY | user-key = deny+/api/k8s/{path...} | cyclops-configmaps | QUERY | user-key-verified = deny+/api/k8s/{path...} | discovery | DELETE | admin-spa = deny+/api/k8s/{path...} | discovery | DELETE | cua-cli = deny+/api/k8s/{path...} | discovery | DELETE | dcr-client = deny+/api/k8s/{path...} | discovery | DELETE | empty-sub = deny+/api/k8s/{path...} | discovery | DELETE | github-oidc = deny+/api/k8s/{path...} | discovery | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | discovery | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | discovery | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | discovery | DELETE | spa = deny+/api/k8s/{path...} | discovery | DELETE | user-key = deny+/api/k8s/{path...} | discovery | DELETE | user-key-verified = deny+/api/k8s/{path...} | discovery | GET | admin-spa = allow+/api/k8s/{path...} | discovery | GET | cua-cli = allow+/api/k8s/{path...} | discovery | GET | dcr-client = deny+/api/k8s/{path...} | discovery | GET | empty-sub = deny+/api/k8s/{path...} | discovery | GET | github-oidc = deny+/api/k8s/{path...} | discovery | GET | oauth2-proxy = deny+/api/k8s/{path...} | discovery | GET | per-key-other-ns = deny+/api/k8s/{path...} | discovery | GET | per-key-owned-ns = deny+/api/k8s/{path...} | discovery | GET | spa = allow+/api/k8s/{path...} | discovery | GET | user-key = allow+/api/k8s/{path...} | discovery | GET | user-key-verified = allow+/api/k8s/{path...} | discovery | PATCH | admin-spa = deny+/api/k8s/{path...} | discovery | PATCH | cua-cli = deny+/api/k8s/{path...} | discovery | PATCH | dcr-client = deny+/api/k8s/{path...} | discovery | PATCH | empty-sub = deny+/api/k8s/{path...} | discovery | PATCH | github-oidc = deny+/api/k8s/{path...} | discovery | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | discovery | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | discovery | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | discovery | PATCH | spa = deny+/api/k8s/{path...} | discovery | PATCH | user-key = deny+/api/k8s/{path...} | discovery | PATCH | user-key-verified = deny+/api/k8s/{path...} | discovery | POST | admin-spa = deny+/api/k8s/{path...} | discovery | POST | cua-cli = deny+/api/k8s/{path...} | discovery | POST | dcr-client = deny+/api/k8s/{path...} | discovery | POST | empty-sub = deny+/api/k8s/{path...} | discovery | POST | github-oidc = deny+/api/k8s/{path...} | discovery | POST | oauth2-proxy = deny+/api/k8s/{path...} | discovery | POST | per-key-other-ns = deny+/api/k8s/{path...} | discovery | POST | per-key-owned-ns = deny+/api/k8s/{path...} | discovery | POST | spa = deny+/api/k8s/{path...} | discovery | POST | user-key = deny+/api/k8s/{path...} | discovery | POST | user-key-verified = deny+/api/k8s/{path...} | discovery | QUERY | admin-spa = deny+/api/k8s/{path...} | discovery | QUERY | cua-cli = deny+/api/k8s/{path...} | discovery | QUERY | dcr-client = deny+/api/k8s/{path...} | discovery | QUERY | empty-sub = deny+/api/k8s/{path...} | discovery | QUERY | github-oidc = deny+/api/k8s/{path...} | discovery | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | discovery | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | discovery | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | discovery | QUERY | spa = deny+/api/k8s/{path...} | discovery | QUERY | user-key = deny+/api/k8s/{path...} | discovery | QUERY | user-key-verified = deny+/api/k8s/{path...} | event-group-collision | DELETE | admin-spa = deny+/api/k8s/{path...} | event-group-collision | DELETE | cua-cli = deny+/api/k8s/{path...} | event-group-collision | DELETE | dcr-client = deny+/api/k8s/{path...} | event-group-collision | DELETE | empty-sub = deny+/api/k8s/{path...} | event-group-collision | DELETE | github-oidc = deny+/api/k8s/{path...} | event-group-collision | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | event-group-collision | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | event-group-collision | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | event-group-collision | DELETE | spa = deny+/api/k8s/{path...} | event-group-collision | DELETE | user-key = deny+/api/k8s/{path...} | event-group-collision | DELETE | user-key-verified = deny+/api/k8s/{path...} | event-group-collision | GET | admin-spa = deny+/api/k8s/{path...} | event-group-collision | GET | cua-cli = deny+/api/k8s/{path...} | event-group-collision | GET | dcr-client = deny+/api/k8s/{path...} | event-group-collision | GET | empty-sub = deny+/api/k8s/{path...} | event-group-collision | GET | github-oidc = deny+/api/k8s/{path...} | event-group-collision | GET | oauth2-proxy = deny+/api/k8s/{path...} | event-group-collision | GET | per-key-other-ns = deny+/api/k8s/{path...} | event-group-collision | GET | per-key-owned-ns = deny+/api/k8s/{path...} | event-group-collision | GET | spa = deny+/api/k8s/{path...} | event-group-collision | GET | user-key = deny+/api/k8s/{path...} | event-group-collision | GET | user-key-verified = deny+/api/k8s/{path...} | event-group-collision | PATCH | admin-spa = deny+/api/k8s/{path...} | event-group-collision | PATCH | cua-cli = deny+/api/k8s/{path...} | event-group-collision | PATCH | dcr-client = deny+/api/k8s/{path...} | event-group-collision | PATCH | empty-sub = deny+/api/k8s/{path...} | event-group-collision | PATCH | github-oidc = deny+/api/k8s/{path...} | event-group-collision | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | event-group-collision | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | event-group-collision | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | event-group-collision | PATCH | spa = deny+/api/k8s/{path...} | event-group-collision | PATCH | user-key = deny+/api/k8s/{path...} | event-group-collision | PATCH | user-key-verified = deny+/api/k8s/{path...} | event-group-collision | POST | admin-spa = deny+/api/k8s/{path...} | event-group-collision | POST | cua-cli = deny+/api/k8s/{path...} | event-group-collision | POST | dcr-client = deny+/api/k8s/{path...} | event-group-collision | POST | empty-sub = deny+/api/k8s/{path...} | event-group-collision | POST | github-oidc = deny+/api/k8s/{path...} | event-group-collision | POST | oauth2-proxy = deny+/api/k8s/{path...} | event-group-collision | POST | per-key-other-ns = deny+/api/k8s/{path...} | event-group-collision | POST | per-key-owned-ns = deny+/api/k8s/{path...} | event-group-collision | POST | spa = deny+/api/k8s/{path...} | event-group-collision | POST | user-key = deny+/api/k8s/{path...} | event-group-collision | POST | user-key-verified = deny+/api/k8s/{path...} | event-group-collision | QUERY | admin-spa = deny+/api/k8s/{path...} | event-group-collision | QUERY | cua-cli = deny+/api/k8s/{path...} | event-group-collision | QUERY | dcr-client = deny+/api/k8s/{path...} | event-group-collision | QUERY | empty-sub = deny+/api/k8s/{path...} | event-group-collision | QUERY | github-oidc = deny+/api/k8s/{path...} | event-group-collision | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | event-group-collision | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | event-group-collision | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | event-group-collision | QUERY | spa = deny+/api/k8s/{path...} | event-group-collision | QUERY | user-key = deny+/api/k8s/{path...} | event-group-collision | QUERY | user-key-verified = deny+/api/k8s/{path...} | granted-ns-claims | DELETE | admin-spa = deny+/api/k8s/{path...} | granted-ns-claims | DELETE | cua-cli = deny+/api/k8s/{path...} | granted-ns-claims | DELETE | dcr-client = deny+/api/k8s/{path...} | granted-ns-claims | DELETE | empty-sub = deny+/api/k8s/{path...} | granted-ns-claims | DELETE | github-oidc = deny+/api/k8s/{path...} | granted-ns-claims | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | granted-ns-claims | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | granted-ns-claims | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | granted-ns-claims | DELETE | spa = deny+/api/k8s/{path...} | granted-ns-claims | DELETE | user-key = deny+/api/k8s/{path...} | granted-ns-claims | DELETE | user-key-verified = deny+/api/k8s/{path...} | granted-ns-claims | GET | admin-spa = allow+/api/k8s/{path...} | granted-ns-claims | GET | cua-cli = allow+/api/k8s/{path...} | granted-ns-claims | GET | dcr-client = deny+/api/k8s/{path...} | granted-ns-claims | GET | empty-sub = deny+/api/k8s/{path...} | granted-ns-claims | GET | github-oidc = allow+/api/k8s/{path...} | granted-ns-claims | GET | oauth2-proxy = deny+/api/k8s/{path...} | granted-ns-claims | GET | per-key-other-ns = deny+/api/k8s/{path...} | granted-ns-claims | GET | per-key-owned-ns = deny+/api/k8s/{path...} | granted-ns-claims | GET | spa = allow+/api/k8s/{path...} | granted-ns-claims | GET | user-key = allow+/api/k8s/{path...} | granted-ns-claims | GET | user-key-verified = allow+/api/k8s/{path...} | granted-ns-claims | PATCH | admin-spa = deny+/api/k8s/{path...} | granted-ns-claims | PATCH | cua-cli = deny+/api/k8s/{path...} | granted-ns-claims | PATCH | dcr-client = deny+/api/k8s/{path...} | granted-ns-claims | PATCH | empty-sub = deny+/api/k8s/{path...} | granted-ns-claims | PATCH | github-oidc = deny+/api/k8s/{path...} | granted-ns-claims | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | granted-ns-claims | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | granted-ns-claims | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | granted-ns-claims | PATCH | spa = deny+/api/k8s/{path...} | granted-ns-claims | PATCH | user-key = deny+/api/k8s/{path...} | granted-ns-claims | PATCH | user-key-verified = deny+/api/k8s/{path...} | granted-ns-claims | POST | admin-spa = allow+/api/k8s/{path...} | granted-ns-claims | POST | cua-cli = allow+/api/k8s/{path...} | granted-ns-claims | POST | dcr-client = deny+/api/k8s/{path...} | granted-ns-claims | POST | empty-sub = deny+/api/k8s/{path...} | granted-ns-claims | POST | github-oidc = allow+/api/k8s/{path...} | granted-ns-claims | POST | oauth2-proxy = deny+/api/k8s/{path...} | granted-ns-claims | POST | per-key-other-ns = deny+/api/k8s/{path...} | granted-ns-claims | POST | per-key-owned-ns = deny+/api/k8s/{path...} | granted-ns-claims | POST | spa = allow+/api/k8s/{path...} | granted-ns-claims | POST | user-key = allow+/api/k8s/{path...} | granted-ns-claims | POST | user-key-verified = allow+/api/k8s/{path...} | granted-ns-claims | QUERY | admin-spa = deny+/api/k8s/{path...} | granted-ns-claims | QUERY | cua-cli = deny+/api/k8s/{path...} | granted-ns-claims | QUERY | dcr-client = deny+/api/k8s/{path...} | granted-ns-claims | QUERY | empty-sub = deny+/api/k8s/{path...} | granted-ns-claims | QUERY | github-oidc = deny+/api/k8s/{path...} | granted-ns-claims | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | granted-ns-claims | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | granted-ns-claims | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | granted-ns-claims | QUERY | spa = deny+/api/k8s/{path...} | granted-ns-claims | QUERY | user-key = deny+/api/k8s/{path...} | granted-ns-claims | QUERY | user-key-verified = deny+/api/k8s/{path...} | granted-ns-pools | DELETE | admin-spa = deny+/api/k8s/{path...} | granted-ns-pools | DELETE | cua-cli = deny+/api/k8s/{path...} | granted-ns-pools | DELETE | dcr-client = deny+/api/k8s/{path...} | granted-ns-pools | DELETE | empty-sub = deny+/api/k8s/{path...} | granted-ns-pools | DELETE | github-oidc = allow+/api/k8s/{path...} | granted-ns-pools | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | granted-ns-pools | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | granted-ns-pools | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | granted-ns-pools | DELETE | spa = deny+/api/k8s/{path...} | granted-ns-pools | DELETE | user-key = deny+/api/k8s/{path...} | granted-ns-pools | DELETE | user-key-verified = deny+/api/k8s/{path...} | granted-ns-pools | GET | admin-spa = allow+/api/k8s/{path...} | granted-ns-pools | GET | cua-cli = allow+/api/k8s/{path...} | granted-ns-pools | GET | dcr-client = deny+/api/k8s/{path...} | granted-ns-pools | GET | empty-sub = deny+/api/k8s/{path...} | granted-ns-pools | GET | github-oidc = allow+/api/k8s/{path...} | granted-ns-pools | GET | oauth2-proxy = deny+/api/k8s/{path...} | granted-ns-pools | GET | per-key-other-ns = deny+/api/k8s/{path...} | granted-ns-pools | GET | per-key-owned-ns = deny+/api/k8s/{path...} | granted-ns-pools | GET | spa = allow+/api/k8s/{path...} | granted-ns-pools | GET | user-key = allow+/api/k8s/{path...} | granted-ns-pools | GET | user-key-verified = allow+/api/k8s/{path...} | granted-ns-pools | PATCH | admin-spa = deny+/api/k8s/{path...} | granted-ns-pools | PATCH | cua-cli = deny+/api/k8s/{path...} | granted-ns-pools | PATCH | dcr-client = deny+/api/k8s/{path...} | granted-ns-pools | PATCH | empty-sub = deny+/api/k8s/{path...} | granted-ns-pools | PATCH | github-oidc = allow+/api/k8s/{path...} | granted-ns-pools | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | granted-ns-pools | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | granted-ns-pools | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | granted-ns-pools | PATCH | spa = deny+/api/k8s/{path...} | granted-ns-pools | PATCH | user-key = deny+/api/k8s/{path...} | granted-ns-pools | PATCH | user-key-verified = deny+/api/k8s/{path...} | granted-ns-pools | POST | admin-spa = allow+/api/k8s/{path...} | granted-ns-pools | POST | cua-cli = allow+/api/k8s/{path...} | granted-ns-pools | POST | dcr-client = deny+/api/k8s/{path...} | granted-ns-pools | POST | empty-sub = deny+/api/k8s/{path...} | granted-ns-pools | POST | github-oidc = allow+/api/k8s/{path...} | granted-ns-pools | POST | oauth2-proxy = deny+/api/k8s/{path...} | granted-ns-pools | POST | per-key-other-ns = deny+/api/k8s/{path...} | granted-ns-pools | POST | per-key-owned-ns = deny+/api/k8s/{path...} | granted-ns-pools | POST | spa = allow+/api/k8s/{path...} | granted-ns-pools | POST | user-key = allow+/api/k8s/{path...} | granted-ns-pools | POST | user-key-verified = allow+/api/k8s/{path...} | granted-ns-pools | QUERY | admin-spa = deny+/api/k8s/{path...} | granted-ns-pools | QUERY | cua-cli = deny+/api/k8s/{path...} | granted-ns-pools | QUERY | dcr-client = deny+/api/k8s/{path...} | granted-ns-pools | QUERY | empty-sub = deny+/api/k8s/{path...} | granted-ns-pools | QUERY | github-oidc = deny+/api/k8s/{path...} | granted-ns-pools | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | granted-ns-pools | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | granted-ns-pools | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | granted-ns-pools | QUERY | spa = deny+/api/k8s/{path...} | granted-ns-pools | QUERY | user-key = deny+/api/k8s/{path...} | granted-ns-pools | QUERY | user-key-verified = deny+/api/k8s/{path...} | group-cluster-events | DELETE | admin-spa = deny+/api/k8s/{path...} | group-cluster-events | DELETE | cua-cli = deny+/api/k8s/{path...} | group-cluster-events | DELETE | dcr-client = deny+/api/k8s/{path...} | group-cluster-events | DELETE | empty-sub = deny+/api/k8s/{path...} | group-cluster-events | DELETE | github-oidc = deny+/api/k8s/{path...} | group-cluster-events | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | group-cluster-events | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | group-cluster-events | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | group-cluster-events | DELETE | spa = deny+/api/k8s/{path...} | group-cluster-events | DELETE | user-key = deny+/api/k8s/{path...} | group-cluster-events | DELETE | user-key-verified = deny+/api/k8s/{path...} | group-cluster-events | GET | admin-spa = deny+/api/k8s/{path...} | group-cluster-events | GET | cua-cli = deny+/api/k8s/{path...} | group-cluster-events | GET | dcr-client = deny+/api/k8s/{path...} | group-cluster-events | GET | empty-sub = deny+/api/k8s/{path...} | group-cluster-events | GET | github-oidc = deny+/api/k8s/{path...} | group-cluster-events | GET | oauth2-proxy = deny+/api/k8s/{path...} | group-cluster-events | GET | per-key-other-ns = deny+/api/k8s/{path...} | group-cluster-events | GET | per-key-owned-ns = deny+/api/k8s/{path...} | group-cluster-events | GET | spa = deny+/api/k8s/{path...} | group-cluster-events | GET | user-key = deny+/api/k8s/{path...} | group-cluster-events | GET | user-key-verified = deny+/api/k8s/{path...} | group-cluster-events | PATCH | admin-spa = deny+/api/k8s/{path...} | group-cluster-events | PATCH | cua-cli = deny+/api/k8s/{path...} | group-cluster-events | PATCH | dcr-client = deny+/api/k8s/{path...} | group-cluster-events | PATCH | empty-sub = deny+/api/k8s/{path...} | group-cluster-events | PATCH | github-oidc = deny+/api/k8s/{path...} | group-cluster-events | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | group-cluster-events | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | group-cluster-events | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | group-cluster-events | PATCH | spa = deny+/api/k8s/{path...} | group-cluster-events | PATCH | user-key = deny+/api/k8s/{path...} | group-cluster-events | PATCH | user-key-verified = deny+/api/k8s/{path...} | group-cluster-events | POST | admin-spa = deny+/api/k8s/{path...} | group-cluster-events | POST | cua-cli = deny+/api/k8s/{path...} | group-cluster-events | POST | dcr-client = deny+/api/k8s/{path...} | group-cluster-events | POST | empty-sub = deny+/api/k8s/{path...} | group-cluster-events | POST | github-oidc = deny+/api/k8s/{path...} | group-cluster-events | POST | oauth2-proxy = deny+/api/k8s/{path...} | group-cluster-events | POST | per-key-other-ns = deny+/api/k8s/{path...} | group-cluster-events | POST | per-key-owned-ns = deny+/api/k8s/{path...} | group-cluster-events | POST | spa = deny+/api/k8s/{path...} | group-cluster-events | POST | user-key = deny+/api/k8s/{path...} | group-cluster-events | POST | user-key-verified = deny+/api/k8s/{path...} | group-cluster-events | QUERY | admin-spa = deny+/api/k8s/{path...} | group-cluster-events | QUERY | cua-cli = deny+/api/k8s/{path...} | group-cluster-events | QUERY | dcr-client = deny+/api/k8s/{path...} | group-cluster-events | QUERY | empty-sub = deny+/api/k8s/{path...} | group-cluster-events | QUERY | github-oidc = deny+/api/k8s/{path...} | group-cluster-events | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | group-cluster-events | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | group-cluster-events | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | group-cluster-events | QUERY | spa = deny+/api/k8s/{path...} | group-cluster-events | QUERY | user-key = deny+/api/k8s/{path...} | group-cluster-events | QUERY | user-key-verified = deny+/api/k8s/{path...} | group-namespaced-events | DELETE | admin-spa = deny+/api/k8s/{path...} | group-namespaced-events | DELETE | cua-cli = deny+/api/k8s/{path...} | group-namespaced-events | DELETE | dcr-client = deny+/api/k8s/{path...} | group-namespaced-events | DELETE | empty-sub = deny+/api/k8s/{path...} | group-namespaced-events | DELETE | github-oidc = deny+/api/k8s/{path...} | group-namespaced-events | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | group-namespaced-events | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | group-namespaced-events | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | group-namespaced-events | DELETE | spa = deny+/api/k8s/{path...} | group-namespaced-events | DELETE | user-key = deny+/api/k8s/{path...} | group-namespaced-events | DELETE | user-key-verified = deny+/api/k8s/{path...} | group-namespaced-events | GET | admin-spa = deny+/api/k8s/{path...} | group-namespaced-events | GET | cua-cli = deny+/api/k8s/{path...} | group-namespaced-events | GET | dcr-client = deny+/api/k8s/{path...} | group-namespaced-events | GET | empty-sub = deny+/api/k8s/{path...} | group-namespaced-events | GET | github-oidc = deny+/api/k8s/{path...} | group-namespaced-events | GET | oauth2-proxy = deny+/api/k8s/{path...} | group-namespaced-events | GET | per-key-other-ns = deny+/api/k8s/{path...} | group-namespaced-events | GET | per-key-owned-ns = deny+/api/k8s/{path...} | group-namespaced-events | GET | spa = deny+/api/k8s/{path...} | group-namespaced-events | GET | user-key = deny+/api/k8s/{path...} | group-namespaced-events | GET | user-key-verified = deny+/api/k8s/{path...} | group-namespaced-events | PATCH | admin-spa = deny+/api/k8s/{path...} | group-namespaced-events | PATCH | cua-cli = deny+/api/k8s/{path...} | group-namespaced-events | PATCH | dcr-client = deny+/api/k8s/{path...} | group-namespaced-events | PATCH | empty-sub = deny+/api/k8s/{path...} | group-namespaced-events | PATCH | github-oidc = deny+/api/k8s/{path...} | group-namespaced-events | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | group-namespaced-events | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | group-namespaced-events | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | group-namespaced-events | PATCH | spa = deny+/api/k8s/{path...} | group-namespaced-events | PATCH | user-key = deny+/api/k8s/{path...} | group-namespaced-events | PATCH | user-key-verified = deny+/api/k8s/{path...} | group-namespaced-events | POST | admin-spa = deny+/api/k8s/{path...} | group-namespaced-events | POST | cua-cli = deny+/api/k8s/{path...} | group-namespaced-events | POST | dcr-client = deny+/api/k8s/{path...} | group-namespaced-events | POST | empty-sub = deny+/api/k8s/{path...} | group-namespaced-events | POST | github-oidc = deny+/api/k8s/{path...} | group-namespaced-events | POST | oauth2-proxy = deny+/api/k8s/{path...} | group-namespaced-events | POST | per-key-other-ns = deny+/api/k8s/{path...} | group-namespaced-events | POST | per-key-owned-ns = deny+/api/k8s/{path...} | group-namespaced-events | POST | spa = deny+/api/k8s/{path...} | group-namespaced-events | POST | user-key = deny+/api/k8s/{path...} | group-namespaced-events | POST | user-key-verified = deny+/api/k8s/{path...} | group-namespaced-events | QUERY | admin-spa = deny+/api/k8s/{path...} | group-namespaced-events | QUERY | cua-cli = deny+/api/k8s/{path...} | group-namespaced-events | QUERY | dcr-client = deny+/api/k8s/{path...} | group-namespaced-events | QUERY | empty-sub = deny+/api/k8s/{path...} | group-namespaced-events | QUERY | github-oidc = deny+/api/k8s/{path...} | group-namespaced-events | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | group-namespaced-events | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | group-namespaced-events | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | group-namespaced-events | QUERY | spa = deny+/api/k8s/{path...} | group-namespaced-events | QUERY | user-key = deny+/api/k8s/{path...} | group-namespaced-events | QUERY | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | DELETE | admin-spa = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | DELETE | cua-cli = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | DELETE | dcr-client = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | DELETE | empty-sub = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | DELETE | github-oidc = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | DELETE | spa = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | DELETE | user-key = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | DELETE | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | GET | admin-spa = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | GET | cua-cli = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | GET | dcr-client = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | GET | empty-sub = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | GET | github-oidc = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | GET | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | GET | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | GET | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | GET | spa = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | GET | user-key = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | GET | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | PATCH | admin-spa = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | PATCH | cua-cli = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | PATCH | dcr-client = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | PATCH | empty-sub = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | PATCH | github-oidc = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | PATCH | spa = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | PATCH | user-key = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | PATCH | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | POST | admin-spa = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | POST | cua-cli = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | POST | dcr-client = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | POST | empty-sub = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | POST | github-oidc = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | POST | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | POST | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | POST | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | POST | spa = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | POST | user-key = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | POST | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | QUERY | admin-spa = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | QUERY | cua-cli = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | QUERY | dcr-client = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | QUERY | empty-sub = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | QUERY | github-oidc = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | QUERY | spa = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | QUERY | user-key = deny+/api/k8s/{path...} | legacy-watch-cluster-nodes | QUERY | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | DELETE | admin-spa = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | DELETE | cua-cli = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | DELETE | dcr-client = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | DELETE | empty-sub = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | DELETE | github-oidc = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | DELETE | spa = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | DELETE | user-key = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | DELETE | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | GET | admin-spa = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | GET | cua-cli = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | GET | dcr-client = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | GET | empty-sub = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | GET | github-oidc = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | GET | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | GET | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | GET | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | GET | spa = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | GET | user-key = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | GET | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | PATCH | admin-spa = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | PATCH | cua-cli = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | PATCH | dcr-client = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | PATCH | empty-sub = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | PATCH | github-oidc = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | PATCH | spa = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | PATCH | user-key = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | PATCH | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | POST | admin-spa = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | POST | cua-cli = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | POST | dcr-client = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | POST | empty-sub = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | POST | github-oidc = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | POST | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | POST | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | POST | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | POST | spa = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | POST | user-key = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | POST | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | QUERY | admin-spa = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | QUERY | cua-cli = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | QUERY | dcr-client = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | QUERY | empty-sub = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | QUERY | github-oidc = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | QUERY | spa = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | QUERY | user-key = deny+/api/k8s/{path...} | legacy-watch-cluster-pods | QUERY | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-events | DELETE | admin-spa = deny+/api/k8s/{path...} | legacy-watch-events | DELETE | cua-cli = deny+/api/k8s/{path...} | legacy-watch-events | DELETE | dcr-client = deny+/api/k8s/{path...} | legacy-watch-events | DELETE | empty-sub = deny+/api/k8s/{path...} | legacy-watch-events | DELETE | github-oidc = deny+/api/k8s/{path...} | legacy-watch-events | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-events | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-events | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-events | DELETE | spa = deny+/api/k8s/{path...} | legacy-watch-events | DELETE | user-key = deny+/api/k8s/{path...} | legacy-watch-events | DELETE | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-events | GET | admin-spa = deny+/api/k8s/{path...} | legacy-watch-events | GET | cua-cli = deny+/api/k8s/{path...} | legacy-watch-events | GET | dcr-client = deny+/api/k8s/{path...} | legacy-watch-events | GET | empty-sub = deny+/api/k8s/{path...} | legacy-watch-events | GET | github-oidc = deny+/api/k8s/{path...} | legacy-watch-events | GET | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-events | GET | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-events | GET | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-events | GET | spa = deny+/api/k8s/{path...} | legacy-watch-events | GET | user-key = deny+/api/k8s/{path...} | legacy-watch-events | GET | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-events | PATCH | admin-spa = deny+/api/k8s/{path...} | legacy-watch-events | PATCH | cua-cli = deny+/api/k8s/{path...} | legacy-watch-events | PATCH | dcr-client = deny+/api/k8s/{path...} | legacy-watch-events | PATCH | empty-sub = deny+/api/k8s/{path...} | legacy-watch-events | PATCH | github-oidc = deny+/api/k8s/{path...} | legacy-watch-events | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-events | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-events | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-events | PATCH | spa = deny+/api/k8s/{path...} | legacy-watch-events | PATCH | user-key = deny+/api/k8s/{path...} | legacy-watch-events | PATCH | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-events | POST | admin-spa = deny+/api/k8s/{path...} | legacy-watch-events | POST | cua-cli = deny+/api/k8s/{path...} | legacy-watch-events | POST | dcr-client = deny+/api/k8s/{path...} | legacy-watch-events | POST | empty-sub = deny+/api/k8s/{path...} | legacy-watch-events | POST | github-oidc = deny+/api/k8s/{path...} | legacy-watch-events | POST | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-events | POST | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-events | POST | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-events | POST | spa = deny+/api/k8s/{path...} | legacy-watch-events | POST | user-key = deny+/api/k8s/{path...} | legacy-watch-events | POST | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-events | QUERY | admin-spa = deny+/api/k8s/{path...} | legacy-watch-events | QUERY | cua-cli = deny+/api/k8s/{path...} | legacy-watch-events | QUERY | dcr-client = deny+/api/k8s/{path...} | legacy-watch-events | QUERY | empty-sub = deny+/api/k8s/{path...} | legacy-watch-events | QUERY | github-oidc = deny+/api/k8s/{path...} | legacy-watch-events | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-events | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-events | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-events | QUERY | spa = deny+/api/k8s/{path...} | legacy-watch-events | QUERY | user-key = deny+/api/k8s/{path...} | legacy-watch-events | QUERY | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | DELETE | admin-spa = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | DELETE | cua-cli = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | DELETE | dcr-client = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | DELETE | empty-sub = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | DELETE | github-oidc = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | DELETE | spa = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | DELETE | user-key = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | DELETE | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | GET | admin-spa = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | GET | cua-cli = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | GET | dcr-client = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | GET | empty-sub = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | GET | github-oidc = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | GET | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | GET | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | GET | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | GET | spa = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | GET | user-key = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | GET | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | PATCH | admin-spa = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | PATCH | cua-cli = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | PATCH | dcr-client = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | PATCH | empty-sub = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | PATCH | github-oidc = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | PATCH | spa = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | PATCH | user-key = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | PATCH | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | POST | admin-spa = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | POST | cua-cli = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | POST | dcr-client = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | POST | empty-sub = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | POST | github-oidc = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | POST | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | POST | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | POST | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | POST | spa = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | POST | user-key = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | POST | user-key-verified = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | QUERY | admin-spa = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | QUERY | cua-cli = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | QUERY | dcr-client = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | QUERY | empty-sub = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | QUERY | github-oidc = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | QUERY | spa = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | QUERY | user-key = deny+/api/k8s/{path...} | legacy-watch-namespaced-events | QUERY | user-key-verified = deny+/api/k8s/{path...} | namespaced-events | DELETE | admin-spa = deny+/api/k8s/{path...} | namespaced-events | DELETE | cua-cli = deny+/api/k8s/{path...} | namespaced-events | DELETE | dcr-client = deny+/api/k8s/{path...} | namespaced-events | DELETE | empty-sub = deny+/api/k8s/{path...} | namespaced-events | DELETE | github-oidc = deny+/api/k8s/{path...} | namespaced-events | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-events | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-events | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-events | DELETE | spa = deny+/api/k8s/{path...} | namespaced-events | DELETE | user-key = deny+/api/k8s/{path...} | namespaced-events | DELETE | user-key-verified = deny+/api/k8s/{path...} | namespaced-events | GET | admin-spa = deny+/api/k8s/{path...} | namespaced-events | GET | cua-cli = deny+/api/k8s/{path...} | namespaced-events | GET | dcr-client = deny+/api/k8s/{path...} | namespaced-events | GET | empty-sub = deny+/api/k8s/{path...} | namespaced-events | GET | github-oidc = deny+/api/k8s/{path...} | namespaced-events | GET | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-events | GET | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-events | GET | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-events | GET | spa = deny+/api/k8s/{path...} | namespaced-events | GET | user-key = deny+/api/k8s/{path...} | namespaced-events | GET | user-key-verified = deny+/api/k8s/{path...} | namespaced-events | PATCH | admin-spa = deny+/api/k8s/{path...} | namespaced-events | PATCH | cua-cli = deny+/api/k8s/{path...} | namespaced-events | PATCH | dcr-client = deny+/api/k8s/{path...} | namespaced-events | PATCH | empty-sub = deny+/api/k8s/{path...} | namespaced-events | PATCH | github-oidc = deny+/api/k8s/{path...} | namespaced-events | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-events | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-events | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-events | PATCH | spa = deny+/api/k8s/{path...} | namespaced-events | PATCH | user-key = deny+/api/k8s/{path...} | namespaced-events | PATCH | user-key-verified = deny+/api/k8s/{path...} | namespaced-events | POST | admin-spa = deny+/api/k8s/{path...} | namespaced-events | POST | cua-cli = deny+/api/k8s/{path...} | namespaced-events | POST | dcr-client = deny+/api/k8s/{path...} | namespaced-events | POST | empty-sub = deny+/api/k8s/{path...} | namespaced-events | POST | github-oidc = deny+/api/k8s/{path...} | namespaced-events | POST | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-events | POST | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-events | POST | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-events | POST | spa = deny+/api/k8s/{path...} | namespaced-events | POST | user-key = deny+/api/k8s/{path...} | namespaced-events | POST | user-key-verified = deny+/api/k8s/{path...} | namespaced-events | QUERY | admin-spa = deny+/api/k8s/{path...} | namespaced-events | QUERY | cua-cli = deny+/api/k8s/{path...} | namespaced-events | QUERY | dcr-client = deny+/api/k8s/{path...} | namespaced-events | QUERY | empty-sub = deny+/api/k8s/{path...} | namespaced-events | QUERY | github-oidc = deny+/api/k8s/{path...} | namespaced-events | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-events | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-events | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-events | QUERY | spa = deny+/api/k8s/{path...} | namespaced-events | QUERY | user-key = deny+/api/k8s/{path...} | namespaced-events | QUERY | user-key-verified = deny+/api/k8s/{path...} | namespaced-pods | DELETE | admin-spa = deny+/api/k8s/{path...} | namespaced-pods | DELETE | cua-cli = deny+/api/k8s/{path...} | namespaced-pods | DELETE | dcr-client = deny+/api/k8s/{path...} | namespaced-pods | DELETE | empty-sub = deny+/api/k8s/{path...} | namespaced-pods | DELETE | github-oidc = deny+/api/k8s/{path...} | namespaced-pods | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-pods | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-pods | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-pods | DELETE | spa = deny+/api/k8s/{path...} | namespaced-pods | DELETE | user-key = deny+/api/k8s/{path...} | namespaced-pods | DELETE | user-key-verified = deny+/api/k8s/{path...} | namespaced-pods | GET | admin-spa = allow+/api/k8s/{path...} | namespaced-pods | GET | cua-cli = allow+/api/k8s/{path...} | namespaced-pods | GET | dcr-client = deny+/api/k8s/{path...} | namespaced-pods | GET | empty-sub = deny+/api/k8s/{path...} | namespaced-pods | GET | github-oidc = deny+/api/k8s/{path...} | namespaced-pods | GET | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-pods | GET | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-pods | GET | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-pods | GET | spa = allow+/api/k8s/{path...} | namespaced-pods | GET | user-key = allow+/api/k8s/{path...} | namespaced-pods | GET | user-key-verified = allow+/api/k8s/{path...} | namespaced-pods | PATCH | admin-spa = deny+/api/k8s/{path...} | namespaced-pods | PATCH | cua-cli = deny+/api/k8s/{path...} | namespaced-pods | PATCH | dcr-client = deny+/api/k8s/{path...} | namespaced-pods | PATCH | empty-sub = deny+/api/k8s/{path...} | namespaced-pods | PATCH | github-oidc = deny+/api/k8s/{path...} | namespaced-pods | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-pods | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-pods | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-pods | PATCH | spa = deny+/api/k8s/{path...} | namespaced-pods | PATCH | user-key = deny+/api/k8s/{path...} | namespaced-pods | PATCH | user-key-verified = deny+/api/k8s/{path...} | namespaced-pods | POST | admin-spa = deny+/api/k8s/{path...} | namespaced-pods | POST | cua-cli = deny+/api/k8s/{path...} | namespaced-pods | POST | dcr-client = deny+/api/k8s/{path...} | namespaced-pods | POST | empty-sub = deny+/api/k8s/{path...} | namespaced-pods | POST | github-oidc = deny+/api/k8s/{path...} | namespaced-pods | POST | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-pods | POST | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-pods | POST | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-pods | POST | spa = deny+/api/k8s/{path...} | namespaced-pods | POST | user-key = deny+/api/k8s/{path...} | namespaced-pods | POST | user-key-verified = deny+/api/k8s/{path...} | namespaced-pods | QUERY | admin-spa = deny+/api/k8s/{path...} | namespaced-pods | QUERY | cua-cli = deny+/api/k8s/{path...} | namespaced-pods | QUERY | dcr-client = deny+/api/k8s/{path...} | namespaced-pods | QUERY | empty-sub = deny+/api/k8s/{path...} | namespaced-pods | QUERY | github-oidc = deny+/api/k8s/{path...} | namespaced-pods | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-pods | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-pods | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-pods | QUERY | spa = deny+/api/k8s/{path...} | namespaced-pods | QUERY | user-key = deny+/api/k8s/{path...} | namespaced-pods | QUERY | user-key-verified = deny+/api/k8s/{path...} | namespaced-secrets | DELETE | admin-spa = deny+/api/k8s/{path...} | namespaced-secrets | DELETE | cua-cli = deny+/api/k8s/{path...} | namespaced-secrets | DELETE | dcr-client = deny+/api/k8s/{path...} | namespaced-secrets | DELETE | empty-sub = deny+/api/k8s/{path...} | namespaced-secrets | DELETE | github-oidc = deny+/api/k8s/{path...} | namespaced-secrets | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-secrets | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-secrets | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-secrets | DELETE | spa = deny+/api/k8s/{path...} | namespaced-secrets | DELETE | user-key = deny+/api/k8s/{path...} | namespaced-secrets | DELETE | user-key-verified = deny+/api/k8s/{path...} | namespaced-secrets | GET | admin-spa = deny+/api/k8s/{path...} | namespaced-secrets | GET | cua-cli = deny+/api/k8s/{path...} | namespaced-secrets | GET | dcr-client = deny+/api/k8s/{path...} | namespaced-secrets | GET | empty-sub = deny+/api/k8s/{path...} | namespaced-secrets | GET | github-oidc = deny+/api/k8s/{path...} | namespaced-secrets | GET | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-secrets | GET | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-secrets | GET | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-secrets | GET | spa = deny+/api/k8s/{path...} | namespaced-secrets | GET | user-key = deny+/api/k8s/{path...} | namespaced-secrets | GET | user-key-verified = deny+/api/k8s/{path...} | namespaced-secrets | PATCH | admin-spa = deny+/api/k8s/{path...} | namespaced-secrets | PATCH | cua-cli = deny+/api/k8s/{path...} | namespaced-secrets | PATCH | dcr-client = deny+/api/k8s/{path...} | namespaced-secrets | PATCH | empty-sub = deny+/api/k8s/{path...} | namespaced-secrets | PATCH | github-oidc = deny+/api/k8s/{path...} | namespaced-secrets | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-secrets | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-secrets | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-secrets | PATCH | spa = deny+/api/k8s/{path...} | namespaced-secrets | PATCH | user-key = deny+/api/k8s/{path...} | namespaced-secrets | PATCH | user-key-verified = deny+/api/k8s/{path...} | namespaced-secrets | POST | admin-spa = deny+/api/k8s/{path...} | namespaced-secrets | POST | cua-cli = deny+/api/k8s/{path...} | namespaced-secrets | POST | dcr-client = deny+/api/k8s/{path...} | namespaced-secrets | POST | empty-sub = deny+/api/k8s/{path...} | namespaced-secrets | POST | github-oidc = deny+/api/k8s/{path...} | namespaced-secrets | POST | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-secrets | POST | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-secrets | POST | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-secrets | POST | spa = deny+/api/k8s/{path...} | namespaced-secrets | POST | user-key = deny+/api/k8s/{path...} | namespaced-secrets | POST | user-key-verified = deny+/api/k8s/{path...} | namespaced-secrets | QUERY | admin-spa = deny+/api/k8s/{path...} | namespaced-secrets | QUERY | cua-cli = deny+/api/k8s/{path...} | namespaced-secrets | QUERY | dcr-client = deny+/api/k8s/{path...} | namespaced-secrets | QUERY | empty-sub = deny+/api/k8s/{path...} | namespaced-secrets | QUERY | github-oidc = deny+/api/k8s/{path...} | namespaced-secrets | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | namespaced-secrets | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | namespaced-secrets | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | namespaced-secrets | QUERY | spa = deny+/api/k8s/{path...} | namespaced-secrets | QUERY | user-key = deny+/api/k8s/{path...} | namespaced-secrets | QUERY | user-key-verified = deny+/api/k8s/{path...} | pod-logs | DELETE | admin-spa = deny+/api/k8s/{path...} | pod-logs | DELETE | cua-cli = deny+/api/k8s/{path...} | pod-logs | DELETE | dcr-client = deny+/api/k8s/{path...} | pod-logs | DELETE | empty-sub = deny+/api/k8s/{path...} | pod-logs | DELETE | github-oidc = deny+/api/k8s/{path...} | pod-logs | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | pod-logs | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | pod-logs | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | pod-logs | DELETE | spa = deny+/api/k8s/{path...} | pod-logs | DELETE | user-key = deny+/api/k8s/{path...} | pod-logs | DELETE | user-key-verified = deny+/api/k8s/{path...} | pod-logs | GET | admin-spa = allow+/api/k8s/{path...} | pod-logs | GET | cua-cli = allow+/api/k8s/{path...} | pod-logs | GET | dcr-client = deny+/api/k8s/{path...} | pod-logs | GET | empty-sub = deny+/api/k8s/{path...} | pod-logs | GET | github-oidc = deny+/api/k8s/{path...} | pod-logs | GET | oauth2-proxy = deny+/api/k8s/{path...} | pod-logs | GET | per-key-other-ns = deny+/api/k8s/{path...} | pod-logs | GET | per-key-owned-ns = deny+/api/k8s/{path...} | pod-logs | GET | spa = allow+/api/k8s/{path...} | pod-logs | GET | user-key = allow+/api/k8s/{path...} | pod-logs | GET | user-key-verified = allow+/api/k8s/{path...} | pod-logs | PATCH | admin-spa = deny+/api/k8s/{path...} | pod-logs | PATCH | cua-cli = deny+/api/k8s/{path...} | pod-logs | PATCH | dcr-client = deny+/api/k8s/{path...} | pod-logs | PATCH | empty-sub = deny+/api/k8s/{path...} | pod-logs | PATCH | github-oidc = deny+/api/k8s/{path...} | pod-logs | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | pod-logs | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | pod-logs | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | pod-logs | PATCH | spa = deny+/api/k8s/{path...} | pod-logs | PATCH | user-key = deny+/api/k8s/{path...} | pod-logs | PATCH | user-key-verified = deny+/api/k8s/{path...} | pod-logs | POST | admin-spa = deny+/api/k8s/{path...} | pod-logs | POST | cua-cli = deny+/api/k8s/{path...} | pod-logs | POST | dcr-client = deny+/api/k8s/{path...} | pod-logs | POST | empty-sub = deny+/api/k8s/{path...} | pod-logs | POST | github-oidc = deny+/api/k8s/{path...} | pod-logs | POST | oauth2-proxy = deny+/api/k8s/{path...} | pod-logs | POST | per-key-other-ns = deny+/api/k8s/{path...} | pod-logs | POST | per-key-owned-ns = deny+/api/k8s/{path...} | pod-logs | POST | spa = deny+/api/k8s/{path...} | pod-logs | POST | user-key = deny+/api/k8s/{path...} | pod-logs | POST | user-key-verified = deny+/api/k8s/{path...} | pod-logs | QUERY | admin-spa = deny+/api/k8s/{path...} | pod-logs | QUERY | cua-cli = deny+/api/k8s/{path...} | pod-logs | QUERY | dcr-client = deny+/api/k8s/{path...} | pod-logs | QUERY | empty-sub = deny+/api/k8s/{path...} | pod-logs | QUERY | github-oidc = deny+/api/k8s/{path...} | pod-logs | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | pod-logs | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | pod-logs | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | pod-logs | QUERY | spa = deny+/api/k8s/{path...} | pod-logs | QUERY | user-key = deny+/api/k8s/{path...} | pod-logs | QUERY | user-key-verified = deny+/api/k8s/{path...} | pool-create-allowed-image | DELETE | admin-spa = deny+/api/k8s/{path...} | pool-create-allowed-image | DELETE | cua-cli = deny+/api/k8s/{path...} | pool-create-allowed-image | DELETE | dcr-client = deny+/api/k8s/{path...} | pool-create-allowed-image | DELETE | empty-sub = deny+/api/k8s/{path...} | pool-create-allowed-image | DELETE | github-oidc = allow+/api/k8s/{path...} | pool-create-allowed-image | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | pool-create-allowed-image | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | pool-create-allowed-image | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | pool-create-allowed-image | DELETE | spa = deny+/api/k8s/{path...} | pool-create-allowed-image | DELETE | user-key = deny+/api/k8s/{path...} | pool-create-allowed-image | DELETE | user-key-verified = deny+/api/k8s/{path...} | pool-create-allowed-image | GET | admin-spa = allow+/api/k8s/{path...} | pool-create-allowed-image | GET | cua-cli = allow+/api/k8s/{path...} | pool-create-allowed-image | GET | dcr-client = deny+/api/k8s/{path...} | pool-create-allowed-image | GET | empty-sub = deny+/api/k8s/{path...} | pool-create-allowed-image | GET | github-oidc = allow+/api/k8s/{path...} | pool-create-allowed-image | GET | oauth2-proxy = deny+/api/k8s/{path...} | pool-create-allowed-image | GET | per-key-other-ns = deny+/api/k8s/{path...} | pool-create-allowed-image | GET | per-key-owned-ns = deny+/api/k8s/{path...} | pool-create-allowed-image | GET | spa = allow+/api/k8s/{path...} | pool-create-allowed-image | GET | user-key = allow+/api/k8s/{path...} | pool-create-allowed-image | GET | user-key-verified = allow+/api/k8s/{path...} | pool-create-allowed-image | PATCH | admin-spa = deny+/api/k8s/{path...} | pool-create-allowed-image | PATCH | cua-cli = deny+/api/k8s/{path...} | pool-create-allowed-image | PATCH | dcr-client = deny+/api/k8s/{path...} | pool-create-allowed-image | PATCH | empty-sub = deny+/api/k8s/{path...} | pool-create-allowed-image | PATCH | github-oidc = allow+/api/k8s/{path...} | pool-create-allowed-image | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | pool-create-allowed-image | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | pool-create-allowed-image | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | pool-create-allowed-image | PATCH | spa = deny+/api/k8s/{path...} | pool-create-allowed-image | PATCH | user-key = deny+/api/k8s/{path...} | pool-create-allowed-image | PATCH | user-key-verified = deny+/api/k8s/{path...} | pool-create-allowed-image | POST | admin-spa = allow+/api/k8s/{path...} | pool-create-allowed-image | POST | cua-cli = allow+/api/k8s/{path...} | pool-create-allowed-image | POST | dcr-client = deny+/api/k8s/{path...} | pool-create-allowed-image | POST | empty-sub = deny+/api/k8s/{path...} | pool-create-allowed-image | POST | github-oidc = allow+/api/k8s/{path...} | pool-create-allowed-image | POST | oauth2-proxy = deny+/api/k8s/{path...} | pool-create-allowed-image | POST | per-key-other-ns = deny+/api/k8s/{path...} | pool-create-allowed-image | POST | per-key-owned-ns = deny+/api/k8s/{path...} | pool-create-allowed-image | POST | spa = allow+/api/k8s/{path...} | pool-create-allowed-image | POST | user-key = allow+/api/k8s/{path...} | pool-create-allowed-image | POST | user-key-verified = allow+/api/k8s/{path...} | pool-create-allowed-image | QUERY | admin-spa = deny+/api/k8s/{path...} | pool-create-allowed-image | QUERY | cua-cli = deny+/api/k8s/{path...} | pool-create-allowed-image | QUERY | dcr-client = deny+/api/k8s/{path...} | pool-create-allowed-image | QUERY | empty-sub = deny+/api/k8s/{path...} | pool-create-allowed-image | QUERY | github-oidc = deny+/api/k8s/{path...} | pool-create-allowed-image | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | pool-create-allowed-image | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | pool-create-allowed-image | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | pool-create-allowed-image | QUERY | spa = deny+/api/k8s/{path...} | pool-create-allowed-image | QUERY | user-key = deny+/api/k8s/{path...} | pool-create-allowed-image | QUERY | user-key-verified = deny+/api/k8s/{path...} | pool-create-disallowed-image | DELETE | admin-spa = deny+/api/k8s/{path...} | pool-create-disallowed-image | DELETE | cua-cli = deny+/api/k8s/{path...} | pool-create-disallowed-image | DELETE | dcr-client = deny+/api/k8s/{path...} | pool-create-disallowed-image | DELETE | empty-sub = deny+/api/k8s/{path...} | pool-create-disallowed-image | DELETE | github-oidc = allow+/api/k8s/{path...} | pool-create-disallowed-image | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | pool-create-disallowed-image | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | pool-create-disallowed-image | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | pool-create-disallowed-image | DELETE | spa = deny+/api/k8s/{path...} | pool-create-disallowed-image | DELETE | user-key = deny+/api/k8s/{path...} | pool-create-disallowed-image | DELETE | user-key-verified = deny+/api/k8s/{path...} | pool-create-disallowed-image | GET | admin-spa = allow+/api/k8s/{path...} | pool-create-disallowed-image | GET | cua-cli = allow+/api/k8s/{path...} | pool-create-disallowed-image | GET | dcr-client = deny+/api/k8s/{path...} | pool-create-disallowed-image | GET | empty-sub = deny+/api/k8s/{path...} | pool-create-disallowed-image | GET | github-oidc = allow+/api/k8s/{path...} | pool-create-disallowed-image | GET | oauth2-proxy = deny+/api/k8s/{path...} | pool-create-disallowed-image | GET | per-key-other-ns = deny+/api/k8s/{path...} | pool-create-disallowed-image | GET | per-key-owned-ns = deny+/api/k8s/{path...} | pool-create-disallowed-image | GET | spa = allow+/api/k8s/{path...} | pool-create-disallowed-image | GET | user-key = allow+/api/k8s/{path...} | pool-create-disallowed-image | GET | user-key-verified = allow+/api/k8s/{path...} | pool-create-disallowed-image | PATCH | admin-spa = deny+/api/k8s/{path...} | pool-create-disallowed-image | PATCH | cua-cli = deny+/api/k8s/{path...} | pool-create-disallowed-image | PATCH | dcr-client = deny+/api/k8s/{path...} | pool-create-disallowed-image | PATCH | empty-sub = deny+/api/k8s/{path...} | pool-create-disallowed-image | PATCH | github-oidc = deny+/api/k8s/{path...} | pool-create-disallowed-image | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | pool-create-disallowed-image | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | pool-create-disallowed-image | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | pool-create-disallowed-image | PATCH | spa = deny+/api/k8s/{path...} | pool-create-disallowed-image | PATCH | user-key = deny+/api/k8s/{path...} | pool-create-disallowed-image | PATCH | user-key-verified = deny+/api/k8s/{path...} | pool-create-disallowed-image | POST | admin-spa = deny+/api/k8s/{path...} | pool-create-disallowed-image | POST | cua-cli = deny+/api/k8s/{path...} | pool-create-disallowed-image | POST | dcr-client = deny+/api/k8s/{path...} | pool-create-disallowed-image | POST | empty-sub = deny+/api/k8s/{path...} | pool-create-disallowed-image | POST | github-oidc = deny+/api/k8s/{path...} | pool-create-disallowed-image | POST | oauth2-proxy = deny+/api/k8s/{path...} | pool-create-disallowed-image | POST | per-key-other-ns = deny+/api/k8s/{path...} | pool-create-disallowed-image | POST | per-key-owned-ns = deny+/api/k8s/{path...} | pool-create-disallowed-image | POST | spa = deny+/api/k8s/{path...} | pool-create-disallowed-image | POST | user-key = deny+/api/k8s/{path...} | pool-create-disallowed-image | POST | user-key-verified = deny+/api/k8s/{path...} | pool-create-disallowed-image | QUERY | admin-spa = deny+/api/k8s/{path...} | pool-create-disallowed-image | QUERY | cua-cli = deny+/api/k8s/{path...} | pool-create-disallowed-image | QUERY | dcr-client = deny+/api/k8s/{path...} | pool-create-disallowed-image | QUERY | empty-sub = deny+/api/k8s/{path...} | pool-create-disallowed-image | QUERY | github-oidc = deny+/api/k8s/{path...} | pool-create-disallowed-image | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | pool-create-disallowed-image | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | pool-create-disallowed-image | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | pool-create-disallowed-image | QUERY | spa = deny+/api/k8s/{path...} | pool-create-disallowed-image | QUERY | user-key = deny+/api/k8s/{path...} | pool-create-disallowed-image | QUERY | user-key-verified = deny+/api/k8s/{path...} | ungranted-ns-pools | DELETE | admin-spa = deny+/api/k8s/{path...} | ungranted-ns-pools | DELETE | cua-cli = deny+/api/k8s/{path...} | ungranted-ns-pools | DELETE | dcr-client = deny+/api/k8s/{path...} | ungranted-ns-pools | DELETE | empty-sub = deny+/api/k8s/{path...} | ungranted-ns-pools | DELETE | github-oidc = deny+/api/k8s/{path...} | ungranted-ns-pools | DELETE | oauth2-proxy = deny+/api/k8s/{path...} | ungranted-ns-pools | DELETE | per-key-other-ns = deny+/api/k8s/{path...} | ungranted-ns-pools | DELETE | per-key-owned-ns = deny+/api/k8s/{path...} | ungranted-ns-pools | DELETE | spa = deny+/api/k8s/{path...} | ungranted-ns-pools | DELETE | user-key = deny+/api/k8s/{path...} | ungranted-ns-pools | DELETE | user-key-verified = deny+/api/k8s/{path...} | ungranted-ns-pools | GET | admin-spa = allow+/api/k8s/{path...} | ungranted-ns-pools | GET | cua-cli = allow+/api/k8s/{path...} | ungranted-ns-pools | GET | dcr-client = deny+/api/k8s/{path...} | ungranted-ns-pools | GET | empty-sub = deny+/api/k8s/{path...} | ungranted-ns-pools | GET | github-oidc = deny+/api/k8s/{path...} | ungranted-ns-pools | GET | oauth2-proxy = deny+/api/k8s/{path...} | ungranted-ns-pools | GET | per-key-other-ns = deny+/api/k8s/{path...} | ungranted-ns-pools | GET | per-key-owned-ns = deny+/api/k8s/{path...} | ungranted-ns-pools | GET | spa = allow+/api/k8s/{path...} | ungranted-ns-pools | GET | user-key = allow+/api/k8s/{path...} | ungranted-ns-pools | GET | user-key-verified = allow+/api/k8s/{path...} | ungranted-ns-pools | PATCH | admin-spa = deny+/api/k8s/{path...} | ungranted-ns-pools | PATCH | cua-cli = deny+/api/k8s/{path...} | ungranted-ns-pools | PATCH | dcr-client = deny+/api/k8s/{path...} | ungranted-ns-pools | PATCH | empty-sub = deny+/api/k8s/{path...} | ungranted-ns-pools | PATCH | github-oidc = deny+/api/k8s/{path...} | ungranted-ns-pools | PATCH | oauth2-proxy = deny+/api/k8s/{path...} | ungranted-ns-pools | PATCH | per-key-other-ns = deny+/api/k8s/{path...} | ungranted-ns-pools | PATCH | per-key-owned-ns = deny+/api/k8s/{path...} | ungranted-ns-pools | PATCH | spa = deny+/api/k8s/{path...} | ungranted-ns-pools | PATCH | user-key = deny+/api/k8s/{path...} | ungranted-ns-pools | PATCH | user-key-verified = deny+/api/k8s/{path...} | ungranted-ns-pools | POST | admin-spa = allow+/api/k8s/{path...} | ungranted-ns-pools | POST | cua-cli = allow+/api/k8s/{path...} | ungranted-ns-pools | POST | dcr-client = deny+/api/k8s/{path...} | ungranted-ns-pools | POST | empty-sub = deny+/api/k8s/{path...} | ungranted-ns-pools | POST | github-oidc = deny+/api/k8s/{path...} | ungranted-ns-pools | POST | oauth2-proxy = deny+/api/k8s/{path...} | ungranted-ns-pools | POST | per-key-other-ns = deny+/api/k8s/{path...} | ungranted-ns-pools | POST | per-key-owned-ns = deny+/api/k8s/{path...} | ungranted-ns-pools | POST | spa = allow+/api/k8s/{path...} | ungranted-ns-pools | POST | user-key = allow+/api/k8s/{path...} | ungranted-ns-pools | POST | user-key-verified = allow+/api/k8s/{path...} | ungranted-ns-pools | QUERY | admin-spa = deny+/api/k8s/{path...} | ungranted-ns-pools | QUERY | cua-cli = deny+/api/k8s/{path...} | ungranted-ns-pools | QUERY | dcr-client = deny+/api/k8s/{path...} | ungranted-ns-pools | QUERY | empty-sub = deny+/api/k8s/{path...} | ungranted-ns-pools | QUERY | github-oidc = deny+/api/k8s/{path...} | ungranted-ns-pools | QUERY | oauth2-proxy = deny+/api/k8s/{path...} | ungranted-ns-pools | QUERY | per-key-other-ns = deny+/api/k8s/{path...} | ungranted-ns-pools | QUERY | per-key-owned-ns = deny+/api/k8s/{path...} | ungranted-ns-pools | QUERY | spa = deny+/api/k8s/{path...} | ungranted-ns-pools | QUERY | user-key = deny+/api/k8s/{path...} | ungranted-ns-pools | QUERY | user-key-verified = deny+/api/keys | plain | DELETE | admin-spa = allow+/api/keys | plain | DELETE | cua-cli = allow+/api/keys | plain | DELETE | dcr-client = deny+/api/keys | plain | DELETE | empty-sub = deny+/api/keys | plain | DELETE | github-oidc = deny+/api/keys | plain | DELETE | oauth2-proxy = deny+/api/keys | plain | DELETE | per-key-other-ns = deny+/api/keys | plain | DELETE | per-key-owned-ns = deny+/api/keys | plain | DELETE | spa = allow+/api/keys | plain | DELETE | user-key = deny+/api/keys | plain | DELETE | user-key-verified = deny+/api/keys | plain | GET | admin-spa = allow+/api/keys | plain | GET | cua-cli = allow+/api/keys | plain | GET | dcr-client = deny+/api/keys | plain | GET | empty-sub = deny+/api/keys | plain | GET | github-oidc = deny+/api/keys | plain | GET | oauth2-proxy = deny+/api/keys | plain | GET | per-key-other-ns = deny+/api/keys | plain | GET | per-key-owned-ns = deny+/api/keys | plain | GET | spa = allow+/api/keys | plain | GET | user-key = deny+/api/keys | plain | GET | user-key-verified = deny+/api/keys | plain | PATCH | admin-spa = allow+/api/keys | plain | PATCH | cua-cli = allow+/api/keys | plain | PATCH | dcr-client = deny+/api/keys | plain | PATCH | empty-sub = deny+/api/keys | plain | PATCH | github-oidc = deny+/api/keys | plain | PATCH | oauth2-proxy = deny+/api/keys | plain | PATCH | per-key-other-ns = deny+/api/keys | plain | PATCH | per-key-owned-ns = deny+/api/keys | plain | PATCH | spa = allow+/api/keys | plain | PATCH | user-key = deny+/api/keys | plain | PATCH | user-key-verified = deny+/api/keys | plain | POST | admin-spa = allow+/api/keys | plain | POST | cua-cli = allow+/api/keys | plain | POST | dcr-client = deny+/api/keys | plain | POST | empty-sub = deny+/api/keys | plain | POST | github-oidc = deny+/api/keys | plain | POST | oauth2-proxy = deny+/api/keys | plain | POST | per-key-other-ns = deny+/api/keys | plain | POST | per-key-owned-ns = deny+/api/keys | plain | POST | spa = allow+/api/keys | plain | POST | user-key = deny+/api/keys | plain | POST | user-key-verified = deny+/api/keys | plain | QUERY | admin-spa = allow+/api/keys | plain | QUERY | cua-cli = allow+/api/keys | plain | QUERY | dcr-client = deny+/api/keys | plain | QUERY | empty-sub = deny+/api/keys | plain | QUERY | github-oidc = deny+/api/keys | plain | QUERY | oauth2-proxy = deny+/api/keys | plain | QUERY | per-key-other-ns = deny+/api/keys | plain | QUERY | per-key-owned-ns = deny+/api/keys | plain | QUERY | spa = allow+/api/keys | plain | QUERY | user-key = deny+/api/keys | plain | QUERY | user-key-verified = deny+/api/keys/{id} | id | DELETE | admin-spa = allow+/api/keys/{id} | id | DELETE | cua-cli = allow+/api/keys/{id} | id | DELETE | dcr-client = deny+/api/keys/{id} | id | DELETE | empty-sub = deny+/api/keys/{id} | id | DELETE | github-oidc = deny+/api/keys/{id} | id | DELETE | oauth2-proxy = deny+/api/keys/{id} | id | DELETE | per-key-other-ns = deny+/api/keys/{id} | id | DELETE | per-key-owned-ns = deny+/api/keys/{id} | id | DELETE | spa = allow+/api/keys/{id} | id | DELETE | user-key = deny+/api/keys/{id} | id | DELETE | user-key-verified = deny+/api/keys/{id} | id | GET | admin-spa = allow+/api/keys/{id} | id | GET | cua-cli = allow+/api/keys/{id} | id | GET | dcr-client = deny+/api/keys/{id} | id | GET | empty-sub = deny+/api/keys/{id} | id | GET | github-oidc = deny+/api/keys/{id} | id | GET | oauth2-proxy = deny+/api/keys/{id} | id | GET | per-key-other-ns = deny+/api/keys/{id} | id | GET | per-key-owned-ns = deny+/api/keys/{id} | id | GET | spa = allow+/api/keys/{id} | id | GET | user-key = deny+/api/keys/{id} | id | GET | user-key-verified = deny+/api/keys/{id} | id | PATCH | admin-spa = allow+/api/keys/{id} | id | PATCH | cua-cli = allow+/api/keys/{id} | id | PATCH | dcr-client = deny+/api/keys/{id} | id | PATCH | empty-sub = deny+/api/keys/{id} | id | PATCH | github-oidc = deny+/api/keys/{id} | id | PATCH | oauth2-proxy = deny+/api/keys/{id} | id | PATCH | per-key-other-ns = deny+/api/keys/{id} | id | PATCH | per-key-owned-ns = deny+/api/keys/{id} | id | PATCH | spa = allow+/api/keys/{id} | id | PATCH | user-key = deny+/api/keys/{id} | id | PATCH | user-key-verified = deny+/api/keys/{id} | id | POST | admin-spa = allow+/api/keys/{id} | id | POST | cua-cli = allow+/api/keys/{id} | id | POST | dcr-client = deny+/api/keys/{id} | id | POST | empty-sub = deny+/api/keys/{id} | id | POST | github-oidc = deny+/api/keys/{id} | id | POST | oauth2-proxy = deny+/api/keys/{id} | id | POST | per-key-other-ns = deny+/api/keys/{id} | id | POST | per-key-owned-ns = deny+/api/keys/{id} | id | POST | spa = allow+/api/keys/{id} | id | POST | user-key = deny+/api/keys/{id} | id | POST | user-key-verified = deny+/api/keys/{id} | id | QUERY | admin-spa = allow+/api/keys/{id} | id | QUERY | cua-cli = allow+/api/keys/{id} | id | QUERY | dcr-client = deny+/api/keys/{id} | id | QUERY | empty-sub = deny+/api/keys/{id} | id | QUERY | github-oidc = deny+/api/keys/{id} | id | QUERY | oauth2-proxy = deny+/api/keys/{id} | id | QUERY | per-key-other-ns = deny+/api/keys/{id} | id | QUERY | per-key-owned-ns = deny+/api/keys/{id} | id | QUERY | spa = allow+/api/keys/{id} | id | QUERY | user-key = deny+/api/keys/{id} | id | QUERY | user-key-verified = deny+/api/namespaces | plain | DELETE | admin-spa = allow+/api/namespaces | plain | DELETE | cua-cli = allow+/api/namespaces | plain | DELETE | dcr-client = deny+/api/namespaces | plain | DELETE | empty-sub = deny+/api/namespaces | plain | DELETE | github-oidc = allow+/api/namespaces | plain | DELETE | oauth2-proxy = deny+/api/namespaces | plain | DELETE | per-key-other-ns = deny+/api/namespaces | plain | DELETE | per-key-owned-ns = deny+/api/namespaces | plain | DELETE | spa = allow+/api/namespaces | plain | DELETE | user-key = allow+/api/namespaces | plain | DELETE | user-key-verified = allow+/api/namespaces | plain | GET | admin-spa = allow+/api/namespaces | plain | GET | cua-cli = allow+/api/namespaces | plain | GET | dcr-client = deny+/api/namespaces | plain | GET | empty-sub = deny+/api/namespaces | plain | GET | github-oidc = allow+/api/namespaces | plain | GET | oauth2-proxy = deny+/api/namespaces | plain | GET | per-key-other-ns = deny+/api/namespaces | plain | GET | per-key-owned-ns = deny+/api/namespaces | plain | GET | spa = allow+/api/namespaces | plain | GET | user-key = allow+/api/namespaces | plain | GET | user-key-verified = allow+/api/namespaces | plain | PATCH | admin-spa = allow+/api/namespaces | plain | PATCH | cua-cli = allow+/api/namespaces | plain | PATCH | dcr-client = deny+/api/namespaces | plain | PATCH | empty-sub = deny+/api/namespaces | plain | PATCH | github-oidc = allow+/api/namespaces | plain | PATCH | oauth2-proxy = deny+/api/namespaces | plain | PATCH | per-key-other-ns = deny+/api/namespaces | plain | PATCH | per-key-owned-ns = deny+/api/namespaces | plain | PATCH | spa = allow+/api/namespaces | plain | PATCH | user-key = allow+/api/namespaces | plain | PATCH | user-key-verified = allow+/api/namespaces | plain | POST | admin-spa = allow+/api/namespaces | plain | POST | cua-cli = allow+/api/namespaces | plain | POST | dcr-client = deny+/api/namespaces | plain | POST | empty-sub = deny+/api/namespaces | plain | POST | github-oidc = allow+/api/namespaces | plain | POST | oauth2-proxy = deny+/api/namespaces | plain | POST | per-key-other-ns = deny+/api/namespaces | plain | POST | per-key-owned-ns = deny+/api/namespaces | plain | POST | spa = allow+/api/namespaces | plain | POST | user-key = allow+/api/namespaces | plain | POST | user-key-verified = allow+/api/namespaces | plain | QUERY | admin-spa = allow+/api/namespaces | plain | QUERY | cua-cli = allow+/api/namespaces | plain | QUERY | dcr-client = deny+/api/namespaces | plain | QUERY | empty-sub = deny+/api/namespaces | plain | QUERY | github-oidc = allow+/api/namespaces | plain | QUERY | oauth2-proxy = deny+/api/namespaces | plain | QUERY | per-key-other-ns = deny+/api/namespaces | plain | QUERY | per-key-owned-ns = deny+/api/namespaces | plain | QUERY | spa = allow+/api/namespaces | plain | QUERY | user-key = allow+/api/namespaces | plain | QUERY | user-key-verified = allow+/api/namespaces/{name} | name | DELETE | admin-spa = allow+/api/namespaces/{name} | name | DELETE | cua-cli = allow+/api/namespaces/{name} | name | DELETE | dcr-client = deny+/api/namespaces/{name} | name | DELETE | empty-sub = deny+/api/namespaces/{name} | name | DELETE | github-oidc = allow+/api/namespaces/{name} | name | DELETE | oauth2-proxy = deny+/api/namespaces/{name} | name | DELETE | per-key-other-ns = deny+/api/namespaces/{name} | name | DELETE | per-key-owned-ns = deny+/api/namespaces/{name} | name | DELETE | spa = allow+/api/namespaces/{name} | name | DELETE | user-key = allow+/api/namespaces/{name} | name | DELETE | user-key-verified = allow+/api/namespaces/{name} | name | GET | admin-spa = allow+/api/namespaces/{name} | name | GET | cua-cli = allow+/api/namespaces/{name} | name | GET | dcr-client = deny+/api/namespaces/{name} | name | GET | empty-sub = deny+/api/namespaces/{name} | name | GET | github-oidc = allow+/api/namespaces/{name} | name | GET | oauth2-proxy = deny+/api/namespaces/{name} | name | GET | per-key-other-ns = deny+/api/namespaces/{name} | name | GET | per-key-owned-ns = deny+/api/namespaces/{name} | name | GET | spa = allow+/api/namespaces/{name} | name | GET | user-key = allow+/api/namespaces/{name} | name | GET | user-key-verified = allow+/api/namespaces/{name} | name | PATCH | admin-spa = allow+/api/namespaces/{name} | name | PATCH | cua-cli = allow+/api/namespaces/{name} | name | PATCH | dcr-client = deny+/api/namespaces/{name} | name | PATCH | empty-sub = deny+/api/namespaces/{name} | name | PATCH | github-oidc = allow+/api/namespaces/{name} | name | PATCH | oauth2-proxy = deny+/api/namespaces/{name} | name | PATCH | per-key-other-ns = deny+/api/namespaces/{name} | name | PATCH | per-key-owned-ns = deny+/api/namespaces/{name} | name | PATCH | spa = allow+/api/namespaces/{name} | name | PATCH | user-key = allow+/api/namespaces/{name} | name | PATCH | user-key-verified = allow+/api/namespaces/{name} | name | POST | admin-spa = allow+/api/namespaces/{name} | name | POST | cua-cli = allow+/api/namespaces/{name} | name | POST | dcr-client = deny+/api/namespaces/{name} | name | POST | empty-sub = deny+/api/namespaces/{name} | name | POST | github-oidc = allow+/api/namespaces/{name} | name | POST | oauth2-proxy = deny+/api/namespaces/{name} | name | POST | per-key-other-ns = deny+/api/namespaces/{name} | name | POST | per-key-owned-ns = deny+/api/namespaces/{name} | name | POST | spa = allow+/api/namespaces/{name} | name | POST | user-key = allow+/api/namespaces/{name} | name | POST | user-key-verified = allow+/api/namespaces/{name} | name | QUERY | admin-spa = allow+/api/namespaces/{name} | name | QUERY | cua-cli = allow+/api/namespaces/{name} | name | QUERY | dcr-client = deny+/api/namespaces/{name} | name | QUERY | empty-sub = deny+/api/namespaces/{name} | name | QUERY | github-oidc = allow+/api/namespaces/{name} | name | QUERY | oauth2-proxy = deny+/api/namespaces/{name} | name | QUERY | per-key-other-ns = deny+/api/namespaces/{name} | name | QUERY | per-key-owned-ns = deny+/api/namespaces/{name} | name | QUERY | spa = allow+/api/namespaces/{name} | name | QUERY | user-key = allow+/api/namespaces/{name} | name | QUERY | user-key-verified = allow+/api/namespaces/{name} | unowned-name | DELETE | admin-spa = allow+/api/namespaces/{name} | unowned-name | DELETE | cua-cli = allow+/api/namespaces/{name} | unowned-name | DELETE | dcr-client = deny+/api/namespaces/{name} | unowned-name | DELETE | empty-sub = deny+/api/namespaces/{name} | unowned-name | DELETE | github-oidc = allow+/api/namespaces/{name} | unowned-name | DELETE | oauth2-proxy = deny+/api/namespaces/{name} | unowned-name | DELETE | per-key-other-ns = deny+/api/namespaces/{name} | unowned-name | DELETE | per-key-owned-ns = deny+/api/namespaces/{name} | unowned-name | DELETE | spa = allow+/api/namespaces/{name} | unowned-name | DELETE | user-key = allow+/api/namespaces/{name} | unowned-name | DELETE | user-key-verified = allow+/api/namespaces/{name} | unowned-name | GET | admin-spa = deny+/api/namespaces/{name} | unowned-name | GET | cua-cli = deny+/api/namespaces/{name} | unowned-name | GET | dcr-client = deny+/api/namespaces/{name} | unowned-name | GET | empty-sub = deny+/api/namespaces/{name} | unowned-name | GET | github-oidc = deny+/api/namespaces/{name} | unowned-name | GET | oauth2-proxy = deny+/api/namespaces/{name} | unowned-name | GET | per-key-other-ns = deny+/api/namespaces/{name} | unowned-name | GET | per-key-owned-ns = deny+/api/namespaces/{name} | unowned-name | GET | spa = deny+/api/namespaces/{name} | unowned-name | GET | user-key = deny+/api/namespaces/{name} | unowned-name | GET | user-key-verified = deny+/api/namespaces/{name} | unowned-name | PATCH | admin-spa = allow+/api/namespaces/{name} | unowned-name | PATCH | cua-cli = allow+/api/namespaces/{name} | unowned-name | PATCH | dcr-client = deny+/api/namespaces/{name} | unowned-name | PATCH | empty-sub = deny+/api/namespaces/{name} | unowned-name | PATCH | github-oidc = allow+/api/namespaces/{name} | unowned-name | PATCH | oauth2-proxy = deny+/api/namespaces/{name} | unowned-name | PATCH | per-key-other-ns = deny+/api/namespaces/{name} | unowned-name | PATCH | per-key-owned-ns = deny+/api/namespaces/{name} | unowned-name | PATCH | spa = allow+/api/namespaces/{name} | unowned-name | PATCH | user-key = allow+/api/namespaces/{name} | unowned-name | PATCH | user-key-verified = allow+/api/namespaces/{name} | unowned-name | POST | admin-spa = allow+/api/namespaces/{name} | unowned-name | POST | cua-cli = allow+/api/namespaces/{name} | unowned-name | POST | dcr-client = deny+/api/namespaces/{name} | unowned-name | POST | empty-sub = deny+/api/namespaces/{name} | unowned-name | POST | github-oidc = allow+/api/namespaces/{name} | unowned-name | POST | oauth2-proxy = deny+/api/namespaces/{name} | unowned-name | POST | per-key-other-ns = deny+/api/namespaces/{name} | unowned-name | POST | per-key-owned-ns = deny+/api/namespaces/{name} | unowned-name | POST | spa = allow+/api/namespaces/{name} | unowned-name | POST | user-key = allow+/api/namespaces/{name} | unowned-name | POST | user-key-verified = allow+/api/namespaces/{name} | unowned-name | QUERY | admin-spa = allow+/api/namespaces/{name} | unowned-name | QUERY | cua-cli = allow+/api/namespaces/{name} | unowned-name | QUERY | dcr-client = deny+/api/namespaces/{name} | unowned-name | QUERY | empty-sub = deny+/api/namespaces/{name} | unowned-name | QUERY | github-oidc = allow+/api/namespaces/{name} | unowned-name | QUERY | oauth2-proxy = deny+/api/namespaces/{name} | unowned-name | QUERY | per-key-other-ns = deny+/api/namespaces/{name} | unowned-name | QUERY | per-key-owned-ns = deny+/api/namespaces/{name} | unowned-name | QUERY | spa = allow+/api/namespaces/{name} | unowned-name | QUERY | user-key = allow+/api/namespaces/{name} | unowned-name | QUERY | user-key-verified = allow+/api/namespaces/{name} | unreachable-name | DELETE | admin-spa = allow+/api/namespaces/{name} | unreachable-name | DELETE | cua-cli = allow+/api/namespaces/{name} | unreachable-name | DELETE | dcr-client = deny+/api/namespaces/{name} | unreachable-name | DELETE | empty-sub = deny+/api/namespaces/{name} | unreachable-name | DELETE | github-oidc = allow+/api/namespaces/{name} | unreachable-name | DELETE | oauth2-proxy = deny+/api/namespaces/{name} | unreachable-name | DELETE | per-key-other-ns = deny+/api/namespaces/{name} | unreachable-name | DELETE | per-key-owned-ns = deny+/api/namespaces/{name} | unreachable-name | DELETE | spa = allow+/api/namespaces/{name} | unreachable-name | DELETE | user-key = allow+/api/namespaces/{name} | unreachable-name | DELETE | user-key-verified = allow+/api/namespaces/{name} | unreachable-name | GET | admin-spa = error+/api/namespaces/{name} | unreachable-name | GET | cua-cli = error+/api/namespaces/{name} | unreachable-name | GET | dcr-client = deny+/api/namespaces/{name} | unreachable-name | GET | empty-sub = deny+/api/namespaces/{name} | unreachable-name | GET | github-oidc = deny+/api/namespaces/{name} | unreachable-name | GET | oauth2-proxy = deny+/api/namespaces/{name} | unreachable-name | GET | per-key-other-ns = deny+/api/namespaces/{name} | unreachable-name | GET | per-key-owned-ns = deny+/api/namespaces/{name} | unreachable-name | GET | spa = error+/api/namespaces/{name} | unreachable-name | GET | user-key = error+/api/namespaces/{name} | unreachable-name | GET | user-key-verified = error+/api/namespaces/{name} | unreachable-name | PATCH | admin-spa = allow+/api/namespaces/{name} | unreachable-name | PATCH | cua-cli = allow+/api/namespaces/{name} | unreachable-name | PATCH | dcr-client = deny+/api/namespaces/{name} | unreachable-name | PATCH | empty-sub = deny+/api/namespaces/{name} | unreachable-name | PATCH | github-oidc = allow+/api/namespaces/{name} | unreachable-name | PATCH | oauth2-proxy = deny+/api/namespaces/{name} | unreachable-name | PATCH | per-key-other-ns = deny+/api/namespaces/{name} | unreachable-name | PATCH | per-key-owned-ns = deny+/api/namespaces/{name} | unreachable-name | PATCH | spa = allow+/api/namespaces/{name} | unreachable-name | PATCH | user-key = allow+/api/namespaces/{name} | unreachable-name | PATCH | user-key-verified = allow+/api/namespaces/{name} | unreachable-name | POST | admin-spa = allow+/api/namespaces/{name} | unreachable-name | POST | cua-cli = allow+/api/namespaces/{name} | unreachable-name | POST | dcr-client = deny+/api/namespaces/{name} | unreachable-name | POST | empty-sub = deny+/api/namespaces/{name} | unreachable-name | POST | github-oidc = allow+/api/namespaces/{name} | unreachable-name | POST | oauth2-proxy = deny+/api/namespaces/{name} | unreachable-name | POST | per-key-other-ns = deny+/api/namespaces/{name} | unreachable-name | POST | per-key-owned-ns = deny+/api/namespaces/{name} | unreachable-name | POST | spa = allow+/api/namespaces/{name} | unreachable-name | POST | user-key = allow+/api/namespaces/{name} | unreachable-name | POST | user-key-verified = allow+/api/namespaces/{name} | unreachable-name | QUERY | admin-spa = allow+/api/namespaces/{name} | unreachable-name | QUERY | cua-cli = allow+/api/namespaces/{name} | unreachable-name | QUERY | dcr-client = deny+/api/namespaces/{name} | unreachable-name | QUERY | empty-sub = deny+/api/namespaces/{name} | unreachable-name | QUERY | github-oidc = allow+/api/namespaces/{name} | unreachable-name | QUERY | oauth2-proxy = deny+/api/namespaces/{name} | unreachable-name | QUERY | per-key-other-ns = deny+/api/namespaces/{name} | unreachable-name | QUERY | per-key-owned-ns = deny+/api/namespaces/{name} | unreachable-name | QUERY | spa = allow+/api/namespaces/{name} | unreachable-name | QUERY | user-key = allow+/api/namespaces/{name} | unreachable-name | QUERY | user-key-verified = allow+/api/orch/{namespace}/{service}/{path...} | invalid-ns | DELETE | admin-spa = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | DELETE | cua-cli = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | DELETE | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | DELETE | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | DELETE | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | DELETE | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | DELETE | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | DELETE | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | DELETE | spa = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | DELETE | user-key = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | DELETE | user-key-verified = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | GET | admin-spa = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | GET | cua-cli = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | GET | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | GET | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | GET | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | GET | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | GET | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | GET | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | GET | spa = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | GET | user-key = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | GET | user-key-verified = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | PATCH | admin-spa = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | PATCH | cua-cli = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | PATCH | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | PATCH | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | PATCH | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | PATCH | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | PATCH | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | PATCH | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | PATCH | spa = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | PATCH | user-key = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | PATCH | user-key-verified = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | POST | admin-spa = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | POST | cua-cli = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | POST | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | POST | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | POST | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | POST | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | POST | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | POST | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | POST | spa = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | POST | user-key = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | POST | user-key-verified = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | QUERY | admin-spa = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | QUERY | cua-cli = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | QUERY | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | QUERY | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | QUERY | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | QUERY | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | QUERY | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | QUERY | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | QUERY | spa = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | QUERY | user-key = deny+/api/orch/{namespace}/{service}/{path...} | invalid-ns | QUERY | user-key-verified = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | DELETE | admin-spa = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | DELETE | cua-cli = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | DELETE | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | DELETE | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | DELETE | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | DELETE | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | DELETE | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | DELETE | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | DELETE | spa = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | DELETE | user-key = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | DELETE | user-key-verified = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | GET | admin-spa = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | GET | cua-cli = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | GET | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | GET | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | GET | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | GET | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | GET | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | GET | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | GET | spa = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | GET | user-key = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | GET | user-key-verified = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | PATCH | admin-spa = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | PATCH | cua-cli = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | PATCH | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | PATCH | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | PATCH | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | PATCH | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | PATCH | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | PATCH | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | PATCH | spa = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | PATCH | user-key = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | PATCH | user-key-verified = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | POST | admin-spa = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | POST | cua-cli = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | POST | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | POST | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | POST | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | POST | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | POST | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | POST | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | POST | spa = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | POST | user-key = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | POST | user-key-verified = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | QUERY | admin-spa = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | QUERY | cua-cli = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | QUERY | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | QUERY | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | QUERY | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | QUERY | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | QUERY | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | QUERY | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | QUERY | spa = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | QUERY | user-key = deny+/api/orch/{namespace}/{service}/{path...} | other-ns | QUERY | user-key-verified = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | DELETE | admin-spa = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | DELETE | cua-cli = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | DELETE | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | DELETE | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | DELETE | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | DELETE | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | DELETE | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | DELETE | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | DELETE | spa = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | DELETE | user-key = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | DELETE | user-key-verified = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | GET | admin-spa = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | GET | cua-cli = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | GET | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | GET | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | GET | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | GET | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | GET | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | GET | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | GET | spa = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | GET | user-key = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | GET | user-key-verified = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | PATCH | admin-spa = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | PATCH | cua-cli = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | PATCH | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | PATCH | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | PATCH | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | PATCH | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | PATCH | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | PATCH | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | PATCH | spa = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | PATCH | user-key = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | PATCH | user-key-verified = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | POST | admin-spa = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | POST | cua-cli = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | POST | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | POST | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | POST | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | POST | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | POST | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | POST | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | POST | spa = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | POST | user-key = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | POST | user-key-verified = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | QUERY | admin-spa = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | QUERY | cua-cli = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | QUERY | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | QUERY | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | QUERY | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | QUERY | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | QUERY | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | QUERY | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | owned-ns | QUERY | spa = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | QUERY | user-key = allow+/api/orch/{namespace}/{service}/{path...} | owned-ns | QUERY | user-key-verified = allow+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | DELETE | admin-spa = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | DELETE | cua-cli = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | DELETE | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | DELETE | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | DELETE | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | DELETE | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | DELETE | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | DELETE | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | DELETE | spa = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | DELETE | user-key = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | DELETE | user-key-verified = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | GET | admin-spa = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | GET | cua-cli = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | GET | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | GET | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | GET | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | GET | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | GET | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | GET | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | GET | spa = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | GET | user-key = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | GET | user-key-verified = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | PATCH | admin-spa = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | PATCH | cua-cli = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | PATCH | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | PATCH | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | PATCH | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | PATCH | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | PATCH | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | PATCH | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | PATCH | spa = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | PATCH | user-key = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | PATCH | user-key-verified = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | POST | admin-spa = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | POST | cua-cli = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | POST | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | POST | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | POST | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | POST | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | POST | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | POST | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | POST | spa = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | POST | user-key = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | POST | user-key-verified = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | QUERY | admin-spa = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | QUERY | cua-cli = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | QUERY | dcr-client = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | QUERY | empty-sub = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | QUERY | github-oidc = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | QUERY | oauth2-proxy = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | QUERY | per-key-other-ns = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | QUERY | per-key-owned-ns = deny+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | QUERY | spa = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | QUERY | user-key = error+/api/orch/{namespace}/{service}/{path...} | unreachable-ns | QUERY | user-key-verified = error+/api/state/query | plain | DELETE | admin-spa = deny+/api/state/query | plain | DELETE | cua-cli = deny+/api/state/query | plain | DELETE | dcr-client = deny+/api/state/query | plain | DELETE | empty-sub = deny+/api/state/query | plain | DELETE | github-oidc = deny+/api/state/query | plain | DELETE | oauth2-proxy = deny+/api/state/query | plain | DELETE | per-key-other-ns = deny+/api/state/query | plain | DELETE | per-key-owned-ns = deny+/api/state/query | plain | DELETE | spa = deny+/api/state/query | plain | DELETE | user-key = deny+/api/state/query | plain | DELETE | user-key-verified = deny+/api/state/query | plain | GET | admin-spa = deny+/api/state/query | plain | GET | cua-cli = deny+/api/state/query | plain | GET | dcr-client = deny+/api/state/query | plain | GET | empty-sub = deny+/api/state/query | plain | GET | github-oidc = deny+/api/state/query | plain | GET | oauth2-proxy = deny+/api/state/query | plain | GET | per-key-other-ns = deny+/api/state/query | plain | GET | per-key-owned-ns = deny+/api/state/query | plain | GET | spa = deny+/api/state/query | plain | GET | user-key = deny+/api/state/query | plain | GET | user-key-verified = deny+/api/state/query | plain | PATCH | admin-spa = deny+/api/state/query | plain | PATCH | cua-cli = deny+/api/state/query | plain | PATCH | dcr-client = deny+/api/state/query | plain | PATCH | empty-sub = deny+/api/state/query | plain | PATCH | github-oidc = deny+/api/state/query | plain | PATCH | oauth2-proxy = deny+/api/state/query | plain | PATCH | per-key-other-ns = deny+/api/state/query | plain | PATCH | per-key-owned-ns = deny+/api/state/query | plain | PATCH | spa = deny+/api/state/query | plain | PATCH | user-key = deny+/api/state/query | plain | PATCH | user-key-verified = deny+/api/state/query | plain | POST | admin-spa = deny+/api/state/query | plain | POST | cua-cli = deny+/api/state/query | plain | POST | dcr-client = deny+/api/state/query | plain | POST | empty-sub = deny+/api/state/query | plain | POST | github-oidc = deny+/api/state/query | plain | POST | oauth2-proxy = deny+/api/state/query | plain | POST | per-key-other-ns = deny+/api/state/query | plain | POST | per-key-owned-ns = deny+/api/state/query | plain | POST | spa = deny+/api/state/query | plain | POST | user-key = deny+/api/state/query | plain | POST | user-key-verified = deny+/api/state/query | plain | QUERY | admin-spa = allow+/api/state/query | plain | QUERY | cua-cli = allow+/api/state/query | plain | QUERY | dcr-client = deny+/api/state/query | plain | QUERY | empty-sub = deny+/api/state/query | plain | QUERY | github-oidc = deny+/api/state/query | plain | QUERY | oauth2-proxy = deny+/api/state/query | plain | QUERY | per-key-other-ns = deny+/api/state/query | plain | QUERY | per-key-owned-ns = deny+/api/state/query | plain | QUERY | spa = allow+/api/state/query | plain | QUERY | user-key = allow+/api/state/query | plain | QUERY | user-key-verified = allow+/api/svc/{namespace}/{service} | empty-ns | DELETE | admin-spa = deny+/api/svc/{namespace}/{service} | empty-ns | DELETE | cua-cli = deny+/api/svc/{namespace}/{service} | empty-ns | DELETE | dcr-client = deny+/api/svc/{namespace}/{service} | empty-ns | DELETE | empty-sub = deny+/api/svc/{namespace}/{service} | empty-ns | DELETE | github-oidc = deny+/api/svc/{namespace}/{service} | empty-ns | DELETE | oauth2-proxy = deny+/api/svc/{namespace}/{service} | empty-ns | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service} | empty-ns | DELETE | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | empty-ns | DELETE | spa = deny+/api/svc/{namespace}/{service} | empty-ns | DELETE | user-key = deny+/api/svc/{namespace}/{service} | empty-ns | DELETE | user-key-verified = deny+/api/svc/{namespace}/{service} | empty-ns | GET | admin-spa = deny+/api/svc/{namespace}/{service} | empty-ns | GET | cua-cli = deny+/api/svc/{namespace}/{service} | empty-ns | GET | dcr-client = deny+/api/svc/{namespace}/{service} | empty-ns | GET | empty-sub = deny+/api/svc/{namespace}/{service} | empty-ns | GET | github-oidc = deny+/api/svc/{namespace}/{service} | empty-ns | GET | oauth2-proxy = deny+/api/svc/{namespace}/{service} | empty-ns | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service} | empty-ns | GET | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | empty-ns | GET | spa = deny+/api/svc/{namespace}/{service} | empty-ns | GET | user-key = deny+/api/svc/{namespace}/{service} | empty-ns | GET | user-key-verified = deny+/api/svc/{namespace}/{service} | empty-ns | PATCH | admin-spa = deny+/api/svc/{namespace}/{service} | empty-ns | PATCH | cua-cli = deny+/api/svc/{namespace}/{service} | empty-ns | PATCH | dcr-client = deny+/api/svc/{namespace}/{service} | empty-ns | PATCH | empty-sub = deny+/api/svc/{namespace}/{service} | empty-ns | PATCH | github-oidc = deny+/api/svc/{namespace}/{service} | empty-ns | PATCH | oauth2-proxy = deny+/api/svc/{namespace}/{service} | empty-ns | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service} | empty-ns | PATCH | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | empty-ns | PATCH | spa = deny+/api/svc/{namespace}/{service} | empty-ns | PATCH | user-key = deny+/api/svc/{namespace}/{service} | empty-ns | PATCH | user-key-verified = deny+/api/svc/{namespace}/{service} | empty-ns | POST | admin-spa = deny+/api/svc/{namespace}/{service} | empty-ns | POST | cua-cli = deny+/api/svc/{namespace}/{service} | empty-ns | POST | dcr-client = deny+/api/svc/{namespace}/{service} | empty-ns | POST | empty-sub = deny+/api/svc/{namespace}/{service} | empty-ns | POST | github-oidc = deny+/api/svc/{namespace}/{service} | empty-ns | POST | oauth2-proxy = deny+/api/svc/{namespace}/{service} | empty-ns | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service} | empty-ns | POST | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | empty-ns | POST | spa = deny+/api/svc/{namespace}/{service} | empty-ns | POST | user-key = deny+/api/svc/{namespace}/{service} | empty-ns | POST | user-key-verified = deny+/api/svc/{namespace}/{service} | empty-ns | QUERY | admin-spa = deny+/api/svc/{namespace}/{service} | empty-ns | QUERY | cua-cli = deny+/api/svc/{namespace}/{service} | empty-ns | QUERY | dcr-client = deny+/api/svc/{namespace}/{service} | empty-ns | QUERY | empty-sub = deny+/api/svc/{namespace}/{service} | empty-ns | QUERY | github-oidc = deny+/api/svc/{namespace}/{service} | empty-ns | QUERY | oauth2-proxy = deny+/api/svc/{namespace}/{service} | empty-ns | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service} | empty-ns | QUERY | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | empty-ns | QUERY | spa = deny+/api/svc/{namespace}/{service} | empty-ns | QUERY | user-key = deny+/api/svc/{namespace}/{service} | empty-ns | QUERY | user-key-verified = deny+/api/svc/{namespace}/{service} | invalid-ns | DELETE | admin-spa = deny+/api/svc/{namespace}/{service} | invalid-ns | DELETE | cua-cli = deny+/api/svc/{namespace}/{service} | invalid-ns | DELETE | dcr-client = deny+/api/svc/{namespace}/{service} | invalid-ns | DELETE | empty-sub = deny+/api/svc/{namespace}/{service} | invalid-ns | DELETE | github-oidc = deny+/api/svc/{namespace}/{service} | invalid-ns | DELETE | oauth2-proxy = deny+/api/svc/{namespace}/{service} | invalid-ns | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service} | invalid-ns | DELETE | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | invalid-ns | DELETE | spa = deny+/api/svc/{namespace}/{service} | invalid-ns | DELETE | user-key = deny+/api/svc/{namespace}/{service} | invalid-ns | DELETE | user-key-verified = deny+/api/svc/{namespace}/{service} | invalid-ns | GET | admin-spa = deny+/api/svc/{namespace}/{service} | invalid-ns | GET | cua-cli = deny+/api/svc/{namespace}/{service} | invalid-ns | GET | dcr-client = deny+/api/svc/{namespace}/{service} | invalid-ns | GET | empty-sub = deny+/api/svc/{namespace}/{service} | invalid-ns | GET | github-oidc = deny+/api/svc/{namespace}/{service} | invalid-ns | GET | oauth2-proxy = deny+/api/svc/{namespace}/{service} | invalid-ns | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service} | invalid-ns | GET | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | invalid-ns | GET | spa = deny+/api/svc/{namespace}/{service} | invalid-ns | GET | user-key = deny+/api/svc/{namespace}/{service} | invalid-ns | GET | user-key-verified = deny+/api/svc/{namespace}/{service} | invalid-ns | PATCH | admin-spa = deny+/api/svc/{namespace}/{service} | invalid-ns | PATCH | cua-cli = deny+/api/svc/{namespace}/{service} | invalid-ns | PATCH | dcr-client = deny+/api/svc/{namespace}/{service} | invalid-ns | PATCH | empty-sub = deny+/api/svc/{namespace}/{service} | invalid-ns | PATCH | github-oidc = deny+/api/svc/{namespace}/{service} | invalid-ns | PATCH | oauth2-proxy = deny+/api/svc/{namespace}/{service} | invalid-ns | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service} | invalid-ns | PATCH | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | invalid-ns | PATCH | spa = deny+/api/svc/{namespace}/{service} | invalid-ns | PATCH | user-key = deny+/api/svc/{namespace}/{service} | invalid-ns | PATCH | user-key-verified = deny+/api/svc/{namespace}/{service} | invalid-ns | POST | admin-spa = deny+/api/svc/{namespace}/{service} | invalid-ns | POST | cua-cli = deny+/api/svc/{namespace}/{service} | invalid-ns | POST | dcr-client = deny+/api/svc/{namespace}/{service} | invalid-ns | POST | empty-sub = deny+/api/svc/{namespace}/{service} | invalid-ns | POST | github-oidc = deny+/api/svc/{namespace}/{service} | invalid-ns | POST | oauth2-proxy = deny+/api/svc/{namespace}/{service} | invalid-ns | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service} | invalid-ns | POST | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | invalid-ns | POST | spa = deny+/api/svc/{namespace}/{service} | invalid-ns | POST | user-key = deny+/api/svc/{namespace}/{service} | invalid-ns | POST | user-key-verified = deny+/api/svc/{namespace}/{service} | invalid-ns | QUERY | admin-spa = deny+/api/svc/{namespace}/{service} | invalid-ns | QUERY | cua-cli = deny+/api/svc/{namespace}/{service} | invalid-ns | QUERY | dcr-client = deny+/api/svc/{namespace}/{service} | invalid-ns | QUERY | empty-sub = deny+/api/svc/{namespace}/{service} | invalid-ns | QUERY | github-oidc = deny+/api/svc/{namespace}/{service} | invalid-ns | QUERY | oauth2-proxy = deny+/api/svc/{namespace}/{service} | invalid-ns | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service} | invalid-ns | QUERY | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | invalid-ns | QUERY | spa = deny+/api/svc/{namespace}/{service} | invalid-ns | QUERY | user-key = deny+/api/svc/{namespace}/{service} | invalid-ns | QUERY | user-key-verified = deny+/api/svc/{namespace}/{service} | invalid-service | DELETE | admin-spa = deny+/api/svc/{namespace}/{service} | invalid-service | DELETE | cua-cli = deny+/api/svc/{namespace}/{service} | invalid-service | DELETE | dcr-client = deny+/api/svc/{namespace}/{service} | invalid-service | DELETE | empty-sub = deny+/api/svc/{namespace}/{service} | invalid-service | DELETE | github-oidc = deny+/api/svc/{namespace}/{service} | invalid-service | DELETE | oauth2-proxy = deny+/api/svc/{namespace}/{service} | invalid-service | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service} | invalid-service | DELETE | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | invalid-service | DELETE | spa = deny+/api/svc/{namespace}/{service} | invalid-service | DELETE | user-key = deny+/api/svc/{namespace}/{service} | invalid-service | DELETE | user-key-verified = deny+/api/svc/{namespace}/{service} | invalid-service | GET | admin-spa = deny+/api/svc/{namespace}/{service} | invalid-service | GET | cua-cli = deny+/api/svc/{namespace}/{service} | invalid-service | GET | dcr-client = deny+/api/svc/{namespace}/{service} | invalid-service | GET | empty-sub = deny+/api/svc/{namespace}/{service} | invalid-service | GET | github-oidc = deny+/api/svc/{namespace}/{service} | invalid-service | GET | oauth2-proxy = deny+/api/svc/{namespace}/{service} | invalid-service | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service} | invalid-service | GET | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | invalid-service | GET | spa = deny+/api/svc/{namespace}/{service} | invalid-service | GET | user-key = deny+/api/svc/{namespace}/{service} | invalid-service | GET | user-key-verified = deny+/api/svc/{namespace}/{service} | invalid-service | PATCH | admin-spa = deny+/api/svc/{namespace}/{service} | invalid-service | PATCH | cua-cli = deny+/api/svc/{namespace}/{service} | invalid-service | PATCH | dcr-client = deny+/api/svc/{namespace}/{service} | invalid-service | PATCH | empty-sub = deny+/api/svc/{namespace}/{service} | invalid-service | PATCH | github-oidc = deny+/api/svc/{namespace}/{service} | invalid-service | PATCH | oauth2-proxy = deny+/api/svc/{namespace}/{service} | invalid-service | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service} | invalid-service | PATCH | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | invalid-service | PATCH | spa = deny+/api/svc/{namespace}/{service} | invalid-service | PATCH | user-key = deny+/api/svc/{namespace}/{service} | invalid-service | PATCH | user-key-verified = deny+/api/svc/{namespace}/{service} | invalid-service | POST | admin-spa = deny+/api/svc/{namespace}/{service} | invalid-service | POST | cua-cli = deny+/api/svc/{namespace}/{service} | invalid-service | POST | dcr-client = deny+/api/svc/{namespace}/{service} | invalid-service | POST | empty-sub = deny+/api/svc/{namespace}/{service} | invalid-service | POST | github-oidc = deny+/api/svc/{namespace}/{service} | invalid-service | POST | oauth2-proxy = deny+/api/svc/{namespace}/{service} | invalid-service | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service} | invalid-service | POST | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | invalid-service | POST | spa = deny+/api/svc/{namespace}/{service} | invalid-service | POST | user-key = deny+/api/svc/{namespace}/{service} | invalid-service | POST | user-key-verified = deny+/api/svc/{namespace}/{service} | invalid-service | QUERY | admin-spa = deny+/api/svc/{namespace}/{service} | invalid-service | QUERY | cua-cli = deny+/api/svc/{namespace}/{service} | invalid-service | QUERY | dcr-client = deny+/api/svc/{namespace}/{service} | invalid-service | QUERY | empty-sub = deny+/api/svc/{namespace}/{service} | invalid-service | QUERY | github-oidc = deny+/api/svc/{namespace}/{service} | invalid-service | QUERY | oauth2-proxy = deny+/api/svc/{namespace}/{service} | invalid-service | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service} | invalid-service | QUERY | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | invalid-service | QUERY | spa = deny+/api/svc/{namespace}/{service} | invalid-service | QUERY | user-key = deny+/api/svc/{namespace}/{service} | invalid-service | QUERY | user-key-verified = deny+/api/svc/{namespace}/{service} | other-ns | DELETE | admin-spa = deny+/api/svc/{namespace}/{service} | other-ns | DELETE | cua-cli = deny+/api/svc/{namespace}/{service} | other-ns | DELETE | dcr-client = deny+/api/svc/{namespace}/{service} | other-ns | DELETE | empty-sub = deny+/api/svc/{namespace}/{service} | other-ns | DELETE | github-oidc = deny+/api/svc/{namespace}/{service} | other-ns | DELETE | oauth2-proxy = deny+/api/svc/{namespace}/{service} | other-ns | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service} | other-ns | DELETE | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | other-ns | DELETE | spa = deny+/api/svc/{namespace}/{service} | other-ns | DELETE | user-key = deny+/api/svc/{namespace}/{service} | other-ns | DELETE | user-key-verified = deny+/api/svc/{namespace}/{service} | other-ns | GET | admin-spa = deny+/api/svc/{namespace}/{service} | other-ns | GET | cua-cli = deny+/api/svc/{namespace}/{service} | other-ns | GET | dcr-client = deny+/api/svc/{namespace}/{service} | other-ns | GET | empty-sub = deny+/api/svc/{namespace}/{service} | other-ns | GET | github-oidc = deny+/api/svc/{namespace}/{service} | other-ns | GET | oauth2-proxy = deny+/api/svc/{namespace}/{service} | other-ns | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service} | other-ns | GET | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | other-ns | GET | spa = deny+/api/svc/{namespace}/{service} | other-ns | GET | user-key = deny+/api/svc/{namespace}/{service} | other-ns | GET | user-key-verified = deny+/api/svc/{namespace}/{service} | other-ns | PATCH | admin-spa = deny+/api/svc/{namespace}/{service} | other-ns | PATCH | cua-cli = deny+/api/svc/{namespace}/{service} | other-ns | PATCH | dcr-client = deny+/api/svc/{namespace}/{service} | other-ns | PATCH | empty-sub = deny+/api/svc/{namespace}/{service} | other-ns | PATCH | github-oidc = deny+/api/svc/{namespace}/{service} | other-ns | PATCH | oauth2-proxy = deny+/api/svc/{namespace}/{service} | other-ns | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service} | other-ns | PATCH | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | other-ns | PATCH | spa = deny+/api/svc/{namespace}/{service} | other-ns | PATCH | user-key = deny+/api/svc/{namespace}/{service} | other-ns | PATCH | user-key-verified = deny+/api/svc/{namespace}/{service} | other-ns | POST | admin-spa = deny+/api/svc/{namespace}/{service} | other-ns | POST | cua-cli = deny+/api/svc/{namespace}/{service} | other-ns | POST | dcr-client = deny+/api/svc/{namespace}/{service} | other-ns | POST | empty-sub = deny+/api/svc/{namespace}/{service} | other-ns | POST | github-oidc = deny+/api/svc/{namespace}/{service} | other-ns | POST | oauth2-proxy = deny+/api/svc/{namespace}/{service} | other-ns | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service} | other-ns | POST | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | other-ns | POST | spa = deny+/api/svc/{namespace}/{service} | other-ns | POST | user-key = deny+/api/svc/{namespace}/{service} | other-ns | POST | user-key-verified = deny+/api/svc/{namespace}/{service} | other-ns | QUERY | admin-spa = deny+/api/svc/{namespace}/{service} | other-ns | QUERY | cua-cli = deny+/api/svc/{namespace}/{service} | other-ns | QUERY | dcr-client = deny+/api/svc/{namespace}/{service} | other-ns | QUERY | empty-sub = deny+/api/svc/{namespace}/{service} | other-ns | QUERY | github-oidc = deny+/api/svc/{namespace}/{service} | other-ns | QUERY | oauth2-proxy = deny+/api/svc/{namespace}/{service} | other-ns | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service} | other-ns | QUERY | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | other-ns | QUERY | spa = deny+/api/svc/{namespace}/{service} | other-ns | QUERY | user-key = deny+/api/svc/{namespace}/{service} | other-ns | QUERY | user-key-verified = deny+/api/svc/{namespace}/{service} | owned-ns | DELETE | admin-spa = allow+/api/svc/{namespace}/{service} | owned-ns | DELETE | cua-cli = allow+/api/svc/{namespace}/{service} | owned-ns | DELETE | dcr-client = allow+/api/svc/{namespace}/{service} | owned-ns | DELETE | empty-sub = deny+/api/svc/{namespace}/{service} | owned-ns | DELETE | github-oidc = allow+/api/svc/{namespace}/{service} | owned-ns | DELETE | oauth2-proxy = allow+/api/svc/{namespace}/{service} | owned-ns | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service} | owned-ns | DELETE | per-key-owned-ns = allow+/api/svc/{namespace}/{service} | owned-ns | DELETE | spa = allow+/api/svc/{namespace}/{service} | owned-ns | DELETE | user-key = allow+/api/svc/{namespace}/{service} | owned-ns | DELETE | user-key-verified = allow+/api/svc/{namespace}/{service} | owned-ns | GET | admin-spa = allow+/api/svc/{namespace}/{service} | owned-ns | GET | cua-cli = allow+/api/svc/{namespace}/{service} | owned-ns | GET | dcr-client = allow+/api/svc/{namespace}/{service} | owned-ns | GET | empty-sub = deny+/api/svc/{namespace}/{service} | owned-ns | GET | github-oidc = allow+/api/svc/{namespace}/{service} | owned-ns | GET | oauth2-proxy = allow+/api/svc/{namespace}/{service} | owned-ns | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service} | owned-ns | GET | per-key-owned-ns = allow+/api/svc/{namespace}/{service} | owned-ns | GET | spa = allow+/api/svc/{namespace}/{service} | owned-ns | GET | user-key = allow+/api/svc/{namespace}/{service} | owned-ns | GET | user-key-verified = allow+/api/svc/{namespace}/{service} | owned-ns | PATCH | admin-spa = allow+/api/svc/{namespace}/{service} | owned-ns | PATCH | cua-cli = allow+/api/svc/{namespace}/{service} | owned-ns | PATCH | dcr-client = allow+/api/svc/{namespace}/{service} | owned-ns | PATCH | empty-sub = deny+/api/svc/{namespace}/{service} | owned-ns | PATCH | github-oidc = allow+/api/svc/{namespace}/{service} | owned-ns | PATCH | oauth2-proxy = allow+/api/svc/{namespace}/{service} | owned-ns | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service} | owned-ns | PATCH | per-key-owned-ns = allow+/api/svc/{namespace}/{service} | owned-ns | PATCH | spa = allow+/api/svc/{namespace}/{service} | owned-ns | PATCH | user-key = allow+/api/svc/{namespace}/{service} | owned-ns | PATCH | user-key-verified = allow+/api/svc/{namespace}/{service} | owned-ns | POST | admin-spa = allow+/api/svc/{namespace}/{service} | owned-ns | POST | cua-cli = allow+/api/svc/{namespace}/{service} | owned-ns | POST | dcr-client = allow+/api/svc/{namespace}/{service} | owned-ns | POST | empty-sub = deny+/api/svc/{namespace}/{service} | owned-ns | POST | github-oidc = allow+/api/svc/{namespace}/{service} | owned-ns | POST | oauth2-proxy = allow+/api/svc/{namespace}/{service} | owned-ns | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service} | owned-ns | POST | per-key-owned-ns = allow+/api/svc/{namespace}/{service} | owned-ns | POST | spa = allow+/api/svc/{namespace}/{service} | owned-ns | POST | user-key = allow+/api/svc/{namespace}/{service} | owned-ns | POST | user-key-verified = allow+/api/svc/{namespace}/{service} | owned-ns | QUERY | admin-spa = allow+/api/svc/{namespace}/{service} | owned-ns | QUERY | cua-cli = allow+/api/svc/{namespace}/{service} | owned-ns | QUERY | dcr-client = allow+/api/svc/{namespace}/{service} | owned-ns | QUERY | empty-sub = deny+/api/svc/{namespace}/{service} | owned-ns | QUERY | github-oidc = allow+/api/svc/{namespace}/{service} | owned-ns | QUERY | oauth2-proxy = allow+/api/svc/{namespace}/{service} | owned-ns | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service} | owned-ns | QUERY | per-key-owned-ns = allow+/api/svc/{namespace}/{service} | owned-ns | QUERY | spa = allow+/api/svc/{namespace}/{service} | owned-ns | QUERY | user-key = allow+/api/svc/{namespace}/{service} | owned-ns | QUERY | user-key-verified = allow+/api/svc/{namespace}/{service} | unreachable-ns | DELETE | admin-spa = error+/api/svc/{namespace}/{service} | unreachable-ns | DELETE | cua-cli = error+/api/svc/{namespace}/{service} | unreachable-ns | DELETE | dcr-client = error+/api/svc/{namespace}/{service} | unreachable-ns | DELETE | empty-sub = deny+/api/svc/{namespace}/{service} | unreachable-ns | DELETE | github-oidc = deny+/api/svc/{namespace}/{service} | unreachable-ns | DELETE | oauth2-proxy = error+/api/svc/{namespace}/{service} | unreachable-ns | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service} | unreachable-ns | DELETE | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | unreachable-ns | DELETE | spa = error+/api/svc/{namespace}/{service} | unreachable-ns | DELETE | user-key = error+/api/svc/{namespace}/{service} | unreachable-ns | DELETE | user-key-verified = error+/api/svc/{namespace}/{service} | unreachable-ns | GET | admin-spa = error+/api/svc/{namespace}/{service} | unreachable-ns | GET | cua-cli = error+/api/svc/{namespace}/{service} | unreachable-ns | GET | dcr-client = error+/api/svc/{namespace}/{service} | unreachable-ns | GET | empty-sub = deny+/api/svc/{namespace}/{service} | unreachable-ns | GET | github-oidc = deny+/api/svc/{namespace}/{service} | unreachable-ns | GET | oauth2-proxy = error+/api/svc/{namespace}/{service} | unreachable-ns | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service} | unreachable-ns | GET | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | unreachable-ns | GET | spa = error+/api/svc/{namespace}/{service} | unreachable-ns | GET | user-key = error+/api/svc/{namespace}/{service} | unreachable-ns | GET | user-key-verified = error+/api/svc/{namespace}/{service} | unreachable-ns | PATCH | admin-spa = error+/api/svc/{namespace}/{service} | unreachable-ns | PATCH | cua-cli = error+/api/svc/{namespace}/{service} | unreachable-ns | PATCH | dcr-client = error+/api/svc/{namespace}/{service} | unreachable-ns | PATCH | empty-sub = deny+/api/svc/{namespace}/{service} | unreachable-ns | PATCH | github-oidc = deny+/api/svc/{namespace}/{service} | unreachable-ns | PATCH | oauth2-proxy = error+/api/svc/{namespace}/{service} | unreachable-ns | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service} | unreachable-ns | PATCH | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | unreachable-ns | PATCH | spa = error+/api/svc/{namespace}/{service} | unreachable-ns | PATCH | user-key = error+/api/svc/{namespace}/{service} | unreachable-ns | PATCH | user-key-verified = error+/api/svc/{namespace}/{service} | unreachable-ns | POST | admin-spa = error+/api/svc/{namespace}/{service} | unreachable-ns | POST | cua-cli = error+/api/svc/{namespace}/{service} | unreachable-ns | POST | dcr-client = error+/api/svc/{namespace}/{service} | unreachable-ns | POST | empty-sub = deny+/api/svc/{namespace}/{service} | unreachable-ns | POST | github-oidc = deny+/api/svc/{namespace}/{service} | unreachable-ns | POST | oauth2-proxy = error+/api/svc/{namespace}/{service} | unreachable-ns | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service} | unreachable-ns | POST | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | unreachable-ns | POST | spa = error+/api/svc/{namespace}/{service} | unreachable-ns | POST | user-key = error+/api/svc/{namespace}/{service} | unreachable-ns | POST | user-key-verified = error+/api/svc/{namespace}/{service} | unreachable-ns | QUERY | admin-spa = error+/api/svc/{namespace}/{service} | unreachable-ns | QUERY | cua-cli = error+/api/svc/{namespace}/{service} | unreachable-ns | QUERY | dcr-client = error+/api/svc/{namespace}/{service} | unreachable-ns | QUERY | empty-sub = deny+/api/svc/{namespace}/{service} | unreachable-ns | QUERY | github-oidc = deny+/api/svc/{namespace}/{service} | unreachable-ns | QUERY | oauth2-proxy = error+/api/svc/{namespace}/{service} | unreachable-ns | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service} | unreachable-ns | QUERY | per-key-owned-ns = deny+/api/svc/{namespace}/{service} | unreachable-ns | QUERY | spa = error+/api/svc/{namespace}/{service} | unreachable-ns | QUERY | user-key = error+/api/svc/{namespace}/{service} | unreachable-ns | QUERY | user-key-verified = error+/api/svc/{namespace}/{service}/{path...} | empty-ns | DELETE | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | DELETE | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | DELETE | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | DELETE | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | DELETE | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | DELETE | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | DELETE | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | DELETE | spa = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | DELETE | user-key = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | DELETE | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | GET | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | GET | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | GET | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | GET | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | GET | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | GET | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | GET | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | GET | spa = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | GET | user-key = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | GET | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | PATCH | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | PATCH | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | PATCH | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | PATCH | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | PATCH | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | PATCH | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | PATCH | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | PATCH | spa = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | PATCH | user-key = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | PATCH | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | POST | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | POST | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | POST | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | POST | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | POST | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | POST | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | POST | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | POST | spa = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | POST | user-key = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | POST | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | QUERY | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | QUERY | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | QUERY | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | QUERY | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | QUERY | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | QUERY | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | QUERY | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | QUERY | spa = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | QUERY | user-key = deny+/api/svc/{namespace}/{service}/{path...} | empty-ns | QUERY | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | DELETE | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | DELETE | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | DELETE | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | DELETE | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | DELETE | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | DELETE | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | DELETE | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | DELETE | spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | DELETE | user-key = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | DELETE | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | GET | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | GET | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | GET | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | GET | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | GET | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | GET | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | GET | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | GET | spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | GET | user-key = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | GET | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | PATCH | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | PATCH | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | PATCH | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | PATCH | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | PATCH | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | PATCH | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | PATCH | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | PATCH | spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | PATCH | user-key = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | PATCH | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | POST | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | POST | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | POST | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | POST | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | POST | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | POST | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | POST | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | POST | spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | POST | user-key = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | POST | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | QUERY | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | QUERY | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | QUERY | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | QUERY | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | QUERY | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | QUERY | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | QUERY | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | QUERY | spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | QUERY | user-key = deny+/api/svc/{namespace}/{service}/{path...} | invalid-ns | QUERY | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | DELETE | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | DELETE | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | DELETE | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | DELETE | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | DELETE | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | DELETE | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | DELETE | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | DELETE | spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | DELETE | user-key = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | DELETE | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | GET | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | GET | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | GET | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | GET | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | GET | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | GET | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | GET | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | GET | spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | GET | user-key = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | GET | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | PATCH | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | PATCH | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | PATCH | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | PATCH | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | PATCH | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | PATCH | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | PATCH | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | PATCH | spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | PATCH | user-key = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | PATCH | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | POST | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | POST | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | POST | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | POST | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | POST | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | POST | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | POST | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | POST | spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | POST | user-key = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | POST | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | QUERY | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | QUERY | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | QUERY | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | QUERY | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | QUERY | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | QUERY | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | QUERY | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | QUERY | spa = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | QUERY | user-key = deny+/api/svc/{namespace}/{service}/{path...} | invalid-service | QUERY | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | DELETE | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | DELETE | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | DELETE | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | DELETE | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | DELETE | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | DELETE | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | DELETE | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | DELETE | spa = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | DELETE | user-key = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | DELETE | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | GET | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | GET | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | GET | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | GET | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | GET | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | GET | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | GET | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | GET | spa = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | GET | user-key = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | GET | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | PATCH | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | PATCH | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | PATCH | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | PATCH | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | PATCH | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | PATCH | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | PATCH | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | PATCH | spa = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | PATCH | user-key = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | PATCH | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | POST | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | POST | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | POST | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | POST | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | POST | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | POST | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | POST | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | POST | spa = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | POST | user-key = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | POST | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | QUERY | admin-spa = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | QUERY | cua-cli = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | QUERY | dcr-client = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | QUERY | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | QUERY | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | QUERY | oauth2-proxy = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | QUERY | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | QUERY | spa = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | QUERY | user-key = deny+/api/svc/{namespace}/{service}/{path...} | other-ns | QUERY | user-key-verified = deny+/api/svc/{namespace}/{service}/{path...} | owned-ns | DELETE | admin-spa = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | DELETE | cua-cli = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | DELETE | dcr-client = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | DELETE | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | owned-ns | DELETE | github-oidc = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | DELETE | oauth2-proxy = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | owned-ns | DELETE | per-key-owned-ns = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | DELETE | spa = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | DELETE | user-key = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | DELETE | user-key-verified = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | GET | admin-spa = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | GET | cua-cli = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | GET | dcr-client = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | GET | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | owned-ns | GET | github-oidc = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | GET | oauth2-proxy = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | owned-ns | GET | per-key-owned-ns = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | GET | spa = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | GET | user-key = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | GET | user-key-verified = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | PATCH | admin-spa = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | PATCH | cua-cli = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | PATCH | dcr-client = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | PATCH | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | owned-ns | PATCH | github-oidc = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | PATCH | oauth2-proxy = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | owned-ns | PATCH | per-key-owned-ns = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | PATCH | spa = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | PATCH | user-key = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | PATCH | user-key-verified = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | POST | admin-spa = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | POST | cua-cli = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | POST | dcr-client = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | POST | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | owned-ns | POST | github-oidc = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | POST | oauth2-proxy = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | owned-ns | POST | per-key-owned-ns = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | POST | spa = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | POST | user-key = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | POST | user-key-verified = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | QUERY | admin-spa = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | QUERY | cua-cli = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | QUERY | dcr-client = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | QUERY | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | owned-ns | QUERY | github-oidc = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | QUERY | oauth2-proxy = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | owned-ns | QUERY | per-key-owned-ns = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | QUERY | spa = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | QUERY | user-key = allow+/api/svc/{namespace}/{service}/{path...} | owned-ns | QUERY | user-key-verified = allow+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | DELETE | admin-spa = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | DELETE | cua-cli = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | DELETE | dcr-client = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | DELETE | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | DELETE | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | DELETE | oauth2-proxy = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | DELETE | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | DELETE | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | DELETE | spa = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | DELETE | user-key = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | DELETE | user-key-verified = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | GET | admin-spa = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | GET | cua-cli = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | GET | dcr-client = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | GET | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | GET | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | GET | oauth2-proxy = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | GET | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | GET | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | GET | spa = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | GET | user-key = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | GET | user-key-verified = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | PATCH | admin-spa = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | PATCH | cua-cli = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | PATCH | dcr-client = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | PATCH | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | PATCH | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | PATCH | oauth2-proxy = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | PATCH | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | PATCH | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | PATCH | spa = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | PATCH | user-key = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | PATCH | user-key-verified = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | POST | admin-spa = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | POST | cua-cli = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | POST | dcr-client = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | POST | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | POST | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | POST | oauth2-proxy = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | POST | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | POST | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | POST | spa = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | POST | user-key = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | POST | user-key-verified = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | QUERY | admin-spa = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | QUERY | cua-cli = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | QUERY | dcr-client = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | QUERY | empty-sub = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | QUERY | github-oidc = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | QUERY | oauth2-proxy = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | QUERY | per-key-other-ns = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | QUERY | per-key-owned-ns = deny+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | QUERY | spa = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | QUERY | user-key = error+/api/svc/{namespace}/{service}/{path...} | unreachable-ns | QUERY | user-key-verified = error+/api/user-keys | plain | DELETE | admin-spa = allow+/api/user-keys | plain | DELETE | cua-cli = allow+/api/user-keys | plain | DELETE | dcr-client = deny+/api/user-keys | plain | DELETE | empty-sub = deny+/api/user-keys | plain | DELETE | github-oidc = deny+/api/user-keys | plain | DELETE | oauth2-proxy = deny+/api/user-keys | plain | DELETE | per-key-other-ns = deny+/api/user-keys | plain | DELETE | per-key-owned-ns = deny+/api/user-keys | plain | DELETE | spa = allow+/api/user-keys | plain | DELETE | user-key = deny+/api/user-keys | plain | DELETE | user-key-verified = deny+/api/user-keys | plain | GET | admin-spa = allow+/api/user-keys | plain | GET | cua-cli = allow+/api/user-keys | plain | GET | dcr-client = deny+/api/user-keys | plain | GET | empty-sub = deny+/api/user-keys | plain | GET | github-oidc = deny+/api/user-keys | plain | GET | oauth2-proxy = deny+/api/user-keys | plain | GET | per-key-other-ns = deny+/api/user-keys | plain | GET | per-key-owned-ns = deny+/api/user-keys | plain | GET | spa = allow+/api/user-keys | plain | GET | user-key = deny+/api/user-keys | plain | GET | user-key-verified = deny+/api/user-keys | plain | PATCH | admin-spa = allow+/api/user-keys | plain | PATCH | cua-cli = allow+/api/user-keys | plain | PATCH | dcr-client = deny+/api/user-keys | plain | PATCH | empty-sub = deny+/api/user-keys | plain | PATCH | github-oidc = deny+/api/user-keys | plain | PATCH | oauth2-proxy = deny+/api/user-keys | plain | PATCH | per-key-other-ns = deny+/api/user-keys | plain | PATCH | per-key-owned-ns = deny+/api/user-keys | plain | PATCH | spa = allow+/api/user-keys | plain | PATCH | user-key = deny+/api/user-keys | plain | PATCH | user-key-verified = deny+/api/user-keys | plain | POST | admin-spa = allow+/api/user-keys | plain | POST | cua-cli = allow+/api/user-keys | plain | POST | dcr-client = deny+/api/user-keys | plain | POST | empty-sub = deny+/api/user-keys | plain | POST | github-oidc = deny+/api/user-keys | plain | POST | oauth2-proxy = deny+/api/user-keys | plain | POST | per-key-other-ns = deny+/api/user-keys | plain | POST | per-key-owned-ns = deny+/api/user-keys | plain | POST | spa = allow+/api/user-keys | plain | POST | user-key = deny+/api/user-keys | plain | POST | user-key-verified = deny+/api/user-keys | plain | QUERY | admin-spa = allow+/api/user-keys | plain | QUERY | cua-cli = allow+/api/user-keys | plain | QUERY | dcr-client = deny+/api/user-keys | plain | QUERY | empty-sub = deny+/api/user-keys | plain | QUERY | github-oidc = deny+/api/user-keys | plain | QUERY | oauth2-proxy = deny+/api/user-keys | plain | QUERY | per-key-other-ns = deny+/api/user-keys | plain | QUERY | per-key-owned-ns = deny+/api/user-keys | plain | QUERY | spa = allow+/api/user-keys | plain | QUERY | user-key = deny+/api/user-keys | plain | QUERY | user-key-verified = deny+/api/user-keys/{id} | id | DELETE | admin-spa = allow+/api/user-keys/{id} | id | DELETE | cua-cli = allow+/api/user-keys/{id} | id | DELETE | dcr-client = deny+/api/user-keys/{id} | id | DELETE | empty-sub = deny+/api/user-keys/{id} | id | DELETE | github-oidc = deny+/api/user-keys/{id} | id | DELETE | oauth2-proxy = deny+/api/user-keys/{id} | id | DELETE | per-key-other-ns = deny+/api/user-keys/{id} | id | DELETE | per-key-owned-ns = deny+/api/user-keys/{id} | id | DELETE | spa = allow+/api/user-keys/{id} | id | DELETE | user-key = deny+/api/user-keys/{id} | id | DELETE | user-key-verified = deny+/api/user-keys/{id} | id | GET | admin-spa = allow+/api/user-keys/{id} | id | GET | cua-cli = allow+/api/user-keys/{id} | id | GET | dcr-client = deny+/api/user-keys/{id} | id | GET | empty-sub = deny+/api/user-keys/{id} | id | GET | github-oidc = deny+/api/user-keys/{id} | id | GET | oauth2-proxy = deny+/api/user-keys/{id} | id | GET | per-key-other-ns = deny+/api/user-keys/{id} | id | GET | per-key-owned-ns = deny+/api/user-keys/{id} | id | GET | spa = allow+/api/user-keys/{id} | id | GET | user-key = deny+/api/user-keys/{id} | id | GET | user-key-verified = deny+/api/user-keys/{id} | id | PATCH | admin-spa = allow+/api/user-keys/{id} | id | PATCH | cua-cli = allow+/api/user-keys/{id} | id | PATCH | dcr-client = deny+/api/user-keys/{id} | id | PATCH | empty-sub = deny+/api/user-keys/{id} | id | PATCH | github-oidc = deny+/api/user-keys/{id} | id | PATCH | oauth2-proxy = deny+/api/user-keys/{id} | id | PATCH | per-key-other-ns = deny+/api/user-keys/{id} | id | PATCH | per-key-owned-ns = deny+/api/user-keys/{id} | id | PATCH | spa = allow+/api/user-keys/{id} | id | PATCH | user-key = deny+/api/user-keys/{id} | id | PATCH | user-key-verified = deny+/api/user-keys/{id} | id | POST | admin-spa = allow+/api/user-keys/{id} | id | POST | cua-cli = allow+/api/user-keys/{id} | id | POST | dcr-client = deny+/api/user-keys/{id} | id | POST | empty-sub = deny+/api/user-keys/{id} | id | POST | github-oidc = deny+/api/user-keys/{id} | id | POST | oauth2-proxy = deny+/api/user-keys/{id} | id | POST | per-key-other-ns = deny+/api/user-keys/{id} | id | POST | per-key-owned-ns = deny+/api/user-keys/{id} | id | POST | spa = allow+/api/user-keys/{id} | id | POST | user-key = deny+/api/user-keys/{id} | id | POST | user-key-verified = deny+/api/user-keys/{id} | id | QUERY | admin-spa = allow+/api/user-keys/{id} | id | QUERY | cua-cli = allow+/api/user-keys/{id} | id | QUERY | dcr-client = deny+/api/user-keys/{id} | id | QUERY | empty-sub = deny+/api/user-keys/{id} | id | QUERY | github-oidc = deny+/api/user-keys/{id} | id | QUERY | oauth2-proxy = deny+/api/user-keys/{id} | id | QUERY | per-key-other-ns = deny+/api/user-keys/{id} | id | QUERY | per-key-owned-ns = deny+/api/user-keys/{id} | id | QUERY | spa = allow+/api/user-keys/{id} | id | QUERY | user-key = deny+/api/user-keys/{id} | id | QUERY | user-key-verified = denydiff --git a/libs/fleet/backend/auth/testdata/state-query-route-plan.txt b/libs/fleet/backend/auth/testdata/state-query-route-plan.txtnew file mode 100644index 0000000000..198f5eb9af--- /dev/null+++ b/libs/fleet/backend/auth/testdata/state-query-route-plan.txt@@ -0,0 +1,3 @@+All+ Leaf query=data.authz_base.allow source=registered:authz-base+ Leaf query=data.authz_state_query.allow source=multi["registered:authz","registered:authz-state-query"]diff --git a/libs/fleet/backend/auth/testdata/svc-route-plan.txt b/libs/fleet/backend/auth/testdata/svc-route-plan.txtnew file mode 100644index 0000000000..ce8e536a6e--- /dev/null+++ b/libs/fleet/backend/auth/testdata/svc-route-plan.txt@@ -0,0 +1,8 @@+All+ Leaf query=data.authz_base.allow source=registered:authz-base+ Leaf query=data.authz_svc.allow source=multi["registered:authz","registered:authz-svc"]+ 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-rbacdiff --git a/libs/fleet/backend/auth/testdata/user-keys-route-plan.txt b/libs/fleet/backend/auth/testdata/user-keys-route-plan.txtnew file mode 100644index 0000000000..55e21c7039--- /dev/null+++ b/libs/fleet/backend/auth/testdata/user-keys-route-plan.txt@@ -0,0 +1,3 @@+All+ Leaf query=data.authz_base.allow source=registered:authz-base+ Leaf query=data.authz_user_keys.allow source=multi["registered:authz","registered:authz-user-keys"]diff --git a/libs/fleet/backend/docs/docs.go b/libs/fleet/backend/docs/docs.goindex ea93c78b12..aa164910a5 100644--- a/libs/fleet/backend/docs/docs.go+++ b/libs/fleet/backend/docs/docs.go@@ -15,253 +15,6 @@ const docTemplate = `{"host": "{{.Host}}","basePath": "{{.BasePath}}","paths": {- "/api/batch/{pool}/lanes": {- "post": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch lanes route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- },- "delete": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch lanes route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/batch/{pool}/submit": {- "post": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch submission route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/batch/{pool}/{id}": {- "delete": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch delete route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Batch ID",- "name": "id",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/batch/{pool}/{id}/results": {- "get": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch results route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Batch ID",- "name": "id",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/batch/{pool}/{id}/status": {- "get": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch status route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Batch ID",- "name": "id",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },"/api/billing/portal-session": {"post": {"security": [@@ -536,7 +289,7 @@ const docTemplate = `{"BearerAuth": []}],- "description": "Forwards requests to http://127.0.0.1:8001 (the kubectl-proxy sidecar) so the SPA can read K8s resources via the pod ServiceAccount. SPA-only; OPA-gated. EventList responses are filtered by the caller's OPA visible_events policy via auth.K8sEventFilterMiddleware (mounted in main.go's route chain).",+ "description": "Forwards requests to http://127.0.0.1:8001 (the kubectl-proxy sidecar) so the caller can read K8s resources via the pod ServiceAccount. SPA-only; OPA-gated. The policy is an allowlist: only enumerated group/version/resource/method combinations are proxied (the osgym.cua.ai and cua.ai fleet CRDs, namespaced pod/service reads, pod logs and metrics, KubeVirt reads, and API discovery). Anything else, including Kubernetes events and any cluster-scoped path, is denied and never reaches the sidecar.","tags": ["passthrough"],@@ -705,186 +458,6 @@ const docTemplate = `{}}},- "/api/label/{pool}/{label}": {- "delete": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "label"- ],- "summary": "Deprecated label delete route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Label",- "name": "label",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/label/{pool}/{label}/batch": {- "post": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "label"- ],- "summary": "Deprecated label batch route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Label",- "name": "label",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/label/{pool}/{label}/results": {- "get": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "label"- ],- "summary": "Deprecated label results route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Label",- "name": "label",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/label/{pool}/{label}/status": {- "get": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "label"- ],- "summary": "Deprecated label status route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Label",- "name": "label",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },"/api/namespaces": {"get": {"security": [@@ -987,6 +560,68 @@ const docTemplate = `{}},"/api/namespaces/{name}": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Gets a K8s namespace via impersonation. Capsule restricts access to the caller's Tenant.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "namespaces"+ ],+ "summary": "Get a namespace owned by the calling user",+ "parameters": [+ {+ "type": "string",+ "description": "Namespace name",+ "name": "name",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.NamespaceResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },"delete": {"security": [{@@ -1565,7 +1200,7 @@ const docTemplate = `{},"securityDefinitions": {"BearerAuth": {- "description": "Keycloak access token. For /api/keys and /api/{k8s,orch} the token is an interactive user JWT (azp=cyclops-cs-spa or azp=cua-cli). The deprecated /api/batch/{pool} and /api/label/{pool} routes are permanently retired — they return 410 Gone for every request regardless of token validity.",+ "description": "Keycloak access token. For /api/keys and /api/{k8s,orch} the token is an interactive user JWT (azp=cyclops-cs-spa or azp=cua-cli).","type": "apiKey","name": "Authorization","in": "header"@@ -1580,7 +1215,7 @@ var SwaggerInfo = &swag.Spec{BasePath: "/",Schemes: []string{},Title: "Cyclops CS Backend API",- Description: "Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key management, service proxies (k8s / orch / svc), namespace management, and deprecated batch / label routes that now return 410 Gone. All pool operations use OSGymSandboxClaim CRs (Path B).",+ Description: "Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key management, service proxies (k8s / orch / svc), and namespace management. All pool operations use OSGymSandboxClaim CRs (Path B).",InfoInstanceName: "swagger",SwaggerTemplate: docTemplate,LeftDelim: "{{",diff --git a/libs/fleet/backend/docs/swagger.json b/libs/fleet/backend/docs/swagger.jsonindex e1474fb05f..f7a4bfe277 100644--- a/libs/fleet/backend/docs/swagger.json+++ b/libs/fleet/backend/docs/swagger.json@@ -1,260 +1,13 @@{"swagger": "2.0","info": {- "description": "Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key management, service proxies (k8s / orch / svc), namespace management, and deprecated batch / label routes that now return 410 Gone. All pool operations use OSGymSandboxClaim CRs (Path B).",+ "description": "Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key management, service proxies (k8s / orch / svc), and namespace management. All pool operations use OSGymSandboxClaim CRs (Path B).","title": "Cyclops CS Backend API","contact": {},"version": "0.1"},"basePath": "/","paths": {- "/api/batch/{pool}/lanes": {- "post": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch lanes route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- },- "delete": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch lanes route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/batch/{pool}/submit": {- "post": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch submission route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/batch/{pool}/{id}": {- "delete": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch delete route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Batch ID",- "name": "id",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/batch/{pool}/{id}/results": {- "get": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch results route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Batch ID",- "name": "id",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/batch/{pool}/{id}/status": {- "get": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "batch"- ],- "summary": "Deprecated batch status route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Batch ID",- "name": "id",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },"/api/billing/portal-session": {"post": {"security": [@@ -529,7 +282,7 @@"BearerAuth": []}],- "description": "Forwards requests to http://127.0.0.1:8001 (the kubectl-proxy sidecar) so the SPA can read K8s resources via the pod ServiceAccount. SPA-only; OPA-gated. EventList responses are filtered by the caller's OPA visible_events policy via auth.K8sEventFilterMiddleware (mounted in main.go's route chain).",+ "description": "Forwards requests to http://127.0.0.1:8001 (the kubectl-proxy sidecar) so the caller can read K8s resources via the pod ServiceAccount. SPA-only; OPA-gated. The policy is an allowlist: only enumerated group/version/resource/method combinations are proxied (the osgym.cua.ai and cua.ai fleet CRDs, namespaced pod/service reads, pod logs and metrics, KubeVirt reads, and API discovery). Anything else, including Kubernetes events and any cluster-scoped path, is denied and never reaches the sidecar.","tags": ["passthrough"],@@ -698,186 +451,6 @@}}},- "/api/label/{pool}/{label}": {- "delete": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "label"- ],- "summary": "Deprecated label delete route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Label",- "name": "label",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/label/{pool}/{label}/batch": {- "post": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "label"- ],- "summary": "Deprecated label batch route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Label",- "name": "label",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/label/{pool}/{label}/results": {- "get": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "label"- ],- "summary": "Deprecated label results route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Label",- "name": "label",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },- "/api/label/{pool}/{label}/status": {- "get": {- "security": [- {- "BearerAuth": []- }- ],- "description": "Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.",- "produces": [- "application/json"- ],- "tags": [- "label"- ],- "summary": "Deprecated label status route",- "deprecated": true,- "parameters": [- {- "type": "string",- "description": "Pool name",- "name": "pool",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Label",- "name": "label",- "in": "path",- "required": true- }- ],- "responses": {- "410": {- "description": "Gone",- "schema": {- "type": "object",- "additionalProperties": {- "type": "string"- }- }- }- }- }- },"/api/namespaces": {"get": {"security": [@@ -980,6 +553,68 @@}},"/api/namespaces/{name}": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Gets a K8s namespace via impersonation. Capsule restricts access to the caller's Tenant.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "namespaces"+ ],+ "summary": "Get a namespace owned by the calling user",+ "parameters": [+ {+ "type": "string",+ "description": "Namespace name",+ "name": "name",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.NamespaceResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },"delete": {"security": [{@@ -1558,7 +1193,7 @@},"securityDefinitions": {"BearerAuth": {- "description": "Keycloak access token. For /api/keys and /api/{k8s,orch} the token is an interactive user JWT (azp=cyclops-cs-spa or azp=cua-cli). The deprecated /api/batch/{pool} and /api/label/{pool} routes are permanently retired — they return 410 Gone for every request regardless of token validity.",+ "description": "Keycloak access token. For /api/keys and /api/{k8s,orch} the token is an interactive user JWT (azp=cyclops-cs-spa or azp=cua-cli).","type": "apiKey","name": "Authorization","in": "header"diff --git a/libs/fleet/backend/docs/swagger.yaml b/libs/fleet/backend/docs/swagger.yamlindex 57a1090ece..2ff2981890 100644--- a/libs/fleet/backend/docs/swagger.yaml+++ b/libs/fleet/backend/docs/swagger.yaml@@ -162,182 +162,11 @@ definitions:info:contact: {}description: Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key- management, service proxies (k8s / orch / svc), namespace management, and deprecated- batch / label routes that now return 410 Gone. All pool operations use- OSGymSandboxClaim CRs (Path B).+ management, service proxies (k8s / orch / svc), and namespace management. All+ pool operations use OSGymSandboxClaim CRs (Path B).title: Cyclops CS Backend APIversion: "0.1"paths:- /api/batch/{pool}/{id}:- delete:- deprecated: true- description: Route is deprecated and unavailable. Returns 410 Gone for every- request. The orchestrator-backed batch surface is retired; callers must migrate- to the replacement flow.- parameters:- - description: Pool name- in: path- name: pool- required: true- type: string- - description: Batch ID- in: path- name: id- required: true- type: string- produces:- - application/json- responses:- "410":- description: Gone- schema:- additionalProperties:- type: string- type: object- security:- - BearerAuth: []- summary: Deprecated batch delete route- tags:- - batch- /api/batch/{pool}/{id}/results:- get:- deprecated: true- description: Route is deprecated and unavailable. Returns 410 Gone for every- request. The orchestrator-backed batch surface is retired; callers must migrate- to the replacement flow.- parameters:- - description: Pool name- in: path- name: pool- required: true- type: string- - description: Batch ID- in: path- name: id- required: true- type: string- produces:- - application/json- responses:- "410":- description: Gone- schema:- additionalProperties:- type: string- type: object- security:- - BearerAuth: []- summary: Deprecated batch results route- tags:- - batch- /api/batch/{pool}/{id}/status:- get:- deprecated: true- description: Route is deprecated and unavailable. Returns 410 Gone for every- request. The orchestrator-backed batch surface is retired; callers must migrate- to the replacement flow.- parameters:- - description: Pool name- in: path- name: pool- required: true- type: string- - description: Batch ID- in: path- name: id- required: true- type: string- produces:- - application/json- responses:- "410":- description: Gone- schema:- additionalProperties:- type: string- type: object- security:- - BearerAuth: []- summary: Deprecated batch status route- tags:- - batch- /api/batch/{pool}/lanes:- delete:- deprecated: true- description: Route is deprecated and unavailable. Returns 410 Gone for every- request. The orchestrator-backed batch surface is retired; callers must migrate- to the replacement flow.- parameters:- - description: Pool name- in: path- name: pool- required: true- type: string- produces:- - application/json- responses:- "410":- description: Gone- schema:- additionalProperties:- type: string- type: object- security:- - BearerAuth: []- summary: Deprecated batch lanes route- tags:- - batch- post:- deprecated: true- description: Route is deprecated and unavailable. Returns 410 Gone for every- request. The orchestrator-backed batch surface is retired; callers must migrate- to the replacement flow.- parameters:- - description: Pool name- in: path- name: pool- required: true- type: string- produces:- - application/json- responses:- "410":- description: Gone- schema:- additionalProperties:- type: string- type: object- security:- - BearerAuth: []- summary: Deprecated batch lanes route- tags:- - batch- /api/batch/{pool}/submit:- post:- deprecated: true- description: Route is deprecated and unavailable. Returns 410 Gone for every- request. The orchestrator-backed batch surface is retired; callers must migrate- to the replacement flow.- parameters:- - description: Pool name- in: path- name: pool- required: true- type: string- produces:- - application/json- responses:- "410":- description: Gone- schema:- additionalProperties:- type: string- type: object- security:- - BearerAuth: []- summary: Deprecated batch submission route- tags:- - batch/api/billing/portal-session:post:description: Creates a Stripe-hosted Billing Portal Session for the customer@@ -516,10 +345,13 @@ paths:- config/api/k8s/{path}:get:- description: Forwards requests to http://127.0.0.1:8001 (the kubectl-proxy sidecar)- so the SPA can read K8s resources via the pod ServiceAccount. SPA-only; OPA-gated.- EventList responses are filtered by the caller's OPA visible_events policy- via auth.K8sEventFilterMiddleware (mounted in main.go's route chain).+ description: 'Forwards requests to http://127.0.0.1:8001 (the kubectl-proxy+ sidecar) so the caller can read K8s resources via the pod ServiceAccount.+ SPA-only; OPA-gated. The policy is an allowlist: only enumerated group/version/resource/method+ combinations are proxied (the osgym.cua.ai and cua.ai fleet CRDs, namespaced+ pod/service reads, pod logs and metrics, KubeVirt reads, and API discovery).+ Anything else, including Kubernetes events and any cluster-scoped path, is+ denied and never reaches the sidecar.'parameters:- description: K8s API pathin: path@@ -628,130 +460,6 @@ paths:summary: Revoke an API key by Keycloak client UUIDtags:- keys- /api/label/{pool}/{label}:- delete:- deprecated: true- description: Route is deprecated and unavailable. Returns 410 Gone for every- request. The orchestrator-backed batch surface is retired; callers must migrate- to the replacement flow.- parameters:- - description: Pool name- in: path- name: pool- required: true- type: string- - description: Label- in: path- name: label- required: true- type: string- produces:- - application/json- responses:- "410":- description: Gone- schema:- additionalProperties:- type: string- type: object- security:- - BearerAuth: []- summary: Deprecated label delete route- tags:- - label- /api/label/{pool}/{label}/batch:- post:- deprecated: true- description: Route is deprecated and unavailable. Returns 410 Gone for every- request. The orchestrator-backed batch surface is retired; callers must migrate- to the replacement flow.- parameters:- - description: Pool name- in: path- name: pool- required: true- type: string- - description: Label- in: path- name: label- required: true- type: string- produces:- - application/json- responses:- "410":- description: Gone- schema:- additionalProperties:- type: string- type: object- security:- - BearerAuth: []- summary: Deprecated label batch route- tags:- - label- /api/label/{pool}/{label}/results:- get:- deprecated: true- description: Route is deprecated and unavailable. Returns 410 Gone for every- request. The orchestrator-backed batch surface is retired; callers must migrate- to the replacement flow.- parameters:- - description: Pool name- in: path- name: pool- required: true- type: string- - description: Label- in: path- name: label- required: true- type: string- produces:- - application/json- responses:- "410":- description: Gone- schema:- additionalProperties:- type: string- type: object- security:- - BearerAuth: []- summary: Deprecated label results route- tags:- - label- /api/label/{pool}/{label}/status:- get:- deprecated: true- description: Route is deprecated and unavailable. Returns 410 Gone for every- request. The orchestrator-backed batch surface is retired; callers must migrate- to the replacement flow.- parameters:- - description: Pool name- in: path- name: pool- required: true- type: string- - description: Label- in: path- name: label- required: true- type: string- produces:- - application/json- responses:- "410":- description: Gone- schema:- additionalProperties:- type: string- type: object- security:- - BearerAuth: []- summary: Deprecated label status route- tags:- - label/api/namespaces:get:description: Returns namespaces owned by the caller's Capsule Tenant. The list@@ -858,6 +566,47 @@ paths:summary: Delete a namespace owned by the calling usertags:- namespaces+ get:+ description: Gets a K8s namespace via impersonation. Capsule restricts access+ to the caller's Tenant.+ parameters:+ - description: Namespace name+ in: path+ name: name+ required: true+ type: string+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/handlers.NamespaceResponse'+ "400":+ description: Bad Request+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "403":+ description: Forbidden+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "404":+ description: Not Found+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "502":+ description: Bad Gateway+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Get a namespace owned by the calling user+ tags:+ - namespaces/api/orch/{namespace}/{service}/{path}:get:description: Resolves <service>.<namespace>.svc.cluster.local at request time@@ -1047,9 +796,7 @@ paths:securityDefinitions:BearerAuth:description: Keycloak access token. For /api/keys and /api/{k8s,orch} the token- is an interactive user JWT (azp=cyclops-cs-spa or azp=cua-cli). The deprecated- /api/batch/{pool} and /api/label/{pool} routes are permanently- retired — they return 410 Gone for every request regardless of token validity.+ is an interactive user JWT (azp=cyclops-cs-spa or azp=cua-cli).in: headername: Authorizationtype: apiKeydiff --git a/libs/fleet/backend/handlers/deprecated.go b/libs/fleet/backend/handlers/deprecated.godeleted file mode 100644index 6932ef189c..0000000000--- a/libs/fleet/backend/handlers/deprecated.go+++ /dev/null@@ -1,170 +0,0 @@-package handlers--import "net/http"--// DeprecatedBatchRoute replies 410 Gone for the retired batch/label API.-// The per-route wrappers below exist only to carry swagger annotations, so-// `swag init` keeps the retired routes documented as deprecated instead of-// silently dropping them from the spec (pinned by-// TestSwaggerMentionsBatchRouteDeprecation).-func (h Handlers) DeprecatedBatchRoute(w http.ResponseWriter, _ *http.Request) {- writeErr(w, http.StatusGone,- "/api/batch and /api/label are deprecated and unavailable; use the replacement claim-based flow")-}--// DeprecatedBatchSubmit godoc-//-// @Summary Deprecated batch submission route-// @Description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.-// @Deprecated-// @Tags batch-// @Produce json-// @Param pool path string true "Pool name"-// @Failure 410 {object} map[string]string-// @Security BearerAuth-// @Router /api/batch/{pool}/submit [post]-func (h Handlers) DeprecatedBatchSubmit(w http.ResponseWriter, r *http.Request) {- h.DeprecatedBatchRoute(w, r)-}--// DeprecatedBatchLanesCreate godoc-//-// @Summary Deprecated batch lanes route-// @Description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.-// @Deprecated-// @Tags batch-// @Produce json-// @Param pool path string true "Pool name"-// @Failure 410 {object} map[string]string-// @Security BearerAuth-// @Router /api/batch/{pool}/lanes [post]-func (h Handlers) DeprecatedBatchLanesCreate(w http.ResponseWriter, r *http.Request) {- h.DeprecatedBatchRoute(w, r)-}--// DeprecatedBatchLanesDelete godoc-//-// @Summary Deprecated batch lanes route-// @Description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.-// @Deprecated-// @Tags batch-// @Produce json-// @Param pool path string true "Pool name"-// @Failure 410 {object} map[string]string-// @Security BearerAuth-// @Router /api/batch/{pool}/lanes [delete]-func (h Handlers) DeprecatedBatchLanesDelete(w http.ResponseWriter, r *http.Request) {- h.DeprecatedBatchRoute(w, r)-}--// DeprecatedBatchStatus godoc-//-// @Summary Deprecated batch status route-// @Description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.-// @Deprecated-// @Tags batch-// @Produce json-// @Param pool path string true "Pool name"-// @Param id path string true "Batch ID"-// @Failure 410 {object} map[string]string-// @Security BearerAuth-// @Router /api/batch/{pool}/{id}/status [get]-func (h Handlers) DeprecatedBatchStatus(w http.ResponseWriter, r *http.Request) {- h.DeprecatedBatchRoute(w, r)-}--// DeprecatedBatchResults godoc-//-// @Summary Deprecated batch results route-// @Description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.-// @Deprecated-// @Tags batch-// @Produce json-// @Param pool path string true "Pool name"-// @Param id path string true "Batch ID"-// @Failure 410 {object} map[string]string-// @Security BearerAuth-// @Router /api/batch/{pool}/{id}/results [get]-func (h Handlers) DeprecatedBatchResults(w http.ResponseWriter, r *http.Request) {- h.DeprecatedBatchRoute(w, r)-}--// DeprecatedBatchDelete godoc-//-// @Summary Deprecated batch delete route-// @Description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.-// @Deprecated-// @Tags batch-// @Produce json-// @Param pool path string true "Pool name"-// @Param id path string true "Batch ID"-// @Failure 410 {object} map[string]string-// @Security BearerAuth-// @Router /api/batch/{pool}/{id} [delete]-func (h Handlers) DeprecatedBatchDelete(w http.ResponseWriter, r *http.Request) {- h.DeprecatedBatchRoute(w, r)-}--// DeprecatedLabelBatch godoc-//-// @Summary Deprecated label batch route-// @Description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.-// @Deprecated-// @Tags label-// @Produce json-// @Param pool path string true "Pool name"-// @Param label path string true "Label"-// @Failure 410 {object} map[string]string-// @Security BearerAuth-// @Router /api/label/{pool}/{label}/batch [post]-func (h Handlers) DeprecatedLabelBatch(w http.ResponseWriter, r *http.Request) {- h.DeprecatedBatchRoute(w, r)-}--// DeprecatedLabelStatus godoc-//-// @Summary Deprecated label status route-// @Description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.-// @Deprecated-// @Tags label-// @Produce json-// @Param pool path string true "Pool name"-// @Param label path string true "Label"-// @Failure 410 {object} map[string]string-// @Security BearerAuth-// @Router /api/label/{pool}/{label}/status [get]-func (h Handlers) DeprecatedLabelStatus(w http.ResponseWriter, r *http.Request) {- h.DeprecatedBatchRoute(w, r)-}--// DeprecatedLabelResults godoc-//-// @Summary Deprecated label results route-// @Description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.-// @Deprecated-// @Tags label-// @Produce json-// @Param pool path string true "Pool name"-// @Param label path string true "Label"-// @Failure 410 {object} map[string]string-// @Security BearerAuth-// @Router /api/label/{pool}/{label}/results [get]-func (h Handlers) DeprecatedLabelResults(w http.ResponseWriter, r *http.Request) {- h.DeprecatedBatchRoute(w, r)-}--// DeprecatedLabelDelete godoc-//-// @Summary Deprecated label delete route-// @Description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.-// @Deprecated-// @Tags label-// @Produce json-// @Param pool path string true "Pool name"-// @Param label path string true "Label"-// @Failure 410 {object} map[string]string-// @Security BearerAuth-// @Router /api/label/{pool}/{label} [delete]-func (h Handlers) DeprecatedLabelDelete(w http.ResponseWriter, r *http.Request) {- h.DeprecatedBatchRoute(w, r)-}diff --git a/libs/fleet/backend/handlers/k8s.go b/libs/fleet/backend/handlers/k8s.goindex dda4117581..cacd00123d 100644--- a/libs/fleet/backend/handlers/k8s.go+++ b/libs/fleet/backend/handlers/k8s.go@@ -1,10 +1,6 @@package handlersimport (- "bytes"- "context"- "encoding/json"- "io""log/slog""net/http""net/http/httputil"@@ -13,7 +9,6 @@ import ("strings""time"- "cyclops-cs-backend/auth""cyclops-cs-backend/identity""cyclops-cs-backend/metrics""go.opentelemetry.io/otel/attribute"@@ -34,7 +29,7 @@ func kubectlProxyAddr() string {// K8s godoc//// @Summary Authenticated proxy to the in-pod kubectl-proxy sidecar-// @Description Forwards requests to http://127.0.0.1:8001 (the kubectl-proxy sidecar) so the SPA can read K8s resources via the pod ServiceAccount. SPA-only; OPA-gated. EventList responses are filtered by the caller's OPA visible_events policy via auth.K8sEventFilterMiddleware (mounted in main.go's route chain).+// @Description Forwards requests to http://127.0.0.1:8001 (the kubectl-proxy sidecar) so the caller can read K8s resources via the pod ServiceAccount. SPA-only; OPA-gated. The policy is an allowlist: only enumerated group/version/resource/method combinations are proxied (the osgym.cua.ai and cua.ai fleet CRDs, namespaced pod/service reads, pod logs and metrics, KubeVirt reads, and API discovery). Anything else, including Kubernetes events and any cluster-scoped path, is denied and never reaches the sidecar.// @Tags passthrough// @Param path path string true "K8s API path"// @Success 200 {string} string "K8s API response"@@ -60,38 +55,6 @@ func (h Handlers) K8s(w http.ResponseWriter, r *http.Request) {// Extract the authenticated user for K8s impersonation — Capsule// uses these headers to scope the request to the user's Tenant.user := currentUser(r.WithContext(ctx))- if isGitHubPrincipal(user) {- namespace, ok := githubAllowedK8sPath(r.Method, strings.TrimPrefix(r.PathValue("path"), "/"))- if !ok {- writeErr(w, http.StatusForbidden, "k8s path is outside github trust policy scope")- return- }- if !namespaceAllowed(user, namespace) {- writeErr(w, http.StatusForbidden, "namespace is outside github trust policy scope")- return- }- }-- if allowed, err := poolImagePullSecretAllowed(ctx, r); err != nil {- writeErr(w, http.StatusBadRequest, "could not inspect pool request")- return- } else if !allowed {- writeErr(w, http.StatusForbidden, "pool image pull secret or image is not allowed")- return- }-- // macOS is an ADMIN-ONLY capability. The SPA hides the option for- // non-admins, but that is not a boundary — enforce it here so a customer- // cannot create a macOS pool by crafting the API call directly. Any- // osgymworkspacepools write whose body requests the macOS runtime requires- // admin membership; non-macOS pools and all reads are unaffected. CUA-macos.- if forbid, err := macosPoolNeedsAdmin(ctx, user, r); err != nil {- writeErr(w, http.StatusBadRequest, "could not inspect pool request")- return- } else if forbid {- writeErr(w, http.StatusForbidden, "macOS pools are restricted to administrators")- return- }rp := httputil.NewSingleHostReverseProxy(target)origDirector := rp.Director@@ -133,138 +96,6 @@ func (h Handlers) K8s(w http.ResponseWriter, r *http.Request) {metrics.RecordUpstreamProxy("k8s", rw.statusCode, time.Since(start))}-func poolImagePullSecretAllowed(ctx context.Context, r *http.Request) (bool, error) {- switch r.Method {- case http.MethodPost, http.MethodPut, http.MethodPatch:- default:- return true, nil- }- if !isPoolShapedWrite(r.PathValue("path")) || r.Body == nil {- return true, nil- }- body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))- if err != nil {- return false, err- }- r.Body = io.NopCloser(bytes.NewReader(body))- var object map[string]any- if err := json.Unmarshal(body, &object); err != nil {- return false, err- }- return auth.EvalPoolAdmission(ctx, r.Method, object)-}--// isPoolShapedWrite reports whether path targets a resource whose body can-// carry a VM shape (image, runtime, node placement): the native-// OSGymSandboxTemplate, or the retired legacy OSGymWorkspacePool (kept so a-// stale client cannot slip past the gate while the CRD deletion propagates).-func isPoolShapedWrite(path string) bool {- return strings.Contains(path, "osgymsandboxtemplates") ||- strings.Contains(path, "osgymworkspacepools")-}--// macosPoolNeedsAdmin returns true if r is a write to a pool-shaped-// resource whose body opts into the macOS runtime AND the caller is not an-// admin. It rebuffers r.Body so the downstream proxy can still read it. Reads-// and non-macOS writes always return false (no restriction).-func macosPoolNeedsAdmin(ctx context.Context, user *auth.User, r *http.Request) (bool, error) {- switch r.Method {- case http.MethodPost, http.MethodPut, http.MethodPatch:- default:- return false, nil- }- if !isPoolShapedWrite(r.PathValue("path")) || r.Body == nil {- return false, nil- }- body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))- if err != nil {- return false, err- }- r.Body = io.NopCloser(bytes.NewReader(body)) // rebuffer for the proxy- if !bodyRequestsMacOS(body) {- return false, nil- }- isAdmin, err := auth.EvalIsAdmin(ctx, user)- if err != nil {- return false, err- }- return !isAdmin, nil-}--// bodyRequestsMacOS reports whether a pool-shaped CR body opts into the-// macOS runtime — via the VM template's runtime=macos, or (defence in depth)-// the macOS-only runtimeClass / nodeSelector that a macOS pod carries. The VM-// shape lives at spec.vmTemplate on the native OSGymSandboxTemplate and at-// spec.template on the retired legacy OSGymWorkspacePool.-func bodyRequestsMacOS(body []byte) bool {- var obj map[string]any- if json.Unmarshal(body, &obj) != nil {- return false- }- spec, _ := obj["spec"].(map[string]any)- tmpl, _ := spec["vmTemplate"].(map[string]any)- if tmpl == nil {- tmpl, _ = spec["template"].(map[string]any)- }- if tmpl == nil {- return false- }- if s, _ := tmpl["runtime"].(string); strings.EqualFold(s, "macos") {- return true- }- if s, _ := tmpl["runtimeClassName"].(string); s == "cua-macos-native" {- return true- }- if ns, _ := tmpl["nodeSelector"].(map[string]any); ns != nil {- if _, ok := ns["cua.ai/macos"]; ok {- return true- }- }- return false-}--func githubAllowedK8sPath(method, path string) (string, bool) {- parts := strings.Split(path, "/")- if len(parts) != 6 && len(parts) != 7 {- return "", false- }- if len(parts) == 7 && parts[6] == "" {- return "", false- }- if parts[0] != "apis" || parts[3] != "namespaces" {- return "", false- }-- if parts[1] == "cua.ai" && parts[2] == "v1" && parts[5] == "osgymworkspacepools" {- switch method {- case http.MethodGet, http.MethodPost, http.MethodPatch, http.MethodDelete:- return parts[4], true- }- }- if parts[1] != "osgym.cua.ai" || parts[2] != "v1alpha1" {- return "", false- }-- resource := parts[5]- isItem := len(parts) == 7- switch resource {- case "osgymsandboxwarmpools", "osgymsandboxclaims":- switch method {- case http.MethodGet:- return parts[4], true- case http.MethodPost:- return parts[4], !isItem- case http.MethodPatch, http.MethodDelete:- return parts[4], isItem- }- case "osgymsandboxtemplates":- if method == http.MethodGet {- return parts[4], true- }- }- return "", false-}-// Orch godoc//// @Summary SPA-authenticated proxy to a per-namespace orchestrator service@@ -292,11 +123,10 @@ func (h Handlers) Orch(w http.ResponseWriter, r *http.Request) {writeErr(w, http.StatusBadRequest, "invalid namespace or service")return}- // Tenancy boundary: this proxy dials Service DNS directly (never the- // K8s API), so Capsule can't scope it — enforce ownership here.- if !h.requireNamespaceAccess(w, r, user, ns) {- return- }+ // Tenancy boundary: this proxy dials Service DNS directly (never the K8s+ // API), so Capsule can't scope it. The boundary is the ownership conjunct+ // of OrchRoutePolicy, which has already run by the time this handler is+ // reached — see auth/authz_ownership.rego.upstreamPath := "/" + strings.TrimPrefix(r.PathValue("path"), "/")host := svc + "." + ns + "." + h.GatewayCfg.ClusterDomaintarget := &url.URL{Scheme: h.GatewayCfg.Scheme, Host: host + ":" + h.GatewayCfg.Port}diff --git a/libs/fleet/backend/handlers/k8s_test.go b/libs/fleet/backend/handlers/k8s_test.goindex 6fd58f63c1..3a0909397a 100644--- a/libs/fleet/backend/handlers/k8s_test.go+++ b/libs/fleet/backend/handlers/k8s_test.go@@ -113,10 +113,10 @@ func TestK8sProxy_ForwardsPath(t *testing.T) {},{name: "path with query params",- pathValue: "api/v1/namespaces/foo/events",- queryParam: "fieldSelector=reason%3DPoolCreated",- wantPath: "/api/v1/namespaces/foo/events",- wantQuery: "fieldSelector=reason%3DPoolCreated",+ pathValue: "api/v1/namespaces/foo/pods",+ queryParam: "fieldSelector=status.phase%3DRunning",+ wantPath: "/api/v1/namespaces/foo/pods",+ wantQuery: "fieldSelector=status.phase%3DRunning",},}@@ -230,54 +230,6 @@ func TestK8sProxy_CreatesTracingSpan(t *testing.T) {}}-func TestK8sProxy_RejectsDisallowedPoolImagePullSecret(t *testing.T) {- auth.LoadOpa()- upstreamCalled := false- upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- upstreamCalled = true- w.WriteHeader(http.StatusCreated)- }))- defer upstream.Close()- t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)-- body := []byte(`{"spec":{"template":{"containerDiskImage":"evil.example/workspace:latest","imagePullSecret":"ecr-credentials"}}}`)- r := httptest.NewRequest(http.MethodPost, "/api/k8s/apis/cua.ai/v1/namespaces/foo/osgymworkspacepools", bytes.NewReader(body))- r.SetPathValue("path", "apis/cua.ai/v1/namespaces/foo/osgymworkspacepools")- w := httptest.NewRecorder()-- (Handlers{}).K8s(w, r)-- if w.Code != http.StatusForbidden {- t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusForbidden, w.Body.String())- }- if upstreamCalled {- t.Fatal("disallowed pool request reached kubectl proxy")- }-}--func TestBodyRequestsMacOS(t *testing.T) {- cases := []struct {- name string- body string- want bool- }{- {"runtime macos", `{"spec":{"template":{"runtime":"macos","containerDiskImage":"img"}}}`, true},- {"runtime MacOS mixed-case", `{"spec":{"template":{"runtime":"MacOS"}}}`, true},- {"macos runtimeClass", `{"spec":{"template":{"runtimeClassName":"cua-macos-native"}}}`, true},- {"macos nodeSelector", `{"spec":{"template":{"nodeSelector":{"cua.ai/macos":"true"}}}}`, true},- {"kubevirt default", `{"spec":{"template":{"containerDiskImage":"img","cpuCores":4}}}`, false},- {"no template", `{"spec":{"replicas":1}}`, false},- {"garbage", `not json`, false},- }- for _, c := range cases {- t.Run(c.name, func(t *testing.T) {- if got := bodyRequestsMacOS([]byte(c.body)); got != c.want {- t.Fatalf("bodyRequestsMacOS(%s) = %v, want %v", c.body, got, c.want)- }- })- }-}-func TestK8sProxy_GitHubPrincipalAllowsNamespacedPoolCRUDPath(t *testing.T) {var receivedPath stringupstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -309,62 +261,27 @@ func TestK8sProxy_GitHubPrincipalAllowsNamespacedPoolCRUDPath(t *testing.T) {}}-func TestK8sProxy_GitHubPrincipalRejectsClusterWidePath(t *testing.T) {- h := Handlers{}- r := httptest.NewRequest(http.MethodGet, "/api/k8s/api/v1/nodes", nil)- r.SetPathValue("path", "api/v1/nodes")- r = withUser(r, &auth.User{- ID: "user-123",- AZP: "github-oidc",- PrincipalType: auth.PrincipalTypeGitHubOIDC,- AllowedNamespaces: []string{"ns-a"},- })- w := httptest.NewRecorder()+func TestK8sProxy_DirectHandlerLeavesAdmissionToMiddleware(t *testing.T) {+ auth.LoadOpa()+ upstreamCalled := false+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ upstreamCalled = true+ w.WriteHeader(http.StatusCreated)+ }))+ defer upstream.Close()+ t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)- h.K8s(w, r)+ body := []byte(`{"spec":{"template":{"containerDiskImage":"evil.example/workspace:latest","imagePullSecret":"ecr-credentials"}}}`)+ request := httptest.NewRequest(http.MethodPost, "/api/k8s/apis/cua.ai/v1/namespaces/foo/osgymworkspacepools", bytes.NewReader(body))+ request.SetPathValue("path", "apis/cua.ai/v1/namespaces/foo/osgymworkspacepools")+ response := httptest.NewRecorder()- if w.Code != http.StatusForbidden {- t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())- }-}+ (Handlers{}).K8s(response, request)-func TestGitHubAllowedK8sPath_SandboxLifecycle(t *testing.T) {- const namespace = "cua-cli-wif-smoke"- cases := []struct {- name string- method string- path string- want bool- }{- {"get warm pool", http.MethodGet, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxwarmpools/cua-cli-wif-smoke", true},- {"patch warm pool", http.MethodPatch, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxwarmpools/cua-cli-wif-smoke", true},- {"post warm pool item", http.MethodPost, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxwarmpools/cua-cli-wif-smoke", false},- {"patch warm pool collection", http.MethodPatch, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxwarmpools", false},- {"delete warm pool collection", http.MethodDelete, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxwarmpools", false},- {"patch trailing slash warm pool collection", http.MethodPatch, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxwarmpools/", false},- {"create claim", http.MethodPost, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxclaims", true},- {"post claim item", http.MethodPost, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxclaims/wif-smoke-123", false},- {"patch claim collection", http.MethodPatch, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxclaims", false},- {"delete claim collection", http.MethodDelete, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxclaims", false},- {"delete trailing slash claim collection", http.MethodDelete, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxclaims/", false},- {"get claim", http.MethodGet, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxclaims/wif-smoke-123", true},- {"renew claim", http.MethodPatch, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxclaims/wif-smoke-123", true},- {"delete claim", http.MethodDelete, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxclaims/wif-smoke-123", true},- {"get template", http.MethodGet, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxtemplates/cua-cli-wif-smoke-template", true},- {"write template", http.MethodPatch, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxtemplates/cua-cli-wif-smoke-template", false},- {"nested claim path", http.MethodGet, "apis/osgym.cua.ai/v1alpha1/namespaces/cua-cli-wif-smoke/osgymsandboxclaims/wif-smoke-123/status", false},- {"cluster-wide warm pools", http.MethodGet, "apis/osgym.cua.ai/v1alpha1/osgymsandboxwarmpools", false},+ if response.Code != http.StatusCreated {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusCreated, response.Body.String())}-- for _, tc := range cases {- t.Run(tc.name, func(t *testing.T) {- gotNamespace, got := githubAllowedK8sPath(tc.method, tc.path)- if got != tc.want {- t.Fatalf("githubAllowedK8sPath(%q, %q) allowed = %v, want %v", tc.method, tc.path, got, tc.want)- }- if tc.want && gotNamespace != namespace {- t.Fatalf("githubAllowedK8sPath(%q, %q) namespace = %q, want %q", tc.method, tc.path, gotNamespace, namespace)- }- })+ if !upstreamCalled {+ t.Fatal("direct handler request did not reach kubectl proxy")}}diff --git a/libs/fleet/backend/handlers/namespaces.go b/libs/fleet/backend/handlers/namespaces.goindex 5e9bdf3db4..26692d1390 100644--- a/libs/fleet/backend/handlers/namespaces.go+++ b/libs/fleet/backend/handlers/namespaces.go@@ -352,10 +352,6 @@ func (h Handlers) GetNamespace(w http.ResponseWriter, r *http.Request) {return}- if !h.requireNamespaceAccess(w, r, user, name) {- return- }-var namespace struct {Metadata struct {Name string `json:"name"`diff --git a/libs/fleet/backend/handlers/namespaces_test.go b/libs/fleet/backend/handlers/namespaces_test.goindex 74c7949898..3818cada96 100644--- a/libs/fleet/backend/handlers/namespaces_test.go+++ b/libs/fleet/backend/handlers/namespaces_test.go@@ -143,17 +143,15 @@ func TestGetNamespace_Success(t *testing.T) {if w.Code != http.StatusOK {t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())}- if len(fk.requests) != 2 {- t.Fatalf("request count = %d, want 2", len(fk.requests))+ // One request, not two: the ownership probe this handler used to make after+ // the read is the policy stage's now, and runs before the handler at all.+ if len(fk.requests) != 1 {+ t.Fatalf("request count = %d, want 1", len(fk.requests))}namespaceGet := fk.requests[0]if namespaceGet.method != http.MethodGet || namespaceGet.path != "/api/v1/namespaces/demo" {t.Fatalf("namespace GET = %s %s", namespaceGet.method, namespaceGet.path)}- probe := fk.requests[1]- if probe.method != http.MethodGet || probe.path != "/apis/rbac.authorization.k8s.io/v1/namespaces/demo/rolebindings" {- t.Fatalf("ownership probe = %s %s", probe.method, probe.path)- }var got NamespaceResponseif err := json.NewDecoder(w.Body).Decode(&got); err != nil {t.Fatal(err)@@ -220,12 +218,18 @@ func TestGetNamespace_PreservesForbiddenAndNotFound(t *testing.T) {}}-func TestGetNamespace_ExistingNamespaceWithoutOwnership_Forbidden(t *testing.T) {+// A non-owner CAN read another tenant's namespace object through impersonation+// — capsule-tenant-cluster-resources grants namespaces get cluster-wide to+// system:authenticated, so the read succeeds and gates nothing. What stops the+// request is the ownership conjunct of the namespaces policy, which runs before+// this handler; TestNamespacesRoute_GetOtherTenant_Forbidden is that test.+//+// This one pins the half that is left here: the handler does not re-check, so+// calling it directly serves the namespace it was given. Same shape as+// TestK8sProxy_DirectHandlerLeavesAdmissionToMiddleware.+func TestGetNamespace_DirectHandlerLeavesOwnershipToPolicy(t *testing.T) {resetOwnershipCache()- fk := newFakeK8sSequence(- fakeK8sResponse{status: http.StatusOK, body: nsCreatedResponse("other-tenant")},- fakeK8sResponse{status: http.StatusForbidden, body: `{"kind":"Status"}`},- )+ fk := newFakeK8s(http.StatusOK, nsCreatedResponse("other-tenant"))defer fk.server.Close()overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")@@ -236,18 +240,15 @@ func TestGetNamespace_ExistingNamespaceWithoutOwnership_Forbidden(t *testing.T)Handlers{}.GetNamespace(w, r)- if w.Code != http.StatusForbidden {- t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusForbidden, w.Body.String())+ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())}- if len(fk.requests) != 2 {- t.Fatalf("request count = %d, want 2", len(fk.requests))+ if len(fk.requests) != 1 {+ t.Fatalf("request count = %d, want 1", len(fk.requests))}if got := fk.requests[0].path; got != "/api/v1/namespaces/other-tenant" {t.Fatalf("namespace GET path = %q", got)}- if got := fk.requests[1].path; got != "/apis/rbac.authorization.k8s.io/v1/namespaces/other-tenant/rolebindings" {- t.Fatalf("ownership probe path = %q", got)- }}func TestCreateNamespace_ValidName(t *testing.T) {diff --git a/libs/fleet/backend/handlers/ownership.go b/libs/fleet/backend/handlers/ownership.goindex f8093024c9..d5e8240ee8 100644--- a/libs/fleet/backend/handlers/ownership.go+++ b/libs/fleet/backend/handlers/ownership.go@@ -1,12 +1,13 @@-// Namespace-ownership enforcement for the direct-dial service proxies-// (/api/svc and /api/orch).+// The Kubernetes half of namespace ownership: does this subject hold RBAC in+// this namespace?//-// These proxies dial {service}.{namespace}.svc.cluster.local directly —-// they never traverse the K8s API — so Capsule cannot enforce tenancy on-// them the way it does for /api/k8s. OPA can't either: it has no K8s-// data. This file is the tenancy boundary for those routes.+// It used to be a whole authorization decision made here, because the policy+// had no way to ask Kubernetes anything. It is now one input to a decision the+// policy makes — authz_ownership.rego — reaching it through the FactProvider+// below. What stayed is the probe and its cache; what left is every judgement+// about which principals deserve one.//-// The check is the impersonated RoleBinding probe already proven by+// The probe is the impersonated RoleBinding list already proven by// waitForNamespaceAdoption (namespaces.go): listing RoleBindings in a// namespace is only authorized for principals holding RBAC there — i.e.// the Capsule tenant owner. (A namespace GET would NOT work: the@@ -20,7 +21,6 @@ import ("log/slog""net/http""net/url"- "strings""sync""time"@@ -63,74 +63,56 @@ func resetOwnershipCache() {ownershipMu.Unlock()}-// keyClientPfx returns the per-key (pool) client-id prefix, defaulting to-// "key-" when config is zero-valued (tests construct Handlers{} bare).-func (h Handlers) keyClientPfx() string {- if h.AuthCfg.KeyClientPfx != "" {- return h.AuthCfg.KeyClientPfx- }- return "key-"-}--func (h Handlers) userKeyClientPfx() string {- if h.AuthCfg.UserKeyClientPfx != "" {- return h.AuthCfg.UserKeyClientPfx- }- return "ukey-"-}--// isPerKeyClient reports whether the token was minted for a per-pool key-// client. ukey-* (per-user key) clients carry a real user identity and-// must NOT match — guard against prefix overlap ("ukey-" does not start-// with "key-", but keep the explicit exclusion in case the configured-// prefixes ever nest).-func (h Handlers) isPerKeyClient(user *auth.User) bool {- if strings.HasPrefix(user.AZP, h.userKeyClientPfx()) {- return false- }- return strings.HasPrefix(user.AZP, h.keyClientPfx())+// NamespaceRBACFacts adapts the probe below to the policy layer. It is the+// third of the three decisions requireNamespaceAccess used to make in Go: the+// other two were claim checks over the token, and authz_ownership.rego makes+// them now. This one is not a rule at all — it is a fact about Kubernetes — so+// it arrives as input.facts.namespace_rbac instead.+//+// It wraps userHasNamespaceRBAC rather than reimplementing it, and that is+// load-bearing. The policy library caches fact loads per request; the probe's+// own cache is a TTL across requests, which is what collapses the noVNC asset+// storm to a couple of probes a minute. Reimplementing the probe here would+// have quietly turned that into one apiserver round trip per request.+//+// main.go registers it under auth.NamespaceRBACFactProvider, which is the name+// NamespaceOwnershipPolicy's tree refers to.+func NamespaceRBACFacts(h Handlers) auth.FactProvider {+ return namespaceRBACFacts{handlers: h}}-// requireNamespaceAccess authorizes user to reach Services in ns through-// the direct-dial proxies. Per-key tokens must carry namespace claim ==-// ns (defense-in-depth mirror of OPA); every other principal (SPA, ukey,-// oauth2-proxy) must hold RBAC in ns, verified by a cached impersonated-// RoleBinding probe. On deny/error it writes the response and returns-// false; callers must return immediately.-func (h Handlers) requireNamespaceAccess(w http.ResponseWriter, r *http.Request, user *auth.User, ns string) bool {- if isGitHubPrincipal(user) {- if namespaceAllowed(user, ns) {- return true- }- writeErr(w, http.StatusForbidden, "namespace access denied")- return false- }- // Per-key clients: bound to exactly one namespace by their token- // claim. No K8s call — the claim IS the grant.- if h.isPerKeyClient(user) {- if user.Namespace != "" && user.Namespace == ns {- return true- }- slog.Warn("namespace access denied (per-key claim mismatch)",- "sub", user.ID, "azp", user.AZP, "claim", user.Namespace, "namespace", ns)- writeErr(w, http.StatusForbidden, "namespace access denied")- return false+type namespaceRBACFacts struct{ handlers Handlers }++func (namespaceRBACFacts) CacheKey() string { return auth.NamespaceRBACFactProvider }++// LoadFacts answers whether this request's subject holds RBAC in this request's+// namespace, and nothing else. It deliberately does not ask who the caller is:+// which principals are worth probing is a policy question, and+// authz_ownership.rego's probe_eligible is where it is answered. What is left+// here is the pair of degenerate inputs the probe cannot form a question from —+// no subject to impersonate, or no namespace to ask about — which deny without+// a round trip.+func (facts namespaceRBACFacts) LoadFacts(ctx context.Context, r *http.Request) (auth.FactSet, error) {+ user := auth.GetUser(r.Context())+ namespace := auth.OwnedNamespace(r.Context())+ if user == nil || user.ID == "" || namespace == "" {+ return auth.FactSet{"allowed": false}, nil}- allowed, err := h.userHasNamespaceRBAC(r.Context(), user.ID, ns)+ allowed, err := facts.handlers.userHasNamespaceRBAC(ctx, user.ID, namespace)if err != nil {slog.Warn("namespace access check unavailable",- "sub", user.ID, "azp", user.AZP, "namespace", ns, "err", err)- writeErr(w, http.StatusBadGateway, "authorization check unavailable")- return false+ "sub", user.ID, "azp", user.AZP, "namespace", namespace, "err", err)+ return nil, &auth.FactUnavailableError{Namespace: auth.NamespaceRBACFactNamespace, Err: err}}if !allowed {+ // The verdict is the policy's to reach, but this is the only place the+ // apiserver's "no" is observed, and it was a logged event before the+ // check moved. PolicyMiddleware's 403 names a route, not a namespace.slog.Warn("namespace access denied",- "sub", user.ID, "azp", user.AZP, "namespace", ns)- writeErr(w, http.StatusForbidden, "namespace access denied")- return false+ "sub", user.ID, "azp", user.AZP, "namespace", namespace)}- return true+ return auth.FactSet{"allowed": allowed}, nil}// userHasNamespaceRBAC reports whether sub holds RBAC in ns, via a TTL-diff --git a/libs/fleet/backend/handlers/ownership_test.go b/libs/fleet/backend/handlers/ownership_test.goindex f8495fd330..0893d5e0de 100644--- a/libs/fleet/backend/handlers/ownership_test.go+++ b/libs/fleet/backend/handlers/ownership_test.go@@ -1,14 +1,37 @@package handlersimport (+ "context"+ "errors""net/http""net/http/httptest""testing""cyclops-cs-backend/auth""cyclops-cs-backend/config"++ "github.com/trycua/cloud/pkg/featureflags")+// Namespace ownership is an authorization decision, and since it moved out of+// the handlers it is no longer one this package can answer on its own. So these+// tests come in two halves.+//+// The first half exercises the FactProvider directly: what it probes, how often,+// and what it does when the apiserver will not answer. That is all this package+// still owns.+//+// The second half runs requests through the real authorization stage —+// auth.RouteMiddleware for the production route, over the production tree, with+// the production provider registered — and asserts the status the caller gets+// together with the number of probes it cost. Those two numbers together are+// the whole behaviour: the same 403 reached with one probe or with none is not+// the same system on a route that serves every noVNC asset.+//+// The stage is put in front of a stub rather than the real handler on purpose.+// h.Svc and h.Orch dial {service}.{namespace}.svc.cluster.local, which in a test+// is a DNS timeout; what is under test here is which requests get that far.+func testHandlers() Handlers {return Handlers{GatewayCfg: config.GatewayConfiguration{@@ -19,6 +42,31 @@ func testHandlers() Handlers {}}+// authorizationStage builds the production authorization middleware for a route+// in front of a stub handler, and reports whether a request reached the stub.+func authorizationStage(t *testing.T, route string) (http.Handler, *bool) {+ t.Helper()+ if err := featureflags.SetupProvider(context.Background(), "development", featureflags.AWSCredentials{}); err != nil {+ t.Fatalf("setup dev provider: %v", err)+ }+ auth.LoadOpa()+ auth.RegisterFactProvider(auth.NamespaceRBACFactProvider, NamespaceRBACFacts(testHandlers()))++ reached := false+ stub := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ reached = true+ w.WriteHeader(http.StatusNoContent)+ })+ return auth.RouteContext(route)(auth.RouteMiddleware(route)(stub)), &reached+}++const (+ svcRoute = "/api/svc/{namespace}/{service}/{path...}"+ orchRoute = "/api/orch/{namespace}/{service}/{path...}"+ namespacesRoute = "/api/namespaces/{name}"+ namespaceList = "/api/namespaces"+)+// svcRequest builds a /api/svc request with path values + user stamped.func svcRequest(u *auth.User, ns, service string) *http.Request {r := httptest.NewRequest(http.MethodGet, "/api/svc/"+ns+"/"+service+"/", nil)@@ -31,58 +79,46 @@ func svcRequest(u *auth.User, ns, service string) *http.Request {return r}-const probePath = "/apis/rbac.authorization.k8s.io/v1/namespaces/other-ns/rolebindings"--func TestSvc_PerKey_NamespaceMismatch_Forbidden(t *testing.T) {- resetOwnershipCache()- fk := newFakeK8s(http.StatusOK, `{"items":[]}`)- defer fk.server.Close()- overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")-- h := testHandlers()- w := httptest.NewRecorder()- h.Svc(w, svcRequest(&auth.User{ID: "svc-acct", AZP: "key-mypool", Namespace: "mypool"}, "other-ns", "novnc"))-- if w.Code != http.StatusForbidden {- t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())+// factRequest builds the request a FactProvider is handed on a route: the user,+// and the route's parameters stamped by the production RouteContext rather than+// by a second copy of what it does.+func factRequest(u *auth.User, route string, params map[string]string) *http.Request {+ r := httptest.NewRequest(http.MethodGet, "/", nil)+ for key, value := range params {+ r.SetPathValue(key, value)}- if len(fk.requests) != 0 {- t.Fatalf("expected no K8s probe for per-key client, got %d request(s)", len(fk.requests))+ if u != nil {+ r = withUser(r, u)}+ var stamped *http.Request+ auth.RouteContext(route)(http.HandlerFunc(func(_ http.ResponseWriter, got *http.Request) {+ stamped = got+ })).ServeHTTP(httptest.NewRecorder(), r)+ return stamped}-// The "allowed" paths are exercised via requireNamespaceAccess directly:-// going through h.Svc would make the reverse proxy dial the (nonexistent)-// *.svc.cluster.local target and stall the test on DNS timeouts.--func TestRequireNamespaceAccess_PerKey_NamespaceMatch_NoProbe(t *testing.T) {- resetOwnershipCache()- fk := newFakeK8s(http.StatusOK, `{"items":[]}`)- defer fk.server.Close()- overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")+const probePath = "/apis/rbac.authorization.k8s.io/v1/namespaces/other-ns/rolebindings"- h := testHandlers()- w := httptest.NewRecorder()- r := svcRequest(&auth.User{ID: "svc-acct", AZP: "key-mypool", Namespace: "mypool"}, "mypool", "novnc")- if !h.requireNamespaceAccess(w, r, currentUser(r), "mypool") {- t.Fatalf("authorized per-key request rejected; status = %d, body = %s", w.Code, w.Body.String())- }- if len(fk.requests) != 0 {- t.Fatalf("expected no K8s probe for per-key client, got %d request(s)", len(fk.requests))- }+func spaUser(sub string) *auth.User {+ return &auth.User{ID: sub, AZP: "cyclops-cs-spa"}}-func TestRequireNamespaceAccess_SPAUser_OwnedNamespace_ProbeAllows(t *testing.T) {+// ── The provider ────────────────────────────────────────────────────────────++func TestNamespaceRBACFacts_ProbeShape(t *testing.T) {resetOwnershipCache()fk := newFakeK8s(http.StatusOK, `{"items":[]}`)defer fk.server.Close()overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")- h := testHandlers()- w := httptest.NewRecorder()- r := svcRequest(&auth.User{ID: "test-uuid", AZP: "cyclops-cs-spa"}, "other-ns", "novnc")- if !h.requireNamespaceAccess(w, r, currentUser(r), "other-ns") {- t.Fatalf("owner rejected; status = %d, body = %s", w.Code, w.Body.String())+ provider := NamespaceRBACFacts(testHandlers())+ facts, err := provider.LoadFacts(context.Background(),+ factRequest(spaUser("test-uuid"), svcRoute, map[string]string{"namespace": "other-ns"}))+ if err != nil {+ t.Fatalf("load facts: %v", err)+ }+ if facts["allowed"] != true {+ t.Fatalf("facts = %#v, want allowed:true", facts)}if len(fk.requests) != 1 {t.Fatalf("expected exactly one probe, got %d", len(fk.requests))@@ -99,161 +135,422 @@ func TestRequireNamespaceAccess_SPAUser_OwnedNamespace_ProbeAllows(t *testing.T)}}-func TestSvc_SPAUser_NonOwnedNamespace_Forbidden(t *testing.T) {+// The {name} parameter is what /api/namespaces/{name} binds, and the provider+// has to reach the same namespace the Rego does from it — see+// TestOwnedNamespaceMatchesRego for the other half of that agreement.+func TestNamespaceRBACFacts_ReadsTheNameParameter(t *testing.T) {resetOwnershipCache()- fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status","status":"Failure","reason":"Forbidden"}`)+ fk := newFakeK8s(http.StatusOK, `{"items":[]}`)defer fk.server.Close()overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")- h := testHandlers()- w := httptest.NewRecorder()- h.Svc(w, svcRequest(&auth.User{ID: "intruder-uuid", AZP: "cyclops-cs-spa"}, "other-ns", "novnc"))+ if _, err := NamespaceRBACFacts(testHandlers()).LoadFacts(context.Background(),+ factRequest(spaUser("test-uuid"), namespacesRoute, map[string]string{"name": "other-ns"})); err != nil {+ t.Fatalf("load facts: %v", err)+ }+ if len(fk.requests) != 1 || fk.requests[0].path != probePath {+ t.Fatalf("probes = %#v, want one GET %s", fk.requests, probePath)+ }+}- if w.Code != http.StatusForbidden {- t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())+// The TTL cache that made the old handler check affordable has to survive the+// move. The policy library's own fact cache is per request, so if the provider+// had reimplemented the probe instead of wrapping it, this would be 3.+func TestNamespaceRBACFacts_VerdictCachedAcrossRequests(t *testing.T) {+ resetOwnershipCache()+ fk := newFakeK8s(http.StatusOK, `{"items":[]}`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ provider := NamespaceRBACFacts(testHandlers())+ for i := 0; i < 3; i++ {+ facts, err := provider.LoadFacts(context.Background(),+ factRequest(spaUser("test-uuid"), svcRoute, map[string]string{"namespace": "other-ns"}))+ if err != nil || facts["allowed"] != true {+ t.Fatalf("load %d: facts = %#v, err = %v", i, facts, err)+ }+ }+ if len(fk.requests) != 1 {+ t.Fatalf("expected 1 probe across 3 loads (cached), got %d", len(fk.requests))}}-func TestSvc_OAuth2ProxyUser_NonOwnedNamespace_Forbidden(t *testing.T) {+func TestNamespaceRBACFacts_NegativeVerdictCached(t *testing.T) {resetOwnershipCache()- fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status","status":"Failure","reason":"Forbidden"}`)+ fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status"}`)defer fk.server.Close()overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")- h := testHandlers()- w := httptest.NewRecorder()- h.Svc(w, svcRequest(&auth.User{ID: "intruder-uuid", AZP: "oauth2-proxy", Email: "[email protected]"}, "other-ns", "novnc"))+ provider := NamespaceRBACFacts(testHandlers())+ for i := 0; i < 2; i++ {+ facts, err := provider.LoadFacts(context.Background(),+ factRequest(spaUser("intruder-uuid"), svcRoute, map[string]string{"namespace": "other-ns"}))+ if err != nil || facts["allowed"] != false {+ t.Fatalf("load %d: facts = %#v, err = %v", i, facts, err)+ }+ }+ if len(fk.requests) != 1 {+ t.Fatalf("expected 1 probe across 2 loads (negative cached), got %d", len(fk.requests))+ }+}- if w.Code != http.StatusForbidden {- t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())+func TestNamespaceRBACFacts_CacheIsPerUser(t *testing.T) {+ resetOwnershipCache()+ fk := newFakeK8s(http.StatusOK, `{"items":[]}`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ provider := NamespaceRBACFacts(testHandlers())+ for _, sub := range []string{"user-a", "user-b"} {+ if _, err := provider.LoadFacts(context.Background(),+ factRequest(spaUser(sub), svcRoute, map[string]string{"namespace": "other-ns"})); err != nil {+ t.Fatalf("load for %s: %v", sub, err)+ }+ }+ // A cached verdict for user-a must not leak to user-b.+ if len(fk.requests) != 2 {+ t.Fatalf("expected 2 probes (one per user), got %d", len(fk.requests))}}-func TestSvc_K8sUnavailable_FailsClosed(t *testing.T) {+// An unreachable apiserver is a FactUnavailableError rather than a bare one,+// which is what keeps the response a 502 instead of a 500; and it is not cached,+// so a flapping apiserver cannot pin a verdict.+func TestNamespaceRBACFacts_UnavailableIsTypedAndUncached(t *testing.T) {resetOwnershipCache()fk := newFakeK8s(http.StatusInternalServerError, `oops`)defer fk.server.Close()overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")- h := testHandlers()+ provider := NamespaceRBACFacts(testHandlers())for i := 0; i < 2; i++ {- w := httptest.NewRecorder()- h.Svc(w, svcRequest(&auth.User{ID: "test-uuid", AZP: "cyclops-cs-spa"}, "other-ns", "novnc"))- if w.Code != http.StatusBadGateway {- t.Fatalf("status = %d, want 502; body = %s", w.Code, w.Body.String())+ _, err := provider.LoadFacts(context.Background(),+ factRequest(spaUser("test-uuid"), svcRoute, map[string]string{"namespace": "other-ns"}))+ var unavailable *auth.FactUnavailableError+ if !errors.As(err, &unavailable) {+ t.Fatalf("load %d: err = %v, want a *auth.FactUnavailableError", i, err)+ }+ if unavailable.Namespace != auth.NamespaceRBACFactNamespace {+ t.Fatalf("error names facts %q, want %q", unavailable.Namespace, auth.NamespaceRBACFactNamespace)}}- // Indeterminate verdicts must not be cached: both requests probe.if len(fk.requests) != 2 {t.Fatalf("expected 2 probes (errors uncached), got %d", len(fk.requests))}}-func TestOwnership_PositiveVerdictCached(t *testing.T) {+// Neither degenerate input is a policy judgement: they are questions the probe+// cannot form. Both deny, and neither costs a round trip.+func TestNamespaceRBACFacts_DegenerateInputsDenyWithoutProbing(t *testing.T) {resetOwnershipCache()fk := newFakeK8s(http.StatusOK, `{"items":[]}`)defer fk.server.Close()overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")- h := testHandlers()- for i := 0; i < 3; i++ {+ provider := NamespaceRBACFacts(testHandlers())+ for _, testCase := range []struct {+ name string+ request *http.Request+ }{+ {"no user", factRequest(nil, svcRoute, map[string]string{"namespace": "ns-a"})},+ {"empty sub", factRequest(spaUser(""), svcRoute, map[string]string{"namespace": "ns-a"})},+ {"no namespace", factRequest(spaUser("u-1"), namespaceList, map[string]string{})},+ {"empty namespace", factRequest(spaUser("u-1"), svcRoute, map[string]string{"namespace": ""})},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ facts, err := provider.LoadFacts(context.Background(), testCase.request)+ if err != nil {+ t.Fatalf("load facts: %v", err)+ }+ if facts["allowed"] != false {+ t.Fatalf("facts = %#v, want allowed:false", facts)+ }+ })+ }+ if len(fk.requests) != 0 {+ t.Fatalf("expected no probes, got %d", len(fk.requests))+ }+}++// ── The authorization stage ─────────────────────────────────────────────────++// The noVNC case, end to end: a burst of asset requests from one user for one+// namespace costs one probe, not one each. This is the property the move had to+// preserve — the policy library's fact cache is per request, and only the+// probe's own TTL cache spans them.+func TestSvcRoute_SPAUser_OwnedNamespace_AllowedAndProbedOnce(t *testing.T) {+ resetOwnershipCache()+ fk := newFakeK8s(http.StatusOK, `{"items":[]}`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ stage, reached := authorizationStage(t, svcRoute)+ for i := 0; i < 5; i++ {w := httptest.NewRecorder()- r := svcRequest(&auth.User{ID: "test-uuid", AZP: "cyclops-cs-spa"}, "other-ns", "novnc")- if !h.requireNamespaceAccess(w, r, currentUser(r), "other-ns") {- t.Fatalf("request %d rejected with %d", i, w.Code)+ stage.ServeHTTP(w, svcRequest(spaUser("test-uuid"), "other-ns", "novnc"))+ if w.Code != http.StatusNoContent || !*reached {+ t.Fatalf("request %d: status = %d, reached = %v; want 204 and the handler reached; body = %s",+ i, w.Code, *reached, w.Body.String())}}if len(fk.requests) != 1 {- t.Fatalf("expected 1 probe across 3 requests (cached), got %d", len(fk.requests))+ t.Fatalf("expected 1 probe across 5 requests (TTL-cached), got %d", len(fk.requests))+ }+}++func TestSvcRoute_SPAUser_NonOwnedNamespace_Forbidden(t *testing.T) {+ resetOwnershipCache()+ fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status","status":"Failure","reason":"Forbidden"}`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ stage, reached := authorizationStage(t, svcRoute)+ w := httptest.NewRecorder()+ stage.ServeHTTP(w, svcRequest(spaUser("intruder-uuid"), "other-ns", "novnc"))++ if w.Code != http.StatusForbidden || *reached {+ t.Fatalf("status = %d, reached = %v; want 403 and no handler; body = %s",+ w.Code, *reached, w.Body.String())+ }+}++func TestSvcRoute_OAuth2ProxyUser_NonOwnedNamespace_Forbidden(t *testing.T) {+ resetOwnershipCache()+ fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status","status":"Failure","reason":"Forbidden"}`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ stage, reached := authorizationStage(t, svcRoute)+ w := httptest.NewRecorder()+ stage.ServeHTTP(w, svcRequest(&auth.User{ID: "intruder-uuid", AZP: "oauth2-proxy", Email: "[email protected]"}, "other-ns", "novnc"))++ if w.Code != http.StatusForbidden || *reached {+ t.Fatalf("status = %d, reached = %v; want 403 and no handler; body = %s",+ w.Code, *reached, w.Body.String())}}-func TestOwnership_NegativeVerdictCached(t *testing.T) {+// Per-key clients are bound to their namespace claim, which is a check over the+// token: allowed or denied, it must never cost a probe.+func TestSvcRoute_PerKey_NamespaceMatch_Allowed_NoProbe(t *testing.T) {resetOwnershipCache()fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status"}`)defer fk.server.Close()overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")- h := testHandlers()- for i := 0; i < 2; i++ {- w := httptest.NewRecorder()- h.Svc(w, svcRequest(&auth.User{ID: "intruder-uuid", AZP: "cyclops-cs-spa"}, "other-ns", "novnc"))- if w.Code != http.StatusForbidden {- t.Fatalf("request %d: status = %d, want 403", i, w.Code)- }+ stage, reached := authorizationStage(t, svcRoute)+ w := httptest.NewRecorder()+ stage.ServeHTTP(w, svcRequest(&auth.User{ID: "svc-acct", AZP: "key-mypool", Namespace: "mypool"}, "mypool", "novnc"))++ if w.Code != http.StatusNoContent || !*reached {+ t.Fatalf("status = %d, reached = %v; want 204 and the handler reached; body = %s",+ w.Code, *reached, w.Body.String())}- if len(fk.requests) != 1 {- t.Fatalf("expected 1 probe across 2 requests (negative cached), got %d", len(fk.requests))+ if len(fk.requests) != 0 {+ t.Fatalf("expected no K8s probe for per-key client, got %d request(s)", len(fk.requests))}}-func TestOwnership_CacheIsPerUser(t *testing.T) {+func TestSvcRoute_PerKey_NamespaceMismatch_Forbidden_NoProbe(t *testing.T) {resetOwnershipCache()fk := newFakeK8s(http.StatusOK, `{"items":[]}`)defer fk.server.Close()overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")- h := testHandlers()- for _, sub := range []string{"user-a", "user-b"} {- w := httptest.NewRecorder()- r := svcRequest(&auth.User{ID: sub, AZP: "cyclops-cs-spa"}, "other-ns", "novnc")- h.requireNamespaceAccess(w, r, currentUser(r), "other-ns")+ stage, reached := authorizationStage(t, svcRoute)+ w := httptest.NewRecorder()+ stage.ServeHTTP(w, svcRequest(&auth.User{ID: "svc-acct", AZP: "key-mypool", Namespace: "mypool"}, "other-ns", "novnc"))++ if w.Code != http.StatusForbidden || *reached {+ t.Fatalf("status = %d, reached = %v; want 403 and no handler; body = %s",+ w.Code, *reached, w.Body.String())}- // A cached verdict for user-a must not leak to user-b.- if len(fk.requests) != 2 {- t.Fatalf("expected 2 probes (one per user), got %d", len(fk.requests))+ // The fake would allow this one. A probe here would be a per-key service+ // account borrowing somebody else's namespace.+ if len(fk.requests) != 0 {+ t.Fatalf("expected no K8s probe for per-key client, got %d request(s)", len(fk.requests))}}-func TestSvc_InvalidNamespace_BadRequest(t *testing.T) {+func TestSvcRoute_GitHubPrincipal_ClaimAllows_NoProbe(t *testing.T) {resetOwnershipCache()- h := testHandlers()+ fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status"}`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ stage, reached := authorizationStage(t, svcRoute)w := httptest.NewRecorder()- h.Svc(w, svcRequest(&auth.User{ID: "test-uuid", AZP: "cyclops-cs-spa"}, "Bad_NS", "novnc"))+ stage.ServeHTTP(w, svcRequest(&auth.User{+ ID: "user-123",+ AZP: "github-oidc",+ PrincipalType: auth.PrincipalTypeGitHubOIDC,+ AllowedNamespaces: []string{"allowed-ns"},+ }, "allowed-ns", "novnc"))- if w.Code != http.StatusBadRequest {- t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String())+ if w.Code != http.StatusNoContent || !*reached {+ t.Fatalf("status = %d, reached = %v; want 204 and the handler reached; body = %s",+ w.Code, *reached, w.Body.String())+ }+ if len(fk.requests) != 0 {+ t.Fatalf("expected no K8s probe, got %d request(s)", len(fk.requests))}}-func TestRequireNamespaceAccess_GitHubPrincipalAllowedWithoutProbe(t *testing.T) {+// This is All(cheapDeny, factLeaf) on a production route: probe_eligible is+// false for a GitHub token, so the conjunction is decided before the leaf+// carrying the provider is reached. The fake would have said yes.+func TestSvcRoute_GitHubPrincipal_UngrantedNamespace_Forbidden_NoProbe(t *testing.T) {resetOwnershipCache()- fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status"}`)+ fk := newFakeK8s(http.StatusOK, `{"items":[]}`)defer fk.server.Close()overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")- h := testHandlers()+ stage, reached := authorizationStage(t, svcRoute)w := httptest.NewRecorder()- r := svcRequest(&auth.User{+ stage.ServeHTTP(w, svcRequest(&auth.User{ID: "user-123",AZP: "github-oidc",PrincipalType: auth.PrincipalTypeGitHubOIDC,AllowedNamespaces: []string{"allowed-ns"},- }, "allowed-ns", "novnc")- if !h.requireNamespaceAccess(w, r, currentUser(r), "allowed-ns") {- t.Fatalf("authorized GitHub principal rejected; status = %d, body = %s", w.Code, w.Body.String())+ }, "other-ns", "novnc"))++ if w.Code != http.StatusForbidden || *reached {+ t.Fatalf("status = %d, reached = %v; want 403 and no handler; body = %s",+ w.Code, *reached, w.Body.String())}if len(fk.requests) != 0 {t.Fatalf("expected no K8s probe, got %d request(s)", len(fk.requests))}}-func TestOrch_NonOwnedNamespace_Forbidden(t *testing.T) {+// And this is the other short-circuit: a cheap sibling of the ownership+// conjunct — the surface's DNS-label check — denying before it runs at all.+func TestSvcRoute_InvalidNamespace_Forbidden_NoProbe(t *testing.T) {+ resetOwnershipCache()+ fk := newFakeK8s(http.StatusOK, `{"items":[]}`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ stage, reached := authorizationStage(t, svcRoute)+ w := httptest.NewRecorder()+ stage.ServeHTTP(w, svcRequest(spaUser("test-uuid"), "Bad_NS", "novnc"))++ if w.Code != http.StatusForbidden || *reached {+ t.Fatalf("status = %d, reached = %v; want 403 and no handler; body = %s",+ w.Code, *reached, w.Body.String())+ }+ if len(fk.requests) != 0 {+ t.Fatalf("expected no K8s probe, got %d request(s)", len(fk.requests))+ }+}++// The failure mode the move had to preserve: an unreachable apiserver is a 502+// the caller can retry, not a 500. Through the lattice it would have been a 500+// without FactUnavailableError.+func TestSvcRoute_K8sUnavailable_FailsClosedWith502(t *testing.T) {+ resetOwnershipCache()+ fk := newFakeK8s(http.StatusInternalServerError, `oops`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ stage, reached := authorizationStage(t, svcRoute)+ for i := 0; i < 2; i++ {+ w := httptest.NewRecorder()+ stage.ServeHTTP(w, svcRequest(spaUser("test-uuid"), "other-ns", "novnc"))+ if w.Code != http.StatusBadGateway || *reached {+ t.Fatalf("request %d: status = %d, reached = %v; want 502 and no handler; body = %s",+ i, w.Code, *reached, w.Body.String())+ }+ }+ // Indeterminate verdicts must not be cached: both requests probe.+ if len(fk.requests) != 2 {+ t.Fatalf("expected 2 probes (errors uncached), got %d", len(fk.requests))+ }+}++func TestOrchRoute_NonOwnedNamespace_Forbidden(t *testing.T) {resetOwnershipCache()fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status"}`)defer fk.server.Close()overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")- h := testHandlers()+ stage, reached := authorizationStage(t, orchRoute)r := httptest.NewRequest(http.MethodGet, "/api/orch/other-ns/catalog/items", nil)r.SetPathValue("namespace", "other-ns")r.SetPathValue("service", "catalog")r.SetPathValue("path", "items")- r = withUser(r, &auth.User{ID: "intruder-uuid", AZP: "cyclops-cs-spa"})+ r = withUser(r, spaUser("intruder-uuid"))w := httptest.NewRecorder()- h.Orch(w, r)+ stage.ServeHTTP(w, r)- if w.Code != http.StatusForbidden {- t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())+ if w.Code != http.StatusForbidden || *reached {+ t.Fatalf("status = %d, reached = %v; want 403 and no handler; body = %s",+ w.Code, *reached, w.Body.String())+ }+}++func TestNamespacesRoute_GetOtherTenant_Forbidden(t *testing.T) {+ resetOwnershipCache()+ fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status"}`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ stage, reached := authorizationStage(t, namespacesRoute)+ r := httptest.NewRequest(http.MethodGet, "/api/namespaces/other-ns", nil)+ r.SetPathValue("name", "other-ns")+ r = withUser(r, spaUser("intruder-uuid"))+ w := httptest.NewRecorder()+ stage.ServeHTTP(w, r)++ if w.Code != http.StatusForbidden || *reached {+ t.Fatalf("status = %d, reached = %v; want 403 and no handler; body = %s",+ w.Code, *reached, w.Body.String())+ }+ if len(fk.requests) != 1 {+ t.Fatalf("expected exactly one probe, got %d", len(fk.requests))+ }+}++// The other three routes on the namespaces surface never ran this check, and+// still must not: DELETE goes to the K8s API impersonated, where Capsule is the+// boundary, and the list route names no namespace to probe for in the first+// place.+func TestNamespacesSurface_RoutesOutsideTheBoundaryDoNotProbe(t *testing.T) {+ resetOwnershipCache()+ fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status"}`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ for _, testCase := range []struct {+ name string+ route string+ method string+ path string+ params map[string]string+ wantHit bool+ }{+ {name: "delete", route: namespacesRoute, method: http.MethodDelete, path: "/api/namespaces/other-ns",+ params: map[string]string{"name": "other-ns"}, wantHit: true},+ {name: "list", route: namespaceList, method: http.MethodGet, path: "/api/namespaces",+ params: map[string]string{}, wantHit: true},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ stage, reached := authorizationStage(t, testCase.route)+ r := httptest.NewRequest(testCase.method, testCase.path, nil)+ for key, value := range testCase.params {+ r.SetPathValue(key, value)+ }+ r = withUser(r, spaUser("test-uuid"))+ w := httptest.NewRecorder()+ stage.ServeHTTP(w, r)++ if (w.Code == http.StatusNoContent) != testCase.wantHit || *reached != testCase.wantHit {+ t.Fatalf("status = %d, reached = %v; want the handler reached = %v; body = %s",+ w.Code, *reached, testCase.wantHit, w.Body.String())+ }+ })+ }+ if len(fk.requests) != 0 {+ t.Fatalf("expected no probes off the ownership boundary, got %d", len(fk.requests))}}diff --git a/libs/fleet/backend/handlers/svc.go b/libs/fleet/backend/handlers/svc.goindex 9c7819e771..8878a2f7b5 100644--- a/libs/fleet/backend/handlers/svc.go+++ b/libs/fleet/backend/handlers/svc.go@@ -78,11 +78,10 @@ func (h Handlers) Svc(w http.ResponseWriter, r *http.Request) {return}- // Tenancy boundary: this proxy dials Service DNS directly (never the- // K8s API), so Capsule can't scope it — enforce ownership here.- if !h.requireNamespaceAccess(w, r, user, ns) {- return- }+ // Tenancy boundary: this proxy dials Service DNS directly (never the K8s+ // API), so Capsule can't scope it. The boundary is the ownership conjunct+ // of SvcRoutePolicy, which has already run by the time this handler is+ // reached — see auth/authz_ownership.rego.host := fmt.Sprintf("%s.%s.%s", service, ns, h.GatewayCfg.ClusterDomain)target := &url.URL{Scheme: h.GatewayCfg.Scheme, Host: host + ":" + h.GatewayCfg.Port}diff --git a/libs/fleet/backend/handlers/user_keys.go b/libs/fleet/backend/handlers/user_keys.goindex 3cd78d7905..a802bd06e5 100644--- a/libs/fleet/backend/handlers/user_keys.go+++ b/libs/fleet/backend/handlers/user_keys.go@@ -147,4 +147,3 @@ func (h Handlers) DeleteUserKey(w http.ResponseWriter, r *http.Request) {}w.WriteHeader(http.StatusNoContent)}-diff --git a/libs/fleet/backend/main.go b/libs/fleet/backend/main.goindex a294397ef7..f59358b11f 100644--- a/libs/fleet/backend/main.go+++ b/libs/fleet/backend/main.go@@ -9,20 +9,14 @@// /api/keys[/{id}] — SPA-authenticated CRUD on per-user// service-account clients in Keycloak.//-// /api/batch/{pool}, /api/label/{pool}-// — DEPRECATED. Returns 410 Gone for every-// request. The orchestrator-backed batch-// surface is retired; callers must-// migrate to the replacement flow.-//// @title Cyclops CS Backend API// @version 0.1-// @description Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key management, service proxies (k8s / orch / svc), namespace management, and deprecated batch / label routes that now return 410 Gone. All pool operations use OSGymSandboxClaim CRs (Path B).+// @description Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key management, service proxies (k8s / orch / svc), and namespace management. All pool operations use OSGymSandboxClaim CRs (Path B).// @BasePath /// @securityDefinitions.apikey BearerAuth// @in header// @name Authorization-// @description Keycloak access token. For /api/keys and /api/{k8s,orch} the token is an interactive user JWT (azp=cyclops-cs-spa or azp=cua-cli). The deprecated /api/batch/{pool} and /api/label/{pool} routes are permanently retired — they return 410 Gone for every request regardless of token validity.+// @description Keycloak access token. For /api/keys and /api/{k8s,orch} the token is an interactive user JWT (azp=cyclops-cs-spa or azp=cua-cli).package mainimport (@@ -52,31 +46,66 @@ import (var configValues *config.Configuration-// withMiddlewares mirrors grt — every authenticated route runs through-// Trace → Log → TokenAuth → OPA. RouteContext stamps the matched route-// (and its named params) onto the request context so the Rego policy-// can branch on `input.route` instead of regex-parsing the URL.-func withMiddlewares(route string, params []string, h http.HandlerFunc) http.Handler {- return middlewares.TraceMiddleware(route,- middlewares.LogMiddleware(- auth.RouteContext(route, params...)(- auth.TokenAuthMiddleware(- auth.OpaMiddleware(- http.HandlerFunc(h))))))+func withMiddlewares(handler http.Handler, chain ...auth.Middleware) http.Handler {+ for index := len(chain) - 1; index >= 0; index-- {+ handler = chain[index](handler)+ }+ return handler}-// withK8sMiddlewares is withMiddlewares + auth.K8sEventFilterMiddleware-// sitting immediately above the handler. The event filter only buffers-// responses whose upstream path is a K8s EventList; all other K8s API-// calls pass through untouched.-func withK8sMiddlewares(route string, params []string, h http.HandlerFunc) http.Handler {- return middlewares.TraceMiddleware(route,- middlewares.LogMiddleware(- auth.RouteContext(route, params...)(- auth.TokenAuthMiddleware(- auth.OpaMiddleware(- auth.K8sEventFilterMiddleware(- http.HandlerFunc(h)))))))+func traceMiddleware(route string) auth.Middleware {+ return func(next http.Handler) http.Handler {+ return middlewares.TraceMiddleware(route, next)+ }+}++// withAuthenticatedMiddlewares is the chain every authenticated route runs+// through: Trace → Log → RouteContext → TokenAuth → policy.+//+// Which policy is not decided here. auth.RouteMiddleware looks the route up in+// the route → surface table in auth/policy_routes.go, so the route name passed+// to RouteContext — the same string the policy matches as input.route — is also+// what selects the policy. A route this file registers but that table does not+// name panics during route construction rather than serving traffic on a policy+// nobody chose. Plans are memoized per surface, not per route, so routes sharing+// a surface share one compiled plan.+//+// The route name is also the only place its path parameters are named:+// RouteContext reads the wildcards out of the pattern, so a route cannot be+// registered with a parameter list that disagrees with the path it serves.+//+// The policy stage ran on a bespoke middleware until it moved onto the+// composable policy library, and evaluated one route-aware module for every+// route until that module was decomposed into a shared base plus one surface+// module per group of routes. Neither move changed a verdict: the two+// middlewares were held to identical status and body across allow, deny and+// undecidable requests until the old one was deleted, and the decomposition was+// held to auth/testdata/route-authorization-table.txt.+//+// One thing the old middleware did was dropped rather than carried over: a+// per-request slog.Debug of the elapsed time and the allow/deny result. Nothing+// consumed it and nothing could have — run() installs a JSON handler at slog's+// default level, so debug records are discarded before they are written, and no+// Loki rule, dashboard, or runbook in this repo queries an "opa" line. Its+// deferred call still paid for a time.Since and two Context.Value lookups per+// request to build a record that was then thrown away.+//+// The allow/deny verdict is already observable at Info, and better:+// LogMiddleware wraps this stage and logs route, status, duration, and trace_id+// for every request, which is what the CyclopsCSBackendHighErrorRate alert+// reads through the equivalent 5xx metric. The error string is not part of+// that — PolicyMiddleware logs it at Error itself. Re-adding elapsed time per+// policy belongs on the policy library as a span, not on one middleware as an+// unreachable log line.+func withAuthenticatedMiddlewares(route string, h http.HandlerFunc) http.Handler {+ return withMiddlewares(+ http.HandlerFunc(h),+ traceMiddleware(route),+ middlewares.LogMiddleware,+ auth.RouteContext(route),+ auth.TokenAuthMiddleware,+ auth.RouteMiddleware(route),+ )}func onlyLog(route string, h http.HandlerFunc) http.Handler {@@ -84,25 +113,33 @@ func onlyLog(route string, h http.HandlerFunc) http.Handler {}func setupRouter(c handlers.Handlers) http.Handler {+ // The namespace-ownership conjunct on /api/svc, /api/orch and+ // /api/namespaces/{name} asks Kubernetes a question, through a probe that+ // is a handlers method. auth cannot import handlers, so the policy names+ // the provider and this is where the name is bound to it. It must happen+ // before the first RouteMiddleware below, because that is what compiles the+ // plans that refer to it.+ auth.RegisterFactProvider(auth.NamespaceRBACFactProvider, handlers.NamespaceRBACFacts(c))+r := http.NewServeMux()r.Handle("GET /healthz", onlyLog("/healthz", c.GetHealth))// Feature flags / per-user config. SPA-only (same auth as /api/keys).r.Handle("GET /api/config",- withMiddlewares("/api/config", nil, c.GetConfig))+ withAuthenticatedMiddlewares("/api/config", c.GetConfig))r.Handle("QUERY /api/state/query",- withMiddlewares("/api/state/query", nil, c.QueryState))+ withAuthenticatedMiddlewares("/api/state/query", c.QueryState))// Stripe-hosted billing. Browser routes require the normal SPA JWT; the// webhook uses Stripe signature verification as its authentication boundary.r.Handle("GET /api/billing/summary",- withMiddlewares("/api/billing/summary", nil, c.GetBillingSummary))+ withAuthenticatedMiddlewares("/api/billing/summary", c.GetBillingSummary))r.Handle("POST /api/billing/setup-session",- withMiddlewares("/api/billing/setup-session", nil, c.CreateBillingSetupSession))+ withAuthenticatedMiddlewares("/api/billing/setup-session", c.CreateBillingSetupSession))r.Handle("POST /api/billing/portal-session",- withMiddlewares("/api/billing/portal-session", nil, c.CreateBillingPortalSession))+ withAuthenticatedMiddlewares("/api/billing/portal-session", c.CreateBillingPortalSession))r.Handle("POST /api/billing/webhook",onlyLog("/api/billing/webhook", c.HandleBillingWebhook))@@ -114,82 +151,56 @@ func setupRouter(c handlers.Handlers) http.Handler {}))r.Handle("POST /api/keys",- withMiddlewares("/api/keys", nil, c.CreateKey))+ withAuthenticatedMiddlewares("/api/keys", c.CreateKey))r.Handle("GET /api/keys",- withMiddlewares("/api/keys", nil, c.ListKeys))+ withAuthenticatedMiddlewares("/api/keys", c.ListKeys))r.Handle("DELETE /api/keys/{id}",- withMiddlewares("/api/keys/{id}", []string{"id"}, c.DeleteKey))+ withAuthenticatedMiddlewares("/api/keys/{id}", c.DeleteKey))// Namespace management — Capsule-backed per-user namespaces.// Uses K8s impersonation so Capsule sees the real user identity.r.Handle("GET /api/namespaces",- withMiddlewares("/api/namespaces", nil, c.ListNamespaces))+ withAuthenticatedMiddlewares("/api/namespaces", c.ListNamespaces))r.Handle("POST /api/namespaces",- withMiddlewares("/api/namespaces", nil, c.CreateNamespace))+ withAuthenticatedMiddlewares("/api/namespaces", c.CreateNamespace))r.Handle("GET /api/namespaces/{name}",- withMiddlewares("/api/namespaces/{name}", []string{"name"}, c.GetNamespace))+ withAuthenticatedMiddlewares("/api/namespaces/{name}", c.GetNamespace))r.Handle("DELETE /api/namespaces/{name}",- withMiddlewares("/api/namespaces/{name}", []string{"name"}, c.DeleteNamespace))+ withAuthenticatedMiddlewares("/api/namespaces/{name}", c.DeleteNamespace))// Per-user API keys — Keycloak service-account clients (ukey- prefix).r.Handle("POST /api/user-keys",- withMiddlewares("/api/user-keys", nil, c.CreateUserKey))+ withAuthenticatedMiddlewares("/api/user-keys", c.CreateUserKey))r.Handle("GET /api/user-keys",- withMiddlewares("/api/user-keys", nil, c.ListUserKeys))+ withAuthenticatedMiddlewares("/api/user-keys", c.ListUserKeys))r.Handle("DELETE /api/user-keys/{id}",- withMiddlewares("/api/user-keys/{id}", []string{"id"}, c.DeleteUserKey))+ withAuthenticatedMiddlewares("/api/user-keys/{id}", c.DeleteUserKey))r.Handle("GET /api/github-trust-policies",- withMiddlewares("/api/github-trust-policies", nil, c.ListGitHubTrustPolicies))+ withAuthenticatedMiddlewares("/api/github-trust-policies", c.ListGitHubTrustPolicies))r.Handle("POST /api/github-trust-policies",- withMiddlewares("/api/github-trust-policies", nil, c.CreateGitHubTrustPolicy))+ withAuthenticatedMiddlewares("/api/github-trust-policies", c.CreateGitHubTrustPolicy))r.Handle("PATCH /api/github-trust-policies/{id}",- withMiddlewares("/api/github-trust-policies/{id}", []string{"id"}, c.UpdateGitHubTrustPolicy))+ withAuthenticatedMiddlewares("/api/github-trust-policies/{id}", c.UpdateGitHubTrustPolicy))r.Handle("DELETE /api/github-trust-policies/{id}",- withMiddlewares("/api/github-trust-policies/{id}", []string{"id"}, c.DeleteGitHubTrustPolicy))+ withAuthenticatedMiddlewares("/api/github-trust-policies/{id}", c.DeleteGitHubTrustPolicy))// Generic service proxy — reaches a K8s Service on port 80 in a- // namespace the caller is authorized for. OPA gates authn/shape;- // namespace ownership is enforced in the handler (per-key tokens via- // their namespace claim, everyone else via an impersonated- // RoleBinding probe — see handlers.requireNamespaceAccess).+ // namespace the caller is authorized for. Authn, parameter shape and+ // namespace ownership are all the policy's: per-key and GitHub tokens by+ // their claims, everyone else by an impersonated RoleBinding probe the+ // policy reads as a fact — see auth/authz_ownership.rego.r.Handle("/api/svc/{namespace}/{service}",- withMiddlewares("/api/svc/{namespace}/{service}",- []string{"namespace", "service"}, c.Svc))+ withAuthenticatedMiddlewares("/api/svc/{namespace}/{service}", c.Svc))r.Handle("/api/svc/{namespace}/{service}/{path...}",- withMiddlewares("/api/svc/{namespace}/{service}/{path...}",- []string{"namespace", "service", "path"}, c.Svc))+ withAuthenticatedMiddlewares("/api/svc/{namespace}/{service}/{path...}", c.Svc))// K8s API + per-namespace orchestrator catalog access — replace the// unauthenticated /k8s-api and /orch-api nginx locations from before.r.Handle("/api/k8s/{path...}",- withK8sMiddlewares("/api/k8s/{path...}", []string{"path"}, c.K8s))+ withAuthenticatedMiddlewares("/api/k8s/{path...}", c.K8s))r.Handle("/api/orch/{namespace}/{service}/{path...}",- withMiddlewares("/api/orch/{namespace}/{service}/{path...}",- []string{"namespace", "service", "path"}, c.Orch))-- // Keep deprecated batch/label routes registered so callers get an explicit- // terminal status instead of an implicit 404 from the router.- r.Handle("POST /api/batch/{pool}/submit",- withMiddlewares("/api/batch/{pool}/submit", []string{"pool"}, c.DeprecatedBatchSubmit))- r.Handle("POST /api/batch/{pool}/lanes",- withMiddlewares("/api/batch/{pool}/lanes", []string{"pool"}, c.DeprecatedBatchLanesCreate))- r.Handle("DELETE /api/batch/{pool}/lanes",- withMiddlewares("/api/batch/{pool}/lanes", []string{"pool"}, c.DeprecatedBatchLanesDelete))- r.Handle("GET /api/batch/{pool}/{id}/status",- withMiddlewares("/api/batch/{pool}/{id}/status", []string{"pool", "id"}, c.DeprecatedBatchStatus))- r.Handle("GET /api/batch/{pool}/{id}/results",- withMiddlewares("/api/batch/{pool}/{id}/results", []string{"pool", "id"}, c.DeprecatedBatchResults))- r.Handle("DELETE /api/batch/{pool}/{id}",- withMiddlewares("/api/batch/{pool}/{id}", []string{"pool", "id"}, c.DeprecatedBatchDelete))- r.Handle("POST /api/label/{pool}/{label}/batch",- withMiddlewares("/api/label/{pool}/{label}/batch", []string{"pool", "label"}, c.DeprecatedLabelBatch))- r.Handle("GET /api/label/{pool}/{label}/status",- withMiddlewares("/api/label/{pool}/{label}/status", []string{"pool", "label"}, c.DeprecatedLabelStatus))- r.Handle("GET /api/label/{pool}/{label}/results",- withMiddlewares("/api/label/{pool}/{label}/results", []string{"pool", "label"}, c.DeprecatedLabelResults))- r.Handle("DELETE /api/label/{pool}/{label}",- withMiddlewares("/api/label/{pool}/{label}", []string{"pool", "label"}, c.DeprecatedLabelDelete))+ withAuthenticatedMiddlewares("/api/orch/{namespace}/{service}/{path...}", c.Orch))// Wrap the entire mux in the metrics middleware so every request// (including /healthz and unmatched routes) is recorded. This must bediff --git a/libs/fleet/backend/main_test.go b/libs/fleet/backend/main_test.goindex 9e543dec4d..b6ce882eb7 100644--- a/libs/fleet/backend/main_test.go+++ b/libs/fleet/backend/main_test.go@@ -53,10 +53,6 @@ func TestSwaggerOmitsGatewayRoute(t *testing.T) {}}-// TestDeprecatedRoutes asserts that every deprecated batch/label endpoint-// returns HTTP 410 Gone with the canonical deprecation message. Each route-// is exercised individually so a regression on any single path is immediately-// visible rather than hidden behind a representative sample.func TestSwaggerUsesBillingSetupSessionRoute(t *testing.T) {data, err := os.ReadFile("docs/swagger.json")if err != nil {@@ -77,7 +73,12 @@ func TestSwaggerUsesBillingSetupSessionRoute(t *testing.T) {}}-func TestDeprecatedRoutes(t *testing.T) {+// TestBatchAndLabelRoutesAreRemoved pins the client-visible consequence of+// deleting the surface: these paths used to answer 410 Gone with an explanatory+// body, and now fall through to the mux's bare 404. Every path is exercised+// rather than a representative one, so a route restored by accident is visible+// by name.+func TestBatchAndLabelRoutesAreRemoved(t *testing.T) {router := setupRouter(handlers.Handlers{})cases := []struct {@@ -99,80 +100,31 @@ func TestDeprecatedRoutes(t *testing.T) {{http.MethodDelete, "/api/label/demo/run-1", nil},}- const wantMsg = "/api/batch and /api/label are deprecated and unavailable"-for _, tc := range cases {t.Run(tc.method+" "+tc.path, func(t *testing.T) {req := authorizedRequest(t, tc.method, tc.path, tc.body)w := httptest.NewRecorder()router.ServeHTTP(w, req)- if w.Code != http.StatusGone {- t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusGone, w.Body.String())- }- if !strings.Contains(w.Body.String(), wantMsg) {- t.Fatalf("body = %q, want deprecation message %q", w.Body.String(), wantMsg)+ if w.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusNotFound, w.Body.String())}})}}-func TestSwaggerMentionsBatchRouteDeprecation(t *testing.T) {+// TestSwaggerOmitsBatchAndLabelRoutes is the generated-artifact half of the+// same removal: `swag init` reads annotations off handlers, so a wrapper left+// behind keeps documenting a route the router no longer serves.+func TestSwaggerOmitsBatchAndLabelRoutes(t *testing.T) {data, err := os.ReadFile("docs/swagger.json")if err != nil {t.Fatal(err)}body := string(data)- if !strings.Contains(body, "\"410\"") {- t.Fatalf("swagger.json missing 410 response for deprecated batch routes")- }- if !strings.Contains(body, "deprecated and unavailable") {- t.Fatalf("swagger.json missing deprecation language")- }-- var spec struct {- Paths map[string]map[string]struct {- Description string `json:"description"`- Deprecated *bool `json:"deprecated"`- Responses map[string]any `json:"responses"`- } `json:"paths"`- }- if err := json.Unmarshal(data, &spec); err != nil {- t.Fatalf("unmarshal swagger.json: %v", err)- }-- cases := []struct {- path string- method string- }{- {path: "/api/batch/{pool}/submit", method: "post"},- {path: "/api/batch/{pool}/lanes", method: "post"},- {path: "/api/batch/{pool}/lanes", method: "delete"},- {path: "/api/batch/{pool}/{id}/status", method: "get"},- {path: "/api/batch/{pool}/{id}/results", method: "get"},- {path: "/api/batch/{pool}/{id}", method: "delete"},- {path: "/api/label/{pool}/{label}/batch", method: "post"},- {path: "/api/label/{pool}/{label}/status", method: "get"},- {path: "/api/label/{pool}/{label}/results", method: "get"},- {path: "/api/label/{pool}/{label}", method: "delete"},- }- for _, tc := range cases {- ops, ok := spec.Paths[tc.path]- if !ok {- t.Fatalf("swagger.json missing path %s", tc.path)- }- op, ok := ops[tc.method]- if !ok {- t.Fatalf("swagger.json missing %s %s", strings.ToUpper(tc.method), tc.path)- }- if !strings.Contains(op.Description, "deprecated and unavailable") {- t.Fatalf("%s %s description = %q, want deprecation language", strings.ToUpper(tc.method), tc.path, op.Description)- }- if op.Deprecated == nil || !*op.Deprecated {- t.Fatalf("%s %s deprecated = %v, want true", strings.ToUpper(tc.method), tc.path, op.Deprecated)- }- if _, ok := op.Responses["410"]; !ok {- t.Fatalf("%s %s missing 410 response", strings.ToUpper(tc.method), tc.path)+ for _, prefix := range []string{`"/api/batch/`, `"/api/label/`} {+ if strings.Contains(body, prefix) {+ t.Fatalf("swagger.json still exposes the removed %s routes", strings.Trim(prefix, `"`))}}}@@ -403,3 +355,54 @@ func TestStateQueryRouterUsesQueryMethod(t *testing.T) {t.Fatalf("Allow = %q, want QUERY", got)}}++func TestWithMiddlewaresAppliesInDeclarationOrder(t *testing.T) {+ var order []string+ middleware := func(name string) auth.Middleware {+ return func(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ order = append(order, name+":before")+ next.ServeHTTP(w, r)+ order = append(order, name+":after")+ })+ }+ }+ handler := withMiddlewares(+ http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ order = append(order, "handler")+ w.WriteHeader(http.StatusNoContent)+ }),+ middleware("first"),+ middleware("second"),+ )+ response := httptest.NewRecorder()+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))++ want := []string{"first:before", "second:before", "handler", "second:after", "first:after"}+ if !slices.Equal(order, want) {+ t.Fatalf("order = %v, want %v", order, want)+ }+}++func TestK8sRouteRejectsDisallowedPoolBeforeProxy(t *testing.T) {+ upstreamCalled := false+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ upstreamCalled = true+ w.WriteHeader(http.StatusCreated)+ }))+ defer upstream.Close()+ t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)++ router := setupRouter(handlers.Handlers{})+ body := strings.NewReader(`{"spec":{"template":{"containerDiskImage":"evil.example/workspace:latest","imagePullSecret":"ecr-credentials"}}}`)+ request := authorizedRequest(t, http.MethodPost, "/api/k8s/apis/cua.ai/v1/namespaces/foo/osgymworkspacepools", body)+ response := httptest.NewRecorder()+ router.ServeHTTP(response, request)++ if response.Code != http.StatusForbidden {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusForbidden, response.Body.String())+ }+ if upstreamCalled {+ t.Fatal("disallowed pool request reached kubectl proxy")+ }+}diff --git a/libs/fleet/backend/route_param_derivation_test.go b/libs/fleet/backend/route_param_derivation_test.gonew file mode 100644index 0000000000..a030aa235a--- /dev/null+++ b/libs/fleet/backend/route_param_derivation_test.go@@ -0,0 +1,119 @@+package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "cyclops-cs-backend/handlers"+)++// RouteContext derives a route's parameter names from its pattern rather than+// from a list registered alongside it. These tests are what stands between that+// derivation and a silent lockout: a parser that produced no names — or that+// kept the "..." of a trailing wildcard in the key — leaves input.params.X+// undefined, the rule body fails, `default allow = false` answers, and every+// route whose policy reads a parameter returns 403 to everyone. Nothing else in+// the suite notices, because failing closed is what a deny test expects too.+//+// So both routes below are driven in a pair. The deny half fails closed either+// way and proves nothing on its own; the allow half is the half that breaks.+//+// The verdicts are the ones auth/testdata/route-authorization-table.txt records+// for the same route, params and principal — a spa token here is the table's+// "spa" row.++// isPolicyDenial reports whether a response is the authorization stage's own+// 403 rather than a handler's. The two are told apart by message: the policy+// stage writes the surface's denied message, and every handler past it writes+// its own vocabulary. Status alone cannot separate them — the handlers deny+// with 403 as well.+func isPolicyDenial(t *testing.T, response *httptest.ResponseRecorder, deniedMessage string) bool {+ t.Helper()+ if response.Code != http.StatusForbidden {+ return false+ }+ var body struct {+ Error string `json:"error"`+ }+ if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {+ t.Fatalf("decode error body %q: %v", response.Body.String(), err)+ }+ return body.Error == deniedMessage+}++// TestK8sRouteVerdictFollowsThePathParam pins the {path...} wildcard: the two+// requests differ only in input.params.path, which is what authz_k8s.rego's+// infra-path check reads. Both are table rows —+//+// /api/k8s/{path...} | namespaced-pods | GET | spa = allow+// /api/k8s/{path...} | cluster-nodes | GET | spa = deny+//+// — and the allow row is unreachable unless the parameter is keyed "path" with+// no trailing dots.+func TestK8sRouteVerdictFollowsThePathParam(t *testing.T) {+ cases := []struct {+ name string+ path string+ wantUpstream bool+ wantStatusCode int+ }{+ {name: "namespaced pods are allowed", path: "/api/k8s/api/v1/namespaces/ns-a/pods", wantUpstream: true, wantStatusCode: http.StatusOK},+ {name: "cluster-wide nodes are denied", path: "/api/k8s/api/v1/nodes", wantUpstream: false, wantStatusCode: http.StatusForbidden},+ }++ for _, testCase := range cases {+ t.Run(testCase.name, func(t *testing.T) {+ upstreamCalled := false+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ upstreamCalled = true+ w.WriteHeader(http.StatusOK)+ }))+ defer upstream.Close()+ t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)++ router := setupRouter(handlers.Handlers{})+ response := httptest.NewRecorder()+ router.ServeHTTP(response, authorizedRequest(t, http.MethodGet, testCase.path, nil))++ if response.Code != testCase.wantStatusCode {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, testCase.wantStatusCode, response.Body.String())+ }+ if upstreamCalled != testCase.wantUpstream {+ t.Fatalf("upstream reached = %t, want %t; body = %s", upstreamCalled, testCase.wantUpstream, response.Body.String())+ }+ })+ }+}++// TestSvcRouteVerdictFollowsTheNamespaceParam pins the two mid-path wildcards+// of /api/svc/{namespace}/{service}, which authz_svc.rego shape-checks as DNS+// labels. Both are table rows —+//+// /api/svc/{namespace}/{service} | owned-ns | GET | spa = allow+// /api/svc/{namespace}/{service} | invalid-ns | GET | spa = deny+//+// The allowed request is not asserted to succeed: past the policy it reaches+// handlers.Svc, whose namespace-ownership probe has no K8s client in a test and+// fails closed. What is asserted is that the 403 it does not get is the policy's+// — which is exactly the verdict the table records.+func TestSvcRouteVerdictFollowsTheNamespaceParam(t *testing.T) {+ // The svc surface takes the default denied message; see auth.PolicyMiddleware.+ const svcDeniedMessage = "forbidden"++ router := setupRouter(handlers.Handlers{})++ allowed := httptest.NewRecorder()+ router.ServeHTTP(allowed, authorizedRequest(t, http.MethodGet, "/api/svc/ns-a/svc-a", nil))+ if isPolicyDenial(t, allowed, svcDeniedMessage) {+ t.Fatalf("a valid namespace and service were denied by the policy; body = %s", allowed.Body.String())+ }++ denied := httptest.NewRecorder()+ router.ServeHTTP(denied, authorizedRequest(t, http.MethodGet, "/api/svc/Not_A_Label/svc-a", nil))+ if !isPolicyDenial(t, denied, svcDeniedMessage) {+ t.Fatalf("a namespace that is not a DNS label was not denied by the policy; status = %d, body = %s",+ denied.Code, denied.Body.String())+ }+}diff --git a/libs/fleet/backend/route_policy_correspondence_test.go b/libs/fleet/backend/route_policy_correspondence_test.gonew file mode 100644index 0000000000..73ac6e7442--- /dev/null+++ b/libs/fleet/backend/route_policy_correspondence_test.go@@ -0,0 +1,443 @@+package main++import (+ "go/ast"+ "go/parser"+ "go/token"+ "os"+ "path/filepath"+ "slices"+ "strconv"+ "strings"+ "testing"++ "cyclops-cs-backend/auth"++ regoast "github.com/open-policy-agent/opa/ast"+)++// Three descriptions of the same route set have to agree, and until this file+// existed nothing made them:+//+// 1. what setupRouter registers,+// 2. what auth/policy_routes.go binds to an authorization surface,+// 3. what the Rego reasons about as input.route.+//+// #6702 deleted the /api/gateway route from (1) and its rules survived in (3)+// until a human noticed. This test is the thing that notices. It reads all three+// from source rather than from a copy: setupRouter's AST, the exported route+// table, and the parsed Rego modules.+//+// The checks run in both directions on purpose. A route registered with no+// policy is an open endpoint; a policy naming a route nobody registers is dead+// authorization code that reads as protection and provides none.++// routeWrappers is every helper setupRouter may wrap a handler in, and whether+// that helper installs the authorization stage. A wrapper missing from this map+// fails the test rather than being skipped: a new chain that quietly bypasses+// the policy is precisely the drift this file exists to catch.+var routeWrappers = map[string]bool{+ "withAuthenticatedMiddlewares": true,+ "onlyLog": false,+}++type registeredRoute struct {+ route string+ wrapper string+ authenticated bool+}++// registeredRoutes reads setupRouter's body and returns the route name each+// r.Handle call passes to its wrapper. That name — not the mux pattern — is what+// RouteContext stamps and what the policy matches as input.route, so it is the+// only one of the two worth comparing against a policy.+func registeredRoutes(t *testing.T) []registeredRoute {+ t.Helper()++ fileSet := token.NewFileSet()+ file, err := parser.ParseFile(fileSet, "main.go", nil, parser.ParseComments)+ if err != nil {+ t.Fatalf("parse main.go: %v", err)+ }++ var setupRouterDecl *ast.FuncDecl+ for _, decl := range file.Decls {+ if function, ok := decl.(*ast.FuncDecl); ok && function.Name.Name == "setupRouter" && function.Recv == nil {+ setupRouterDecl = function+ break+ }+ }+ if setupRouterDecl == nil {+ t.Fatal("main.go has no setupRouter function; this test reads the route table out of its body")+ }++ var routes []registeredRoute+ ast.Inspect(setupRouterDecl.Body, func(n ast.Node) bool {+ call, ok := n.(*ast.CallExpr)+ if !ok {+ return true+ }+ selector, ok := call.Fun.(*ast.SelectorExpr)+ if !ok || selector.Sel.Name != "Handle" {+ return true+ }+ if receiver, ok := selector.X.(*ast.Ident); !ok || receiver.Name != "r" {+ return true+ }+ if len(call.Args) != 2 {+ t.Errorf("r.Handle at %s takes %d arguments; expected a pattern and a handler",+ fileSet.Position(call.Pos()), len(call.Args))+ return true+ }+ wrapper, ok := call.Args[1].(*ast.CallExpr)+ if !ok {+ t.Errorf("r.Handle at %s does not wrap its handler in a known chain; every route must go through one of %v",+ fileSet.Position(call.Pos()), sortedWrapperNames())+ return true+ }+ name, ok := wrapper.Fun.(*ast.Ident)+ if !ok {+ t.Errorf("r.Handle at %s wraps its handler in a non-identifier call; every route must go through one of %v",+ fileSet.Position(call.Pos()), sortedWrapperNames())+ return true+ }+ authenticated, known := routeWrappers[name.Name]+ if !known {+ t.Errorf(`r.Handle at %s wraps its handler in %s, which routeWrappers does not know about.+Add it to routeWrappers with whether it installs the authorization stage. A new+chain that skips the policy must not be able to reach production by being+unrecognised here.`, fileSet.Position(call.Pos()), name.Name)+ return true+ }+ if len(wrapper.Args) == 0 {+ t.Errorf("%s at %s takes no route name", name.Name, fileSet.Position(wrapper.Pos()))+ return true+ }+ literal, ok := wrapper.Args[0].(*ast.BasicLit)+ if !ok || literal.Kind != token.STRING {+ t.Errorf("%s at %s is given a non-literal route name; the route table can only be read from literals",+ name.Name, fileSet.Position(wrapper.Pos()))+ return true+ }+ route, err := strconv.Unquote(literal.Value)+ if err != nil {+ t.Errorf("unquote route name %s at %s: %v", literal.Value, fileSet.Position(literal.Pos()), err)+ return true+ }+ routes = append(routes, registeredRoute{route: route, wrapper: name.Name, authenticated: authenticated})+ return true+ })++ if len(routes) == 0 {+ t.Fatal("read no routes out of setupRouter; the AST shape this test relies on has changed")+ }+ return routes+}++func sortedWrapperNames() []string {+ names := make([]string, 0, len(routeWrappers))+ for name := range routeWrappers {+ names = append(names, name)+ }+ slices.Sort(names)+ return names+}++// policyRouteSet is what the Rego reasons about: the route names it compares+// against, the prefixes it matches, and the routes a prefix rule excludes.+//+// Exclusions are collected module-wide rather than per rule, so the model reads+// `startswith(input.route, "/api/billing/")` and `input.route !=+// "/api/billing/webhook"` as "the billing prefix minus the webhook" even though+// nothing here checks the two share a rule body. That is exact for the one+// prefix rule that exists, and it errs towards reporting a route as uncovered —+// the safe direction, since a false "uncovered" is a failing test and a false+// "covered" is an unguarded endpoint.+type policyRouteSet struct {+ literals map[string][]string+ prefixes map[string][]string+ excluded map[string][]string+}++func (set policyRouteSet) covers(route string) bool {+ if _, ok := set.excluded[route]; ok {+ return false+ }+ if _, ok := set.literals[route]; ok {+ return true+ }+ for prefix := range set.prefixes {+ if strings.HasPrefix(route, prefix) {+ return true+ }+ }+ return false+}++var inputRouteRef = regoast.MustParseRef("input.route")++// policyRoutes parses every non-test Rego module in auth/ and extracts the ways+// each one constrains input.route. Reading the directory rather than a list of+// filenames means a surface module added without being named here is still+// covered.+func policyRoutes(t *testing.T) policyRouteSet {+ t.Helper()++ paths, err := filepath.Glob(filepath.Join("auth", "*.rego"))+ if err != nil {+ t.Fatalf("glob auth/*.rego: %v", err)+ }+ set := policyRouteSet{+ literals: map[string][]string{},+ prefixes: map[string][]string{},+ excluded: map[string][]string{},+ }+ modules := 0+ for _, path := range paths {+ if strings.HasSuffix(path, "_test.rego") {+ continue+ }+ modules+++ module, err := regoast.ParseModule(path, readFileForTest(t, path))+ if err != nil {+ t.Fatalf("parse %s: %v", path, err)+ }+ collectRouteConstraints(t, path, module, set)+ }+ if modules == 0 {+ t.Fatal("found no Rego modules under auth/")+ }+ return set+}++func collectRouteConstraints(t *testing.T, path string, module *regoast.Module, set policyRouteSet) {+ t.Helper()++ regoast.WalkExprs(module, func(expr *regoast.Expr) bool {+ if !mentionsRoute(expr) {+ return false+ }+ operator, operands := callParts(expr)+ literal, matched := "", false+ if len(operands) == 2 {+ switch operator {+ case "equal", "eq", "neq":+ if operands[0].Value.Compare(inputRouteRef) == 0 {+ literal, matched = stringValue(operands[1])+ }+ case "startswith":+ if operands[0].Value.Compare(inputRouteRef) == 0 {+ literal, matched = stringValue(operands[1])+ }+ }+ }+ if !matched {+ t.Errorf(`%s constrains input.route in a form this test cannot read: %v+Recognised forms are input.route == "x", input.route != "x", and+startswith(input.route, "p"). Teach this test the new form, or the route+correspondence it checks silently stops covering that rule.`, path, expr)+ return false+ }+ if expr.Negated {+ t.Errorf(`%s negates a route constraint (%v). The coverage model here is a+plain union of literals and prefixes and cannot represent that.`, path, expr)+ return false+ }+ switch operator {+ case "equal", "eq":+ set.literals[literal] = appendOnce(set.literals[literal], path)+ case "neq":+ set.excluded[literal] = appendOnce(set.excluded[literal], path)+ case "startswith":+ set.prefixes[literal] = appendOnce(set.prefixes[literal], path)+ }+ return false+ })+}++func mentionsRoute(expr *regoast.Expr) bool {+ found := false+ regoast.WalkRefs(expr, func(ref regoast.Ref) bool {+ if ref.Compare(inputRouteRef) == 0 {+ found = true+ }+ return found+ })+ return found+}++func callParts(expr *regoast.Expr) (string, []*regoast.Term) {+ terms, ok := expr.Terms.([]*regoast.Term)+ if !ok || len(terms) == 0 {+ return "", nil+ }+ ref, ok := terms[0].Value.(regoast.Ref)+ if !ok {+ return "", nil+ }+ return strings.TrimPrefix(ref.String(), "internal."), terms[1:]+}++func stringValue(term *regoast.Term) (string, bool) {+ value, ok := term.Value.(regoast.String)+ if !ok {+ return "", false+ }+ return string(value), true+}++func appendOnce(existing []string, value string) []string {+ if slices.Contains(existing, value) {+ return existing+ }+ return append(existing, value)+}++func readFileForTest(t *testing.T, path string) string {+ t.Helper()+ contents, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ return string(contents)+}++// TestRegisteredRoutesHaveAnAuthorizationSurface checks setupRouter against the+// route → surface table every authenticated route is dispatched through. A route+// registered but unbound cannot start (RouteMiddleware panics), so this direction+// mostly reports the failure earlier and by name; a surface bound to a route+// nobody registers is the direction with no runtime symptom at all.+func TestRegisteredRoutesHaveAnAuthorizationSurface(t *testing.T) {+ registered := registeredRoutes(t)++ fromRouter := map[string]bool{}+ for _, route := range registered {+ if route.authenticated {+ fromRouter[route.route] = true+ }+ }++ fromTable := map[string]bool{}+ for _, route := range auth.AuthenticatedRoutes() {+ fromTable[route] = true+ }++ for route := range fromRouter {+ if !fromTable[route] {+ t.Errorf("setupRouter registers %q behind the authorization stage, but routeSurfaces in auth/policy_routes.go does not bind it to a surface", route)+ }+ }+ for route := range fromTable {+ if !fromRouter[route] {+ t.Errorf("routeSurfaces binds %q to a surface, but setupRouter registers no such route; delete the binding or restore the route", route)+ }+ }++ for _, route := range registered {+ if route.authenticated {+ continue+ }+ if fromTable[route.route] {+ t.Errorf("%q is registered through %s, which installs no authorization stage, yet routeSurfaces binds it to a surface", route.route, route.wrapper)+ }+ }+}++// TestPolicyAndRouterAgreeOnRoutes is the check that would have caught #6702.+// The gateway route left main.go and its allow rules stayed; nothing compared+// the two, so the rules read as protection for a surface that no longer existed.+func TestPolicyAndRouterAgreeOnRoutes(t *testing.T) {+ registered := registeredRoutes(t)+ policy := policyRoutes(t)++ authenticated := map[string]bool{}+ all := map[string]bool{}+ for _, route := range registered {+ all[route.route] = true+ if route.authenticated {+ authenticated[route.route] = true+ }+ }++ t.Run("every authenticated route is reasoned about", func(t *testing.T) {+ for route := range authenticated {+ if !policy.covers(route) {+ t.Errorf(`%q runs the authorization stage, but no Rego rule constrains+input.route to it. Its policy can only allow it by accident or deny it always.`, route)+ }+ }+ })++ t.Run("every route the policy names is registered", func(t *testing.T) {+ for literal, sources := range policy.literals {+ if !authenticated[literal] {+ t.Errorf(`%v compares input.route against %q, which setupRouter does not+register behind the authorization stage. This is dead authorization code: it+reads as protection for a surface that does not exist.`, sources, literal)+ }+ }+ })++ t.Run("every prefix the policy matches covers a registered route", func(t *testing.T) {+ for prefix, sources := range policy.prefixes {+ covered := 0+ for route := range authenticated {+ if strings.HasPrefix(route, prefix) {+ covered+++ }+ }+ if covered == 0 {+ t.Errorf("%v matches input.route against the prefix %q, which no registered authenticated route starts with", sources, prefix)+ }+ }+ })++ t.Run("every route the policy excludes is registered", func(t *testing.T) {+ for literal, sources := range policy.excluded {+ if !all[literal] {+ t.Errorf(`%v excludes %q from a prefix rule, but setupRouter registers no+such route. A stale exclusion is a hole waiting for a route to be added back+under the same name.`, sources, literal)+ }+ }+ })++ t.Run("no unauthenticated route is covered", func(t *testing.T) {+ for _, route := range registered {+ if route.authenticated {+ continue+ }+ if policy.covers(route.route) {+ t.Errorf(`%q is registered through %s, which installs no authorization+stage, yet the policy reasons about it. Either the route needs the stage or the+rule is describing a boundary it does not enforce.`, route.route, route.wrapper)+ }+ }+ })+}++// TestEveryPolicySurfaceOwnsARoute catches a surface that survives the routes it+// was written for. A surface nobody dispatches to is a compiled plan no request+// can reach, and it looks exactly like one that is load-bearing.+func TestEveryPolicySurfaceOwnsARoute(t *testing.T) {+ owned := map[string]int{}+ for _, name := range auth.SurfaceNames() {+ owned[name] = 0+ }+ for _, route := range auth.AuthenticatedRoutes() {+ name, ok := auth.RouteSurface(route)+ if !ok {+ t.Fatalf("AuthenticatedRoutes returned %q, which RouteSurface does not resolve", route)+ }+ if _, known := owned[name]; !known {+ t.Errorf("route %q names surface %q, which SurfaceNames does not list", route, name)+ continue+ }+ owned[name]+++ }+ for name, count := range owned {+ if count == 0 {+ t.Errorf("surface %q owns no route; delete it or bind the routes it was written for", name)+ }+ }+}diff --git a/libs/fleet/js-sdk/src/generated/cyclops-cs-backend.ts b/libs/fleet/js-sdk/src/generated/cyclops-cs-backend.tsindex 310eb7a731..db3d838f2d 100644--- a/libs/fleet/js-sdk/src/generated/cyclops-cs-backend.ts+++ b/libs/fleet/js-sdk/src/generated/cyclops-cs-backend.ts@@ -708,7 +708,7 @@ export class Api<};k8S = {/**- * @description Forwards requests to http://127.0.0.1:8001 (the kubectl-proxy sidecar) so the SPA can read K8s resources via the pod ServiceAccount. SPA-only; OPA-gated. EventList responses are filtered by the caller's OPA visible_events policy via auth.K8sEventFilterMiddleware (mounted in main.go's route chain).+ * @description Forwards requests to http://127.0.0.1:8001 (the kubectl-proxy sidecar) so the caller can read K8s resources via the pod ServiceAccount. SPA-only; OPA-gated. The policy is an allowlist: only enumerated group/version/resource/method combinations are proxied (the osgym.cua.ai and cua.ai fleet CRDs, namespaced pod/service reads, pod logs and metrics, KubeVirt reads, and API discovery). Anything else, including Kubernetes events and any cluster-scoped path, is denied and never reaches the sidecar.** @tags passthrough* @name GetK8S