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
Project import generated by Copybara.
Copybara Synccf313294f56f
diff --git a/libs/fleet/.dockerignore b/libs/fleet/.dockerignorenew file mode 100644index 0000000000..9766ae2e7a--- /dev/null+++ b/libs/fleet/.dockerignore@@ -0,0 +1,6 @@+node_modules+dist+.git+*.log+README.md+# copybara mirror e2e verified 2026-07-15 (libs/fleet layout)diff --git a/libs/fleet/.nvmrc b/libs/fleet/.nvmrcnew file mode 100644index 0000000000..67e145bf0f--- /dev/null+++ b/libs/fleet/.nvmrc@@ -0,0 +1 @@+v20.18.0diff --git a/libs/fleet/Dockerfile b/libs/fleet/Dockerfilenew file mode 100644index 0000000000..12742bfb22--- /dev/null+++ b/libs/fleet/Dockerfile@@ -0,0 +1,43 @@+# Build stage — produces /app/dist (Vite output).+FROM node:20-alpine AS builder+WORKDIR /app++# pnpm via corepack (matches the repo's pnpm-based workflow).+RUN corepack enable && corepack prepare [email protected] --activate++# Install deps first (better layer caching). patches/ must be present before+# install so pnpm can apply pnpm.patchedDependencies (e.g. the @novnc BGR fix).+COPY package.json pnpm-lock.yaml ./+COPY patches ./patches+RUN pnpm install --frozen-lockfile --ignore-workspace++# Build.+COPY . .+RUN pnpm build++# Runtime stage — nginx serves static files and proxies /api to cyclops-ctrl.+FROM nginx:1.27-alpine AS runtime++# In-cluster DNS for the cyclops-ctrl Service. Override at deploy-time+# with the CYCLOPS_CTRL env var if cyclops-cs runs outside the cyclops+# namespace or against a different controller.+ENV CYCLOPS_CTRL=http://cyclops-ctrl.cyclops:8080++# In-cluster DNS for the cyclops-cs-backend Service (sibling Deployment+# in the same namespace). Override if the backend is reached at a+# different hostname.+#+# Use the short Service name, NOT the FQDN. nginx:alpine uses musl;+# with ndots:5 the 4-dot FQDN can't be resolved at config-parse time+# and nginx crashloops with "host not found in upstream". The short+# name resolves through the search list at runtime.+ENV CYCLOPS_CS_BACKEND=http://cyclops-cs-backend:8080++# Default Keycloak runtime config for the SPA. Overridden via the+# CYCLOPS_CS_CONFIG_JSON env var (JSON object as a string) at deploy+# time — nginx envsubst inlines it into /config.js, which the SPA+# loads before the React bundle (window.__CYCLOPS_CS_CFG__).+ENV CYCLOPS_CS_CONFIG_JSON='{"kcUrl":"https://auth.cua.ai","kcRealm":"cyclops-cs","kcClientId":"cyclops-cs-spa"}'++COPY nginx.conf /etc/nginx/templates/default.conf.template+COPY --from=builder /app/dist /usr/share/nginx/htmldiff --git a/libs/fleet/backend/Dockerfile b/libs/fleet/backend/Dockerfilenew file mode 100644index 0000000000..3325a0f732--- /dev/null+++ b/libs/fleet/backend/Dockerfile@@ -0,0 +1,29 @@+# Cyclops-CS backend — Go sidecar exposed inside the cyclops-cs Pod via+# nginx (cyclops-cs/nginx.conf routes /api/{keys,gateway} to 127.0.0.1:8080).+#+# Build context is the repo root so the pkg/featureflags module (referenced+# by cyclops-cs/backend/go.mod via a local `replace`) is reachable. The+# build-cyclops-cs.yml workflow sets the context to `.` for this image.+FROM --platform=linux/amd64 golang:1.24-alpine AS builder+WORKDIR /src+COPY pkg/featureflags ./pkg/featureflags+COPY cyclops-cs/backend ./cyclops-cs/backend+WORKDIR /src/cyclops-cs/backend+RUN go mod download+# Ensure go.mod/go.sum are tidy (catches manual edits without `go mod tidy`).+RUN go mod tidy+# Regenerate docs/ in CI so the embedded swagger spec stays in sync with+# annotated source. swag is installed via `go install` rather than added+# as a runtime dep — we only need its CLI here.+RUN go install github.com/swaggo/swag/cmd/[email protected] && \+ /go/bin/swag init -g main.go -o ./docs --parseDependency --parseInternal+RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/cyclops-cs-backend .++# Distroless static — Rego policy is embedded into the binary via+# //go:embed in auth/middlewares.go, so no extra file is shipped here.+FROM gcr.io/distroless/static:nonroot AS runtime+WORKDIR /app+COPY --from=builder /out/cyclops-cs-backend /app/cyclops-cs-backend+USER nonroot:nonroot+EXPOSE 8080+ENTRYPOINT ["/app/cyclops-cs-backend"]diff --git a/libs/fleet/backend/auth/auth.go b/libs/fleet/backend/auth/auth.gonew file mode 100644index 0000000000..b477cb0ba7--- /dev/null+++ b/libs/fleet/backend/auth/auth.go@@ -0,0 +1,131 @@+// Package auth — Keycloak JWT validation, adapted from r33drichards/grt.+//+// Differences from upstream:+// - Issuer-based validation (`iss` must match the configured realm)+// replaces grt's `aud`/scope checks — Keycloak service-account tokens+// don't carry a useful `aud`, but `iss` + signature are sufficient+// given we control the realm.+// - OPA (Rego) is used for all route-level authorization via+// OpaMiddleware; see auth/authz.rego. The gateway surface additionally+// enforces that the token's `namespace` claim equals "pool-{name}"+// (CUA-527), preventing a compromised key from reaching any pool other+// than its own.+// - Two flavors of token use: SPA (azp must equal the SPA client) and+// Gateway (azp must be a per-key client; namespace claim mandatory).+package auth++import (+ "context"+ "fmt"+ "log"+ "log/slog"+ "net/http"+ "strings"+ "time"++ "cyclops-cs-backend/config"++ keyfunc "github.com/MicahParks/keyfunc/v2"+ jwt "github.com/golang-jwt/jwt/v5"+)++var (+ authConfig *config.AuthConfiguration+ cachedJWKS *keyfunc.JWKS+)++// Init mirrors grt's auth.Init — fetch JWKS once, keep refreshing.+func Init(c *config.AuthConfiguration) error {+ authConfig = c+ jwks, err := keyfunc.Get(c.JWKSUri, keyfunc.Options{+ RequestFactory: func(ctx context.Context, url string) (*http.Request, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)+ if err != nil {+ return nil, err+ }+ return req, nil+ },+ Client: &http.Client{Timeout: 15 * time.Second},+ RefreshInterval: time.Hour,+ RefreshTimeout: 10 * time.Second,+ RefreshUnknownKID: true,+ RefreshErrorHandler: func(err error) {+ slog.Error("JWKS refresh", "error", err.Error())+ },+ })+ if err != nil {+ return fmt.Errorf("fetch JWKS at %s: %w", c.JWKSUri, err)+ }+ cachedJWKS = jwks+ return nil+}++// MustInit panics on Init failure — for use inside main().+func MustInit(c *config.AuthConfiguration) {+ if err := Init(c); err != nil {+ log.Fatalf("auth init: %v", err)+ }+}++func extractToken(r *http.Request) (string, error) {+ h := r.Header.Get("Authorization")+ parts := strings.SplitN(h, " ", 2)+ if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") || parts[1] == "" {+ return "", fmt.Errorf("missing or malformed Authorization header")+ }+ return parts[1], nil+}++func sliceContains[K comparable](s []K, e K) bool {+ for _, a := range s {+ if a == e {+ return true+ }+ }+ return false+}++// validate parses + verifies the token signature, expiry, issuer, and+// signing algorithm. It does NOT enforce `azp` / `namespace` — those are+// up to the calling middleware.+func validate(raw string) (*User, error) {+ tok, err := jwt.Parse(raw, cachedJWKS.Keyfunc,+ jwt.WithLeeway(30*time.Second),+ jwt.WithIssuer(authConfig.Issuer),+ jwt.WithValidMethods(authConfig.SigningAlgs),+ )+ if err != nil {+ return nil, err+ }+ if !tok.Valid {+ return nil, fmt.Errorf("invalid token")+ }+ if !sliceContains(authConfig.SigningAlgs, tok.Method.Alg()) {+ return nil, fmt.Errorf("disallowed signing alg %q", tok.Method.Alg())+ }+ claims, ok := tok.Claims.(jwt.MapClaims)+ if !ok {+ return nil, fmt.Errorf("unexpected claims type")+ }+ return &User{+ ID: str(claims, "sub"),+ Name: str(claims, "name"),+ Email: str(claims, "email"),+ AZP: str(claims, "azp"),+ Namespace: str(claims, "namespace"),+ Claims: map[string]string{+ "preferred_username": str(claims, "preferred_username"),+ "user_sub": str(claims, "user_sub"),+ "user_groups": str(claims, "user_groups"),+ },+ }, nil+}++func str(c jwt.MapClaims, k string) string {+ if v, ok := c[k]; ok {+ if s, ok := v.(string); ok {+ return s+ }+ }+ return ""+}diff --git a/libs/fleet/backend/auth/authz.rego b/libs/fleet/backend/auth/authz.regonew file mode 100644index 0000000000..42f61f46ce--- /dev/null+++ b/libs/fleet/backend/auth/authz.rego@@ -0,0 +1,356 @@+# Cyclops-CS authorization policy.+#+# Surfaces, distinguished by `input.route`:+#+# /api/keys, /api/k8s, /api/orch — SPA surfaces. Require a token+# issued to the cyclops-cs-spa client+# (azp == "cyclops-cs-spa") and a non-empty+# subject. Anyone signed into the cyclops-cs realm+# may use them.+#+# /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.+#+# /api/gateway/{name} — orchestrator proxy. Requires a token issued to+# a per-key client (azp starts with "key-") with:+# • a non-empty `namespace` claim+# • `namespace` == "{name}" (the token's+# hardcoded-claim mapper must name the exact pool+# the client belongs to, so one compromised key+# cannot reach another pool)+# Per-pool orchestrators no longer have a direct+# Tailscale Ingress — all traffic MUST flow through+# this proxy (CUA-527).+#+# Data-visibility filtering (which events/env-vars the caller may see) lives+# in filters.rego, not here. authz.rego decides allow/deny only.+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`.+is_admin {+ input.flags.admin_subs[_] == input.user.sub+}++# ── Route allow rules ───────────────────────────────────────────────────────++# /api/keys (POST/GET) and /api/keys/{id} (DELETE).+allow {+ input.route == "/api/keys"+ input.user.sub != ""+ input.user.azp == "cyclops-cs-spa"+}++allow {+ input.route == "/api/keys/{id}"+ input.user.sub != ""+ input.user.azp == "cyclops-cs-spa"+}++# /api/config — per-user feature flags. SPA-only.+allow {+ input.route == "/api/config"+ input.user.sub != ""+ input.user.azp == "cyclops-cs-spa"+}++# /api/namespaces — namespace management (list, create, delete).+# SPA-only; any authenticated user 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 != ""+ input.user.azp == "cyclops-cs-spa"+}++allow {+ input.route == "/api/namespaces/{name}"+ input.user.sub != ""+ input.user.azp == "cyclops-cs-spa"+}++# /api/pool-templates — per-user saved pool configs (list, create, get,+# delete). SPA-only; the backend scopes every operation to the caller's+# sub, so a user can only ever read or mutate their own templates.+allow {+ input.route == "/api/pool-templates"+ input.user.sub != ""+ input.user.azp == "cyclops-cs-spa"+}++allow {+ input.route == "/api/pool-templates/{name}"+ input.user.sub != ""+ input.user.azp == "cyclops-cs-spa"+}++# /api/k8s/{path...} — kubectl-proxy passthrough.+#+# Any SPA user 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 != ""+ input.user.azp == "cyclops-cs-spa"+ not is_infra_k8s_path(input.params.path)+}++allow {+ input.route == "/api/k8s/{path...}"+ input.user.sub != ""+ input.user.azp == "cyclops-cs-spa"+ is_admin+}++# 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/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) {+ parts := split(path, "/")+ count(parts) >= 4+ parts[0] == "apis"+ parts[1] == "capsule.clastix.io"+ parts[2] != ""+ parts[3] == "tenants"+}++# /api/orch/{namespace}/{service}/{path...} — per-namespace orchestrator+# catalog read. SPA-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 != ""+ input.user.azp == "cyclops-cs-spa"+ 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 != ""+ input.user.azp == "cyclops-cs-spa"+ 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/gateway/{name}[/{path...}].+#+# The JWT `namespace` claim is set by a hardcoded-claim protocol mapper on+# the per-key Keycloak client. Pool name = namespace name (1:1), so we+# enforce the exact match here: a token for pool "foo" carries+# namespace="foo" and may only reach /api/gateway/foo/…+allow {+ is_gateway_route+ is_per_key_client+ valid_dns_label(input.params.name)+ input.user.namespace != ""+ input.user.namespace == input.params.name+}++is_gateway_route { input.route == "/api/gateway/{name}" }+is_gateway_route { input.route == "/api/gateway/{name}/{path...}" }++# /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 != ""+ input.user.azp == "cyclops-cs-spa"+}++allow {+ input.route == "/api/user-keys/{id}"+ input.user.sub != ""+ input.user.azp == "cyclops-cs-spa"+}++# ── 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-") }++# 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+}++# Pool templates — user API keys manage their owner's templates, same as+# SPA users (the backend scopes every call to the resolved sub).+allow {+ input.route == "/api/pool-templates"+ input.user.sub != ""+ is_user_key_client+}++allow {+ input.route == "/api/pool-templates/{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)+}++# 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+}++# 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)+}diff --git a/libs/fleet/backend/auth/authz_test.rego b/libs/fleet/backend/auth/authz_test.regonew file mode 100644index 0000000000..fa752d9421--- /dev/null+++ b/libs/fleet/backend/auth/authz_test.rego@@ -0,0 +1,990 @@+package authz_test++import rego.v1++import 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_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/gateway ──────────────────────────────────────────────────────────────+#+# Policy (CUA-527): token's `namespace` claim MUST equal the pool name.+# A per-key client holds exactly one pool; namespace is set by the Keycloak+# hardcoded-claim mapper.++test_gateway_exact_namespace_allowed if {+ authz.allow with input as {+ "route": "/api/gateway/{name}",+ "method": "GET",+ "path": "/api/gateway/mypool",+ "params": {"name": "mypool"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},+ }+}++test_gateway_path_exact_namespace_allowed if {+ authz.allow with input as {+ "route": "/api/gateway/{name}/{path...}",+ "method": "GET",+ "path": "/api/gateway/mypool/step",+ "params": {"name": "mypool", "path": "step"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},+ }+}++# Wrong namespace — must be rejected (cross-pool attack).+test_gateway_wrong_namespace_denied if {+ not authz.allow with input as {+ "route": "/api/gateway/{name}",+ "method": "GET",+ "path": "/api/gateway/mypool",+ "params": {"name": "mypool"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "otherpool", "email": ""},+ }+}++# Namespace matches pool name — allowed (1:1 mapping).+test_gateway_matching_name_namespace_allowed if {+ authz.allow with input as {+ "route": "/api/gateway/{name}",+ "method": "GET",+ "path": "/api/gateway/mypool",+ "params": {"name": "mypool"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "mypool", "email": ""},+ }+}++# Empty namespace — denied.+test_gateway_empty_namespace_denied if {+ not authz.allow with input as {+ "route": "/api/gateway/{name}",+ "method": "GET",+ "path": "/api/gateway/mypool",+ "params": {"name": "mypool"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "", "email": ""},+ }+}++# SPA token on gateway route — denied (must use per-key client).+test_gateway_spa_token_denied if {+ not authz.allow with input as {+ "route": "/api/gateway/{name}",+ "method": "GET",+ "path": "/api/gateway/mypool",+ "params": {"name": "mypool"},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "mypool", "email": "[email protected]"},+ }+}++# Invalid pool name (contains uppercase) — denied by DNS-label check.+test_gateway_invalid_pool_name_denied if {+ not authz.allow with input as {+ "route": "/api/gateway/{name}",+ "method": "GET",+ "path": "/api/gateway/MyPool",+ "params": {"name": "MyPool"},+ "user": {"sub": "svc-123", "azp": "key-mypool", "namespace": "MyPool", "email": ""},+ }+}++# ── /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]"},+ }+}++# ── /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]"},+ }+}++# ── /api/batch and /api/label ────────────────────────────────────────────────+#+# Pool is in the URL path. A per-key token's `namespace` claim MUST equal+# the pool name, mirroring /api/gateway/{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"},+ "flags": {"admin_subs": ["admin-1", "admin-2"]},+ }+}++test_is_admin_false_not_listed if {+ not authz.is_admin with input as {+ "user": {"sub": "nobody"},+ "flags": {"admin_subs": ["admin-1"]},+ }+}++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/pool-templates — per-user saved pool configs ───────────────────────++test_pool_templates_spa_list_allowed if {+ authz.allow with input as {+ "route": "/api/pool-templates",+ "method": "GET",+ "path": "/api/pool-templates",+ "params": {},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_pool_templates_spa_create_allowed if {+ authz.allow with input as {+ "route": "/api/pool-templates",+ "method": "POST",+ "path": "/api/pool-templates",+ "params": {},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_pool_templates_spa_get_allowed if {+ authz.allow with input as {+ "route": "/api/pool-templates/{name}",+ "method": "GET",+ "path": "/api/pool-templates/gpu-large",+ "params": {"name": "gpu-large"},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++test_pool_templates_spa_delete_allowed if {+ authz.allow with input as {+ "route": "/api/pool-templates/{name}",+ "method": "DELETE",+ "path": "/api/pool-templates/gpu-large",+ "params": {"name": "gpu-large"},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++# Per-key clients (key-*) CANNOT touch pool templates — those tokens are+# bound to a single pool, not a user identity.+test_pool_templates_per_key_denied if {+ not authz.allow with input as {+ "route": "/api/pool-templates",+ "method": "GET",+ "path": "/api/pool-templates",+ "params": {},+ "user": {"sub": "svc-123", "azp": "key-foo", "namespace": "foo", "email": ""},+ }+}++# User API keys (ukey-*) act on behalf of a user and may manage templates.+test_pool_templates_user_key_list_allowed if {+ authz.allow with input as {+ "route": "/api/pool-templates",+ "method": "GET",+ "path": "/api/pool-templates",+ "params": {},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ }+}++test_pool_templates_user_key_delete_allowed if {+ authz.allow with input as {+ "route": "/api/pool-templates/{name}",+ "method": "DELETE",+ "path": "/api/pool-templates/gpu-large",+ "params": {"name": "gpu-large"},+ "user": {"sub": "user-123", "azp": "ukey-test123abc", "namespace": "", "email": ""},+ }+}++# Empty sub denied on pool-template routes.+test_pool_templates_empty_sub_denied if {+ not authz.allow with input as {+ "route": "/api/pool-templates",+ "method": "GET",+ "path": "/api/pool-templates",+ "params": {},+ "user": {"sub": "", "azp": "cyclops-cs-spa", "namespace": "", "email": "[email protected]"},+ }+}++# Missing azp denied on pool-template routes.+test_pool_templates_missing_azp_denied if {+ not authz.allow with input as {+ "route": "/api/pool-templates",+ "method": "GET",+ "path": "/api/pool-templates",+ "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_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": ""},+ }+}++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": ""},+ }+}++# 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": ""},+ }+}diff --git a/libs/fleet/backend/auth/event_filter.go b/libs/fleet/backend/auth/event_filter.gonew file mode 100644index 0000000000..8f2760d3be--- /dev/null+++ b/libs/fleet/backend/auth/event_filter.go@@ -0,0 +1,157 @@+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.gonew file mode 100644index 0000000000..74e6efe5d0--- /dev/null+++ b/libs/fleet/backend/auth/event_filter_test.go@@ -0,0 +1,161 @@+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/filters.rego b/libs/fleet/backend/auth/filters.regonew file mode 100644index 0000000000..949657c565--- /dev/null+++ b/libs/fleet/backend/auth/filters.rego@@ -0,0 +1,46 @@+# 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.regonew file mode 100644index 0000000000..a1965ecadf--- /dev/null+++ b/libs/fleet/backend/auth/filters_test.rego@@ -0,0 +1,46 @@+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.gonew file mode 100644index 0000000000..78dfe38368--- /dev/null+++ b/libs/fleet/backend/auth/flags_test.go@@ -0,0 +1,118 @@+package auth++import (+ "context"+ "testing"+ "time"++ "github.com/trycua/cloud/pkg/featureflags"+)++// resetFlagsCache clears the TTL cache so the next flagsData() re-resolves+// from the (test-controlled) provider/env.+func resetFlagsCache() {+ flagsMu.Lock()+ flagsValue = nil+ flagsExp = time.Time{}+ flagsMu.Unlock()+}++// 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+// 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)+ }+ LoadOpa()+ resetFlagsCache() // force a fresh resolve now that env is set++ ctx := context.Background()++ t.Run("EvalIsAdmin", func(t *testing.T) {+ ok, err := EvalIsAdmin(ctx, &User{ID: "admin-sub", AZP: "cyclops-cs-spa"})+ if err != nil || !ok {+ t.Fatalf("EvalIsAdmin(admin) = %v, %v; want true, nil", ok, err)+ }+ ok, err = EvalIsAdmin(ctx, &User{ID: "someone-else", AZP: "cyclops-cs-spa"})+ if err != nil || ok {+ t.Fatalf("EvalIsAdmin(non-admin) = %v, %v; want false, nil", ok, err)+ }+ ok, err = EvalIsAdmin(ctx, nil)+ if err != nil || ok {+ t.Fatalf("EvalIsAdmin(nil) = %v, %v; want false, nil", ok, err)+ }+ })++ 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 stable+// value within the window and re-resolves lazily (ad-hoc, no background+// timer) once expired.+func TestFlagsDataCachedAndRefreshes(t *testing.T) {+ t.Setenv("CYCLOPS_CS_ADMIN_SUBS", `["a"]`)+ if err := featureflags.SetupProvider(context.Background(), "development", featureflags.AWSCredentials{}); err != nil {+ t.Fatalf("setup dev provider: %v", err)+ }+ resetFlagsCache()++ first := flagsData()+ if got := asStrings(first["admin_subs"]); len(got) != 1 || got[0] != "a" {+ t.Fatalf("admin_subs = %v, want [a]", got)+ }++ // Within the TTL the cached value is returned even though env changed.+ t.Setenv("CYCLOPS_CS_ADMIN_SUBS", `["a","b"]`)+ if got := asStrings(flagsData()["admin_subs"]); len(got) != 1 {+ t.Fatalf("expected cached value within TTL, got %v", got)+ }++ // After expiry the next call re-resolves and picks up the change.+ flagsMu.Lock()+ flagsExp = time.Now().Add(-time.Second)+ flagsMu.Unlock()+ if got := asStrings(flagsData()["admin_subs"]); len(got) != 2 {+ t.Fatalf("expected refreshed value after expiry, got %v", got)+ }+}++func asStrings(v any) []string {+ items, ok := v.([]interface{})+ if !ok {+ return nil+ }+ out := make([]string, 0, len(items))+ for _, it := range items {+ if s, ok := it.(string); ok {+ out = append(out, s)+ }+ }+ return out+}diff --git a/libs/fleet/backend/auth/middlewares.go b/libs/fleet/backend/auth/middlewares.gonew file mode 100644index 0000000000..2d136842d0--- /dev/null+++ b/libs/fleet/backend/auth/middlewares.go@@ -0,0 +1,460 @@+package auth++import (+ "context"+ _ "embed"+ "encoding/json"+ "log"+ "log/slog"+ "net/http"+ "strings"+ "sync"+ "time"++ "cyclops-cs-backend/middlewares"++ "github.com/open-feature/go-sdk/openfeature"+ "github.com/open-policy-agent/opa/rego"+ "github.com/trycua/cloud/pkg/featureflags"+ "golang.org/x/sync/singleflight"+)++type ctxKey int++const UserKey ctxKey = 1++var opaQuery *rego.PreparedEvalQuery+var opaEventQuery *rego.PreparedEvalQuery+var opaAdminQuery *rego.PreparedEvalQuery+var opaPoolAdmissionQuery *rego.PreparedEvalQuery++//go:embed authz.rego+var authzPolicy string++//go:embed filters.rego+var filtersPolicy string++//go:embed pool_admission.rego+var poolAdmissionPolicy 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+//+// Values are JSON string arrays (e.g. '["sub1","sub2"]').+const flagPrefix = "/feature-flags/cyclops-cs/"++// flagsTTL bounds how long flagsData returns its last computed result+// 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.+const flagsTTL = 1 * time.Minute++var (+ flagsMu sync.Mutex+ flagsValue map[string]interface{}+ flagsExp time.Time++ // flagsSF collapses concurrent refreshes (e.g. a burst of requests+ // arriving right after expiry, or at cold start) into a single+ // compute, so we never fan out N simultaneous SSM round-trips.+ flagsSF singleflight.Group++ // ffClient is the lazily-initialised OpenFeature client used by+ // computeFlagsData. NewClient is cheap, but sync.Once gives us a+ // single shared handle across concurrent first-callers and pins the+ // client name to one place.+ ffClientOnce sync.Once+ 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).+//+// The OpenFeature provider is installed by featureflags.SetupProvider at+// startup (main.go) — aws-ssm in prod, SimpleEnvProvider in dev, with the+// contrib from-env provider as a degraded fallback.+func flagsData() map[string]interface{} {+ flagsMu.Lock()+ if flagsValue != nil && time.Now().Before(flagsExp) {+ cached := flagsValue+ flagsMu.Unlock()+ return cached+ }+ flagsMu.Unlock()++ v, _, _ := flagsSF.Do("flags", func() (interface{}, error) {+ // Re-check under the lock: a concurrent refresh may have just+ // populated the cache while we waited to enter singleflight.+ flagsMu.Lock()+ if flagsValue != nil && time.Now().Before(flagsExp) {+ cached := flagsValue+ flagsMu.Unlock()+ return cached, nil+ }+ flagsMu.Unlock()++ // Resolve with a detached context so a single caller's cancelled+ // request can't abort the refresh shared by everyone else.+ result := computeFlagsData(context.Background())++ flagsMu.Lock()+ flagsValue = result+ flagsExp = time.Now().Add(flagsTTL)+ flagsMu.Unlock()+ return result, nil+ })+ return v.(map[string]interface{})+}++func computeFlagsData(ctx context.Context) map[string]interface{} {+ ffClientOnce.Do(func() {+ ffClient = openfeature.NewClient("cyclops-cs-auth")+ })+ keys, err := featureflags.ListFlagKeys(ctx, flagPrefix)+ if err != nil {+ slog.Warn("auth: flag discovery failed; flags will be empty", "prefix", flagPrefix, "err", err)+ }+ flags := map[string]interface{}{}+ for _, key := range keys {+ name := opaNameFromFlagKey(key)+ if name == "" {+ continue+ }+ flags[name] = loadStringList(ctx, ffClient, key)+ }+ return flags+}++// opaNameFromFlagKey maps a discovered flag path to the Rego identifier+// used by the policy (under input.flags). Nested paths under flagPrefix are+// skipped — the policy only references single-leaf flag names.+//+// /feature-flags/cyclops-cs/admin-subs → admin_subs+func opaNameFromFlagKey(key string) string {+ leaf := strings.TrimPrefix(key, flagPrefix)+ if leaf == "" || strings.Contains(leaf, "/") {+ return ""+ }+ return strings.ReplaceAll(leaf, "-", "_")+}++// loadStringList resolves a JSON-array flag to []interface{} for OPA's+// input.flags document. The value is StringValue with default "[]"; a+// malformed payload yields an empty list and a warn log so OPA still+// evaluates.+//+// A 3s per-call deadline keeps an unreachable Parameter Store from+// stalling pod startup; the from-env fallback kicks in on timeout.+func loadStringList(ctx context.Context, client *openfeature.Client, flagKey string) []interface{} {+ callCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ raw, err := client.StringValue(callCtx, flagKey, "[]", openfeature.EvaluationContext{})+ if err != nil {+ slog.Warn("auth: flag eval failed; using empty list", "flag", flagKey, "err", err)+ return []interface{}{}+ }+ var items []string+ if err := json.Unmarshal([]byte(raw), &items); err != nil {+ slog.Warn("auth: flag value is not a JSON string array; using empty list", "flag", flagKey, "err", err)+ return []interface{}{}+ }+ out := make([]interface{}, len(items))+ for i, v := range items {+ out[i] = v+ }+ return out+}++// LoadOpa prepares the embedded Rego policy and all derived queries.+// Feature flags are NOT baked into an OPA data store here; they are passed+// per-request as input.flags (see flagsData), so prepared queries stay+// 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+ }++ // filter queries need both authz.rego (for data.authz.is_admin) and filters.rego+ prepareFilterQuery := 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)+ }+ 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+ // startup logs rather than on a user's first call.+ _ = 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.+func EvalIsAdmin(ctx context.Context, user *User) (bool, error) {+ if user == nil {+ return false, nil+ }+ input := map[string]interface{}{+ "user": buildUserInput(user),+ "flags": flagsData(),+ }+ res, err := opaAdminQuery.Eval(ctx, rego.EvalInput(input))+ if err != nil {+ return false, err+ }+ if len(res) == 0 || len(res[0].Expressions) == 0 {+ return false, nil+ }+ v, _ := res[0].Expressions[0].Value.(bool)+ return v, nil+}++func writeJSONErr(w http.ResponseWriter, status int, msg string) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _ = json.NewEncoder(w).Encode(map[string]any{"error": msg})+}++// TokenAuthMiddleware validates a Bearer JWT and stores the resulting+// User on the request context. User-key tokens (azp starts with "ukey-")+// are normal JWTs from Keycloak client_credentials grants; they carry+// hardcoded `user_sub` and `user_groups` claims that override the identity+// so the request acts on behalf of the key owner. No `azp` / `namespace`+// enforcement here — that's OPA's job.+func TokenAuthMiddleware(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ start := time.Now()+ result := "valid"+ defer func() {+ slog.Debug("auth", "elapsed", time.Since(start), "result", result,+ "traceId", r.Context().Value(middlewares.ContextKey("traceId")))+ }()++ raw, err := extractToken(r)+ if err != nil {+ // Fallback: oauth2-proxy sets X-Auth-Request-User when the+ // browser has a valid session cookie. nginx auth_request+ // forwards this header after a successful /oauth2/auth check.+ if proxyUser := r.Header.Get("X-Auth-Request-User"); proxyUser != "" {+ proxyEmail := r.Header.Get("X-Auth-Request-Email")+ user := &User{+ ID: proxyUser,+ Email: proxyEmail,+ AZP: "oauth2-proxy", // distinct from SPA/key clients for OPA+ }+ next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), UserKey, user)))+ return+ }+ result = err.Error()+ writeJSONErr(w, http.StatusUnauthorized, "auth token was not provided or is invalid")+ return+ }++ // ── JWT validation ─────────────────────────────────────────+ user, err := validate(raw)+ if err != nil {+ result = err.Error()+ writeJSONErr(w, http.StatusUnauthorized, "auth token is invalid")+ return+ }++ // ── User-key identity override ─────────────────────────────+ // User-key tokens have azp="ukey-..." and carry hardcoded+ // user_sub / user_groups claims from the Keycloak client's+ // protocol mappers. Override the user identity so downstream+ // handlers and OPA see the key owner, not the service account.+ userKeyPfx := "ukey-"+ if authConfig != nil && authConfig.UserKeyClientPfx != "" {+ userKeyPfx = authConfig.UserKeyClientPfx+ }+ if strings.HasPrefix(user.AZP, userKeyPfx) {+ if userSub := user.Claims["user_sub"]; userSub != "" {+ user.ID = userSub+ }+ if userGroups := user.Claims["user_groups"]; userGroups != "" {+ user.Groups = strings.Split(userGroups, ",")+ }+ }++ next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), UserKey, user)))+ })+}++// 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/gateway/{name}") 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{}+ }+ return map[string]any{+ "sub": user.ID,+ "azp": user.AZP,+ "namespace": user.Namespace,+ "email": user.Email,+ "groups": user.Groups,+ }+}++// route / params context plumbing — keeps the Rego policy stable even if+// the URL pattern changes, and lets it reference `input.params.name`+// directly instead of substring-parsing `input.path`.++type routeCtxKey int++const (+ routeKey routeCtxKey = 1+ paramsKey routeCtxKey = 2+)++// 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 {+ return func(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ params := map[string]string{}+ for _, k := range paramKeys {+ params[k] = r.PathValue(k)+ }+ ctx := r.Context()+ ctx = context.WithValue(ctx, routeKey, route)+ ctx = context.WithValue(ctx, paramsKey, params)+ next.ServeHTTP(w, r.WithContext(ctx))+ })+ }+}++// GetUser returns the User stamped on the context by TokenAuthMiddleware.+func GetUser(ctx context.Context) *User {+ if u, ok := ctx.Value(UserKey).(*User); ok {+ return u+ }+ return nil+}diff --git a/libs/fleet/backend/auth/policy_test.go b/libs/fleet/backend/auth/policy_test.gonew file mode 100644index 0000000000..0a7095b71d--- /dev/null+++ b/libs/fleet/backend/auth/policy_test.go@@ -0,0 +1,288 @@+package auth++import (+ "context"+ "net/http"+ "testing"++ "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+// 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.++func prepareQuery(t *testing.T, query string, modules map[string]string) rego.PreparedEvalQuery {+ t.Helper()+ opts := []func(*rego.Rego){rego.Query(query)}+ for name, src := range modules {+ opts = append(opts, rego.Module(name, src))+ }+ pq, err := rego.New(opts...).PrepareForEval(context.Background())+ if err != nil {+ t.Fatalf("prepare %q: %v", query, err)+ }+ return pq+}++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)+ }+ return rs.Allowed()+}++func evalIsAdmin(t *testing.T, input map[string]any) bool {+ 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)+ }+ return rs.Allowed()+}++func evalVisibleEvents(t *testing.T, input map[string]any) []any {+ t.Helper()+ pq := prepareQuery(t, "data.filters.visible_events", map[string]string{+ "authz.rego": authzPolicy,+ "filters.rego": filtersPolicy,+ })+ 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+ }+ return nil+}++func evalPoolAdmission(t *testing.T, input map[string]any) bool {+ t.Helper()+ pq := prepareQuery(t, "data.pool_admission.allow", map[string]string{+ "pool_admission.rego": poolAdmissionPolicy,+ })+ rs, err := pq.Eval(context.Background(), rego.EvalInput(input))+ if err != nil {+ t.Fatalf("eval pool admission: %v", err)+ }+ return rs.Allowed()+}++func TestPoolAdmissionImagePullSecret(t *testing.T) {+ const allowedImage = "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace-duo:latest"+ cases := []struct {+ name string+ method string+ template map[string]any+ want bool+ }{+ {"no pull secret", "POST", map[string]any{"containerDiskImage": "docker.io/library/alpine:3.20"}, true},+ {"non ecr secret", "POST", map[string]any{"containerDiskImage": allowedImage, "imagePullSecret": "other-secret"}, false},+ {"ecr secret allowlisted image", "POST", map[string]any{"containerDiskImage": allowedImage, "imagePullSecret": "ecr-credentials"}, true},+ {"ecr secret disallowed image", "POST", map[string]any{"containerDiskImage": "evil.example/workspace:latest", "imagePullSecret": "ecr-credentials"}, false},+ {"repository prefix collision", "POST", map[string]any{"containerDiskImage": "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace-evil:latest", "imagePullSecret": "ecr-credentials"}, false},+ {"allowlisted digest", "POST", map[string]any{"containerDiskImage": "296062593712.dkr.ecr.us-west-2.amazonaws.com/osgym-workspace@sha256:abc", "imagePullSecret": "ecr-credentials"}, true},+ {"unrelated patch", "PATCH", map[string]any{"cpuCores": 8}, true},+ {"image only patch denied", "PATCH", map[string]any{"containerDiskImage": allowedImage}, false},+ {"secret only patch denied", "PATCH", map[string]any{"imagePullSecret": "ecr-credentials"}, false},+ {"remove secret patch", "PATCH", map[string]any{"imagePullSecret": nil}, true},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ input := map[string]any{+ "method": tc.method,+ "object": map[string]any{"spec": map[string]any{"template": tc.template}},+ }+ if got := evalPoolAdmission(t, input); got != tc.want {+ t.Fatalf("pool admission = %v, want %v", got, tc.want)+ }+ })+ }+}++func spaUser(sub string) map[string]any {+ return map[string]any{"sub": sub, "azp": "cyclops-cs-spa"}+}++// flagsFor returns an input.flags doc whose admin_subs contains sub iff admin.+func flagsFor(admin bool, sub string) map[string]any {+ subs := []any{}+ if admin {+ subs = []any{sub}+ }+ return map[string]any{"admin_subs": subs}+}++func k8sInput(path string, admin bool) map[string]any {+ const sub = "u-1"+ return map[string]any{+ "route": "/api/k8s/{path...}",+ "method": "GET",+ "params": map[string]any{"path": path},+ "user": spaUser(sub),+ "flags": flagsFor(admin, sub),+ }+}++func TestK8sAllow_InfraPathsRequireAdmin(t *testing.T) {+ cases := []struct {+ name string+ path string+ admin bool+ want bool+ }{+ // Infra-only: denied for non-admins, allowed for admins.+ {"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},+ {"Capsule tenants / non-admin", "apis/capsule.clastix.io/v1beta2/tenants", false, 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},++ // Customer-facing: allowed regardless of admin.+ {"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+ // (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},+ {"events list / non-admin (contents filtered elsewhere)", "api/v1/events", false, true},+ {"namespaced events / non-admin", "api/v1/namespaces/pool-foo/events", false, true},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := evalAllow(t, k8sInput(tc.path, tc.admin)); got != tc.want {+ t.Fatalf("allow(path=%q admin=%v) = %v, want %v", tc.path, tc.admin, got, tc.want)+ }+ })+ }+}++func TestK8sAllow_RequiresSpaClient(t *testing.T) {+ // A non-SPA token (e.g. a per-key client) is denied even on an+ // otherwise-open path, and even if its sub were in admin_subs.+ in := k8sInput("api/v1/namespaces/pool-foo/pods", true)+ in["user"] = map[string]any{"sub": "u-1", "azp": "key-pool-foo"}+ if evalAllow(t, in) {+ t.Fatal("expected non-SPA client to be denied on /api/k8s")+ }+}++func TestK8sAllow_UserKeyCannotReachCapsuleTenantLifecycle(t *testing.T) {+ in := k8sInput("apis/capsule.clastix.io/v1beta2/tenants", false)+ in["method"] = http.MethodPost+ in["user"] = map[string]any{"sub": "u-1", "azp": "ukey-u-1"}+ if evalAllow(t, in) {+ t.Fatal("expected user key to be denied on Capsule Tenant lifecycle")+ }+}++func TestIsAdmin(t *testing.T) {+ cases := []struct {+ name string+ flags map[string]any+ sub string+ want bool+ }{+ {"sub in admin_subs", map[string]any{"admin_subs": []any{"a", "b"}}, "b", true},+ {"sub not in admin_subs", map[string]any{"admin_subs": []any{"a", "b"}}, "c", false},+ {"empty admin_subs", map[string]any{"admin_subs": []any{}}, "a", false},+ {"missing flags doc", nil, "a", false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ in := map[string]any{"user": map[string]any{"sub": tc.sub}}+ if tc.flags != nil {+ in["flags"] = tc.flags+ }+ if got := evalIsAdmin(t, in); got != tc.want {+ t.Fatalf("is_admin = %v, want %v", got, tc.want)+ }+ })+ }+}++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,+ }+ if got := len(evalVisibleEvents(t, in)); got != 3 {+ t.Fatalf("admin visible_events = %d, want 3", got)+ }+ })++ 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)+ }+ })++ 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)+ }+ })++ 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)+ }+ })+}diff --git a/libs/fleet/backend/auth/pool_admission.rego b/libs/fleet/backend/auth/pool_admission.regonew file mode 100644index 0000000000..23c8f16ea9--- /dev/null+++ b/libs/fleet/backend/auth/pool_admission.rego@@ -0,0 +1,70 @@+package pool_admission++default allow = false++ecr_pull_secret := "ecr-credentials"++allowed_image_repositories := {+ "296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows",+ "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace",+ "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace-duo",+ "296062593712.dkr.ecr.us-west-2.amazonaws.com/osgym-workspace",+ "296062593712.dkr.ecr.us-west-2.amazonaws.com/osworld-golden-workspace",+ "296062593712.dkr.ecr.us-west-2.amazonaws.com/ubuntu-vnc-cua-kubevirt",+}++template := object.get(object.get(input.object, "spec", {}), "template", {})++has_pull_secret {+ object.get(template, "imagePullSecret", null) != null+}++has_image {+ object.get(template, "containerDiskImage", null) != null+}++allowed_image {+ image := template.containerDiskImage+ repository := allowed_image_repositories[_]+ image == repository+}++allowed_image {+ image := template.containerDiskImage+ repository := allowed_image_repositories[_]+ startswith(image, sprintf("%s:", [repository]))+}++allowed_image {+ image := template.containerDiskImage+ repository := allowed_image_repositories[_]+ startswith(image, sprintf("%s@", [repository]))+}++allow {+ input.method != "PATCH"+ not has_pull_secret+}++allow {+ input.method != "PATCH"+ template.imagePullSecret == ecr_pull_secret+ allowed_image+}++allow {+ input.method == "PATCH"+ not has_pull_secret+ not has_image+}++allow {+ input.method == "PATCH"+ object.get(template, "imagePullSecret", "missing") == null+}++allow {+ input.method == "PATCH"+ template.imagePullSecret == ecr_pull_secret+ allowed_image+}diff --git a/libs/fleet/backend/auth/pool_admission_test.rego b/libs/fleet/backend/auth/pool_admission_test.regonew file mode 100644index 0000000000..a036c0a71e--- /dev/null+++ b/libs/fleet/backend/auth/pool_admission_test.rego@@ -0,0 +1,73 @@+package pool_admission_test++import data.pool_admission++allowed_image := "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace-duo:latest"++test_no_pull_secret_allowed {+ pool_admission.allow with input as {+ "method": "POST",+ "object": {"spec": {"template": {"containerDiskImage": "docker.io/library/alpine:3.20"}}},+ }+}++test_non_ecr_secret_denied {+ not pool_admission.allow with input as {+ "method": "POST",+ "object": {"spec": {"template": {+ "containerDiskImage": allowed_image,+ "imagePullSecret": "other-secret",+ }}},+ }+}++test_ecr_secret_allowlisted_image_allowed {+ pool_admission.allow with input as {+ "method": "POST",+ "object": {"spec": {"template": {+ "containerDiskImage": allowed_image,+ "imagePullSecret": "ecr-credentials",+ }}},+ }+}++test_ecr_secret_disallowed_image_denied {+ not pool_admission.allow with input as {+ "method": "POST",+ "object": {"spec": {"template": {+ "containerDiskImage": "evil.example/workspace:latest",+ "imagePullSecret": "ecr-credentials",+ }}},+ }+}++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",+ }}},+ }+}++test_unrelated_patch_allowed {+ pool_admission.allow with input as {+ "method": "PATCH",+ "object": {"spec": {"services": [{"name": "server", "targetPort": 8000}]}},+ }+}++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"}}},+ }+}diff --git a/libs/fleet/backend/auth/user.go b/libs/fleet/backend/auth/user.gonew file mode 100644index 0000000000..8719c1e3c0--- /dev/null+++ b/libs/fleet/backend/auth/user.go@@ -0,0 +1,15 @@+package auth++// User mirrors r33drichards/grt's auth.User shape — the value placed on+// the request context after a successful TokenAuthMiddleware. Extra+// claim values relevant to cyclops-cs (`namespace`, `azp`) are surfaced+// as struct fields rather than buried in the generic Claims map.+type User struct {+ ID string // sub+ Name string+ Email string+ AZP string // authorized party = client_id of the token issuer+ Namespace string // hardcoded-claim mapper on per-key clients+ Groups []string // groups for K8s impersonation (populated from user_groups claim for ukey- tokens)+ Claims map[string]string+}diff --git a/libs/fleet/backend/config/config.go b/libs/fleet/backend/config/config.gonew file mode 100644index 0000000000..1b77aa14a3--- /dev/null+++ b/libs/fleet/backend/config/config.go@@ -0,0 +1,200 @@+// Package config loads cyclops-cs backend config via Cobra + Viper.+//+// Precedence: command-line flag > environment variable > hardcoded default.+// Existing env var names (KC_BASE_URL, LISTEN_ADDR, ORCH_*, …) are preserved+// so no deployment/Helm change is required. Defaults equal the previous+// hardcoded literals, so behaviour is unchanged unless explicitly overridden.+//+// Cross-service identity prefixes (user-/oidc:) are NOT here — they live in+// OpenFeature/SSM so backend Tenant provisioning and impersonation use the same+// values (see package identity). The key-/ukey- client-id prefixes are+// cyclops-only, so they stay in this local config.+package config++import (+ "fmt"+ "strings"++ "github.com/spf13/pflag"+ "github.com/spf13/viper"+)++type Configuration struct {+ WebServer WebServerConfiguration+ Auth AuthConfiguration+ Keycloak KeycloakConfiguration+ Gateway GatewayConfiguration+ Templates TemplatesConfiguration+ Metrics MetricsConfiguration+ Telemetry TelemetryConfiguration+}++type WebServerConfiguration struct {+ Addr string+}++// AuthConfiguration follows the grt naming so the JWKS / verifier code+// reads like the upstream template.+type AuthConfiguration struct {+ Issuer string // https://auth.cua.ai/realms/cyclops-cs+ JWKSUri string // <Issuer>/protocol/openid-connect/certs+ SigningAlgs []string // RS256, RS512, ES256+ SPAClientID string+ KeyClientPfx string // pool/gateway key client-id prefix ("key-")+ UserKeyClientPfx string // per-user key client-id prefix ("ukey-")+}++type KeycloakConfiguration struct {+ BaseURL string+ Realm string+ AdminClientID string+ AdminClientSecret string+ TokenURL string++ // Workloads realm — the machine-only realm AWS STS (and other OIDC-trust+ // providers) federate against. The backend mints a per-tenant+ // service-account client here so OSGym pool VMs can obtain a+ // tenant-scoped OIDC token. Disabled (no client minted) when+ // WorkloadAdminClientSecret is empty. The admin client lives IN the+ // workloads realm (Keycloak realm-management roles are per-realm, so the+ // cyclops-cs-realm admin can't manage workloads). See+ // docs/decisions/2026-06-25-osgym-pool-workload-oidc.md.+ WorkloadRealm string+ WorkloadAdminClientID string+ WorkloadAdminClientSecret string+ WorkloadTokenURL string+ WorkloadAudience string+}++type GatewayConfiguration struct {+ Scheme string+ Port string+ ClusterDomain string+}++// TemplatesConfiguration drives the per-user pool-template store+// (/api/pool-templates). BATCH_REDIS_URL remains a compatibility fallback.+type TemplatesConfiguration struct {+ RedisURL string // POOL_TEMPLATES_REDIS_URL (falls back to BATCH_REDIS_URL)+}++type MetricsConfiguration struct {+ Addr string // METRICS_ADDR — Prometheus listen addr+}++type TelemetryConfiguration struct {+ Endpoint string // OTEL_EXPORTER_OTLP_ENDPOINT+ Protocol string // OTEL_EXPORTER_OTLP_PROTOCOL+ ServiceName string // OTEL_SERVICE_NAME+ ServiceNamespace string // OTEL_SERVICE_NAMESPACE+ Environment string // OTEL_ENVIRONMENT+ ResourceAttrs string // OTEL_RESOURCE_ATTRIBUTES+}++// flagSpec maps one config value to its viper key, CLI flag, env var, and+// hardcoded default. Keeping them in one table guarantees flag/env/default+// stay in sync.+type flagSpec struct {+ key, flag, env, def, usage string+}++var specs = []flagSpec{+ {"webserver.addr", "listen-addr", "LISTEN_ADDR", "127.0.0.1:8080", "HTTP listen address"},+ {"kc.base-url", "kc-base-url", "KC_BASE_URL", "https://auth.cua.ai", "Keycloak base URL"},+ {"kc.realm", "kc-realm", "KC_REALM", "cyclops-cs", "Keycloak realm"},+ {"kc.issuer", "kc-issuer", "KC_ISSUER", "", "JWT issuer override (defaults to <base>/realms/<realm>)"},+ {"kc.spa-client-id", "kc-spa-client-id", "KC_SPA_CLIENT_ID", "cyclops-cs-spa", "SPA OIDC client id"},+ {"kc.key-client-prefix", "kc-key-client-prefix", "KC_KEY_CLIENT_PFX", "key-", "pool/gateway key client-id prefix"},+ {"kc.user-key-client-prefix", "kc-user-key-client-prefix", "KC_USER_KEY_CLIENT_PFX", "ukey-", "per-user key client-id prefix"},+ {"kc.admin-client-id", "kc-admin-client-id", "KC_ADMIN_CLIENT_ID", "cyclops-cs-backend", "Keycloak admin client id"},+ {"kc.admin-client-secret", "kc-admin-client-secret", "KC_ADMIN_CLIENT_SECRET", "", "Keycloak admin client secret (required)"},+ {"kc.workload-realm", "kc-workload-realm", "KC_WORKLOAD_REALM", "workloads", "Keycloak realm AWS/OIDC trusts for pool VM tokens"},+ {"kc.workload-admin-client-id", "kc-workload-admin-client-id", "KC_WORKLOAD_ADMIN_CLIENT_ID", "workloads-admin", "admin client id IN the workloads realm"},+ {"kc.workload-admin-client-secret", "kc-workload-admin-client-secret", "KC_WORKLOAD_ADMIN_CLIENT_SECRET", "", "admin client secret for the workloads realm (enables per-tenant pool VM OIDC when set)"},+ {"kc.workload-audience", "kc-workload-audience", "KC_WORKLOAD_AUDIENCE", "sts.amazonaws.com", "aud claim stamped on per-tenant pool VM workload tokens"},+ {"gateway.scheme", "orch-scheme", "ORCH_SCHEME", "http", "orchestrator scheme"},+ {"gateway.port", "orch-port", "ORCH_PORT", "80", "orchestrator port"},+ {"gateway.cluster-domain", "cluster-domain", "CLUSTER_DOMAIN", "svc.cluster.local", "in-cluster DNS domain"},+ {"batch.redis-url", "batch-redis-url", "BATCH_REDIS_URL", "", "legacy pool-templates Redis URL fallback"},+ {"templates.redis-url", "pool-templates-redis-url", "POOL_TEMPLATES_REDIS_URL", "", "pool-templates Redis URL (falls back to batch Redis)"},+ {"metrics.addr", "metrics-addr", "METRICS_ADDR", ":9091", "Prometheus metrics listen address"},+ {"telemetry.endpoint", "otel-endpoint", "OTEL_EXPORTER_OTLP_ENDPOINT", "https://otel.cua.ai", "OTLP HTTP traces endpoint"},+ {"telemetry.protocol", "otel-protocol", "OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf", "OTLP exporter protocol"},+ {"telemetry.service-name", "otel-service-name", "OTEL_SERVICE_NAME", "cyclops-cs-backend", "OTEL service.name"},+ {"telemetry.service-namespace", "otel-service-namespace", "OTEL_SERVICE_NAMESPACE", "cyclops-cs", "OTEL service.namespace"},+ {"telemetry.environment", "otel-environment", "OTEL_ENVIRONMENT", "production", "OTEL deployment environment"},+ {"telemetry.resource-attributes", "otel-resource-attributes", "OTEL_RESOURCE_ATTRIBUTES", "", "Additional OTEL resource attributes"},+}++// RegisterFlags wires the flag set + viper bindings. Call once from the Cobra+// rootCmd before LoadConfig (Cobra parses flags before RunE runs).+func RegisterFlags(fs *pflag.FlagSet) {+ for _, s := range specs {+ fs.String(s.flag, s.def, s.usage)+ _ = viper.BindPFlag(s.key, fs.Lookup(s.flag))+ _ = viper.BindEnv(s.key, s.env)+ viper.SetDefault(s.key, s.def)+ }+}++func LoadConfig() (*Configuration, error) {+ base := strings.TrimRight(viper.GetString("kc.base-url"), "/")+ realm := viper.GetString("kc.realm")+ realmPath := fmt.Sprintf("%s/realms/%s", base, realm)++ // KC_ISSUER overrides the expected `iss` claim; default to the realm path.+ issuer := viper.GetString("kc.issuer")+ if issuer == "" {+ issuer = realmPath+ }++ templatesRedis := viper.GetString("templates.redis-url")+ if templatesRedis == "" {+ templatesRedis = viper.GetString("batch.redis-url")+ }++ cfg := &Configuration{+ WebServer: WebServerConfiguration{Addr: viper.GetString("webserver.addr")},+ Auth: AuthConfiguration{+ Issuer: issuer,+ JWKSUri: realmPath + "/protocol/openid-connect/certs",+ SigningAlgs: []string{"RS256", "RS512", "ES256"},+ SPAClientID: viper.GetString("kc.spa-client-id"),+ KeyClientPfx: viper.GetString("kc.key-client-prefix"),+ UserKeyClientPfx: viper.GetString("kc.user-key-client-prefix"),+ },+ Keycloak: KeycloakConfiguration{+ BaseURL: base,+ Realm: realm,+ AdminClientID: viper.GetString("kc.admin-client-id"),+ AdminClientSecret: viper.GetString("kc.admin-client-secret"),+ TokenURL: realmPath + "/protocol/openid-connect/token",++ WorkloadRealm: viper.GetString("kc.workload-realm"),+ WorkloadAdminClientID: viper.GetString("kc.workload-admin-client-id"),+ WorkloadAdminClientSecret: viper.GetString("kc.workload-admin-client-secret"),+ WorkloadTokenURL: fmt.Sprintf("%s/realms/%s/protocol/openid-connect/token",+ base, viper.GetString("kc.workload-realm")),+ WorkloadAudience: viper.GetString("kc.workload-audience"),+ },+ Gateway: GatewayConfiguration{+ Scheme: viper.GetString("gateway.scheme"),+ Port: viper.GetString("gateway.port"),+ ClusterDomain: viper.GetString("gateway.cluster-domain"),+ },+ Templates: TemplatesConfiguration{RedisURL: templatesRedis},+ Metrics: MetricsConfiguration{Addr: viper.GetString("metrics.addr")},+ Telemetry: TelemetryConfiguration{+ Endpoint: viper.GetString("telemetry.endpoint"),+ Protocol: viper.GetString("telemetry.protocol"),+ ServiceName: viper.GetString("telemetry.service-name"),+ ServiceNamespace: viper.GetString("telemetry.service-namespace"),+ Environment: viper.GetString("telemetry.environment"),+ ResourceAttrs: viper.GetString("telemetry.resource-attributes"),+ },+ }+ if cfg.Keycloak.AdminClientSecret == "" {+ return nil, fmt.Errorf("KC_ADMIN_CLIENT_SECRET is required")+ }+ return cfg, nil+}diff --git a/libs/fleet/backend/config/config_test.go b/libs/fleet/backend/config/config_test.gonew file mode 100644index 0000000000..26ad916537--- /dev/null+++ b/libs/fleet/backend/config/config_test.go@@ -0,0 +1,33 @@+package config++import (+ "testing"++ "github.com/spf13/pflag"+)++func TestLoadConfig_TelemetryDefaults(t *testing.T) {+ t.Setenv("KC_ADMIN_CLIENT_SECRET", "secret")+ RegisterFlags(pflag.NewFlagSet("test", pflag.ContinueOnError))++ cfg, err := LoadConfig()+ if err != nil {+ t.Fatalf("LoadConfig() error = %v", err)+ }++ if got, want := cfg.Telemetry.Endpoint, "https://otel.cua.ai"; got != want {+ t.Fatalf("Telemetry.Endpoint = %q, want %q", got, want)+ }+ if got, want := cfg.Telemetry.Protocol, "http/protobuf"; got != want {+ t.Fatalf("Telemetry.Protocol = %q, want %q", got, want)+ }+ if got, want := cfg.Telemetry.ServiceName, "cyclops-cs-backend"; got != want {+ t.Fatalf("Telemetry.ServiceName = %q, want %q", got, want)+ }+ if got, want := cfg.Telemetry.ServiceNamespace, "cyclops-cs"; got != want {+ t.Fatalf("Telemetry.ServiceNamespace = %q, want %q", got, want)+ }+ if got, want := cfg.Telemetry.Environment, "production"; got != want {+ t.Fatalf("Telemetry.Environment = %q, want %q", got, want)+ }+}diff --git a/libs/fleet/backend/docs/docs.go b/libs/fleet/backend/docs/docs.gonew file mode 100644index 0000000000..0741ebf61c--- /dev/null+++ b/libs/fleet/backend/docs/docs.go@@ -0,0 +1,1587 @@+// Package docs Code generated by swaggo/swag. DO NOT EDIT+package docs++import "github.com/swaggo/swag"++const docTemplate = `{+ "schemes": {{ marshal .Schemes }},+ "swagger": "2.0",+ "info": {+ "description": "{{escape .Description}}",+ "title": "{{.Title}}",+ "contact": {},+ "version": "{{.Version}}"+ },+ "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 lane acquisition 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 lane release 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 cancellation 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/config": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Returns OPA-evaluated feature flags for the authenticated SPA user. ` + "`" + `admin` + "`" + ` is true when the caller's JWT sub appears in input.flags.admin_subs.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "config"+ ],+ "summary": "Per-user feature flags",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.ConfigResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/gateway/{name}/{path}": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "DEPRECATED (CUA-609): The per-pool orchestrator HTTP layer has been removed. This route returns 410 Gone for all requests. All pool operations must use OSGymSandboxClaim CRs (Path B) directly.",+ "tags": [+ "gateway"+ ],+ "summary": "DEPRECATED (CUA-609): per-pool orchestrator proxy — returns 410 Gone",+ "parameters": [+ {+ "type": "string",+ "description": "Pool name (DNS-1123 label)",+ "name": "name",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Upstream path (proxied verbatim, no validation)",+ "name": "path",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "Upstream response",+ "schema": {+ "type": "string"+ }+ },+ "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"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/k8s/{path}": {+ "get": {+ "security": [+ {+ "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).",+ "tags": [+ "passthrough"+ ],+ "summary": "Authenticated proxy to the in-pod kubectl-proxy sidecar",+ "parameters": [+ {+ "type": "string",+ "description": "K8s API path",+ "name": "path",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "K8s API response",+ "schema": {+ "type": "string"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/keys": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "keys"+ ],+ "summary": "List the calling user's API keys",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.ListKeysResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Creates a Keycloak service-account client owned by the calling user. The returned ` + "`" + `client_secret` + "`" + ` is shown exactly once.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "keys"+ ],+ "summary": "Create a new API key",+ "parameters": [+ {+ "description": "Key parameters",+ "name": "body",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.CreateKeyRequest"+ }+ }+ ],+ "responses": {+ "201": {+ "description": "Created",+ "schema": {+ "$ref": "#/definitions/handlers.CreateKeyResponse"+ }+ },+ "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"+ }+ }+ }+ }+ },+ "/api/keys/{id}": {+ "delete": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "keys"+ ],+ "summary": "Revoke an API key by Keycloak client UUID",+ "parameters": [+ {+ "type": "string",+ "description": "Keycloak client UUID",+ "name": "id",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/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": [+ "batch"+ ],+ "summary": "Deprecated label cancellation route",+ "deprecated": true,+ "parameters": [+ {+ "type": "string",+ "description": "Pool name",+ "name": "pool",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Batch 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": [+ "batch"+ ],+ "summary": "Deprecated label batch submission route",+ "deprecated": true,+ "parameters": [+ {+ "type": "string",+ "description": "Pool name",+ "name": "pool",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Batch 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": [+ "batch"+ ],+ "summary": "Deprecated label results route",+ "deprecated": true,+ "parameters": [+ {+ "type": "string",+ "description": "Pool name",+ "name": "pool",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Batch 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": [+ "batch"+ ],+ "summary": "Deprecated label status route",+ "deprecated": true,+ "parameters": [+ {+ "type": "string",+ "description": "Pool name",+ "name": "pool",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Batch label",+ "name": "label",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "410": {+ "description": "Gone",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "/api/namespaces": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Returns namespaces owned by the caller's Capsule Tenant. The list is scoped by a capsule.clastix.io/tenant=\u003ctenant\u003e label selector built from the authenticated subject, so it stays fail-closed even when Capsule Proxy isn't filtering.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "namespaces"+ ],+ "summary": "List the calling user's namespaces",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/handlers.NamespaceResponse"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Creates a K8s namespace via impersonation. Capsule's webhook intercepts the creation and assigns it to the user's Tenant.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "namespaces"+ ],+ "summary": "Create a namespace for the calling user",+ "parameters": [+ {+ "description": "Namespace parameters",+ "name": "body",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.CreateNamespaceRequest"+ }+ }+ ],+ "responses": {+ "201": {+ "description": "Created",+ "schema": {+ "$ref": "#/definitions/handlers.NamespaceResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "409": {+ "description": "Conflict",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/namespaces/{name}": {+ "delete": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Deletes a K8s namespace via impersonation. Capsule blocks deletion if the namespace doesn't belong to the user's Tenant.",+ "tags": [+ "namespaces"+ ],+ "summary": "Delete a namespace owned by the calling user",+ "parameters": [+ {+ "type": "string",+ "description": "Namespace name",+ "name": "name",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "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"+ }+ }+ }+ }+ },+ "/api/orch/{namespace}/{service}/{path}": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Resolves \u003cservice\u003e.\u003cnamespace\u003e.svc.cluster.local at request time (in-cluster DNS). The caller must hold RBAC in {namespace} (verified via an impersonated RoleBinding probe); OPA additionally validates that namespace and service look like DNS-1123 labels.",+ "tags": [+ "passthrough"+ ],+ "summary": "SPA-authenticated proxy to a per-namespace orchestrator service",+ "parameters": [+ {+ "type": "string",+ "description": "Namespace (DNS-1123 label)",+ "name": "namespace",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Service name (DNS-1123 label)",+ "name": "service",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Upstream path",+ "name": "path",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "Upstream response",+ "schema": {+ "type": "string"+ }+ },+ "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"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/pool-templates": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Returns every pool template owned by the calling user, newest first.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "pool-templates"+ ],+ "summary": "List the calling user's pool templates",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/handlers.PoolTemplateResponse"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Stores the given pool config under a name owned by the calling user. Re-saving an existing name overwrites the config while preserving the original creation time. Use GET /api/pool-templates to list them and seed a new pool.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "pool-templates"+ ],+ "summary": "Save a pool config as a reusable template",+ "parameters": [+ {+ "description": "Template name + pool config",+ "name": "body",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.CreatePoolTemplateRequest"+ }+ }+ ],+ "responses": {+ "201": {+ "description": "Created",+ "schema": {+ "$ref": "#/definitions/handlers.PoolTemplateResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/pool-templates/{name}": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "pool-templates"+ ],+ "summary": "Get one of the calling user's pool templates",+ "parameters": [+ {+ "type": "string",+ "description": "Template name",+ "name": "name",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.PoolTemplateResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },+ "delete": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "tags": [+ "pool-templates"+ ],+ "summary": "Delete one of the calling user's pool templates",+ "parameters": [+ {+ "type": "string",+ "description": "Template name",+ "name": "name",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/svc/{namespace}/{service}/{path}": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Proxies to {service}.{namespace}.svc.cluster.local:80. Per-key tokens are bound to their ` + "`" + `namespace` + "`" + ` claim; all other principals (SPA, user keys, oauth2-proxy browser sessions) must hold RBAC in {namespace}, verified via an impersonated RoleBinding probe. Strips Authorization before forwarding.",+ "tags": [+ "gateway"+ ],+ "summary": "Authenticated reverse proxy to a K8s Service in a namespace the caller owns",+ "parameters": [+ {+ "type": "string",+ "description": "K8s namespace (caller must own it, or it must match a per-key token's namespace claim)",+ "name": "namespace",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "K8s Service name (DNS-1123 label)",+ "name": "service",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Upstream path (proxied verbatim)",+ "name": "path",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "Upstream response",+ "schema": {+ "type": "string"+ }+ },+ "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"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/user-keys": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "user-keys"+ ],+ "summary": "List the calling user's API keys",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.ListUserKeysResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Creates a Keycloak service-account client that acts on behalf of the calling user. The client_secret is returned exactly once; it cannot be retrieved later.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "user-keys"+ ],+ "summary": "Create a per-user API key",+ "parameters": [+ {+ "description": "Key parameters",+ "name": "body",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.CreateUserKeyRequest"+ }+ }+ ],+ "responses": {+ "201": {+ "description": "Created",+ "schema": {+ "$ref": "#/definitions/handlers.CreateUserKeyResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/user-keys/{id}": {+ "delete": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "user-keys"+ ],+ "summary": "Revoke a per-user API key",+ "parameters": [+ {+ "type": "string",+ "description": "Keycloak client UUID",+ "name": "id",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/healthz": {+ "get": {+ "produces": [+ "application/json"+ ],+ "tags": [+ "health"+ ],+ "summary": "Liveness/readiness probe",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.HealthResponse"+ }+ }+ }+ }+ }+ },+ "definitions": {+ "handlers.ConfigResponse": {+ "type": "object",+ "properties": {+ "admin": {+ "description": "Admin is true when the caller is in input.flags.admin_subs (OPA-evaluated).\nNon-admins get the customer view: infra-only nav (Nodes, Operator events)\nis hidden in the SPA and the corresponding kubectl-proxy paths are denied\nserver-side by authz.rego.",+ "type": "boolean"+ }+ }+ },+ "handlers.CreateKeyRequest": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "example": "ci-prod"+ },+ "namespace": {+ "type": "string",+ "example": "test-pool"+ }+ }+ },+ "handlers.CreateKeyResponse": {+ "type": "object",+ "properties": {+ "client_id": {+ "type": "string"+ },+ "client_secret": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "namespace": {+ "type": "string"+ },+ "token_url": {+ "type": "string"+ }+ }+ },+ "handlers.CreateNamespaceRequest": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "example": "my-workspace"+ }+ }+ },+ "handlers.CreatePoolTemplateRequest": {+ "type": "object",+ "properties": {+ "config": {+ "type": "object"+ },+ "name": {+ "type": "string",+ "example": "gpu-large"+ }+ }+ },+ "handlers.CreateUserKeyRequest": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "example": "my-ci-key"+ },+ "scope": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "example": [+ "[\"ns1\"",+ "\"ns2\"]"+ ]+ }+ }+ },+ "handlers.CreateUserKeyResponse": {+ "type": "object",+ "properties": {+ "client_id": {+ "type": "string"+ },+ "client_secret": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "scope": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "token_url": {+ "type": "string"+ }+ }+ },+ "handlers.ErrorResponse": {+ "type": "object",+ "properties": {+ "error": {+ "type": "string"+ }+ }+ },+ "handlers.HealthResponse": {+ "type": "object",+ "properties": {+ "ok": {+ "type": "boolean"+ }+ }+ },+ "handlers.ListKeysResponse": {+ "type": "object",+ "properties": {+ "keys": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/keycloak.KeyClient"+ }+ }+ }+ },+ "handlers.ListUserKeysResponse": {+ "type": "object",+ "properties": {+ "keys": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/handlers.UserKeyResponse"+ }+ }+ }+ },+ "handlers.NamespaceResponse": {+ "type": "object",+ "properties": {+ "createdAt": {+ "type": "string"+ },+ "labels": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ },+ "name": {+ "type": "string"+ },+ "status": {+ "type": "string"+ }+ }+ },+ "handlers.PoolTemplateResponse": {+ "type": "object",+ "properties": {+ "config": {+ "type": "object"+ },+ "createdAt": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "user": {+ "type": "string"+ }+ }+ },+ "handlers.UserKeyResponse": {+ "type": "object",+ "properties": {+ "client_id": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "scope": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "keycloak.KeyClient": {+ "type": "object",+ "properties": {+ "client_id": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "namespace": {+ "type": "string"+ },+ "owner_sub": {+ "type": "string"+ }+ }+ }+ },+ "securityDefinitions": {+ "BearerAuth": {+ "description": "Keycloak access token. For /api/keys and /api/{k8s,orch} the token is the SPA's user JWT (azp=cyclops-cs-spa). /api/gateway/{name} and the deprecated /api/batch/{pool} + /api/label/{pool} routes still run through the same OPA checks; per-key tokens must carry a ` + "`" + `namespace` + "`" + ` claim matching \"pool-{name}\" or \"pool-{pool}\" respectively.",+ "type": "apiKey",+ "name": "Authorization",+ "in": "header"+ }+ }+}`++// SwaggerInfo holds exported Swagger Info so clients can modify it+var SwaggerInfo = &swag.Spec{+ Version: "0.1",+ Host: "",+ 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 gateway / batch / label routes that now return 410 Gone. All pool operations use OSGymSandboxClaim CRs (Path B).",+ InfoInstanceName: "swagger",+ SwaggerTemplate: docTemplate,+ LeftDelim: "{{",+ RightDelim: "}}",+}++func init() {+ swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)+}diff --git a/libs/fleet/backend/docs/swagger.json b/libs/fleet/backend/docs/swagger.jsonnew file mode 100644index 0000000000..eb413d3e75--- /dev/null+++ b/libs/fleet/backend/docs/swagger.json@@ -0,0 +1,1562 @@+{+ "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 gateway / batch / label routes that now return 410 Gone. 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 lane acquisition 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 lane release 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 cancellation 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/config": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Returns OPA-evaluated feature flags for the authenticated SPA user. `admin` is true when the caller's JWT sub appears in input.flags.admin_subs.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "config"+ ],+ "summary": "Per-user feature flags",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.ConfigResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/gateway/{name}/{path}": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "DEPRECATED (CUA-609): The per-pool orchestrator HTTP layer has been removed. This route returns 410 Gone for all requests. All pool operations must use OSGymSandboxClaim CRs (Path B) directly.",+ "tags": [+ "gateway"+ ],+ "summary": "Reverse-proxy to the per-pool orchestrator (sole ingress path — CUA-527)",+ "parameters": [+ {+ "type": "string",+ "description": "Pool name (DNS-1123 label)",+ "name": "name",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Upstream path (proxied verbatim, no validation)",+ "name": "path",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "Upstream response",+ "schema": {+ "type": "string"+ }+ },+ "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"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/k8s/{path}": {+ "get": {+ "security": [+ {+ "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).",+ "tags": [+ "passthrough"+ ],+ "summary": "Authenticated proxy to the in-pod kubectl-proxy sidecar",+ "parameters": [+ {+ "type": "string",+ "description": "K8s API path",+ "name": "path",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "K8s API response",+ "schema": {+ "type": "string"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/keys": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "keys"+ ],+ "summary": "List the calling user's API keys",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.ListKeysResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is shown exactly once.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "keys"+ ],+ "summary": "Create a new API key",+ "parameters": [+ {+ "description": "Key parameters",+ "name": "body",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.CreateKeyRequest"+ }+ }+ ],+ "responses": {+ "201": {+ "description": "Created",+ "schema": {+ "$ref": "#/definitions/handlers.CreateKeyResponse"+ }+ },+ "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"+ }+ }+ }+ }+ },+ "/api/keys/{id}": {+ "delete": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "keys"+ ],+ "summary": "Revoke an API key by Keycloak client UUID",+ "parameters": [+ {+ "type": "string",+ "description": "Keycloak client UUID",+ "name": "id",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/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": [+ "batch"+ ],+ "summary": "Deprecated label cancellation route",+ "deprecated": true,+ "parameters": [+ {+ "type": "string",+ "description": "Pool name",+ "name": "pool",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Batch 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": [+ "batch"+ ],+ "summary": "Deprecated label batch submission route",+ "deprecated": true,+ "parameters": [+ {+ "type": "string",+ "description": "Pool name",+ "name": "pool",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Batch 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": [+ "batch"+ ],+ "summary": "Deprecated label results route",+ "deprecated": true,+ "parameters": [+ {+ "type": "string",+ "description": "Pool name",+ "name": "pool",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Batch 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": [+ "batch"+ ],+ "summary": "Deprecated label status route",+ "deprecated": true,+ "parameters": [+ {+ "type": "string",+ "description": "Pool name",+ "name": "pool",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Batch label",+ "name": "label",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "410": {+ "description": "Gone",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "/api/namespaces": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Returns namespaces owned by the caller's Capsule Tenant. The list is scoped by a capsule.clastix.io/tenant=\u003ctenant\u003e label selector built from the authenticated subject, so it stays fail-closed even when Capsule Proxy isn't filtering.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "namespaces"+ ],+ "summary": "List the calling user's namespaces",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/handlers.NamespaceResponse"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Creates a K8s namespace via impersonation. Capsule's webhook intercepts the creation and assigns it to the user's Tenant.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "namespaces"+ ],+ "summary": "Create a namespace for the calling user",+ "parameters": [+ {+ "description": "Namespace parameters",+ "name": "body",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.CreateNamespaceRequest"+ }+ }+ ],+ "responses": {+ "201": {+ "description": "Created",+ "schema": {+ "$ref": "#/definitions/handlers.NamespaceResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "409": {+ "description": "Conflict",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/namespaces/{name}": {+ "delete": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Deletes a K8s namespace via impersonation. Capsule blocks deletion if the namespace doesn't belong to the user's Tenant.",+ "tags": [+ "namespaces"+ ],+ "summary": "Delete a namespace owned by the calling user",+ "parameters": [+ {+ "type": "string",+ "description": "Namespace name",+ "name": "name",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "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"+ }+ }+ }+ }+ },+ "/api/orch/{namespace}/{service}/{path}": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Resolves \u003cservice\u003e.\u003cnamespace\u003e.svc.cluster.local at request time (in-cluster DNS). The caller must hold RBAC in {namespace} (verified via an impersonated RoleBinding probe); OPA additionally validates that namespace and service look like DNS-1123 labels.",+ "tags": [+ "passthrough"+ ],+ "summary": "SPA-authenticated proxy to a per-namespace orchestrator service",+ "parameters": [+ {+ "type": "string",+ "description": "Namespace (DNS-1123 label)",+ "name": "namespace",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Service name (DNS-1123 label)",+ "name": "service",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Upstream path",+ "name": "path",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "Upstream response",+ "schema": {+ "type": "string"+ }+ },+ "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"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/pool-templates": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Returns every pool template owned by the calling user, newest first.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "pool-templates"+ ],+ "summary": "List the calling user's pool templates",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/handlers.PoolTemplateResponse"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Stores the given pool config under a name owned by the calling user. Re-saving an existing name overwrites the config while preserving the original creation time. Use GET /api/pool-templates to list them and seed a new pool.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "pool-templates"+ ],+ "summary": "Save a pool config as a reusable template",+ "parameters": [+ {+ "description": "Template name + pool config",+ "name": "body",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.CreatePoolTemplateRequest"+ }+ }+ ],+ "responses": {+ "201": {+ "description": "Created",+ "schema": {+ "$ref": "#/definitions/handlers.PoolTemplateResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/pool-templates/{name}": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "pool-templates"+ ],+ "summary": "Get one of the calling user's pool templates",+ "parameters": [+ {+ "type": "string",+ "description": "Template name",+ "name": "name",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.PoolTemplateResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },+ "delete": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "tags": [+ "pool-templates"+ ],+ "summary": "Delete one of the calling user's pool templates",+ "parameters": [+ {+ "type": "string",+ "description": "Template name",+ "name": "name",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/svc/{namespace}/{service}/{path}": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Proxies to {service}.{namespace}.svc.cluster.local:80. Per-key tokens are bound to their `namespace` claim; all other principals (SPA, user keys, oauth2-proxy browser sessions) must hold RBAC in {namespace}, verified via an impersonated RoleBinding probe. Strips Authorization before forwarding.",+ "tags": [+ "gateway"+ ],+ "summary": "Authenticated reverse proxy to a K8s Service in a namespace the caller owns",+ "parameters": [+ {+ "type": "string",+ "description": "K8s namespace (caller must own it, or it must match a per-key token's namespace claim)",+ "name": "namespace",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "K8s Service name (DNS-1123 label)",+ "name": "service",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Upstream path (proxied verbatim)",+ "name": "path",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "Upstream response",+ "schema": {+ "type": "string"+ }+ },+ "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"+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/user-keys": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "user-keys"+ ],+ "summary": "List the calling user's API keys",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.ListUserKeysResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ },+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Creates a Keycloak service-account client that acts on behalf of the calling user. The client_secret is returned exactly once; it cannot be retrieved later.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "user-keys"+ ],+ "summary": "Create a per-user API key",+ "parameters": [+ {+ "description": "Key parameters",+ "name": "body",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.CreateUserKeyRequest"+ }+ }+ ],+ "responses": {+ "201": {+ "description": "Created",+ "schema": {+ "$ref": "#/definitions/handlers.CreateUserKeyResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/api/user-keys/{id}": {+ "delete": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "user-keys"+ ],+ "summary": "Revoke a per-user API key",+ "parameters": [+ {+ "type": "string",+ "description": "Keycloak client UUID",+ "name": "id",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }+ }+ },+ "/healthz": {+ "get": {+ "produces": [+ "application/json"+ ],+ "tags": [+ "health"+ ],+ "summary": "Liveness/readiness probe",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.HealthResponse"+ }+ }+ }+ }+ }+ },+ "definitions": {+ "handlers.ConfigResponse": {+ "type": "object",+ "properties": {+ "admin": {+ "description": "Admin is true when the caller is in input.flags.admin_subs (OPA-evaluated).\nNon-admins get the customer view: infra-only nav (Nodes, Operator events)\nis hidden in the SPA and the corresponding kubectl-proxy paths are denied\nserver-side by authz.rego.",+ "type": "boolean"+ }+ }+ },+ "handlers.CreateKeyRequest": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "example": "ci-prod"+ },+ "namespace": {+ "type": "string",+ "example": "test-pool"+ }+ }+ },+ "handlers.CreateKeyResponse": {+ "type": "object",+ "properties": {+ "client_id": {+ "type": "string"+ },+ "client_secret": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "namespace": {+ "type": "string"+ },+ "token_url": {+ "type": "string"+ }+ }+ },+ "handlers.CreateNamespaceRequest": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "example": "my-workspace"+ }+ }+ },+ "handlers.CreatePoolTemplateRequest": {+ "type": "object",+ "properties": {+ "config": {+ "type": "object"+ },+ "name": {+ "type": "string",+ "example": "gpu-large"+ }+ }+ },+ "handlers.CreateUserKeyRequest": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "example": "my-ci-key"+ },+ "scope": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "example": [+ "[\"ns1\"",+ "\"ns2\"]"+ ]+ }+ }+ },+ "handlers.CreateUserKeyResponse": {+ "type": "object",+ "properties": {+ "client_id": {+ "type": "string"+ },+ "client_secret": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "scope": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "token_url": {+ "type": "string"+ }+ }+ },+ "handlers.ErrorResponse": {+ "type": "object",+ "properties": {+ "error": {+ "type": "string"+ }+ }+ },+ "handlers.HealthResponse": {+ "type": "object",+ "properties": {+ "ok": {+ "type": "boolean"+ }+ }+ },+ "handlers.ListKeysResponse": {+ "type": "object",+ "properties": {+ "keys": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/keycloak.KeyClient"+ }+ }+ }+ },+ "handlers.ListUserKeysResponse": {+ "type": "object",+ "properties": {+ "keys": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/handlers.UserKeyResponse"+ }+ }+ }+ },+ "handlers.NamespaceResponse": {+ "type": "object",+ "properties": {+ "createdAt": {+ "type": "string"+ },+ "labels": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ },+ "name": {+ "type": "string"+ },+ "status": {+ "type": "string"+ }+ }+ },+ "handlers.PoolTemplateResponse": {+ "type": "object",+ "properties": {+ "config": {+ "type": "object"+ },+ "createdAt": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "user": {+ "type": "string"+ }+ }+ },+ "handlers.UserKeyResponse": {+ "type": "object",+ "properties": {+ "client_id": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "scope": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "keycloak.KeyClient": {+ "type": "object",+ "properties": {+ "client_id": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "namespace": {+ "type": "string"+ },+ "owner_sub": {+ "type": "string"+ }+ }+ }+ },+ "securityDefinitions": {+ "BearerAuth": {+ "description": "Keycloak access token. For /api/keys and /api/{k8s,orch} the token is the SPA's user JWT (azp=cyclops-cs-spa). /api/gateway/{name} and the deprecated /api/batch/{pool} + /api/label/{pool} routes still run through the same OPA checks; per-key tokens must carry a `namespace` claim matching \"pool-{name}\" or \"pool-{pool}\" respectively.",+ "type": "apiKey",+ "name": "Authorization",+ "in": "header"+ }+ }+}diff --git a/libs/fleet/backend/docs/swagger.yaml b/libs/fleet/backend/docs/swagger.yamlnew file mode 100644index 0000000000..2a0e3647d8--- /dev/null+++ b/libs/fleet/backend/docs/swagger.yaml@@ -0,0 +1,1053 @@+basePath: /+definitions:+ handlers.ConfigResponse:+ properties:+ admin:+ description: |-+ Admin is true when the caller is in input.flags.admin_subs (OPA-evaluated).+ Non-admins get the customer view: infra-only nav (Nodes, Operator events)+ is hidden in the SPA and the corresponding kubectl-proxy paths are denied+ server-side by authz.rego.+ type: boolean+ type: object+ handlers.CreateKeyRequest:+ properties:+ name:+ example: ci-prod+ type: string+ namespace:+ example: test-pool+ type: string+ type: object+ handlers.CreateKeyResponse:+ properties:+ client_id:+ type: string+ client_secret:+ type: string+ name:+ type: string+ namespace:+ type: string+ token_url:+ type: string+ type: object+ handlers.CreateNamespaceRequest:+ properties:+ name:+ example: my-workspace+ type: string+ type: object+ handlers.CreatePoolTemplateRequest:+ properties:+ config:+ type: object+ name:+ example: gpu-large+ type: string+ type: object+ handlers.CreateUserKeyRequest:+ properties:+ name:+ example: my-ci-key+ type: string+ scope:+ example:+ - '["ns1"'+ - '"ns2"]'+ items:+ type: string+ type: array+ type: object+ handlers.CreateUserKeyResponse:+ properties:+ client_id:+ type: string+ client_secret:+ type: string+ name:+ type: string+ scope:+ items:+ type: string+ type: array+ token_url:+ type: string+ type: object+ handlers.ErrorResponse:+ properties:+ error:+ type: string+ type: object+ handlers.HealthResponse:+ properties:+ ok:+ type: boolean+ type: object+ handlers.ListKeysResponse:+ properties:+ keys:+ items:+ $ref: '#/definitions/keycloak.KeyClient'+ type: array+ type: object+ handlers.ListUserKeysResponse:+ properties:+ keys:+ items:+ $ref: '#/definitions/handlers.UserKeyResponse'+ type: array+ type: object+ handlers.NamespaceResponse:+ properties:+ createdAt:+ type: string+ labels:+ additionalProperties:+ type: string+ type: object+ name:+ type: string+ status:+ type: string+ type: object+ handlers.PoolTemplateResponse:+ properties:+ config:+ type: object+ createdAt:+ type: string+ name:+ type: string+ user:+ type: string+ type: object+ handlers.UserKeyResponse:+ properties:+ client_id:+ type: string+ id:+ type: string+ name:+ type: string+ scope:+ items:+ type: string+ type: array+ type: object+ keycloak.KeyClient:+ properties:+ client_id:+ type: string+ id:+ type: string+ name:+ type: string+ namespace:+ type: string+ owner_sub:+ type: string+ type: object+info:+ contact: {}+ description: Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key+ management, service proxies (k8s / orch / svc), namespace management, and+ deprecated gateway / batch / label routes that now return 410 Gone. All+ pool operations use OSGymSandboxClaim CRs (Path B).+ title: Cyclops CS Backend API+ version: "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 cancellation 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 lane release 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 lane acquisition 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/config:+ get:+ description: Returns OPA-evaluated feature flags for the authenticated SPA user.+ `admin` is true when the caller's JWT sub appears in input.flags.admin_subs.+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/handlers.ConfigResponse'+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Per-user feature flags+ tags:+ - config+ /api/gateway/{name}/{path}:+ get:+ description: 'DEPRECATED (CUA-609): The per-pool orchestrator HTTP layer has+ been removed. This route returns 410 Gone for all requests. All pool+ operations must use OSGymSandboxClaim CRs (Path B) directly.'+ parameters:+ - description: Pool name (DNS-1123 label)+ in: path+ name: name+ required: true+ type: string+ - description: Upstream path (proxied verbatim, no validation)+ in: path+ name: path+ type: string+ responses:+ "200":+ description: Upstream response+ schema:+ type: string+ "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'+ "502":+ description: Bad Gateway+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: DEPRECATED (CUA-609): per-pool orchestrator proxy — returns 410 Gone+ tags:+ - gateway+ /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).+ parameters:+ - description: K8s API path+ in: path+ name: path+ required: true+ type: string+ responses:+ "200":+ description: K8s API response+ schema:+ type: string+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "403":+ description: Forbidden+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "502":+ description: Bad Gateway+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Authenticated proxy to the in-pod kubectl-proxy sidecar+ tags:+ - passthrough+ /api/keys:+ get:+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/handlers.ListKeysResponse'+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: List the calling user's API keys+ tags:+ - keys+ post:+ consumes:+ - application/json+ description: Creates a Keycloak service-account client owned by the calling+ user. The returned `client_secret` is shown exactly once.+ parameters:+ - description: Key parameters+ in: body+ name: body+ required: true+ schema:+ $ref: '#/definitions/handlers.CreateKeyRequest'+ produces:+ - application/json+ responses:+ "201":+ description: Created+ schema:+ $ref: '#/definitions/handlers.CreateKeyResponse'+ "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'+ security:+ - BearerAuth: []+ summary: Create a new API key+ tags:+ - keys+ /api/keys/{id}:+ delete:+ parameters:+ - description: Keycloak client UUID+ in: path+ name: id+ required: true+ type: string+ produces:+ - application/json+ responses:+ "204":+ description: No Content+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "403":+ description: Forbidden+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Revoke an API key by Keycloak client UUID+ tags:+ - 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: Batch 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 cancellation route+ tags:+ - batch+ /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: Batch 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 submission route+ tags:+ - batch+ /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: Batch 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:+ - batch+ /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: Batch 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:+ - batch+ /api/namespaces:+ get:+ description: Returns namespaces owned by the caller's Capsule Tenant. The list+ is scoped by a capsule.clastix.io/tenant=<tenant> label selector built from+ the authenticated subject, so it stays fail-closed even when Capsule Proxy+ isn't filtering.+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ items:+ $ref: '#/definitions/handlers.NamespaceResponse'+ type: array+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "502":+ description: Bad Gateway+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: List the calling user's namespaces+ tags:+ - namespaces+ post:+ consumes:+ - application/json+ description: Creates a K8s namespace via impersonation. Capsule's webhook intercepts+ the creation and assigns it to the user's Tenant.+ parameters:+ - description: Namespace parameters+ in: body+ name: body+ required: true+ schema:+ $ref: '#/definitions/handlers.CreateNamespaceRequest'+ produces:+ - application/json+ responses:+ "201":+ description: Created+ schema:+ $ref: '#/definitions/handlers.NamespaceResponse'+ "400":+ description: Bad Request+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "409":+ description: Conflict+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "502":+ description: Bad Gateway+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Create a namespace for the calling user+ tags:+ - namespaces+ /api/namespaces/{name}:+ delete:+ description: Deletes a K8s namespace via impersonation. Capsule blocks deletion+ if the namespace doesn't belong to the user's Tenant.+ parameters:+ - description: Namespace name+ in: path+ name: name+ required: true+ type: string+ responses:+ "204":+ description: No Content+ "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: Delete 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+ (in-cluster DNS). The caller must hold RBAC in {namespace} (verified via an+ impersonated RoleBinding probe); OPA additionally validates that namespace+ and service look like DNS-1123 labels.+ parameters:+ - description: Namespace (DNS-1123 label)+ in: path+ name: namespace+ required: true+ type: string+ - description: Service name (DNS-1123 label)+ in: path+ name: service+ required: true+ type: string+ - description: Upstream path+ in: path+ name: path+ required: true+ type: string+ responses:+ "200":+ description: Upstream response+ schema:+ type: string+ "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'+ "502":+ description: Bad Gateway+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: SPA-authenticated proxy to a per-namespace orchestrator service+ tags:+ - passthrough+ /api/pool-templates:+ get:+ description: Returns every pool template owned by the calling user, newest first.+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ items:+ $ref: '#/definitions/handlers.PoolTemplateResponse'+ type: array+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "503":+ description: Service Unavailable+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: List the calling user's pool templates+ tags:+ - pool-templates+ post:+ consumes:+ - application/json+ description: Stores the given pool config under a name owned by the calling+ user. Re-saving an existing name overwrites the config while preserving the+ original creation time. Use GET /api/pool-templates to list them and seed+ a new pool.+ parameters:+ - description: Template name + pool config+ in: body+ name: body+ required: true+ schema:+ $ref: '#/definitions/handlers.CreatePoolTemplateRequest'+ produces:+ - application/json+ responses:+ "201":+ description: Created+ schema:+ $ref: '#/definitions/handlers.PoolTemplateResponse'+ "400":+ description: Bad Request+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "503":+ description: Service Unavailable+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Save a pool config as a reusable template+ tags:+ - pool-templates+ /api/pool-templates/{name}:+ delete:+ parameters:+ - description: Template name+ in: path+ name: name+ required: true+ type: string+ responses:+ "204":+ description: No Content+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "404":+ description: Not Found+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "503":+ description: Service Unavailable+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Delete one of the calling user's pool templates+ tags:+ - pool-templates+ get:+ parameters:+ - description: Template name+ in: path+ name: name+ required: true+ type: string+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/handlers.PoolTemplateResponse'+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "404":+ description: Not Found+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "503":+ description: Service Unavailable+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Get one of the calling user's pool templates+ tags:+ - pool-templates+ /api/svc/{namespace}/{service}/{path}:+ get:+ description: Proxies to {service}.{namespace}.svc.cluster.local:80. Per-key+ tokens are bound to their `namespace` claim; all other principals (SPA, user+ keys, oauth2-proxy browser sessions) must hold RBAC in {namespace}, verified+ via an impersonated RoleBinding probe. Strips Authorization before forwarding.+ parameters:+ - description: K8s namespace (caller must own it, or it must match a per-key+ token's namespace claim)+ in: path+ name: namespace+ required: true+ type: string+ - description: K8s Service name (DNS-1123 label)+ in: path+ name: service+ required: true+ type: string+ - description: Upstream path (proxied verbatim)+ in: path+ name: path+ type: string+ responses:+ "200":+ description: Upstream response+ schema:+ type: string+ "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'+ "502":+ description: Bad Gateway+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Authenticated reverse proxy to a K8s Service in a namespace the caller+ owns+ tags:+ - gateway+ /api/user-keys:+ get:+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/handlers.ListUserKeysResponse'+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: List the calling user's API keys+ tags:+ - user-keys+ post:+ consumes:+ - application/json+ description: Creates a Keycloak service-account client that acts on behalf of+ the calling user. The client_secret is returned exactly once; it cannot be+ retrieved later.+ parameters:+ - description: Key parameters+ in: body+ name: body+ required: true+ schema:+ $ref: '#/definitions/handlers.CreateUserKeyRequest'+ produces:+ - application/json+ responses:+ "201":+ description: Created+ schema:+ $ref: '#/definitions/handlers.CreateUserKeyResponse'+ "400":+ description: Bad Request+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Create a per-user API key+ tags:+ - user-keys+ /api/user-keys/{id}:+ delete:+ parameters:+ - description: Keycloak client UUID+ in: path+ name: id+ required: true+ type: string+ produces:+ - application/json+ responses:+ "204":+ description: No Content+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "403":+ description: Forbidden+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Revoke a per-user API key+ tags:+ - user-keys+ /healthz:+ get:+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/handlers.HealthResponse'+ summary: Liveness/readiness probe+ tags:+ - health+securityDefinitions:+ BearerAuth:+ description: Keycloak access token. For /api/keys and /api/{k8s,orch} the token+ is the SPA's user JWT (azp=cyclops-cs-spa). /api/gateway/{name} and the deprecated+ /api/batch/{pool} + /api/label/{pool} routes still run through the same OPA+ checks; per-key tokens must carry a `namespace` claim matching "pool-{name}"+ or "pool-{pool}" respectively.+ in: header+ name: Authorization+ type: apiKey+swagger: "2.0"diff --git a/libs/fleet/backend/go.mod b/libs/fleet/backend/go.modnew file mode 100644index 0000000000..01c16071ed--- /dev/null+++ b/libs/fleet/backend/go.mod@@ -0,0 +1,114 @@+module cyclops-cs-backend++go 1.24.0++toolchain go1.24.7++require (+ github.com/MicahParks/keyfunc/v2 v2.1.0+ github.com/Nerzal/gocloak/v13 v13.9.0+ github.com/golang-jwt/jwt/v5 v5.2.1+ github.com/google/uuid v1.6.0+ github.com/open-feature/go-sdk v1.17.0+ github.com/open-policy-agent/opa v0.69.0+ github.com/prometheus/client_golang v1.20.4+ github.com/redis/go-redis/v9 v9.19.0+ github.com/spf13/cobra v1.10.2+ github.com/spf13/pflag v1.0.10+ github.com/spf13/viper v1.21.0+ github.com/swaggo/http-swagger/v2 v2.0.2+ github.com/swaggo/swag v1.16.6+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.28.0+ golang.org/x/sync v0.17.0+)++require (+ github.com/aws/aws-sdk-go-v2 v1.41.7 // indirect+ github.com/aws/aws-sdk-go-v2/config v1.32.17 // indirect+ github.com/cenkalti/backoff/v4 v4.3.0 // indirect+ github.com/felixge/httpsnoop v1.0.4 // indirect+ github.com/fsnotify/fsnotify v1.9.0 // indirect+ github.com/go-viper/mapstructure/v2 v2.4.0 // indirect+ github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 // indirect+ github.com/inconshreveable/mousetrap v1.1.0 // indirect+ github.com/open-feature/go-sdk-contrib/providers/aws-ssm v1.0.0 // indirect+ github.com/open-feature/go-sdk-contrib/providers/from-env v0.1.6 // indirect+ github.com/pelletier/go-toml/v2 v2.2.4 // indirect+ github.com/sagikazarmark/locafero v0.11.0 // indirect+ github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect+ github.com/spf13/afero v1.15.0 // indirect+ github.com/spf13/cast v1.10.0 // indirect+ github.com/subosito/gotenv v1.6.0 // indirect+ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.28.0 // indirect+ go.opentelemetry.io/proto/otlp v1.3.1 // indirect+ go.uber.org/mock v0.6.0 // indirect+ go.yaml.in/yaml/v3 v3.0.4 // indirect+ golang.org/x/text v0.30.0 // indirect+ google.golang.org/genproto/googleapis/api v0.0.0-20240814211410-ddb44dafa142 // indirect+ google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 // indirect+ google.golang.org/grpc v1.67.0 // indirect+)++require (+ github.com/KyleBanks/depth v1.2.1 // indirect+ github.com/OneOfOne/xxhash v1.2.8 // indirect+ github.com/agnivade/levenshtein v1.2.0 // indirect+ github.com/aws/aws-sdk-go-v2/credentials v1.19.16 // indirect+ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 // indirect+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 // indirect+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 // indirect+ github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 // indirect+ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 // indirect+ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 // indirect+ github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 // indirect+ github.com/aws/aws-sdk-go-v2/service/ssm v1.68.6 // indirect+ github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 // indirect+ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21 // indirect+ github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 // indirect+ github.com/aws/smithy-go v1.25.1 // indirect+ github.com/beorn7/perks v1.0.1 // indirect+ github.com/cespare/xxhash/v2 v2.3.0 // indirect+ github.com/go-ini/ini v1.67.0 // indirect+ github.com/go-logr/logr v1.4.3 // indirect+ github.com/go-logr/stdr v1.2.2 // indirect+ github.com/go-openapi/jsonpointer v0.19.5 // indirect+ github.com/go-openapi/jsonreference v0.20.0 // indirect+ github.com/go-openapi/spec v0.20.6 // indirect+ github.com/go-openapi/swag v0.19.15 // indirect+ github.com/go-resty/resty/v2 v2.7.0 // indirect+ github.com/gobwas/glob v0.2.3 // indirect+ github.com/gorilla/mux v1.8.1 // indirect+ github.com/josharian/intern v1.0.0 // indirect+ github.com/klauspost/compress v1.17.9 // indirect+ github.com/mailru/easyjson v0.7.6 // indirect+ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect+ github.com/opentracing/opentracing-go v1.2.0 // indirect+ github.com/pkg/errors v0.9.1 // indirect+ github.com/prometheus/client_model v0.6.1 // indirect+ github.com/prometheus/common v0.55.0 // indirect+ github.com/prometheus/procfs v0.15.1 // indirect+ github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 // indirect+ github.com/segmentio/ksuid v1.0.4 // indirect+ github.com/sirupsen/logrus v1.9.3 // indirect+ github.com/swaggo/files/v2 v2.0.0 // indirect+ github.com/tchap/go-patricia/v2 v2.3.1 // indirect+ github.com/trycua/cloud/pkg/featureflags v0.0.0+ github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect+ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect+ github.com/yashtewari/glob-intersection v0.2.0 // indirect+ go.opentelemetry.io/otel v1.28.0+ go.opentelemetry.io/otel/metric v1.28.0 // indirect+ go.opentelemetry.io/otel/sdk v1.28.0+ go.opentelemetry.io/otel/trace v1.28.0+ go.uber.org/atomic v1.11.0 // indirect+ golang.org/x/mod v0.28.0 // indirect+ golang.org/x/net v0.44.0 // indirect+ golang.org/x/sys v0.36.0 // indirect+ golang.org/x/tools v0.37.0 // indirect+ google.golang.org/protobuf v1.34.2 // indirect+ gopkg.in/yaml.v2 v2.4.0 // indirect+ sigs.k8s.io/yaml v1.4.0 // indirect+)++replace github.com/trycua/cloud/pkg/featureflags => ../../pkg/featureflagsdiff --git a/libs/fleet/backend/go.sum b/libs/fleet/backend/go.sumnew file mode 100644index 0000000000..07b321d77a--- /dev/null+++ b/libs/fleet/backend/go.sum@@ -0,0 +1,294 @@+github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=+github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=+github.com/MicahParks/keyfunc/v2 v2.1.0 h1:6ZXKb9Rp6qp1bDbJefnG7cTH8yMN1IC/4nf+GVjO99k=+github.com/MicahParks/keyfunc/v2 v2.1.0/go.mod h1:rW42fi+xgLJ2FRRXAfNx9ZA8WpD4OeE/yHVMteCkw9k=+github.com/Nerzal/gocloak/v13 v13.9.0 h1:YWsJsdM5b0yhM2Ba3MLydiOlujkBry4TtdzfIzSVZhw=+github.com/Nerzal/gocloak/v13 v13.9.0/go.mod h1:YYuDcXZ7K2zKECyVP7pPqjKxx2AzYSpKDj8d6GuyM10=+github.com/OneOfOne/xxhash v1.2.8 h1:31czK/TI9sNkxIKfaUfGlU47BAxQ0ztGgd9vPyqimf8=+github.com/OneOfOne/xxhash v1.2.8/go.mod h1:eZbhyaAYD41SGSSsnmcpxVoRiQ/MPUTjUdIIOT9Um7Q=+github.com/agnivade/levenshtein v1.2.0 h1:U9L4IOT0Y3i0TIlUIDJ7rVUziKi/zPbrJGaFrtYH3SY=+github.com/agnivade/levenshtein v1.2.0/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=+github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=+github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=+github.com/aws/aws-sdk-go-v2 v1.41.7 h1:DWpAJt66FmnnaRIOT/8ASTucrvuDPZASqhhLey6tLY8=+github.com/aws/aws-sdk-go-v2 v1.41.7/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc=+github.com/aws/aws-sdk-go-v2/config v1.32.17 h1:FpL4/758/diKwqbytU0prpuiu60fgXKUWCpDJtApclU=+github.com/aws/aws-sdk-go-v2/config v1.32.17/go.mod h1:OXqUMzgXytfoF9JaKkhrOYsyh72t9G+MJH8mMRaexOE=+github.com/aws/aws-sdk-go-v2/credentials v1.19.16 h1:r3RJBuU7X9ibt8RHbMjWE6y60QbKBiII6wSrXnapxSU=+github.com/aws/aws-sdk-go-v2/credentials v1.19.16/go.mod h1:6cx7zqDENJDbBIIWX6P8s0h6hqHC8Avbjh9Dseo27ug=+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 h1:UuSfcORqNSz/ey3VPRS8TcVH2Ikf0/sC+Hdj400QI6U=+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23/go.mod h1:+G/OSGiOFnSOkYloKj/9M35s74LgVAdJBSD5lsFfqKg=+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 h1:GpT/TrnBYuE5gan2cZbTtvP+JlHsutdmlV2YfEyNde0=+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23/go.mod h1:xYWD6BS9ywC5bS3sz9Xh04whO/hzK2plt2Zkyrp4JuA=+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 h1:bpd8vxhlQi2r1hiueOw02f/duEPTMK59Q4QMAoTTtTo=+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23/go.mod h1:15DfR2nw+CRHIk0tqNyifu3G1YdAOy68RftkhMDDwYk=+github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 h1:OQqn11BtaYv1WLUowvcA30MpzIu8Ti4pcLPIIyoKZrA=+github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24/go.mod h1:X5ZJyfwVrWA96GzPmUCWFQaEARPR7gCrpq2E92PJwAE=+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 h1:FLudkZLt5ci0ozzgkVo8BJGwvqNaZbTWb3UcucAateA=+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9/go.mod h1:w7wZ/s9qK7c8g4al+UyoF1Sp/Z45UwMGcqIzLWVQHWk=+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 h1:pbrxO/kuIwgEsOPLkaHu0O+m4fNgLU8B3vxQ+72jTPw=+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23/go.mod h1:/CMNUqoj46HpS3MNRDEDIwcgEnrtZlKRaHNaHxIFpNA=+github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 h1:TdJ+HdzOBhU8+iVAOGUTU63VXopcumCOF1paFulHWZc=+github.com/aws/aws-sdk-go-v2/service/signin v1.0.11/go.mod h1:R82ZRExE/nheo0N+T8zHPcLRTcH8MGsnR3BiVGX0TwI=+github.com/aws/aws-sdk-go-v2/service/ssm v1.68.6 h1:0LPJjbSNEDHidGOXa0LfvSVbdn9/GdlJUQTgE0kFpso=+github.com/aws/aws-sdk-go-v2/service/ssm v1.68.6/go.mod h1:SrZAopBP5/lyQ6NBVXKlRp8wPIXhzBCZU98sEozmv8Y=+github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 h1:7byT8HUWrgoRp6sXjxtZwgOKfhss5fW6SkLBtqzgRoE=+github.com/aws/aws-sdk-go-v2/service/sso v1.30.17/go.mod h1:xNWknVi4Ezm1vg1QsB/5EWpAJURq22uqd38U8qKvOJc=+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21 h1:+1Kl1zx6bWi4X7cKi3VYh29h8BvsCoHQEQ6ST9X8w7w=+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21/go.mod h1:4vIRDq+CJB2xFAXZ+YgGUTiEft7oAQlhIs71xcSeuVg=+github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 h1:F/M5Y9I3nwr2IEpshZgh1GeHpOItExNM9L1euNuh/fk=+github.com/aws/aws-sdk-go-v2/service/sts v1.42.1/go.mod h1:mTNxImtovCOEEuD65mKW7DCsL+2gjEH+RPEAexAzAio=+github.com/aws/smithy-go v1.25.1 h1:J8ERsGSU7d+aCmdQur5Txg6bVoYelvQJgtZehD12GkI=+github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=+github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=+github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=+github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=+github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=+github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=+github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=+github.com/bytecodealliance/wasmtime-go/v3 v3.0.2 h1:3uZCA/BLTIu+DqCfguByNMJa2HVHpXvjfy0Dy7g6fuA=+github.com/bytecodealliance/wasmtime-go/v3 v3.0.2/go.mod h1:RnUjnIXxEJcL6BgCvNyzCCRzZcxCgsZCi+RNlvYor5Q=+github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=+github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=+github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=+github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=+github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/dgraph-io/badger/v3 v3.2103.5 h1:ylPa6qzbjYRQMU6jokoj4wzcaweHylt//CH0AKt0akg=+github.com/dgraph-io/badger/v3 v3.2103.5/go.mod h1:4MPiseMeDQ3FNCYwRbbcBOGJLf5jsE0PPFzRiKjtcdw=+github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8=+github.com/dgraph-io/ristretto v0.1.1/go.mod h1:S1GPSBCYCIhmVNfcth17y2zZtQT6wzkzgwUve0VDWWA=+github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo=+github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=+github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=+github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=+github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=+github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=+github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw=+github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=+github.com/foxcpp/go-mockdns v1.1.0 h1:jI0rD8M0wuYAxL7r/ynTrCQQq0BVqfB99Vgk7DlmewI=+github.com/foxcpp/go-mockdns v1.1.0/go.mod h1:IhLeSFGed3mJIAXPH2aiRQB+kqz7oqu8ld2qVbOu7Wk=+github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=+github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=+github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=+github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=+github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=+github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=+github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=+github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=+github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=+github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=+github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA=+github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo=+github.com/go-openapi/spec v0.20.6 h1:ich1RQ3WDbfoeTqTAb+5EIxNmpKVJZWBNah9RAT0jIQ=+github.com/go-openapi/spec v0.20.6/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA=+github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=+github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=+github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=+github.com/go-resty/resty/v2 v2.7.0 h1:me+K9p3uhSmXtrBZ4k9jcEAfJmuC8IivWHwaLZwPrFY=+github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I=+github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=+github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=+github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=+github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=+github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=+github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=+github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=+github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=+github.com/golang/glog v1.2.2 h1:1+mZ9upx1Dh6FmUTFR1naJ77miKiXgALjWOZ3NVFPmY=+github.com/golang/glog v1.2.2/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w=+github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=+github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=+github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=+github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=+github.com/google/flatbuffers v1.12.1 h1:MVlul7pQNoDzWRLTw5imwYsl+usrS1TXG2H4jg6ImGw=+github.com/google/flatbuffers v1.12.1/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8=+github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=+github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=+github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=+github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=+github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 h1:bkypFPDjIYGfCYD5mRBvpqxfYX1YCS1PXdKYWi8FsN0=+github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0/go.mod h1:P+Lt/0by1T8bfcF3z737NnSbmxQAppXMRziHUxPOC8k=+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=+github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=+github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=+github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=+github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=+github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=+github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=+github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=+github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=+github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=+github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=+github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=+github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=+github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=+github.com/miekg/dns v1.1.57 h1:Jzi7ApEIzwEPLHWRcafCN9LZSBbqQpxjt/wpgvg7wcM=+github.com/miekg/dns v1.1.57/go.mod h1:uqRjCRUuEAA6qsOiJvDd+CFo/vW+y5WR6SNmHE55hZk=+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=+github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=+github.com/open-feature/go-sdk v1.17.0 h1:/OUBBw5d9D61JaNZZxb2Nnr5/EJrEpjtKCTY3rspJQk=+github.com/open-feature/go-sdk v1.17.0/go.mod h1:lPxPSu1UnZ4E3dCxZi5gV3et2ACi8O8P+zsTGVsDZUw=+github.com/open-feature/go-sdk-contrib/providers/aws-ssm v1.0.0 h1:CAOJS6xFtuthfk4OFWmj4zyxSZ2xTCgDbMGqTCp3teE=+github.com/open-feature/go-sdk-contrib/providers/aws-ssm v1.0.0/go.mod h1:pdo/WJdJ52dQtiRUFHj5PtRXL+tsYKin+zuYxNmmt9M=+github.com/open-feature/go-sdk-contrib/providers/from-env v0.1.6 h1:tD9kPmv/3cLmAtTCrrCx3CrkrzpOx3fdwojL/kncVMM=+github.com/open-feature/go-sdk-contrib/providers/from-env v0.1.6/go.mod h1:85Wn9Wm5D9aEfL4MEZEceW4pJt6sc8J97RGCGY8hD3M=+github.com/open-policy-agent/opa v0.69.0 h1:s2igLw2Z6IvGWGuXSfugWkVultDMsM9pXiDuMp7ckWw=+github.com/open-policy-agent/opa v0.69.0/go.mod h1:+qyXJGkpEJ6kpB1kGo8JSwHtVXbTdsGdQYPWWNYNj+4=+github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=+github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=+github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=+github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=+github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/prometheus/client_golang v1.20.4 h1:Tgh3Yr67PaOv/uTqloMsCEdeuFTatm5zIq5+qNN23vI=+github.com/prometheus/client_golang v1.20.4/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=+github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=+github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=+github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc=+github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8=+github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=+github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=+github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 h1:MkV+77GLUNo5oJ0jf870itWm3D0Sjh7+Za9gazKc5LQ=+github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=+github.com/redis/go-redis/v9 v9.19.0 h1:XPVaaPSnG6RhYf7p+rmSa9zZfeVAnWsH5h3lxthOm/k=+github.com/redis/go-redis/v9 v9.19.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=+github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=+github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=+github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=+github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=+github.com/segmentio/ksuid v1.0.4 h1:sBo2BdShXjmcugAMwjugoGUdUV0pcxY5mW4xKRn3v4c=+github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE=+github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=+github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=+github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=+github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=+github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=+github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=+github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=+github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=+github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=+github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=+github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=+github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=+github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=+github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=+github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=+github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=+github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=+github.com/swaggo/files/v2 v2.0.0 h1:hmAt8Dkynw7Ssz46F6pn8ok6YmGZqHSVLZ+HQM7i0kw=+github.com/swaggo/files/v2 v2.0.0/go.mod h1:24kk2Y9NYEJ5lHuCra6iVwkMjIekMCaFq/0JQj66kyM=+github.com/swaggo/http-swagger/v2 v2.0.2 h1:FKCdLsl+sFCx60KFsyM0rDarwiUSZ8DqbfSyIKC9OBg=+github.com/swaggo/http-swagger/v2 v2.0.2/go.mod h1:r7/GBkAWIfK6E/OLnE8fXnviHiDeAHmgIyooa4xm3AQ=+github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=+github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=+github.com/tchap/go-patricia/v2 v2.3.1 h1:6rQp39lgIYZ+MHmdEq4xzuk1t7OdC35z/xm0BGhTkes=+github.com/tchap/go-patricia/v2 v2.3.1/go.mod h1:VZRHKAb53DLaG+nA9EaYYiaEx6YztwDlLElMsnSHD4k=+github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo=+github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=+github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=+github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=+github.com/yashtewari/glob-intersection v0.2.0 h1:8iuHdN88yYuCzCdjt0gDe+6bAhUwBeEWqThExu54RFg=+github.com/yashtewari/glob-intersection v0.2.0/go.mod h1:LK7pIC3piUjovexikBbJ26Yml7g8xa5bsjfx2v1fwok=+github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=+github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=+go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=+go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0 h1:4K4tsIXefpVJtvA/8srF4V4y0akAoPHkIslgAkjixJA=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0/go.mod h1:jjdQuTGVsXV4vSs+CJ2qYDeDPf9yIJV23qlIzBm73Vg=+go.opentelemetry.io/otel v1.28.0 h1:/SqNcYk+idO0CxKEUOtKQClMK/MimZihKYMruSMViUo=+go.opentelemetry.io/otel v1.28.0/go.mod h1:q68ijF8Fc8CnMHKyzqL6akLO46ePnjkgfIMIjUIX9z4=+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.28.0 h1:3Q/xZUyC1BBkualc9ROb4G8qkH90LXEIICcs5zv1OYY=+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.28.0/go.mod h1:s75jGIWA9OfCMzF0xr+ZgfrB5FEbbV7UuYo32ahUiFI=+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.28.0 h1:R3X6ZXmNPRR8ul6i3WgFURCHzaXjHdm0karRG/+dj3s=+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.28.0/go.mod h1:QWFXnDavXWwMx2EEcZsf3yxgEKAqsxQ+Syjp+seyInw=+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.28.0 h1:j9+03ymgYhPKmeXGk5Zu+cIZOlVzd9Zv7QIiyItjFBU=+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.28.0/go.mod h1:Y5+XiUG4Emn1hTfciPzGPJaSI+RpDts6BnCIir0SLqk=+go.opentelemetry.io/otel/metric v1.28.0 h1:f0HGvSl1KRAU1DLgLGFjrwVyismPlnuU6JD6bOeuA5Q=+go.opentelemetry.io/otel/metric v1.28.0/go.mod h1:Fb1eVBFZmLVTMb6PPohq3TO9IIhUisDsbJoL/+uQW4s=+go.opentelemetry.io/otel/sdk v1.28.0 h1:b9d7hIry8yZsgtbmM0DKyPWMMUMlK9NEKuIG4aBqWyE=+go.opentelemetry.io/otel/sdk v1.28.0/go.mod h1:oYj7ClPUA7Iw3m+r7GeEjz0qckQRJK2B8zjcZEfu7Pg=+go.opentelemetry.io/otel/trace v1.28.0 h1:GhQ9cUuQGmNDd5BTCP2dAvv75RdMxEfTmYejp+lkx9g=+go.opentelemetry.io/otel/trace v1.28.0/go.mod h1:jPyXzNPg6da9+38HEwElrQiHlVMTnVfM3/yv2OlIHaI=+go.opentelemetry.io/proto/otlp v1.3.1 h1:TrMUixzpM0yuc/znrFTP9MMRh8trP93mkCiDVeXrui0=+go.opentelemetry.io/proto/otlp v1.3.1/go.mod h1:0X1WI4de4ZsLrrJNLAQbFeLCm3T7yBkR0XqQ7niQU+8=+go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=+go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=+go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=+golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=+golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=+golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U=+golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI=+golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=+golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=+golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=+golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=+golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=+golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=+golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=+golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k=+golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM=+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=+golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE=+golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w=+google.golang.org/genproto/googleapis/api v0.0.0-20240814211410-ddb44dafa142 h1:wKguEg1hsxI2/L3hUYrpo1RVi48K+uTyzKqprwLXsb8=+google.golang.org/genproto/googleapis/api v0.0.0-20240814211410-ddb44dafa142/go.mod h1:d6be+8HhtEtucleCbxpPW9PA9XwISACu8nvpPqF0BVo=+google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 h1:e7S5W7MGGLaSu8j3YjdezkZ+m1/Nm0uRVRMEMGk26Xs=+google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU=+google.golang.org/grpc v1.67.0 h1:IdH9y6PF5MPSdAntIcpjQ+tXO41pcQsfZV2RxtQgVcw=+google.golang.org/grpc v1.67.0/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA=+google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=+google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=+gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E=+sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY=diff --git a/libs/fleet/backend/handlers/config.go b/libs/fleet/backend/handlers/config.gonew file mode 100644index 0000000000..e4377d164a--- /dev/null+++ b/libs/fleet/backend/handlers/config.go@@ -0,0 +1,43 @@+package handlers++import (+ "log/slog"+ "net/http"++ "cyclops-cs-backend/auth"+)++// ConfigResponse is the payload returned by GET /api/config.+// The frontend uses this to select the correct UI strategy (admin vs customer).+type ConfigResponse struct {+ // Admin is true when the caller is in input.flags.admin_subs (OPA-evaluated).+ // Non-admins get the customer view: infra-only nav (Nodes, Operator events)+ // is hidden in the SPA and the corresponding kubectl-proxy paths are denied+ // server-side by authz.rego.+ Admin bool `json:"admin"`+}++// GetConfig returns per-user feature flags evaluated by OPA.+//+// @Summary Per-user feature flags+// @Description Returns OPA-evaluated feature flags for the authenticated SPA user. `admin` is true when the caller's JWT sub appears in input.flags.admin_subs.+// @Tags config+// @Produce json+// @Success 200 {object} ConfigResponse+// @Failure 401 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/config [get]+func (h Handlers) GetConfig(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ ctx := r.Context()++ isAdmin, err := auth.EvalIsAdmin(ctx, user)+ if err != nil {+ // Fail closed to the most restrictive view, and log so a+ // misconfigured OPA store / provider is visible to operators.+ slog.WarnContext(ctx, "opa: is_admin eval failed; defaulting to non-admin", "err", err)+ isAdmin = false+ }++ writeJSON(w, http.StatusOK, ConfigResponse{Admin: isAdmin})+}diff --git a/libs/fleet/backend/handlers/deprecated.go b/libs/fleet/backend/handlers/deprecated.gonew file mode 100644index 0000000000..2c7cfb576e--- /dev/null+++ b/libs/fleet/backend/handlers/deprecated.go@@ -0,0 +1,8 @@+package handlers++import "net/http"++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")+}diff --git a/libs/fleet/backend/handlers/gateway.go b/libs/fleet/backend/handlers/gateway.gonew file mode 100644index 0000000000..b8b3456b11--- /dev/null+++ b/libs/fleet/backend/handlers/gateway.go@@ -0,0 +1,23 @@+package handlers++import (+ "net/http"+)++// Gateway godoc+//+// @Summary DEPRECATED: Per-pool orchestrator reverse-proxy (CUA-609)+// @Description The per-pool HTTP orchestrator has been deprecated and removed. All pools now use OSGymSandboxClaim CRs exclusively (Path B). This endpoint returns 410 Gone for any request. See CUA-609.+// @Tags gateway+// @Param name path string true "Pool name (DNS-1123 label)"+// @Param path path string false "Upstream path (ignored)"+// @Success 410 {object} ErrorResponse "Orchestrator HTTP layer deprecated (CUA-609)"+// @Router /api/gateway/{name}/{path} [get]+func (h Handlers) Gateway(w http.ResponseWriter, r *http.Request) {+ // CUA-609: The per-pool orchestrator HTTP layer has been removed.+ // Per-pool orchestrators (Deployments in <pool>-orchestrator namespaces)+ // no longer run. All VM operations go through OSGymSandboxClaim CRs.+ // Zero HTTP traffic was confirmed before removal.+ writeErr(w, http.StatusGone,+ "orchestrator HTTP layer deprecated (CUA-609): use OSGymSandboxClaim CRs instead")+}diff --git a/libs/fleet/backend/handlers/handlers.go b/libs/fleet/backend/handlers/handlers.gonew file mode 100644index 0000000000..da320be761--- /dev/null+++ b/libs/fleet/backend/handlers/handlers.go@@ -0,0 +1,120 @@+// Package handlers — REST + reverse-proxy handlers for the cyclops-cs+// backend. Mirrors the constructor + utilities pattern from r33drichards/grt.+package handlers++import (+ "bufio"+ "encoding/json"+ "fmt"+ "net"+ "net/http"+ "regexp"++ "cyclops-cs-backend/auth"+ "cyclops-cs-backend/config"+ "cyclops-cs-backend/keycloak"+ "cyclops-cs-backend/templates"+ "go.opentelemetry.io/otel"+ "go.opentelemetry.io/otel/trace"+)++type Handlers struct {+ Admin *keycloak.Admin+ GatewayCfg config.GatewayConfiguration+ AuthCfg config.AuthConfiguration+ KC config.KeycloakConfiguration++ // Templates is the Redis-backed pool-template store. nil when no+ // Redis is configured — the pool-template handlers then reply 503.+ Templates templates.Store++ // WorkloadAdmin manages per-tenant clients in the workloads realm so+ // OSGym pool VMs can obtain a tenant-scoped OIDC token. nil disables+ // the feature (CreateNamespace then skips OIDC credential provisioning).+ // WorkloadAudience / WorkloadTokenURL are the aud claim and the token+ // endpoint baked into the per-tenant credentials Secret.+ WorkloadAdmin *keycloak.Admin+ WorkloadAudience string+ WorkloadTokenURL string+}++func New(admin *keycloak.Admin, cfg *config.Configuration) Handlers {+ return Handlers{+ Admin: admin,+ GatewayCfg: cfg.Gateway,+ AuthCfg: cfg.Auth,+ KC: cfg.Keycloak,+ }+}++var dnsLabel = regexp.MustCompile(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$`)++func handlerTracer() trace.Tracer {+ return otel.Tracer("cyclops-cs-backend/handlers")+}++func writeJSON(w http.ResponseWriter, status int, v any) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _ = json.NewEncoder(w).Encode(v)+}++func writeErr(w http.ResponseWriter, status int, msg string) {+ writeJSON(w, status, map[string]string{"error": msg})+}++func currentUser(r *http.Request) *auth.User {+ return auth.GetUser(r.Context())+}++// statusCapture wraps http.ResponseWriter to capture the status code written+// by a reverse proxy for post-request metrics recording.+type statusCapture struct {+ http.ResponseWriter+ statusCode int+ written bool+}++func (sc *statusCapture) WriteHeader(code int) {+ if !sc.written {+ sc.statusCode = code+ sc.written = true+ }+ sc.ResponseWriter.WriteHeader(code)+}++func (sc *statusCapture) Write(b []byte) (int, error) {+ if sc.statusCode == 0 {+ sc.statusCode = http.StatusOK+ }+ if !sc.written {+ sc.written = true+ }+ return sc.ResponseWriter.Write(b)+}++// Hijack forwards to the underlying ResponseWriter so httputil.ReverseProxy+// can switch protocols (WebSocket upgrades, e.g. noVNC's /websockify through+// /api/svc). Embedding only exposes the http.ResponseWriter interface methods,+// so without this explicit passthrough every 101 response fails with "can't+// switch protocols using non-Hijacker ResponseWriter".+func (sc *statusCapture) Hijack() (net.Conn, *bufio.ReadWriter, error) {+ hj, ok := sc.ResponseWriter.(http.Hijacker)+ if !ok {+ return nil, nil, fmt.Errorf("underlying ResponseWriter does not implement http.Hijacker")+ }+ if !sc.written {+ // A hijacked connection is a successful upgrade for metrics purposes.+ sc.statusCode = http.StatusSwitchingProtocols+ sc.written = true+ }+ return hj.Hijack()+}++// Flush forwards to the underlying ResponseWriter so streaming upstream+// responses (SSE, chunked) are not buffered by the wrapper.+func (sc *statusCapture) Flush() {+ if f, ok := sc.ResponseWriter.(http.Flusher); ok {+ f.Flush()+ }+}diff --git a/libs/fleet/backend/handlers/health.go b/libs/fleet/backend/handlers/health.gonew file mode 100644index 0000000000..1b1f87e8a4--- /dev/null+++ b/libs/fleet/backend/handlers/health.go@@ -0,0 +1,19 @@+package handlers++import "net/http"++// HealthResponse is the body of GET /healthz.+type HealthResponse struct {+ OK bool `json:"ok"`+}++// GetHealth godoc+//+// @Summary Liveness/readiness probe+// @Tags health+// @Produce json+// @Success 200 {object} HealthResponse+// @Router /healthz [get]+func (h Handlers) GetHealth(w http.ResponseWriter, _ *http.Request) {+ writeJSON(w, http.StatusOK, HealthResponse{OK: true})+}diff --git a/libs/fleet/backend/handlers/k8s.go b/libs/fleet/backend/handlers/k8s.gonew file mode 100644index 0000000000..71258576d0--- /dev/null+++ b/libs/fleet/backend/handlers/k8s.go@@ -0,0 +1,266 @@+package handlers++import (+ "bytes"+ "context"+ "encoding/json"+ "io"+ "log/slog"+ "net/http"+ "net/http/httputil"+ "net/url"+ "os"+ "strings"+ "time"++ "cyclops-cs-backend/auth"+ "cyclops-cs-backend/identity"+ "cyclops-cs-backend/metrics"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/codes"+ "go.opentelemetry.io/otel/trace"+)++// kubectlProxyAddr is the address of the in-pod kubectl-proxy sidecar.+// kubectl proxy authenticates against the K8s API using the pod's+// ServiceAccount; we keep that hop and just add SPA auth in front of it.+func kubectlProxyAddr() string {+ if v := os.Getenv("KUBECTL_PROXY_ADDR"); v != "" {+ return v+ }+ return "http://127.0.0.1:8001"+}++// 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).+// @Tags passthrough+// @Param path path string true "K8s API path"+// @Success 200 {string} string "K8s API response"+// @Failure 401 {object} ErrorResponse+// @Failure 403 {object} ErrorResponse+// @Failure 502 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/k8s/{path} [get]+func (h Handlers) K8s(w http.ResponseWriter, r *http.Request) {+ target, err := url.Parse(kubectlProxyAddr())+ if err != nil {+ writeErr(w, http.StatusInternalServerError, "bad KUBECTL_PROXY_ADDR")+ return+ }+ upstreamPath := "/" + strings.TrimPrefix(r.PathValue("path"), "/")+ ctx, span := handlerTracer().Start(r.Context(), "k8s.proxy", trace.WithAttributes(+ attribute.String("proxy.target", "k8s"),+ attribute.String("http.route", "/api/k8s/{path...}"),+ attribute.String("k8s.path", upstreamPath),+ ))+ defer span.End()++ // 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 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+ rp.Director = func(req *http.Request) {+ origDirector(req)+ req.URL.Path = upstreamPath+ req.URL.RawPath = ""+ req.URL.RawQuery = r.URL.RawQuery+ // kubectl-proxy default --accept-hosts rejects requests whose Host+ // header isn't localhost-ish (existing nginx block worked around+ // this the same way).+ req.Host = "localhost"+ req.Header.Set("Host", "localhost")+ req.Header.Del("Authorization")++ // K8s impersonation headers — the kubectl-proxy ServiceAccount+ // needs the "impersonate" verb on users and groups for this to+ // work. The OIDC username format is "oidc:<sub>" and the group+ // is "oidc:user-<sub>", matching the Keycloak OIDC provider+ // config on the K3s apiserver. Capsule intercepts these to+ // enforce per-tenant namespace scoping.+ if user != nil && user.ID != "" {+ ctx := req.Context()+ req.Header.Set("Impersonate-User", identity.ImpersonateUser(ctx, user.ID))+ req.Header.Set("Impersonate-Group", identity.ImpersonateGroup(ctx, user.ID))+ }+ }++ rw := &statusCapture{ResponseWriter: w}+ rp.ErrorHandler = func(rw http.ResponseWriter, _ *http.Request, err error) {+ span.RecordError(err)+ span.SetStatus(codes.Error, "kubectl-proxy unavailable")+ slog.Warn("k8s proxy error", "path", upstreamPath, "err", err)+ http.Error(rw, "kubectl-proxy unavailable", http.StatusBadGateway)+ }+ start := time.Now()+ rp.ServeHTTP(rw, r.WithContext(ctx))+ span.SetAttributes(attribute.Int("http.status_code", rw.statusCode))+ 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 !strings.Contains(r.PathValue("path"), "osgymworkspacepools") || 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)+}++// macosPoolNeedsAdmin returns true if r is a write to an osgymworkspacepools+// 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 !strings.Contains(r.PathValue("path"), "osgymworkspacepools") || 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 an OSGymWorkspacePool CR body opts into the+// macOS runtime — via spec.template.runtime=macos, or (defence in depth) the+// macOS-only runtimeClass / nodeSelector that a macOS pod carries.+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["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+}++// Orch godoc+//+// @Summary SPA-authenticated proxy to a per-namespace orchestrator service+// @Description Resolves <service>.<namespace>.svc.cluster.local at request time (in-cluster DNS). The caller must hold RBAC in {namespace} (verified via an impersonated RoleBinding probe); OPA additionally validates that namespace and service look like DNS-1123 labels.+// @Tags passthrough+// @Param namespace path string true "Namespace (DNS-1123 label)"+// @Param service path string true "Service name (DNS-1123 label)"+// @Param path path string true "Upstream path"+// @Success 200 {string} string "Upstream response"+// @Failure 400 {object} ErrorResponse+// @Failure 401 {object} ErrorResponse+// @Failure 403 {object} ErrorResponse+// @Failure 502 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/orch/{namespace}/{service}/{path} [get]+func (h Handlers) Orch(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }+ ns := r.PathValue("namespace")+ svc := r.PathValue("service")+ if !dnsLabel.MatchString(ns) || !dnsLabel.MatchString(svc) {+ 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+ }+ upstreamPath := "/" + strings.TrimPrefix(r.PathValue("path"), "/")+ host := svc + "." + ns + "." + h.GatewayCfg.ClusterDomain+ target := &url.URL{Scheme: h.GatewayCfg.Scheme, Host: host + ":" + h.GatewayCfg.Port}+ ctx, span := handlerTracer().Start(r.Context(), "orch.proxy", trace.WithAttributes(+ attribute.String("proxy.target", "orch"),+ attribute.String("http.route", "/api/orch/{namespace}/{service}/{path...}"),+ attribute.String("k8s.namespace", ns),+ attribute.String("k8s.service", svc),+ attribute.String("http.target_path", upstreamPath),+ ))+ defer span.End()++ rp := httputil.NewSingleHostReverseProxy(target)+ origDirector := rp.Director+ rp.Director = func(req *http.Request) {+ origDirector(req)+ req.URL.Path = upstreamPath+ req.URL.RawPath = ""+ req.URL.RawQuery = r.URL.RawQuery+ req.Host = target.Host+ req.Header.Del("Authorization")+ }+ rw := &statusCapture{ResponseWriter: w}+ rp.ErrorHandler = func(rw http.ResponseWriter, _ *http.Request, err error) {+ span.RecordError(err)+ span.SetStatus(codes.Error, "upstream unavailable")+ slog.Warn("orch proxy error", "host", host, "path", upstreamPath, "err", err)+ http.Error(rw, "upstream unavailable", http.StatusBadGateway)+ }+ start := time.Now()+ rp.ServeHTTP(rw, r.WithContext(ctx))+ span.SetAttributes(attribute.Int("http.status_code", rw.statusCode))+ metrics.RecordUpstreamProxy("orch", rw.statusCode, time.Since(start))+}diff --git a/libs/fleet/backend/handlers/k8s_test.go b/libs/fleet/backend/handlers/k8s_test.gonew file mode 100644index 0000000000..f128aae79a--- /dev/null+++ b/libs/fleet/backend/handlers/k8s_test.go@@ -0,0 +1,279 @@+package handlers++import (+ "bytes"+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "testing"++ "cyclops-cs-backend/auth"+ "go.opentelemetry.io/otel"+ sdktrace "go.opentelemetry.io/otel/sdk/trace"+ "go.opentelemetry.io/otel/sdk/trace/tracetest"+)++func TestK8sProxy_ImpersonationHeaders(t *testing.T) {+ var receivedHeaders http.Header+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ receivedHeaders = r.Header.Clone()+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"kind":"PodList","items":[]}`))+ }))+ defer upstream.Close()+ t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)++ h := Handlers{}++ r := httptest.NewRequest(http.MethodGet, "/api/k8s/api/v1/namespaces/foo/pods", nil)+ r.SetPathValue("path", "api/v1/namespaces/foo/pods")+ r = withUser(r, &auth.User{ID: "user-abc-123"})+ w := httptest.NewRecorder()++ h.K8s(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())+ }++ // Verify impersonation headers were added.+ if got := receivedHeaders.Get("Impersonate-User"); got != "oidc:user-abc-123" {+ t.Fatalf("Impersonate-User = %q, want %q", got, "oidc:user-abc-123")+ }+ if got := receivedHeaders.Get("Impersonate-Group"); got != "oidc:cyclops-cs-tenants" {+ t.Fatalf("Impersonate-Group = %q, want %q", got, "oidc:cyclops-cs-tenants")+ }++ // Authorization header must be stripped.+ if got := receivedHeaders.Get("Authorization"); got != "" {+ t.Fatalf("Authorization header should be stripped, got %q", got)+ }++ // Note: Go's HTTP client moves Host into r.Host, so checking the+ // header map is unreliable. The Director sets both req.Host and+ // the "Host" header; the important thing is that the proxy reaches+ // our test server (which accepts any host) and the Director logic+ // is exercised.+}++func TestK8sProxy_NoUser(t *testing.T) {+ var receivedHeaders http.Header+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ receivedHeaders = r.Header.Clone()+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"kind":"PodList","items":[]}`))+ }))+ defer upstream.Close()+ t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)++ h := Handlers{}+ r := httptest.NewRequest(http.MethodGet, "/api/k8s/api/v1/namespaces/foo/pods", nil)+ r.SetPathValue("path", "api/v1/namespaces/foo/pods")+ // No user context — backward compat: no impersonation headers.+ w := httptest.NewRecorder()++ h.K8s(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())+ }++ if got := receivedHeaders.Get("Impersonate-User"); got != "" {+ t.Fatalf("Impersonate-User should be absent, got %q", got)+ }+ if got := receivedHeaders.Get("Impersonate-Group"); got != "" {+ t.Fatalf("Impersonate-Group should be absent, got %q", got)+ }+}++func TestK8sProxy_ForwardsPath(t *testing.T) {+ cases := []struct {+ name string+ pathValue string+ wantPath string+ wantQuery string+ queryParam string+ }{+ {+ name: "simple namespaced path",+ pathValue: "api/v1/namespaces/foo/pods",+ wantPath: "/api/v1/namespaces/foo/pods",+ },+ {+ name: "cluster-wide path",+ pathValue: "api/v1/nodes",+ wantPath: "/api/v1/nodes",+ },+ {+ name: "CRD path",+ pathValue: "apis/cua.ai/v1/osgymworkspacepools",+ wantPath: "/apis/cua.ai/v1/osgymworkspacepools",+ },+ {+ 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",+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ var receivedPath string+ var receivedQuery string+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ receivedPath = r.URL.Path+ receivedQuery = r.URL.RawQuery+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))+ }))+ defer upstream.Close()+ t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)++ h := Handlers{}+ target := "/api/k8s/" + tc.pathValue+ if tc.queryParam != "" {+ target += "?" + tc.queryParam+ }+ r := httptest.NewRequest(http.MethodGet, target, nil)+ r.SetPathValue("path", tc.pathValue)+ w := httptest.NewRecorder()++ h.K8s(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())+ }+ if receivedPath != tc.wantPath {+ t.Fatalf("upstream path = %q, want %q", receivedPath, tc.wantPath)+ }+ if tc.wantQuery != "" && receivedQuery != tc.wantQuery {+ t.Fatalf("upstream query = %q, want %q", receivedQuery, tc.wantQuery)+ }+ })+ }+}++func TestK8sProxy_ResponseBody(t *testing.T) {+ // Verify the proxy faithfully forwards the upstream response body.+ wantBody := `{"kind":"PodList","items":[{"metadata":{"name":"pod-1"}}]}`+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(wantBody))+ }))+ defer upstream.Close()+ t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)++ h := Handlers{}+ r := httptest.NewRequest(http.MethodGet, "/api/k8s/api/v1/namespaces/test/pods", nil)+ r.SetPathValue("path", "api/v1/namespaces/test/pods")+ w := httptest.NewRecorder()++ h.K8s(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)+ }++ gotBody, _ := io.ReadAll(w.Result().Body)+ var got, want map[string]any+ if err := json.Unmarshal(gotBody, &got); err != nil {+ t.Fatalf("response not JSON: %v", err)+ }+ if err := json.Unmarshal([]byte(wantBody), &want); err != nil {+ t.Fatalf("want not JSON: %v", err)+ }+ if got["kind"] != want["kind"] {+ t.Fatalf("kind = %v, want %v", got["kind"], want["kind"])+ }+}++func TestK8sProxy_CreatesTracingSpan(t *testing.T) {+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"kind":"PodList","items":[]}`))+ }))+ defer upstream.Close()+ t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)++ recorder := tracetest.NewSpanRecorder()+ tp := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder))+ otel.SetTracerProvider(tp)++ ctx, root := tp.Tracer("test").Start(context.Background(), "request")++ h := Handlers{}+ r := httptest.NewRequest(http.MethodGet, "/api/k8s/api/v1/namespaces/foo/pods", nil).WithContext(ctx)+ r.SetPathValue("path", "api/v1/namespaces/foo/pods")+ r = withUser(r, &auth.User{ID: "user-abc-123"})+ w := httptest.NewRecorder()++ h.K8s(w, r)+ root.End()++ var found bool+ for _, span := range recorder.Ended() {+ if span.Name() != "k8s.proxy" {+ continue+ }+ found = true+ if got, want := span.Parent().SpanID(), root.SpanContext().SpanID(); got != want {+ t.Fatalf("parent span id = %s, want %s", got, want)+ }+ }+ if !found {+ t.Fatal("expected k8s.proxy span")+ }+}++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)+ }+ })+ }+}diff --git a/libs/fleet/backend/handlers/keys.go b/libs/fleet/backend/handlers/keys.gonew file mode 100644index 0000000000..2e6fe560cd--- /dev/null+++ b/libs/fleet/backend/handlers/keys.go@@ -0,0 +1,135 @@+package handlers++import (+ "encoding/json"+ "net/http"++ "cyclops-cs-backend/keycloak"+)++// CreateKeyRequest is the body for POST /api/keys.+type CreateKeyRequest struct {+ Name string `json:"name" example:"ci-prod"`+ Namespace string `json:"namespace" example:"test-pool"`+}++// CreateKeyResponse is what the SPA shows once after a successful create.+// `client_secret` is irretrievable after this response — the SPA must+// surface it to the user immediately and forget it.+type CreateKeyResponse struct {+ ClientID string `json:"client_id"`+ ClientSecret string `json:"client_secret"`+ TokenURL string `json:"token_url"`+ Name string `json:"name"`+ Namespace string `json:"namespace"`+}++// ListKeysResponse wraps the keys list — keeps room to add pagination+// metadata later without a breaking change to the client.+type ListKeysResponse struct {+ Keys []keycloak.KeyClient `json:"keys"`+}++// ErrorResponse is the shape every 4xx/5xx body uses.+type ErrorResponse struct {+ Error string `json:"error"`+}++// CreateKey godoc+//+// @Summary Create a new API key+// @Description Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is shown exactly once.+// @Tags keys+// @Accept json+// @Produce json+// @Param body body CreateKeyRequest true "Key parameters"+// @Success 201 {object} CreateKeyResponse+// @Failure 400 {object} ErrorResponse+// @Failure 401 {object} ErrorResponse+// @Failure 403 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/keys [post]+func (h Handlers) CreateKey(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }+ var req CreateKeyRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeErr(w, http.StatusBadRequest, "invalid body")+ return+ }+ if req.Name == "" {+ writeErr(w, http.StatusBadRequest, "name is required")+ return+ }+ if !dnsLabel.MatchString(req.Namespace) || len(req.Namespace) > 63 {+ writeErr(w, http.StatusBadRequest, "namespace must be a DNS-1123 label")+ return+ }+ cid, secret, _, err := h.Admin.CreateKeyClient(r.Context(), req.Name, req.Namespace, user.ID)+ if err != nil {+ writeErr(w, http.StatusInternalServerError, "keycloak: "+err.Error())+ return+ }+ writeJSON(w, http.StatusCreated, CreateKeyResponse{+ ClientID: cid,+ ClientSecret: secret,+ TokenURL: h.KC.TokenURL,+ Name: req.Name,+ Namespace: req.Namespace,+ })+}++// ListKeys godoc+//+// @Summary List the calling user's API keys+// @Tags keys+// @Produce json+// @Success 200 {object} ListKeysResponse+// @Failure 401 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/keys [get]+func (h Handlers) ListKeys(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }+ keys, err := h.Admin.ListKeyClients(r.Context(), user.ID)+ if err != nil {+ writeErr(w, http.StatusInternalServerError, "keycloak: "+err.Error())+ return+ }+ writeJSON(w, http.StatusOK, ListKeysResponse{Keys: keys})+}++// DeleteKey godoc+//+// @Summary Revoke an API key by Keycloak client UUID+// @Tags keys+// @Produce json+// @Param id path string true "Keycloak client UUID"+// @Success 204+// @Failure 401 {object} ErrorResponse+// @Failure 403 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/keys/{id} [delete]+func (h Handlers) DeleteKey(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }+ id := r.PathValue("id")+ if id == "" {+ writeErr(w, http.StatusBadRequest, "id is required")+ return+ }+ if err := h.Admin.DeleteKeyClient(r.Context(), id, user.ID); err != nil {+ writeErr(w, http.StatusForbidden, err.Error())+ return+ }+ w.WriteHeader(http.StatusNoContent)+}diff --git a/libs/fleet/backend/handlers/namespaces.go b/libs/fleet/backend/handlers/namespaces.gonew file mode 100644index 0000000000..56ff1d7859--- /dev/null+++ b/libs/fleet/backend/handlers/namespaces.go@@ -0,0 +1,535 @@+package handlers++import (+ "bytes"+ "context"+ "crypto/tls"+ "crypto/x509"+ "encoding/json"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "net/url"+ "os"+ "strings"+ "sync"+ "time"++ "cyclops-cs-backend/identity"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/codes"+ "go.opentelemetry.io/otel/trace"+)++// ── Request / Response types ───────────────────────────────────────────++// CreateNamespaceRequest is the body for POST /api/namespaces.+type CreateNamespaceRequest struct {+ Name string `json:"name" example:"my-workspace"`+}++// NamespaceResponse is a single namespace entry returned by the API.+type NamespaceResponse struct {+ Name string `json:"name"`+ Status string `json:"status"`+ CreatedAt string `json:"createdAt"`+ Labels map[string]string `json:"labels"`+}++// ── Impersonation helper ───────────────────────────────────────────────++// k8sImpersonate performs a K8s API request on behalf of the authenticated+// user. Production routes this through Capsule Proxy for Tenant filtering;+// environments without Capsule Proxy fall back to the direct apiserver.+//+// The OIDC username format is "oidc:<sub>" and the shared Capsule gate group+// is "oidc:cyclops-cs-tenants", matching the K3s OIDC configuration.++var (+ k8sClientOnce sync.Once+ k8sClient *http.Client+ k8sAPIServer string+ // k8sDirectAPIServer always targets the in-cluster apiserver. The+ // impersonated path may instead use Capsule Proxy for tenant filtering.+ k8sDirectAPIServer string+ k8sSAToken string+)++// overrideK8sClient is used by tests to inject a fake K8s API server.+// It sets the client AND marks the Once as done so initK8sClient() is a no-op.+func overrideK8sClient(client *http.Client, apiServer, saToken string) {+ overrideK8sClientTargets(client, apiServer, apiServer, saToken)+}++func overrideK8sClientTargets(+ client *http.Client, impersonatedServer, directServer, saToken string,+) {+ k8sClientOnce.Do(func() {}) // exhaust the Once+ k8sClient = client+ k8sAPIServer = impersonatedServer+ k8sDirectAPIServer = directServer+ k8sSAToken = saToken+}++func initK8sClient() {+ k8sClientOnce.Do(func() {+ // Direct in-cluster apiserver address. ServiceAccount-only control-plane+ // operations must not depend on Capsule Proxy behavior.+ host := os.Getenv("KUBERNETES_SERVICE_HOST")+ port := os.Getenv("KUBERNETES_SERVICE_PORT")+ if host == "" {+ host = "kubernetes.default.svc"+ }+ if port == "" {+ port = "443"+ }+ if strings.Contains(host, ":") {+ host = "[" + host + "]"+ }+ k8sDirectAPIServer = fmt.Sprintf("https://%s:%s", host, port)++ // Capsule Proxy — filters list responses by Tenant ownership.+ // Falls back to direct K8s API if CAPSULE_PROXY_ADDR is not set.+ if proxyAddr := os.Getenv("CAPSULE_PROXY_ADDR"); proxyAddr != "" {+ k8sAPIServer = proxyAddr+ slog.Info("k8sImpersonate: using Capsule Proxy", "addr", proxyAddr)+ } else {+ k8sAPIServer = k8sDirectAPIServer+ slog.Info("k8sImpersonate: using K8s API directly", "addr", k8sAPIServer)+ }++ // Load SA token+ tokenBytes, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token")+ if err != nil {+ slog.Warn("k8sImpersonate: cannot read SA token", "err", err)+ return+ }+ k8sSAToken = strings.TrimSpace(string(tokenBytes))++ // Load CA cert+ caCert, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt")+ if err != nil {+ slog.Warn("k8sImpersonate: cannot read CA cert, using system pool", "err", err)+ k8sClient = &http.Client{Timeout: 15 * time.Second}+ return+ }+ pool := x509.NewCertPool()+ pool.AppendCertsFromPEM(caCert)+ k8sClient = &http.Client{+ Timeout: 15 * time.Second,+ Transport: &http.Transport{+ TLSClientConfig: &tls.Config{RootCAs: pool},+ },+ }+ })+}++func (h Handlers) k8sImpersonate(+ ctx context.Context, method, path string, body io.Reader, userSub string,+) (*http.Response, error) {+ if k8sClient == nil {+ initK8sClient()+ }+ if k8sClient == nil {+ return nil, fmt.Errorf("k8s client not initialised (missing SA token)")+ }++ target := k8sAPIServer + path+ req, err := http.NewRequestWithContext(ctx, method, target, body)+ if err != nil {+ return nil, fmt.Errorf("build request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json")++ // Authenticate as the pod's ServiceAccount+ req.Header.Set("Authorization", "Bearer "+k8sSAToken)++ // K8s impersonation headers — the SA needs the "impersonate" verb+ // on users and groups (granted by cyclops-cs-impersonator ClusterRole).+ // Prefixes resolve from OpenFeature (see package identity) so Tenant+ // provisioning, impersonation, and apiserver flags stay aligned.+ req.Header.Set("Impersonate-User", identity.ImpersonateUser(ctx, userSub))+ req.Header.Set("Impersonate-Group", identity.ImpersonateGroup(ctx, userSub))++ return k8sClient.Do(req)+}++// Adoption-wait tuning. Capsule normally adopts within a second or two; the+// cap just keeps a wedged Capsule controller from stalling namespace creation.+const (+ adoptionWaitTimeout = 10 * time.Second+ adoptionWaitStep = 500 * time.Millisecond+)++// waitForNamespaceAdoption polls a RoleBinding LIST in the new namespace as+// the impersonated user until it succeeds (Capsule's owner RoleBindings are in+// place) or the timeout elapses. RoleBinding list is the probe because it is+// only authorized by the `admin` RoleBinding Capsule creates on adoption — the+// very thing being waited for. (A GET on the namespace itself does NOT work:+// the capsule-tenant-cluster-resources ClusterRole grants namespaces get/list+// cluster-wide to system:authenticated, so that probe succeeds instantly and+// gates nothing.) Best-effort by design: failures are logged, never+// surfaced — the namespace was created either way.+func (h Handlers) waitForNamespaceAdoption(ctx context.Context, name, userSub string) {+ adoptionCtx, cancel := context.WithTimeout(ctx, adoptionWaitTimeout)+ defer cancel()+ for {+ resp, err := h.k8sImpersonate(adoptionCtx, "GET",+ "/apis/rbac.authorization.k8s.io/v1/namespaces/"+url.PathEscape(name)+"/rolebindings?limit=1",+ nil, userSub)+ if err == nil {+ _, _ = io.Copy(io.Discard, resp.Body)+ resp.Body.Close()+ if resp.StatusCode >= 200 && resp.StatusCode < 300 {+ return+ }+ }+ if adoptionCtx.Err() != nil {+ slog.Warn("namespace create: adoption wait timed out; returning anyway",+ "namespace", name)+ return+ }+ select {+ case <-time.After(adoptionWaitStep):+ case <-adoptionCtx.Done():+ return+ }+ }+}++// ── Handlers ───────────────────────────────────────────────────────────++// ListNamespaces godoc+//+// @Summary List the calling user's namespaces+// @Description Returns namespaces owned by the caller's Capsule Tenant. The list is scoped by a capsule.clastix.io/tenant=<tenant> label selector built from the authenticated subject, so it stays fail-closed even when Capsule Proxy isn't filtering.+// @Tags namespaces+// @Produce json+// @Success 200 {array} NamespaceResponse+// @Failure 401 {object} ErrorResponse+// @Failure 502 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/namespaces [get]+func (h Handlers) ListNamespaces(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }+ ctx, span := handlerTracer().Start(r.Context(), "namespaces.list", trace.WithAttributes(+ attribute.String("http.route", "/api/namespaces"),+ attribute.String("user.id", user.ID),+ ))+ defer span.End()++ // Scope the list to the caller's own Tenant. Every namespace owned by a+ // Tenant carries capsule.clastix.io/tenant=<tenant> (set on create — see+ // CreateNamespace — and enforced by Capsule). Selecting on it makes this+ // fail-closed: even if Capsule Proxy isn't filtering (e.g. while+ // CapsuleConfiguration.userGroups is being reconciled, or right after a+ // capsule-proxy restart with a cold cache), the apiserver only returns the+ // caller's namespaces. The personal Tenant name follows the "user-<sub>"+ // convention, and the selector is derived from the authenticated subject,+ // so a caller can never widen it to another tenant.+ selector := "capsule.clastix.io/tenant=" + identity.PersonalGroup(ctx, user.ID)+ path := "/api/v1/namespaces?labelSelector=" + url.QueryEscape(selector)+ resp, err := h.k8sImpersonate(ctx, "GET", path, nil, user.ID)+ if err != nil {+ span.RecordError(err)+ span.SetStatus(codes.Error, "namespace list request failed")+ slog.Warn("namespace list: k8s request failed", "err", err)+ writeErr(w, http.StatusBadGateway, "kubectl-proxy unavailable")+ return+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ body, _ := io.ReadAll(resp.Body)+ span.SetStatus(codes.Error, "namespace list returned non-200")+ span.SetAttributes(attribute.Int("http.status_code", resp.StatusCode))+ slog.Warn("namespace list: k8s error", "status", resp.StatusCode, "body", string(body))+ writeErr(w, resp.StatusCode, "k8s: "+string(body))+ return+ }++ // Parse K8s NamespaceList.+ var nsList struct {+ Items []struct {+ Metadata struct {+ Name string `json:"name"`+ Labels map[string]string `json:"labels"`+ CreationTimestamp string `json:"creationTimestamp"`+ } `json:"metadata"`+ Status struct {+ Phase string `json:"phase"`+ } `json:"status"`+ } `json:"items"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&nsList); err != nil {+ span.RecordError(err)+ span.SetStatus(codes.Error, "namespace list decode failed")+ slog.Warn("namespace list: decode error", "err", err)+ writeErr(w, http.StatusBadGateway, "bad response from k8s")+ return+ }++ out := make([]NamespaceResponse, 0, len(nsList.Items))+ for _, ns := range nsList.Items {+ out = append(out, NamespaceResponse{+ Name: ns.Metadata.Name,+ Status: ns.Status.Phase,+ CreatedAt: ns.Metadata.CreationTimestamp,+ Labels: ns.Metadata.Labels,+ })+ }+ span.SetAttributes(+ attribute.Int("http.status_code", http.StatusOK),+ attribute.Int("namespaces.count", len(out)),+ )+ writeJSON(w, http.StatusOK, out)+}++// CreateNamespace godoc+//+// @Summary Create a namespace for the calling user+// @Description Creates a K8s namespace via impersonation. Capsule's webhook intercepts the creation and assigns it to the user's Tenant.+// @Tags namespaces+// @Accept json+// @Produce json+// @Param body body CreateNamespaceRequest true "Namespace parameters"+// @Success 201 {object} NamespaceResponse+// @Failure 400 {object} ErrorResponse+// @Failure 401 {object} ErrorResponse+// @Failure 409 {object} ErrorResponse+// @Failure 502 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/namespaces [post]+func (h Handlers) CreateNamespace(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil || user.ID == "" {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }++ var req CreateNamespaceRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeErr(w, http.StatusBadRequest, "invalid body")+ return+ }+ if req.Name == "" {+ writeErr(w, http.StatusBadRequest, "name is required")+ return+ }+ if !dnsLabel.MatchString(req.Name) || len(req.Name) > 63 {+ writeErr(w, http.StatusBadRequest, "name must be a DNS-1123 label (lowercase alphanumeric + dashes, max 63 chars)")+ return+ }+ ctx, span := handlerTracer().Start(r.Context(), "namespaces.create", trace.WithAttributes(+ attribute.String("http.route", "/api/namespaces"),+ attribute.String("user.id", user.ID),+ attribute.String("k8s.namespace", req.Name),+ ))+ defer span.End()++ // Tenant provisioning is just-in-time so a freshly authenticated user can+ // create their first namespace without waiting for a separate reconciler.+ // This request runs as the backend ServiceAccount (not as the user) and+ // fails closed if an existing Tenant has unexpected ownership or roles.+ tenantName, err := h.ensurePersonalTenant(ctx, user.ID)+ if err != nil {+ span.RecordError(err)+ span.SetStatus(codes.Error, "personal tenant ensure failed")+ slog.Warn("namespace create: personal tenant ensure failed", "err", err)+ writeErr(w, http.StatusBadGateway, "could not ensure personal tenant")+ return+ }++ // Build K8s Namespace object with Capsule tenant label.+ // The label tells Capsule which Tenant owns this namespace.+ // The prefix resolves from OpenFeature through the same identity helper used+ // above, so the Tenant and namespace label cannot drift.+ nsObj := map[string]interface{}{+ "apiVersion": "v1",+ "kind": "Namespace",+ "metadata": map[string]interface{}{+ "name": req.Name,+ "labels": map[string]string{+ "capsule.clastix.io/tenant": tenantName,+ },+ },+ }+ body, err := json.Marshal(nsObj)+ if err != nil {+ span.RecordError(err)+ span.SetStatus(codes.Error, "namespace create marshal failed")+ writeErr(w, http.StatusInternalServerError, "marshal error")+ return+ }++ // Capsule's admission webhook observes Tenants through an informer cache.+ // Immediately after first-use Tenant creation, that cache can briefly lag+ // both the object and its status.owners update. Retry only the exact Capsule+ // missing-Tenant 500 and non-owned-Tenant 400; every other transport or+ // admission failure is returned immediately.+ retryCtx, cancelRetry := context.WithTimeout(ctx, tenantInformerWaitTimeout)+ defer cancelRetry()+ var respStatus int+ var respBody []byte+ for {+ resp, requestErr := h.k8sImpersonate(+ retryCtx, "POST", "/api/v1/namespaces", bytes.NewReader(body), user.ID,+ )+ if requestErr != nil {+ span.RecordError(requestErr)+ span.SetStatus(codes.Error, "namespace create request failed")+ slog.Warn("namespace create: k8s request failed", "err", requestErr)+ writeErr(w, http.StatusBadGateway, "kubectl-proxy unavailable")+ return+ }+ respStatus = resp.StatusCode+ respBody, err = readBoundedK8sBody(resp.Body)+ resp.Body.Close()+ if err != nil {+ span.RecordError(err)+ span.SetStatus(codes.Error, "namespace create response failed")+ writeErr(w, http.StatusBadGateway, "bad response from k8s")+ return+ }+ if !isPersonalTenantAdmissionCacheLag(respStatus, respBody, tenantName) {+ break+ }+ select {+ case <-time.After(tenantInformerWaitStep):+ case <-retryCtx.Done():+ span.RecordError(retryCtx.Err())+ span.SetStatus(codes.Error, "namespace create cancelled during tenant readiness wait")+ writeErr(w, http.StatusBadGateway, "namespace create cancelled")+ return+ }+ }++ if respStatus == http.StatusConflict {+ span.SetAttributes(attribute.Int("http.status_code", http.StatusConflict))+ writeErr(w, http.StatusConflict, "namespace already exists")+ return+ }+ if respStatus != http.StatusCreated {+ span.SetStatus(codes.Error, "namespace create returned non-201")+ span.SetAttributes(attribute.Int("http.status_code", respStatus))+ slog.Warn("namespace create: k8s error", "status", respStatus, "body", string(respBody))+ writeErr(w, respStatus, "k8s: "+string(respBody))+ return+ }++ // Wait for Capsule to adopt the namespace before returning, so callers can+ // immediately create resources in it. Adoption is asynchronous: Capsule's+ // controller sets the Tenant ownerReference and creates the owner+ // RoleBindings a moment after the namespace exists. Until those bindings+ // land, the user has NO permissions inside the namespace and an immediate+ // follow-up (e.g. the dashboard's pool create) races into a 403. A GET on+ // the namespace as the impersonated user is a zero-coupling adoption probe:+ // it only succeeds once the RoleBindings exist — the same instant any other+ // in-namespace call becomes authorized. Best-effort: on timeout we still+ // return 201 (the namespace exists; adoption is merely late).+ h.waitForNamespaceAdoption(ctx, req.Name, user.ID)++ // Best-effort: provision the tenant's workload-OIDC credentials into the+ // new namespace so OSGym pool VMs here can mint a tenant-scoped OIDC+ // token (see provisionWorkloadOIDC; no-op when the feature is disabled).+ h.provisionWorkloadOIDC(ctx, user.ID, req.Name)++ // Parse the created namespace.+ var created struct {+ Metadata struct {+ Name string `json:"name"`+ Labels map[string]string `json:"labels"`+ CreationTimestamp string `json:"creationTimestamp"`+ } `json:"metadata"`+ Status struct {+ Phase string `json:"phase"`+ } `json:"status"`+ }+ if err := json.Unmarshal(respBody, &created); err != nil {+ span.SetAttributes(attribute.Int("http.status_code", http.StatusCreated))+ // Creation succeeded but response parsing failed — still 201.+ writeJSON(w, http.StatusCreated, NamespaceResponse{Name: req.Name, Status: "Active"})+ return+ }+ span.SetAttributes(attribute.Int("http.status_code", http.StatusCreated))+ writeJSON(w, http.StatusCreated, NamespaceResponse{+ Name: created.Metadata.Name,+ Status: created.Status.Phase,+ CreatedAt: created.Metadata.CreationTimestamp,+ Labels: created.Metadata.Labels,+ })+}++// DeleteNamespace godoc+//+// @Summary Delete a namespace owned by the calling user+// @Description Deletes a K8s namespace via impersonation. Capsule blocks deletion if the namespace doesn't belong to the user's Tenant.+// @Tags namespaces+// @Param name path string true "Namespace name"+// @Success 204+// @Failure 400 {object} ErrorResponse+// @Failure 401 {object} ErrorResponse+// @Failure 403 {object} ErrorResponse+// @Failure 404 {object} ErrorResponse+// @Failure 502 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/namespaces/{name} [delete]+func (h Handlers) DeleteNamespace(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }++ name := r.PathValue("name")+ if name == "" {+ writeErr(w, http.StatusBadRequest, "name is required")+ return+ }+ if !dnsLabel.MatchString(name) || len(name) > 63 {+ writeErr(w, http.StatusBadRequest, "invalid namespace name")+ return+ }+ ctx, span := handlerTracer().Start(r.Context(), "namespaces.delete", trace.WithAttributes(+ attribute.String("http.route", "/api/namespaces/{name}"),+ attribute.String("user.id", user.ID),+ attribute.String("k8s.namespace", name),+ ))+ defer span.End()++ resp, err := h.k8sImpersonate(ctx, "DELETE", "/api/v1/namespaces/"+name, nil, user.ID)+ if err != nil {+ span.RecordError(err)+ span.SetStatus(codes.Error, "namespace delete request failed")+ slog.Warn("namespace delete: k8s request failed", "err", err)+ writeErr(w, http.StatusBadGateway, "kubectl-proxy unavailable")+ return+ }+ defer resp.Body.Close()++ if resp.StatusCode == http.StatusNotFound {+ span.SetAttributes(attribute.Int("http.status_code", http.StatusNotFound))+ writeErr(w, http.StatusNotFound, "namespace not found")+ return+ }+ if resp.StatusCode == http.StatusForbidden {+ span.SetAttributes(attribute.Int("http.status_code", http.StatusForbidden))+ writeErr(w, http.StatusForbidden, "not allowed to delete this namespace")+ return+ }+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {+ body, _ := io.ReadAll(resp.Body)+ span.SetStatus(codes.Error, "namespace delete returned unexpected status")+ span.SetAttributes(attribute.Int("http.status_code", resp.StatusCode))+ slog.Warn("namespace delete: k8s error", "status", resp.StatusCode, "body", string(body))+ writeErr(w, resp.StatusCode, "k8s: "+string(body))+ return+ }+ span.SetAttributes(attribute.Int("http.status_code", http.StatusNoContent))+ w.WriteHeader(http.StatusNoContent)+}diff --git a/libs/fleet/backend/handlers/namespaces_test.go b/libs/fleet/backend/handlers/namespaces_test.gonew file mode 100644index 0000000000..433118082b--- /dev/null+++ b/libs/fleet/backend/handlers/namespaces_test.go@@ -0,0 +1,468 @@+package handlers++import (+ "bytes"+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "testing"++ "cyclops-cs-backend/auth"+ "go.opentelemetry.io/otel"+ sdktrace "go.opentelemetry.io/otel/sdk/trace"+ "go.opentelemetry.io/otel/sdk/trace/tracetest"+)++// withUser stamps a *auth.User on the request context the same way+// TokenAuthMiddleware does in production.+func withUser(r *http.Request, u *auth.User) *http.Request {+ return r.WithContext(context.WithValue(r.Context(), auth.UserKey, u))+}++// fakeK8sProxy returns an httptest.Server that records every request it+// receives (most-recent also exposed via the flat fields) and replies with the+// canned status/body. The caller can inspect recorded headers and path after+// the handler runs.+type recordedReq struct {+ method string+ path string+ rawQuery string+ headers http.Header+ body []byte+}++type fakeK8s struct {+ server *httptest.Server++ // recorded from the last request+ method string+ path string+ rawQuery string+ headers http.Header+ body []byte++ // every request, in order+ requests []recordedReq+}++func newFakeK8s(status int, respBody string) *fakeK8s {+ return newFakeK8sHandler(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(status)+ _, _ = w.Write([]byte(respBody))+ })+}++func newFakeK8sHandler(handler http.HandlerFunc) *fakeK8s {+ fk := &fakeK8s{}+ fk.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ fk.method = r.Method+ fk.path = r.URL.Path+ fk.rawQuery = r.URL.RawQuery+ fk.headers = r.Header.Clone()+ fk.body, _ = io.ReadAll(r.Body)+ r.Body = io.NopCloser(bytes.NewReader(fk.body))+ fk.requests = append(fk.requests, recordedReq{+ method: fk.method,+ path: fk.path,+ rawQuery: fk.rawQuery,+ headers: fk.headers,+ body: fk.body,+ })+ handler(w, r)+ }))+ return fk+}++// nsListResponse builds a minimal K8s NamespaceList JSON.+func nsListResponse(names ...string) string {+ type nsMeta struct {+ Name string `json:"name"`+ Labels map[string]string `json:"labels"`+ CreationTimestamp string `json:"creationTimestamp"`+ }+ type nsStatus struct {+ Phase string `json:"phase"`+ }+ type nsItem struct {+ Metadata nsMeta `json:"metadata"`+ Status nsStatus `json:"status"`+ }+ items := make([]nsItem, 0, len(names))+ for _, n := range names {+ items = append(items, nsItem{+ Metadata: nsMeta{Name: n, Labels: map[string]string{}, CreationTimestamp: "2026-05-28T00:00:00Z"},+ Status: nsStatus{Phase: "Active"},+ })+ }+ b, _ := json.Marshal(map[string]any{"items": items})+ return string(b)+}++// nsCreatedResponse builds a minimal K8s Namespace JSON (single object).+func nsCreatedResponse(name string) string {+ b, _ := json.Marshal(map[string]any{+ "metadata": map[string]any{+ "name": name,+ "labels": map[string]string{},+ "creationTimestamp": "2026-05-28T00:00:00Z",+ },+ "status": map[string]any{"phase": "Active"},+ })+ return string(b)+}++func existingPersonalTenantResponse(userSub string) string {+ tenant := desiredPersonalTenant(context.Background(), userSub)+ tenant.Status = &capsuleTenantStatus{Owners: []capsuleTenantOwner{+ tenant.Spec.Owners[0],+ }}+ b, _ := json.Marshal(tenant)+ return string(b)+}++func pendingPersonalTenantResponse(userSub string) string {+ b, _ := json.Marshal(desiredPersonalTenant(context.Background(), userSub))+ return string(b)+}++func newNamespaceCreateK8s(userSub string, status int, respBody string) *fakeK8s {+ tenantPath := capsuleTenantCollectionPath + "/user-" + userSub+ return newFakeK8sHandler(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == tenantPath:+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(existingPersonalTenantResponse(userSub)))+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/namespaces":+ w.WriteHeader(status)+ _, _ = w.Write([]byte(respBody))+ case r.Method == http.MethodGet && strings.HasPrefix(+ r.URL.Path, "/apis/rbac.authorization.k8s.io/v1/namespaces/",+ ):+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"items":[]}`))+ default:+ w.WriteHeader(http.StatusInternalServerError)+ _, _ = w.Write([]byte(`{"error":"unexpected test request"}`))+ }+ })+}++func TestCreateNamespace_ValidName(t *testing.T) {+ fk := newNamespaceCreateK8s("test-uuid", http.StatusCreated, nsCreatedResponse("my-workspace"))+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ h := Handlers{}+ body := `{"name":"my-workspace"}`+ r := httptest.NewRequest(http.MethodPost, "/api/namespaces", strings.NewReader(body))+ r = withUser(r, &auth.User{ID: "test-uuid"})+ w := httptest.NewRecorder()++ h.CreateNamespace(w, r)++ if w.Code != http.StatusCreated {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusCreated, w.Body.String())+ }++ // The handler validates the Tenant, creates the namespace, then probes for+ // adoption; inspect the namespace POST explicitly.+ if len(fk.requests) < 3 {+ t.Fatalf("expected tenant GET + namespace POST + adoption probe GET, got %d request(s)", len(fk.requests))+ }+ post := fk.requests[1]++ // Verify impersonation headers sent to k8s proxy.+ if got := post.headers.Get("Impersonate-User"); got != "oidc:test-uuid" {+ t.Fatalf("Impersonate-User = %q, want %q", got, "oidc:test-uuid")+ }+ if got := post.headers.Get("Impersonate-Group"); got != "oidc:cyclops-cs-tenants" {+ t.Fatalf("Impersonate-Group = %q, want %q", got, "oidc:cyclops-cs-tenants")+ }++ // Verify path.+ if post.method != http.MethodPost || post.path != "/api/v1/namespaces" {+ t.Fatalf("upstream req = %s %q, want POST /api/v1/namespaces", post.method, post.path)+ }++ // Verify the K8s body contains the namespace name.+ var nsObj map[string]any+ if err := json.Unmarshal(post.body, &nsObj); err != nil {+ t.Fatalf("upstream body not JSON: %v", err)+ }+ meta, _ := nsObj["metadata"].(map[string]any)+ if meta["name"] != "my-workspace" {+ t.Fatalf("upstream ns name = %v, want my-workspace", meta["name"])+ }++ // Verify the adoption probe: an impersonated RoleBinding LIST in the new+ // namespace (only authorized once Capsule's owner RoleBindings exist —+ // unlike a namespace GET, which system:authenticated can always do).+ probe := fk.requests[len(fk.requests)-1]+ wantProbe := "/apis/rbac.authorization.k8s.io/v1/namespaces/my-workspace/rolebindings"+ if probe.method != http.MethodGet || probe.path != wantProbe {+ t.Fatalf("probe req = %s %q, want GET %s", probe.method, probe.path, wantProbe)+ }+ if got := probe.headers.Get("Impersonate-User"); got != "oidc:test-uuid" {+ t.Fatalf("probe Impersonate-User = %q, want %q", got, "oidc:test-uuid")+ }++ // Verify response body.+ var resp NamespaceResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.Name != "my-workspace" {+ t.Fatalf("response name = %q, want my-workspace", resp.Name)+ }+}++func TestCreateNamespace_InvalidName(t *testing.T) {+ h := Handlers{}++ cases := []struct {+ name string+ payload string+ }{+ {"uppercase", `{"name":"MyWorkspace"}`},+ {"special chars", `{"name":"my_workspace!"}`},+ {"starts with dash", `{"name":"-bad"}`},+ {"too long", `{"name":"` + strings.Repeat("a", 64) + `"}`},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ r := httptest.NewRequest(http.MethodPost, "/api/namespaces", strings.NewReader(tc.payload))+ r = withUser(r, &auth.User{ID: "test-uuid"})+ w := httptest.NewRecorder()++ h.CreateNamespace(w, r)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())+ }+ })+ }+}++func TestCreateNamespace_MissingBody(t *testing.T) {+ h := Handlers{}++ t.Run("empty body", func(t *testing.T) {+ r := httptest.NewRequest(http.MethodPost, "/api/namespaces", strings.NewReader(""))+ r = withUser(r, &auth.User{ID: "test-uuid"})+ w := httptest.NewRecorder()++ h.CreateNamespace(w, r)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())+ }+ })++ t.Run("empty name", func(t *testing.T) {+ r := httptest.NewRequest(http.MethodPost, "/api/namespaces", strings.NewReader(`{"name":""}`))+ r = withUser(r, &auth.User{ID: "test-uuid"})+ w := httptest.NewRecorder()++ h.CreateNamespace(w, r)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())+ }+ })++ t.Run("no JSON", func(t *testing.T) {+ r := httptest.NewRequest(http.MethodPost, "/api/namespaces", bytes.NewReader([]byte("not-json")))+ r = withUser(r, &auth.User{ID: "test-uuid"})+ w := httptest.NewRecorder()++ h.CreateNamespace(w, r)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())+ }+ })+}++func TestCreateNamespace_MissingUser(t *testing.T) {+ h := Handlers{}+ body := `{"name":"my-workspace"}`+ r := httptest.NewRequest(http.MethodPost, "/api/namespaces", strings.NewReader(body))+ // No withUser — context has no user.+ w := httptest.NewRecorder()++ h.CreateNamespace(w, r)++ if w.Code != http.StatusUnauthorized {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusUnauthorized, w.Body.String())+ }+}++func TestCreateNamespace_CreatesTracingSpan(t *testing.T) {+ fk := newNamespaceCreateK8s("test-uuid", http.StatusCreated, nsCreatedResponse("my-workspace"))+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ recorder := tracetest.NewSpanRecorder()+ tp := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder))+ otel.SetTracerProvider(tp)++ ctx, root := tp.Tracer("test").Start(context.Background(), "request")++ h := Handlers{}+ r := httptest.NewRequest(http.MethodPost, "/api/namespaces", strings.NewReader(`{"name":"my-workspace"}`)).WithContext(ctx)+ r = withUser(r, &auth.User{ID: "test-uuid"})+ w := httptest.NewRecorder()++ h.CreateNamespace(w, r)+ root.End()++ var found bool+ for _, span := range recorder.Ended() {+ if span.Name() != "namespaces.create" {+ continue+ }+ found = true+ if got, want := span.Parent().SpanID(), root.SpanContext().SpanID(); got != want {+ t.Fatalf("parent span id = %s, want %s", got, want)+ }+ }+ if !found {+ t.Fatal("expected namespaces.create span")+ }+}++func TestDeleteNamespace_Success(t *testing.T) {+ fk := newFakeK8s(http.StatusOK, `{"kind":"Status","status":"Success"}`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ h := Handlers{}+ r := httptest.NewRequest(http.MethodDelete, "/api/namespaces/my-workspace", nil)+ r.SetPathValue("name", "my-workspace")+ r = withUser(r, &auth.User{ID: "test-uuid"})+ w := httptest.NewRecorder()++ h.DeleteNamespace(w, r)++ if w.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusNoContent, w.Body.String())+ }++ // Verify impersonation headers.+ if got := fk.headers.Get("Impersonate-User"); got != "oidc:test-uuid" {+ t.Fatalf("Impersonate-User = %q, want %q", got, "oidc:test-uuid")+ }+ if got := fk.headers.Get("Impersonate-Group"); got != "oidc:cyclops-cs-tenants" {+ t.Fatalf("Impersonate-Group = %q, want %q", got, "oidc:cyclops-cs-tenants")+ }++ // Verify DELETE was sent to the right path.+ if fk.method != http.MethodDelete {+ t.Fatalf("upstream method = %q, want DELETE", fk.method)+ }+ if fk.path != "/api/v1/namespaces/my-workspace" {+ t.Fatalf("upstream path = %q, want /api/v1/namespaces/my-workspace", fk.path)+ }+}++func TestDeleteNamespace_MissingUser(t *testing.T) {+ h := Handlers{}+ r := httptest.NewRequest(http.MethodDelete, "/api/namespaces/my-workspace", nil)+ r.SetPathValue("name", "my-workspace")+ // No user context.+ w := httptest.NewRecorder()++ h.DeleteNamespace(w, r)++ if w.Code != http.StatusUnauthorized {+ t.Fatalf("status = %d, want %d", w.Code, http.StatusUnauthorized)+ }+}++func TestDeleteNamespace_NotFound(t *testing.T) {+ fk := newFakeK8s(http.StatusNotFound, `{"kind":"Status","status":"Failure","reason":"NotFound"}`)+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ h := Handlers{}+ r := httptest.NewRequest(http.MethodDelete, "/api/namespaces/no-such-ns", nil)+ r.SetPathValue("name", "no-such-ns")+ r = withUser(r, &auth.User{ID: "test-uuid"})+ w := httptest.NewRecorder()++ h.DeleteNamespace(w, r)++ if w.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusNotFound, w.Body.String())+ }+}++func TestListNamespaces_Success(t *testing.T) {+ fk := newFakeK8s(http.StatusOK, nsListResponse("ns-alpha", "ns-beta"))+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ h := Handlers{}+ r := httptest.NewRequest(http.MethodGet, "/api/namespaces", nil)+ r = withUser(r, &auth.User{ID: "test-uuid"})+ w := httptest.NewRecorder()++ h.ListNamespaces(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())+ }++ // Verify impersonation headers.+ if got := fk.headers.Get("Impersonate-User"); got != "oidc:test-uuid" {+ t.Fatalf("Impersonate-User = %q, want %q", got, "oidc:test-uuid")+ }+ if got := fk.headers.Get("Impersonate-Group"); got != "oidc:cyclops-cs-tenants" {+ t.Fatalf("Impersonate-Group = %q, want %q", got, "oidc:cyclops-cs-tenants")+ }++ // Verify the list is scoped to the caller's Tenant by label selector —+ // this is the fail-closed boundary that does not depend on Capsule Proxy.+ if fk.path != "/api/v1/namespaces" {+ t.Fatalf("upstream path = %q, want /api/v1/namespaces", fk.path)+ }+ q, err := url.ParseQuery(fk.rawQuery)+ if err != nil {+ t.Fatalf("parse upstream query %q: %v", fk.rawQuery, err)+ }+ if got, want := q.Get("labelSelector"), "capsule.clastix.io/tenant=user-test-uuid"; got != want {+ t.Fatalf("labelSelector = %q, want %q", got, want)+ }++ // Parse the response body.+ var nsList []NamespaceResponse+ if err := json.NewDecoder(w.Body).Decode(&nsList); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if len(nsList) != 2 {+ t.Fatalf("namespace count = %d, want 2", len(nsList))+ }+ if nsList[0].Name != "ns-alpha" {+ t.Fatalf("first namespace = %q, want ns-alpha", nsList[0].Name)+ }+ if nsList[1].Name != "ns-beta" {+ t.Fatalf("second namespace = %q, want ns-beta", nsList[1].Name)+ }+}++func TestListNamespaces_MissingUser(t *testing.T) {+ h := Handlers{}+ r := httptest.NewRequest(http.MethodGet, "/api/namespaces", nil)+ // No user context.+ w := httptest.NewRecorder()++ h.ListNamespaces(w, r)++ if w.Code != http.StatusUnauthorized {+ t.Fatalf("status = %d, want %d", w.Code, http.StatusUnauthorized)+ }+}diff --git a/libs/fleet/backend/handlers/ownership.go b/libs/fleet/backend/handlers/ownership.gonew file mode 100644index 0000000000..a82ced0016--- /dev/null+++ b/libs/fleet/backend/handlers/ownership.go@@ -0,0 +1,192 @@+// Namespace-ownership enforcement for the direct-dial service proxies+// (/api/svc and /api/orch).+//+// 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.+//+// The check is the impersonated RoleBinding probe 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+// capsule-tenant-cluster-resources ClusterRole grants namespaces+// get/list cluster-wide to system:authenticated, so it gates nothing.)+package handlers++import (+ "context"+ "fmt"+ "log/slog"+ "net/http"+ "net/url"+ "strings"+ "sync"+ "time"++ "golang.org/x/sync/singleflight"++ "cyclops-cs-backend/auth"+)++const (+ // ownershipPositiveTTL bounds how long an "owns it" verdict is reused.+ // Ownership effectively never changes, but a short TTL keeps a deleted+ // + re-created namespace from serving a stale verdict for long, while+ // still collapsing the noVNC asset storm to ~2 probes/min/user/ns.+ ownershipPositiveTTL = 30 * time.Second+ // ownershipNegativeTTL damps brute-force namespace enumeration without+ // locking a user out of a just-adopted namespace for long.+ ownershipNegativeTTL = 5 * time.Second+)++type ownershipVerdict struct {+ allowed bool+ exp time.Time+}++// Package-level like the k8sImpersonate client state — Handlers is a value+// type, so per-struct state wouldn't survive across requests anyway.+var (+ ownershipMu sync.Mutex+ ownershipCache = map[string]ownershipVerdict{}+ // ownershipSF collapses concurrent probes for the same (sub, ns) —+ // noVNC fires dozens of parallel asset requests on first load.+ // Mirrors flagsSF in auth/middlewares.go.+ ownershipSF singleflight.Group+)++// resetOwnershipCache clears the verdict cache; tests only.+func resetOwnershipCache() {+ ownershipMu.Lock()+ ownershipCache = map[string]ownershipVerdict{}+ 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())+}++// 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 {+ // 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+ }++ allowed, err := h.userHasNamespaceRBAC(r.Context(), user.ID, ns)+ 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+ }+ if !allowed {+ slog.Warn("namespace access denied",+ "sub", user.ID, "azp", user.AZP, "namespace", ns)+ writeErr(w, http.StatusForbidden, "namespace access denied")+ return false+ }+ return true+}++// userHasNamespaceRBAC reports whether sub holds RBAC in ns, via a TTL-+// cached, singleflighted impersonated RoleBinding LIST probe. A non-nil+// error means the apiserver was unreachable or replied with an unexpected+// status — callers fail closed; nothing is cached so a flapping apiserver+// can't pin verdicts.+func (h Handlers) userHasNamespaceRBAC(ctx context.Context, sub, ns string) (bool, error) {+ key := sub + "\x00" + ns++ ownershipMu.Lock()+ if v, ok := ownershipCache[key]; ok && time.Now().Before(v.exp) {+ ownershipMu.Unlock()+ return v.allowed, nil+ }+ ownershipMu.Unlock()++ v, err, _ := ownershipSF.Do(key, func() (interface{}, error) {+ // Re-check under the lock: a concurrent probe may have just+ // populated the cache while we waited to enter singleflight.+ ownershipMu.Lock()+ if v, ok := ownershipCache[key]; ok && time.Now().Before(v.exp) {+ ownershipMu.Unlock()+ return v.allowed, nil+ }+ ownershipMu.Unlock()++ resp, err := h.k8sImpersonate(ctx, "GET",+ "/apis/rbac.authorization.k8s.io/v1/namespaces/"+url.PathEscape(ns)+"/rolebindings?limit=1",+ nil, sub)+ if err != nil {+ return false, err+ }+ defer resp.Body.Close()++ var allowed bool+ switch {+ case resp.StatusCode >= 200 && resp.StatusCode < 300:+ allowed = true+ case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:+ allowed = false+ default:+ // 5xx etc. — indeterminate, fail closed, don't cache.+ return false, &unexpectedProbeStatus{status: resp.StatusCode}+ }++ ttl := ownershipPositiveTTL+ if !allowed {+ ttl = ownershipNegativeTTL+ }+ ownershipMu.Lock()+ ownershipCache[key] = ownershipVerdict{allowed: allowed, exp: time.Now().Add(ttl)}+ ownershipMu.Unlock()+ return allowed, nil+ })+ if err != nil {+ return false, err+ }+ return v.(bool), nil+}++type unexpectedProbeStatus struct{ status int }++func (e *unexpectedProbeStatus) Error() string {+ return fmt.Sprintf("unexpected status %d from rolebinding probe", e.status)+}diff --git a/libs/fleet/backend/handlers/ownership_test.go b/libs/fleet/backend/handlers/ownership_test.gonew file mode 100644index 0000000000..58d7d8fc7a--- /dev/null+++ b/libs/fleet/backend/handlers/ownership_test.go@@ -0,0 +1,237 @@+package handlers++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "cyclops-cs-backend/auth"+ "cyclops-cs-backend/config"+)++func testHandlers() Handlers {+ return Handlers{+ GatewayCfg: config.GatewayConfiguration{+ Scheme: "http",+ Port: "80",+ ClusterDomain: "svc.cluster.local",+ },+ }+}++// 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)+ r.SetPathValue("namespace", ns)+ r.SetPathValue("service", service)+ r.SetPathValue("path", "")+ if u != nil {+ r = withUser(r, u)+ }+ 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())+ }+ if len(fk.requests) != 0 {+ t.Fatalf("expected no K8s probe for per-key client, got %d request(s)", len(fk.requests))+ }+}++// 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")++ 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 TestRequireNamespaceAccess_SPAUser_OwnedNamespace_ProbeAllows(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())+ }+ if len(fk.requests) != 1 {+ t.Fatalf("expected exactly one probe, got %d", len(fk.requests))+ }+ probe := fk.requests[0]+ if probe.method != http.MethodGet || probe.path != probePath {+ t.Fatalf("probe = %s %q, want GET %s", probe.method, probe.path, probePath)+ }+ if got := probe.headers.Get("Impersonate-User"); got != "oidc:test-uuid" {+ t.Fatalf("Impersonate-User = %q, want oidc:test-uuid", got)+ }+ if got := probe.headers.Get("Impersonate-Group"); got != "oidc:cyclops-cs-tenants" {+ t.Fatalf("Impersonate-Group = %q, want oidc:cyclops-cs-tenants", got)+ }+}++func TestSvc_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")++ h := testHandlers()+ 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("status = %d, want 403; body = %s", w.Code, w.Body.String())+ }+}++func TestSvc_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")++ h := testHandlers()+ w := httptest.NewRecorder()+ h.Svc(w, svcRequest(&auth.User{ID: "intruder-uuid", AZP: "oauth2-proxy", Email: "[email protected]"}, "other-ns", "novnc"))++ if w.Code != http.StatusForbidden {+ t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())+ }+}++func TestSvc_K8sUnavailable_FailsClosed(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()+ 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())+ }+ }+ // 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) {+ 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++ {+ 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)+ }+ }+ if len(fk.requests) != 1 {+ t.Fatalf("expected 1 probe across 3 requests (cached), got %d", len(fk.requests))+ }+}++func TestOwnership_NegativeVerdictCached(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)+ }+ }+ if len(fk.requests) != 1 {+ t.Fatalf("expected 1 probe across 2 requests (negative cached), got %d", len(fk.requests))+ }+}++func TestOwnership_CacheIsPerUser(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")+ }+ // 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_InvalidNamespace_BadRequest(t *testing.T) {+ resetOwnershipCache()+ h := testHandlers()+ w := httptest.NewRecorder()+ h.Svc(w, svcRequest(&auth.User{ID: "test-uuid", AZP: "cyclops-cs-spa"}, "Bad_NS", "novnc"))++ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String())+ }+}++func TestOrch_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()+ 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"})+ w := httptest.NewRecorder()+ h.Orch(w, r)++ if w.Code != http.StatusForbidden {+ t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())+ }+}diff --git a/libs/fleet/backend/handlers/pool_templates.go b/libs/fleet/backend/handlers/pool_templates.gonew file mode 100644index 0000000000..056eff71f7--- /dev/null+++ b/libs/fleet/backend/handlers/pool_templates.go@@ -0,0 +1,233 @@+package handlers++import (+ "encoding/json"+ "errors"+ "log/slog"+ "net/http"+ "regexp"++ "cyclops-cs-backend/templates"+)++// templateName bounds a template's name: 1–63 chars, alphanumerics plus+// dot/dash/underscore, no leading separator. It deliberately forbids ':'+// (the Redis key separator) so a name can never escape its owner's+// keyspace. Looser than a DNS-1123 label — a template name is a friendly+// SPA label, not a K8s object name.+var templateName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$`)++// maxTemplateConfigBytes caps the stored config blob. A pool config is a+// few hundred bytes; 256 KiB is a generous ceiling that still bounds what+// a single request can push into Redis.+const maxTemplateConfigBytes = 256 << 10++// CreatePoolTemplateRequest is the body for POST /api/pool-templates.+// Config is the opaque pool config the SPA would otherwise pass straight+// to createPool (cpu, ram, ociImage, replicas, services, probes).+type CreatePoolTemplateRequest struct {+ Name string `json:"name" example:"gpu-large"`+ Config json.RawMessage `json:"config" swaggertype:"object"`+}++// PoolTemplateResponse is a single saved template. It mirrors the four+// stored fields: the owning user, the name, when it was created, and the+// opaque pool config.+type PoolTemplateResponse struct {+ User string `json:"user"`+ Name string `json:"name"`+ CreatedAt string `json:"createdAt"`+ Config json.RawMessage `json:"config" swaggertype:"object"`+}++func toPoolTemplateResponse(t *templates.Template) PoolTemplateResponse {+ return PoolTemplateResponse{+ User: t.User,+ Name: t.Name,+ CreatedAt: t.CreatedAt.UTC().Format("2006-01-02T15:04:05.999999999Z07:00"),+ Config: t.Config,+ }+}++// templatesEnabled writes a 503 and returns false when no Redis-backed+// store is configured. The routes are always registered; this keeps the+// failure mode explicit ("not configured") instead of silently empty.+func (h Handlers) templatesEnabled(w http.ResponseWriter) bool {+ if h.Templates == nil {+ writeErr(w, http.StatusServiceUnavailable, "pool templates are not configured")+ return false+ }+ return true+}++// CreatePoolTemplate godoc+//+// @Summary Save a pool config as a reusable template+// @Description Stores the given pool config under a name owned by the calling user. Re-saving an existing name overwrites the config while preserving the original creation time. Use GET /api/pool-templates to list them and seed a new pool.+// @Tags pool-templates+// @Accept json+// @Produce json+// @Param body body CreatePoolTemplateRequest true "Template name + pool config"+// @Success 201 {object} PoolTemplateResponse+// @Failure 400 {object} ErrorResponse+// @Failure 401 {object} ErrorResponse+// @Failure 503 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/pool-templates [post]+func (h Handlers) CreatePoolTemplate(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }+ if !h.templatesEnabled(w) {+ return+ }++ r.Body = http.MaxBytesReader(w, r.Body, maxTemplateConfigBytes+4096)+ var req CreatePoolTemplateRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ var mbe *http.MaxBytesError+ if errors.As(err, &mbe) {+ writeErr(w, http.StatusBadRequest, "config too large")+ return+ }+ writeErr(w, http.StatusBadRequest, "invalid body")+ return+ }+ if !templateName.MatchString(req.Name) {+ writeErr(w, http.StatusBadRequest, "name must be 1-63 chars: letters, digits, '.', '-', '_' (no leading separator)")+ return+ }+ // A successful json.RawMessage decode already guarantees config is+ // well-formed JSON; we only need to reject the empty/oversized cases.+ if len(req.Config) == 0 {+ writeErr(w, http.StatusBadRequest, "config is required")+ return+ }+ if len(req.Config) > maxTemplateConfigBytes {+ writeErr(w, http.StatusBadRequest, "config too large")+ return+ }++ t := &templates.Template{User: user.ID, Name: req.Name, Config: req.Config}+ if err := h.Templates.Save(r.Context(), t); err != nil {+ slog.Warn("pool template save failed", "err", err, "user", user.ID, "name", req.Name)+ writeErr(w, http.StatusInternalServerError, "failed to save template")+ return+ }+ writeJSON(w, http.StatusCreated, toPoolTemplateResponse(t))+}++// ListPoolTemplates godoc+//+// @Summary List the calling user's pool templates+// @Description Returns every pool template owned by the calling user, newest first.+// @Tags pool-templates+// @Produce json+// @Success 200 {array} PoolTemplateResponse+// @Failure 401 {object} ErrorResponse+// @Failure 503 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/pool-templates [get]+func (h Handlers) ListPoolTemplates(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }+ if !h.templatesEnabled(w) {+ return+ }++ list, err := h.Templates.List(r.Context(), user.ID)+ if err != nil {+ slog.Warn("pool template list failed", "err", err, "user", user.ID)+ writeErr(w, http.StatusInternalServerError, "failed to list templates")+ return+ }+ out := make([]PoolTemplateResponse, 0, len(list))+ for _, t := range list {+ out = append(out, toPoolTemplateResponse(t))+ }+ writeJSON(w, http.StatusOK, out)+}++// GetPoolTemplate godoc+//+// @Summary Get one of the calling user's pool templates+// @Tags pool-templates+// @Produce json+// @Param name path string true "Template name"+// @Success 200 {object} PoolTemplateResponse+// @Failure 401 {object} ErrorResponse+// @Failure 404 {object} ErrorResponse+// @Failure 503 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/pool-templates/{name} [get]+func (h Handlers) GetPoolTemplate(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }+ if !h.templatesEnabled(w) {+ return+ }++ name := r.PathValue("name")+ if !templateName.MatchString(name) {+ writeErr(w, http.StatusBadRequest, "invalid template name")+ return+ }+ t, err := h.Templates.Get(r.Context(), user.ID, name)+ if err != nil {+ slog.Warn("pool template get failed", "err", err, "user", user.ID, "name", name)+ writeErr(w, http.StatusInternalServerError, "failed to get template")+ return+ }+ if t == nil {+ writeErr(w, http.StatusNotFound, "template not found")+ return+ }+ writeJSON(w, http.StatusOK, toPoolTemplateResponse(t))+}++// DeletePoolTemplate godoc+//+// @Summary Delete one of the calling user's pool templates+// @Tags pool-templates+// @Param name path string true "Template name"+// @Success 204+// @Failure 401 {object} ErrorResponse+// @Failure 404 {object} ErrorResponse+// @Failure 503 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/pool-templates/{name} [delete]+func (h Handlers) DeletePoolTemplate(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }+ if !h.templatesEnabled(w) {+ return+ }++ name := r.PathValue("name")+ if !templateName.MatchString(name) {+ writeErr(w, http.StatusBadRequest, "invalid template name")+ return+ }+ existed, err := h.Templates.Delete(r.Context(), user.ID, name)+ if err != nil {+ slog.Warn("pool template delete failed", "err", err, "user", user.ID, "name", name)+ writeErr(w, http.StatusInternalServerError, "failed to delete template")+ return+ }+ if !existed {+ writeErr(w, http.StatusNotFound, "template not found")+ return+ }+ w.WriteHeader(http.StatusNoContent)+}diff --git a/libs/fleet/backend/handlers/pool_templates_test.go b/libs/fleet/backend/handlers/pool_templates_test.gonew file mode 100644index 0000000000..6adef11321--- /dev/null+++ b/libs/fleet/backend/handlers/pool_templates_test.go@@ -0,0 +1,217 @@+package handlers++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "cyclops-cs-backend/auth"+ "cyclops-cs-backend/templates"+)++// fakeTemplateStore is an in-memory templates.Store for handler tests —+// it exercises the real handler logic (auth, validation, status codes,+// per-user scoping) without a Redis dependency.+type fakeTemplateStore struct {+ m map[string]*templates.Template // keyed by user + "\x00" + name+}++func newFakeStore() *fakeTemplateStore {+ return &fakeTemplateStore{m: map[string]*templates.Template{}}+}++func (f *fakeTemplateStore) key(user, name string) string { return user + "\x00" + name }++func (f *fakeTemplateStore) Save(_ context.Context, t *templates.Template) error {+ if t.CreatedAt.IsZero() {+ t.CreatedAt = time.Now().UTC()+ }+ cp := *t+ f.m[f.key(t.User, t.Name)] = &cp+ return nil+}++func (f *fakeTemplateStore) Get(_ context.Context, user, name string) (*templates.Template, error) {+ t, ok := f.m[f.key(user, name)]+ if !ok {+ return nil, nil+ }+ cp := *t+ return &cp, nil+}++func (f *fakeTemplateStore) List(_ context.Context, user string) ([]*templates.Template, error) {+ var out []*templates.Template+ for _, t := range f.m {+ if t.User == user {+ cp := *t+ out = append(out, &cp)+ }+ }+ return out, nil+}++func (f *fakeTemplateStore) Delete(_ context.Context, user, name string) (bool, error) {+ k := f.key(user, name)+ if _, ok := f.m[k]; !ok {+ return false, nil+ }+ delete(f.m, k)+ return true, nil+}++func newReq(method, target, body string, user *auth.User) *http.Request {+ var r *http.Request+ if body != "" {+ r = httptest.NewRequest(method, target, strings.NewReader(body))+ } else {+ r = httptest.NewRequest(method, target, nil)+ }+ if user != nil {+ r = withUser(r, user)+ }+ return r+}++var alice = &auth.User{ID: "user-alice"}++func TestCreatePoolTemplate_Success(t *testing.T) {+ h := Handlers{Templates: newFakeStore()}+ r := newReq(http.MethodPost, "/api/pool-templates",+ `{"name":"gpu-large","config":{"cpu":8,"ram":"16Gi"}}`, alice)+ w := httptest.NewRecorder()++ h.CreatePoolTemplate(w, r)++ if w.Code != http.StatusCreated {+ t.Fatalf("status = %d, want 201; body = %s", w.Code, w.Body.String())+ }+ var resp PoolTemplateResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp.Name != "gpu-large" || resp.User != "user-alice" {+ t.Fatalf("resp = %+v", resp)+ }+ if resp.CreatedAt == "" {+ t.Fatal("createdAt not set")+ }+ if string(resp.Config) != `{"cpu":8,"ram":"16Gi"}` {+ t.Fatalf("config = %s", string(resp.Config))+ }+}++func TestCreatePoolTemplate_Validation(t *testing.T) {+ cases := map[string]string{+ "bad name": `{"name":"bad name","config":{}}`,+ "colon in name": `{"name":"a:b","config":{}}`,+ "empty name": `{"name":"","config":{}}`,+ "missing config": `{"name":"ok"}`,+ "bad json": `{"name":"ok","config":}`,+ }+ for label, body := range cases {+ t.Run(label, func(t *testing.T) {+ h := Handlers{Templates: newFakeStore()}+ w := httptest.NewRecorder()+ h.CreatePoolTemplate(w, newReq(http.MethodPost, "/api/pool-templates", body, alice))+ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String())+ }+ })+ }+}++func TestPoolTemplate_Unauthorized(t *testing.T) {+ h := Handlers{Templates: newFakeStore()}+ w := httptest.NewRecorder()+ h.ListPoolTemplates(w, newReq(http.MethodGet, "/api/pool-templates", "", nil))+ if w.Code != http.StatusUnauthorized {+ t.Fatalf("status = %d, want 401", w.Code)+ }+}++func TestPoolTemplate_Disabled503(t *testing.T) {+ h := Handlers{} // no store+ w := httptest.NewRecorder()+ h.ListPoolTemplates(w, newReq(http.MethodGet, "/api/pool-templates", "", alice))+ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("status = %d, want 503; body = %s", w.Code, w.Body.String())+ }+}++func TestListPoolTemplates_IsolatedPerUser(t *testing.T) {+ store := newFakeStore()+ h := Handlers{Templates: store}++ // Alice saves one.+ w := httptest.NewRecorder()+ h.CreatePoolTemplate(w, newReq(http.MethodPost, "/api/pool-templates",+ `{"name":"a-tpl","config":{"cpu":1}}`, alice))+ if w.Code != http.StatusCreated {+ t.Fatalf("alice create: %d", w.Code)+ }++ // Bob lists — must not see Alice's template.+ bob := &auth.User{ID: "user-bob"}+ w = httptest.NewRecorder()+ h.ListPoolTemplates(w, newReq(http.MethodGet, "/api/pool-templates", "", bob))+ if w.Code != http.StatusOK {+ t.Fatalf("bob list: %d", w.Code)+ }+ var bobList []PoolTemplateResponse+ _ = json.Unmarshal(w.Body.Bytes(), &bobList)+ if len(bobList) != 0 {+ t.Fatalf("bob saw %d templates, want 0", len(bobList))+ }++ // Alice lists — sees exactly her one template.+ w = httptest.NewRecorder()+ h.ListPoolTemplates(w, newReq(http.MethodGet, "/api/pool-templates", "", alice))+ var aliceList []PoolTemplateResponse+ _ = json.Unmarshal(w.Body.Bytes(), &aliceList)+ if len(aliceList) != 1 || aliceList[0].Name != "a-tpl" {+ t.Fatalf("alice list = %+v", aliceList)+ }+}++func TestGetPoolTemplate_NotFound(t *testing.T) {+ h := Handlers{Templates: newFakeStore()}+ r := newReq(http.MethodGet, "/api/pool-templates/missing", "", alice)+ r.SetPathValue("name", "missing")+ w := httptest.NewRecorder()+ h.GetPoolTemplate(w, r)+ if w.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want 404", w.Code)+ }+}++func TestDeletePoolTemplate_RoundTrip(t *testing.T) {+ store := newFakeStore()+ h := Handlers{Templates: store}++ // Create, then delete → 204, then delete again → 404.+ w := httptest.NewRecorder()+ h.CreatePoolTemplate(w, newReq(http.MethodPost, "/api/pool-templates",+ `{"name":"doomed","config":{"cpu":1}}`, alice))+ if w.Code != http.StatusCreated {+ t.Fatalf("create: %d", w.Code)+ }++ del := func() int {+ r := newReq(http.MethodDelete, "/api/pool-templates/doomed", "", alice)+ r.SetPathValue("name", "doomed")+ w := httptest.NewRecorder()+ h.DeletePoolTemplate(w, r)+ return w.Code+ }+ if code := del(); code != http.StatusNoContent {+ t.Fatalf("first delete = %d, want 204", code)+ }+ if code := del(); code != http.StatusNotFound {+ t.Fatalf("second delete = %d, want 404", code)+ }+}diff --git a/libs/fleet/backend/handlers/svc.go b/libs/fleet/backend/handlers/svc.gonew file mode 100644index 0000000000..2d5c9677de--- /dev/null+++ b/libs/fleet/backend/handlers/svc.go@@ -0,0 +1,132 @@+package handlers++import (+ "fmt"+ "log/slog"+ "net/http"+ "net/http/httputil"+ "net/url"+ "strings"+ "time"++ "cyclops-cs-backend/metrics"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/codes"+ "go.opentelemetry.io/otel/trace"+)++// rewriteLocation prepends basePath to upstream Location header values+// so browsers stay within the /api/svc proxy prefix. External URLs+// (with a host) are returned unchanged.+func rewriteLocation(loc, basePath string) string {+ if loc == "" {+ return ""+ }+ // Absolute path: /foo → /api/svc/{ns}/{svc}/foo+ if strings.HasPrefix(loc, "/") {+ return basePath + loc+ }+ // Full URL with host — leave as-is (external redirect)+ parsed, err := url.Parse(loc)+ if err != nil || parsed.Host != "" {+ return loc+ }+ // Relative path: foo → /api/svc/{ns}/{svc}/foo+ return basePath + "/" + loc+}++// Svc godoc+//+// @Summary Authenticated reverse proxy to a K8s Service in a namespace the caller owns+// @Description Proxies to {service}.{namespace}.svc.cluster.local:80. Per-key tokens are bound to their `namespace` claim; all other principals (SPA, user keys, oauth2-proxy browser sessions) must hold RBAC in {namespace}, verified via an impersonated RoleBinding probe. Strips Authorization before forwarding.+// @Tags gateway+// @Param namespace path string true "K8s namespace (caller must own it, or it must match a per-key token's namespace claim)"+// @Param service path string true "K8s Service name (DNS-1123 label)"+// @Param path path string false "Upstream path (proxied verbatim)"+// @Success 200 {string} string "Upstream response"+// @Failure 400 {object} ErrorResponse+// @Failure 401 {object} ErrorResponse+// @Failure 403 {object} ErrorResponse+// @Failure 502 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/svc/{namespace}/{service}/{path} [get]+func (h Handlers) Svc(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }++ ns := r.PathValue("namespace")+ service := r.PathValue("service")+ // Defense in depth — OPA already enforced the DNS-label shape, but+ // validate here too so a policy regression can't turn the proxy into+ // an SSRF vector (same belt-and-braces as Gateway/Orch).+ if !dnsLabel.MatchString(ns) || !dnsLabel.MatchString(service) {+ 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+ }++ host := fmt.Sprintf("%s.%s.%s", service, ns, h.GatewayCfg.ClusterDomain)+ target := &url.URL{Scheme: h.GatewayCfg.Scheme, Host: host + ":" + h.GatewayCfg.Port}++ upstreamPath := r.PathValue("path")+ if upstreamPath == "" {+ upstreamPath = "/"+ } else if !strings.HasPrefix(upstreamPath, "/") {+ upstreamPath = "/" + upstreamPath+ }+ ctx, span := handlerTracer().Start(r.Context(), "svc.proxy", trace.WithAttributes(+ attribute.String("proxy.target", "svc"),+ attribute.String("http.route", "/api/svc/{namespace}/{service}/{path...}"),+ attribute.String("k8s.namespace", ns),+ attribute.String("k8s.service", service),+ attribute.String("http.target_path", upstreamPath),+ ))+ defer span.End()++ // The base path prefix that the upstream doesn't know about.+ // Upstream redirects (Location headers) must be rewritten to+ // prepend this prefix so the browser stays within /api/svc.+ basePath := fmt.Sprintf("/api/svc/%s/%s", ns, service)++ rp := httputil.NewSingleHostReverseProxy(target)+ origDirector := rp.Director+ rp.Director = func(req *http.Request) {+ origDirector(req)+ req.URL.Path = upstreamPath+ req.URL.RawPath = ""+ req.URL.RawQuery = r.URL.RawQuery+ req.Header.Del("Authorization")+ req.Host = target.Host+ }+ // Rewrite upstream Location headers to include the base path.+ rp.ModifyResponse = func(resp *http.Response) error {+ loc := resp.Header.Get("Location")+ if rewritten := rewriteLocation(loc, basePath); rewritten != loc {+ resp.Header.Set("Location", rewritten)+ }+ return nil+ }++ rw := &statusCapture{ResponseWriter: w}+ rp.ErrorHandler = func(rw http.ResponseWriter, _ *http.Request, err error) {+ span.RecordError(err)+ span.SetStatus(codes.Error, "upstream unavailable")+ slog.Warn("svc proxy error", "host", host, "path", upstreamPath, "err", err)+ http.Error(rw, "upstream unavailable", http.StatusBadGateway)+ }++ start := time.Now()+ slog.Info("svc proxy",+ "client", user.AZP, "namespace", ns, "service", service, "path", upstreamPath)+ rp.ServeHTTP(rw, r.WithContext(ctx))+ span.SetAttributes(attribute.Int("http.status_code", rw.statusCode))+ metrics.RecordUpstreamProxy("svc", rw.statusCode, time.Since(start))+}diff --git a/libs/fleet/backend/handlers/svc_test.go b/libs/fleet/backend/handlers/svc_test.gonew file mode 100644index 0000000000..e85a96b7b6--- /dev/null+++ b/libs/fleet/backend/handlers/svc_test.go@@ -0,0 +1,58 @@+package handlers++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "cyclops-cs-backend/config"+)++func TestRewriteLocation(t *testing.T) {+ tests := []struct {+ name string+ location string+ basePath string+ want string+ }{+ {"absolute /llms.txt", "/llms.txt", "/api/svc/myns/mysvc", "/api/svc/myns/mysvc/llms.txt"},+ {"absolute /foo/bar", "/foo/bar", "/api/svc/pool-test/test-abc-mcp", "/api/svc/pool-test/test-abc-mcp/foo/bar"},+ {"root /", "/", "/api/svc/ns/svc", "/api/svc/ns/svc/"},+ {"relative path", "other.html", "/api/svc/ns/svc", "/api/svc/ns/svc/other.html"},+ {"external URL unchanged", "https://example.com/foo", "/api/svc/ns/svc", "https://example.com/foo"},+ {"empty unchanged", "", "/api/svc/ns/svc", ""},+ {"absolute with query", "/search?q=test", "/api/svc/ns/svc", "/api/svc/ns/svc/search?q=test"},+ {"absolute with fragment", "/page#section", "/api/svc/ns/svc", "/api/svc/ns/svc/page#section"},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := rewriteLocation(tc.location, tc.basePath)+ if got != tc.want {+ t.Errorf("rewriteLocation(%q, %q) = %q, want %q", tc.location, tc.basePath, got, tc.want)+ }+ })+ }+}++func TestSvc_Unauthenticated(t *testing.T) {+ h := Handlers{+ GatewayCfg: config.GatewayConfiguration{+ Scheme: "http",+ Port: "80",+ ClusterDomain: "svc.cluster.local",+ },+ }++ w := httptest.NewRecorder()+ r := httptest.NewRequest("GET", "/api/svc/ns/svc/path", nil)+ r.SetPathValue("namespace", "ns")+ r.SetPathValue("service", "svc")+ r.SetPathValue("path", "path")++ h.Svc(w, r)++ if w.Code != http.StatusUnauthorized {+ t.Errorf("expected 401, got %d", w.Code)+ }+}diff --git a/libs/fleet/backend/handlers/tenants.go b/libs/fleet/backend/handlers/tenants.gonew file mode 100644index 0000000000..b5027c30bd--- /dev/null+++ b/libs/fleet/backend/handlers/tenants.go@@ -0,0 +1,331 @@+package handlers++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "slices"+ "strings"+ "time"++ "cyclops-cs-backend/identity"+)++const (+ capsuleTenantCollectionPath = "/apis/capsule.clastix.io/v1beta2/tenants"+ personalTenantEnsureTimeout = 15 * time.Second+ personalTenantReadyWaitStep = 250 * time.Millisecond+ k8sResponseBodyLimit = 64 << 10+ tenantInformerWaitTimeout = 5 * time.Second+ tenantInformerWaitStep = 250 * time.Millisecond+)++var personalTenantClusterRoles = [...]string{+ "admin",+ "capsule-namespace-deleter",+ "capsule-tenant-cluster-resources",+}++type capsuleTenant struct {+ APIVersion string `json:"apiVersion"`+ Kind string `json:"kind"`+ Metadata capsuleTenantMetadata `json:"metadata"`+ Spec capsuleTenantSpec `json:"spec"`+ Status *capsuleTenantStatus `json:"status,omitempty"`+}++type capsuleTenantMetadata struct {+ Name string `json:"name"`+}++type capsuleTenantSpec struct {+ Owners []capsuleTenantOwner `json:"owners"`+ Permissions *capsuleTenantPermissions `json:"permissions,omitempty"`+ AdditionalRoleBindings []json.RawMessage `json:"additionalRoleBindings,omitempty"`+}++type capsuleTenantPermissions struct {+ MatchOwners []json.RawMessage `json:"matchOwners,omitempty"`+}++type capsuleTenantStatus struct {+ Owners []capsuleTenantOwner `json:"owners,omitempty"`+}++type capsuleTenantOwner struct {+ Kind string `json:"kind"`+ Name string `json:"name"`+ ClusterRoles []string `json:"clusterRoles"`+ ProxySettings []json.RawMessage `json:"proxySettings,omitempty"`+}++func desiredPersonalTenant(ctx context.Context, userSub string) capsuleTenant {+ return capsuleTenant{+ APIVersion: "capsule.clastix.io/v1beta2",+ Kind: "Tenant",+ Metadata: capsuleTenantMetadata{+ Name: identity.PersonalGroup(ctx, userSub),+ },+ Spec: capsuleTenantSpec{+ Owners: []capsuleTenantOwner{{+ Kind: "User",+ Name: identity.ImpersonateUser(ctx, userSub),+ ClusterRoles: append([]string(nil), personalTenantClusterRoles[:]...),+ }},+ },+ }+}++// k8sServiceAccount performs a direct Kubernetes apiserver request as the+// backend's ServiceAccount. Unlike k8sImpersonate, it bypasses Capsule Proxy+// and deliberately sends no Impersonate-* headers; personal Tenant lifecycle+// is a backend responsibility, not a capability delegated to the caller.+func (h Handlers) k8sServiceAccount(+ ctx context.Context, method, path string, body io.Reader,+) (*http.Response, error) {+ if k8sClient == nil {+ initK8sClient()+ }+ if k8sClient == nil {+ return nil, fmt.Errorf("k8s client not initialised (missing SA token)")+ }++ if k8sDirectAPIServer == "" {+ return nil, fmt.Errorf("direct k8s apiserver is not initialised")+ }+ req, err := http.NewRequestWithContext(ctx, method, k8sDirectAPIServer+path, body)+ if err != nil {+ return nil, fmt.Errorf("build request: %w", err)+ }+ req.Header.Set("Authorization", "Bearer "+k8sSAToken)+ req.Header.Set("Content-Type", "application/json")+ return k8sClient.Do(req)+}++// ensurePersonalTenant creates the authenticated user's Capsule Tenant on+// first use. Existing Tenants are accepted only when their single static owner+// matches the expected user, carries every required role, and dynamic owner+// matching is disabled. A mismatched object is never patched or replaced, so a+// name collision fails closed instead of changing ownership.+func (h Handlers) ensurePersonalTenant(ctx context.Context, userSub string) (string, error) {+ if userSub == "" {+ return "", fmt.Errorf("authenticated subject is empty")+ }++ ctx, cancel := context.WithTimeout(ctx, personalTenantEnsureTimeout)+ defer cancel()++ desired := desiredPersonalTenant(ctx, userSub)+ if !dnsLabel.MatchString(desired.Metadata.Name) || len(desired.Metadata.Name) > 63 {+ return "", fmt.Errorf("personal tenant name is not a DNS-1123 label")+ }++ exists, ready, err := h.getAndValidatePersonalTenant(ctx, desired)+ if err != nil {+ return "", err+ }+ if exists {+ if ready {+ return desired.Metadata.Name, nil+ }+ return h.waitForPersonalTenantReady(ctx, desired)+ }++ body, err := json.Marshal(desired)+ if err != nil {+ return "", fmt.Errorf("marshal personal tenant: %w", err)+ }+ resp, err := h.k8sServiceAccount(+ ctx, http.MethodPost, capsuleTenantCollectionPath, bytes.NewReader(body),+ )+ if err != nil {+ return "", fmt.Errorf("create personal tenant: %w", err)+ }+ if _, err := readBoundedK8sBody(resp.Body); err != nil {+ resp.Body.Close()+ return "", fmt.Errorf("create personal tenant response: %w", err)+ }+ resp.Body.Close()++ switch resp.StatusCode {+ case http.StatusCreated:+ // Admission webhooks can mutate a submitted object. Read the persisted+ // Tenant back and apply the same fail-closed ownership validation used+ // for pre-existing and concurrently-created objects. Capsule authorizes+ // namespace creation from status.owners, so also wait for the controller+ // to publish the exact effective owner before continuing.+ return h.waitForPersonalTenantReady(ctx, desired)+ case http.StatusConflict:+ // Another request may have created the same Tenant between our GET and+ // POST. Re-read it and verify ownership rather than trusting the 409.+ return h.waitForPersonalTenantReady(ctx, desired)+ default:+ return "", fmt.Errorf("create personal tenant: k8s returned status %d", resp.StatusCode)+ }+}++func (h Handlers) waitForPersonalTenantReady(+ ctx context.Context, desired capsuleTenant,+) (string, error) {+ for {+ exists, ready, err := h.getAndValidatePersonalTenant(ctx, desired)+ if err != nil {+ return "", err+ }+ if !exists {+ return "", fmt.Errorf("personal tenant was not found after creation")+ }+ if ready {+ return desired.Metadata.Name, nil+ }++ select {+ case <-time.After(personalTenantReadyWaitStep):+ case <-ctx.Done():+ return "", fmt.Errorf("wait for personal tenant readiness: %w", ctx.Err())+ }+ }+}++func (h Handlers) getAndValidatePersonalTenant(+ ctx context.Context, desired capsuleTenant,+) (bool, bool, error) {+ path := capsuleTenantCollectionPath + "/" + url.PathEscape(desired.Metadata.Name)+ resp, err := h.k8sServiceAccount(ctx, http.MethodGet, path, nil)+ if err != nil {+ return false, false, fmt.Errorf("get personal tenant: %w", err)+ }+ defer resp.Body.Close()+ body, err := readBoundedK8sBody(resp.Body)+ if err != nil {+ return false, false, fmt.Errorf("get personal tenant response: %w", err)+ }++ switch resp.StatusCode {+ case http.StatusNotFound:+ return false, false, nil+ case http.StatusOK:+ var existing capsuleTenant+ if err := json.Unmarshal(body, &existing); err != nil {+ return false, false, fmt.Errorf("decode existing personal tenant: %w", err)+ }+ if err := validatePersonalTenant(existing, desired); err != nil {+ return false, false, err+ }+ ready := existing.Status != nil && len(existing.Status.Owners) == 1+ return true, ready, nil+ default:+ return false, false, fmt.Errorf("get personal tenant: k8s returned status %d", resp.StatusCode)+ }+}++func validatePersonalTenant(existing, desired capsuleTenant) error {+ if existing.APIVersion != desired.APIVersion || existing.Kind != desired.Kind {+ return fmt.Errorf("existing personal tenant type does not match")+ }+ if existing.Metadata.Name != desired.Metadata.Name {+ return fmt.Errorf("existing personal tenant metadata does not match")+ }+ if len(existing.Spec.Owners) != 1 {+ return fmt.Errorf("existing personal tenant owner does not match")+ }+ // Capsule promotes TenantOwner resources selected by matchOwners into the+ // effective owner list. Personal Tenants must never enable that second+ // ownership path, even when their static owner looks correct.+ if existing.Spec.Permissions != nil &&+ len(existing.Spec.Permissions.MatchOwners) != 0 {+ return fmt.Errorf("existing personal tenant owner does not match")+ }+ if len(existing.Spec.AdditionalRoleBindings) != 0 {+ return fmt.Errorf("existing personal tenant role bindings do not match")+ }+ existingOwner := existing.Spec.Owners[0]+ desiredOwner := desired.Spec.Owners[0]+ if existingOwner.Kind != desiredOwner.Kind ||+ existingOwner.Name != desiredOwner.Name ||+ !sameClusterRoleSet(existingOwner.ClusterRoles, desiredOwner.ClusterRoles) ||+ len(existingOwner.ProxySettings) != 0 {+ return fmt.Errorf("existing personal tenant owner does not match")+ }+ // status.owners is what Capsule uses for authorization. It may be empty+ // immediately after creation, before the controller's first reconcile. Once+ // populated, reject stale or dynamically-added effective owners as well.+ if existing.Status != nil && len(existing.Status.Owners) != 0 {+ if len(existing.Status.Owners) != 1 {+ return fmt.Errorf("existing personal tenant effective owner does not match")+ }+ effectiveOwner := existing.Status.Owners[0]+ if effectiveOwner.Kind != desiredOwner.Kind ||+ effectiveOwner.Name != desiredOwner.Name ||+ !sameClusterRoleSet(effectiveOwner.ClusterRoles, desiredOwner.ClusterRoles) {+ return fmt.Errorf("existing personal tenant effective owner does not match")+ }+ }+ return nil+}++func sameClusterRoleSet(existing, required []string) bool {+ if len(existing) != len(required) {+ return false+ }+ for _, role := range required {+ if !slices.Contains(existing, role) {+ return false+ }+ }+ return true+}++func readBoundedK8sBody(r io.Reader) ([]byte, error) {+ body, err := io.ReadAll(io.LimitReader(r, k8sResponseBodyLimit+1))+ if err != nil {+ return nil, err+ }+ if len(body) > k8sResponseBodyLimit {+ return nil, fmt.Errorf("response body exceeds %d bytes", k8sResponseBodyLimit)+ }+ return body, nil+}++// isPersonalTenantAdmissionCacheLag identifies the two retryable namespace+// admission failures after a Tenant is first created. Capsule's webhook reads+// both the Tenant and status.owners from its controller-runtime cache, which+// can briefly lag the successful direct-apiserver reads above. Match only the+// exact Capsule errors so unrelated admission failures return immediately.+func isPersonalTenantAdmissionCacheLag(statusCode int, body []byte, tenantName string) bool {+ var status struct {+ Kind string `json:"kind"`+ Status string `json:"status"`+ Message string `json:"message"`+ Code int `json:"code"`+ }+ if json.Unmarshal(body, &status) != nil ||+ status.Kind != "Status" ||+ status.Status != "Failure" ||+ status.Code != statusCode {+ return false+ }+ if statusCode == http.StatusBadRequest {+ return strings.Contains(+ status.Message,+ "can not assign the desired namespace to a non-owned Tenant",+ )+ }+ if statusCode != http.StatusInternalServerError {+ return false+ }+ for _, resource := range []string{+ "Tenant.capsule.clastix.io",+ "tenants.capsule.clastix.io",+ } {+ want := fmt.Sprintf("%s %q not found", resource, tenantName)+ if strings.Contains(status.Message, want) {+ return true+ }+ }+ return false+}diff --git a/libs/fleet/backend/handlers/tenants_test.go b/libs/fleet/backend/handlers/tenants_test.gonew file mode 100644index 0000000000..9adcbaee99--- /dev/null+++ b/libs/fleet/backend/handlers/tenants_test.go@@ -0,0 +1,621 @@+package handlers++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "reflect"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "cyclops-cs-backend/auth"+)++type roundTripperFunc func(*http.Request) (*http.Response, error)++func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) {+ return f(r)+}++func TestCreateNamespace_FirstUseCreatesPersonalTenant(t *testing.T) {+ const userSub = "test-uuid"+ desired := desiredPersonalTenant(context.Background(), userSub)+ tenantPath := capsuleTenantCollectionPath + "/" + desired.Metadata.Name+ tenantGetCount := 0+ namespacePostCount := 0++ fk := newFakeK8sHandler(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == tenantPath:+ tenantGetCount+++ if tenantGetCount == 1 {+ w.WriteHeader(http.StatusNotFound)+ _, _ = w.Write([]byte(`{"kind":"Status","reason":"NotFound"}`))+ return+ }+ if tenantGetCount == 2 {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(pendingPersonalTenantResponse(userSub)))+ return+ }+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(existingPersonalTenantResponse(userSub)))+ case r.Method == http.MethodPost && r.URL.Path == capsuleTenantCollectionPath:+ w.WriteHeader(http.StatusCreated)+ _, _ = w.Write([]byte(existingPersonalTenantResponse(userSub)))+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/namespaces":+ namespacePostCount+++ if namespacePostCount == 1 {+ status, _ := json.Marshal(map[string]any{+ "kind": "Status",+ "status": "Failure",+ "code": http.StatusBadRequest,+ "message": "admission webhook denied the request: can not assign the desired namespace to a non-owned Tenant",+ })+ w.WriteHeader(http.StatusBadRequest)+ _, _ = w.Write(status)+ return+ }+ if namespacePostCount == 2 {+ status, _ := json.Marshal(map[string]any{+ "kind": "Status",+ "status": "Failure",+ "code": http.StatusInternalServerError,+ "message": "admission failed: Tenant.capsule.clastix.io \"" ++ desired.Metadata.Name + "\" not found",+ })+ w.WriteHeader(http.StatusInternalServerError)+ _, _ = w.Write(status)+ return+ }+ w.WriteHeader(http.StatusCreated)+ _, _ = w.Write([]byte(nsCreatedResponse("my-workspace")))+ case r.Method == http.MethodGet && strings.HasPrefix(+ r.URL.Path, "/apis/rbac.authorization.k8s.io/v1/namespaces/",+ ):+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"items":[]}`))+ default:+ t.Errorf("unexpected k8s request: %s %s", r.Method, r.URL.Path)+ w.WriteHeader(http.StatusInternalServerError)+ }+ })+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ h := Handlers{}+ r := httptest.NewRequest(+ http.MethodPost, "/api/namespaces", strings.NewReader(`{"name":"my-workspace"}`),+ )+ r = withUser(r, &auth.User{ID: userSub})+ w := httptest.NewRecorder()++ h.CreateNamespace(w, r)++ if w.Code != http.StatusCreated {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusCreated, w.Body.String())+ }+ if len(fk.requests) != 8 {+ t.Fatalf("request count = %d, want 8", len(fk.requests))+ }+ wantSequence := []struct {+ method string+ path string+ }{+ {http.MethodGet, tenantPath},+ {http.MethodPost, capsuleTenantCollectionPath},+ {http.MethodGet, tenantPath},+ {http.MethodGet, tenantPath},+ {http.MethodPost, "/api/v1/namespaces"},+ {http.MethodPost, "/api/v1/namespaces"},+ {http.MethodPost, "/api/v1/namespaces"},+ {http.MethodGet, "/apis/rbac.authorization.k8s.io/v1/namespaces/my-workspace/rolebindings"},+ }+ for i, want := range wantSequence {+ got := fk.requests[i]+ if got.method != want.method || got.path != want.path {+ t.Fatalf("request[%d] = %s %s, want %s %s", i, got.method, got.path, want.method, want.path)+ }+ }++ for i := 0; i < 4; i++ {+ request := fk.requests[i]+ if got := request.headers.Get("Authorization"); got != "Bearer fake-sa-token" {+ t.Fatalf("tenant request[%d] Authorization = %q", i, got)+ }+ if got := request.headers.Get("Impersonate-User"); got != "" {+ t.Fatalf("tenant request[%d] Impersonate-User = %q, want empty", i, got)+ }+ if got := request.headers.Get("Impersonate-Group"); got != "" {+ t.Fatalf("tenant request[%d] Impersonate-Group = %q, want empty", i, got)+ }+ }++ var created capsuleTenant+ if err := json.Unmarshal(fk.requests[1].body, &created); err != nil {+ t.Fatalf("decode Tenant create body: %v", err)+ }+ if created.APIVersion != "capsule.clastix.io/v1beta2" || created.Kind != "Tenant" {+ t.Fatalf("unexpected Tenant type: %s %s", created.APIVersion, created.Kind)+ }+ if err := validatePersonalTenant(created, desired); err != nil {+ t.Fatalf("Tenant create body mismatch: %v; body = %s", err, fk.requests[1].body)+ }+ wantRoles := []string{+ "admin",+ "capsule-namespace-deleter",+ "capsule-tenant-cluster-resources",+ }+ if got := created.Spec.Owners[0].ClusterRoles; !reflect.DeepEqual(got, wantRoles) {+ t.Fatalf("Tenant clusterRoles = %#v, want literal roles %#v", got, wantRoles)+ }++ namespaceRequest := fk.requests[6]+ if got := namespaceRequest.headers.Get("Impersonate-User"); got != "oidc:"+userSub {+ t.Fatalf("namespace Impersonate-User = %q, want %q", got, "oidc:"+userSub)+ }+}++func TestValidatePersonalTenant_RejectsRoleAndOwnerDrift(t *testing.T) {+ desired := desiredPersonalTenant(context.Background(), "test-uuid")+ tests := []struct {+ name string+ mutate func(*capsuleTenant)+ }{+ {+ name: "extra role",+ mutate: func(tenant *capsuleTenant) {+ tenant.Spec.Owners[0].ClusterRoles = append(+ tenant.Spec.Owners[0].ClusterRoles, "cluster-admin",+ )+ },+ },+ {+ name: "missing role",+ mutate: func(tenant *capsuleTenant) {+ tenant.Spec.Owners[0].ClusterRoles = tenant.Spec.Owners[0].ClusterRoles[:2]+ },+ },+ {+ name: "substituted role",+ mutate: func(tenant *capsuleTenant) {+ tenant.Spec.Owners[0].ClusterRoles[1] = "cluster-admin"+ },+ },+ {+ name: "duplicate role",+ mutate: func(tenant *capsuleTenant) {+ tenant.Spec.Owners[0].ClusterRoles[1] = "admin"+ },+ },+ {+ name: "extra owner",+ mutate: func(tenant *capsuleTenant) {+ tenant.Spec.Owners = append(tenant.Spec.Owners, tenant.Spec.Owners[0])+ },+ },+ {+ name: "dynamic owner selector",+ mutate: func(tenant *capsuleTenant) {+ tenant.Spec.Permissions = &capsuleTenantPermissions{+ MatchOwners: []json.RawMessage{json.RawMessage(`{"matchLabels":{"team":"all"}}`)},+ }+ },+ },+ {+ name: "additional role binding",+ mutate: func(tenant *capsuleTenant) {+ tenant.Spec.AdditionalRoleBindings = []json.RawMessage{+ json.RawMessage(`{"clusterRoleName":"cluster-admin"}`),+ }+ },+ },+ {+ name: "owner proxy settings",+ mutate: func(tenant *capsuleTenant) {+ tenant.Spec.Owners[0].ProxySettings = []json.RawMessage{+ json.RawMessage(`{"kind":"Nodes","operations":["List"]}`),+ }+ },+ },+ {+ name: "extra effective owner",+ mutate: func(tenant *capsuleTenant) {+ tenant.Status = &capsuleTenantStatus{Owners: []capsuleTenantOwner{+ tenant.Spec.Owners[0],+ {Kind: "Group", Name: "oidc:someone-else"},+ }}+ },+ },+ {+ name: "wrong effective owner",+ mutate: func(tenant *capsuleTenant) {+ tenant.Status = &capsuleTenantStatus{Owners: []capsuleTenantOwner{{+ Kind: "User",+ Name: "oidc:someone-else",+ ClusterRoles: append([]string(nil), personalTenantClusterRoles[:]...),+ }}}+ },+ },+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ existing := desiredPersonalTenant(context.Background(), "test-uuid")+ tc.mutate(&existing)+ if err := validatePersonalTenant(existing, desired); err == nil {+ t.Fatal("validatePersonalTenant() accepted mismatched Tenant")+ }+ })+ }+}++func TestValidatePersonalTenant_RejectsPrivilegeFieldsFromKubernetesJSON(t *testing.T) {+ desired := desiredPersonalTenant(context.Background(), "test-uuid")+ const base = `{+ "apiVersion":"capsule.clastix.io/v1beta2",+ "kind":"Tenant",+ "metadata":{"name":"user-test-uuid"},+ "spec":{+ "owners":[{+ "kind":"User",+ "name":"oidc:test-uuid",+ "clusterRoles":["admin","capsule-namespace-deleter","capsule-tenant-cluster-resources"]+ }]+ PRIVILEGE_FIELD+ }+ }`+ fields := []string{+ `,"permissions":{"matchOwners":[{}]}`,+ `,"additionalRoleBindings":[{"clusterRoleName":"cluster-admin"}]`,+ }+ for _, field := range fields {+ var existing capsuleTenant+ raw := strings.Replace(base, "PRIVILEGE_FIELD", field, 1)+ if err := json.Unmarshal([]byte(raw), &existing); err != nil {+ t.Fatalf("decode test Tenant: %v", err)+ }+ if err := validatePersonalTenant(existing, desired); err == nil {+ t.Fatalf("accepted Kubernetes Tenant privilege field %s", field)+ }+ }+}++func TestValidatePersonalTenant_AcceptsEquivalentRoleOrderAndEmptyDynamicOwners(t *testing.T) {+ desired := desiredPersonalTenant(context.Background(), "test-uuid")+ existing := desiredPersonalTenant(context.Background(), "test-uuid")+ existing.Spec.Owners[0].ClusterRoles = []string{+ "capsule-tenant-cluster-resources",+ "admin",+ "capsule-namespace-deleter",+ }+ existing.Spec.Permissions = &capsuleTenantPermissions{MatchOwners: []json.RawMessage{}}+ existing.Status = &capsuleTenantStatus{Owners: []capsuleTenantOwner{+ existing.Spec.Owners[0],+ }}++ if err := validatePersonalTenant(existing, desired); err != nil {+ t.Fatalf("validatePersonalTenant() rejected equivalent Tenant: %v", err)+ }+}++func TestPersonalTenantAdmissionCacheLag_OnlyMatchesExactCapsuleErrors(t *testing.T) {+ for _, resource := range []string{"Tenant.capsule.clastix.io", "tenants.capsule.clastix.io"} {+ body := []byte(`{"kind":"Status","status":"Failure","code":500,"message":"` ++ resource + ` \"user-test-uuid\" not found"}`)+ if !isPersonalTenantAdmissionCacheLag(http.StatusInternalServerError, body, "user-test-uuid") {+ t.Fatalf("expected %s cache miss to be retryable", resource)+ }+ }+ body := []byte(`{"kind":"Status","status":"Failure","code":500,"message":"Tenant.capsule.clastix.io \"user-test-uuid\" not found"}`)+ if isPersonalTenantAdmissionCacheLag(http.StatusInternalServerError, body, "user-someone-else") {+ t.Fatal("matched a different Tenant name")+ }+ if isPersonalTenantAdmissionCacheLag(http.StatusBadGateway, body, "user-test-uuid") {+ t.Fatal("matched a non-500 response")+ }+ if isPersonalTenantAdmissionCacheLag(+ http.StatusInternalServerError,+ []byte(`{"kind":"Status","status":"Failure","code":500,"message":"another admission webhook failed"}`),+ "user-test-uuid",+ ) {+ t.Fatal("matched an unrelated admission failure")+ }+ for _, malformed := range [][]byte{+ []byte(`Tenant.capsule.clastix.io "user-test-uuid" not found`),+ []byte(`{"message":"Tenant.capsule.clastix.io \"user-test-uuid\" not found"}`),+ []byte(`{"kind":"Status","status":"Failure","code":500`),+ } {+ if isPersonalTenantAdmissionCacheLag(+ http.StatusInternalServerError, malformed, "user-test-uuid",+ ) {+ t.Fatalf("matched malformed or non-Status body: %q", malformed)+ }+ }+ nonOwned := []byte(`{"kind":"Status","status":"Failure","code":400,"message":"admission webhook denied the request: can not assign the desired namespace to a non-owned Tenant"}`)+ if !isPersonalTenantAdmissionCacheLag(http.StatusBadRequest, nonOwned, "user-test-uuid") {+ t.Fatal("expected exact non-owned Tenant cache lag to be retryable")+ }+ if isPersonalTenantAdmissionCacheLag(http.StatusInternalServerError, nonOwned, "user-test-uuid") {+ t.Fatal("matched non-owned Tenant message with mismatched HTTP status")+ }+}++func TestK8sTenantLifecycleBypassesCapsuleProxy(t *testing.T) {+ const userSub = "test-uuid"+ direct := newFakeK8s(http.StatusOK, existingPersonalTenantResponse(userSub))+ defer direct.server.Close()+ proxy := newFakeK8s(http.StatusCreated, nsCreatedResponse("my-workspace"))+ defer proxy.server.Close()+ overrideK8sClientTargets(+ direct.server.Client(), proxy.server.URL, direct.server.URL, "fake-sa-token",+ )++ h := Handlers{}+ if _, err := h.ensurePersonalTenant(context.Background(), userSub); err != nil {+ t.Fatalf("ensurePersonalTenant() error = %v", err)+ }+ resp, err := h.k8sImpersonate(+ context.Background(), http.MethodPost, "/api/v1/namespaces", nil, userSub,+ )+ if err != nil {+ t.Fatalf("k8sImpersonate() error = %v", err)+ }+ resp.Body.Close()++ if len(direct.requests) != 1 || direct.requests[0].path != capsuleTenantCollectionPath+"/user-"+userSub {+ t.Fatalf("direct apiserver requests = %+v, want only Tenant GET", direct.requests)+ }+ if got := direct.requests[0].headers.Get("Impersonate-User"); got != "" {+ t.Fatalf("direct Tenant request Impersonate-User = %q, want empty", got)+ }+ if len(proxy.requests) != 1 || proxy.requests[0].path != "/api/v1/namespaces" {+ t.Fatalf("Capsule Proxy requests = %+v, want only Namespace POST", proxy.requests)+ }+ if got := proxy.requests[0].headers.Get("Impersonate-User"); got != "oidc:"+userSub {+ t.Fatalf("proxy Namespace request Impersonate-User = %q", got)+ }+}++func TestCreateNamespace_CancellationBoundsInformerRetryRequest(t *testing.T) {+ const userSub = "test-uuid"+ direct := newFakeK8s(http.StatusOK, existingPersonalTenantResponse(userSub))+ defer direct.server.Close()++ var posts atomic.Int32+ started := make(chan struct{}, 1)+ baseTransport := direct.server.Client().Transport+ client := &http.Client{Transport: roundTripperFunc(func(r *http.Request) (*http.Response, error) {+ if r.URL.Host == "capsule-proxy.test" {+ posts.Add(1)+ started <- struct{}{}+ <-r.Context().Done()+ return nil, r.Context().Err()+ }+ return baseTransport.RoundTrip(r)+ })}+ overrideK8sClientTargets(+ client, "http://capsule-proxy.test", direct.server.URL, "fake-sa-token",+ )++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ r := httptest.NewRequest(+ http.MethodPost, "/api/namespaces", strings.NewReader(`{"name":"my-workspace"}`),+ ).WithContext(ctx)+ r = withUser(r, &auth.User{ID: userSub})+ w := httptest.NewRecorder()+ done := make(chan struct{})+ go func() {+ (Handlers{}).CreateNamespace(w, r)+ close(done)+ }()++ select {+ case <-started:+ cancel()+ case <-time.After(2 * time.Second):+ cancel()+ select {+ case <-done:+ case <-time.After(time.Second):+ }+ t.Fatal("namespace POST did not start")+ }+ select {+ case <-done:+ case <-time.After(time.Second):+ t.Fatal("handler did not stop after request cancellation")+ }++ if w.Code != http.StatusBadGateway {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadGateway, w.Body.String())+ }+ if got := posts.Load(); got != 1 {+ t.Fatalf("namespace POST count = %d, want 1", got)+ }+}++func TestEnsurePersonalTenant_AlreadyExists(t *testing.T) {+ const userSub = "test-uuid"+ fk := newFakeK8s(http.StatusOK, existingPersonalTenantResponse(userSub))+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ if _, err := (Handlers{}).ensurePersonalTenant(context.Background(), userSub); err != nil {+ t.Fatalf("ensurePersonalTenant() error = %v", err)+ }+ if len(fk.requests) != 1 {+ t.Fatalf("request count = %d, want 1 GET", len(fk.requests))+ }+ if got := fk.requests[0].method; got != http.MethodGet {+ t.Fatalf("method = %q, want GET", got)+ }+ if got := fk.requests[0].headers.Get("Impersonate-User"); got != "" {+ t.Fatalf("Impersonate-User = %q, want empty", got)+ }+}++func TestCreateNamespace_PendingTenantStatusStopsBeforeNamespace(t *testing.T) {+ const userSub = "test-uuid"+ var gets atomic.Int32+ secondGet := make(chan struct{}, 1)+ direct := newFakeK8sHandler(func(w http.ResponseWriter, _ *http.Request) {+ if gets.Add(1) == 2 {+ secondGet <- struct{}{}+ }+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(pendingPersonalTenantResponse(userSub)))+ })+ defer direct.server.Close()+ proxy := newFakeK8s(http.StatusInternalServerError, "unexpected namespace request")+ defer proxy.server.Close()+ overrideK8sClientTargets(+ direct.server.Client(), proxy.server.URL, direct.server.URL, "fake-sa-token",+ )++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ r := httptest.NewRequest(+ http.MethodPost, "/api/namespaces", strings.NewReader(`{"name":"my-workspace"}`),+ ).WithContext(ctx)+ r = withUser(r, &auth.User{ID: userSub})+ w := httptest.NewRecorder()+ done := make(chan struct{})+ go func() {+ (Handlers{}).CreateNamespace(w, r)+ close(done)+ }()++ select {+ case <-secondGet:+ cancel()+ case <-time.After(2 * time.Second):+ cancel()+ select {+ case <-done:+ case <-time.After(time.Second):+ }+ t.Fatal("Tenant readiness was not polled")+ }+ select {+ case <-done:+ case <-time.After(time.Second):+ t.Fatal("handler did not stop after readiness wait cancellation")+ }++ if w.Code != http.StatusBadGateway {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadGateway, w.Body.String())+ }+ if len(proxy.requests) != 0 {+ t.Fatalf("namespace requests = %+v, want none before status.owners is ready", proxy.requests)+ }+}++func TestEnsurePersonalTenant_CreateConflictRevalidatesWinner(t *testing.T) {+ const userSub = "test-uuid"+ getCount := 0+ fk := newFakeK8sHandler(func(w http.ResponseWriter, r *http.Request) {+ switch r.Method {+ case http.MethodGet:+ getCount+++ if getCount == 1 {+ w.WriteHeader(http.StatusNotFound)+ return+ }+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(existingPersonalTenantResponse(userSub)))+ case http.MethodPost:+ w.WriteHeader(http.StatusConflict)+ default:+ t.Errorf("unexpected method: %s", r.Method)+ w.WriteHeader(http.StatusInternalServerError)+ }+ })+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ if _, err := (Handlers{}).ensurePersonalTenant(context.Background(), userSub); err != nil {+ t.Fatalf("ensurePersonalTenant() error = %v", err)+ }+ if len(fk.requests) != 3 {+ t.Fatalf("request count = %d, want GET, POST, GET", len(fk.requests))+ }+ if fk.requests[0].method != http.MethodGet ||+ fk.requests[1].method != http.MethodPost ||+ fk.requests[2].method != http.MethodGet {+ t.Fatalf("unexpected request sequence: %+v", fk.requests)+ }+}++func TestCreateNamespace_MismatchedTenantFailsClosed(t *testing.T) {+ existing := desiredPersonalTenant(context.Background(), "test-uuid")+ existing.Spec.Owners[0].Name = "oidc:someone-else"+ body, err := json.Marshal(existing)+ if err != nil {+ t.Fatal(err)+ }++ fk := newFakeK8s(http.StatusOK, string(body))+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ h := Handlers{}+ r := httptest.NewRequest(+ http.MethodPost, "/api/namespaces", strings.NewReader(`{"name":"my-workspace"}`),+ )+ r = withUser(r, &auth.User{ID: "test-uuid"})+ w := httptest.NewRecorder()+ h.CreateNamespace(w, r)++ if w.Code != http.StatusBadGateway {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadGateway, w.Body.String())+ }+ if len(fk.requests) != 1 || fk.requests[0].method != http.MethodGet {+ t.Fatalf("requests = %+v, want only Tenant GET", fk.requests)+ }+ if strings.Contains(w.Body.String(), "someone-else") {+ t.Fatalf("response exposed Tenant details: %s", w.Body.String())+ }+}++func TestCreateNamespace_TenantBackendFailureStopsBeforeNamespace(t *testing.T) {+ fk := newFakeK8s(http.StatusInternalServerError, "backend unavailable")+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ h := Handlers{}+ r := httptest.NewRequest(+ http.MethodPost, "/api/namespaces", strings.NewReader(`{"name":"my-workspace"}`),+ )+ r = withUser(r, &auth.User{ID: "test-uuid"})+ w := httptest.NewRecorder()+ h.CreateNamespace(w, r)++ if w.Code != http.StatusBadGateway {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadGateway, w.Body.String())+ }+ if len(fk.requests) != 1 || fk.requests[0].method != http.MethodGet {+ t.Fatalf("requests = %+v, want only Tenant GET", fk.requests)+ }+ if got, want := w.Body.String(), "{\"error\":\"could not ensure personal tenant\"}\n"; got != want {+ t.Fatalf("body = %q, want bounded generic error %q", got, want)+ }+}++func TestCreateNamespace_EmptySubjectIsUnauthorized(t *testing.T) {+ h := Handlers{}+ r := httptest.NewRequest(+ http.MethodPost, "/api/namespaces", strings.NewReader(`{"name":"my-workspace"}`),+ )+ r = withUser(r, &auth.User{})+ w := httptest.NewRecorder()++ h.CreateNamespace(w, r)++ if w.Code != http.StatusUnauthorized {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusUnauthorized, w.Body.String())+ }+}diff --git a/libs/fleet/backend/handlers/user_keys.go b/libs/fleet/backend/handlers/user_keys.gonew file mode 100644index 0000000000..fa9107bc8a--- /dev/null+++ b/libs/fleet/backend/handlers/user_keys.go@@ -0,0 +1,150 @@+package handlers++import (+ "encoding/json"+ "net/http"+)++// CreateUserKeyRequest is the body for POST /api/user-keys.+type CreateUserKeyRequest struct {+ Name string `json:"name" example:"my-ci-key"`+ Scope []string `json:"scope" example:"[\"ns1\",\"ns2\"]"`+}++// CreateUserKeyResponse is returned on successful creation. The+// `client_secret` is shown exactly ONCE and cannot be retrieved later.+type CreateUserKeyResponse struct {+ ClientID string `json:"client_id"`+ ClientSecret string `json:"client_secret"`+ TokenURL string `json:"token_url"`+ Name string `json:"name"`+ Scope []string `json:"scope"`+}++// UserKeyResponse is a single key in the list response (no secret).+type UserKeyResponse struct {+ ID string `json:"id"`+ ClientID string `json:"client_id"`+ Name string `json:"name"`+ Scope []string `json:"scope"`+}++// ListUserKeysResponse wraps the user keys list.+type ListUserKeysResponse struct {+ Keys []UserKeyResponse `json:"keys"`+}++// CreateUserKey godoc+//+// @Summary Create a per-user API key+// @Description Creates a Keycloak service-account client that acts on behalf of the calling user. The client_secret is returned exactly once; it cannot be retrieved later.+// @Tags user-keys+// @Accept json+// @Produce json+// @Param body body CreateUserKeyRequest true "Key parameters"+// @Success 201 {object} CreateUserKeyResponse+// @Failure 400 {object} ErrorResponse+// @Failure 401 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/user-keys [post]+func (h Handlers) CreateUserKey(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }+ var req CreateUserKeyRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeErr(w, http.StatusBadRequest, "invalid body")+ return+ }+ if req.Name == "" {+ writeErr(w, http.StatusBadRequest, "name is required")+ return+ }+ // Validate scope entries if provided.+ for _, ns := range req.Scope {+ if !dnsLabel.MatchString(ns) || len(ns) > 63 {+ writeErr(w, http.StatusBadRequest, "each scope entry must be a DNS-1123 label")+ return+ }+ }++ cid, secret, tokenURL, err := h.Admin.CreateUserKeyClient(r.Context(), req.Name, user.ID, req.Scope)+ if err != nil {+ writeErr(w, http.StatusInternalServerError, "keycloak: "+err.Error())+ return+ }+ writeJSON(w, http.StatusCreated, CreateUserKeyResponse{+ ClientID: cid,+ ClientSecret: secret,+ TokenURL: tokenURL,+ Name: req.Name,+ Scope: req.Scope,+ })+}++// ListUserKeys godoc+//+// @Summary List the calling user's API keys+// @Tags user-keys+// @Produce json+// @Success 200 {object} ListUserKeysResponse+// @Failure 401 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/user-keys [get]+func (h Handlers) ListUserKeys(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }++ keys, err := h.Admin.ListUserKeyClients(r.Context(), user.ID)+ if err != nil {+ writeErr(w, http.StatusInternalServerError, "keycloak: "+err.Error())+ return+ }++ resp := make([]UserKeyResponse, 0, len(keys))+ for _, k := range keys {+ resp = append(resp, UserKeyResponse{+ ID: k.ID,+ ClientID: k.ClientID,+ Name: k.Name,+ Scope: k.Scope,+ })+ }+ writeJSON(w, http.StatusOK, ListUserKeysResponse{Keys: resp})+}++// DeleteUserKey godoc+//+// @Summary Revoke a per-user API key+// @Tags user-keys+// @Produce json+// @Param id path string true "Keycloak client UUID"+// @Success 204+// @Failure 401 {object} ErrorResponse+// @Failure 403 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/user-keys/{id} [delete]+func (h Handlers) DeleteUserKey(w http.ResponseWriter, r *http.Request) {+ user := currentUser(r)+ if user == nil {+ writeErr(w, http.StatusUnauthorized, "missing user")+ return+ }+ id := r.PathValue("id")+ if id == "" {+ writeErr(w, http.StatusBadRequest, "id is required")+ return+ }++ if err := h.Admin.DeleteUserKeyClient(r.Context(), user.ID, id); err != nil {+ writeErr(w, http.StatusForbidden, err.Error())+ return+ }+ w.WriteHeader(http.StatusNoContent)+}+diff --git a/libs/fleet/backend/handlers/workload_oidc.go b/libs/fleet/backend/handlers/workload_oidc.gonew file mode 100644index 0000000000..35b02392f7--- /dev/null+++ b/libs/fleet/backend/handlers/workload_oidc.go@@ -0,0 +1,108 @@+package handlers++import (+ "bytes"+ "context"+ "encoding/json"+ "io"+ "log/slog"+ "net/http"+ "net/url"++ "cyclops-cs-backend/identity"+)++// workloadOIDCSecretName is the conventional name of the per-tenant Keycloak+// workload-OIDC credentials Secret written into each pool namespace. The+// OSGym pool's vmTemplate.oidc.credentialsSecret defaults to this (see+// charts/osgym-workspace-test/values.yaml and+// docs/decisions/2026-06-25-osgym-pool-workload-oidc.md).+const workloadOIDCSecretName = "cua-workload-oidc"++// provisionWorkloadOIDC best-effort ensures the tenant's workloads-realm+// Keycloak client exists and writes its credentials into a Secret in the+// just-created namespace, so OSGym pool VMs in that namespace can mint a+// tenant-scoped OIDC token. No-op when the feature is disabled+// (WorkloadAdmin nil). All failures are logged, never surfaced: the+// namespace was created either way, and the OSGym Sandbox controller retries+// until the Secret appears.+func (h Handlers) provisionWorkloadOIDC(ctx context.Context, userSub, namespace string) {+ if h.WorkloadAdmin == nil {+ return+ }+ tenant := identity.PersonalGroup(ctx, userSub)+ clientID, clientSecret, err := h.WorkloadAdmin.EnsureTenantWorkloadClient(+ ctx, userSub, tenant, h.WorkloadAudience,+ )+ if err != nil {+ slog.Warn("workload-oidc: ensure tenant client failed",+ "err", err, "namespace", namespace, "tenant", tenant)+ return+ }+ if err := h.writeWorkloadOIDCSecret(+ ctx, userSub, namespace, clientID, clientSecret, tenant,+ ); err != nil {+ slog.Warn("workload-oidc: write credentials Secret failed",+ "err", err, "namespace", namespace)+ return+ }+ slog.Info("workload-oidc: provisioned tenant credentials",+ "namespace", namespace, "tenant", tenant, "client_id", clientID)+}++// writeWorkloadOIDCSecret creates the credentials Secret in the namespace via+// impersonation (the caller has admin in their own Capsule namespace). An+// already-exists conflict is treated as success: EnsureTenantWorkloadClient+// returns a stable secret, so an existing Secret already holds the right+// credentials.+func (h Handlers) writeWorkloadOIDCSecret(+ ctx context.Context, userSub, namespace, clientID, clientSecret, tenant string,+) error {+ secret := map[string]any{+ "apiVersion": "v1",+ "kind": "Secret",+ "metadata": map[string]any{+ "name": workloadOIDCSecretName,+ "namespace": namespace,+ "labels": map[string]string{+ "app.kubernetes.io/managed-by": "cyclops-cs-backend",+ "cua.ai/purpose": "workload-oidc",+ },+ },+ "type": "Opaque",+ // client_id/client_secret are what the in-guest refresher uses;+ // tenant/token_url are surfaced for convenience (a customer reads+ // `tenant` to write their OIDC trust policy condition).+ "stringData": map[string]string{+ "client_id": clientID,+ "client_secret": clientSecret,+ "tenant": tenant,+ "token_url": h.WorkloadTokenURL,+ },+ }+ body, err := json.Marshal(secret)+ if err != nil {+ return err+ }+ resp, err := h.k8sImpersonate(+ ctx, "POST",+ "/api/v1/namespaces/"+url.PathEscape(namespace)+"/secrets",+ bytes.NewReader(body), userSub,+ )+ if err != nil {+ return err+ }+ defer resp.Body.Close()+ _, _ = io.Copy(io.Discard, resp.Body)+ if resp.StatusCode == http.StatusCreated || resp.StatusCode == http.StatusConflict {+ return nil+ }+ return &k8sStatusError{code: resp.StatusCode}+}++// k8sStatusError is a tiny error carrying an unexpected K8s HTTP status.+type k8sStatusError struct{ code int }++func (e *k8sStatusError) Error() string {+ return "unexpected k8s status " + http.StatusText(e.code)+}diff --git a/libs/fleet/backend/handlers/workload_oidc_test.go b/libs/fleet/backend/handlers/workload_oidc_test.gonew file mode 100644index 0000000000..c3503f65e7--- /dev/null+++ b/libs/fleet/backend/handlers/workload_oidc_test.go@@ -0,0 +1,101 @@+package handlers++import (+ "context"+ "encoding/json"+ "net/http"+ "testing"+)++// When the feature is disabled (WorkloadAdmin nil), provisioning is a no-op+// and never touches Kubernetes.+func TestProvisionWorkloadOIDC_DisabledIsNoop(t *testing.T) {+ fk := newFakeK8s(http.StatusCreated, "{}")+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ h := Handlers{} // WorkloadAdmin == nil+ h.provisionWorkloadOIDC(context.Background(), "sub-1", "mypool")++ if len(fk.requests) != 0 {+ t.Fatalf("disabled feature made %d k8s request(s), want 0", len(fk.requests))+ }+}++func TestWriteWorkloadOIDCSecret_PostsSecret(t *testing.T) {+ fk := newFakeK8s(http.StatusCreated, "{}")+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ h := Handlers{+ WorkloadTokenURL: "https://auth.cua.ai/realms/workloads/protocol/openid-connect/token",+ }+ err := h.writeWorkloadOIDCSecret(+ context.Background(), "sub-1", "mypool",+ "tenant-sub-1", "secret-xyz", "user-sub-1",+ )+ if err != nil {+ t.Fatalf("writeWorkloadOIDCSecret err = %v", err)+ }+ if len(fk.requests) != 1 {+ t.Fatalf("expected 1 k8s request, got %d", len(fk.requests))+ }+ req := fk.requests[0]+ if req.method != http.MethodPost ||+ req.path != "/api/v1/namespaces/mypool/secrets" {+ t.Fatalf("req = %s %q, want POST /api/v1/namespaces/mypool/secrets",+ req.method, req.path)+ }+ // Scoped to the caller's tenant via impersonation.+ if got := req.headers.Get("Impersonate-User"); got != "oidc:sub-1" {+ t.Fatalf("Impersonate-User = %q, want oidc:sub-1", got)+ }+ var sec struct {+ Metadata struct {+ Name string `json:"name"`+ } `json:"metadata"`+ StringData map[string]string `json:"stringData"`+ }+ if err := json.Unmarshal(req.body, &sec); err != nil {+ t.Fatalf("secret body not JSON: %v", err)+ }+ if sec.Metadata.Name != workloadOIDCSecretName {+ t.Fatalf("secret name = %q, want %q", sec.Metadata.Name, workloadOIDCSecretName)+ }+ if sec.StringData["client_id"] != "tenant-sub-1" ||+ sec.StringData["client_secret"] != "secret-xyz" ||+ sec.StringData["tenant"] != "user-sub-1" {+ t.Fatalf("unexpected stringData: %+v", sec.StringData)+ }+ if sec.StringData["token_url"] != h.WorkloadTokenURL {+ t.Fatalf("token_url = %q, want %q", sec.StringData["token_url"], h.WorkloadTokenURL)+ }+}++// An already-existing Secret (409) is treated as success: the per-tenant+// client secret is stable, so the existing Secret holds the right creds.+func TestWriteWorkloadOIDCSecret_ConflictIsSuccess(t *testing.T) {+ fk := newFakeK8s(http.StatusConflict, "{}")+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ h := Handlers{}+ if err := h.writeWorkloadOIDCSecret(+ context.Background(), "sub-1", "mypool", "cid", "csec", "user-sub-1",+ ); err != nil {+ t.Fatalf("409 should be treated as success, got err = %v", err)+ }+}++func TestWriteWorkloadOIDCSecret_ServerErrorPropagates(t *testing.T) {+ fk := newFakeK8s(http.StatusInternalServerError, "boom")+ defer fk.server.Close()+ overrideK8sClient(fk.server.Client(), fk.server.URL, "fake-sa-token")++ h := Handlers{}+ if err := h.writeWorkloadOIDCSecret(+ context.Background(), "sub-1", "mypool", "cid", "csec", "user-sub-1",+ ); err == nil {+ t.Fatal("expected an error on 500, got nil")+ }+}diff --git a/libs/fleet/backend/identity/identity.go b/libs/fleet/backend/identity/identity.gonew file mode 100644index 0000000000..ba0f9cf2d7--- /dev/null+++ b/libs/fleet/backend/identity/identity.go@@ -0,0 +1,137 @@+// Package identity resolves the cross-service identity prefixes (Keycloak+// group / Capsule tenant prefix and the OIDC username/groups prefixes) from+// OpenFeature, so the cyclops-cs backend's Tenant lifecycle and impersonation+// headers stay aligned with the k3s apiserver flags instead of hardcoding+// separate copies — the drift that previously broke tenant RBAC.+//+// Flag keys (SSM Parameter Store paths):+//+// /feature-flags/identity/user-group-prefix default "user-"+// /feature-flags/identity/oidc-username-prefix default "oidc:"+// /feature-flags/identity/oidc-groups-prefix default "oidc:"+// /feature-flags/identity/tenant-group default "cyclops-cs-tenants"+//+// Defaults equal today's hardcoded literals, so behaviour is unchanged until an+// SSM value is set. The OpenFeature provider must be installed+// (featureflags.SetupProvider) before these are called; with no provider the+// SDK returns the supplied default.+//+// Callers should use the Impersonate*/Tenant* composers rather than+// concatenating prefixes themselves, so the composition rules live in one place.+package identity++import (+ "context"+ "sync"+ "time"++ "github.com/open-feature/go-sdk/openfeature"+)++const (+ flagUserGroupPrefix = "/feature-flags/identity/user-group-prefix"+ flagOIDCUsernamePrefix = "/feature-flags/identity/oidc-username-prefix"+ flagOIDCGroupsPrefix = "/feature-flags/identity/oidc-groups-prefix"+ flagTenantGroup = "/feature-flags/identity/tenant-group"+ defaultUserGroupPrefix = "user-"+ defaultOIDCUserPrefix = "oidc:"+ defaultOIDCGroupsPrefix = "oidc:"+ // defaultTenantGroup is the shared Capsule "gate" group every cyclops user is+ // impersonated into. It is the single, STATIC entry in+ // CapsuleConfiguration.userGroups (declared in GitOps at+ // clusters/kopf-k3s/capsule/capsule-configuration.yaml) — keep the two in+ // sync. Per-user isolation is the Tenant owner (= the impersonated User),+ // not this group, so userGroups never needs per-user runtime patching.+ defaultTenantGroup = "cyclops-cs-tenants"+ // cacheTTL bounds how long a resolved prefix is reused before re-resolving+ // via OpenFeature (mirrors auth.flagsTTL). Refresh is lazy on the next call.+ cacheTTL = 1 * time.Minute+ // evalTimeout keeps an unreachable Parameter Store from stalling a request;+ // the SDK falls back to the default value on timeout.+ evalTimeout = 3 * time.Second+)++var (+ clientOnce sync.Once+ client *openfeature.Client++ mu sync.Mutex+ cache = map[string]cached{}+)++type cached struct {+ val string+ exp time.Time+}++func ff() *openfeature.Client {+ clientOnce.Do(func() { client = openfeature.NewClient("cyclops-cs-identity") })+ return client+}++// resolve returns the flag's string value, cached for cacheTTL, falling back to+// def on error/timeout/missing provider.+func resolve(ctx context.Context, key, def string) string {+ mu.Lock()+ if c, ok := cache[key]; ok && time.Now().Before(c.exp) {+ mu.Unlock()+ return c.val+ }+ mu.Unlock()++ callCtx, cancel := context.WithTimeout(ctx, evalTimeout)+ defer cancel()+ val, err := ff().StringValue(callCtx, key, def, openfeature.EvaluationContext{})+ if err != nil || val == "" {+ val = def+ }++ mu.Lock()+ cache[key] = cached{val: val, exp: time.Now().Add(cacheTTL)}+ mu.Unlock()+ return val+}++// UserGroupPrefix is the Keycloak personal-group / Capsule tenant prefix ("user-").+func UserGroupPrefix(ctx context.Context) string {+ return resolve(ctx, flagUserGroupPrefix, defaultUserGroupPrefix)+}++// OIDCUsernamePrefix is the apiserver oidc-username-prefix ("oidc:").+func OIDCUsernamePrefix(ctx context.Context) string {+ return resolve(ctx, flagOIDCUsernamePrefix, defaultOIDCUserPrefix)+}++// OIDCGroupsPrefix is the apiserver oidc-groups-prefix ("oidc:").+func OIDCGroupsPrefix(ctx context.Context) string {+ return resolve(ctx, flagOIDCGroupsPrefix, defaultOIDCGroupsPrefix)+}++// ImpersonateUser builds the K8s Impersonate-User value for a Keycloak subject+// (e.g. "oidc:<sub>").+func ImpersonateUser(ctx context.Context, sub string) string {+ return OIDCUsernamePrefix(ctx) + sub+}++// PersonalGroup is the Keycloak personal group / Capsule tenant name for a+// subject (e.g. "user-<sub>").+func PersonalGroup(ctx context.Context, sub string) string {+ return UserGroupPrefix(ctx) + sub+}++// TenantGroup is the shared Capsule gate group, oidc-groups prefix applied+// (e.g. "oidc:cyclops-cs-tenants"). It is the single static entry in+// CapsuleConfiguration.userGroups.+func TenantGroup(ctx context.Context) string {+ return OIDCGroupsPrefix(ctx) + resolve(ctx, flagTenantGroup, defaultTenantGroup)+}++// ImpersonateGroup builds the K8s Impersonate-Group value: the shared Capsule+// gate group (e.g. "oidc:cyclops-cs-tenants"). Every cyclops user is+// impersonated as a member of this ONE group so Capsule treats the request as+// tenant-managed; which tenant they own is decided by the Tenant owner matching+// ImpersonateUser (the User), NOT by a per-user group. The sub arg is unused+// (kept for call-site stability / future per-user gating).+func ImpersonateGroup(ctx context.Context, _ string) string {+ return TenantGroup(ctx)+}diff --git a/libs/fleet/backend/keycloak/admin.go b/libs/fleet/backend/keycloak/admin.gonew file mode 100644index 0000000000..159c130d65--- /dev/null+++ b/libs/fleet/backend/keycloak/admin.go@@ -0,0 +1,448 @@+// Package keycloak — gocloak admin wrapper used by /api/keys and+// /api/user-keys to CRUD per-key service-account clients in the+// cyclops-cs realm.+package keycloak++import (+ "context"+ "fmt"+ "strings"+ "time"++ "github.com/Nerzal/gocloak/v13"+ "github.com/google/uuid"++ "cyclops-cs-backend/identity"+ "cyclops-cs-backend/metrics"+ "go.opentelemetry.io/otel"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/codes"+ "go.opentelemetry.io/otel/trace"+)++type Admin struct {+ client *gocloak.GoCloak+ baseURL string+ realm string+ clientID string+ clientSecret string+ keyClientPfx string // pool/gateway key client-id prefix ("key-")+ userKeyClientPfx string // per-user key client-id prefix ("ukey-")+}++func adminTracer() trace.Tracer {+ return otel.Tracer("cyclops-cs-backend/keycloak")+}++func NewAdmin(baseURL, realm, clientID, clientSecret, keyClientPfx, userKeyClientPfx string) *Admin {+ return &Admin{+ client: gocloak.NewClient(baseURL),+ baseURL: baseURL,+ realm: realm,+ clientID: clientID,+ clientSecret: clientSecret,+ keyClientPfx: keyClientPfx,+ userKeyClientPfx: userKeyClientPfx,+ }+}++func (a *Admin) token(ctx context.Context) (string, error) {+ ctx, span := adminTracer().Start(ctx, "keycloak.admin_login")+ defer span.End()++ start := time.Now()+ t, err := a.client.LoginClient(ctx, a.clientID, a.clientSecret, a.realm)+ metrics.RecordKeycloakRequest("AdminLogin", time.Since(start), err)+ if err != nil {+ span.RecordError(err)+ span.SetStatus(codes.Error, "admin login failed")+ return "", fmt.Errorf("admin login: %w", err)+ }+ return t.AccessToken, nil+}++type KeyClient struct {+ ID string `json:"id"`+ ClientID string `json:"client_id"`+ Name string `json:"name"`+ Namespace string `json:"namespace"`+ OwnerSub string `json:"owner_sub"`+}++// CreateKeyClient creates a confidential service-account client whose+// access tokens carry a hardcoded `namespace` claim. Returns the+// client_id and the freshly generated client_secret.+func (a *Admin) CreateKeyClient(ctx context.Context, name, namespace, ownerSub string) (clientID, clientSecret, kcUUID string, err error) {+ ctx, span := adminTracer().Start(ctx, "keycloak.create_key_client", trace.WithAttributes(+ attribute.String("keycloak.key_type", "pool"),+ attribute.String("key.name", name),+ attribute.String("k8s.namespace", namespace),+ ))+ defer span.End()++ start := time.Now()+ defer func() { metrics.RecordKeycloakRequest("CreateKeyClient", time.Since(start), err) }()++ tok, err := a.token(ctx)+ if err != nil {+ return "", "", "", err+ }++ clientID = a.keyClientPfx + shortUUID()+ desc := fmt.Sprintf("cyclops-cs API key %q for owner %s", name, ownerSub)+ saEnabled := true+ publicClient := false+ stdFlow := false+ implicitFlow := false+ directAccess := false++ c := gocloak.Client{+ ClientID: gocloak.StringP(clientID),+ Name: gocloak.StringP(name),+ Description: gocloak.StringP(desc),+ Enabled: gocloak.BoolP(true),+ PublicClient: &publicClient,+ ServiceAccountsEnabled: &saEnabled,+ StandardFlowEnabled: &stdFlow,+ ImplicitFlowEnabled: &implicitFlow,+ DirectAccessGrantsEnabled: &directAccess,+ Attributes: &map[string]string{+ "namespace": namespace,+ "owner_sub": ownerSub,+ "key_name": name,+ "managed_by": "cyclops-cs-backend",+ },+ ProtocolMappers: &[]gocloak.ProtocolMapperRepresentation{+ {+ Name: gocloak.StringP("namespace"),+ Protocol: gocloak.StringP("openid-connect"),+ ProtocolMapper: gocloak.StringP("oidc-hardcoded-claim-mapper"),+ Config: &map[string]string{+ "claim.name": "namespace",+ "claim.value": namespace,+ "jsonType.label": "String",+ "access.token.claim": "true",+ "id.token.claim": "false",+ "userinfo.token.claim": "false",+ },+ },+ },+ }++ kcUUID, err = a.client.CreateClient(ctx, tok, a.realm, c)+ if err != nil {+ return "", "", "", fmt.Errorf("create client: %w", err)+ }+ cs, err := a.client.GetClientSecret(ctx, tok, a.realm, kcUUID)+ if err != nil {+ _ = a.client.DeleteClient(ctx, tok, a.realm, kcUUID)+ return "", "", "", fmt.Errorf("read client secret: %w", err)+ }+ if cs.Value == nil {+ _ = a.client.DeleteClient(ctx, tok, a.realm, kcUUID)+ return "", "", "", fmt.Errorf("client secret missing in keycloak response")+ }+ return clientID, *cs.Value, kcUUID, nil+}++// ListKeyClients returns every client managed by cyclops-cs-backend that+// belongs to ownerSub.+func (a *Admin) ListKeyClients(ctx context.Context, ownerSub string) ([]KeyClient, error) {+ ctx, span := adminTracer().Start(ctx, "keycloak.list_key_clients", trace.WithAttributes(+ attribute.String("keycloak.key_type", "pool"),+ ))+ defer span.End()++ start := time.Now()+ var err error+ defer func() { metrics.RecordKeycloakRequest("ListKeyClients", time.Since(start), err) }()++ var tok string+ tok, err = a.token(ctx)+ if err != nil {+ return nil, err+ }+ out := []KeyClient{}+ first := 0+ const max = 100+ for {+ params := gocloak.GetClientsParams{+ First: &first,+ Max: gocloak.IntP(max),+ }+ clients, listErr := a.client.GetClients(ctx, tok, a.realm, params)+ if listErr != nil {+ err = fmt.Errorf("list clients: %w", listErr)+ return nil, err+ }+ for _, c := range clients {+ attrs := derefMap(c.Attributes)+ if attrs["managed_by"] != "cyclops-cs-backend" || attrs["owner_sub"] != ownerSub {+ continue+ }+ out = append(out, KeyClient{+ ID: derefStr(c.ID),+ ClientID: derefStr(c.ClientID),+ Name: derefStr(c.Name),+ Namespace: attrs["namespace"],+ OwnerSub: attrs["owner_sub"],+ })+ }+ if len(clients) < max {+ break+ }+ first += max+ }+ return out, nil+}++// DeleteKeyClient deletes by Keycloak UUID, but only if owner_sub matches.+func (a *Admin) DeleteKeyClient(ctx context.Context, kcUUID, ownerSub string) error {+ ctx, span := adminTracer().Start(ctx, "keycloak.delete_key_client", trace.WithAttributes(+ attribute.String("keycloak.key_type", "pool"),+ attribute.String("keycloak.client_uuid", kcUUID),+ ))+ defer span.End()++ start := time.Now()+ var err error+ defer func() { metrics.RecordKeycloakRequest("DeleteKeyClient", time.Since(start), err) }()++ var tok string+ tok, err = a.token(ctx)+ if err != nil {+ return err+ }+ c, err := a.client.GetClient(ctx, tok, a.realm, kcUUID)+ if err != nil {+ return fmt.Errorf("get client: %w", err)+ }+ attrs := derefMap(c.Attributes)+ if attrs["managed_by"] != "cyclops-cs-backend" {+ return fmt.Errorf("not a cyclops-cs-managed client")+ }+ if attrs["owner_sub"] != ownerSub {+ return fmt.Errorf("forbidden")+ }+ if err := a.client.DeleteClient(ctx, tok, a.realm, kcUUID); err != nil {+ return fmt.Errorf("delete client: %w", err)+ }+ return nil+}++// UserKeyClient is a per-user API key Keycloak client.+type UserKeyClient struct {+ ID string `json:"id"`+ ClientID string `json:"client_id"`+ Name string `json:"name"`+ Scope []string `json:"scope"`+ OwnerSub string `json:"owner_sub"`+}++// CreateUserKeyClient creates a confidential service-account client whose+// access tokens carry hardcoded `user_sub` and `user_groups` claims.+// Returns the client_id, freshly generated client_secret, and token URL.+func (a *Admin) CreateUserKeyClient(ctx context.Context, name, ownerSub string, scope []string) (clientID, clientSecret, tokenURL string, err error) {+ ctx, span := adminTracer().Start(ctx, "keycloak.create_user_key_client", trace.WithAttributes(+ attribute.String("keycloak.key_type", "user"),+ attribute.String("key.name", name),+ ))+ defer span.End()++ start := time.Now()+ defer func() { metrics.RecordKeycloakRequest("CreateUserKeyClient", time.Since(start), err) }()++ tok, err := a.token(ctx)+ if err != nil {+ return "", "", "", err+ }++ clientID = a.userKeyClientPfx + shortUUID()+ desc := fmt.Sprintf("cyclops-cs user API key %q for owner %s", name, ownerSub)+ saEnabled := true+ publicClient := false+ stdFlow := false+ implicitFlow := false+ directAccess := false++ scopeStr := strings.Join(scope, ",")++ c := gocloak.Client{+ ClientID: gocloak.StringP(clientID),+ Name: gocloak.StringP(name),+ Description: gocloak.StringP(desc),+ Enabled: gocloak.BoolP(true),+ PublicClient: &publicClient,+ ServiceAccountsEnabled: &saEnabled,+ StandardFlowEnabled: &stdFlow,+ ImplicitFlowEnabled: &implicitFlow,+ DirectAccessGrantsEnabled: &directAccess,+ Attributes: &map[string]string{+ "owner_sub": ownerSub,+ "key_name": name,+ "managed_by": "cyclops-cs-backend",+ "key_type": "user",+ "scope": scopeStr,+ },+ ProtocolMappers: &[]gocloak.ProtocolMapperRepresentation{+ {+ Name: gocloak.StringP("user_sub"),+ Protocol: gocloak.StringP("openid-connect"),+ ProtocolMapper: gocloak.StringP("oidc-hardcoded-claim-mapper"),+ Config: &map[string]string{+ "claim.name": "user_sub",+ "claim.value": ownerSub,+ "jsonType.label": "String",+ "access.token.claim": "true",+ "id.token.claim": "false",+ "userinfo.token.claim": "false",+ },+ },+ {+ Name: gocloak.StringP("user_groups"),+ Protocol: gocloak.StringP("openid-connect"),+ ProtocolMapper: gocloak.StringP("oidc-hardcoded-claim-mapper"),+ Config: &map[string]string{+ "claim.name": "user_groups",+ "claim.value": identity.ImpersonateGroup(ctx, ownerSub),+ "jsonType.label": "String",+ "access.token.claim": "true",+ "id.token.claim": "false",+ "userinfo.token.claim": "false",+ },+ },+ },+ }++ kcUUID, err := a.client.CreateClient(ctx, tok, a.realm, c)+ if err != nil {+ return "", "", "", fmt.Errorf("create client: %w", err)+ }+ cs, err := a.client.GetClientSecret(ctx, tok, a.realm, kcUUID)+ if err != nil {+ _ = a.client.DeleteClient(ctx, tok, a.realm, kcUUID)+ return "", "", "", fmt.Errorf("read client secret: %w", err)+ }+ if cs.Value == nil {+ _ = a.client.DeleteClient(ctx, tok, a.realm, kcUUID)+ return "", "", "", fmt.Errorf("client secret missing in keycloak response")+ }++ tokenURL = a.tokenURL()+ return clientID, *cs.Value, tokenURL, nil+}++// ListUserKeyClients returns every user-key client owned by ownerSub.+func (a *Admin) ListUserKeyClients(ctx context.Context, ownerSub string) ([]UserKeyClient, error) {+ ctx, span := adminTracer().Start(ctx, "keycloak.list_user_key_clients", trace.WithAttributes(+ attribute.String("keycloak.key_type", "user"),+ ))+ defer span.End()++ start := time.Now()+ var err error+ defer func() { metrics.RecordKeycloakRequest("ListUserKeyClients", time.Since(start), err) }()++ var tok string+ tok, err = a.token(ctx)+ if err != nil {+ return nil, err+ }+ out := []UserKeyClient{}+ first := 0+ const max = 100+ for {+ params := gocloak.GetClientsParams{+ First: &first,+ Max: gocloak.IntP(max),+ }+ clients, listErr := a.client.GetClients(ctx, tok, a.realm, params)+ if listErr != nil {+ err = fmt.Errorf("list clients: %w", listErr)+ return nil, err+ }+ for _, c := range clients {+ attrs := derefMap(c.Attributes)+ if attrs["managed_by"] != "cyclops-cs-backend" || attrs["key_type"] != "user" || attrs["owner_sub"] != ownerSub {+ continue+ }+ var scope []string+ if s := attrs["scope"]; s != "" {+ scope = strings.Split(s, ",")+ }+ out = append(out, UserKeyClient{+ ID: derefStr(c.ID),+ ClientID: derefStr(c.ClientID),+ Name: derefStr(c.Name),+ Scope: scope,+ OwnerSub: attrs["owner_sub"],+ })+ }+ if len(clients) < max {+ break+ }+ first += max+ }+ return out, nil+}++// DeleteUserKeyClient deletes a user-key client by Keycloak UUID,+// but only if owner_sub matches and the client is a user key.+func (a *Admin) DeleteUserKeyClient(ctx context.Context, ownerSub, kcUUID string) error {+ ctx, span := adminTracer().Start(ctx, "keycloak.delete_user_key_client", trace.WithAttributes(+ attribute.String("keycloak.key_type", "user"),+ attribute.String("keycloak.client_uuid", kcUUID),+ ))+ defer span.End()++ start := time.Now()+ var err error+ defer func() { metrics.RecordKeycloakRequest("DeleteUserKeyClient", time.Since(start), err) }()++ var tok string+ tok, err = a.token(ctx)+ if err != nil {+ return err+ }+ c, err := a.client.GetClient(ctx, tok, a.realm, kcUUID)+ if err != nil {+ return fmt.Errorf("get client: %w", err)+ }+ attrs := derefMap(c.Attributes)+ if attrs["managed_by"] != "cyclops-cs-backend" {+ return fmt.Errorf("not a cyclops-cs-managed client")+ }+ if attrs["key_type"] != "user" {+ return fmt.Errorf("not a user key client")+ }+ if attrs["owner_sub"] != ownerSub {+ return fmt.Errorf("forbidden")+ }+ if err := a.client.DeleteClient(ctx, tok, a.realm, kcUUID); err != nil {+ return fmt.Errorf("delete client: %w", err)+ }+ return nil+}++// tokenURL returns the Keycloak token endpoint for the realm.+func (a *Admin) tokenURL() string {+ return fmt.Sprintf("%s/realms/%s/protocol/openid-connect/token", a.baseURL, a.realm)+}++func shortUUID() string {+ return strings.ReplaceAll(uuid.NewString(), "-", "")[:12]+}++func derefStr(s *string) string {+ if s == nil {+ return ""+ }+ return *s+}++func derefMap(m *map[string]string) map[string]string {+ if m == nil {+ return map[string]string{}+ }+ return *m+}diff --git a/libs/fleet/backend/keycloak/workload.go b/libs/fleet/backend/keycloak/workload.gonew file mode 100644index 0000000000..a79868548d--- /dev/null+++ b/libs/fleet/backend/keycloak/workload.go@@ -0,0 +1,179 @@+package keycloak++import (+ "context"+ "fmt"+ "time"++ "github.com/Nerzal/gocloak/v13"++ "cyclops-cs-backend/metrics"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/codes"+ "go.opentelemetry.io/otel/trace"+)++// WorkloadClientPrefix is the client-id prefix for the per-tenant+// service-account clients minted in the workloads realm for OSGym pool VM+// OIDC federation. One client per tenant (keyed by the owner's Keycloak+// subject), so every pool the tenant owns shares the same identity.+const WorkloadClientPrefix = "tenant-"++// EnsureTenantWorkloadClient idempotently ensures a confidential+// service-account client exists in this Admin's realm (expected to be the+// workloads realm) for the tenant identified by ownerSub, and returns its+// client_id + client_secret.+//+// The client's client_credentials access tokens carry two hardcoded claims:+//+// - tenant = tenantClaim (e.g. "user-<sub>", the Capsule tenant that owns+// the pool) — what a customer keys their OIDC trust policy off.+// - aud = audience (e.g. "sts.amazonaws.com") — required by AWS STS for+// AssumeRoleWithWebIdentity; the realm's IAM OIDC provider already lists+// this audience, so per-tenant clients need NO terraform/OIDC-provider+// change.+//+// Idempotent: a second call returns the existing client and its current+// secret (the secret is therefore stable across calls, which lets callers+// treat a Secret-already-exists conflict as success). A lost create race is+// recovered by re-looking-up the client.+//+// See docs/decisions/2026-06-25-osgym-pool-workload-oidc.md.+func (a *Admin) EnsureTenantWorkloadClient(+ ctx context.Context, ownerSub, tenantClaim, audience string,+) (clientID, clientSecret string, err error) {+ ctx, span := adminTracer().Start(ctx, "keycloak.ensure_tenant_workload_client",+ trace.WithAttributes(+ attribute.String("keycloak.key_type", "workload"),+ attribute.String("keycloak.realm", a.realm),+ attribute.String("tenant", tenantClaim),+ ))+ defer span.End()++ start := time.Now()+ defer func() {+ metrics.RecordKeycloakRequest("EnsureTenantWorkloadClient", time.Since(start), err)+ }()++ tok, err := a.token(ctx)+ if err != nil {+ return "", "", err+ }++ clientID = WorkloadClientPrefix + ownerSub++ // Idempotent fast path: return the existing client's secret.+ if cid, secret, found, lookErr := a.lookupClientSecret(ctx, tok, clientID); lookErr != nil {+ span.RecordError(lookErr)+ span.SetStatus(codes.Error, "client lookup failed")+ return "", "", lookErr+ } else if found {+ return cid, secret, nil+ }++ saEnabled := true+ publicClient := false+ stdFlow := false+ implicitFlow := false+ directAccess := false++ c := gocloak.Client{+ ClientID: gocloak.StringP(clientID),+ Name: gocloak.StringP(fmt.Sprintf("cua tenant %s (pool VM OIDC)", tenantClaim)),+ Description: gocloak.StringP(fmt.Sprintf("Per-tenant workload OIDC client for %s, managed by cyclops-cs-backend", tenantClaim)),+ Enabled: gocloak.BoolP(true),+ PublicClient: &publicClient,+ ServiceAccountsEnabled: &saEnabled,+ StandardFlowEnabled: &stdFlow,+ ImplicitFlowEnabled: &implicitFlow,+ DirectAccessGrantsEnabled: &directAccess,+ Attributes: &map[string]string{+ "tenant": tenantClaim,+ "owner_sub": ownerSub,+ "managed_by": "cyclops-cs-backend",+ "key_type": "workload",+ },+ ProtocolMappers: &[]gocloak.ProtocolMapperRepresentation{+ {+ // The trust anchor: a stable per-tenant claim. We key off a+ // custom claim rather than `sub` because in client_credentials+ // grants Keycloak sets `sub` to the service-account's internal+ // UUID (mirrors the workloads-realm opencode/openclaw clients).+ Name: gocloak.StringP("tenant"),+ Protocol: gocloak.StringP("openid-connect"),+ ProtocolMapper: gocloak.StringP("oidc-hardcoded-claim-mapper"),+ Config: &map[string]string{+ "claim.name": "tenant",+ "claim.value": tenantClaim,+ "jsonType.label": "String",+ "access.token.claim": "true",+ "id.token.claim": "false",+ "userinfo.token.claim": "false",+ },+ },+ {+ // aud = audience (sts.amazonaws.com). Keycloak defaults `aud`+ // to the client_id; this mapper overrides it so AWS STS — and+ // the realm's existing IAM OIDC provider audience list —+ // accept the token without a per-client provider update.+ Name: gocloak.StringP("workload-audience"),+ Protocol: gocloak.StringP("openid-connect"),+ ProtocolMapper: gocloak.StringP("oidc-audience-mapper"),+ Config: &map[string]string{+ "included.custom.audience": audience,+ "access.token.claim": "true",+ "id.token.claim": "false",+ },+ },+ },+ }++ kcUUID, err := a.client.CreateClient(ctx, tok, a.realm, c)+ if err != nil {+ // Likely a create race (another replica created it concurrently) or+ // a pre-existing client our initial lookup missed — recover by+ // re-looking-up and returning the existing secret.+ if cid, secret, found, lookErr := a.lookupClientSecret(ctx, tok, clientID); lookErr == nil && found {+ return cid, secret, nil+ }+ span.RecordError(err)+ span.SetStatus(codes.Error, "create client failed")+ return "", "", fmt.Errorf("create client: %w", err)+ }++ cs, err := a.client.GetClientSecret(ctx, tok, a.realm, kcUUID)+ if err != nil {+ return "", "", fmt.Errorf("read client secret: %w", err)+ }+ if cs.Value == nil {+ return "", "", fmt.Errorf("client secret missing in keycloak response")+ }+ return clientID, *cs.Value, nil+}++// lookupClientSecret returns (clientID, secret, found, err) for a client by+// its clientId. found=false (nil err) means no such client.+func (a *Admin) lookupClientSecret(+ ctx context.Context, tok, clientID string,+) (string, string, bool, error) {+ clients, err := a.client.GetClients(ctx, tok, a.realm, gocloak.GetClientsParams{+ ClientID: gocloak.StringP(clientID),+ })+ if err != nil {+ return "", "", false, fmt.Errorf("lookup client: %w", err)+ }+ for _, c := range clients {+ if derefStr(c.ClientID) != clientID {+ continue+ }+ cs, secErr := a.client.GetClientSecret(ctx, tok, a.realm, derefStr(c.ID))+ if secErr != nil {+ return "", "", false, fmt.Errorf("read client secret: %w", secErr)+ }+ if cs.Value == nil {+ return "", "", false, fmt.Errorf("client secret missing in keycloak response")+ }+ return clientID, *cs.Value, true, nil+ }+ return "", "", false, nil+}diff --git a/libs/fleet/backend/main.go b/libs/fleet/backend/main.gonew file mode 100644index 0000000000..85daeb7c17--- /dev/null+++ b/libs/fleet/backend/main.go@@ -0,0 +1,320 @@+// cyclops-cs backend — sidecar for the cyclops-cs Pod.+//+// Every authenticated route runs through the standard+//+// Trace → Log → TokenAuth → OPA → handler+//+// pipeline borrowed from r33drichards/grt:+//+// /api/keys[/{id}] — SPA-authenticated CRUD on per-user+// service-account clients in Keycloak.+//+// /api/gateway/{name}[/{p...}]— DEPRECATED (CUA-609). Returns 410 Gone.+// The per-pool orchestrator HTTP layer has+// been removed. All pool operations now use+// OSGymSandboxClaim CRs (Path B) directly.+// Zero HTTP traffic was confirmed before+// removal. Route kept for OPA continuity+// (per-key tokens still validated).+//+// /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 gateway / batch / label routes that now return 410 Gone. 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 the SPA's user JWT (azp=cyclops-cs-spa). /api/gateway/{name} requires a per-key token whose `namespace` claim equals "pool-{name}" (enforced by OPA). The deprecated /api/batch/{pool} and /api/label/{pool} routes are permanently retired — they return 410 Gone for every request regardless of token validity.+package main++import (+ "context"+ "fmt"+ "log/slog"+ "net/http"+ "os"++ "github.com/spf13/cobra"++ "cyclops-cs-backend/auth"+ "cyclops-cs-backend/config"+ _ "cyclops-cs-backend/docs" // generated by `swag init`+ "cyclops-cs-backend/handlers"+ "cyclops-cs-backend/keycloak"+ "cyclops-cs-backend/metrics"+ "cyclops-cs-backend/middlewares"+ "cyclops-cs-backend/telemetry"+ "cyclops-cs-backend/templates"++ httpSwagger "github.com/swaggo/http-swagger/v2"+ "github.com/trycua/cloud/pkg/featureflags"+)++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))))))+}++// 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 onlyLog(route string, h http.HandlerFunc) http.Handler {+ return middlewares.TraceMiddleware(route, middlewares.LogMiddleware(http.HandlerFunc(h)))+}++func setupRouter(c handlers.Handlers) http.Handler {+ 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))++ // Swagger UI + JSON. The SPA points its codegen at /api/swagger/doc.json+ // (see cyclops-cs/scripts/codegen.sh). We don't put the doc behind auth+ // — the schema is public and the actual endpoints are still gated.+ r.Handle("GET /api/swagger/", onlyLog("/api/swagger/", func(w http.ResponseWriter, r *http.Request) {+ httpSwagger.Handler(httpSwagger.URL("/api/swagger/doc.json")).ServeHTTP(w, r)+ }))++ r.Handle("POST /api/keys",+ withMiddlewares("/api/keys", nil, c.CreateKey))+ r.Handle("GET /api/keys",+ withMiddlewares("/api/keys", nil, c.ListKeys))+ r.Handle("DELETE /api/keys/{id}",+ withMiddlewares("/api/keys/{id}", []string{"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))+ r.Handle("POST /api/namespaces",+ withMiddlewares("/api/namespaces", nil, c.CreateNamespace))+ r.Handle("DELETE /api/namespaces/{name}",+ withMiddlewares("/api/namespaces/{name}", []string{"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))+ r.Handle("GET /api/user-keys",+ withMiddlewares("/api/user-keys", nil, c.ListUserKeys))+ r.Handle("DELETE /api/user-keys/{id}",+ withMiddlewares("/api/user-keys/{id}", []string{"id"}, c.DeleteUserKey))++ // Per-user pool templates — Redis-backed saved pool configs the SPA+ // reuses to seed new pools. SPA-auth, same pipeline as /api/keys.+ // Always registered; the handlers reply 503 when no Redis is wired.+ r.Handle("POST /api/pool-templates",+ withMiddlewares("/api/pool-templates", nil, c.CreatePoolTemplate))+ r.Handle("GET /api/pool-templates",+ withMiddlewares("/api/pool-templates", nil, c.ListPoolTemplates))+ r.Handle("GET /api/pool-templates/{name}",+ withMiddlewares("/api/pool-templates/{name}", []string{"name"}, c.GetPoolTemplate))+ r.Handle("DELETE /api/pool-templates/{name}",+ withMiddlewares("/api/pool-templates/{name}", []string{"name"}, c.DeletePoolTemplate))++ r.Handle("/api/gateway/{name}",+ withMiddlewares("/api/gateway/{name}", []string{"name"}, c.Gateway))+ r.Handle("/api/gateway/{name}/{path...}",+ withMiddlewares("/api/gateway/{name}/{path...}", []string{"name", "path"}, c.Gateway))++ // 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).+ r.Handle("/api/svc/{namespace}/{service}",+ withMiddlewares("/api/svc/{namespace}/{service}",+ []string{"namespace", "service"}, c.Svc))+ r.Handle("/api/svc/{namespace}/{service}/{path...}",+ withMiddlewares("/api/svc/{namespace}/{service}/{path...}",+ []string{"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))+ 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.DeprecatedBatchRoute))+ r.Handle("POST /api/batch/{pool}/lanes",+ withMiddlewares("/api/batch/{pool}/lanes", []string{"pool"}, c.DeprecatedBatchRoute))+ r.Handle("DELETE /api/batch/{pool}/lanes",+ withMiddlewares("/api/batch/{pool}/lanes", []string{"pool"}, c.DeprecatedBatchRoute))+ r.Handle("GET /api/batch/{pool}/{id}/status",+ withMiddlewares("/api/batch/{pool}/{id}/status", []string{"pool", "id"}, c.DeprecatedBatchRoute))+ r.Handle("GET /api/batch/{pool}/{id}/results",+ withMiddlewares("/api/batch/{pool}/{id}/results", []string{"pool", "id"}, c.DeprecatedBatchRoute))+ r.Handle("DELETE /api/batch/{pool}/{id}",+ withMiddlewares("/api/batch/{pool}/{id}", []string{"pool", "id"}, c.DeprecatedBatchRoute))+ r.Handle("POST /api/label/{pool}/{label}/batch",+ withMiddlewares("/api/label/{pool}/{label}/batch", []string{"pool", "label"}, c.DeprecatedBatchRoute))+ r.Handle("GET /api/label/{pool}/{label}/status",+ withMiddlewares("/api/label/{pool}/{label}/status", []string{"pool", "label"}, c.DeprecatedBatchRoute))+ r.Handle("GET /api/label/{pool}/{label}/results",+ withMiddlewares("/api/label/{pool}/{label}/results", []string{"pool", "label"}, c.DeprecatedBatchRoute))+ r.Handle("DELETE /api/label/{pool}/{label}",+ withMiddlewares("/api/label/{pool}/{label}", []string{"pool", "label"}, c.DeprecatedBatchRoute))++ // Wrap the entire mux in the metrics middleware so every request+ // (including /healthz and unmatched routes) is recorded. This must be+ // the outermost layer so the status code from inner middlewares (auth,+ // OPA) is captured correctly.+ return metrics.Middleware(r)+}++var rootCmd = &cobra.Command{+ Use: "cyclops-cs-backend",+ Short: "cyclops-cs backend sidecar",+ SilenceUsage: true,+ SilenceErrors: true,+ RunE: func(_ *cobra.Command, _ []string) error { return run() },+}++func init() {+ config.RegisterFlags(rootCmd.PersistentFlags())+}++func main() {+ if err := rootCmd.Execute(); err != nil {+ slog.Error("fatal", "err", err)+ os.Exit(1)+ }+}++func run() error {+ slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))+ ctx := context.Background()++ cfg, err := config.LoadConfig()+ if err != nil {+ return fmt.Errorf("load config: %w", err)+ }+ configValues = cfg++ telemetryShutdown := func(context.Context) error { return nil }+ if shutdown, err := telemetry.Init(ctx, telemetry.Config{+ Endpoint: cfg.Telemetry.Endpoint,+ Protocol: cfg.Telemetry.Protocol,+ ServiceName: cfg.Telemetry.ServiceName,+ ServiceNamespace: cfg.Telemetry.ServiceNamespace,+ Environment: cfg.Telemetry.Environment,+ ResourceAttrs: cfg.Telemetry.ResourceAttrs,+ }); err != nil {+ slog.Warn("otel: init failed; tracing disabled", "err", err)+ } else {+ telemetryShutdown = shutdown+ }+ defer func() {+ if err := telemetryShutdown(context.Background()); err != nil {+ slog.Warn("otel: shutdown failed", "err", err)+ }+ }()++ slog.Info("starting", "issuer", cfg.Auth.Issuer, "listen", cfg.WebServer.Addr, "jwks_uri", cfg.Auth.JWKSUri)++ slog.Info("init: fetching JWKS")+ auth.MustInit(&cfg.Auth)+ slog.Info("init: JWKS ok, setting up OpenFeature provider")+ // SetupProvider returns a non-nil error when it falls back to the+ // from-env provider (missing creds / SSM init failure). Log it but+ // keep starting — flag evaluations still resolve via the fallback.+ if err := featureflags.SetupProvider(ctx, os.Getenv("ENVIRONMENT"), featureflags.AWSCredentials{+ AccessKeyID: os.Getenv("AWS_ACCESS_KEY_ID"),+ SecretAccessKey: os.Getenv("AWS_SECRET_ACCESS_KEY"),+ Region: os.Getenv("AWS_REGION"),+ }); err != nil {+ slog.Warn("openfeature: provider setup degraded", "err", err)+ }+ slog.Info("init: OpenFeature ok, loading OPA")+ auth.LoadOpa()+ slog.Info("init: OPA ok")++ // Start the Prometheus metrics server on a separate port so that it+ // doesn't compete with the main API server. The port is configurable+ // via METRICS_ADDR; the default :9091 avoids collision with the+ // in-namespace Prometheus deployment (which serves on :9090 / :80).+ metricsAddr := cfg.Metrics.Addr+ go func() {+ slog.Info("starting metrics server", "addr", metricsAddr)+ if err := metrics.StartMetricsServer(metricsAddr); err != nil {+ slog.Error("metrics server exited", "err", err)+ }+ }()++ admin := keycloak.NewAdmin(cfg.Keycloak.BaseURL, cfg.Keycloak.Realm, cfg.Keycloak.AdminClientID, cfg.Keycloak.AdminClientSecret, cfg.Auth.KeyClientPfx, cfg.Auth.UserKeyClientPfx)++ // Optional: admin client for the workloads realm, used to mint per-tenant+ // OIDC clients for OSGym pool VMs. Enabled only when its secret is set;+ // the admin client lives in the workloads realm because Keycloak+ // realm-management roles are per-realm. See+ // docs/decisions/2026-06-25-osgym-pool-workload-oidc.md.+ var workloadAdmin *keycloak.Admin+ if cfg.Keycloak.WorkloadAdminClientSecret != "" {+ workloadAdmin = keycloak.NewAdmin(+ cfg.Keycloak.BaseURL, cfg.Keycloak.WorkloadRealm,+ cfg.Keycloak.WorkloadAdminClientID, cfg.Keycloak.WorkloadAdminClientSecret,+ "", "",+ )+ slog.Info("workload-oidc: enabled", "realm", cfg.Keycloak.WorkloadRealm)+ } else {+ slog.Info("workload-oidc: disabled (KC_WORKLOAD_ADMIN_CLIENT_SECRET unset)")+ }++ // Redis-backed pool templates. A connection failure is non-fatal —+ // the routes stay registered and reply 503 until Redis is reachable,+ // mirroring how other optional surfaces degrade gracefully.+ h := handlers.New(admin, cfg)+ h.WorkloadAdmin = workloadAdmin+ h.WorkloadAudience = cfg.Keycloak.WorkloadAudience+ h.WorkloadTokenURL = cfg.Keycloak.WorkloadTokenURL+ if store, err := templates.New(ctx, cfg.Templates.RedisURL); err != nil {+ slog.Error("pool templates: init failed; /api/pool-templates will return 503", "err", err)+ } else if store != nil {+ h.Templates = store+ slog.Info("pool templates: enabled")+ } else {+ slog.Info("pool templates: disabled (no Redis URL configured)")+ }++ router := setupRouter(h)++ srv := &http.Server{Addr: cfg.WebServer.Addr, Handler: router}+ if err := srv.ListenAndServe(); err != nil {+ return fmt.Errorf("server exited: %w", err)+ }+ return nil+}diff --git a/libs/fleet/backend/main_test.go b/libs/fleet/backend/main_test.gonew file mode 100644index 0000000000..7f5f44a94c--- /dev/null+++ b/libs/fleet/backend/main_test.go@@ -0,0 +1,214 @@+package main++import (+ "context"+ "crypto/rand"+ "crypto/rsa"+ "encoding/base64"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "testing"+ "time"++ "cyclops-cs-backend/auth"+ "cyclops-cs-backend/config"+ "cyclops-cs-backend/handlers"++ jwt "github.com/golang-jwt/jwt/v5"+ "github.com/trycua/cloud/pkg/featureflags"+)++// 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 TestDeprecatedRoutes(t *testing.T) {+ router := setupRouter(handlers.Handlers{})++ cases := []struct {+ method string+ path string+ body io.Reader+ }{+ // batch routes+ {http.MethodPost, "/api/batch/demo/submit", strings.NewReader(`{"runs":[]}`)},+ {http.MethodPost, "/api/batch/demo/lanes", strings.NewReader(`{}`)},+ {http.MethodDelete, "/api/batch/demo/lanes", nil},+ {http.MethodGet, "/api/batch/demo/run-1/status", nil},+ {http.MethodGet, "/api/batch/demo/run-1/results", nil},+ {http.MethodDelete, "/api/batch/demo/run-1", nil},+ // label routes+ {http.MethodPost, "/api/label/demo/run-1/batch", strings.NewReader(`{}`)},+ {http.MethodGet, "/api/label/demo/run-1/status", nil},+ {http.MethodGet, "/api/label/demo/run-1/results", nil},+ {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)+ }+ })+ }+}++func TestSwaggerMentionsBatchRouteDeprecation(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)+ }+ }+}++const (+ testIssuer = "https://issuer.example.test/realms/cyclops-cs"+ testKeyID = "router-test-key"+)++var testSigningKey *rsa.PrivateKey++func TestMain(m *testing.M) {+ key, err := rsa.GenerateKey(rand.Reader, 2048)+ if err != nil {+ panic(err)+ }+ testSigningKey = key++ jwksBody, err := json.Marshal(map[string]any{+ "keys": []map[string]any{{+ "kty": "RSA",+ "use": "sig",+ "alg": "RS256",+ "kid": testKeyID,+ "n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()),+ "e": base64.RawURLEncoding.EncodeToString(bigEndianBytes(key.E)),+ }},+ })+ if err != nil {+ panic(err)+ }++ jwksServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write(jwksBody)+ }))+ defer jwksServer.Close()++ if err := os.Setenv("CYCLOPS_CS_ADMIN_SUBS", `[]`); err != nil {+ panic(err)+ }+ if err := featureflags.SetupProvider(context.Background(), "development", featureflags.AWSCredentials{}); err != nil {+ panic(err)+ }+ auth.LoadOpa()+ if err := auth.Init(&config.AuthConfiguration{+ Issuer: testIssuer,+ JWKSUri: jwksServer.URL,+ SigningAlgs: []string{"RS256"},+ SPAClientID: "cyclops-cs-spa",+ KeyClientPfx: "key-",+ UserKeyClientPfx: "ukey-",+ }); err != nil {+ panic(err)+ }++ os.Exit(m.Run())+}++func authorizedRequest(t *testing.T, method, path string, body io.Reader) *http.Request {+ t.Helper()++ req := httptest.NewRequest(method, path, body)+ token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{+ "iss": testIssuer,+ "sub": "user-123",+ "azp": "cyclops-cs-spa",+ "exp": time.Now().Add(time.Hour).Unix(),+ "iat": time.Now().Add(-time.Minute).Unix(),+ })+ token.Header["kid"] = testKeyID++ raw, err := token.SignedString(testSigningKey)+ if err != nil {+ t.Fatalf("sign test token: %v", err)+ }+ req.Header.Set("Authorization", "Bearer "+raw)+ return req+}++func bigEndianBytes(v int) []byte {+ if v == 0 {+ return []byte{0}+ }+ var out []byte+ for n := v; n > 0; n >>= 8 {+ out = append([]byte{byte(n & 0xff)}, out...)+ }+ return out+}diff --git a/libs/fleet/backend/metrics/metrics.go b/libs/fleet/backend/metrics/metrics.gonew file mode 100644index 0000000000..32392f9581--- /dev/null+++ b/libs/fleet/backend/metrics/metrics.go@@ -0,0 +1,211 @@+// Package metrics provides Prometheus metrics for the cyclops-cs backend.+//+// Exported metrics:+//+// cyclops_cs_http_requests_total - counter, labels: method, path, status_code+// cyclops_cs_http_request_duration_seconds - histogram, labels: method, path, status_code+// cyclops_cs_keycloak_requests_total - counter, labels: operation, status+// cyclops_cs_keycloak_request_duration_seconds - histogram, labels: operation, status+// cyclops_cs_upstream_proxy_requests_total - counter, labels: target, status_code+// cyclops_cs_upstream_proxy_duration_seconds - histogram, labels: target, status_code+// cyclops_cs_active_requests - gauge+//+// The metrics server is started separately on METRICS_ADDR (default :9091)+// so that the main HTTP server on :8080 stays free of /metrics traffic.+package metrics++import (+ "bufio"+ "fmt"+ "net"+ "net/http"+ "strconv"+ "time"++ "github.com/prometheus/client_golang/prometheus"+ "github.com/prometheus/client_golang/prometheus/promauto"+ "github.com/prometheus/client_golang/prometheus/promhttp"+)++var (+ // HTTP SLIs+ HTTPRequestsTotal = promauto.NewCounterVec(prometheus.CounterOpts{+ Name: "cyclops_cs_http_requests_total",+ Help: "Total HTTP requests handled by the cyclops-cs backend, by method, normalised path, and status code.",+ }, []string{"method", "path", "status_code"})++ HTTPRequestDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{+ Name: "cyclops_cs_http_request_duration_seconds",+ Help: "Latency of HTTP requests handled by the cyclops-cs backend.",+ Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},+ }, []string{"method", "path", "status_code"})++ ActiveRequests = promauto.NewGauge(prometheus.GaugeOpts{+ Name: "cyclops_cs_active_requests",+ Help: "Number of HTTP requests currently being processed by the cyclops-cs backend.",+ })++ // Keycloak admin API SLIs+ KeycloakRequestsTotal = promauto.NewCounterVec(prometheus.CounterOpts{+ Name: "cyclops_cs_keycloak_requests_total",+ Help: "Total Keycloak admin API requests made by the cyclops-cs backend.",+ }, []string{"operation", "status"})++ KeycloakRequestDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{+ Name: "cyclops_cs_keycloak_request_duration_seconds",+ Help: "Latency of Keycloak admin API requests.",+ Buckets: []float64{0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5},+ }, []string{"operation", "status"})++ // Upstream proxy SLIs (/api/gateway + /api/orch + /api/k8s)+ UpstreamProxyRequestsTotal = promauto.NewCounterVec(prometheus.CounterOpts{+ Name: "cyclops_cs_upstream_proxy_requests_total",+ Help: "Total requests proxied to upstream services (gateway/orch/k8s).",+ }, []string{"target", "status_code"})++ UpstreamProxyDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{+ Name: "cyclops_cs_upstream_proxy_duration_seconds",+ Help: "Latency of requests proxied to upstream services.",+ Buckets: []float64{0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30},+ }, []string{"target", "status_code"})+)++// responseWriter wraps http.ResponseWriter to capture the status code+// written by the handler so the metrics middleware can record it.+type responseWriter struct {+ http.ResponseWriter+ statusCode int+ written bool+}++func newResponseWriter(w http.ResponseWriter) *responseWriter {+ return &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}+}++func (rw *responseWriter) WriteHeader(code int) {+ if !rw.written {+ rw.statusCode = code+ rw.written = true+ }+ rw.ResponseWriter.WriteHeader(code)+}++func (rw *responseWriter) Write(b []byte) (int, error) {+ if !rw.written {+ rw.written = true+ }+ return rw.ResponseWriter.Write(b)+}++// Flush forwards to the underlying ResponseWriter if it implements+// http.Flusher. Required for streaming/proxy responses so that data is+// not buffered indefinitely in the middleware wrapper.+func (rw *responseWriter) Flush() {+ if f, ok := rw.ResponseWriter.(http.Flusher); ok {+ f.Flush()+ }+}++// Hijack forwards to the underlying ResponseWriter so WebSocket upgrades+// (e.g. noVNC's /websockify through /api/svc) survive this wrapper. Struct+// embedding only exposes http.ResponseWriter's interface methods, so without+// this passthrough httputil.ReverseProxy fails every 101 Switching Protocols+// with a 502 ("can't switch protocols using non-Hijacker ResponseWriter").+func (rw *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {+ hj, ok := rw.ResponseWriter.(http.Hijacker)+ if !ok {+ return nil, nil, fmt.Errorf("underlying ResponseWriter does not implement http.Hijacker")+ }+ if !rw.written {+ rw.statusCode = http.StatusSwitchingProtocols+ rw.written = true+ }+ return hj.Hijack()+}++// Middleware returns an http.Handler that records HTTP SLI metrics for+// each request. It must be placed as the outermost handler wrapper so+// that it captures the final status code from all inner layers (auth,+// OPA, business logic).+func Middleware(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ start := time.Now()+ rw := newResponseWriter(w)+ ActiveRequests.Inc()+ defer ActiveRequests.Dec()++ next.ServeHTTP(rw, r)++ duration := time.Since(start).Seconds()+ statusStr := strconv.Itoa(rw.statusCode)+ path := normalizePath(r.URL.Path)++ HTTPRequestsTotal.WithLabelValues(r.Method, path, statusStr).Inc()+ HTTPRequestDuration.WithLabelValues(r.Method, path, statusStr).Observe(duration)+ })+}++// normalizePath collapses high-cardinality dynamic path segments so+// Prometheus cardinality stays bounded.+//+// Examples:+//+// /api/keys/3f2a... → /api/keys/:id+// /api/gateway/mypool/reset → /api/gateway/:name/:path+// /api/orch/ns/svc/api/vms → /api/orch/:namespace/:service/:path+// /api/k8s/api/v1/pods → /api/k8s/:path+func normalizePath(p string) string {+ switch {+ case p == "/healthz":+ return "/healthz"+ case p == "/api/keys":+ return "/api/keys"+ case len(p) > 10 && p[:10] == "/api/keys/":+ return "/api/keys/:id"+ case len(p) > 13 && p[:13] == "/api/gateway/":+ return "/api/gateway/:name/:path"+ case len(p) > 9 && p[:9] == "/api/svc/":+ return "/api/svc/:namespace/:service/:path"+ case len(p) > 10 && p[:10] == "/api/orch/":+ return "/api/orch/:namespace/:service/:path"+ case len(p) > 9 && p[:9] == "/api/k8s/":+ return "/api/k8s/:path"+ default:+ return p+ }+}++// RecordKeycloakRequest records a Keycloak admin API operation result.+// operation: CreateKey, ListKeys, DeleteKey, AdminLogin+// success: true on 2xx / no error, false otherwise+func RecordKeycloakRequest(operation string, duration time.Duration, err error) {+ status := "success"+ if err != nil {+ status = "error"+ }+ KeycloakRequestsTotal.WithLabelValues(operation, status).Inc()+ KeycloakRequestDuration.WithLabelValues(operation, status).Observe(duration.Seconds())+}++// RecordUpstreamProxy records a reverse-proxy request to an upstream target.+// target: "gateway", "orch", or "k8s"+// statusCode: HTTP status code returned from upstream (0 if dial failed)+func RecordUpstreamProxy(target string, statusCode int, duration time.Duration) {+ statusStr := strconv.Itoa(statusCode)+ UpstreamProxyRequestsTotal.WithLabelValues(target, statusStr).Inc()+ UpstreamProxyDuration.WithLabelValues(target, statusStr).Observe(duration.Seconds())+}++// StartMetricsServer starts a lightweight HTTP server that exposes+// /metrics in Prometheus exposition format on addr (e.g. ":9090").+// It blocks until the server exits; run it in a goroutine.+func StartMetricsServer(addr string) error {+ mux := http.NewServeMux()+ mux.Handle("/metrics", promhttp.Handler())+ mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("ok"))+ })+ srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}+ return srv.ListenAndServe()+}diff --git a/libs/fleet/backend/metrics/metrics_test.go b/libs/fleet/backend/metrics/metrics_test.gonew file mode 100644index 0000000000..98dcb53ec1--- /dev/null+++ b/libs/fleet/backend/metrics/metrics_test.go@@ -0,0 +1,34 @@+package metrics++import (+ "testing"+)++func TestNormalizePath(t *testing.T) {+ cases := []struct {+ in string+ want string+ }{+ {"/healthz", "/healthz"},+ {"/api/keys", "/api/keys"},+ {"/api/keys/3f2a1b2c3d4e", "/api/keys/:id"},+ {"/api/keys/abc-def-ghi", "/api/keys/:id"},+ {"/api/gateway/mypool", "/api/gateway/:name/:path"},+ {"/api/gateway/mypool/reset", "/api/gateway/:name/:path"},+ {"/api/gateway/mypool/vms/list", "/api/gateway/:name/:path"},+ {"/api/svc/pool-mypool/my-svc/health", "/api/svc/:namespace/:service/:path"},+ {"/api/svc/pool-mypool/my-svc", "/api/svc/:namespace/:service/:path"},+ {"/api/orch/myns/svc/api/vms", "/api/orch/:namespace/:service/:path"},+ {"/api/k8s/api/v1/pods", "/api/k8s/:path"},+ {"/api/k8s/apis/apps/v1/deployments", "/api/k8s/:path"},+ {"/api/swagger/doc.json", "/api/swagger/doc.json"},+ {"/unknown", "/unknown"},+ {"", ""},+ }+ for _, tc := range cases {+ got := normalizePath(tc.in)+ if got != tc.want {+ t.Errorf("normalizePath(%q) = %q, want %q", tc.in, got, tc.want)+ }+ }+}diff --git a/libs/fleet/backend/middlewares/log.go b/libs/fleet/backend/middlewares/log.gonew file mode 100644index 0000000000..ee6c9e2674--- /dev/null+++ b/libs/fleet/backend/middlewares/log.go@@ -0,0 +1,91 @@+package middlewares++import (+ "bufio"+ "fmt"+ "log/slog"+ "net"+ "net/http"+ "os"+ "time"++ "go.opentelemetry.io/otel/trace"+)++type logResponseWriter struct {+ http.ResponseWriter+ statusCode int+}++func (w *logResponseWriter) WriteHeader(code int) {+ w.statusCode = code+ w.ResponseWriter.WriteHeader(code)+}++// Hijack forwards to the underlying ResponseWriter so WebSocket upgrades+// (e.g. noVNC's /websockify through /api/svc) survive this wrapper. Struct+// embedding only exposes http.ResponseWriter's interface methods, so without+// this passthrough httputil.ReverseProxy fails every 101 Switching Protocols+// with a 502 ("can't switch protocols using non-Hijacker ResponseWriter").+func (w *logResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {+ hj, ok := w.ResponseWriter.(http.Hijacker)+ if !ok {+ return nil, nil, fmt.Errorf("underlying ResponseWriter does not implement http.Hijacker")+ }+ w.statusCode = http.StatusSwitchingProtocols+ return hj.Hijack()+}++// Flush forwards to the underlying ResponseWriter so streaming responses+// (SSE, chunked proxying) are not buffered by the wrapper.+func (w *logResponseWriter) Flush() {+ if f, ok := w.ResponseWriter.(http.Flusher); ok {+ f.Flush()+ }+}++func LogMiddleware(next http.Handler) http.Handler {+ return LogMiddlewareWithLogger(slog.Default())(next)+}++func LogMiddlewareWithLogger(logger *slog.Logger) func(http.Handler) http.Handler {+ return func(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ start := time.Now()+ lw := &logResponseWriter{ResponseWriter: w, statusCode: http.StatusOK}+ next.ServeHTTP(lw, r)++ spanCtx := trace.SpanContextFromContext(r.Context())+ route, _ := r.Context().Value(ContextKey("route")).(string)+ if route == "" {+ route = r.URL.Path+ }++ attrs := []any{+ "service_name", envOrDefault("OTEL_SERVICE_NAME", "cyclops-cs-backend"),+ "service_namespace", envOrDefault("OTEL_SERVICE_NAMESPACE", "cyclops-cs"),+ "deployment_environment", envOrDefault("OTEL_ENVIRONMENT", "production"),+ "method", r.Method,+ "url", r.URL.Path,+ "route", route,+ "duration", time.Since(start),+ "status", lw.statusCode,+ }+ if spanCtx.IsValid() {+ attrs = append(attrs,+ "trace_id", spanCtx.TraceID().String(),+ "span_id", spanCtx.SpanID().String(),+ )+ }++ logger.Info("WebRequest", attrs...)+ })+ }+}++func envOrDefault(key, fallback string) string {+ if value := os.Getenv(key); value != "" {+ return value+ }+ return fallback+}diff --git a/libs/fleet/backend/middlewares/log_test.go b/libs/fleet/backend/middlewares/log_test.gonew file mode 100644index 0000000000..6c061a63c4--- /dev/null+++ b/libs/fleet/backend/middlewares/log_test.go@@ -0,0 +1,80 @@+package middlewares++import (+ "bytes"+ "context"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "go.opentelemetry.io/otel"+ sdktrace "go.opentelemetry.io/otel/sdk/trace"+ "go.opentelemetry.io/otel/trace"+)++func TestLogMiddleware_EmitsTraceAndSpanIDs(t *testing.T) {+ t.Setenv("OTEL_SERVICE_NAME", "cyclops-cs-backend")+ t.Setenv("OTEL_SERVICE_NAMESPACE", "cyclops-cs")+ t.Setenv("OTEL_ENVIRONMENT", "production")++ tp := sdktrace.NewTracerProvider()+ ctx, span := tp.Tracer("test").Start(context.Background(), "request")+ defer span.End()++ var buf bytes.Buffer+ logger := slog.New(slog.NewJSONHandler(&buf, nil))+ req := httptest.NewRequest(http.MethodGet, "/healthz", nil).WithContext(ctx)+ req = req.WithContext(context.WithValue(req.Context(), ContextKey("route"), "/healthz"))+ rr := httptest.NewRecorder()++ LogMiddlewareWithLogger(logger)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ })).ServeHTTP(rr, req)++ logLine := buf.String()+ if !strings.Contains(logLine, "trace_id") {+ t.Fatalf("log line missing trace_id: %s", logLine)+ }+ if !strings.Contains(logLine, "span_id") {+ t.Fatalf("log line missing span_id: %s", logLine)+ }+ if !strings.Contains(logLine, "\"route\":\"/healthz\"") {+ t.Fatalf("log line missing route: %s", logLine)+ }+ if !strings.Contains(logLine, "\"service_name\":\"cyclops-cs-backend\"") {+ t.Fatalf("log line missing service_name: %s", logLine)+ }+}++func TestTraceMiddleware_StartsSpanAndStoresRoute(t *testing.T) {+ tp := sdktrace.NewTracerProvider()+ otel.SetTracerProvider(tp)+ t.Cleanup(func() {+ _ = tp.Shutdown(context.Background())+ })++ var (+ gotRoute string+ hasSpan bool+ )++ req := httptest.NewRequest(http.MethodGet, "/api/keys", nil)+ rr := httptest.NewRecorder()++ handler := TraceMiddleware("/api/keys", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotRoute, _ = r.Context().Value(ContextKey("route")).(string)+ hasSpan = trace.SpanContextFromContext(r.Context()).IsValid()+ w.WriteHeader(http.StatusOK)+ }))++ handler.ServeHTTP(rr, req)++ if gotRoute != "/api/keys" {+ t.Fatalf("route = %q, want %q", gotRoute, "/api/keys")+ }+ if !hasSpan {+ t.Fatal("expected valid span context")+ }+}diff --git a/libs/fleet/backend/middlewares/trace.go b/libs/fleet/backend/middlewares/trace.gonew file mode 100644index 0000000000..badd945f9a--- /dev/null+++ b/libs/fleet/backend/middlewares/trace.go@@ -0,0 +1,27 @@+// Package middlewares wires request-scoped metadata used across auth, logging,+// and OTEL tracing.+package middlewares++import (+ "context"+ "net/http"++ "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"+)++type ContextKey string++func TraceMiddleware(route string, next http.Handler) http.Handler {+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ ctx := context.WithValue(r.Context(), ContextKey("route"), route)+ next.ServeHTTP(w, r.WithContext(ctx))+ })++ return otelhttp.NewHandler(+ handler,+ route,+ otelhttp.WithSpanNameFormatter(func(_ string, _ *http.Request) string {+ return route+ }),+ )+}diff --git a/libs/fleet/backend/telemetry/telemetry.go b/libs/fleet/backend/telemetry/telemetry.gonew file mode 100644index 0000000000..be967e1b83--- /dev/null+++ b/libs/fleet/backend/telemetry/telemetry.go@@ -0,0 +1,83 @@+package telemetry++import (+ "context"+ "fmt"+ "strings"+ "sync"++ "go.opentelemetry.io/otel"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"+ "go.opentelemetry.io/otel/propagation"+ "go.opentelemetry.io/otel/sdk/resource"+ sdktrace "go.opentelemetry.io/otel/sdk/trace"+ semconv "go.opentelemetry.io/otel/semconv/v1.26.0"+)++type Config struct {+ Endpoint string+ Protocol string+ ServiceName string+ ServiceNamespace string+ Environment string+ ResourceAttrs string+}++func Init(ctx context.Context, cfg Config) (func(context.Context) error, error) {+ if cfg.Endpoint == "" {+ return func(context.Context) error { return nil }, nil+ }+ if cfg.Protocol != "" && cfg.Protocol != "http/protobuf" {+ return nil, fmt.Errorf("unsupported OTEL protocol %q", cfg.Protocol)+ }++ res, err := resource.New(+ ctx,+ resource.WithAttributes(buildResourceAttributes(cfg)...),+ )+ if err != nil {+ return nil, fmt.Errorf("build resource: %w", err)+ }++ exporter, err := otlptracehttp.New(ctx, otlptracehttp.WithEndpointURL(cfg.Endpoint))+ if err != nil {+ return nil, fmt.Errorf("create otlp http trace exporter: %w", err)+ }++ provider := sdktrace.NewTracerProvider(+ sdktrace.WithBatcher(exporter),+ sdktrace.WithResource(res),+ )+ otel.SetTracerProvider(provider)+ otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(+ propagation.TraceContext{},+ propagation.Baggage{},+ ))++ var once sync.Once+ return func(ctx context.Context) error {+ var shutdownErr error+ once.Do(func() {+ shutdownErr = provider.Shutdown(ctx)+ })+ return shutdownErr+ }, nil+}++func buildResourceAttributes(cfg Config) []attribute.KeyValue {+ attrs := []attribute.KeyValue{+ semconv.ServiceName(cfg.ServiceName),+ semconv.ServiceNamespace(cfg.ServiceNamespace),+ attribute.String("deployment.environment", cfg.Environment),+ }++ for _, part := range strings.Split(cfg.ResourceAttrs, ",") {+ key, value, ok := strings.Cut(strings.TrimSpace(part), "=")+ if !ok || key == "" || value == "" {+ continue+ }+ attrs = append(attrs, attribute.String(key, value))+ }+ return attrs+}diff --git a/libs/fleet/backend/telemetry/telemetry_test.go b/libs/fleet/backend/telemetry/telemetry_test.gonew file mode 100644index 0000000000..eef9f5d814--- /dev/null+++ b/libs/fleet/backend/telemetry/telemetry_test.go@@ -0,0 +1,70 @@+package telemetry++import (+ "context"+ "io"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"+ "time"++ "go.opentelemetry.io/otel"+)++func TestInit_ExportsSpansOverOTLPHTTP(t *testing.T) {+ var (+ mu sync.Mutex+ requestPath string+ bodySize int+ )++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, err := io.ReadAll(r.Body)+ if err != nil {+ t.Fatalf("read body: %v", err)+ }+ mu.Lock()+ requestPath = r.URL.Path+ bodySize = len(body)+ mu.Unlock()+ w.WriteHeader(http.StatusAccepted)+ }))+ defer srv.Close()++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ shutdown, err := Init(ctx, Config{+ Endpoint: srv.URL,+ Protocol: "http/protobuf",+ ServiceName: "cyclops-cs-backend",+ ServiceNamespace: "cyclops-cs",+ Environment: "production",+ })+ if err != nil {+ t.Fatalf("Init() error = %v", err)+ }+ defer func() {+ if err := shutdown(context.Background()); err != nil {+ t.Fatalf("shutdown() error = %v", err)+ }+ }()++ _, span := otel.Tracer("test").Start(ctx, "backend.request")+ span.End()++ if err := shutdown(context.Background()); err != nil {+ t.Fatalf("shutdown() error = %v", err)+ }++ mu.Lock()+ defer mu.Unlock()++ if requestPath != "/v1/traces" {+ t.Fatalf("request path = %q, want %q", requestPath, "/v1/traces")+ }+ if bodySize == 0 {+ t.Fatalf("body size = %d, want > 0", bodySize)+ }+}diff --git a/libs/fleet/backend/templates/store.go b/libs/fleet/backend/templates/store.gonew file mode 100644index 0000000000..980953d69e--- /dev/null+++ b/libs/fleet/backend/templates/store.go@@ -0,0 +1,199 @@+package templates++// Redis-backed persistence for pool templates.+//+// Schema:+//+// pooltpl:<user>:<name> HASH user, name, created_at (RFC3339Nano), config+// pooltpl:index:<user> SET template names owned by <user>+//+// The per-user index SET is the listing index — List() reads it and+// HGETALLs each member, so we never SCAN the whole keyspace (and never+// risk returning another user's templates). The `pooltpl:` prefix keeps+// this keyspace disjoint from the batch driver's `batch:*` keys when both+// share one Redis instance.+//+// Unlike the batch Store, writes here are synchronous: a template save is+// a deliberate, low-frequency user action (clicking "Save as template"),+// not a hot per-request mutation, so there's no CUA-535 latency concern to+// engineer around.++import (+ "context"+ "encoding/json"+ "fmt"+ "log/slog"+ "time"++ "github.com/redis/go-redis/v9"+)++const (+ keyPrefix = "pooltpl:"+ indexPrefix = "pooltpl:index:"+)++// Store persists per-user pool templates. Every method takes the owning+// user so the storage layer enforces the same isolation the HTTP layer+// does — there is no way to address a template without naming its owner.+type Store interface {+ Save(ctx context.Context, t *Template) error+ Get(ctx context.Context, user, name string) (*Template, error)+ List(ctx context.Context, user string) ([]*Template, error)+ // Delete reports whether a template existed, so the handler can+ // distinguish 404 from a successful no-op.+ Delete(ctx context.Context, user, name string) (bool, error)+}++func tplKey(user, name string) string { return keyPrefix + user + ":" + name }+func indexKey(user string) string { return indexPrefix + user }++type redisStore struct{ c *redis.Client }++// New connects to Redis and returns a Store. An empty url returns+// (nil, nil): the caller treats a nil Store as "templates disabled" and+// the handlers reply 503, rather than a no-op store silently dropping+// writes and confusing the user with an always-empty list. A malformed+// url is a genuine config error and is returned as such.+//+// The startup ping is best-effort: a transient Redis outage during a+// deploy must not permanently disable the feature, and the go-redis+// client reconnects on its own, so a failed ping is logged and the store+// is still returned. Real outages then surface as per-request 500s+// (handler errors), not as a silent always-503.+func New(ctx context.Context, url string) (Store, error) {+ if url == "" {+ return nil, nil+ }+ opts, err := redis.ParseURL(url)+ if err != nil {+ return nil, fmt.Errorf("parse redis url: %w", err)+ }+ c := redis.NewClient(opts)+ pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ if err := c.Ping(pingCtx).Err(); err != nil {+ slog.Warn("templates: redis ping failed at startup; will retry on demand", "err", err)+ }+ return &redisStore{c: c}, nil+}++// Save writes (or overwrites) a template and adds it to the owner's index.+// Overwriting an existing template preserves its original created_at — a+// re-save updates the config without resetting the template's age.+func (s *redisStore) Save(ctx context.Context, t *Template) error {+ key := tplKey(t.User, t.Name)++ createdAt := t.CreatedAt+ switch existing, err := s.c.HGet(ctx, key, "created_at").Result(); {+ case err == nil && existing != "":+ if parsed, perr := time.Parse(time.RFC3339Nano, existing); perr == nil {+ createdAt = parsed+ }+ case err != nil && err != redis.Nil:+ return fmt.Errorf("hget created_at: %w", err)+ }+ if createdAt.IsZero() {+ createdAt = time.Now().UTC()+ }+ t.CreatedAt = createdAt++ pipe := s.c.TxPipeline()+ pipe.HSet(ctx, key, map[string]interface{}{+ "user": t.User,+ "name": t.Name,+ "created_at": createdAt.UTC().Format(time.RFC3339Nano),+ "config": string(t.Config),+ })+ pipe.SAdd(ctx, indexKey(t.User), t.Name)+ if _, err := pipe.Exec(ctx); err != nil {+ return fmt.Errorf("save template: %w", err)+ }+ return nil+}++// Get returns one template, or (nil, nil) if the user has no template by+// that name.+func (s *redisStore) Get(ctx context.Context, user, name string) (*Template, error) {+ fields, err := s.c.HGetAll(ctx, tplKey(user, name)).Result()+ if err != nil {+ return nil, fmt.Errorf("hgetall: %w", err)+ }+ if len(fields) == 0 {+ return nil, nil+ }+ return hydrate(user, name, fields), nil+}++// List returns all of the user's templates, newest first. Stale index+// entries (name present but hash gone, e.g. TTL/eviction) are self-healed+// with an SREM and skipped.+func (s *redisStore) List(ctx context.Context, user string) ([]*Template, error) {+ names, err := s.c.SMembers(ctx, indexKey(user)).Result()+ if err != nil {+ return nil, fmt.Errorf("smembers: %w", err)+ }+ out := make([]*Template, 0, len(names))+ for _, name := range names {+ fields, err := s.c.HGetAll(ctx, tplKey(user, name)).Result()+ if err != nil {+ return nil, fmt.Errorf("hgetall %s: %w", name, err)+ }+ if len(fields) == 0 {+ s.c.SRem(ctx, indexKey(user), name)+ continue+ }+ out = append(out, hydrate(user, name, fields))+ }+ sortByCreatedDesc(out)+ return out, nil+}++// Delete removes a template and its index entry. The bool reports whether+// the template existed so the handler can return 404 vs 204.+func (s *redisStore) Delete(ctx context.Context, user, name string) (bool, error) {+ pipe := s.c.TxPipeline()+ del := pipe.Del(ctx, tplKey(user, name))+ pipe.SRem(ctx, indexKey(user), name)+ if _, err := pipe.Exec(ctx); err != nil {+ return false, fmt.Errorf("delete template: %w", err)+ }+ return del.Val() > 0, nil+}++// hydrate builds a Template from a Redis HASH. user/name args are the+// addressed key components, used as a fallback if the stored fields are+// somehow missing.+func hydrate(user, name string, fields map[string]string) *Template {+ t := &Template{+ User: fields["user"],+ Name: fields["name"],+ Config: json.RawMessage(fields["config"]),+ }+ if t.User == "" {+ t.User = user+ }+ if t.Name == "" {+ t.Name = name+ }+ if v := fields["created_at"]; v != "" {+ if parsed, err := time.Parse(time.RFC3339Nano, v); err == nil {+ t.CreatedAt = parsed+ }+ }+ if len(t.Config) == 0 {+ t.Config = json.RawMessage("null")+ }+ return t+}++// sortByCreatedDesc orders templates newest-first. Insertion sort keeps+// the dependency surface zero (no sort import churn) and is trivially fast+// for the handful of templates a single user keeps.+func sortByCreatedDesc(ts []*Template) {+ for i := 1; i < len(ts); i++ {+ for j := i; j > 0 && ts[j].CreatedAt.After(ts[j-1].CreatedAt); j-- {+ ts[j], ts[j-1] = ts[j-1], ts[j]+ }+ }+}diff --git a/libs/fleet/backend/templates/store_test.go b/libs/fleet/backend/templates/store_test.gonew file mode 100644index 0000000000..ea6b59696a--- /dev/null+++ b/libs/fleet/backend/templates/store_test.go@@ -0,0 +1,87 @@+package templates++import (+ "context"+ "encoding/json"+ "testing"+ "time"+)++func TestKeyLayoutIsUserScoped(t *testing.T) {+ // A template key always carries its owner, so one user's name can+ // never resolve to another user's hash.+ if got := tplKey("user-a", "tpl"); got != "pooltpl:user-a:tpl" {+ t.Fatalf("tplKey = %q", got)+ }+ if got := indexKey("user-a"); got != "pooltpl:index:user-a" {+ t.Fatalf("indexKey = %q", got)+ }+ if tplKey("user-a", "tpl") == tplKey("user-b", "tpl") {+ t.Fatal("identical template name across users must not collide")+ }+}++func TestHydrateFallsBackToAddressedKey(t *testing.T) {+ // Missing user/name fields fall back to the addressed components;+ // missing config becomes JSON null, not an empty (invalid) blob.+ got := hydrate("user-a", "tpl", map[string]string{+ "created_at": "2026-05-01T10:00:00Z",+ })+ if got.User != "user-a" || got.Name != "tpl" {+ t.Fatalf("fallback user/name = %q/%q", got.User, got.Name)+ }+ if string(got.Config) != "null" {+ t.Fatalf("empty config = %q, want null", string(got.Config))+ }+ if got.CreatedAt.IsZero() {+ t.Fatal("created_at not parsed")+ }+}++func TestHydratePrefersStoredFields(t *testing.T) {+ got := hydrate("addr-user", "addr-name", map[string]string{+ "user": "stored-user",+ "name": "stored-name",+ "config": `{"cpu":4}`,+ })+ if got.User != "stored-user" || got.Name != "stored-name" {+ t.Fatalf("stored user/name = %q/%q", got.User, got.Name)+ }+ if string(got.Config) != `{"cpu":4}` {+ t.Fatalf("config = %q", string(got.Config))+ }+}++func TestSortByCreatedDescNewestFirst(t *testing.T) {+ mk := func(name string, ts string) *Template {+ at, _ := time.Parse(time.RFC3339, ts)+ return &Template{Name: name, CreatedAt: at, Config: json.RawMessage("null")}+ }+ ts := []*Template{+ mk("old", "2026-01-01T00:00:00Z"),+ mk("new", "2026-03-01T00:00:00Z"),+ mk("mid", "2026-02-01T00:00:00Z"),+ }+ sortByCreatedDesc(ts)+ if ts[0].Name != "new" || ts[1].Name != "mid" || ts[2].Name != "old" {+ t.Fatalf("order = %s,%s,%s", ts[0].Name, ts[1].Name, ts[2].Name)+ }+}++func TestNewEmptyURLDisabled(t *testing.T) {+ // No URL → (nil, nil): the caller treats nil as "disabled" and the+ // handlers return 503 rather than silently dropping writes.+ store, err := New(context.Background(), "")+ if err != nil {+ t.Fatalf("New(\"\") err = %v", err)+ }+ if store != nil {+ t.Fatal("New(\"\") store should be nil")+ }+}++func TestNewInvalidURLErrors(t *testing.T) {+ if _, err := New(context.Background(), "not-a-redis-url"); err == nil {+ t.Fatal("New with garbage URL should error")+ }+}diff --git a/libs/fleet/backend/templates/types.go b/libs/fleet/backend/templates/types.gonew file mode 100644index 0000000000..6cf592c63e--- /dev/null+++ b/libs/fleet/backend/templates/types.go@@ -0,0 +1,34 @@+// Package templates provides Redis-backed, per-user pool templates for+// cyclops-cs.+//+// A template is a saved OSGymWorkspacePool config the user can reuse to+// stamp out new pools without re-entering every field. It is the+// persistent, per-user evolution of the SPA's existing in-memory+// "Duplicate pool" action.+//+// Each template is stored exactly as requested — four fields:+//+// user the owning user (Keycloak sub)+// created_at when the template was first saved (RFC3339Nano)+// name the template's name (unique per user)+// config the opaque pool-config JSON the SPA sends to createPool+//+// The HTTP layer scopes every call to the caller's sub, and the Redis+// key layout (see store.go) namespaces every key by user, so one user+// can never see or clobber another's templates.+package templates++import (+ "encoding/json"+ "time"+)++// Template is a single saved pool config owned by one user. Config is+// kept opaque (json.RawMessage) so the backend never has to track the+// evolving OSGymWorkspacePool spec — the SPA owns that shape.+type Template struct {+ User string `json:"user"`+ Name string `json:"name"`+ CreatedAt time.Time `json:"createdAt"`+ Config json.RawMessage `json:"config"`+}diff --git a/libs/fleet/biome.json b/libs/fleet/biome.jsonnew file mode 100644index 0000000000..df3dd30a83--- /dev/null+++ b/libs/fleet/biome.json@@ -0,0 +1,46 @@+{+ "$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",+ "vcs": { "enabled": false, "clientKind": "git", "useIgnoreFile": false },+ "files": {+ "includes": ["src/**", "!**/dist", "!**/node_modules", "!src/api/generated/**"]+ },+ "overrides": [+ {+ "includes": ["src/api/generated/**"],+ "linter": { "enabled": false }+ }+ ],+ "formatter": { "enabled": false },+ "assist": { "actions": { "source": { "organizeImports": "off" } } },+ "linter": {+ "enabled": true,+ "rules": {+ "recommended": true,+ "style": {+ "useSelfClosingElements": "warn",+ "noUnusedTemplateLiteral": "warn",+ "noNonNullAssertion": "off",+ "useImportType": "warn"+ },+ "a11y": {+ "useKeyWithClickEvents": "warn",+ "useKeyWithMouseEvents": "warn",+ "useButtonType": "warn"+ },+ "suspicious": {+ "noArrayIndexKey": "off",+ "noGlobalIsFinite": "warn",+ "noGlobalIsNan": "warn"+ },+ "security": {+ "noDangerouslySetInnerHtml": "warn"+ },+ "correctness": {+ "noUnusedVariables": "error",+ "noUnusedFunctionParameters": "warn",+ "noUnusedImports": "warn",+ "useExhaustiveDependencies": "warn"+ }+ }+ }+}diff --git a/libs/fleet/e2e/fixtures/mock-api.ts b/libs/fleet/e2e/fixtures/mock-api.tsnew file mode 100644index 0000000000..8fba24731d--- /dev/null+++ b/libs/fleet/e2e/fixtures/mock-api.ts@@ -0,0 +1,450 @@+// Mock API helpers for Playwright E2E tests.+//+// The cyclops-cs SPA authenticates via Keycloak PKCE (keycloak-js). In+// tests we intercept every outbound request so no real Keycloak or K8s+// cluster is needed.++import type { Page } from "@playwright/test"++// ---------------------------------------------------------------------------+// Keycloak auth mocking+// ---------------------------------------------------------------------------+// keycloak-js performs:+// 1. OIDC discovery: GET <kcUrl>/realms/<realm>/.well-known/openid-configuration+// 2. Token exchange (authorization_code or refresh): POST <tokenEndpoint>+// 3. Redirect to <authorizationEndpoint> when onLoad is "login-required"+//+// With onLoad: "login-required" the library checks for an existing session+// by looking at an iframe or checking URL params. If none, it redirects.+// Our strategy: intercept the well-known endpoint so the library gets+// valid-looking URLs, then intercept the auth redirect and short-circuit+// it by navigating back with a fake code. Finally, intercept the token+// endpoint to return a fake JWT.+//+// Simpler alternative chosen here: inject a script BEFORE the app bundle+// loads that replaces the Keycloak constructor with a stub. Vite serves+// the app as ES modules, and page.addInitScript runs before any module+// evaluation.++const FAKE_TOKEN =+ "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9." ++ btoa(+ JSON.stringify({+ sub: "test-user-id",+ email: "[email protected]",+ preferred_username: "testuser",+ exp: Math.floor(Date.now() / 1000) + 3600,+ iat: Math.floor(Date.now() / 1000),+ iss: "https://auth.cua.ai/realms/cyclops-cs",+ aud: "cyclops-cs-spa",+ }),+ ) ++ ".fake-signature"++/**+ * Stub Keycloak auth so the AuthProvider renders children immediately.+ *+ * Must be called BEFORE page.goto() so the init script runs before the+ * app's ES modules are evaluated.+ *+ * Strategy: intercept the Vite-served keycloak-js module and replace it+ * with a stub class that resolves init() immediately as authenticated.+ * This avoids the real keycloak-js redirecting to the Keycloak login page.+ */+export async function mockAuth(page: Page): Promise<void> {+ // Intercept the Vite pre-bundled keycloak-js module. Vite serves+ // node_modules deps from /.vite/deps/ or /node_modules/.vite/deps/.+ // Replace the entire module with a stub Keycloak class.+ await page.route(/keycloak-js/, (route) => {+ route.fulfill({+ contentType: "application/javascript",+ body: `+ class Keycloak {+ constructor() {+ this.token = "${FAKE_TOKEN}";+ this.refreshToken = "fake-refresh";+ this.idToken = "${FAKE_TOKEN}";+ this.authenticated = true;+ this.tokenParsed = {+ sub: "test-user-id",+ email: "[email protected]",+ preferred_username: "testuser",+ azp: "cyclops-cs-spa",+ exp: Math.floor(Date.now() / 1000) + 3600,+ };+ this.realmAccess = { roles: [] };+ this.resourceAccess = {};+ this.subject = "test-user-id";+ }+ async init() { this.authenticated = true; return true; }+ async updateToken() { return true; }+ login() {}+ logout() { window.location.href = "/"; }+ register() {}+ accountManagement() {}+ createLoginUrl() { return "/"; }+ createLogoutUrl() { return "/"; }+ createRegisterUrl() { return "/"; }+ createAccountUrl() { return "/"; }+ isTokenExpired() { return false; }+ clearToken() {}+ hasRealmRole() { return false; }+ hasResourceRole() { return false; }+ loadUserProfile() { return Promise.resolve({ username: "testuser" }); }+ loadUserInfo() { return Promise.resolve({ sub: "test-user-id" }); }+ }+ Keycloak.default = Keycloak;+ export default Keycloak;+ export { Keycloak };+ `,+ })+ })++ // Mock the /api/config endpoint (feature flags)+ await page.route("**/api/config", (route) =>+ route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({ admin: false }),+ }),+ )++ // Intercept any stray Keycloak endpoint requests+ await page.route("**/realms/cyclops-cs/**", (route) =>+ route.fulfill({ status: 200, contentType: "application/json", body: "{}" }),+ )+}++// ---------------------------------------------------------------------------+// Namespaces API mocking+// ---------------------------------------------------------------------------++export interface MockNamespace {+ name: string+ status: string+ createdAt: string+ labels: Record<string, string> | null+}++const DEFAULT_NAMESPACES: MockNamespace[] = [+ {+ name: "my-workspace",+ status: "Active",+ createdAt: "2026-01-15T10:00:00Z",+ labels: null,+ },+ {+ name: "staging",+ status: "Active",+ createdAt: "2026-02-01T12:00:00Z",+ labels: null,+ },+]++export async function mockNamespacesApi(+ page: Page,+ namespaces: MockNamespace[] = DEFAULT_NAMESPACES,+): Promise<void> {+ // The app calls /api/namespaces (GET, POST) and /api/namespaces/:name (DELETE)+ await page.route("**/api/namespaces", async (route) => {+ if (route.request().method() === "GET") {+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify(namespaces),+ })+ } else if (route.request().method() === "POST") {+ const body = route.request().postDataJSON()+ const created: MockNamespace = {+ name: body.name,+ status: "Active",+ createdAt: new Date().toISOString(),+ labels: null,+ }+ namespaces.push(created)+ await route.fulfill({+ status: 201,+ contentType: "application/json",+ body: JSON.stringify(created),+ })+ } else {+ await route.continue()+ }+ })++ await page.route("**/api/namespaces/*", async (route) => {+ if (route.request().method() === "DELETE") {+ const url = new URL(route.request().url())+ const name = url.pathname.split("/").pop()+ const idx = namespaces.findIndex((ns) => ns.name === name)+ if (idx >= 0) namespaces.splice(idx, 1)+ await route.fulfill({ status: 204, body: "" })+ } else {+ await route.continue()+ }+ })+}++// ---------------------------------------------------------------------------+// User API keys mocking+// ---------------------------------------------------------------------------++export interface MockUserApiKey {+ id: string+ client_id: string+ name: string+ scope: string[]+}++const DEFAULT_USER_KEYS: MockUserApiKey[] = [+ {+ id: "key-1",+ client_id: "sa-testuser-mykey",+ name: "my-key",+ scope: [],+ },+]++export async function mockUserKeysApi(+ page: Page,+ keys: MockUserApiKey[] = DEFAULT_USER_KEYS,+): Promise<void> {+ await page.route("**/api/user-keys", async (route) => {+ if (route.request().method() === "GET") {+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({ keys }),+ })+ } else if (route.request().method() === "POST") {+ const body = route.request().postDataJSON()+ const newKey: MockUserApiKey = {+ id: `key-${Date.now()}`,+ client_id: `sa-testuser-${body.name}`,+ name: body.name,+ scope: body.scope ?? [],+ }+ keys.push(newKey)+ await route.fulfill({+ status: 201,+ contentType: "application/json",+ body: JSON.stringify({+ client_id: newKey.client_id,+ client_secret: "fake-client-secret-shown-once",+ token_url:+ "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token",+ name: newKey.name,+ scope: newKey.scope,+ }),+ })+ } else {+ await route.continue()+ }+ })++ await page.route("**/api/user-keys/*", async (route) => {+ if (route.request().method() === "DELETE") {+ const url = new URL(route.request().url())+ const id = url.pathname.split("/").pop()+ const idx = keys.findIndex((k) => k.id === id)+ if (idx >= 0) keys.splice(idx, 1)+ await route.fulfill({ status: 204, body: "" })+ } else {+ await route.continue()+ }+ })+}++// ---------------------------------------------------------------------------+// Pools API mocking (K8s CRD via kubectl-proxy sidecar)+// ---------------------------------------------------------------------------++export async function mockPoolsApi(page: Page): Promise<void> {+ // List pools: GET /api/k8s/apis/cua.ai/v1/osgymworkspacepools+ await page.route("**/api/k8s/apis/cua.ai/v1/osgymworkspacepools", async (route) => {+ if (route.request().method() === "GET") {+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({+ items: [+ {+ metadata: { name: "demo-pool", namespace: "my-workspace" },+ spec: { replicas: 2 },+ status: { phase: "Ready", availableCount: 2 },+ },+ ],+ }),+ })+ } else {+ await route.continue()+ }+ })++ // Create pool: POST /api/k8s/apis/cua.ai/v1/namespaces/*/osgymworkspacepools+ await page.route(+ "**/api/k8s/apis/cua.ai/v1/namespaces/*/osgymworkspacepools",+ async (route) => {+ if (route.request().method() === "POST") {+ const body = route.request().postDataJSON()+ await route.fulfill({+ status: 201,+ contentType: "application/json",+ body: JSON.stringify({+ metadata: {+ name: body.metadata.name,+ namespace: route.request().url().split("/namespaces/")[1].split("/")[0],+ },+ spec: body.spec,+ status: { phase: "Provisioning" },+ }),+ })+ } else {+ await route.continue()+ }+ },+ )+}++// ---------------------------------------------------------------------------+// Claims API mocking (OSGymSandboxClaim CRD)+// ---------------------------------------------------------------------------++export async function mockClaimsApi(page: Page): Promise<void> {+ await page.route(+ "**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/*/osgymsandboxclaims",+ async (route) => {+ if (route.request().method() === "GET") {+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({+ items: [+ {+ metadata: {+ name: "claim-abc123",+ namespace: "pool-demo-pool",+ creationTimestamp: "2026-05-28T10:00:00Z",+ },+ spec: {+ sandboxTemplateRef: { name: "demo-pool-template" },+ warmpool: "default",+ },+ status: {+ phase: "Bound",+ sandbox: {+ name: "vm-xyz789",+ service: "vm-xyz789-svc",+ },+ },+ },+ ],+ }),+ })+ } else if (route.request().method() === "POST") {+ const body = route.request().postDataJSON()+ await route.fulfill({+ status: 201,+ contentType: "application/json",+ body: JSON.stringify({+ metadata: {+ name: body.metadata.name,+ namespace: "pool-demo-pool",+ creationTimestamp: new Date().toISOString(),+ },+ spec: body.spec,+ status: { phase: "Pending" },+ }),+ })+ } else {+ await route.continue()+ }+ },+ )++ // DELETE for individual claims+ await page.route(+ "**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/*/osgymsandboxclaims/*",+ async (route) => {+ if (route.request().method() === "DELETE") {+ await route.fulfill({ status: 200, body: "{}" })+ } else {+ await route.continue()+ }+ },+ )+}++// ---------------------------------------------------------------------------+// Pool templates API mocking (/api/pool-templates — Redis-backed)+// ---------------------------------------------------------------------------++export interface MockPoolTemplate {+ user: string+ name: string+ createdAt: string+ config: Record<string, unknown>+}++const DEFAULT_POOL_TEMPLATES: MockPoolTemplate[] = [+ {+ user: "test-user-id",+ name: "gpu-large",+ createdAt: "2026-05-01T10:00:00Z",+ config: {+ cpu: 8,+ ram: "16Gi",+ ociImage: "example/osgym-workspace:latest",+ replicas: 2,+ },+ },+]++export async function mockPoolTemplatesApi(+ page: Page,+ templates: MockPoolTemplate[] = DEFAULT_POOL_TEMPLATES,+): Promise<void> {+ // GET list + POST create+ await page.route("**/api/pool-templates", async (route) => {+ if (route.request().method() === "GET") {+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify(templates),+ })+ } else if (route.request().method() === "POST") {+ const body = route.request().postDataJSON()+ const created: MockPoolTemplate = {+ user: "test-user-id",+ name: body.name,+ createdAt: new Date().toISOString(),+ config: body.config,+ }+ const idx = templates.findIndex((t) => t.name === body.name)+ if (idx >= 0) templates[idx] = created+ else templates.push(created)+ await route.fulfill({+ status: 201,+ contentType: "application/json",+ body: JSON.stringify(created),+ })+ } else {+ await route.continue()+ }+ })++ // DELETE /api/pool-templates/:name+ await page.route("**/api/pool-templates/*", async (route) => {+ if (route.request().method() === "DELETE") {+ const url = new URL(route.request().url())+ const name = decodeURIComponent(url.pathname.split("/").pop() ?? "")+ const idx = templates.findIndex((t) => t.name === name)+ if (idx < 0) {+ await route.fulfill({+ status: 404,+ contentType: "application/json",+ body: JSON.stringify({ error: "template not found" }),+ })+ return+ }+ templates.splice(idx, 1)+ await route.fulfill({ status: 204, body: "" })+ } else {+ await route.continue()+ }+ })+}diff --git a/libs/fleet/e2e/pools.spec.ts b/libs/fleet/e2e/pools.spec.tsnew file mode 100644index 0000000000..8cb0617c21--- /dev/null+++ b/libs/fleet/e2e/pools.spec.ts@@ -0,0 +1,173 @@+import { test, expect } from "@playwright/test"+import {+ mockAuth,+ mockNamespacesApi,+ mockPoolsApi,+ mockClaimsApi,+} from "./fixtures/mock-api"++test.describe("Pool creation", () => {+ test("pool creation form has name field", async ({ page }) => {+ await mockAuth(page)+ await mockNamespacesApi(page)+ await mockPoolsApi(page)++ await page.goto("/pools/new")++ // The form should have a name input+ await expect(page.getByPlaceholder("my-pool")).toBeVisible()+ })++ test("form has all required fields", async ({ page }) => {+ await mockAuth(page)+ await mockNamespacesApi(page)+ await mockPoolsApi(page)++ await page.goto("/pools/new")++ // Name input+ await expect(page.getByPlaceholder("my-pool")).toBeVisible()+ // Numeric inputs (vCPU, replicas)+ await expect(page.getByRole("spinbutton").first()).toBeVisible()++ // Services section has an "Add service" button+ await expect(page.getByRole("button", { name: "Add service" })).toBeVisible()+ })++})++test.describe("Pool duplication", () => {+ // Reproduces the bug: clicking "Duplicate" for a pool in the list should+ // open the New pool form pre-filled with that pool's existing config. The+ // list row only carries summary fields (name, replicas, phase,+ // availableCount), so PoolNew's `source.cpu ?? DEFAULTS.cpu` (and ram /+ // ociImage / services) all fall through to DEFAULTS — the form shows a+ // fresh "new pool" with default data instead of the source's config.+ test("duplicate from the list pre-fills the form with the source pool's config", async ({+ page,+ }) => {+ await mockAuth(page)+ await mockNamespacesApi(page)++ // Source pool with a NON-default resource spec (defaults are cpu 4,+ // ram 4Gi, the ECR image, replicas 1, no services).+ const sourcePool = {+ metadata: { name: "demo-pool", namespace: "my-workspace" },+ spec: {+ replicas: 3,+ template: {+ containerDiskImage: "custom-image:v1",+ cpuCores: 8,+ memory: "16Gi",+ },+ services: [{ name: "api", targetPort: 8080, protocol: "TCP" }],+ },+ status: { phase: "Ready", totalCount: 3, availableCount: 3, claimedCount: 0 },+ }++ // listPools() iterates the user's namespaces and lists pools in each.+ await page.route(+ "**/api/k8s/apis/cua.ai/v1/namespaces/*/osgymworkspacepools",+ async (route) => {+ if (route.request().method() !== "GET") return route.continue()+ const ns = route.request().url().split("/namespaces/")[1].split("/")[0]+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({ items: ns === "my-workspace" ? [sourcePool] : [] }),+ })+ },+ )++ // Single-pool GET — where a correct duplicate flow would read the full+ // spec. Registered after the list route so it wins for this exact path.+ await page.route(+ "**/api/k8s/apis/cua.ai/v1/namespaces/my-workspace/osgymworkspacepools/demo-pool",+ async (route) => {+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify(sourcePool),+ })+ },+ )++ await page.goto("/pools")++ // Select the pool's row and click Duplicate.+ const row = page.getByRole("row").filter({ hasText: "demo-pool" })+ await expect(row).toBeVisible()+ await row.getByRole("checkbox").check()+ await page.getByRole("button", { name: "Duplicate" }).click()++ // We land on the duplicate form...+ await expect(+ page.getByRole("heading", { name: "Duplicate pool" }),+ ).toBeVisible()+ // ...with the name seeded from the source (this part already works).+ await expect(page.getByRole("textbox", { name: "Name" })).toHaveValue(+ "demo-pool-copy",+ )++ // The bug: these reflect DEFAULTS instead of the source pool's config.+ await expect(+ page.getByRole("spinbutton", { name: "vCPU cores" }),+ ).toHaveValue("8")+ await expect(page.getByRole("textbox", { name: "RAM" })).toHaveValue("16Gi")+ await expect(page.getByRole("textbox", { name: "OCI image" })).toHaveValue(+ "custom-image:v1",+ )+ })+})++test.describe("Pool detail with claims", () => {+ test("pool detail page shows claims section", async ({ page }) => {+ await mockAuth(page)+ await mockNamespacesApi(page)+ await mockPoolsApi(page)+ await mockClaimsApi(page)++ // Mock the getPool endpoint for a specific pool+ await page.route(+ "**/api/k8s/apis/cua.ai/v1/namespaces/my-workspace/osgymworkspacepools/demo-pool",+ async (route) => {+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({+ metadata: { name: "demo-pool", namespace: "my-workspace" },+ spec: {+ replicas: 2,+ template: {+ containerDiskImage: "test-image:latest",+ cpuCores: 4,+ memory: "4Gi",+ },+ services: [],+ },+ status: {+ phase: "Ready",+ totalCount: 2,+ availableCount: 1,+ claimedCount: 1,+ },+ }),+ })+ },+ )++ await page.goto("/pools/my-workspace/demo-pool")++ // The pool name should be shown+ await expect(page.getByRole("heading", { name: "demo-pool" })).toBeVisible()++ // The Claims section should be present+ await expect(page.getByRole("heading", { name: "Claims" })).toBeVisible()++ // The "Create claim" button should be visible+ await expect(+ page.getByRole("button", { name: "Create claim" }),+ ).toBeVisible()++ // The existing mock claim should be listed+ await expect(page.getByText("claim-abc123")).toBeVisible()+ await expect(page.getByText("Bound")).toBeVisible()+ })+})diff --git a/libs/fleet/e2e/user-keys.spec.ts b/libs/fleet/e2e/user-keys.spec.tsnew file mode 100644index 0000000000..d917302c46--- /dev/null+++ b/libs/fleet/e2e/user-keys.spec.ts@@ -0,0 +1,104 @@+import { test, expect } from "@playwright/test"+import {+ mockAuth,+ mockNamespacesApi,+ mockUserKeysApi,+} from "./fixtures/mock-api"++test.describe("User API keys", () => {+ test.beforeEach(async ({ page }) => {+ await mockAuth(page)+ await mockNamespacesApi(page)+ await mockUserKeysApi(page)+ })++ test("renders the API keys page with existing keys", async ({ page }) => {+ await page.goto("/user-keys")++ // The page should have the "Your API keys" table header+ await expect(+ page.getByRole("heading", { name: "Your API keys" }),+ ).toBeVisible()++ // The existing mock key should be listed+ await expect(page.getByText("my-key")).toBeVisible()+ await expect(page.getByText("sa-testuser-mykey")).toBeVisible()+ })++ test("shows the create key form", async ({ page }) => {+ await page.goto("/user-keys")++ // Wait for the page heading to confirm the route rendered+ await expect(+ page.getByRole("heading", { name: /api keys/i }).first(),+ ).toBeVisible({ timeout: 10000 })++ // The create key button should be visible+ await expect(+ page.getByRole("button", { name: /create/i }).first(),+ ).toBeVisible()+ })++ test("can create a new API key and see credentials", async ({ page }) => {+ await page.goto("/user-keys")++ // Wait for page to load+ await expect(+ page.getByRole("heading", { name: /api keys/i }).first(),+ ).toBeVisible({ timeout: 10000 })++ // Fill in the name — find the first text input on the page+ const nameInput = page.getByRole("textbox").first()+ await nameInput.fill("test-key")++ // Click create+ await page.getByRole("button", { name: "Create key" }).click()++ // The credentials modal should appear with client_id and client_secret+ await expect(page.getByText("API key created")).toBeVisible()+ await expect(page.getByText("sa-testuser-test-key").first()).toBeVisible()+ await expect(+ page.getByText("fake-client-secret-shown-once").first(),+ ).toBeVisible()++ await expect(page.getByText("Token URL")).not.toBeVisible()+ await expect(page.getByText("Usage")).not.toBeVisible()++ // Dismiss the modal+ await page+ .getByRole("button", { name: "I have copied the credentials" })+ .click()+ })++ test("has revoke button for each key", async ({ page }) => {+ await page.goto("/user-keys")++ // Each key should have a Revoke button (multiple keys = multiple buttons)+ await expect(page.getByRole("button", { name: "Revoke" }).first()).toBeVisible()+ })++ test("shows revoke confirmation modal", async ({ page }) => {+ await page.goto("/user-keys")++ await page.getByRole("button", { name: "Revoke" }).first().click()++ // Confirmation modal should appear+ await expect(page.getByText("Revoke API key?")).toBeVisible()+ await expect(+ page.getByText(/this action cannot be undone/i),+ ).toBeVisible()++ // Should have Cancel and Revoke buttons in the modal+ await expect(page.getByRole("button", { name: "Cancel" })).toBeVisible()+ })++ test("shows scope field with namespace options", async ({ page }) => {+ await page.goto("/user-keys")++ // The scope multiselect should mention namespaces+ await expect(page.getByText("Scope (optional)")).toBeVisible()+ await expect(+ page.getByText(/restrict this key to specific namespaces/i),+ ).toBeVisible()+ })+})diff --git a/libs/fleet/index.html b/libs/fleet/index.htmlnew file mode 100644index 0000000000..9e001c591f--- /dev/null+++ b/libs/fleet/index.html@@ -0,0 +1,16 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Pools</title>+ </head>+ <body>+ <!-- Runtime config injected by nginx envsubst (see nginx.conf+ /config.js block). Loaded before the bundle so AuthProvider can+ read window.__CYCLOPS_CS_CFG__ on first render. -->+ <script src="/config.js"></script>+ <div id="root"></div>+ <script type="module" src="/src/main.tsx"></script>+ </body>+</html>diff --git a/libs/fleet/js-sdk/LICENSE b/libs/fleet/js-sdk/LICENSEnew file mode 100644index 0000000000..5ca2270404--- /dev/null+++ b/libs/fleet/js-sdk/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Cua++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/libs/fleet/js-sdk/README.md b/libs/fleet/js-sdk/README.mdnew file mode 100644index 0000000000..1dc8892e34--- /dev/null+++ b/libs/fleet/js-sdk/README.md@@ -0,0 +1,90 @@+# Cyclops JavaScript client++`@trycua/cyclops` is the OpenAPI-generated JavaScript and TypeScript client for+Cyclops. It supports ESM applications on Node.js 18 and newer, where the Fetch+API is available as `globalThis.fetch`.++```sh+npm install @trycua/cyclops+```++```ts+import { CyclopsClient } from "@trycua/cyclops"++const client = new CyclopsClient({+ clientId: process.env.CUA_CLIENT_ID!,+ clientSecret: process.env.CUA_CLIENT_SECRET!,+})++const response = await client.keys.keysList()+console.log(response.data.keys)+```++Keep `clientSecret` in server-side environment variables or a secret manager.+Never expose client credentials in browser bundles or client-side code.++## Node.js and Fetch API support++The generated client uses the standard Fetch API. Node.js 18+ supplies it+through `globalThis.fetch`, so the SDK has no runtime fetch dependency. A clear+error is thrown before a request when fetch is unavailable.++Use the `fetch` option to inject a compatible implementation for older runtimes,+polyfills, test doubles, proxies, tracing, or other custom networking behavior.+The same function handles both OAuth token exchange and generated API requests.++```ts+const client = new CyclopsClient({+ clientId: process.env.CUA_CLIENT_ID!,+ clientSecret: process.env.CUA_CLIENT_SECRET!,+ fetch: customFetch,+})+```++`securityWorker` is not a browser API. It is a callback generated by+`swagger-typescript-api` that adds authentication parameters before secure API+requests. `CyclopsClient` configures that callback to obtain an OAuth2 token and+add the bearer authorization header.++## Agent examples++- [`examples/pi-agent.mjs`](examples/pi-agent.mjs) claims a sandbox and+ exposes its computer-server and cua-driver MCP tools to a Pi agent.+- [`examples/claude-agent-sdk.mjs`](examples/claude-agent-sdk.mjs) runs the+ same authenticated sandbox and MCP lifecycle with the official Claude Agent+ SDK. After building the client and installing the dependencies documented at+ the top of the file, run it with `CUA_CLIENT_ID`, `CUA_CLIENT_SECRET`,+ `CUA_POOL`, and `ANTHROPIC_API_KEY` set.++## Generate the client++Run these commands from `cyclops-cs/js-sdk`:++```sh+npm ci+npm run generate+npm run generate:check+```++`npm run generate` reads `../backend/docs/swagger.json`, writes+`src/generated/cyclops-cs-backend.ts`, and applies the deterministic runtime+fetch guard. `npm run generate:check` regenerates the file and fails if the+checked-in output differs.++## Generated and handwritten boundary++- `src/generated/cyclops-cs-backend.ts` contains all endpoint methods and DTOs+ represented by the checked-in OpenAPI specification.+- `src/token.ts` contains only the OAuth2 client-credentials token provider.+- `src/index.ts` exports the generated API and configures its generated+ `securityWorker` callback with the token provider. It does not implement+ endpoint methods or DTOs.++The Python examples also perform typed `OSGymSandboxClaim` lifecycle operations+and build service-proxy workflows. Those typed claim resources are not modeled+by the current OpenAPI specification. This package therefore does not expose+handwritten claim, wait, release, service URL, or MCP helpers. The generated+spec currently includes generic `/api/k8s/{path}` and+`/api/svc/{namespace}/{service}/{path}` GET operations only; callers needing a+richer claim/service API must wait for those operations and schemas to be added+to the authoritative specification.diff --git a/libs/fleet/js-sdk/examples/claude-agent-sdk.mjs b/libs/fleet/js-sdk/examples/claude-agent-sdk.mjsnew file mode 100644index 0000000000..54f9063b65--- /dev/null+++ b/libs/fleet/js-sdk/examples/claude-agent-sdk.mjs@@ -0,0 +1,441 @@+/**+ * Provision a CUA sandbox and operate it with the official Claude Agent SDK.+ *+ * This example claims a sandbox from an existing pool configured with the+ * computer-server and cua-driver services described by CUA_SERVICES. It+ * preflights both Streamable HTTP MCP endpoints, discovers their tools, then+ * gives only those remote MCP tools to Claude.+ *+ * From cyclops-cs/js-sdk:+ * npm run build+ * npm install --no-save --package-lock=false \+ * @anthropic-ai/claude-agent-sdk @modelcontextprotocol/sdk+ * CUA_CLIENT_ID=ukey-... CUA_CLIENT_SECRET=... CUA_POOL=my-pool \+ * ANTHROPIC_API_KEY=... node examples/claude-agent-sdk.mjs+ *+ * Optional: CUA_BASE_URL, CUA_TOKEN_URL, CUA_CLAIM_NAME, CLAUDE_MODEL,+ * CLAUDE_MAX_TURNS, CLAUDE_MAX_BUDGET_USD, CUA_BIND_TIMEOUT_MS, and+ * CUA_READY_TIMEOUT_MS.+ *+ * Use a per-user Cyclops key because Kubernetes claim operations require the+ * user's Kubernetes identity. The Claude Agent SDK requires Node.js 18+.+ */++import { randomUUID } from "node:crypto"++import { query } from "@anthropic-ai/claude-agent-sdk"+// The MCP SDK calls this class Client; aliasing it makes the session role clear.+import { Client as ClientSession } from "@modelcontextprotocol/sdk/client"+import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"++import { ContentType, CyclopsClient, DEFAULT_BASE_URL } from "../dist/index.js"++const CUA_SERVICES = [+ {+ name: "computer-server",+ service_suffix: "server",+ guest_port: 8000,+ mcp_path: "/mcp",+ health_path: "/status",+ },+ {+ name: "cua-driver",+ service_suffix: "mcp",+ guest_port: 3000,+ mcp_path: "/mcp",+ health_path: "/healthz",+ },+]++const CLAIM_GROUP = "osgym.cua.ai"+const CLAIM_VERSION = "v1alpha1"+const CLAIM_PLURAL = "osgymsandboxclaims"+const POLL_INTERVAL_MS = 2_000+const DEFAULT_BIND_TIMEOUT_MS = 10 * 60_000+const DEFAULT_READY_TIMEOUT_MS = 5 * 60_000+const DEFAULT_MAX_TURNS = 20+const DEFAULT_MAX_BUDGET_USD = 5+const DEFAULT_TASK =+ "Open Firefox and navigate to https://example.com. Take a screenshot and " ++ "report the page title. Do not click links, enter data, download files, or " ++ "change browser or system settings."++function section(title) {+ console.log(`\n=== ${title} ===`)+}++function info(message) {+ console.log(` ${message}`)+}++function requiredEnv(name) {+ const value = process.env[name]+ if (!value) {+ throw new Error(`Missing required environment variable: ${name}`)+ }+ return value+}++function envNumber(name, fallback) {+ const raw = process.env[name]+ if (!raw) return fallback+ const value = Number(raw)+ if (!Number.isFinite(value) || value <= 0) {+ throw new Error(`${name} must be a positive number`)+ }+ return value+}++function sleep(milliseconds) {+ return new Promise((resolve) => setTimeout(resolve, milliseconds))+}++function trimSlashes(path) {+ return path.replace(/^\/+|\/+$/g, "")+}++function claimsPath(pool, claimName) {+ const collection = `apis/${CLAIM_GROUP}/${CLAIM_VERSION}/namespaces/${pool}/${CLAIM_PLURAL}`+ return claimName ? `${collection}/${claimName}` : collection+}++function serviceName(sandbox, service) {+ return `${sandbox}-${service.service_suffix}`+}++function serviceUrl(baseUrl, pool, sandbox, service, path) {+ const proxyPath = `/api/svc/${pool}/${serviceName(sandbox, service)}/${trimSlashes(path)}`+ return new URL(proxyPath, `${baseUrl.replace(/\/$/, "")}/`).toString()+}++async function describeError(error) {+ if (error instanceof Response) {+ let body = ""+ try {+ const parsedError = "error" in error ? error.error : undefined+ body = parsedError+ ? JSON.stringify(parsedError)+ : await error.clone().text()+ } catch {+ // Status information remains useful when the response body is unavailable.+ }+ return `${error.status} ${error.statusText}${body ? `: ${body}` : ""}`+ }+ return error instanceof Error ? error.message : String(error)+}++async function createClaim(client, pool, claimName) {+ // The generated GET helper does not model claim creation, but the generated+ // client's public request method supports the same authenticated proxy route.+ await client.request({+ path: `/api/k8s/${claimsPath(pool)}`,+ method: "POST",+ secure: true,+ type: ContentType.Json,+ format: "json",+ body: {+ apiVersion: `${CLAIM_GROUP}/${CLAIM_VERSION}`,+ kind: "OSGymSandboxClaim",+ metadata: { name: claimName },+ spec: {+ sandboxTemplateRef: { name: `${pool}-template` },+ bindDeadline: 600,+ },+ },+ })+}++async function waitForBoundSandbox(client, pool, claimName, timeoutMs) {+ const deadline = Date.now() + timeoutMs+ let previousPhase++ while (Date.now() < deadline) {+ const response = await client.k8S.getK8S(claimsPath(pool, claimName), {+ format: "json",+ })+ const status = response.data.status ?? {}+ const phase = status.phase ?? "Pending"+ const sandbox = status.sandbox?.name++ if (phase !== previousPhase) {+ info(`claim ${claimName}: ${phase}`)+ previousPhase = phase+ }+ if (phase === "Bound" && sandbox) return sandbox+ if (phase === "Failed") {+ throw new Error(`Claim ${claimName} failed: ${JSON.stringify(status)}`)+ }+ await sleep(POLL_INTERVAL_MS)+ }++ throw new Error(`Timed out waiting for claim ${claimName} to bind`)+}++async function waitForService(client, pool, sandbox, service, timeoutMs) {+ const deadline = Date.now() + timeoutMs+ const name = serviceName(sandbox, service)+ const path = trimSlashes(service.health_path)+ let lastError = "not ready"++ while (Date.now() < deadline) {+ try {+ await client.svc.getSvc(pool, name, path, { format: "text" })+ info(+ `${service.name} ready at ${name} ` ++ `(guest port ${service.guest_port})`,+ )+ return+ } catch (error) {+ lastError = await describeError(error)+ await sleep(POLL_INTERVAL_MS)+ }+ }++ throw new Error(`${service.name} did not become ready: ${lastError}`)+}++async function releaseClaim(client, pool, claimName) {+ await client.request({+ path: `/api/k8s/${claimsPath(pool, claimName)}`,+ method: "DELETE",+ secure: true,+ })+}++async function connectMcpServer({+ baseUrl,+ pool,+ sandbox,+ service,+ authHeaders,+}) {+ const url = serviceUrl(baseUrl, pool, sandbox, service, service.mcp_path)+ const transport = new StreamableHTTPClientTransport(new URL(url), {+ requestInit: { headers: authHeaders },+ })+ const session = new ClientSession({+ name: `cyclops-claude-${service.name}`,+ version: "1.0.0",+ })++ await session.connect(transport)+ const { tools } = await session.listTools()+ info(`${service.name}: connected to ${url} (${tools.length} tools)`)++ return { service, session, tools, url }+}++function normalizedServerName(name) {+ return name.replace(/[^a-zA-Z0-9_-]/g, "_")+}++function claudeToolName(serverName, toolName) {+ return `mcp__${normalizedServerName(serverName)}__${toolName}`+}++function buildClaudeMcpConfig(connections, authHeaders) {+ return Object.fromEntries(+ connections.map(({ service, tools, url }) => [+ service.name,+ {+ type: "http",+ url,+ headers: authHeaders,+ tools: tools.map((tool) => ({+ name: tool.name,+ permission_policy: "always_allow",+ })),+ timeout: 120_000,+ alwaysLoad: true,+ },+ ]),+ )+}++function discoveredClaudeTools(connections) {+ return connections.flatMap(({ service, tools }) =>+ tools.map((tool) => claudeToolName(service.name, tool.name)),+ )+}++function logAssistantMessage(message) {+ for (const block of message.message.content) {+ if (block.type === "text") {+ for (const line of block.text.trim().split("\n")) info(`Claude: ${line}`)+ } else if (block.type === "tool_use") {+ info(`Claude calling ${block.name}`)+ }+ }+}++async function main() {+ const pool = requiredEnv("CUA_POOL")+ const baseUrl = process.env.CUA_BASE_URL ?? DEFAULT_BASE_URL+ const claimName =+ process.env.CUA_CLAIM_NAME ?? `claude-agent-${randomUUID().slice(0, 8)}`+ const bindTimeoutMs = envNumber(+ "CUA_BIND_TIMEOUT_MS",+ DEFAULT_BIND_TIMEOUT_MS,+ )+ const readyTimeoutMs = envNumber(+ "CUA_READY_TIMEOUT_MS",+ DEFAULT_READY_TIMEOUT_MS,+ )+ const maxTurns = envNumber("CLAUDE_MAX_TURNS", DEFAULT_MAX_TURNS)+ const maxBudgetUsd = envNumber(+ "CLAUDE_MAX_BUDGET_USD",+ DEFAULT_MAX_BUDGET_USD,+ )+ const task = process.argv.slice(2).join(" ") || DEFAULT_TASK++ requiredEnv("ANTHROPIC_API_KEY")++ let client+ let claimCreated = false+ let claudeQuery+ const mcpConnections = []++ try {+ section("1. CUA Authentication")+ client = await CyclopsClient.fromKey({+ clientId: requiredEnv("CUA_CLIENT_ID"),+ clientSecret: requiredEnv("CUA_CLIENT_SECRET"),+ baseUrl,+ tokenUrl: process.env.CUA_TOKEN_URL,+ })+ info("authenticated with Cyclops client credentials")++ section("2. Provision a CUA Sandbox")+ info(`pool: ${pool}`)+ for (const service of CUA_SERVICES) {+ info(+ `${service.name}: ${service.service_suffix} -> guest port ` ++ `${service.guest_port}, MCP ${service.mcp_path}`,+ )+ }+ await createClaim(client, pool, claimName)+ claimCreated = true+ info(`claim created: ${claimName}`)+ const sandbox = await waitForBoundSandbox(+ client,+ pool,+ claimName,+ bindTimeoutMs,+ )+ info(`sandbox bound: ${sandbox}`)++ for (const service of CUA_SERVICES) {+ await waitForService(client, pool, sandbox, service, readyTimeoutMs)+ }++ const authHeaders = {+ Authorization: `Bearer ${await client.tokenProvider.getToken()}`,+ }++ section("3. Connect and Discover MCP Tools")+ for (const service of CUA_SERVICES) {+ mcpConnections.push(+ await connectMcpServer({+ baseUrl,+ pool,+ sandbox,+ service,+ authHeaders,+ }),+ )+ }++ const mcpServers = buildClaudeMcpConfig(mcpConnections, authHeaders)+ const allowedTools = discoveredClaudeTools(mcpConnections)+ info(`discovered ${allowedTools.length} Claude MCP tools`)+ for (const tool of allowedTools) info(tool)++ section("4. Run the Claude Agent Task")+ info(`task: ${task}`)++ claudeQuery = query({+ prompt: task,+ options: {+ allowedTools,+ tools: [],+ mcpServers,+ strictMcpConfig: true,+ settingSources: [],+ persistSession: false,+ maxTurns,+ maxBudgetUsd,+ model: process.env.CLAUDE_MODEL,+ systemPrompt:+ "You operate one CUA desktop through two remote MCP servers: " ++ "computer-server and cua-driver. Use only the provided MCP tools. " ++ "Inspect the desktop before acting, take one action at a time, and " ++ "verify each result. Do not enter credentials, submit forms, make " ++ "purchases, download files, or change system settings unless the " ++ "user explicitly asks.",+ stderr: (data) => console.error(`[claude-agent-sdk] ${data.trimEnd()}`),+ },+ })++ let finalResult+ for await (const message of claudeQuery) {+ if (message.type === "assistant") {+ logAssistantMessage(message)+ } else if (message.type === "result") {+ if (message.subtype === "success") {+ finalResult = message.result+ info(+ `completed in ${message.num_turns} turns ` ++ `($${message.total_cost_usd.toFixed(4)})`,+ )+ } else {+ throw new Error(+ `Claude Agent SDK stopped with ${message.subtype}: ` ++ `${message.errors.join("; ")}`,+ )+ }+ }+ }++ if (!finalResult) {+ throw new Error("Claude Agent SDK completed without a result message")+ }+ console.log(`\nAgent result:\n${finalResult}`)+ } finally {+ section("5. Cleanup")++ if (claudeQuery) {+ claudeQuery.close()+ info("Claude Agent SDK query closed")+ }++ for (const connection of mcpConnections.reverse()) {+ try {+ await connection.session.close()+ info(`${connection.service.name} MCP preflight session closed`)+ } catch (error) {+ info(+ `${connection.service.name} MCP cleanup failed: ` ++ `${await describeError(error)}`,+ )+ }+ }++ if (client && claimCreated) {+ try {+ await releaseClaim(client, pool, claimName)+ info(`claim released: ${claimName}`)+ } catch (error) {+ info(`claim cleanup failed: ${await describeError(error)}`)+ }+ }+ }+}++try {+ await main()+} catch (error) {+ console.error(+ `\nclaude-agent-sdk example failed: ${await describeError(error)}`,+ )+ process.exitCode = 1+}diff --git a/libs/fleet/js-sdk/examples/pi-agent.mjs b/libs/fleet/js-sdk/examples/pi-agent.mjsnew file mode 100644index 0000000000..25457340b4--- /dev/null+++ b/libs/fleet/js-sdk/examples/pi-agent.mjs@@ -0,0 +1,470 @@+/**+ * Provision a CUA sandbox and let a Pi agent operate it through both MCP servers.+ *+ * This example claims a sandbox from an existing pool configured with the+ * computer-server and cua-driver services described by CUA_SERVICES.+ *+ * From cyclops-cs/js-sdk:+ * npm run build+ * npm install --no-save --package-lock=false \+ * @earendil-works/pi-coding-agent @modelcontextprotocol/sdk typebox+ * CUA_CLIENT_ID=ukey-... CUA_CLIENT_SECRET=... CUA_POOL=my-pool \+ * node examples/pi-agent.mjs+ *+ * Pi requires Node.js 22.19 or newer and a configured model/API key. Use a+ * per-user Cyclops key because Kubernetes pool and claim operations require the+ * user's Kubernetes identity.+ */++import { randomUUID } from "node:crypto"++import {+ createAgentSession,+ defineTool,+ SessionManager,+} from "@earendil-works/pi-coding-agent"+// The MCP SDK calls this class Client; aliasing it makes the session role clear.+import { Client as ClientSession } from "@modelcontextprotocol/sdk/client"+import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"+import { Type } from "typebox"++import { ContentType, CyclopsClient, DEFAULT_BASE_URL } from "../dist/index.js"++const CUA_SERVICES = [+ {+ name: "computer-server",+ service_suffix: "server",+ guest_port: 8000,+ mcp_path: "/mcp",+ health_path: "/status",+ },+ {+ name: "cua-driver",+ service_suffix: "mcp",+ guest_port: 3000,+ mcp_path: "/mcp",+ health_path: "/healthz",+ },+]++const CLAIM_GROUP = "osgym.cua.ai"+const CLAIM_VERSION = "v1alpha1"+const CLAIM_PLURAL = "osgymsandboxclaims"+const POLL_INTERVAL_MS = 2_000+const DEFAULT_BIND_TIMEOUT_MS = 10 * 60_000+const DEFAULT_READY_TIMEOUT_MS = 5 * 60_000+const DEFAULT_TASK =+ "Open Firefox and navigate to https://news.ycombinator.com. " ++ "Take a screenshot, then click on the top story."++function section(title) {+ console.log(`\n=== ${title} ===`)+}++function info(message) {+ console.log(` ${message}`)+}++function requiredEnv(name) {+ const value = process.env[name]+ if (!value) {+ throw new Error(`Missing required environment variable: ${name}`)+ }+ return value+}++function envNumber(name, fallback) {+ const raw = process.env[name]+ if (!raw) return fallback+ const value = Number(raw)+ if (!Number.isFinite(value) || value <= 0) {+ throw new Error(`${name} must be a positive number`)+ }+ return value+}++function sleep(milliseconds) {+ return new Promise((resolve) => setTimeout(resolve, milliseconds))+}++function trimSlashes(path) {+ return path.replace(/^\/+|\/+$/g, "")+}++function claimsPath(pool, claimName) {+ const collection = `apis/${CLAIM_GROUP}/${CLAIM_VERSION}/namespaces/${pool}/${CLAIM_PLURAL}`+ return claimName ? `${collection}/${claimName}` : collection+}++function serviceName(sandbox, service) {+ return `${sandbox}-${service.service_suffix}`+}++function serviceUrl(baseUrl, pool, sandbox, service, path) {+ const proxyPath = `/api/svc/${pool}/${serviceName(sandbox, service)}/${trimSlashes(path)}`+ return new URL(proxyPath, `${baseUrl.replace(/\/$/, "")}/`).toString()+}++async function describeError(error) {+ if (error instanceof Response) {+ let body = ""+ try {+ body = error.error+ ? JSON.stringify(error.error)+ : await error.clone().text()+ } catch {+ // Status information remains useful when the response body is unavailable.+ }+ return `${error.status} ${error.statusText}${body ? `: ${body}` : ""}`+ }+ return error instanceof Error ? error.message : String(error)+}++async function createClaim(client, pool, claimName) {+ await client.request({+ path: `/api/k8s/${claimsPath(pool)}`,+ method: "POST",+ secure: true,+ type: ContentType.Json,+ format: "json",+ body: {+ apiVersion: `${CLAIM_GROUP}/${CLAIM_VERSION}`,+ kind: "OSGymSandboxClaim",+ metadata: { name: claimName },+ spec: {+ sandboxTemplateRef: { name: `${pool}-template` },+ bindDeadline: 600,+ },+ },+ })+}++async function waitForBoundSandbox(client, pool, claimName, timeoutMs) {+ const deadline = Date.now() + timeoutMs+ let previousPhase++ while (Date.now() < deadline) {+ const response = await client.k8S.getK8S(claimsPath(pool, claimName), {+ format: "json",+ })+ const status = response.data.status ?? {}+ const phase = status.phase ?? "Pending"+ const sandbox = status.sandbox?.name++ if (phase !== previousPhase) {+ info(`claim ${claimName}: ${phase}`)+ previousPhase = phase+ }+ if (phase === "Bound" && sandbox) return sandbox+ if (phase === "Failed") {+ throw new Error(`Claim ${claimName} failed: ${JSON.stringify(status)}`)+ }+ await sleep(POLL_INTERVAL_MS)+ }++ throw new Error(`Timed out waiting for claim ${claimName} to bind`)+}++async function waitForService(client, pool, sandbox, service, timeoutMs) {+ const deadline = Date.now() + timeoutMs+ const name = serviceName(sandbox, service)+ const path = trimSlashes(service.health_path)+ let lastError = "not ready"++ while (Date.now() < deadline) {+ try {+ await client.svc.getSvc(pool, name, path, { format: "text" })+ info(+ `${service.name} ready at ${name} ` ++ `(guest port ${service.guest_port})`,+ )+ return+ } catch (error) {+ lastError = await describeError(error)+ await sleep(POLL_INTERVAL_MS)+ }+ }++ throw new Error(`${service.name} did not become ready: ${lastError}`)+}++async function releaseClaim(client, pool, claimName) {+ await client.request({+ path: `/api/k8s/${claimsPath(pool, claimName)}`,+ method: "DELETE",+ secure: true,+ })+}++async function connectMcpServer({+ baseUrl,+ pool,+ sandbox,+ service,+ authHeaders,+}) {+ const url = serviceUrl(baseUrl, pool, sandbox, service, service.mcp_path)+ const transport = new StreamableHTTPClientTransport(new URL(url), {+ requestInit: { headers: authHeaders },+ })+ const session = new ClientSession({+ name: `cyclops-pi-${service.name}`,+ version: "1.0.0",+ })++ await session.connect(transport)+ const { tools } = await session.listTools()+ info(`${service.name}: connected to ${url} (${tools.length} tools)`)++ return { service, session, tools }+}++function safeToolName(name) {+ return name.replace(/[^a-zA-Z0-9_-]/g, "_")+}++function toPiContent(content = []) {+ return content.map((item) => {+ if (item.type === "text") {+ return { type: "text", text: item.text }+ }+ if (item.type === "image") {+ return { type: "image", data: item.data, mimeType: item.mimeType }+ }+ return { type: "text", text: JSON.stringify(item) }+ })+}++function registerPiTools(connections) {+ const names = new Set()++ return connections.flatMap(({ service, session, tools }) =>+ tools.map((tool) => {+ const name = `${safeToolName(service.name)}__${safeToolName(tool.name)}`+ if (names.has(name)) throw new Error(`Duplicate Pi tool name: ${name}`)+ names.add(name)++ return defineTool({+ name,+ label: `${service.name}: ${tool.name}`,+ description:+ tool.description ??+ `${tool.name} from the ${service.name} MCP server`,+ parameters: Type.Unsafe(+ tool.inputSchema ?? { type: "object", properties: {} },+ ),+ execute: async (_toolCallId, parameters, signal) => {+ try {+ const result = await session.callTool(+ { name: tool.name, arguments: parameters },+ undefined,+ signal ? { signal } : undefined,+ )+ return {+ content: toPiContent(result.content),+ details: {+ server: service.name,+ tool: tool.name,+ structuredContent: result.structuredContent,+ },+ isError: result.isError === true,+ }+ } catch (error) {+ return {+ content: [+ {+ type: "text",+ text:+ `${service.name}/${tool.name} failed: ` ++ `${await describeError(error)}`,+ },+ ],+ details: { server: service.name, tool: tool.name },+ isError: true,+ }+ }+ },+ })+ }),+ )+}++async function takeInitialScreenshot(connections) {+ const computerServer = connections.find(+ ({ service }) => service.name === "computer-server",+ )+ const screenshotTool = computerServer?.tools.find(+ (tool) => tool.name === "screenshot",+ )+ if (!computerServer || !screenshotTool) {+ throw new Error("computer-server did not advertise a screenshot tool")+ }++ const result = await computerServer.session.callTool({+ name: screenshotTool.name,+ arguments: {},+ })+ if (result.isError) {+ throw new Error(+ `Initial screenshot failed: ${JSON.stringify(result.content)}`,+ )+ }++ const images = toPiContent(result.content).filter(+ (item) => item.type === "image",+ )+ info(`initial screenshot captured (${images.length} image attachment)`)+ return images+}++function finalAssistantText(session) {+ const message = session.state.messages.findLast(+ (candidate) => candidate.role === "assistant",+ )+ return (+ message?.content+ .filter((part) => part.type === "text")+ .map((part) => part.text)+ .join("") ?? ""+ )+}++async function main() {+ const pool = requiredEnv("CUA_POOL")+ const baseUrl = process.env.CUA_BASE_URL ?? DEFAULT_BASE_URL+ const claimName =+ process.env.CUA_CLAIM_NAME ?? `pi-agent-${randomUUID().slice(0, 8)}`+ const bindTimeoutMs = envNumber(+ "CUA_BIND_TIMEOUT_MS",+ DEFAULT_BIND_TIMEOUT_MS,+ )+ const readyTimeoutMs = envNumber(+ "CUA_READY_TIMEOUT_MS",+ DEFAULT_READY_TIMEOUT_MS,+ )+ const task = process.argv.slice(2).join(" ") || DEFAULT_TASK++ let client+ let claimCreated = false+ let piSession+ const mcpConnections = []++ try {+ section("1. CUA Authentication")+ client = await CyclopsClient.fromKey({+ clientId: requiredEnv("CUA_CLIENT_ID"),+ clientSecret: requiredEnv("CUA_CLIENT_SECRET"),+ baseUrl,+ tokenUrl: process.env.CUA_TOKEN_URL,+ })+ info("authenticated with Cyclops client credentials")++ section("2. Provision a CUA Sandbox")+ info(`pool: ${pool}`)+ for (const service of CUA_SERVICES) {+ info(+ `${service.name}: ${service.service_suffix} -> guest port ` ++ `${service.guest_port}, MCP ${service.mcp_path}`,+ )+ }+ await createClaim(client, pool, claimName)+ claimCreated = true+ info(`claim created: ${claimName}`)+ const sandbox = await waitForBoundSandbox(+ client,+ pool,+ claimName,+ bindTimeoutMs,+ )+ info(`sandbox bound: ${sandbox}`)++ for (const service of CUA_SERVICES) {+ await waitForService(client, pool, sandbox, service, readyTimeoutMs)+ }++ const authHeaders = {+ Authorization: `Bearer ${await client.tokenProvider.getToken()}`,+ }++ section("3. Connect to MCP Servers")+ for (const service of CUA_SERVICES) {+ mcpConnections.push(+ await connectMcpServer({+ baseUrl,+ pool,+ sandbox,+ service,+ authHeaders,+ }),+ )+ }++ section("4. Register Tools with Pi")+ const customTools = registerPiTools(mcpConnections)+ info(`registered ${customTools.length} namespaced MCP tools`)+ for (const tool of customTools) info(tool.name)++ section("5. Run the Agent Task")+ const initialImages = await takeInitialScreenshot(mcpConnections)+ info(`task: ${task}`)++ const createdSession = await createAgentSession({+ tools: customTools.map((tool) => tool.name),+ customTools,+ sessionManager: SessionManager.inMemory(),+ })+ piSession = createdSession.session+ piSession.subscribe((event) => {+ if (event.type === "tool_execution_start") {+ info(`Pi calling ${event.toolName}`)+ }+ })++ await piSession.prompt(+ "You operate one CUA desktop through two MCP servers. Tool names are " ++ "namespaced by server (for example computer-server__screenshot and " ++ "cua-driver__click). Inspect the screenshot, take one action at a " ++ `time, and verify the result after each action.\n\nTask: ${task}`,+ { images: initialImages },+ )++ const result = finalAssistantText(piSession)+ if (!result) throw new Error("Pi completed without a text result")+ console.log(`\nAgent result:\n${result}`)+ } finally {+ section("6. Cleanup")++ if (piSession) {+ piSession.dispose()+ info("Pi session disposed")+ }++ for (const connection of mcpConnections.reverse()) {+ try {+ await connection.session.close()+ info(`${connection.service.name} MCP session closed`)+ } catch (error) {+ info(+ `${connection.service.name} MCP cleanup failed: ` ++ `${await describeError(error)}`,+ )+ }+ }++ if (client && claimCreated) {+ try {+ await releaseClaim(client, pool, claimName)+ info(`claim released: ${claimName}`)+ } catch (error) {+ info(`claim cleanup failed: ${await describeError(error)}`)+ }+ }+ }+}++try {+ await main()+} catch (error) {+ console.error(`\npi-agent failed: ${await describeError(error)}`)+ process.exitCode = 1+}diff --git a/libs/fleet/js-sdk/package-lock.json b/libs/fleet/js-sdk/package-lock.jsonnew file mode 100644index 0000000000..0dfd9f58fc--- /dev/null+++ b/libs/fleet/js-sdk/package-lock.json@@ -0,0 +1,854 @@+{+ "name": "@trycua/cyclops",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@trycua/cyclops",+ "version": "0.1.0",+ "license": "MIT",+ "devDependencies": {+ "swagger-typescript-api": "13.2.7",+ "typescript": "5.7.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@biomejs/js-api": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/@biomejs/js-api/-/js-api-1.0.0.tgz",+ "integrity": "sha512-69OfQ7+09AtiCIg+k+aU3rEsGit5o/SJWCS3BeBH/2nJYdJGi0cIx+ybka8i1EK69aNcZxYO1y1iAAEmYMq1HA==",+ "dev": true,+ "license": "MIT OR Apache-2.0",+ "peerDependencies": {+ "@biomejs/wasm-bundler": "^2.0.0",+ "@biomejs/wasm-nodejs": "^2.0.0",+ "@biomejs/wasm-web": "^2.0.0"+ },+ "peerDependenciesMeta": {+ "@biomejs/wasm-bundler": {+ "optional": true+ },+ "@biomejs/wasm-nodejs": {+ "optional": true+ },+ "@biomejs/wasm-web": {+ "optional": true+ }+ }+ },+ "node_modules/@biomejs/wasm-nodejs": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@biomejs/wasm-nodejs/-/wasm-nodejs-2.0.5.tgz",+ "integrity": "sha512-pihpBMylewgDdGFZHRkgmc3OajuGIJPXhvfYuKCNK/CWyJMrYEFmPKs8Iq1kY0sYMmGlTbD4K2udV03KYa+r0Q==",+ "dev": true,+ "license": "MIT OR Apache-2.0"+ },+ "node_modules/@exodus/schemasafe": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/@exodus/schemasafe/-/schemasafe-1.3.0.tgz",+ "integrity": "sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/swagger-schema-official": {+ "version": "2.0.25",+ "resolved": "https://registry.npmjs.org/@types/swagger-schema-official/-/swagger-schema-official-2.0.25.tgz",+ "integrity": "sha512-T92Xav+Gf/Ik1uPW581nA+JftmjWPgskw/WBf4TJzxRG/SJ+DfNnNE+WuZ4mrXuzflQMqMkm1LSYjzYW7MB1Cg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/ansi-regex": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/ansi-styles": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "color-convert": "^2.0.1"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/argparse": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",+ "dev": true,+ "license": "Python-2.0"+ },+ "node_modules/c12": {+ "version": "3.3.4",+ "resolved": "https://registry.npmjs.org/c12/-/c12-3.3.4.tgz",+ "integrity": "sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "chokidar": "^5.0.0",+ "confbox": "^0.2.4",+ "defu": "^6.1.6",+ "dotenv": "^17.3.1",+ "exsolve": "^1.0.8",+ "giget": "^3.2.0",+ "jiti": "^2.6.1",+ "ohash": "^2.0.11",+ "pathe": "^2.0.3",+ "perfect-debounce": "^2.1.0",+ "pkg-types": "^2.3.0",+ "rc9": "^3.0.1"+ },+ "peerDependencies": {+ "magicast": "*"+ },+ "peerDependenciesMeta": {+ "magicast": {+ "optional": true+ }+ }+ },+ "node_modules/call-me-maybe": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz",+ "integrity": "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/chokidar": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz",+ "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "readdirp": "^5.0.0"+ },+ "engines": {+ "node": ">= 20.19.0"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/citty": {+ "version": "0.1.6",+ "resolved": "https://registry.npmjs.org/citty/-/citty-0.1.6.tgz",+ "integrity": "sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "consola": "^3.2.3"+ }+ },+ "node_modules/cliui": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",+ "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "string-width": "^4.2.0",+ "strip-ansi": "^6.0.1",+ "wrap-ansi": "^7.0.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/color-convert": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "color-name": "~1.1.4"+ },+ "engines": {+ "node": ">=7.0.0"+ }+ },+ "node_modules/color-name": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/confbox": {+ "version": "0.2.4",+ "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz",+ "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/consola": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz",+ "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^14.18.0 || >=16.10.0"+ }+ },+ "node_modules/defu": {+ "version": "6.1.7",+ "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz",+ "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/destr": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz",+ "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/dotenv": {+ "version": "17.4.2",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",+ "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://dotenvx.com"+ }+ },+ "node_modules/emoji-regex": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/es6-promise": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz",+ "integrity": "sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/eta": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/eta/-/eta-2.2.0.tgz",+ "integrity": "sha512-UVQ72Rqjy/ZKQalzV5dCCJP80GrmPrMxh6NlNf+erV6ObL0ZFkhCstWRawS85z3smdr3d2wXPsZEY7rDPfGd2g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ },+ "funding": {+ "url": "https://github.com/eta-dev/eta?sponsor=1"+ }+ },+ "node_modules/exsolve": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.1.0.tgz",+ "integrity": "sha512-D+42+T12DdIlJM3uepa55qGiL3sYdLBOxIl2ifQCzCHz4c7eiolaHsi3BIqEr7JxBzxv2pYZQX9kw16ziMcEmw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fast-safe-stringify": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz",+ "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/giget": {+ "version": "3.3.0",+ "resolved": "https://registry.npmjs.org/giget/-/giget-3.3.0.tgz",+ "integrity": "sha512-gzi2D96p+AMfDcmJHGDj3KJ9NRiwvlFAU5yfa3ROwWZmFUjX4P43x3BcyRaOMMLto1vUo7C+86+MFhYTl6Ryiw==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "giget": "dist/cli.mjs"+ }+ },+ "node_modules/http2-client": {+ "version": "1.3.5",+ "resolved": "https://registry.npmjs.org/http2-client/-/http2-client-1.3.5.tgz",+ "integrity": "sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/is-fullwidth-code-point": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/jiti": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",+ "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "jiti": "lib/jiti-cli.mjs"+ }+ },+ "node_modules/js-yaml": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",+ "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/puzrin"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/nodeca"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "argparse": "^2.0.1"+ },+ "bin": {+ "js-yaml": "bin/js-yaml.js"+ }+ },+ "node_modules/lodash": {+ "version": "4.18.1",+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",+ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/nanoid": {+ "version": "5.1.16",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz",+ "integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.js"+ },+ "engines": {+ "node": "^18 || >=20"+ }+ },+ "node_modules/node-fetch": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "whatwg-url": "^5.0.0"+ },+ "engines": {+ "node": "4.x || >=6.0.0"+ },+ "peerDependencies": {+ "encoding": "^0.1.0"+ },+ "peerDependenciesMeta": {+ "encoding": {+ "optional": true+ }+ }+ },+ "node_modules/node-fetch-h2": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/node-fetch-h2/-/node-fetch-h2-2.3.0.tgz",+ "integrity": "sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "http2-client": "^1.2.5"+ },+ "engines": {+ "node": "4.x || >=6.0.0"+ }+ },+ "node_modules/node-readfiles": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/node-readfiles/-/node-readfiles-0.2.0.tgz",+ "integrity": "sha512-SU00ZarexNlE4Rjdm83vglt5Y9yiQ+XI1XpflWlb7q7UTN1JUItm69xMeiQCTxtTfnzt+83T8Cx+vI2ED++VDA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es6-promise": "^3.2.1"+ }+ },+ "node_modules/oas-kit-common": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/oas-kit-common/-/oas-kit-common-1.0.8.tgz",+ "integrity": "sha512-pJTS2+T0oGIwgjGpw7sIRU8RQMcUoKCDWFLdBqKB2BNmGpbBMH2sdqAaOXUg8OzonZHU0L7vfJu1mJFEiYDWOQ==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "fast-safe-stringify": "^2.0.7"+ }+ },+ "node_modules/oas-linter": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/oas-linter/-/oas-linter-3.2.2.tgz",+ "integrity": "sha512-KEGjPDVoU5K6swgo9hJVA/qYGlwfbFx+Kg2QB/kd7rzV5N8N5Mg6PlsoCMohVnQmo+pzJap/F610qTodKzecGQ==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "@exodus/schemasafe": "^1.0.0-rc.2",+ "should": "^13.2.1",+ "yaml": "^1.10.0"+ },+ "funding": {+ "url": "https://github.com/Mermade/oas-kit?sponsor=1"+ }+ },+ "node_modules/oas-resolver": {+ "version": "2.5.6",+ "resolved": "https://registry.npmjs.org/oas-resolver/-/oas-resolver-2.5.6.tgz",+ "integrity": "sha512-Yx5PWQNZomfEhPPOphFbZKi9W93CocQj18NlD2Pa4GWZzdZpSJvYwoiuurRI7m3SpcChrnO08hkuQDL3FGsVFQ==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "node-fetch-h2": "^2.3.0",+ "oas-kit-common": "^1.0.8",+ "reftools": "^1.1.9",+ "yaml": "^1.10.0",+ "yargs": "^17.0.1"+ },+ "bin": {+ "resolve": "resolve.js"+ },+ "funding": {+ "url": "https://github.com/Mermade/oas-kit?sponsor=1"+ }+ },+ "node_modules/oas-schema-walker": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/oas-schema-walker/-/oas-schema-walker-1.1.5.tgz",+ "integrity": "sha512-2yucenq1a9YPmeNExoUa9Qwrt9RFkjqaMAA1X+U7sbb0AqBeTIdMHky9SQQ6iN94bO5NW0W4TRYXerG+BdAvAQ==",+ "dev": true,+ "license": "BSD-3-Clause",+ "funding": {+ "url": "https://github.com/Mermade/oas-kit?sponsor=1"+ }+ },+ "node_modules/oas-validator": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/oas-validator/-/oas-validator-5.0.8.tgz",+ "integrity": "sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "call-me-maybe": "^1.0.1",+ "oas-kit-common": "^1.0.8",+ "oas-linter": "^3.2.2",+ "oas-resolver": "^2.5.6",+ "oas-schema-walker": "^1.1.5",+ "reftools": "^1.1.9",+ "should": "^13.2.1",+ "yaml": "^1.10.0"+ },+ "funding": {+ "url": "https://github.com/Mermade/oas-kit?sponsor=1"+ }+ },+ "node_modules/ohash": {+ "version": "2.0.11",+ "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz",+ "integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/perfect-debounce": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-2.1.0.tgz",+ "integrity": "sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/pkg-types": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.1.tgz",+ "integrity": "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "confbox": "^0.2.4",+ "exsolve": "^1.0.8",+ "pathe": "^2.0.3"+ }+ },+ "node_modules/rc9": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/rc9/-/rc9-3.0.1.tgz",+ "integrity": "sha512-gMDyleLWVE+i6Sgtc0QbbY6pEKqYs97NGi6isHQPqYlLemPoO8dxQ3uGi0f4NiP98c+jMW6cG1Kx9dDwfvqARQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "defu": "^6.1.6",+ "destr": "^2.0.5"+ }+ },+ "node_modules/readdirp": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.0.0.tgz",+ "integrity": "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 20.19.0"+ },+ "funding": {+ "type": "individual",+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/reftools": {+ "version": "1.1.9",+ "resolved": "https://registry.npmjs.org/reftools/-/reftools-1.1.9.tgz",+ "integrity": "sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==",+ "dev": true,+ "license": "BSD-3-Clause",+ "funding": {+ "url": "https://github.com/Mermade/oas-kit?sponsor=1"+ }+ },+ "node_modules/require-directory": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/should": {+ "version": "13.2.3",+ "resolved": "https://registry.npmjs.org/should/-/should-13.2.3.tgz",+ "integrity": "sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "should-equal": "^2.0.0",+ "should-format": "^3.0.3",+ "should-type": "^1.4.0",+ "should-type-adaptors": "^1.0.1",+ "should-util": "^1.0.0"+ }+ },+ "node_modules/should-equal": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/should-equal/-/should-equal-2.0.0.tgz",+ "integrity": "sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "should-type": "^1.4.0"+ }+ },+ "node_modules/should-format": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/should-format/-/should-format-3.0.3.tgz",+ "integrity": "sha512-hZ58adtulAk0gKtua7QxevgUaXTTXxIi8t41L3zo9AHvjXO1/7sdLECuHeIN2SRtYXpNkmhoUP2pdeWgricQ+Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "should-type": "^1.3.0",+ "should-type-adaptors": "^1.0.1"+ }+ },+ "node_modules/should-type": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/should-type/-/should-type-1.4.0.tgz",+ "integrity": "sha512-MdAsTu3n25yDbIe1NeN69G4n6mUnJGtSJHygX3+oN0ZbO3DTiATnf7XnYJdGT42JCXurTb1JI0qOBR65shvhPQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/should-type-adaptors": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/should-type-adaptors/-/should-type-adaptors-1.1.0.tgz",+ "integrity": "sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "should-type": "^1.3.0",+ "should-util": "^1.0.0"+ }+ },+ "node_modules/should-util": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/should-util/-/should-util-1.0.1.tgz",+ "integrity": "sha512-oXF8tfxx5cDk8r2kYqlkUJzZpDBqVY/II2WhvU0n9Y3XYvAYRmeaf1PvvIvTgPnv4KJ+ES5M0PyDq5Jp+Ygy2g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/string-width": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^8.0.0",+ "is-fullwidth-code-point": "^3.0.0",+ "strip-ansi": "^6.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/strip-ansi": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/swagger-schema-official": {+ "version": "2.0.0-bab6bed",+ "resolved": "https://registry.npmjs.org/swagger-schema-official/-/swagger-schema-official-2.0.0-bab6bed.tgz",+ "integrity": "sha512-rCC0NWGKr/IJhtRuPq/t37qvZHI/mH4I4sxflVM+qgVe5Z2uOCivzWaVbuioJaB61kvm5UvB7b49E+oBY0M8jA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/swagger-typescript-api": {+ "version": "13.2.7",+ "resolved": "https://registry.npmjs.org/swagger-typescript-api/-/swagger-typescript-api-13.2.7.tgz",+ "integrity": "sha512-rfqqoRFpZJPl477M/snMJPM90EvI8WqhuUHSF5ecC2r/w376T29+QXNJFVPsJmbFu5rBc/8m3vhArtMctjONdw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@biomejs/js-api": "1.0.0",+ "@biomejs/wasm-nodejs": "2.0.5",+ "@types/swagger-schema-official": "^2.0.25",+ "c12": "^3.0.4",+ "citty": "^0.1.6",+ "consola": "^3.4.2",+ "eta": "^2.2.0",+ "js-yaml": "^4.1.0",+ "lodash": "^4.17.21",+ "nanoid": "^5.1.5",+ "swagger-schema-official": "2.0.0-bab6bed",+ "swagger2openapi": "^7.0.8",+ "typescript": "~5.8.3"+ },+ "bin": {+ "sta": "dist/cli.js",+ "swagger-typescript-api": "dist/cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/swagger-typescript-api/node_modules/typescript": {+ "version": "5.8.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",+ "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/swagger2openapi": {+ "version": "7.0.8",+ "resolved": "https://registry.npmjs.org/swagger2openapi/-/swagger2openapi-7.0.8.tgz",+ "integrity": "sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "call-me-maybe": "^1.0.1",+ "node-fetch": "^2.6.1",+ "node-fetch-h2": "^2.3.0",+ "node-readfiles": "^0.2.0",+ "oas-kit-common": "^1.0.8",+ "oas-resolver": "^2.5.6",+ "oas-schema-walker": "^1.1.5",+ "oas-validator": "^5.0.8",+ "reftools": "^1.1.9",+ "yaml": "^1.10.0",+ "yargs": "^17.0.1"+ },+ "bin": {+ "boast": "boast.js",+ "oas-validate": "oas-validate.js",+ "swagger2openapi": "swagger2openapi.js"+ },+ "funding": {+ "url": "https://github.com/Mermade/oas-kit?sponsor=1"+ }+ },+ "node_modules/tr46": {+ "version": "0.0.3",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/typescript": {+ "version": "5.7.2",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.2.tgz",+ "integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/webidl-conversions": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",+ "dev": true,+ "license": "BSD-2-Clause"+ },+ "node_modules/whatwg-url": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tr46": "~0.0.3",+ "webidl-conversions": "^3.0.0"+ }+ },+ "node_modules/wrap-ansi": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^4.0.0",+ "string-width": "^4.1.0",+ "strip-ansi": "^6.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yaml": {+ "version": "1.10.3",+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz",+ "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/yargs": {+ "version": "17.7.3",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz",+ "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cliui": "^8.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "require-directory": "^2.1.1",+ "string-width": "^4.2.3",+ "y18n": "^5.0.5",+ "yargs-parser": "^21.1.1"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/yargs-parser": {+ "version": "21.1.1",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",+ "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ }+ }+}diff --git a/libs/fleet/js-sdk/package.json b/libs/fleet/js-sdk/package.jsonnew file mode 100644index 0000000000..a3e6032649--- /dev/null+++ b/libs/fleet/js-sdk/package.json@@ -0,0 +1,54 @@+{+ "name": "@trycua/cyclops",+ "version": "0.1.0",+ "description": "OpenAPI-generated JavaScript and TypeScript client for Cua Cyclops",+ "type": "module",+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js"+ }+ },+ "files": [+ "dist",+ "README.md",+ "LICENSE"+ ],+ "engines": {+ "node": ">=18.0.0"+ },+ "publishConfig": {+ "access": "public"+ },+ "scripts": {+ "clean": "rm -rf dist",+ "generate": "swagger-typescript-api generate -p ../backend/docs/swagger.json -o ./src/generated -n cyclops-cs-backend.ts --module-name-index 1 --extract-request-body --extract-request-params --extract-response-body --extract-response-error && node ./scripts/patch-generated-client.mjs",+ "generate:check": "node ./scripts/check-generated-client.mjs",+ "build": "npm run clean && tsc -p tsconfig.json",+ "typecheck": "tsc -p tsconfig.json --noEmit",+ "test": "npm run build && node --test test/*.test.js",+ "prepublishOnly": "npm run generate:check && npm run typecheck && npm test && npm run build"+ },+ "keywords": [+ "cua",+ "cyclops",+ "openapi",+ "sdk"+ ],+ "license": "MIT",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/trycua/cloud.git",+ "directory": "cyclops-cs/js-sdk"+ },+ "bugs": {+ "url": "https://github.com/trycua/cloud/issues"+ },+ "homepage": "https://github.com/trycua/cloud/tree/main/cyclops-cs/js-sdk#readme",+ "devDependencies": {+ "swagger-typescript-api": "13.2.7",+ "typescript": "5.7.2"+ }+}diff --git a/libs/fleet/js-sdk/scripts/check-generated-client.mjs b/libs/fleet/js-sdk/scripts/check-generated-client.mjsnew file mode 100644index 0000000000..7f77a6bbe4--- /dev/null+++ b/libs/fleet/js-sdk/scripts/check-generated-client.mjs@@ -0,0 +1,15 @@+import { execFileSync } from "node:child_process"+import { readFile, writeFile } from "node:fs/promises"++const generatedClientPath = new URL("../src/generated/cyclops-cs-backend.ts", import.meta.url)+const before = await readFile(generatedClientPath)++try {+ execFileSync("npm", ["run", "generate"], { stdio: "inherit" })+ const after = await readFile(generatedClientPath)+ if (!before.equals(after)) {+ throw new Error("Generated client drift detected; run npm run generate and commit the result")+ }+} finally {+ await writeFile(generatedClientPath, before)+}diff --git a/libs/fleet/js-sdk/scripts/patch-generated-client.mjs b/libs/fleet/js-sdk/scripts/patch-generated-client.mjsnew file mode 100644index 0000000000..afc5d92bca--- /dev/null+++ b/libs/fleet/js-sdk/scripts/patch-generated-client.mjs@@ -0,0 +1,21 @@+import { readFile, writeFile } from "node:fs/promises"++const generatedClientPath = new URL("../src/generated/cyclops-cs-backend.ts", import.meta.url)+const original = await readFile(generatedClientPath, "utf8")+const oldImplementation = ` private customFetch = (...fetchParams: Parameters<typeof fetch>) =>+ fetch(...fetchParams);`+const newImplementation = ` private customFetch: typeof fetch = (...fetchParams) => {+ const runtimeFetch = globalThis.fetch;+ if (typeof runtimeFetch !== "function") {+ throw new Error(+ "Fetch API is unavailable. @trycua/cyclops requires Node.js 18+ or an injected customFetch implementation.",+ );+ }+ return runtimeFetch(...fetchParams);+ };`++if (!original.includes(oldImplementation)) {+ throw new Error("Generated HttpClient fetch implementation did not match the expected template")+}++await writeFile(generatedClientPath, original.replace(oldImplementation, newImplementation))diff --git a/libs/fleet/js-sdk/src/generated/cyclops-cs-backend.ts b/libs/fleet/js-sdk/src/generated/cyclops-cs-backend.tsnew file mode 100644index 0000000000..87cbc33588--- /dev/null+++ b/libs/fleet/js-sdk/src/generated/cyclops-cs-backend.ts@@ -0,0 +1,1032 @@+/* eslint-disable */+/* tslint:disable */+// @ts-nocheck+/*+ * ---------------------------------------------------------------+ * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##+ * ## ##+ * ## AUTHOR: acacode ##+ * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##+ * ---------------------------------------------------------------+ */++export interface HandlersConfigResponse {+ /**+ * Admin is true when the caller is in input.flags.admin_subs (OPA-evaluated).+ * Non-admins get the customer view: infra-only nav (Nodes, Operator events)+ * is hidden in the SPA and the corresponding kubectl-proxy paths are denied+ * server-side by authz.rego.+ */+ admin?: boolean;+}++export interface HandlersCreateKeyRequest {+ /** @example "ci-prod" */+ name?: string;+ /** @example "test-pool" */+ namespace?: string;+}++export interface HandlersCreateKeyResponse {+ client_id?: string;+ client_secret?: string;+ name?: string;+ namespace?: string;+ token_url?: string;+}++export interface HandlersCreateNamespaceRequest {+ /** @example "my-workspace" */+ name?: string;+}++export interface HandlersCreatePoolTemplateRequest {+ config?: object;+ /** @example "gpu-large" */+ name?: string;+}++export interface HandlersCreateUserKeyRequest {+ /** @example "my-ci-key" */+ name?: string;+ /** @example ["[\"ns1\"","\"ns2\"]"] */+ scope?: string[];+}++export interface HandlersCreateUserKeyResponse {+ client_id?: string;+ client_secret?: string;+ name?: string;+ scope?: string[];+ token_url?: string;+}++export interface HandlersErrorResponse {+ error?: string;+}++export interface HandlersHealthResponse {+ ok?: boolean;+}++export interface HandlersListKeysResponse {+ keys?: KeycloakKeyClient[];+}++export interface HandlersListUserKeysResponse {+ keys?: HandlersUserKeyResponse[];+}++export interface HandlersNamespaceResponse {+ createdAt?: string;+ labels?: Record<string, string>;+ name?: string;+ status?: string;+}++export interface HandlersPoolTemplateResponse {+ config?: object;+ createdAt?: string;+ name?: string;+ user?: string;+}++export interface HandlersUserKeyResponse {+ client_id?: string;+ id?: string;+ name?: string;+ scope?: string[];+}++export interface KeycloakKeyClient {+ client_id?: string;+ id?: string;+ name?: string;+ namespace?: string;+ owner_sub?: string;+}++export type BatchLanesCreateError = Record<string, string>;++export type BatchLanesDeleteError = Record<string, string>;++export type BatchSubmitCreateError = Record<string, string>;++export type BatchDeleteError = Record<string, string>;++export type BatchResultsListError = Record<string, string>;++export type BatchStatusListError = Record<string, string>;++export type ConfigListData = HandlersConfigResponse;++export type ConfigListError = HandlersErrorResponse;++export type GatewayDetailData = string;++export type GatewayDetailError = HandlersErrorResponse;++export type GetK8SData = string;++export type GetK8SError = HandlersErrorResponse;++export type KeysListData = HandlersListKeysResponse;++export type KeysListError = HandlersErrorResponse;++export type KeysCreateData = HandlersCreateKeyResponse;++export type KeysCreateError = HandlersErrorResponse;++export type KeysDeleteData = any;++export type KeysDeleteError = HandlersErrorResponse;++export type LabelDeleteError = Record<string, string>;++export type LabelBatchCreateError = Record<string, string>;++export type LabelResultsListError = Record<string, string>;++export type LabelStatusListError = Record<string, string>;++export type NamespacesListData = HandlersNamespaceResponse[];++export type NamespacesListError = HandlersErrorResponse;++export type NamespacesCreateData = HandlersNamespaceResponse;++export type NamespacesCreateError = HandlersErrorResponse;++export type NamespacesDeleteData = any;++export type NamespacesDeleteError = HandlersErrorResponse;++export type OrchDetailData = string;++export type OrchDetailError = HandlersErrorResponse;++export type PoolTemplatesListData = HandlersPoolTemplateResponse[];++export type PoolTemplatesListError = HandlersErrorResponse;++export type PoolTemplatesCreateData = HandlersPoolTemplateResponse;++export type PoolTemplatesCreateError = HandlersErrorResponse;++export type PoolTemplatesDetailData = HandlersPoolTemplateResponse;++export type PoolTemplatesDetailError = HandlersErrorResponse;++export type PoolTemplatesDeleteData = any;++export type PoolTemplatesDeleteError = HandlersErrorResponse;++export type GetSvcData = string;++export type GetSvcError = HandlersErrorResponse;++export type UserKeysListData = HandlersListUserKeysResponse;++export type UserKeysListError = HandlersErrorResponse;++export type UserKeysCreateData = HandlersCreateUserKeyResponse;++export type UserKeysCreateError = HandlersErrorResponse;++export type UserKeysDeleteData = any;++export type UserKeysDeleteError = HandlersErrorResponse;++export type HealthzListData = HandlersHealthResponse;++export type QueryParamsType = Record<string | number, any>;+export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;++export interface FullRequestParams extends Omit<RequestInit, "body"> {+ /** set parameter to `true` for call `securityWorker` for this request */+ secure?: boolean;+ /** request path */+ path: string;+ /** content type of request body */+ type?: ContentType;+ /** query params */+ query?: QueryParamsType;+ /** format of response (i.e. response.json() -> format: "json") */+ format?: ResponseFormat;+ /** request body */+ body?: unknown;+ /** base url */+ baseUrl?: string;+ /** request cancellation token */+ cancelToken?: CancelToken;+}++export type RequestParams = Omit<+ FullRequestParams,+ "body" | "method" | "query" | "path"+>;++export interface ApiConfig<SecurityDataType = unknown> {+ baseUrl?: string;+ baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;+ securityWorker?: (+ securityData: SecurityDataType | null,+ ) => Promise<RequestParams | void> | RequestParams | void;+ customFetch?: typeof fetch;+}++export interface HttpResponse<D extends unknown, E extends unknown = unknown>+ extends Response {+ data: D;+ error: E;+}++type CancelToken = Symbol | string | number;++export enum ContentType {+ Json = "application/json",+ JsonApi = "application/vnd.api+json",+ FormData = "multipart/form-data",+ UrlEncoded = "application/x-www-form-urlencoded",+ Text = "text/plain",+}++export class HttpClient<SecurityDataType = unknown> {+ public baseUrl: string = "/";+ private securityData: SecurityDataType | null = null;+ private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];+ private abortControllers = new Map<CancelToken, AbortController>();+ private customFetch: typeof fetch = (...fetchParams) => {+ const runtimeFetch = globalThis.fetch;+ if (typeof runtimeFetch !== "function") {+ throw new Error(+ "Fetch API is unavailable. @trycua/cyclops requires Node.js 18+ or an injected customFetch implementation.",+ );+ }+ return runtimeFetch(...fetchParams);+ };++ private baseApiParams: RequestParams = {+ credentials: "same-origin",+ headers: {},+ redirect: "follow",+ referrerPolicy: "no-referrer",+ };++ constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {+ Object.assign(this, apiConfig);+ }++ public setSecurityData = (data: SecurityDataType | null) => {+ this.securityData = data;+ };++ protected encodeQueryParam(key: string, value: any) {+ const encodedKey = encodeURIComponent(key);+ return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`;+ }++ protected addQueryParam(query: QueryParamsType, key: string) {+ return this.encodeQueryParam(key, query[key]);+ }++ protected addArrayQueryParam(query: QueryParamsType, key: string) {+ const value = query[key];+ return value.map((v: any) => this.encodeQueryParam(key, v)).join("&");+ }++ protected toQueryString(rawQuery?: QueryParamsType): string {+ const query = rawQuery || {};+ const keys = Object.keys(query).filter(+ (key) => "undefined" !== typeof query[key],+ );+ return keys+ .map((key) =>+ Array.isArray(query[key])+ ? this.addArrayQueryParam(query, key)+ : this.addQueryParam(query, key),+ )+ .join("&");+ }++ protected addQueryParams(rawQuery?: QueryParamsType): string {+ const queryString = this.toQueryString(rawQuery);+ return queryString ? `?${queryString}` : "";+ }++ private contentFormatters: Record<ContentType, (input: any) => any> = {+ [ContentType.Json]: (input: any) =>+ input !== null && (typeof input === "object" || typeof input === "string")+ ? JSON.stringify(input)+ : input,+ [ContentType.JsonApi]: (input: any) =>+ input !== null && (typeof input === "object" || typeof input === "string")+ ? JSON.stringify(input)+ : input,+ [ContentType.Text]: (input: any) =>+ input !== null && typeof input !== "string"+ ? JSON.stringify(input)+ : input,+ [ContentType.FormData]: (input: any) =>+ Object.keys(input || {}).reduce((formData, key) => {+ const property = input[key];+ formData.append(+ key,+ property instanceof Blob+ ? property+ : typeof property === "object" && property !== null+ ? JSON.stringify(property)+ : `${property}`,+ );+ return formData;+ }, new FormData()),+ [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),+ };++ protected mergeRequestParams(+ params1: RequestParams,+ params2?: RequestParams,+ ): RequestParams {+ return {+ ...this.baseApiParams,+ ...params1,+ ...(params2 || {}),+ headers: {+ ...(this.baseApiParams.headers || {}),+ ...(params1.headers || {}),+ ...((params2 && params2.headers) || {}),+ },+ };+ }++ protected createAbortSignal = (+ cancelToken: CancelToken,+ ): AbortSignal | undefined => {+ if (this.abortControllers.has(cancelToken)) {+ const abortController = this.abortControllers.get(cancelToken);+ if (abortController) {+ return abortController.signal;+ }+ return void 0;+ }++ const abortController = new AbortController();+ this.abortControllers.set(cancelToken, abortController);+ return abortController.signal;+ };++ public abortRequest = (cancelToken: CancelToken) => {+ const abortController = this.abortControllers.get(cancelToken);++ if (abortController) {+ abortController.abort();+ this.abortControllers.delete(cancelToken);+ }+ };++ public request = async <T = any, E = any>({+ body,+ secure,+ path,+ type,+ query,+ format,+ baseUrl,+ cancelToken,+ ...params+ }: FullRequestParams): Promise<HttpResponse<T, E>> => {+ const secureParams =+ ((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&+ this.securityWorker &&+ (await this.securityWorker(this.securityData))) ||+ {};+ const requestParams = this.mergeRequestParams(params, secureParams);+ const queryString = query && this.toQueryString(query);+ const payloadFormatter = this.contentFormatters[type || ContentType.Json];+ const responseFormat = format || requestParams.format;++ return this.customFetch(+ `${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`,+ {+ ...requestParams,+ headers: {+ ...(requestParams.headers || {}),+ ...(type && type !== ContentType.FormData+ ? { "Content-Type": type }+ : {}),+ },+ signal:+ (cancelToken+ ? this.createAbortSignal(cancelToken)+ : requestParams.signal) || null,+ body:+ typeof body === "undefined" || body === null+ ? null+ : payloadFormatter(body),+ },+ ).then(async (response) => {+ const r = response.clone() as HttpResponse<T, E>;+ r.data = null as unknown as T;+ r.error = null as unknown as E;++ const data = !responseFormat+ ? r+ : await response[responseFormat]()+ .then((data) => {+ if (r.ok) {+ r.data = data;+ } else {+ r.error = data;+ }+ return r;+ })+ .catch((e) => {+ r.error = e;+ return r;+ });++ if (cancelToken) {+ this.abortControllers.delete(cancelToken);+ }++ if (!response.ok) throw data;+ return data;+ });+ };+}++/**+ * @title Cyclops CS Backend API+ * @version 0.1+ * @baseUrl /+ * @contact+ *+ * Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key management, service proxies (k8s / orch / svc), namespace management, and deprecated gateway / batch / label routes that now return 410 Gone. All pool operations use OSGymSandboxClaim CRs (Path B).+ */+export class Api<+ SecurityDataType extends unknown,+> extends HttpClient<SecurityDataType> {+ /**+ * No description+ *+ * @tags health+ * @name HealthzList+ * @summary Liveness/readiness probe+ * @request GET:/healthz+ */+ healthzList = (params: RequestParams = {}) =>+ this.request<HealthzListData, any>({+ path: `/healthz`,+ method: "GET",+ format: "json",+ ...params,+ });++ batch = {+ /**+ * @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.+ *+ * @tags batch+ * @name BatchLanesCreate+ * @summary Deprecated batch lane acquisition route+ * @request POST:/api/batch/{pool}/lanes+ * @deprecated+ * @secure+ */+ batchLanesCreate: (pool: string, params: RequestParams = {}) =>+ this.request<any, BatchLanesCreateError>({+ path: `/api/batch/${pool}/lanes`,+ method: "POST",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name BatchLanesDelete+ * @summary Deprecated batch lane release route+ * @request DELETE:/api/batch/{pool}/lanes+ * @deprecated+ * @secure+ */+ batchLanesDelete: (pool: string, params: RequestParams = {}) =>+ this.request<any, BatchLanesDeleteError>({+ path: `/api/batch/${pool}/lanes`,+ method: "DELETE",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name BatchSubmitCreate+ * @summary Deprecated batch submission route+ * @request POST:/api/batch/{pool}/submit+ * @deprecated+ * @secure+ */+ batchSubmitCreate: (pool: string, params: RequestParams = {}) =>+ this.request<any, BatchSubmitCreateError>({+ path: `/api/batch/${pool}/submit`,+ method: "POST",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name BatchDelete+ * @summary Deprecated batch cancellation route+ * @request DELETE:/api/batch/{pool}/{id}+ * @deprecated+ * @secure+ */+ batchDelete: (pool: string, id: string, params: RequestParams = {}) =>+ this.request<any, BatchDeleteError>({+ path: `/api/batch/${pool}/${id}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name BatchResultsList+ * @summary Deprecated batch results route+ * @request GET:/api/batch/{pool}/{id}/results+ * @deprecated+ * @secure+ */+ batchResultsList: (pool: string, id: string, params: RequestParams = {}) =>+ this.request<any, BatchResultsListError>({+ path: `/api/batch/${pool}/${id}/results`,+ method: "GET",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name BatchStatusList+ * @summary Deprecated batch status route+ * @request GET:/api/batch/{pool}/{id}/status+ * @deprecated+ * @secure+ */+ batchStatusList: (pool: string, id: string, params: RequestParams = {}) =>+ this.request<any, BatchStatusListError>({+ path: `/api/batch/${pool}/${id}/status`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ config = {+ /**+ * @description Returns OPA-evaluated feature flags for the authenticated SPA user. `admin` is true when the caller's JWT sub appears in input.flags.admin_subs.+ *+ * @tags config+ * @name ConfigList+ * @summary Per-user feature flags+ * @request GET:/api/config+ * @secure+ */+ configList: (params: RequestParams = {}) =>+ this.request<ConfigListData, ConfigListError>({+ path: `/api/config`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),+ };+ gateway = {+ /**+ * @description DEPRECATED (CUA-609): The per-pool orchestrator HTTP layer has been removed. This route returns 410 Gone for all requests. All pool operations must use OSGymSandboxClaim CRs (Path B) directly.+ *+ * @tags gateway+ * @name GatewayDetail+ * @summary Reverse-proxy to the per-pool orchestrator (sole ingress path — CUA-527)+ * @request GET:/api/gateway/{name}/{path}+ * @secure+ */+ gatewayDetail: (name: string, path?: string, params: RequestParams = {}) =>+ this.request<GatewayDetailData, GatewayDetailError>({+ path: `/api/gateway/${name}/${path}`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ 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).+ *+ * @tags passthrough+ * @name GetK8S+ * @summary Authenticated proxy to the in-pod kubectl-proxy sidecar+ * @request GET:/api/k8s/{path}+ * @secure+ */+ getK8S: (path: string, params: RequestParams = {}) =>+ this.request<GetK8SData, GetK8SError>({+ path: `/api/k8s/${path}`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ keys = {+ /**+ * No description+ *+ * @tags keys+ * @name KeysList+ * @summary List the calling user's API keys+ * @request GET:/api/keys+ * @secure+ */+ keysList: (params: RequestParams = {}) =>+ this.request<KeysListData, KeysListError>({+ path: `/api/keys`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * @description Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is shown exactly once.+ *+ * @tags keys+ * @name KeysCreate+ * @summary Create a new API key+ * @request POST:/api/keys+ * @secure+ */+ keysCreate: (body: HandlersCreateKeyRequest, params: RequestParams = {}) =>+ this.request<KeysCreateData, KeysCreateError>({+ path: `/api/keys`,+ method: "POST",+ body: body,+ secure: true,+ type: ContentType.Json,+ format: "json",+ ...params,+ }),++ /**+ * No description+ *+ * @tags keys+ * @name KeysDelete+ * @summary Revoke an API key by Keycloak client UUID+ * @request DELETE:/api/keys/{id}+ * @secure+ */+ keysDelete: (id: string, params: RequestParams = {}) =>+ this.request<KeysDeleteData, KeysDeleteError>({+ path: `/api/keys/${id}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),+ };+ label = {+ /**+ * @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.+ *+ * @tags batch+ * @name LabelDelete+ * @summary Deprecated label cancellation route+ * @request DELETE:/api/label/{pool}/{label}+ * @deprecated+ * @secure+ */+ labelDelete: (pool: string, label: string, params: RequestParams = {}) =>+ this.request<any, LabelDeleteError>({+ path: `/api/label/${pool}/${label}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name LabelBatchCreate+ * @summary Deprecated label batch submission route+ * @request POST:/api/label/{pool}/{label}/batch+ * @deprecated+ * @secure+ */+ labelBatchCreate: (+ pool: string,+ label: string,+ params: RequestParams = {},+ ) =>+ this.request<any, LabelBatchCreateError>({+ path: `/api/label/${pool}/${label}/batch`,+ method: "POST",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name LabelResultsList+ * @summary Deprecated label results route+ * @request GET:/api/label/{pool}/{label}/results+ * @deprecated+ * @secure+ */+ labelResultsList: (+ pool: string,+ label: string,+ params: RequestParams = {},+ ) =>+ this.request<any, LabelResultsListError>({+ path: `/api/label/${pool}/${label}/results`,+ method: "GET",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name LabelStatusList+ * @summary Deprecated label status route+ * @request GET:/api/label/{pool}/{label}/status+ * @deprecated+ * @secure+ */+ labelStatusList: (+ pool: string,+ label: string,+ params: RequestParams = {},+ ) =>+ this.request<any, LabelStatusListError>({+ path: `/api/label/${pool}/${label}/status`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ namespaces = {+ /**+ * @description Returns namespaces owned by the caller's Capsule Tenant. The list is scoped by a capsule.clastix.io/tenant=<tenant> label selector built from the authenticated subject, so it stays fail-closed even when Capsule Proxy isn't filtering.+ *+ * @tags namespaces+ * @name NamespacesList+ * @summary List the calling user's namespaces+ * @request GET:/api/namespaces+ * @secure+ */+ namespacesList: (params: RequestParams = {}) =>+ this.request<NamespacesListData, NamespacesListError>({+ path: `/api/namespaces`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * @description Creates a K8s namespace via impersonation. Capsule's webhook intercepts the creation and assigns it to the user's Tenant.+ *+ * @tags namespaces+ * @name NamespacesCreate+ * @summary Create a namespace for the calling user+ * @request POST:/api/namespaces+ * @secure+ */+ namespacesCreate: (+ body: HandlersCreateNamespaceRequest,+ params: RequestParams = {},+ ) =>+ this.request<NamespacesCreateData, NamespacesCreateError>({+ path: `/api/namespaces`,+ method: "POST",+ body: body,+ secure: true,+ type: ContentType.Json,+ format: "json",+ ...params,+ }),++ /**+ * @description Deletes a K8s namespace via impersonation. Capsule blocks deletion if the namespace doesn't belong to the user's Tenant.+ *+ * @tags namespaces+ * @name NamespacesDelete+ * @summary Delete a namespace owned by the calling user+ * @request DELETE:/api/namespaces/{name}+ * @secure+ */+ namespacesDelete: (name: string, params: RequestParams = {}) =>+ this.request<NamespacesDeleteData, NamespacesDeleteError>({+ path: `/api/namespaces/${name}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),+ };+ orch = {+ /**+ * @description Resolves <service>.<namespace>.svc.cluster.local at request time (in-cluster DNS). The caller must hold RBAC in {namespace} (verified via an impersonated RoleBinding probe); OPA additionally validates that namespace and service look like DNS-1123 labels.+ *+ * @tags passthrough+ * @name OrchDetail+ * @summary SPA-authenticated proxy to a per-namespace orchestrator service+ * @request GET:/api/orch/{namespace}/{service}/{path}+ * @secure+ */+ orchDetail: (+ namespace: string,+ service: string,+ path: string,+ params: RequestParams = {},+ ) =>+ this.request<OrchDetailData, OrchDetailError>({+ path: `/api/orch/${namespace}/${service}/${path}`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ poolTemplates = {+ /**+ * @description Returns every pool template owned by the calling user, newest first.+ *+ * @tags pool-templates+ * @name PoolTemplatesList+ * @summary List the calling user's pool templates+ * @request GET:/api/pool-templates+ * @secure+ */+ poolTemplatesList: (params: RequestParams = {}) =>+ this.request<PoolTemplatesListData, PoolTemplatesListError>({+ path: `/api/pool-templates`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * @description Stores the given pool config under a name owned by the calling user. Re-saving an existing name overwrites the config while preserving the original creation time. Use GET /api/pool-templates to list them and seed a new pool.+ *+ * @tags pool-templates+ * @name PoolTemplatesCreate+ * @summary Save a pool config as a reusable template+ * @request POST:/api/pool-templates+ * @secure+ */+ poolTemplatesCreate: (+ body: HandlersCreatePoolTemplateRequest,+ params: RequestParams = {},+ ) =>+ this.request<PoolTemplatesCreateData, PoolTemplatesCreateError>({+ path: `/api/pool-templates`,+ method: "POST",+ body: body,+ secure: true,+ type: ContentType.Json,+ format: "json",+ ...params,+ }),++ /**+ * No description+ *+ * @tags pool-templates+ * @name PoolTemplatesDetail+ * @summary Get one of the calling user's pool templates+ * @request GET:/api/pool-templates/{name}+ * @secure+ */+ poolTemplatesDetail: (name: string, params: RequestParams = {}) =>+ this.request<PoolTemplatesDetailData, PoolTemplatesDetailError>({+ path: `/api/pool-templates/${name}`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * No description+ *+ * @tags pool-templates+ * @name PoolTemplatesDelete+ * @summary Delete one of the calling user's pool templates+ * @request DELETE:/api/pool-templates/{name}+ * @secure+ */+ poolTemplatesDelete: (name: string, params: RequestParams = {}) =>+ this.request<PoolTemplatesDeleteData, PoolTemplatesDeleteError>({+ path: `/api/pool-templates/${name}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),+ };+ svc = {+ /**+ * @description Proxies to {service}.{namespace}.svc.cluster.local:80. Per-key tokens are bound to their `namespace` claim; all other principals (SPA, user keys, oauth2-proxy browser sessions) must hold RBAC in {namespace}, verified via an impersonated RoleBinding probe. Strips Authorization before forwarding.+ *+ * @tags gateway+ * @name GetSvc+ * @summary Authenticated reverse proxy to a K8s Service in a namespace the caller owns+ * @request GET:/api/svc/{namespace}/{service}/{path}+ * @secure+ */+ getSvc: (+ namespace: string,+ service: string,+ path?: string,+ params: RequestParams = {},+ ) =>+ this.request<GetSvcData, GetSvcError>({+ path: `/api/svc/${namespace}/${service}/${path}`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ userKeys = {+ /**+ * No description+ *+ * @tags user-keys+ * @name UserKeysList+ * @summary List the calling user's API keys+ * @request GET:/api/user-keys+ * @secure+ */+ userKeysList: (params: RequestParams = {}) =>+ this.request<UserKeysListData, UserKeysListError>({+ path: `/api/user-keys`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * @description Creates a Keycloak service-account client that acts on behalf of the calling user. The client_secret is returned exactly once; it cannot be retrieved later.+ *+ * @tags user-keys+ * @name UserKeysCreate+ * @summary Create a per-user API key+ * @request POST:/api/user-keys+ * @secure+ */+ userKeysCreate: (+ body: HandlersCreateUserKeyRequest,+ params: RequestParams = {},+ ) =>+ this.request<UserKeysCreateData, UserKeysCreateError>({+ path: `/api/user-keys`,+ method: "POST",+ body: body,+ secure: true,+ type: ContentType.Json,+ format: "json",+ ...params,+ }),++ /**+ * No description+ *+ * @tags user-keys+ * @name UserKeysDelete+ * @summary Revoke a per-user API key+ * @request DELETE:/api/user-keys/{id}+ * @secure+ */+ userKeysDelete: (id: string, params: RequestParams = {}) =>+ this.request<UserKeysDeleteData, UserKeysDeleteError>({+ path: `/api/user-keys/${id}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),+ };+}diff --git a/libs/fleet/js-sdk/src/index.ts b/libs/fleet/js-sdk/src/index.tsnew file mode 100644index 0000000000..a284615e3c--- /dev/null+++ b/libs/fleet/js-sdk/src/index.ts@@ -0,0 +1,62 @@+import { Api, type ApiConfig } from "./generated/cyclops-cs-backend.js"+import {+ ClientCredentialsTokenProvider,+ type ClientCredentialsTokenProviderOptions,+} from "./token.js"++export * from "./generated/cyclops-cs-backend.js"+export * from "./token.js"++export const DEFAULT_TOKEN_URL =+ "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"+export const DEFAULT_BASE_URL = "https://run.cua.ai"++export interface CyclopsClientOptions {+ clientId: string+ clientSecret: string+ tokenUrl?: string+ baseUrl?: string+ fetch?: typeof fetch+ refreshBufferMs?: number+}++function resolveFetch(customFetch?: typeof fetch): typeof fetch {+ const runtimeFetch = customFetch ?? globalThis.fetch+ if (typeof runtimeFetch !== "function") {+ throw new Error(+ "Fetch API is unavailable. @trycua/cyclops requires Node.js 18+ or an injected fetch implementation.",+ )+ }+ return runtimeFetch+}++export class CyclopsClient extends Api<unknown> {+ readonly tokenProvider: ClientCredentialsTokenProvider++ constructor(options: CyclopsClientOptions) {+ const fetch = resolveFetch(options.fetch)+ const tokenOptions: ClientCredentialsTokenProviderOptions = {+ tokenUrl: options.tokenUrl ?? DEFAULT_TOKEN_URL,+ clientId: options.clientId,+ clientSecret: options.clientSecret,+ fetch,+ refreshBufferMs: options.refreshBufferMs,+ }+ const tokenProvider = new ClientCredentialsTokenProvider(tokenOptions)+ const config: ApiConfig = {+ baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,+ customFetch: fetch,+ securityWorker: async () => ({+ headers: { Authorization: `Bearer ${await tokenProvider.getToken()}` },+ }),+ }+ super(config)+ this.tokenProvider = tokenProvider+ }++ static async fromKey(options: CyclopsClientOptions): Promise<CyclopsClient> {+ const client = new CyclopsClient(options)+ await client.tokenProvider.getToken()+ return client+ }+}diff --git a/libs/fleet/js-sdk/src/token.ts b/libs/fleet/js-sdk/src/token.tsnew file mode 100644index 0000000000..6b2f88d47e--- /dev/null+++ b/libs/fleet/js-sdk/src/token.ts@@ -0,0 +1,73 @@+export interface ClientCredentialsTokenProviderOptions {+ tokenUrl: string+ clientId: string+ clientSecret: string+ fetch?: typeof fetch+ refreshBufferMs?: number+}++function resolveFetch(customFetch?: typeof fetch): typeof fetch {+ const runtimeFetch = customFetch ?? globalThis.fetch+ if (typeof runtimeFetch !== "function") {+ throw new Error(+ "Fetch API is unavailable. @trycua/cyclops requires Node.js 18+ or an injected fetch implementation.",+ )+ }+ return runtimeFetch+}++interface TokenResponse {+ access_token: string+ expires_in?: number+}++export class ClientCredentialsTokenProvider {+ private readonly tokenUrl: string+ private readonly clientId: string+ private readonly clientSecret: string+ private readonly fetch: typeof fetch+ private readonly refreshBufferMs: number+ private accessToken?: string+ private tokenDeadline = 0+ private refreshPromise?: Promise<string>++ constructor(options: ClientCredentialsTokenProviderOptions) {+ this.tokenUrl = options.tokenUrl+ this.clientId = options.clientId+ this.clientSecret = options.clientSecret+ this.fetch = resolveFetch(options.fetch)+ this.refreshBufferMs = options.refreshBufferMs ?? 30_000+ }++ async getToken(): Promise<string> {+ if (this.accessToken && Date.now() < this.tokenDeadline - this.refreshBufferMs) {+ return this.accessToken+ }+ if (!this.refreshPromise) {+ this.refreshPromise = this.exchangeToken().finally(() => {+ this.refreshPromise = undefined+ })+ }+ return this.refreshPromise+ }++ private async exchangeToken(): Promise<string> {+ const response = await this.fetch(this.tokenUrl, {+ method: "POST",+ body: new URLSearchParams({+ grant_type: "client_credentials",+ client_id: this.clientId,+ client_secret: this.clientSecret,+ }),+ })+ if (!response.ok) {+ const body = await response.text().catch(() => "")+ throw new Error(`${response.status} ${response.statusText}${body ? `: ${body}` : ""}`)+ }++ const token = (await response.json()) as TokenResponse+ this.accessToken = token.access_token+ this.tokenDeadline = Date.now() + Number(token.expires_in ?? 300) * 1000+ return this.accessToken+ }+}diff --git a/libs/fleet/js-sdk/test/client.test.js b/libs/fleet/js-sdk/test/client.test.jsnew file mode 100644index 0000000000..d525bbd18e--- /dev/null+++ b/libs/fleet/js-sdk/test/client.test.js@@ -0,0 +1,76 @@+import assert from "node:assert/strict"+import test from "node:test"++import { CyclopsClient } from "../dist/index.js"++test("generated endpoint uses its generated route and bearer authentication", async () => {+ const requests = []+ const fetch = async (input, init = {}) => {+ requests.push({ url: String(input), init })+ if (String(input).endsWith("/token")) {+ return Response.json({ access_token: "token-1", expires_in: 300 })+ }+ return Response.json({ keys: [] })+ }++ const client = new CyclopsClient({+ baseUrl: "https://run.example",+ tokenUrl: "https://auth.example/token",+ clientId: "key-example",+ clientSecret: "secret",+ fetch,+ })++ const response = await client.keys.keysList()++ assert.deepEqual(response.data, { keys: [] })+ assert.equal(requests[1].url, "https://run.example/api/keys")+ assert.equal(requests[1].init.method, "GET")+ assert.equal(requests[1].init.headers.Authorization, "Bearer token-1")+})++test("Node global fetch handles token and generated API requests", async () => {+ const originalFetch = globalThis.fetch+ const requests = []+ globalThis.fetch = async (input, init = {}) => {+ requests.push({ url: String(input), init })+ if (String(input).endsWith("/token")) {+ return Response.json({ access_token: "global-token", expires_in: 300 })+ }+ return Response.json({ keys: [] })+ }++ try {+ const client = new CyclopsClient({+ baseUrl: "https://run.example",+ tokenUrl: "https://auth.example/token",+ clientId: "key-example",+ clientSecret: "secret",+ })++ await client.keys.keysList()++ assert.equal(requests.length, 2)+ assert.equal(requests[1].init.headers.Authorization, "Bearer global-token")+ } finally {+ globalThis.fetch = originalFetch+ }+})++test("client fails clearly when fetch is unavailable", () => {+ const originalFetch = globalThis.fetch+ globalThis.fetch = undefined++ try {+ assert.throws(+ () =>+ new CyclopsClient({+ clientId: "key-example",+ clientSecret: "secret",+ }),+ /requires Node\.js 18\+ or an injected fetch implementation/,+ )+ } finally {+ globalThis.fetch = originalFetch+ }+})diff --git a/libs/fleet/js-sdk/test/token.test.js b/libs/fleet/js-sdk/test/token.test.jsnew file mode 100644index 0000000000..b2d2f859da--- /dev/null+++ b/libs/fleet/js-sdk/test/token.test.js@@ -0,0 +1,43 @@+import assert from "node:assert/strict"+import test from "node:test"++import { ClientCredentialsTokenProvider } from "../dist/index.js"++test("token provider exchanges credentials and reuses an unexpired token", async () => {+ const requests = []+ const provider = new ClientCredentialsTokenProvider({+ tokenUrl: "https://auth.example/token",+ clientId: "key-example",+ clientSecret: "secret",+ fetch: async (input, init = {}) => {+ requests.push({ url: String(input), init })+ return Response.json({ access_token: "token-1", expires_in: 300 })+ },+ })++ assert.equal(await provider.getToken(), "token-1")+ assert.equal(await provider.getToken(), "token-1")+ assert.equal(requests.length, 1)+ assert.equal(requests[0].url, "https://auth.example/token")+ assert.equal(requests[0].init.method, "POST")+ assert.equal(requests[0].init.body.get("grant_type"), "client_credentials")+ assert.equal(requests[0].init.body.get("client_id"), "key-example")+ assert.equal(requests[0].init.body.get("client_secret"), "secret")+})++test("token provider refreshes inside the configured expiry buffer", async () => {+ let exchanges = 0+ const provider = new ClientCredentialsTokenProvider({+ tokenUrl: "https://auth.example/token",+ clientId: "key-example",+ clientSecret: "secret",+ refreshBufferMs: 30_000,+ fetch: async () => {+ exchanges += 1+ return Response.json({ access_token: `token-${exchanges}`, expires_in: 1 })+ },+ })++ assert.equal(await provider.getToken(), "token-1")+ assert.equal(await provider.getToken(), "token-2")+})diff --git a/libs/fleet/js-sdk/tsconfig.json b/libs/fleet/js-sdk/tsconfig.jsonnew file mode 100644index 0000000000..b9ac97ec16--- /dev/null+++ b/libs/fleet/js-sdk/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "strict": true,+ "declaration": true,+ "outDir": "dist",+ "rootDir": "src",+ "skipLibCheck": true+ },+ "include": ["src"]+}diff --git a/libs/fleet/nginx.conf b/libs/fleet/nginx.confnew file mode 100644index 0000000000..07f4e48cc9--- /dev/null+++ b/libs/fleet/nginx.conf@@ -0,0 +1,181 @@+# nginx config for cyclops-cs.+#+# - Serves the Vite-built SPA at /, with a try_files fallback to index.html+# so deep links like /modules/foo render correctly.+# - Proxies /api/* to the cyclops-ctrl Service inside the cluster, stripping+# the /api prefix (mirrors the dev-mode Vite proxy).+#+# `${CYCLOPS_CTRL}` and `${CYCLOPS_CS_BACKEND}` are substituted by nginx's+# envsubst at container start (default behavior of the official+# nginx:alpine image when the file is placed under /etc/nginx/templates/).++# WebSocket upgrade pass-through (used by /api/svc): forward the client's+# Upgrade header and synthesize the matching Connection header. Without+# these, nginx drops the hop-by-hop Upgrade/Connection headers and the+# upstream sees a plain GET — websockify then answers 404 instead of+# completing the 101 handshake (noVNC "Failed to connect to server").+# This file is included at http{} level (conf.d), so map is legal here.+map $http_upgrade $connection_upgrade {+ default upgrade;+ '' close;+}++server {+ listen 80;+ server_name _;++ # Static SPA.+ root /usr/share/nginx/html;+ index index.html;++ location / {+ try_files $uri $uri/ /index.html;+ }++ # OAuth discovery metadata for MCP clients (claude.ai connectors et al).+ #+ # MCP authorization (OAuth 2.1) discovers the authorization server via+ # RFC 9728 Protected Resource Metadata at this well-known path. Without+ # these blocks the SPA catch-all above answers 200 text/html for the+ # well-known paths, the client falls back to spec-default /authorize at+ # the origin — also the SPA — and the connector flow dies on the Pools+ # page.+ #+ # RFC 9728 allows a path-suffixed form+ # (/.well-known/oauth-protected-resource/api/svc/...); echo the suffix+ # back as the resource identifier so strict clients that compare+ # metadata.resource against the URL they asked about still match.+ location ~ ^/\.well-known/oauth-protected-resource(?<resource_path>/.*)?$ {+ default_type application/json;+ add_header Access-Control-Allow-Origin * always;+ return 200 '{"resource":"https://$host$resource_path","authorization_servers":["https://auth.cua.ai/realms/cyclops-cs"]}';+ }++ # Legacy fallback (pre-RFC 9728 MCP clients): authorization-server+ # metadata looked up at the resource origin. Keycloak serves the real+ # RFC 8414 document; send clients there.+ location /.well-known/oauth-authorization-server {+ return 302 https://auth.cua.ai/realms/cyclops-cs/.well-known/oauth-authorization-server;+ }++ # cyclops-cs backend — Keycloak-authenticated handlers for:+ # /api/keys — per-user API key (service-account client) management+ # /api/gateway — token-authenticated proxy to per-pool orchestrators+ # /api/k8s — SPA-authenticated proxy to the kubectl-proxy sidecar+ # (replaces the old /k8s-api/ nginx block)+ # /api/orch — SPA-authenticated proxy to per-namespace orchestrator+ # services (replaces the old /orch-api/ nginx block)+ # /api/batch — OSGym batch driver (submit/poll/results/cancel)+ # /api/label — same, label-scoped streaming variant+ #+ # Backend runs as a standalone Deployment in the same namespace; nginx+ # reaches it via the cyclops-cs-backend Service (envsubst substitutes+ # the cluster DNS URL at container start). Matched before the catch-all+ # /api/ block so cyclops-ctrl never sees these paths.+ # /api/svc — sandbox service proxy.+ #+ # Two auth paths:+ # 1. Bearer token → skip oauth2-proxy, backend validates JWT+ # 2. Browser (no Bearer) → oauth2-proxy auth_request → Keycloak+ # login → session cookie+ #+ # nginx doesn't support conditional auth_request, so we use a+ # named location (@svc_with_oauth) for the cookie path and route+ # Bearer requests directly to the backend.+ location ~ ^/api/svc(/|$) {+ # oauth2-proxy handles both Bearer tokens (--skip-jwt-bearer-tokens+ # returns 202) and cookies. No nginx if-hack needed.+ auth_request /oauth2/auth;+ auth_request_set $auth_user $upstream_http_x_auth_request_user;+ auth_request_set $auth_email $upstream_http_x_auth_request_email;+ error_page 401 = /oauth2/start?rd=$request_uri;++ proxy_pass ${CYCLOPS_CS_BACKEND};+ proxy_http_version 1.1;+ # WebSocket upgrade (noVNC /websockify et al.) — see map above.+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection $connection_upgrade;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_set_header X-Auth-Request-User $auth_user;+ proxy_set_header X-Auth-Request-Email $auth_email;+ proxy_buffering off;+ proxy_read_timeout 1h;+ proxy_send_timeout 1h;+ }++ # oauth2-proxy endpoints — auth check + login flow.+ # oauth2-proxy runs as a sidecar on the backend pod; nginx reaches+ # it via the backend Service on port 4180 (CYCLOPS_CS_OAUTH2_PROXY).+ location /oauth2/ {+ proxy_pass ${CYCLOPS_CS_OAUTH2_PROXY};+ proxy_http_version 1.1;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ # Pass the rd= query param as the redirect header so oauth2-proxy+ # redirects back to the original /api/svc URL after login.+ proxy_set_header X-Auth-Request-Redirect $arg_rd;+ }++ # oauth2-proxy auth subrequest endpoint (internal only).+ location = /oauth2/auth {+ internal;+ proxy_pass ${CYCLOPS_CS_OAUTH2_PROXY}/oauth2/auth;+ proxy_pass_request_body off;+ proxy_set_header Content-Length "";+ # Forward the Authorization header so oauth2-proxy can validate+ # Bearer tokens (--skip-jwt-bearer-tokens returns 202 for them).+ proxy_set_header Authorization $http_authorization;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ }++ # All other /api/* backend routes (no oauth2-proxy).+ location ~ ^/api/(keys|user-keys|gateway|k8s|orch|swagger|batch|label|namespaces|config)(/|$) {+ proxy_pass ${CYCLOPS_CS_BACKEND};+ proxy_http_version 1.1;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_buffering off;+ proxy_read_timeout 1h;+ proxy_send_timeout 1h;+ }++ # Runtime config for the SPA — generated by envsubst at container start+ # so we don't have to bake KC_URL / KC_REALM into the Vite bundle.+ # Loaded from index.html before the React entry point; AuthProvider+ # reads window.__CYCLOPS_CS_CFG__.+ location = /config.js {+ default_type application/javascript;+ return 200 'window.__CYCLOPS_CS_CFG__=${CYCLOPS_CS_CONFIG_JSON};';+ }++ # API proxy — mirrors the /api → cyclops-ctrl rewrite from vite.config.ts.+ location /api/ {+ proxy_pass ${CYCLOPS_CTRL}/;+ proxy_http_version 1.1;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ # SSE endpoints (cyclops streams resources/logs); disable buffering.+ proxy_buffering off;+ proxy_read_timeout 1h;+ proxy_send_timeout 1h;+ }++ # The previous /k8s-api/ and /orch-api/ blocks were removed — both are+ # now served by the cyclops-cs-backend Deployment at /api/k8s and+ # /api/orch with Keycloak SSO + OPA authorization in front. The+ # kubectl-proxy container moved with the backend (it talks to it on+ # 127.0.0.1:8001 to inherit the backend pod's ServiceAccount K8s+ # credentials).+}diff --git a/libs/fleet/package.json b/libs/fleet/package.jsonnew file mode 100644index 0000000000..721dc0ccba--- /dev/null+++ b/libs/fleet/package.json@@ -0,0 +1,43 @@+{+ "name": "cyclops-cs",+ "private": true,+ "version": "0.0.1",+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "tsc -b && vite build",+ "preview": "vite preview",+ "typecheck": "tsc -b --noEmit",+ "lint": "biome check",+ "lint:fix": "biome check --write",+ "test:e2e": "playwright test",+ "test:e2e:ui": "playwright test --ui",+ "gen:api": "swagger-typescript-api generate -p ./backend/docs/swagger.json -o ./src/api/generated -n cyclops-cs-backend.ts --module-name-index 1 --extract-request-body --extract-request-params --extract-response-body --extract-response-error"+ },+ "dependencies": {+ "@cloudscape-design/collection-hooks": "^1.0.93",+ "@cloudscape-design/components": "^3.0.825",+ "@cloudscape-design/global-styles": "^1.0.36",+ "@novnc/novnc": "^1.7.0",+ "ansi-to-html": "^0.7.2",+ "keycloak-js": "^25.0.6",+ "react": "^18.3.1",+ "react-dom": "^18.3.1",+ "react-router-dom": "^6.28.0"+ },+ "devDependencies": {+ "@biomejs/biome": "^2.4.15",+ "@playwright/test": "^1.60.0",+ "@types/react": "^18.3.12",+ "@types/react-dom": "^18.3.1",+ "@vitejs/plugin-react": "^4.3.4",+ "swagger-typescript-api": "13.2.7",+ "typescript": "^5.7.2",+ "vite": "^5.4.11"+ },+ "pnpm": {+ "patchedDependencies": {+ "@novnc/[email protected]": "patches/@[email protected]"+ }+ }+}diff --git a/libs/fleet/patches/@[email protected] b/libs/fleet/patches/@[email protected]new file mode 100644index 0000000000..d93fcbb303--- /dev/null+++ b/libs/fleet/patches/@[email protected]@@ -0,0 +1,23 @@+diff --git a/core/display.js b/core/display.js+index 4efd6f4b97dfda3ab450723ff8c722c8258d60fc..e20a68db8da2d9b26ac288a7ef15ff8b83ef69e0 100644+--- a/core/display.js++++ b/core/display.js+@@ -411,6 +411,8 @@ export default class Display {+ let data = new Uint8ClampedArray(arr.buffer,+ arr.byteOffset + offset,+ width * height * 4);++ // trycua: macOS VM framebuffers arrive BGR; swap R/B per pixel.++ for (let _i = 0; _i < data.length; _i += 4) { const _r = data[_i]; data[_i] = data[_i + 2]; data[_i + 2] = _r; }+ let img = new ImageData(data, width, height);+ this._drawCtx.putImageData(img, x, y);+ this._damage(x, y, width, height);+@@ -472,7 +474,8 @@ export default class Display {+ }++ _setFillColor(color) {+- const newStyle = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')';++ // trycua: macOS VM framebuffers arrive BGR; swap R/B so colors render correctly.++ const newStyle = 'rgb(' + color[2] + ',' + color[1] + ',' + color[0] + ')';+ if (newStyle !== this._prevDrawStyle) {+ this._drawCtx.fillStyle = newStyle;+ this._prevDrawStyle = newStyle;diff --git a/libs/fleet/playwright.config.ts b/libs/fleet/playwright.config.tsnew file mode 100644index 0000000000..9fd838cbd7--- /dev/null+++ b/libs/fleet/playwright.config.ts@@ -0,0 +1,23 @@+import { defineConfig } from "@playwright/test"++export default defineConfig({+ testDir: "./e2e",+ timeout: 30_000,+ retries: 0,+ use: {+ baseURL: "http://localhost:5180",+ headless: true,+ },+ webServer: {+ command: "pnpm dev",+ port: 5180,+ reuseExistingServer: true,+ timeout: 30_000,+ },+ projects: [+ {+ name: "chromium",+ use: { browserName: "chromium" },+ },+ ],+})diff --git a/libs/fleet/pnpm-lock.yaml b/libs/fleet/pnpm-lock.yamlnew file mode 100644index 0000000000..9fde5564ed--- /dev/null+++ b/libs/fleet/pnpm-lock.yaml@@ -0,0 +1,2131 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++patchedDependencies:+ '@novnc/[email protected]':+ hash: c119c00d14c51f940f1ebed4fe41ad2fe1358c63e1095baa39d11d696b66dbff+ path: patches/@[email protected]++importers:++ .:+ dependencies:+ '@cloudscape-design/collection-hooks':+ specifier: ^1.0.93+ version: 1.0.93([email protected])+ '@cloudscape-design/components':+ specifier: ^3.0.825+ '@cloudscape-design/global-styles':+ specifier: ^1.0.36+ version: 1.0.58+ '@novnc/novnc':+ specifier: ^1.7.0+ version: 1.7.0(patch_hash=c119c00d14c51f940f1ebed4fe41ad2fe1358c63e1095baa39d11d696b66dbff)+ ansi-to-html:+ specifier: ^0.7.2+ version: 0.7.2+ keycloak-js:+ specifier: ^25.0.6+ version: 25.0.6+ react:+ specifier: ^18.3.1+ version: 18.3.1+ react-dom:+ specifier: ^18.3.1+ version: 18.3.1([email protected])+ react-router-dom:+ specifier: ^6.28.0+ devDependencies:+ '@biomejs/biome':+ specifier: ^2.4.15+ version: 2.4.15+ '@playwright/test':+ specifier: ^1.60.0+ version: 1.60.0+ '@types/react':+ specifier: ^18.3.12+ version: 18.3.28+ '@types/react-dom':+ specifier: ^18.3.1+ version: 18.3.7(@types/[email protected])+ '@vitejs/plugin-react':+ specifier: ^4.3.4+ version: 4.7.0([email protected])+ swagger-typescript-api:+ specifier: 13.2.7+ version: 13.2.7+ typescript:+ specifier: ^5.7.2+ version: 5.9.3+ vite:+ specifier: ^5.4.11+ version: 5.4.21++packages:++ '@babel/[email protected]':+ resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-LIVqM46zQWZhj17qA8wb4nW/ixr2y1Nw+r1etiAWgRM6U1IqP+LNhL1yg440jYZR72jCWcWbLWzIosH+uP1fqg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0++ '@babel/[email protected]':+ resolution: {integrity: sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-b3ctpQwp+PROvU/cttc4OYl4MzfJUWy6FZg+PMXfzmt/+39iHVF0sDfqay8TQM3JA2EUOyKcFZt75jWriQijsA==}+ engines: {node: '>=6.0.0'}+ hasBin: true++ '@babel/[email protected]':+ resolution: {integrity: sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}+ engines: {node: '>=6.9.0'}++ '@biomejs/[email protected]':+ resolution: {integrity: sha512-j5VH3a/h/HXTKBM50MDMxRCzkeLv9S2XJcW2WgnZT1+xyisi+0bISrXR82gCX+8S9lvK0skEvHJRN+3Ktr2hlw==}+ engines: {node: '>=14.21.3'}+ hasBin: true++ '@biomejs/[email protected]':+ resolution: {integrity: sha512-rF3PPqLq1yoST79zaQbDjVJwsuIeci/O+9bgNmC5QpgOqz6aqYuzA4abyAGx+mgyiDXn4A049xAN8gijbuR1Qg==}+ engines: {node: '>=14.21.3'}+ cpu: [arm64]+ os: [darwin]++ '@biomejs/[email protected]':+ resolution: {integrity: sha512-/5KHXYMfSJs1fNXiX30xFtI8JcCFV6zaVVLxOa0M2sfqBKHkpQhRTv94yxQWxeTY2lzo2OuTlNvPC+hDQt2wcQ==}+ engines: {node: '>=14.21.3'}+ cpu: [x64]+ os: [darwin]++ '@biomejs/[email protected]':+ resolution: {integrity: sha512-ZPcxznxm0pogHBLZhYntyR3sR+MrZjqJIKEr7ZqVen0Rl+P/4upVmfYXjftizi9RoqZntg33fv/1fbdhbYXpEQ==}+ engines: {node: '>=14.21.3'}+ cpu: [arm64]+ os: [linux]++ '@biomejs/[email protected]':+ resolution: {integrity: sha512-owaAMZD/T4LrD0ELNCk0Km3qrRHuM0X6EAyVE1FSqGY0rbLoiDLrO4Us2tllm6cAeB2Ioa9C2C08NZPdr8+0Ug==}+ engines: {node: '>=14.21.3'}+ cpu: [arm64]+ os: [linux]++ '@biomejs/[email protected]':+ resolution: {integrity: sha512-CNq/9W38SYSH023lfcQ4KKU8K0YX8T//FZUhcgtMMRABDojx5XsMV7jlweAvGSl389wJQB29Qo6Zb/a+jdvt+w==}+ engines: {node: '>=14.21.3'}+ cpu: [x64]+ os: [linux]++ '@biomejs/[email protected]':+ resolution: {integrity: sha512-0jj7THz12GbUOLmMibktK6DZjqz2zV64KFxyBtcFTKPiiOIY0a7vns1elpO1dERvxpsZ5ik0oFfz0oGwFde1+g==}+ engines: {node: '>=14.21.3'}+ cpu: [x64]+ os: [linux]++ '@biomejs/[email protected]':+ resolution: {integrity: sha512-ouhkYdlhp/1GghEJPdWwD/Vi3gQ1nFxuSpMolWsbq3Lsq3QUR4jl6UdhhscdCugKU5vOEuMiJhvKj66O0OCq+w==}+ engines: {node: '>=14.21.3'}+ cpu: [arm64]+ os: [win32]++ '@biomejs/[email protected]':+ resolution: {integrity: sha512-zBrGq5mx5wwpnow4+2BxUvleDM+GNd4sLbPaMapsSLQLD0NGRCquqPBTgN+7XkUteHvj7M+BstuI8tmnV7+HgQ==}+ engines: {node: '>=14.21.3'}+ cpu: [x64]+ os: [win32]++ '@biomejs/[email protected]':+ resolution: {integrity: sha512-69OfQ7+09AtiCIg+k+aU3rEsGit5o/SJWCS3BeBH/2nJYdJGi0cIx+ybka8i1EK69aNcZxYO1y1iAAEmYMq1HA==}+ peerDependencies:+ '@biomejs/wasm-bundler': ^2.0.0+ '@biomejs/wasm-nodejs': ^2.0.0+ '@biomejs/wasm-web': ^2.0.0+ peerDependenciesMeta:+ '@biomejs/wasm-bundler':+ optional: true+ '@biomejs/wasm-nodejs':+ optional: true+ '@biomejs/wasm-web':+ optional: true++ '@biomejs/[email protected]':+ resolution: {integrity: sha512-pihpBMylewgDdGFZHRkgmc3OajuGIJPXhvfYuKCNK/CWyJMrYEFmPKs8Iq1kY0sYMmGlTbD4K2udV03KYa+r0Q==}++ '@cloudscape-design/[email protected]':+ resolution: {integrity: sha512-77khCT0cwxxEddRxfsvuZNlrlu/Qk2CNPm+tMsMTXoL1/n4mrDKQh/AA0sbnvCga7m4g9xS3kW27RfN1H9eu1Q==}+ peerDependencies:+ react: '>=16.8.0'++ '@cloudscape-design/[email protected]':+ resolution: {integrity: sha512-tMne0Tefzq75n0w+Y1akTT7M4iZZYMYAVGNrw06wRagJeSoGJH0VCWd0nnDPj/vmCJOwxn0K27p1meNe724u/w==}+ peerDependencies:+ react: '>=16.8.0'++ '@cloudscape-design/[email protected]':+ resolution: {integrity: sha512-TSMs/YkXNqUSbe55GDlAQ+UAdcOv1aJldjXlkCWJEqZiyoFvS58AhevP2vFgPsoy2RrX8/sCa0/BZJFv4jLkSA==}+ peerDependencies:+ react: '>=16.8.0'++ '@cloudscape-design/[email protected]':+ resolution: {integrity: sha512-iyAxmsCqPvHKfiG7pSlyjiuzAFjojfnsWiHRGwsz/FnkVPGXk5gdlgrs0Q9lNfaFP/XGZZKE40c5ZixvO5pvMA==}++ '@cloudscape-design/[email protected]':+ resolution: {integrity: sha512-c9abt/vnYykkL+LF0nwxFk+Yyr1fsURsrWv9ArMPp47Jt+SlxRFo4+RLkwvu0+Yd2IeCMIKJdZjNxUnBguUA/Q==}++ '@cloudscape-design/[email protected]':+ resolution: {integrity: sha512-zPE/wkrnjNAut5e3JmAEJ0QWS8firOWzwq4Hzh02KPQr9YDj1tABzcxqXda37NzpTG+/UEgud+39RQiCATJdkw==}++ '@dnd-kit/[email protected]':+ resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==}+ peerDependencies:+ react: '>=16.8.0'++ '@dnd-kit/[email protected]':+ resolution: {integrity: sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==}+ peerDependencies:+ react: '>=16.8.0'+ react-dom: '>=16.8.0'++ '@dnd-kit/[email protected]':+ resolution: {integrity: sha512-wDkBHHf9iCi1veM834Gbk1429bd4lHX4RpAwT0y2cHLf246GAvU2sVw/oxWNpPKQNQRQaeGXhAVgrOl1IT+iyA==}+ peerDependencies:+ '@dnd-kit/core': ^6.0.7+ react: '>=16.8.0'++ '@dnd-kit/[email protected]':+ resolution: {integrity: sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==}+ peerDependencies:+ react: '>=16.8.0'++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==}+ engines: {node: '>=12'}+ cpu: [ppc64]+ os: [aix]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==}+ engines: {node: '>=12'}+ cpu: [arm64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==}+ engines: {node: '>=12'}+ cpu: [arm]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==}+ engines: {node: '>=12'}+ cpu: [x64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==}+ engines: {node: '>=12'}+ cpu: [arm64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==}+ engines: {node: '>=12'}+ cpu: [x64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==}+ engines: {node: '>=12'}+ cpu: [arm64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==}+ engines: {node: '>=12'}+ cpu: [x64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==}+ engines: {node: '>=12'}+ cpu: [arm64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==}+ engines: {node: '>=12'}+ cpu: [arm]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==}+ engines: {node: '>=12'}+ cpu: [ia32]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==}+ engines: {node: '>=12'}+ cpu: [loong64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==}+ engines: {node: '>=12'}+ cpu: [mips64el]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==}+ engines: {node: '>=12'}+ cpu: [ppc64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==}+ engines: {node: '>=12'}+ cpu: [riscv64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==}+ engines: {node: '>=12'}+ cpu: [s390x]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==}+ engines: {node: '>=12'}+ cpu: [x64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==}+ engines: {node: '>=12'}+ cpu: [x64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==}+ engines: {node: '>=12'}+ cpu: [x64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==}+ engines: {node: '>=12'}+ cpu: [x64]+ os: [sunos]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==}+ engines: {node: '>=12'}+ cpu: [arm64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==}+ engines: {node: '>=12'}+ cpu: [ia32]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==}+ engines: {node: '>=12'}+ cpu: [x64]+ os: [win32]++ '@exodus/[email protected]':+ resolution: {integrity: sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==}++ '@formatjs/[email protected]':+ resolution: {integrity: sha512-HJnTFeRM2kVFVr5gr5kH1XP6K0JcJtE7Lzvtr3FS/so5f1kpsqqqxy5JF+FRaO6H2qmcMfAUIox7AJteieRtVw==}++ '@formatjs/[email protected]':+ resolution: {integrity: sha512-Yabmi9nSvyOMrlSeGGWDiH7rf3a7sIwplbvo/dlz9WCIjzIQAfy1RMf4S0X3yG724n5Ghu2GmEl5NJIV6O9sZQ==}++ '@formatjs/[email protected]':+ resolution: {integrity: sha512-7kR78cRrPNB4fjGFZg3Rmj5aah8rQj9KPzuLsmcSn4ipLXQvC04keycTI1F7kJYDwIXtT2+7IDEto842CfZBtw==}++ '@formatjs/[email protected]':+ resolution: {integrity: sha512-H13E9Xl+PxBd8D5/6TVUluSpxGNvFSlN/b3coUp0e0JpuWXXnQDiavIpY3NnvSp4xhEMoXyyBvVfdFX8jglOHQ==}++ '@formatjs/[email protected]':+ resolution: {integrity: sha512-XOMO2Hupl0wdd172Y06h6kLpBz6Dv+J4okPLl4LPtzbr8f66WbIoy4ev98EBuZ6ZK4h5ydTN6XneT4QVpD7cdA==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}+ engines: {node: '>=6.0.0'}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}++ '@material/[email protected]':+ resolution: {integrity: sha512-ztmtTd6xwnuh2/xu+Vb01btgV8SQWYCaK56CkRK8gEkWe5TuDyBcYJ0wgkMRn+2VcE9KUmhvkz+N9GHrqw/C0g==}++ '@novnc/[email protected]':+ resolution: {integrity: sha512-ucEJOx4T2avIRCleodk7YobZj5O2Ga2AeLfQ69A/yjG9HHba2+PDgwSkN3FttrmG+70ZGx21sElNFouK13RzyA==}++ '@playwright/[email protected]':+ resolution: {integrity: sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==}+ engines: {node: '>=18'}+ hasBin: true++ '@remix-run/[email protected]':+ resolution: {integrity: sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==}+ engines: {node: '>=14.0.0'}++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==}++ '@rollup/[email protected]':+ resolution: {integrity: sha512-x35CNW/ANXG3hE/EZpRU8MXX1JDN86hBb2wMGAtltkz7pc6cxgjpy1OMMfDosOQ+2hWqIkag/fGok1Yady9nGw==}+ cpu: [arm]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-xw3xtkDApIOGayehp2+Rz4zimfkaX65r4t47iy+ymQB2G4iJCBBfj0ogVg5jpvjpn8UWn/+q9tprxleYeNp3Hw==}+ cpu: [arm64]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-vo6Y5Qfpx7/5EaamIwi0WqW2+zfiusVihKatLvtN1VFVy3D13uERk/6gZLU1UiHRL6fDXqj/ELIeVRGnvcTE1g==}+ cpu: [arm64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-D+0QGcZhBzTN82weOnsSlY7V7+RMmPuF1CkbxyMAGE8+ZHeUjyb76ZiWmBlCu//AQQONvxcqRbwZTajZKqjuOw==}+ cpu: [x64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-6HnvHCT7fDyj6R0Ph7A6x8dQS/S38MClRWeDLqc0MdfWkxjiu1HSDYrdPhqSILzjTIC/pnXbbJbo+ft+gy/9hQ==}+ cpu: [arm64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-KHLgC3WKlUYW3ShFKnnosZDOJ0xjg9zp7au3sIm2bs/tGBeC2ipmvRh/N7JKi0t9Ue20C0dpEshi8WUubg+cnA==}+ cpu: [x64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-DV6fJoxEYWJOvaZIsok7KrYl0tPvga5OZ2yvKHNNYyk/2roMLqQAbGhr78EQ5YhHpnhLKJD3S1WFusAkmUuV5g==}+ cpu: [arm]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-mQKoJAzvuOs6F+TZybQO4GOTSMUu7v0WdxEk24krQ/uUxXoPTtHjuaUuPmFhtBcM4K0ons8nrE3JyhTuCFtT/w==}+ cpu: [arm]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-Whjj2qoiJ6+OOJMGptTYazaJvjOJm+iKHpXQM1P3LzGjt7Ff++Tp7nH4N8J/BUA7R9IHfDyx4DJIflifwnbmIA==}+ cpu: [arm64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-4YTNHKqGng5+yiZt3mg77nmyuCfmNfX4fPmyUapBcIk+BdwSwmCWGXOUxhXbBEkFHtoN5boLj/5NON+u5QC9tg==}+ cpu: [arm64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-SU3kNlhkpI4UqlUc2VXPGK9o886ZsSeGfMAX2ba2b8DKmMXq4AL7KUrkSWVbb7koVqx41Yczx6dx5PNargIrEA==}+ cpu: [loong64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-6lDLl5h4TXpB1mTf2rQWnAk/LcXrx9vBfu/DT5TIPhvMhRWaZ5MxkIc8u4lJAmBo6klTe1ywXIUHFjylW505sg==}+ cpu: [loong64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-BMo8bOw8evlup/8G+cj5xWtPyp93xPdyoSN16Zy90Q2QZ0ZYRhCt6ZJSwbrRzG9HApFabjwj2p25TUPDWrhzqQ==}+ cpu: [ppc64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-E0L8X1dZN1/Rph+5VPF6Xj2G7JJvMACVXtamTJIDrVI44Y3K+G8gQaMEAavbqCGTa16InptiVrX6eM6pmJ+7qA==}+ cpu: [ppc64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-oZJ/WHaVfHUiRAtmTAeo3DcevNsVvH8mbvodjZy7D5QKvCefO371SiKRpxoDcCxB3PTRTLayWBkvmDQKTcX/sw==}+ cpu: [riscv64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-Dhbyh7j9FybM3YaTgaHmVALwA8AkUwTPccyCQ79TG9AJUsMQqgN1DDEZNr4+QUfwiWvLDumW5vdwzoeUF+TNxQ==}+ cpu: [riscv64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-cJd1X5XhHHlltkaypz1UcWLA8AcoIi1aWhsvaWDskD1oz2eKCypnqvTQ8ykMNI0RSmm7NkTdSqSSD7zM0xa6Ig==}+ cpu: [s390x]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-DAZDBHQfG2oQuhY7mc6I3/qB4LU2fQCjRvxbDwd/Jdvb9fypP4IJ4qmtu6lNjes6B531AI8cg1aKC2di97bUxA==}+ cpu: [x64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-cRxsE8c13mZOh3vP+wLDxpQBRrOHDIGOWyDL93Sy0Ga8y515fBcC2pjUfFwUe5T7tqvTvWbCpg1URM/AXdWIXA==}+ cpu: [x64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-QaWcIgRxqEdQdhJqW4DJctsH6HCmo5vHxY0krHSX4jMtOqfzC+dqDGuHM87bu4H8JBeibWx7jFz+h6/4C8wA5Q==}+ cpu: [x64]+ os: [openbsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-AaXwSvUi3QIPtroAUw1t5yHGIyqKEXwH54WUocFolZhpGDruJcs8c+xPNDRn4XiQsS7MEwnYsHW2l0MBLDMkWg==}+ cpu: [arm64]+ os: [openharmony]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-65LAKM/bAWDqKNEelHlcHvm2V+Vfb8C6INFxQXRHCvaVN1rJfwr4NvdP4FyzUaLqWfaCGaadf6UbTm8xJeYfEg==}+ cpu: [arm64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-EEM2gyhBF5MFnI6vMKdX1LAosE627RGBzIoGMdLloPZkXrUN0Ckqgr2Qi8+J3zip/8NVVro3/FjB+tjhZUgUHA==}+ cpu: [ia32]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-E5Eb5H/DpxaoXH++Qkv28RcUJboMopmdDUALBczvHMf7hNIxaDZqwY5lK12UK1BHacSmvupoEWGu+n993Z0y1A==}+ cpu: [x64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-hPt/bgL5cE+Qp+/TPHBqptcAgPzgj46mPcg/16zNUmbQk0j+mOEQV/+Lqu8QRtDV3Ek95Q6FeFITpuhl6OTsAA==}+ cpu: [x64]+ os: [win32]++ '@types/[email protected]':+ resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==}++ '@types/[email protected]':+ resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==}++ '@types/[email protected]':+ resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}++ '@types/[email protected]':+ resolution: {integrity: sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==}+ peerDependencies:+ '@types/react': ^18.0.0++ '@types/[email protected]':+ resolution: {integrity: sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-T92Xav+Gf/Ik1uPW581nA+JftmjWPgskw/WBf4TJzxRG/SJ+DfNnNE+WuZ4mrXuzflQMqMkm1LSYjzYW7MB1Cg==}++ '@vitejs/[email protected]':+ resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==}+ engines: {node: ^14.18.0 || >=16.0.0}+ peerDependencies:+ vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0++ resolution: {integrity: sha512-L1ddibQ7F3vyXR2k2fg+I8TQTPWVA6CKeDQr/h2+8CeyTp3W6EQL8xNFZRTztuP8xNOAqL3IYPqdzs31GCjDvg==}++ resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-v6MqmEpNlxF+POuyhKkidusCHWWkaLcGRURzivcU3I9tv7k4JVhFcnukrM5Rlk2rUywdZuzYAZ+kbZqWCnfN3g==}+ engines: {node: '>=8.0.0'}+ hasBin: true++ resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}++ resolution: {integrity: sha512-Ic44hnOtFIgravCunj1ifSoQPSUrkNiJuH9Mf6jr2jjoA74icqV8wU0KuadXeOR8zuIJMOoTv0GuQjZ9ZYNMeA==}+ engines: {node: '>=6.0.0'}+ hasBin: true++ resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==}+ engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}+ hasBin: true++ resolution: {integrity: sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA==}+ peerDependencies:+ magicast: '*'+ peerDependenciesMeta:+ magicast:+ optional: true++ resolution: {integrity: sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==}++ resolution: {integrity: sha512-hVLMUZFgR4JJ6ACt1uEESvQN1/dBVqPAKY0hgrV70eN3391K6juAfTjKZLKvOMsx8PxA7gsY1/tLMMTcfFLLpw==}++ resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==}+ engines: {node: '>= 20.19.0'}++ resolution: {integrity: sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==}++ resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}+ engines: {node: '>=7.0.0'}++ resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}++ resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==}++ resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}+ engines: {node: ^14.18.0 || >=16.10.0}++ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}++ resolution: {integrity: sha512-Jd6Ig3/pe62/qe5SBPTN8h8LeUg/pT4lLgtavPf7updwwHpvFzxvOQBHYj2LZDMjUnBzgvIUSjRcf6oT5HzHFg==}++ resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}++ resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}+ engines: {node: '>=4'}+ hasBin: true++ resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}++ resolution: {integrity: sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==}++ resolution: {integrity: sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==}++ resolution: {integrity: sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==}+ engines: {node: '>=0.11'}++ resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}+ engines: {node: '>=6.0'}+ peerDependencies:+ supports-color: '*'+ peerDependenciesMeta:+ supports-color:+ optional: true++ resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==}++ resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==}++ resolution: {integrity: sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==}++ resolution: {integrity: sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==}++ resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-kOrWphBi8TOZyiJZqsgqIle0lw+tzmnQK83pV9dZUd01Nm2POECSyFQMAuarzZdYqQW7FH9RaYOuaRo3h+bQ3w==}++ resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}++ resolution: {integrity: sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==}++ resolution: {integrity: sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==}++ resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==}+ engines: {node: '>=12'}+ hasBin: true++ resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-UVQ72Rqjy/ZKQalzV5dCCJP80GrmPrMxh6NlNf+erV6ObL0ZFkhCstWRawS85z3smdr3d2wXPsZEY7rDPfGd2g==}+ engines: {node: '>=6.0.0'}++ resolution: {integrity: sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==}++ resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}++ resolution: {integrity: sha512-483XLLxTVIwWK3QTrMGRqUfUpoOs/0hbQrl2oz4J0pAcm3A3bu84wxTFqGqkJzewCLdME38xJLJAxBABfQT8sQ==}++ resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}+ os: [darwin]++ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}+ os: [darwin]++ resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}+ engines: {node: '>=6.9.0'}++ resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}+ engines: {node: 6.* || 8.* || >= 10.*}++ resolution: {integrity: sha512-GvHTWcykIR/fP8cj8dMpuMMkvaeJfPvYnhq0oW+chSeIr+ldX21ifU2Ms6KBoyKZQZmVaUAAhQ2EZ68KJF8a7A==}+ hasBin: true++ resolution: {integrity: sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA==}++ resolution: {integrity: sha512-m3Ofv/X/tV8Y3tHXLohcuVuhWKo7BBq62cqY15etqmLxg2DZ34AGGgQDeR+SCta2+zICb1NX83af0GJmbQ1++g==}++ resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}+ hasBin: true++ resolution: {integrity: sha512-o6WSo/LUvY2uC4j7mO50a2ms7E/EAdbP0swigLV+nzHKTTaYnaLIWJ02VdXrsJX0vGedDESQnLsOekr94ryfjg==}++ resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}++ resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==}+ hasBin: true++ resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}+ engines: {node: '>=6'}+ hasBin: true++ resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}+ engines: {node: '>=6'}+ hasBin: true++ resolution: {integrity: sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-Km+dc+XfNvY6a4az5jcxTK0zPk52ns9mAxLrHj7lF3V+riVYvQujfHmhayltJDjEpSOJ4C8a57LFNNKnNnRP2g==}++ resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}++ resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}+ hasBin: true++ resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}++ resolution: {integrity: sha512-3ZH4UWBGpAwCKdfjynLQpUDVZWMe6vRHwarIpMdGLUp89CVR9hjzgyWERtMyqx+fPEqQ/PsAxFwvwPxLFxW40A==}+ engines: {node: '>=12.13.0'}++ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}++ resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==}+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}+ hasBin: true++ resolution: {integrity: sha512-v+KEsUv2ps74PaSKv0gHTxTCgMXOIfBEbaqa6w6ISIGC7ZsvHN4N9oJ8d4cmf0n5oTzQz2SLmThbQWhjd/8eKg==}+ engines: {node: ^18 || >=20}+ hasBin: true++ resolution: {integrity: sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==}+ engines: {node: 4.x || >=6.0.0}++ resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}+ engines: {node: 4.x || >=6.0.0}+ peerDependencies:+ encoding: ^0.1.0+ peerDependenciesMeta:+ encoding:+ optional: true++ resolution: {integrity: sha512-SU00ZarexNlE4Rjdm83vglt5Y9yiQ+XI1XpflWlb7q7UTN1JUItm69xMeiQCTxtTfnzt+83T8Cx+vI2ED++VDA==}++ resolution: {integrity: sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==}++ resolution: {integrity: sha512-pJTS2+T0oGIwgjGpw7sIRU8RQMcUoKCDWFLdBqKB2BNmGpbBMH2sdqAaOXUg8OzonZHU0L7vfJu1mJFEiYDWOQ==}++ resolution: {integrity: sha512-KEGjPDVoU5K6swgo9hJVA/qYGlwfbFx+Kg2QB/kd7rzV5N8N5Mg6PlsoCMohVnQmo+pzJap/F610qTodKzecGQ==}++ resolution: {integrity: sha512-Yx5PWQNZomfEhPPOphFbZKi9W93CocQj18NlD2Pa4GWZzdZpSJvYwoiuurRI7m3SpcChrnO08hkuQDL3FGsVFQ==}+ hasBin: true++ resolution: {integrity: sha512-2yucenq1a9YPmeNExoUa9Qwrt9RFkjqaMAA1X+U7sbb0AqBeTIdMHky9SQQ6iN94bO5NW0W4TRYXerG+BdAvAQ==}++ resolution: {integrity: sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==}++ resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==}++ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}++ resolution: {integrity: sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==}++ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}++ resolution: {integrity: sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg==}++ resolution: {integrity: sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-SoSL4+OSEtR99LHFZQiJLkT59C5B1amGO1NzTwj7TT1qCUgUO6hxOvzkOYxD+vMrXBM3XJIKzokoERdqQq/Zmg==}+ engines: {node: ^10 || ^12 || >=14}++ resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}++ resolution: {integrity: sha512-gMDyleLWVE+i6Sgtc0QbbY6pEKqYs97NGi6isHQPqYlLemPoO8dxQ3uGi0f4NiP98c+jMW6cG1Kx9dDwfvqARQ==}++ resolution: {integrity: sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==}+ peerDependencies:+ react: ^18.3.1++ resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}++ resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==}++ resolution: {integrity: sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==}+ engines: {node: '>=14.0.0'}+ peerDependencies:+ react: '>=16.8'+ react-dom: '>=16.8'++ resolution: {integrity: sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==}+ engines: {node: '>=14.0.0'}+ peerDependencies:+ react: '>=16.8'++ resolution: {integrity: sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==}+ peerDependencies:+ react: '>=16.6.0'+ react-dom: '>=16.6.0'++ resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==}+ engines: {node: '>= 20.19.0'}++ resolution: {integrity: sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==}++ resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-pAQK9HalE84QSm4Po3EmWIZPd3FnjkShVkiMlz1iligWYkWQ7wHYd1PF/T7QZ5TVSD6uSTon5gBVMSM4JfBV+A==}+ engines: {node: '>=18.0.0', npm: '>=8.0.0'}+ hasBin: true++ resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==}++ resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}+ hasBin: true++ resolution: {integrity: sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==}++ resolution: {integrity: sha512-hZ58adtulAk0gKtua7QxevgUaXTTXxIi8t41L3zo9AHvjXO1/7sdLECuHeIN2SRtYXpNkmhoUP2pdeWgricQ+Q==}++ resolution: {integrity: sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==}++ resolution: {integrity: sha512-MdAsTu3n25yDbIe1NeN69G4n6mUnJGtSJHygX3+oN0ZbO3DTiATnf7XnYJdGT42JCXurTb1JI0qOBR65shvhPQ==}++ resolution: {integrity: sha512-oXF8tfxx5cDk8r2kYqlkUJzZpDBqVY/II2WhvU0n9Y3XYvAYRmeaf1PvvIvTgPnv4KJ+ES5M0PyDq5Jp+Ygy2g==}++ resolution: {integrity: sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==}++ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-rCC0NWGKr/IJhtRuPq/t37qvZHI/mH4I4sxflVM+qgVe5Z2uOCivzWaVbuioJaB61kvm5UvB7b49E+oBY0M8jA==}++ resolution: {integrity: sha512-rfqqoRFpZJPl477M/snMJPM90EvI8WqhuUHSF5ecC2r/w376T29+QXNJFVPsJmbFu5rBc/8m3vhArtMctjONdw==}+ engines: {node: '>=20'}+ hasBin: true++ resolution: {integrity: sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==}+ hasBin: true++ resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==}++ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}++ resolution: {integrity: sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==}+ engines: {node: '>=14.17'}+ hasBin: true++ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}+ engines: {node: '>=14.17'}+ hasBin: true++ resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}+ hasBin: true+ peerDependencies:+ browserslist: '>= 4.21.0'++ resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==}+ engines: {node: ^18.0.0 || >=20.0.0}+ hasBin: true+ peerDependencies:+ '@types/node': ^18.0.0 || >=20.0.0+ less: '*'+ lightningcss: ^1.21.0+ sass: '*'+ sass-embedded: '*'+ stylus: '*'+ sugarss: '*'+ terser: ^5.4.0+ peerDependenciesMeta:+ '@types/node':+ optional: true+ less:+ optional: true+ lightningcss:+ optional: true+ sass:+ optional: true+ sass-embedded:+ optional: true+ stylus:+ optional: true+ sugarss:+ optional: true+ terser:+ optional: true++ resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}++ resolution: {integrity: sha512-ZO3I7c7J9nwGN1PZKZeBYAsuwWEsCOZi5T68cQoVNYrzrpp5Br0Bgi0OF4l8kH/Ez7nKfxa5mSsXjsgris3+qg==}++ resolution: {integrity: sha512-HjYc14IQUwDcnGICuc8tVtqAd6EFpoAQMqgrqcNtWWZB+F1b7iTq44GzwM1qvnH4upFgbhJsaNHuK93NOFheSg==}++ resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}++ resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}++ resolution: {integrity: sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}+ engines: {node: '>=12'}++snapshots:++ '@babel/[email protected]':+ dependencies:+ '@babel/helper-validator-identifier': 7.28.5+ js-tokens: 4.0.0+ picocolors: 1.1.1++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.0+ '@babel/generator': 7.29.1+ '@babel/helper-compilation-targets': 7.28.6+ '@babel/helper-module-transforms': 7.28.6(@babel/[email protected])+ '@babel/helpers': 7.29.2+ '@babel/parser': 7.29.3+ '@babel/template': 7.28.6+ '@babel/traverse': 7.29.0+ '@babel/types': 7.29.0+ '@jridgewell/remapping': 2.3.5+ convert-source-map: 2.0.0+ debug: 4.4.3+ gensync: 1.0.0-beta.2+ json5: 2.2.3+ semver: 6.3.1+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]':+ dependencies:+ '@babel/parser': 7.29.3+ '@babel/types': 7.29.0+ '@jridgewell/gen-mapping': 0.3.13+ '@jridgewell/trace-mapping': 0.3.31+ jsesc: 3.1.0++ '@babel/[email protected]':+ dependencies:+ '@babel/compat-data': 7.29.3+ '@babel/helper-validator-option': 7.27.1+ browserslist: 4.28.2+ lru-cache: 5.1.1+ semver: 6.3.1++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/traverse': 7.29.0+ '@babel/types': 7.29.0+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected](@babel/[email protected])':+ dependencies:+ '@babel/core': 7.29.0+ '@babel/helper-module-imports': 7.28.6+ '@babel/helper-validator-identifier': 7.28.5+ '@babel/traverse': 7.29.0+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/template': 7.28.6+ '@babel/types': 7.29.0++ '@babel/[email protected]':+ dependencies:+ '@babel/types': 7.29.0++ '@babel/[email protected](@babel/[email protected])':+ dependencies:+ '@babel/core': 7.29.0+ '@babel/helper-plugin-utils': 7.28.6++ '@babel/[email protected](@babel/[email protected])':+ dependencies:+ '@babel/core': 7.29.0+ '@babel/helper-plugin-utils': 7.28.6++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.0+ '@babel/parser': 7.29.3+ '@babel/types': 7.29.0++ '@babel/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.0+ '@babel/generator': 7.29.1+ '@babel/helper-globals': 7.28.0+ '@babel/parser': 7.29.3+ '@babel/template': 7.28.6+ '@babel/types': 7.29.0+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]':+ dependencies:+ '@babel/helper-string-parser': 7.27.1+ '@babel/helper-validator-identifier': 7.28.5++ '@biomejs/[email protected]':+ optionalDependencies:+ '@biomejs/cli-darwin-arm64': 2.4.15+ '@biomejs/cli-darwin-x64': 2.4.15+ '@biomejs/cli-linux-arm64': 2.4.15+ '@biomejs/cli-linux-arm64-musl': 2.4.15+ '@biomejs/cli-linux-x64': 2.4.15+ '@biomejs/cli-linux-x64-musl': 2.4.15+ '@biomejs/cli-win32-arm64': 2.4.15+ '@biomejs/cli-win32-x64': 2.4.15++ '@biomejs/[email protected]':+ optional: true++ '@biomejs/[email protected]':+ optional: true++ '@biomejs/[email protected]':+ optional: true++ '@biomejs/[email protected]':+ optional: true++ '@biomejs/[email protected]':+ optional: true++ '@biomejs/[email protected]':+ optional: true++ '@biomejs/[email protected]':+ optional: true++ '@biomejs/[email protected]':+ optional: true++ '@biomejs/[email protected](@biomejs/[email protected])':+ optionalDependencies:+ '@biomejs/wasm-nodejs': 2.0.5++ '@biomejs/[email protected]': {}++ '@cloudscape-design/[email protected]([email protected])':+ dependencies:+ '@cloudscape-design/component-toolkit': 1.0.0-beta.159([email protected])+ react: 18.3.1++ '@cloudscape-design/[email protected]([email protected])':+ dependencies:+ react: 18.3.1+ tslib: 2.8.1+ weekstart: 2.0.0++ dependencies:+ '@cloudscape-design/collection-hooks': 1.0.93([email protected])+ '@cloudscape-design/component-toolkit': 1.0.0-beta.159([email protected])+ '@cloudscape-design/test-utils-core': 1.0.81+ '@cloudscape-design/theming-runtime': 1.0.110+ '@dnd-kit/sortable': 7.0.2(@dnd-kit/[email protected]([email protected]([email protected]))([email protected]))([email protected])+ '@dnd-kit/utilities': 3.2.2([email protected])+ ace-builds: 1.43.6+ clsx: 1.2.1+ d3-shape: 1.3.7+ date-fns: 2.30.0+ intl-messageformat: 10.7.18+ mnth: 2.0.0+ react: 18.3.1+ react-is: 18.3.1+ tslib: 2.8.1+ weekstart: 1.1.0+ transitivePeerDependencies:+ - react-dom++ '@cloudscape-design/[email protected]': {}++ '@cloudscape-design/[email protected]':+ dependencies:+ css-selector-tokenizer: 0.8.0+ css.escape: 1.5.1++ '@cloudscape-design/[email protected]':+ dependencies:+ '@material/material-color-utilities': 0.3.0+ tslib: 2.8.1++ '@dnd-kit/[email protected]([email protected])':+ dependencies:+ react: 18.3.1+ tslib: 2.8.1++ dependencies:+ '@dnd-kit/accessibility': 3.1.1([email protected])+ '@dnd-kit/utilities': 3.2.2([email protected])+ react: 18.3.1+ react-dom: 18.3.1([email protected])+ tslib: 2.8.1++ '@dnd-kit/[email protected](@dnd-kit/[email protected]([email protected]([email protected]))([email protected]))([email protected])':+ dependencies:+ '@dnd-kit/utilities': 3.2.2([email protected])+ react: 18.3.1+ tslib: 2.8.1++ '@dnd-kit/[email protected]([email protected])':+ dependencies:+ react: 18.3.1+ tslib: 2.8.1++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@exodus/[email protected]': {}++ '@formatjs/[email protected]':+ dependencies:+ '@formatjs/fast-memoize': 2.2.7+ '@formatjs/intl-localematcher': 0.6.2+ decimal.js: 10.6.0+ tslib: 2.8.1++ '@formatjs/[email protected]':+ dependencies:+ tslib: 2.8.1++ '@formatjs/[email protected]':+ dependencies:+ '@formatjs/ecma402-abstract': 2.3.6+ '@formatjs/icu-skeleton-parser': 1.8.16+ tslib: 2.8.1++ '@formatjs/[email protected]':+ dependencies:+ '@formatjs/ecma402-abstract': 2.3.6+ tslib: 2.8.1++ '@formatjs/[email protected]':+ dependencies:+ tslib: 2.8.1++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/sourcemap-codec': 1.5.5+ '@jridgewell/trace-mapping': 0.3.31++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/gen-mapping': 0.3.13+ '@jridgewell/trace-mapping': 0.3.31++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/resolve-uri': 3.1.2+ '@jridgewell/sourcemap-codec': 1.5.5++ '@material/[email protected]': {}++ '@novnc/[email protected](patch_hash=c119c00d14c51f940f1ebed4fe41ad2fe1358c63e1095baa39d11d696b66dbff)': {}++ '@playwright/[email protected]':+ dependencies:+ playwright: 1.60.0++ '@remix-run/[email protected]': {}++ '@rolldown/[email protected]': {}++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@types/[email protected]':+ dependencies:+ '@babel/parser': 7.29.3+ '@babel/types': 7.29.0+ '@types/babel__generator': 7.27.0+ '@types/babel__template': 7.4.4+ '@types/babel__traverse': 7.28.0++ '@types/[email protected]':+ dependencies:+ '@babel/types': 7.29.0++ '@types/[email protected]':+ dependencies:+ '@babel/parser': 7.29.3+ '@babel/types': 7.29.0++ '@types/[email protected]':+ dependencies:+ '@babel/types': 7.29.0++ '@types/[email protected]': {}++ '@types/[email protected]': {}++ '@types/[email protected](@types/[email protected])':+ dependencies:+ '@types/react': 18.3.28++ '@types/[email protected]':+ dependencies:+ '@types/prop-types': 15.7.15+ csstype: 3.2.3++ '@types/[email protected]': {}++ '@vitejs/[email protected]([email protected])':+ dependencies:+ '@babel/core': 7.29.0+ '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/[email protected])+ '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/[email protected])+ '@rolldown/pluginutils': 1.0.0-beta.27+ '@types/babel__core': 7.20.5+ react-refresh: 0.17.0+ vite: 5.4.21+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ [email protected]: {}++ dependencies:+ color-convert: 2.0.1++ dependencies:+ entities: 2.2.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ baseline-browser-mapping: 2.10.28+ caniuse-lite: 1.0.30001792+ electron-to-chromium: 1.5.353+ node-releases: 2.0.38+ update-browserslist-db: 1.2.3([email protected])++ dependencies:+ chokidar: 5.0.0+ confbox: 0.2.4+ defu: 6.1.7+ dotenv: 17.4.2+ exsolve: 1.0.8+ giget: 3.2.0+ jiti: 2.7.0+ ohash: 2.0.11+ pathe: 2.0.3+ perfect-debounce: 2.1.0+ pkg-types: 2.3.1+ rc9: 3.0.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ readdirp: 5.0.0++ dependencies:+ consola: 3.4.2++ dependencies:+ string-width: 4.2.3+ strip-ansi: 6.0.1+ wrap-ansi: 7.0.0++ [email protected]: {}++ dependencies:+ color-name: 1.1.4++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ cssesc: 3.0.0+ fastparse: 1.1.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ d3-path: 1.0.9++ dependencies:+ '@babel/runtime': 7.29.2++ dependencies:+ ms: 2.1.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@babel/runtime': 7.29.2+ csstype: 3.2.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optionalDependencies:+ '@esbuild/aix-ppc64': 0.21.5+ '@esbuild/android-arm': 0.21.5+ '@esbuild/android-arm64': 0.21.5+ '@esbuild/android-x64': 0.21.5+ '@esbuild/darwin-arm64': 0.21.5+ '@esbuild/darwin-x64': 0.21.5+ '@esbuild/freebsd-arm64': 0.21.5+ '@esbuild/freebsd-x64': 0.21.5+ '@esbuild/linux-arm': 0.21.5+ '@esbuild/linux-arm64': 0.21.5+ '@esbuild/linux-ia32': 0.21.5+ '@esbuild/linux-loong64': 0.21.5+ '@esbuild/linux-mips64el': 0.21.5+ '@esbuild/linux-ppc64': 0.21.5+ '@esbuild/linux-riscv64': 0.21.5+ '@esbuild/linux-s390x': 0.21.5+ '@esbuild/linux-x64': 0.21.5+ '@esbuild/netbsd-x64': 0.21.5+ '@esbuild/openbsd-x64': 0.21.5+ '@esbuild/sunos-x64': 0.21.5+ '@esbuild/win32-arm64': 0.21.5+ '@esbuild/win32-ia32': 0.21.5+ '@esbuild/win32-x64': 0.21.5++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optional: true++ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@formatjs/ecma402-abstract': 2.3.6+ '@formatjs/fast-memoize': 2.2.7+ '@formatjs/icu-messageformat-parser': 2.11.4+ tslib: 2.8.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ argparse: 2.0.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ js-sha256: 0.11.1+ jwt-decode: 4.0.0++ [email protected]: {}++ dependencies:+ js-tokens: 4.0.0++ dependencies:+ yallist: 3.1.1++ dependencies:+ '@babel/runtime': 7.29.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ http2-client: 1.3.5++ dependencies:+ whatwg-url: 5.0.0++ dependencies:+ es6-promise: 3.3.1++ [email protected]: {}++ dependencies:+ fast-safe-stringify: 2.1.1++ dependencies:+ '@exodus/schemasafe': 1.3.0+ should: 13.2.3+ yaml: 1.10.3++ dependencies:+ node-fetch-h2: 2.3.0+ oas-kit-common: 1.0.8+ reftools: 1.1.9+ yaml: 1.10.3+ yargs: 17.7.2++ [email protected]: {}++ dependencies:+ call-me-maybe: 1.0.2+ oas-kit-common: 1.0.8+ oas-linter: 3.2.2+ oas-resolver: 2.5.6+ oas-schema-walker: 1.1.5+ reftools: 1.1.9+ should: 13.2.3+ yaml: 1.10.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ confbox: 0.2.4+ exsolve: 1.0.8+ pathe: 2.0.3++ [email protected]: {}++ dependencies:+ playwright-core: 1.60.0+ optionalDependencies:+ fsevents: 2.3.2++ dependencies:+ nanoid: 3.3.12+ picocolors: 1.1.1+ source-map-js: 1.2.1++ dependencies:+ loose-envify: 1.4.0+ object-assign: 4.1.1+ react-is: 16.13.1++ dependencies:+ defu: 6.1.7+ destr: 2.0.5++ dependencies:+ loose-envify: 1.4.0+ react: 18.3.1+ scheduler: 0.23.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@remix-run/router': 1.23.2+ react: 18.3.1+ react-dom: 18.3.1([email protected])+ react-router: 6.30.3([email protected])++ dependencies:+ '@remix-run/router': 1.23.2+ react: 18.3.1++ dependencies:+ '@babel/runtime': 7.29.2+ dom-helpers: 5.2.1+ loose-envify: 1.4.0+ prop-types: 15.8.1+ react: 18.3.1+ react-dom: 18.3.1([email protected])++ dependencies:+ loose-envify: 1.4.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@types/estree': 1.0.8+ optionalDependencies:+ '@rollup/rollup-android-arm-eabi': 4.60.3+ '@rollup/rollup-android-arm64': 4.60.3+ '@rollup/rollup-darwin-arm64': 4.60.3+ '@rollup/rollup-darwin-x64': 4.60.3+ '@rollup/rollup-freebsd-arm64': 4.60.3+ '@rollup/rollup-freebsd-x64': 4.60.3+ '@rollup/rollup-linux-arm-gnueabihf': 4.60.3+ '@rollup/rollup-linux-arm-musleabihf': 4.60.3+ '@rollup/rollup-linux-arm64-gnu': 4.60.3+ '@rollup/rollup-linux-arm64-musl': 4.60.3+ '@rollup/rollup-linux-loong64-gnu': 4.60.3+ '@rollup/rollup-linux-loong64-musl': 4.60.3+ '@rollup/rollup-linux-ppc64-gnu': 4.60.3+ '@rollup/rollup-linux-ppc64-musl': 4.60.3+ '@rollup/rollup-linux-riscv64-gnu': 4.60.3+ '@rollup/rollup-linux-riscv64-musl': 4.60.3+ '@rollup/rollup-linux-s390x-gnu': 4.60.3+ '@rollup/rollup-linux-x64-gnu': 4.60.3+ '@rollup/rollup-linux-x64-musl': 4.60.3+ '@rollup/rollup-openbsd-x64': 4.60.3+ '@rollup/rollup-openharmony-arm64': 4.60.3+ '@rollup/rollup-win32-arm64-msvc': 4.60.3+ '@rollup/rollup-win32-ia32-msvc': 4.60.3+ '@rollup/rollup-win32-x64-gnu': 4.60.3+ '@rollup/rollup-win32-x64-msvc': 4.60.3+ fsevents: 2.3.3++ dependencies:+ loose-envify: 1.4.0++ [email protected]: {}++ dependencies:+ should-type: 1.4.0++ dependencies:+ should-type: 1.4.0+ should-type-adaptors: 1.1.0++ dependencies:+ should-type: 1.4.0+ should-util: 1.0.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ should-equal: 2.0.0+ should-format: 3.0.3+ should-type: 1.4.0+ should-type-adaptors: 1.1.0+ should-util: 1.0.1++ [email protected]: {}++ dependencies:+ emoji-regex: 8.0.0+ is-fullwidth-code-point: 3.0.0+ strip-ansi: 6.0.1++ dependencies:+ ansi-regex: 5.0.1++ [email protected]: {}++ dependencies:+ '@biomejs/js-api': 1.0.0(@biomejs/[email protected])+ '@biomejs/wasm-nodejs': 2.0.5+ '@types/swagger-schema-official': 2.0.25+ c12: 3.3.4+ citty: 0.1.6+ consola: 3.4.2+ eta: 2.2.0+ js-yaml: 4.1.1+ lodash: 4.18.1+ nanoid: 5.1.11+ swagger-schema-official: 2.0.0-bab6bed+ swagger2openapi: 7.0.8+ typescript: 5.8.3+ transitivePeerDependencies:+ - '@biomejs/wasm-bundler'+ - '@biomejs/wasm-web'+ - encoding+ - magicast++ dependencies:+ call-me-maybe: 1.0.2+ node-fetch: 2.7.0+ node-fetch-h2: 2.3.0+ node-readfiles: 0.2.0+ oas-kit-common: 1.0.8+ oas-resolver: 2.5.6+ oas-schema-walker: 1.1.5+ oas-validator: 5.0.8+ reftools: 1.1.9+ yaml: 1.10.3+ yargs: 17.7.2+ transitivePeerDependencies:+ - encoding++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ browserslist: 4.28.2+ escalade: 3.2.0+ picocolors: 1.1.1++ dependencies:+ esbuild: 0.21.5+ postcss: 8.5.14+ rollup: 4.60.3+ optionalDependencies:+ fsevents: 2.3.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ tr46: 0.0.3+ webidl-conversions: 3.0.1++ dependencies:+ ansi-styles: 4.3.0+ string-width: 4.2.3+ strip-ansi: 6.0.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ cliui: 8.0.1+ escalade: 3.2.0+ get-caller-file: 2.0.5+ require-directory: 2.1.1+ string-width: 4.2.3+ y18n: 5.0.8+ yargs-parser: 21.1.1diff --git a/libs/fleet/python-sdk/.gitignore b/libs/fleet/python-sdk/.gitignorenew file mode 100644index 0000000000..79a2c3d73c--- /dev/null+++ b/libs/fleet/python-sdk/.gitignore@@ -0,0 +1,23 @@+__pycache__/+build/+dist/+*.egg-info/+.pytest_cache/++# pyenv+.python-version++# Environments+.env+.venv++# mypy+.mypy_cache/+.dmypy.json+dmypy.json++# JetBrains+.idea/++/coverage.xml+/.coveragediff --git a/libs/fleet/python-sdk/README.md b/libs/fleet/python-sdk/README.mdnew file mode 100644index 0000000000..8b13789179--- /dev/null+++ b/libs/fleet/python-sdk/README.md@@ -0,0 +1 @@+diff --git a/libs/fleet/python-sdk/cua_train/__init__.py b/libs/fleet/python-sdk/cua_train/__init__.pynew file mode 100644index 0000000000..c0b9d96bd7--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/__init__.py@@ -0,0 +1,10 @@+"""cua-train — Python client library for the CUA training / batch backend API."""++from ._convenience import TrainClient+from .client import AuthenticatedClient, Client++__all__ = (+ "AuthenticatedClient",+ "Client",+ "TrainClient",+)diff --git a/libs/fleet/python-sdk/cua_train/_convenience.py b/libs/fleet/python-sdk/cua_train/_convenience.pynew file mode 100644index 0000000000..dc3422bb00--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/_convenience.py@@ -0,0 +1,147 @@+"""+TrainClient — an AuthenticatedClient that also exposes every generated+endpoint as a method, so callers write::++ c = TrainClient.from_key(token_url=..., client_id=..., client_secret=...)+ c.acquire_lanes(pool="test-pool", body=AcquireLanesRequest(n=8))+ c.submit_label_batch(pool="test-pool", label="run-1", body=BatchSubmitRequest(...))+ c.get_label_results(pool="test-pool", label="run-1", completed_only=True)++instead of importing each generated module and calling ``.sync`` by hand.++The endpoint surface is built generically: :func:`_load_operations` loops over+every module under ``cua_train.api`` once at import and maps each operation's+``sync`` function by name. ``TrainClient.__getattr__`` then resolves an+unknown attribute to that function with ``client=self`` pre-bound — no+per-endpoint code and no routing logic, so a new endpoint is callable the moment+it is regenerated from the OpenAPI spec. ``c`` remains a drop-in+``AuthenticatedClient`` for the low-level ``cua_train.api.*`` functions.+"""++from __future__ import annotations++import functools+import importlib+import pkgutil+import threading+import time+from collections.abc import Callable++import httpx++from . import api+from .client import AuthenticatedClient+++def _load_operations() -> dict[str, Callable]:+ """Map ``operation_name -> sync()`` for every generated endpoint module.++ Walks ``cua_train/api/<tag>/<operation>.py`` (operation names are globally+ unique, so a flat namespace is safe). Run once at import.+ """+ ops: dict[str, Callable] = {}+ for tag in pkgutil.iter_modules(api.__path__):+ if not tag.ispkg:+ continue+ pkg = importlib.import_module(f"{api.__name__}.{tag.name}")+ for op in pkgutil.iter_modules(pkg.__path__):+ module = importlib.import_module(f"{pkg.__name__}.{op.name}")+ fn = getattr(module, "sync", None)+ if callable(fn):+ ops[op.name] = fn+ return ops+++_OPERATIONS = _load_operations()+++class TrainClient(AuthenticatedClient):+ """AuthenticatedClient with a ``client_credentials`` helper, a bearer token+ that is refreshed transparently before it expires, and every generated+ endpoint exposed as a method (its ``sync``, client pre-bound)."""++ @classmethod+ def from_key(+ cls,+ *,+ token_url: str,+ client_id: str,+ client_secret: str,+ base_url: str = "https://run.cua.ai",+ **kwargs,+ ) -> TrainClient:+ """Exchange client credentials for a bearer token and return a ready client.++ Args:+ token_url: Keycloak token endpoint, e.g.+ ``https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token``+ client_id: Service-account client ID (starts with ``key-``).+ client_secret: Client secret returned by ``POST /api/keys``.+ base_url: Backend base URL (default: production, run.cua.ai).+ **kwargs: Forwarded to :class:`AuthenticatedClient`.+ """+ token, ttl = cls._exchange(token_url, client_id, client_secret)+ self = cls(base_url=base_url, token=token, **kwargs)+ # Stash credentials so the token can be refreshed transparently.+ self._token_url = token_url+ self._client_id = client_id+ self._client_secret = client_secret+ self._token_deadline = time.monotonic() + ttl+ self._refresh_lock = threading.Lock()+ return self++ @staticmethod+ def _exchange(token_url: str, client_id: str, client_secret: str) -> tuple[str, float]:+ """client_credentials exchange → (access_token, lifetime_seconds)."""+ resp = httpx.post(+ token_url,+ data={+ "grant_type": "client_credentials",+ "client_id": client_id,+ "client_secret": client_secret,+ },+ )+ resp.raise_for_status()+ body = resp.json()+ return body["access_token"], float(body.get("expires_in", 300))++ def _refresh_token(self) -> None:+ """Re-mint the bearer token shortly before it expires. Transparent to+ callers, thread-safe (double-checked under a lock), and a no-op for+ clients not created via :meth:`from_key`."""+ if getattr(self, "_token_url", None) is None:+ return+ if time.monotonic() < self._token_deadline - 30:+ return+ with self._refresh_lock:+ if time.monotonic() < self._token_deadline - 30:+ return+ token, ttl = self._exchange(self._token_url, self._client_id, self._client_secret)+ self.token = token+ self._token_deadline = time.monotonic() + ttl+ header = f"{self.prefix} {token}" if self.prefix else token+ self._headers[self.auth_header_name] = header+ if self._client is not None:+ self._client.headers[self.auth_header_name] = header+ if self._async_client is not None:+ self._async_client.headers[self.auth_header_name] = header++ def get_httpx_client(self) -> httpx.Client:+ self._refresh_token()+ return super().get_httpx_client()++ def get_async_httpx_client(self) -> httpx.AsyncClient:+ self._refresh_token()+ return super().get_async_httpx_client()++ def __getattr__(self, name: str) -> Callable:+ # Only reached for attributes not found normally (slots/methods take+ # precedence), so this never shadows real client state. Unknown names —+ # including dunders probed by copy/pickle — raise AttributeError.+ fn = _OPERATIONS.get(name)+ if fn is None:+ raise AttributeError(+ f"{type(self).__name__!r} object has no attribute {name!r}; "+ f"available operations: {', '.join(sorted(_OPERATIONS))}"+ )+ return functools.partial(fn, client=self)diff --git a/libs/fleet/python-sdk/cua_train/api/__init__.py b/libs/fleet/python-sdk/cua_train/api/__init__.pynew file mode 100644index 0000000000..81f9fa241b--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/__init__.py@@ -0,0 +1 @@+"""Contains methods for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/batch/__init__.py b/libs/fleet/python-sdk/cua_train/api/batch/__init__.pynew file mode 100644index 0000000000..2d7c0b23da--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/batch/__init__.py@@ -0,0 +1 @@+"""Contains endpoint functions for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/batch/acquire_lanes.py b/libs/fleet/python-sdk/cua_train/api/batch/acquire_lanes.pynew file mode 100644index 0000000000..453c8323b6--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/batch/acquire_lanes.py@@ -0,0 +1,212 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.acquire_lanes_request import AcquireLanesRequest+from ...models.acquire_lanes_response import AcquireLanesResponse+from ...models.error_response import ErrorResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ *,+ body: AcquireLanesRequest,+) -> dict[str, Any]:+ headers: dict[str, Any] = {}++ _kwargs: dict[str, Any] = {+ "method": "post",+ "url": "/api/batch/{pool}/lanes".format(+ pool=quote(str(pool), safe=""),+ ),+ }++ _kwargs["json"] = body.to_dict()++ headers["Content-Type"] = "application/json"++ _kwargs["headers"] = headers+ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> AcquireLanesResponse | ErrorResponse | None:+ if response.status_code == 200:+ response_200 = AcquireLanesResponse.from_dict(response.json())++ return response_200++ if response.status_code == 400:+ response_400 = ErrorResponse.from_dict(response.json())++ return response_400++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if response.status_code == 503:+ response_503 = ErrorResponse.from_dict(response.json())++ return response_503++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[AcquireLanesResponse | ErrorResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: AcquireLanesRequest,+) -> Response[AcquireLanesResponse | ErrorResponse]:+ r"""Acquire warm VM lanes++ Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as+ `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to+ release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool+ can't supply every lane in time.++ Args:+ pool (str):+ body (AcquireLanesRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[AcquireLanesResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ body=body,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: AcquireLanesRequest,+) -> AcquireLanesResponse | ErrorResponse | None:+ r"""Acquire warm VM lanes++ Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as+ `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to+ release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool+ can't supply every lane in time.++ Args:+ pool (str):+ body (AcquireLanesRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ AcquireLanesResponse | ErrorResponse+ """++ return sync_detailed(+ pool=pool,+ client=client,+ body=body,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: AcquireLanesRequest,+) -> Response[AcquireLanesResponse | ErrorResponse]:+ r"""Acquire warm VM lanes++ Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as+ `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to+ release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool+ can't supply every lane in time.++ Args:+ pool (str):+ body (AcquireLanesRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[AcquireLanesResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ body=body,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: AcquireLanesRequest,+) -> AcquireLanesResponse | ErrorResponse | None:+ r"""Acquire warm VM lanes++ Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as+ `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to+ release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool+ can't supply every lane in time.++ Args:+ pool (str):+ body (AcquireLanesRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ AcquireLanesResponse | ErrorResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ client=client,+ body=body,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/batch/cancel_batch.py b/libs/fleet/python-sdk/cua_train/api/batch/cancel_batch.pynew file mode 100644index 0000000000..00110ea700--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/batch/cancel_batch.py@@ -0,0 +1,196 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.cancel_batch_response import CancelBatchResponse+from ...models.error_response import ErrorResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ id: str,+) -> dict[str, Any]:++ _kwargs: dict[str, Any] = {+ "method": "delete",+ "url": "/api/batch/{pool}/{id}".format(+ pool=quote(str(pool), safe=""),+ id=quote(str(id), safe=""),+ ),+ }++ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> CancelBatchResponse | ErrorResponse | None:+ if response.status_code == 200:+ response_200 = CancelBatchResponse.from_dict(response.json())++ return response_200++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if response.status_code == 404:+ response_404 = ErrorResponse.from_dict(response.json())++ return response_404++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[CancelBatchResponse | ErrorResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[CancelBatchResponse | ErrorResponse]:+ """Cancel a batch++ Hard-cancels the batch — aborts in-flight /reset and /step calls+ and stops dispatch. Idempotent on terminal batches. Returns 200+ with the final status.++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[CancelBatchResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ id=id,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> CancelBatchResponse | ErrorResponse | None:+ """Cancel a batch++ Hard-cancels the batch — aborts in-flight /reset and /step calls+ and stops dispatch. Idempotent on terminal batches. Returns 200+ with the final status.++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ CancelBatchResponse | ErrorResponse+ """++ return sync_detailed(+ pool=pool,+ id=id,+ client=client,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[CancelBatchResponse | ErrorResponse]:+ """Cancel a batch++ Hard-cancels the batch — aborts in-flight /reset and /step calls+ and stops dispatch. Idempotent on terminal batches. Returns 200+ with the final status.++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[CancelBatchResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ id=id,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> CancelBatchResponse | ErrorResponse | None:+ """Cancel a batch++ Hard-cancels the batch — aborts in-flight /reset and /step calls+ and stops dispatch. Idempotent on terminal batches. Returns 200+ with the final status.++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ CancelBatchResponse | ErrorResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ id=id,+ client=client,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/batch/get_batch_results.py b/libs/fleet/python-sdk/cua_train/api/batch/get_batch_results.pynew file mode 100644index 0000000000..bb2e2b48fd--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/batch/get_batch_results.py@@ -0,0 +1,202 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.batch_in_progress_response import BatchInProgressResponse+from ...models.batch_results_response import BatchResultsResponse+from ...models.error_response import ErrorResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ id: str,+) -> dict[str, Any]:++ _kwargs: dict[str, Any] = {+ "method": "get",+ "url": "/api/batch/{pool}/{id}/results".format(+ pool=quote(str(pool), safe=""),+ id=quote(str(id), safe=""),+ ),+ }++ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> BatchInProgressResponse | BatchResultsResponse | ErrorResponse | None:+ if response.status_code == 200:+ response_200 = BatchResultsResponse.from_dict(response.json())++ return response_200++ if response.status_code == 202:+ response_202 = BatchInProgressResponse.from_dict(response.json())++ return response_202++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if response.status_code == 404:+ response_404 = ErrorResponse.from_dict(response.json())++ return response_404++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]:+ """Final batch results++ Returns 200 with the full results once the batch is in a terminal+ status (completed/failed). While still running, returns 202 with a+ `message` field.++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ id=id,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> BatchInProgressResponse | BatchResultsResponse | ErrorResponse | None:+ """Final batch results++ Returns 200 with the full results once the batch is in a terminal+ status (completed/failed). While still running, returns 202 with a+ `message` field.++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ BatchInProgressResponse | BatchResultsResponse | ErrorResponse+ """++ return sync_detailed(+ pool=pool,+ id=id,+ client=client,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]:+ """Final batch results++ Returns 200 with the full results once the batch is in a terminal+ status (completed/failed). While still running, returns 202 with a+ `message` field.++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ id=id,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> BatchInProgressResponse | BatchResultsResponse | ErrorResponse | None:+ """Final batch results++ Returns 200 with the full results once the batch is in a terminal+ status (completed/failed). While still running, returns 202 with a+ `message` field.++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ BatchInProgressResponse | BatchResultsResponse | ErrorResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ id=id,+ client=client,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/batch/get_batch_status.py b/libs/fleet/python-sdk/cua_train/api/batch/get_batch_status.pynew file mode 100644index 0000000000..e4a13d4a81--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/batch/get_batch_status.py@@ -0,0 +1,180 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.batch_status_response import BatchStatusResponse+from ...models.error_response import ErrorResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ id: str,+) -> dict[str, Any]:++ _kwargs: dict[str, Any] = {+ "method": "get",+ "url": "/api/batch/{pool}/{id}/status".format(+ pool=quote(str(pool), safe=""),+ id=quote(str(id), safe=""),+ ),+ }++ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> BatchStatusResponse | ErrorResponse | None:+ if response.status_code == 200:+ response_200 = BatchStatusResponse.from_dict(response.json())++ return response_200++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if response.status_code == 404:+ response_404 = ErrorResponse.from_dict(response.json())++ return response_404++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[BatchStatusResponse | ErrorResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[BatchStatusResponse | ErrorResponse]:+ """Poll batch progress++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[BatchStatusResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ id=id,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> BatchStatusResponse | ErrorResponse | None:+ """Poll batch progress++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ BatchStatusResponse | ErrorResponse+ """++ return sync_detailed(+ pool=pool,+ id=id,+ client=client,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[BatchStatusResponse | ErrorResponse]:+ """Poll batch progress++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[BatchStatusResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ id=id,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> BatchStatusResponse | ErrorResponse | None:+ """Poll batch progress++ Args:+ pool (str):+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ BatchStatusResponse | ErrorResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ id=id,+ client=client,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/batch/release_lanes.py b/libs/fleet/python-sdk/cua_train/api/batch/release_lanes.pynew file mode 100644index 0000000000..8c8534cf0f--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/batch/release_lanes.py@@ -0,0 +1,199 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.error_response import ErrorResponse+from ...models.release_lanes_request import ReleaseLanesRequest+from ...models.release_lanes_response import ReleaseLanesResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ *,+ body: ReleaseLanesRequest,+) -> dict[str, Any]:+ headers: dict[str, Any] = {}++ _kwargs: dict[str, Any] = {+ "method": "delete",+ "url": "/api/batch/{pool}/lanes".format(+ pool=quote(str(pool), safe=""),+ ),+ }++ _kwargs["json"] = body.to_dict()++ headers["Content-Type"] = "application/json"++ _kwargs["headers"] = headers+ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> ErrorResponse | ReleaseLanesResponse | None:+ if response.status_code == 200:+ response_200 = ReleaseLanesResponse.from_dict(response.json())++ return response_200++ if response.status_code == 400:+ response_400 = ErrorResponse.from_dict(response.json())++ return response_400++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[ErrorResponse | ReleaseLanesResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: ReleaseLanesRequest,+) -> Response[ErrorResponse | ReleaseLanesResponse]:+ """Release warm VM lanes++ Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).+ Best-effort and idempotent — unknown or already-gone ids are ignored.++ Args:+ pool (str):+ body (ReleaseLanesRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[ErrorResponse | ReleaseLanesResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ body=body,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: ReleaseLanesRequest,+) -> ErrorResponse | ReleaseLanesResponse | None:+ """Release warm VM lanes++ Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).+ Best-effort and idempotent — unknown or already-gone ids are ignored.++ Args:+ pool (str):+ body (ReleaseLanesRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ ErrorResponse | ReleaseLanesResponse+ """++ return sync_detailed(+ pool=pool,+ client=client,+ body=body,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: ReleaseLanesRequest,+) -> Response[ErrorResponse | ReleaseLanesResponse]:+ """Release warm VM lanes++ Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).+ Best-effort and idempotent — unknown or already-gone ids are ignored.++ Args:+ pool (str):+ body (ReleaseLanesRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[ErrorResponse | ReleaseLanesResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ body=body,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: ReleaseLanesRequest,+) -> ErrorResponse | ReleaseLanesResponse | None:+ """Release warm VM lanes++ Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).+ Best-effort and idempotent — unknown or already-gone ids are ignored.++ Args:+ pool (str):+ body (ReleaseLanesRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ ErrorResponse | ReleaseLanesResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ client=client,+ body=body,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/batch/submit_batch.py b/libs/fleet/python-sdk/cua_train/api/batch/submit_batch.pynew file mode 100644index 0000000000..5fe187f149--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/batch/submit_batch.py@@ -0,0 +1,219 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.batch_submit_request import BatchSubmitRequest+from ...models.batch_submit_response import BatchSubmitResponse+from ...models.error_response import ErrorResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ *,+ body: BatchSubmitRequest,+) -> dict[str, Any]:+ headers: dict[str, Any] = {}++ _kwargs: dict[str, Any] = {+ "method": "post",+ "url": "/api/batch/{pool}/submit".format(+ pool=quote(str(pool), safe=""),+ ),+ }++ _kwargs["json"] = body.to_dict()++ headers["Content-Type"] = "application/json"++ _kwargs["headers"] = headers+ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> BatchSubmitResponse | ErrorResponse | None:+ if response.status_code == 202:+ response_202 = BatchSubmitResponse.from_dict(response.json())++ return response_202++ if response.status_code == 400:+ response_400 = ErrorResponse.from_dict(response.json())++ return response_400++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[BatchSubmitResponse | ErrorResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: BatchSubmitRequest,+) -> Response[BatchSubmitResponse | ErrorResponse]:+ """Submit a batch of rollouts++ Asynchronously queues a batch of OSGym rollouts under `{pool}`.+ Returns immediately with a `batch_id`; poll+ `/api/batch/{pool}/{id}/status` for progress and+ `/api/batch/{pool}/{id}/results` for the final payload.++ The pool is bound by the URL path; any `pool_name` in the body must+ match the URL pool or the request is rejected with 400.++ Args:+ pool (str):+ body (BatchSubmitRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[BatchSubmitResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ body=body,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: BatchSubmitRequest,+) -> BatchSubmitResponse | ErrorResponse | None:+ """Submit a batch of rollouts++ Asynchronously queues a batch of OSGym rollouts under `{pool}`.+ Returns immediately with a `batch_id`; poll+ `/api/batch/{pool}/{id}/status` for progress and+ `/api/batch/{pool}/{id}/results` for the final payload.++ The pool is bound by the URL path; any `pool_name` in the body must+ match the URL pool or the request is rejected with 400.++ Args:+ pool (str):+ body (BatchSubmitRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ BatchSubmitResponse | ErrorResponse+ """++ return sync_detailed(+ pool=pool,+ client=client,+ body=body,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: BatchSubmitRequest,+) -> Response[BatchSubmitResponse | ErrorResponse]:+ """Submit a batch of rollouts++ Asynchronously queues a batch of OSGym rollouts under `{pool}`.+ Returns immediately with a `batch_id`; poll+ `/api/batch/{pool}/{id}/status` for progress and+ `/api/batch/{pool}/{id}/results` for the final payload.++ The pool is bound by the URL path; any `pool_name` in the body must+ match the URL pool or the request is rejected with 400.++ Args:+ pool (str):+ body (BatchSubmitRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[BatchSubmitResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ body=body,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: BatchSubmitRequest,+) -> BatchSubmitResponse | ErrorResponse | None:+ """Submit a batch of rollouts++ Asynchronously queues a batch of OSGym rollouts under `{pool}`.+ Returns immediately with a `batch_id`; poll+ `/api/batch/{pool}/{id}/status` for progress and+ `/api/batch/{pool}/{id}/results` for the final payload.++ The pool is bound by the URL path; any `pool_name` in the body must+ match the URL pool or the request is rejected with 400.++ Args:+ pool (str):+ body (BatchSubmitRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ BatchSubmitResponse | ErrorResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ client=client,+ body=body,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/health/__init__.py b/libs/fleet/python-sdk/cua_train/api/health/__init__.pynew file mode 100644index 0000000000..2d7c0b23da--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/health/__init__.py@@ -0,0 +1 @@+"""Contains endpoint functions for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/health/healthz.py b/libs/fleet/python-sdk/cua_train/api/health/healthz.pynew file mode 100644index 0000000000..267c378898--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/health/healthz.py@@ -0,0 +1,124 @@+from http import HTTPStatus+from typing import Any++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.health_response import HealthResponse+from ...types import Response+++def _get_kwargs() -> dict[str, Any]:++ _kwargs: dict[str, Any] = {+ "method": "get",+ "url": "/healthz",+ }++ return _kwargs+++def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> HealthResponse | None:+ if response.status_code == 200:+ response_200 = HealthResponse.from_dict(response.json())++ return response_200++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[HealthResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ *,+ client: AuthenticatedClient | Client,+) -> Response[HealthResponse]:+ """Liveness/readiness probe++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[HealthResponse]+ """++ kwargs = _get_kwargs()++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ *,+ client: AuthenticatedClient | Client,+) -> HealthResponse | None:+ """Liveness/readiness probe++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ HealthResponse+ """++ return sync_detailed(+ client=client,+ ).parsed+++async def asyncio_detailed(+ *,+ client: AuthenticatedClient | Client,+) -> Response[HealthResponse]:+ """Liveness/readiness probe++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[HealthResponse]+ """++ kwargs = _get_kwargs()++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ *,+ client: AuthenticatedClient | Client,+) -> HealthResponse | None:+ """Liveness/readiness probe++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ HealthResponse+ """++ return (+ await asyncio_detailed(+ client=client,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/keys/__init__.py b/libs/fleet/python-sdk/cua_train/api/keys/__init__.pynew file mode 100644index 0000000000..2d7c0b23da--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/keys/__init__.py@@ -0,0 +1 @@+"""Contains endpoint functions for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/keys/create_key.py b/libs/fleet/python-sdk/cua_train/api/keys/create_key.pynew file mode 100644index 0000000000..b53a7760db--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/keys/create_key.py@@ -0,0 +1,188 @@+from http import HTTPStatus+from typing import Any++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.create_key_request import CreateKeyRequest+from ...models.create_key_response import CreateKeyResponse+from ...models.error_response import ErrorResponse+from ...types import Response+++def _get_kwargs(+ *,+ body: CreateKeyRequest,+) -> dict[str, Any]:+ headers: dict[str, Any] = {}++ _kwargs: dict[str, Any] = {+ "method": "post",+ "url": "/api/keys",+ }++ _kwargs["json"] = body.to_dict()++ headers["Content-Type"] = "application/json"++ _kwargs["headers"] = headers+ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> CreateKeyResponse | ErrorResponse | None:+ if response.status_code == 201:+ response_201 = CreateKeyResponse.from_dict(response.json())++ return response_201++ if response.status_code == 400:+ response_400 = ErrorResponse.from_dict(response.json())++ return response_400++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if response.status_code == 403:+ response_403 = ErrorResponse.from_dict(response.json())++ return response_403++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[CreateKeyResponse | ErrorResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ *,+ client: AuthenticatedClient | Client,+ body: CreateKeyRequest,+) -> Response[CreateKeyResponse | ErrorResponse]:+ """Create a new API key++ Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is+ shown exactly once.++ Args:+ body (CreateKeyRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[CreateKeyResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ body=body,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ *,+ client: AuthenticatedClient | Client,+ body: CreateKeyRequest,+) -> CreateKeyResponse | ErrorResponse | None:+ """Create a new API key++ Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is+ shown exactly once.++ Args:+ body (CreateKeyRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ CreateKeyResponse | ErrorResponse+ """++ return sync_detailed(+ client=client,+ body=body,+ ).parsed+++async def asyncio_detailed(+ *,+ client: AuthenticatedClient | Client,+ body: CreateKeyRequest,+) -> Response[CreateKeyResponse | ErrorResponse]:+ """Create a new API key++ Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is+ shown exactly once.++ Args:+ body (CreateKeyRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[CreateKeyResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ body=body,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ *,+ client: AuthenticatedClient | Client,+ body: CreateKeyRequest,+) -> CreateKeyResponse | ErrorResponse | None:+ """Create a new API key++ Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is+ shown exactly once.++ Args:+ body (CreateKeyRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ CreateKeyResponse | ErrorResponse+ """++ return (+ await asyncio_detailed(+ client=client,+ body=body,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/keys/delete_key.py b/libs/fleet/python-sdk/cua_train/api/keys/delete_key.pynew file mode 100644index 0000000000..05dd935582--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/keys/delete_key.py@@ -0,0 +1,160 @@+from http import HTTPStatus+from typing import Any, cast+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.error_response import ErrorResponse+from ...types import Response+++def _get_kwargs(+ id: str,+) -> dict[str, Any]:++ _kwargs: dict[str, Any] = {+ "method": "delete",+ "url": "/api/keys/{id}".format(+ id=quote(str(id), safe=""),+ ),+ }++ return _kwargs+++def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Any | ErrorResponse | None:+ if response.status_code == 204:+ response_204 = cast(Any, None)+ return response_204++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if response.status_code == 403:+ response_403 = ErrorResponse.from_dict(response.json())++ return response_403++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[Any | ErrorResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[Any | ErrorResponse]:+ """Revoke an API key by Keycloak client UUID++ Args:+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[Any | ErrorResponse]+ """++ kwargs = _get_kwargs(+ id=id,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Any | ErrorResponse | None:+ """Revoke an API key by Keycloak client UUID++ Args:+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Any | ErrorResponse+ """++ return sync_detailed(+ id=id,+ client=client,+ ).parsed+++async def asyncio_detailed(+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[Any | ErrorResponse]:+ """Revoke an API key by Keycloak client UUID++ Args:+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[Any | ErrorResponse]+ """++ kwargs = _get_kwargs(+ id=id,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Any | ErrorResponse | None:+ """Revoke an API key by Keycloak client UUID++ Args:+ id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Any | ErrorResponse+ """++ return (+ await asyncio_detailed(+ id=id,+ client=client,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/keys/list_keys.py b/libs/fleet/python-sdk/cua_train/api/keys/list_keys.pynew file mode 100644index 0000000000..5b3936ff2f--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/keys/list_keys.py@@ -0,0 +1,134 @@+from http import HTTPStatus+from typing import Any++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.error_response import ErrorResponse+from ...models.list_keys_response import ListKeysResponse+from ...types import Response+++def _get_kwargs() -> dict[str, Any]:++ _kwargs: dict[str, Any] = {+ "method": "get",+ "url": "/api/keys",+ }++ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> ErrorResponse | ListKeysResponse | None:+ if response.status_code == 200:+ response_200 = ListKeysResponse.from_dict(response.json())++ return response_200++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[ErrorResponse | ListKeysResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ *,+ client: AuthenticatedClient | Client,+) -> Response[ErrorResponse | ListKeysResponse]:+ """List the calling user's API keys++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[ErrorResponse | ListKeysResponse]+ """++ kwargs = _get_kwargs()++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ *,+ client: AuthenticatedClient | Client,+) -> ErrorResponse | ListKeysResponse | None:+ """List the calling user's API keys++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ ErrorResponse | ListKeysResponse+ """++ return sync_detailed(+ client=client,+ ).parsed+++async def asyncio_detailed(+ *,+ client: AuthenticatedClient | Client,+) -> Response[ErrorResponse | ListKeysResponse]:+ """List the calling user's API keys++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[ErrorResponse | ListKeysResponse]+ """++ kwargs = _get_kwargs()++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ *,+ client: AuthenticatedClient | Client,+) -> ErrorResponse | ListKeysResponse | None:+ """List the calling user's API keys++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ ErrorResponse | ListKeysResponse+ """++ return (+ await asyncio_detailed(+ client=client,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/label/__init__.py b/libs/fleet/python-sdk/cua_train/api/label/__init__.pynew file mode 100644index 0000000000..2d7c0b23da--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/label/__init__.py@@ -0,0 +1 @@+"""Contains endpoint functions for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/label/cancel_label.py b/libs/fleet/python-sdk/cua_train/api/label/cancel_label.pynew file mode 100644index 0000000000..c22be8df0f--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/label/cancel_label.py@@ -0,0 +1,188 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.cancel_label_response import CancelLabelResponse+from ...models.error_response import ErrorResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ label: str,+) -> dict[str, Any]:++ _kwargs: dict[str, Any] = {+ "method": "delete",+ "url": "/api/label/{pool}/{label}".format(+ pool=quote(str(pool), safe=""),+ label=quote(str(label), safe=""),+ ),+ }++ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> CancelLabelResponse | ErrorResponse | None:+ if response.status_code == 200:+ response_200 = CancelLabelResponse.from_dict(response.json())++ return response_200++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if response.status_code == 404:+ response_404 = ErrorResponse.from_dict(response.json())++ return response_404++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[CancelLabelResponse | ErrorResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[CancelLabelResponse | ErrorResponse]:+ """Cancel every non-terminal batch under a label (scoped to pool)++ Cancels only batches submitted under `{pool}`; same label in other pools is untouched.++ Args:+ pool (str):+ label (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[CancelLabelResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ label=label,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+) -> CancelLabelResponse | ErrorResponse | None:+ """Cancel every non-terminal batch under a label (scoped to pool)++ Cancels only batches submitted under `{pool}`; same label in other pools is untouched.++ Args:+ pool (str):+ label (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ CancelLabelResponse | ErrorResponse+ """++ return sync_detailed(+ pool=pool,+ label=label,+ client=client,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[CancelLabelResponse | ErrorResponse]:+ """Cancel every non-terminal batch under a label (scoped to pool)++ Cancels only batches submitted under `{pool}`; same label in other pools is untouched.++ Args:+ pool (str):+ label (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[CancelLabelResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ label=label,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+) -> CancelLabelResponse | ErrorResponse | None:+ """Cancel every non-terminal batch under a label (scoped to pool)++ Cancels only batches submitted under `{pool}`; same label in other pools is untouched.++ Args:+ pool (str):+ label (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ CancelLabelResponse | ErrorResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ label=label,+ client=client,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/label/get_label_results.py b/libs/fleet/python-sdk/cua_train/api/label/get_label_results.pynew file mode 100644index 0000000000..9083fd115a--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/label/get_label_results.py@@ -0,0 +1,227 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.error_response import ErrorResponse+from ...models.label_in_progress_response import LabelInProgressResponse+from ...models.label_results_response import LabelResultsResponse+from ...types import UNSET, Response, Unset+++def _get_kwargs(+ pool: str,+ label: str,+ *,+ completed_only: bool | Unset = UNSET,+) -> dict[str, Any]:++ params: dict[str, Any] = {}++ params["completed_only"] = completed_only++ params = {k: v for k, v in params.items() if v is not UNSET and v is not None}++ _kwargs: dict[str, Any] = {+ "method": "get",+ "url": "/api/label/{pool}/{label}/results".format(+ pool=quote(str(pool), safe=""),+ label=quote(str(label), safe=""),+ ),+ "params": params,+ }++ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> ErrorResponse | LabelInProgressResponse | LabelResultsResponse | None:+ if response.status_code == 200:+ response_200 = LabelResultsResponse.from_dict(response.json())++ return response_200++ if response.status_code == 202:+ response_202 = LabelInProgressResponse.from_dict(response.json())++ return response_202++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if response.status_code == 404:+ response_404 = ErrorResponse.from_dict(response.json())++ return response_404++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+ completed_only: bool | Unset = UNSET,+) -> Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]:+ """Aggregate results for all batches under a pool+label++ Default mode returns 200 only once every matched batch is completed.+ Pass `?completed_only=true` to drain partial results (200 with the+ filtered subset; non-completed batches are visible via status).+ Aggregates only batches submitted under `{pool}`.++ Args:+ pool (str):+ label (str):+ completed_only (bool | Unset):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ label=label,+ completed_only=completed_only,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+ completed_only: bool | Unset = UNSET,+) -> ErrorResponse | LabelInProgressResponse | LabelResultsResponse | None:+ """Aggregate results for all batches under a pool+label++ Default mode returns 200 only once every matched batch is completed.+ Pass `?completed_only=true` to drain partial results (200 with the+ filtered subset; non-completed batches are visible via status).+ Aggregates only batches submitted under `{pool}`.++ Args:+ pool (str):+ label (str):+ completed_only (bool | Unset):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ ErrorResponse | LabelInProgressResponse | LabelResultsResponse+ """++ return sync_detailed(+ pool=pool,+ label=label,+ client=client,+ completed_only=completed_only,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+ completed_only: bool | Unset = UNSET,+) -> Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]:+ """Aggregate results for all batches under a pool+label++ Default mode returns 200 only once every matched batch is completed.+ Pass `?completed_only=true` to drain partial results (200 with the+ filtered subset; non-completed batches are visible via status).+ Aggregates only batches submitted under `{pool}`.++ Args:+ pool (str):+ label (str):+ completed_only (bool | Unset):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ label=label,+ completed_only=completed_only,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+ completed_only: bool | Unset = UNSET,+) -> ErrorResponse | LabelInProgressResponse | LabelResultsResponse | None:+ """Aggregate results for all batches under a pool+label++ Default mode returns 200 only once every matched batch is completed.+ Pass `?completed_only=true` to drain partial results (200 with the+ filtered subset; non-completed batches are visible via status).+ Aggregates only batches submitted under `{pool}`.++ Args:+ pool (str):+ label (str):+ completed_only (bool | Unset):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ ErrorResponse | LabelInProgressResponse | LabelResultsResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ label=label,+ client=client,+ completed_only=completed_only,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/label/get_label_status.py b/libs/fleet/python-sdk/cua_train/api/label/get_label_status.pynew file mode 100644index 0000000000..815a0f9507--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/label/get_label_status.py@@ -0,0 +1,192 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.error_response import ErrorResponse+from ...models.label_status_response import LabelStatusResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ label: str,+) -> dict[str, Any]:++ _kwargs: dict[str, Any] = {+ "method": "get",+ "url": "/api/label/{pool}/{label}/status".format(+ pool=quote(str(pool), safe=""),+ label=quote(str(label), safe=""),+ ),+ }++ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> ErrorResponse | LabelStatusResponse | None:+ if response.status_code == 200:+ response_200 = LabelStatusResponse.from_dict(response.json())++ return response_200++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if response.status_code == 404:+ response_404 = ErrorResponse.from_dict(response.json())++ return response_404++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[ErrorResponse | LabelStatusResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[ErrorResponse | LabelStatusResponse]:+ """Aggregate status for all batches under a pool+label++ Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are+ invisible.++ Args:+ pool (str):+ label (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[ErrorResponse | LabelStatusResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ label=label,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+) -> ErrorResponse | LabelStatusResponse | None:+ """Aggregate status for all batches under a pool+label++ Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are+ invisible.++ Args:+ pool (str):+ label (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ ErrorResponse | LabelStatusResponse+ """++ return sync_detailed(+ pool=pool,+ label=label,+ client=client,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[ErrorResponse | LabelStatusResponse]:+ """Aggregate status for all batches under a pool+label++ Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are+ invisible.++ Args:+ pool (str):+ label (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[ErrorResponse | LabelStatusResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ label=label,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+) -> ErrorResponse | LabelStatusResponse | None:+ """Aggregate status for all batches under a pool+label++ Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are+ invisible.++ Args:+ pool (str):+ label (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ ErrorResponse | LabelStatusResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ label=label,+ client=client,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/label/submit_label_batch.py b/libs/fleet/python-sdk/cua_train/api/label/submit_label_batch.pynew file mode 100644index 0000000000..3131b4242a--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/label/submit_label_batch.py@@ -0,0 +1,225 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.batch_submit_request import BatchSubmitRequest+from ...models.batch_submit_response import BatchSubmitResponse+from ...models.error_response import ErrorResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ label: str,+ *,+ body: BatchSubmitRequest,+) -> dict[str, Any]:+ headers: dict[str, Any] = {}++ _kwargs: dict[str, Any] = {+ "method": "post",+ "url": "/api/label/{pool}/{label}/batch".format(+ pool=quote(str(pool), safe=""),+ label=quote(str(label), safe=""),+ ),+ }++ _kwargs["json"] = body.to_dict()++ headers["Content-Type"] = "application/json"++ _kwargs["headers"] = headers+ return _kwargs+++def _parse_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> BatchSubmitResponse | ErrorResponse | None:+ if response.status_code == 202:+ response_202 = BatchSubmitResponse.from_dict(response.json())++ return response_202++ if response.status_code == 400:+ response_400 = ErrorResponse.from_dict(response.json())++ return response_400++ if response.status_code == 401:+ response_401 = ErrorResponse.from_dict(response.json())++ return response_401++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(+ *, client: AuthenticatedClient | Client, response: httpx.Response+) -> Response[BatchSubmitResponse | ErrorResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+ body: BatchSubmitRequest,+) -> Response[BatchSubmitResponse | ErrorResponse]:+ """Submit a batch under a pool and label++ Same as `/api/batch/{pool}/submit` but pins the batch's `name`+ field to the URL label, overriding any value in the body. The+ label is scoped to `{pool}`; aggregate routes under+ `/api/label/{pool}/{label}/*` only see batches submitted to the+ same pool.++ Args:+ pool (str):+ label (str):+ body (BatchSubmitRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[BatchSubmitResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ label=label,+ body=body,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+ body: BatchSubmitRequest,+) -> BatchSubmitResponse | ErrorResponse | None:+ """Submit a batch under a pool and label++ Same as `/api/batch/{pool}/submit` but pins the batch's `name`+ field to the URL label, overriding any value in the body. The+ label is scoped to `{pool}`; aggregate routes under+ `/api/label/{pool}/{label}/*` only see batches submitted to the+ same pool.++ Args:+ pool (str):+ label (str):+ body (BatchSubmitRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ BatchSubmitResponse | ErrorResponse+ """++ return sync_detailed(+ pool=pool,+ label=label,+ client=client,+ body=body,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+ body: BatchSubmitRequest,+) -> Response[BatchSubmitResponse | ErrorResponse]:+ """Submit a batch under a pool and label++ Same as `/api/batch/{pool}/submit` but pins the batch's `name`+ field to the URL label, overriding any value in the body. The+ label is scoped to `{pool}`; aggregate routes under+ `/api/label/{pool}/{label}/*` only see batches submitted to the+ same pool.++ Args:+ pool (str):+ label (str):+ body (BatchSubmitRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[BatchSubmitResponse | ErrorResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ label=label,+ body=body,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ label: str,+ *,+ client: AuthenticatedClient | Client,+ body: BatchSubmitRequest,+) -> BatchSubmitResponse | ErrorResponse | None:+ """Submit a batch under a pool and label++ Same as `/api/batch/{pool}/submit` but pins the batch's `name`+ field to the URL label, overriding any value in the body. The+ label is scoped to `{pool}`; aggregate routes under+ `/api/label/{pool}/{label}/*` only see batches submitted to the+ same pool.++ Args:+ pool (str):+ label (str):+ body (BatchSubmitRequest):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ BatchSubmitResponse | ErrorResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ label=label,+ client=client,+ body=body,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/lanes/__init__.py b/libs/fleet/python-sdk/cua_train/api/lanes/__init__.pynew file mode 100644index 0000000000..2d7c0b23da--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/lanes/__init__.py@@ -0,0 +1 @@+"""Contains endpoint functions for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/lanes/create_lane_lanes_post.py b/libs/fleet/python-sdk/cua_train/api/lanes/create_lane_lanes_post.pynew file mode 100644index 0000000000..0b99cd2dc1--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/lanes/create_lane_lanes_post.py@@ -0,0 +1,220 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.lane_create_request import LaneCreateRequest+from ...models.lane_response import LaneResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ *,+ body: LaneCreateRequest,+) -> dict[str, Any]:+ headers: dict[str, Any] = {}++ _kwargs: dict[str, Any] = {+ "method": "post",+ "url": "/api/gateway/{pool}/lanes".format(+ pool=quote(str(pool), safe=""),+ ),+ }++ _kwargs["json"] = body.to_dict()++ headers["Content-Type"] = "application/json"++ _kwargs["headers"] = headers+ return _kwargs+++def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> LaneResponse | None:+ if response.status_code == 200:+ response_200 = LaneResponse.from_dict(response.json())++ return response_200++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[LaneResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: LaneCreateRequest,+) -> Response[LaneResponse]:+ """Create Lane++ Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.++ The lane id is the stable handle the customer holds. The+ underlying claim CR's name rotates on swap; the lane id does+ not. The initial bind is via the normal queue+CAS-PATCH flow,+ same as /reset.++ Args:+ pool (str):+ body (LaneCreateRequest): Body of POST /lanes.++ ``ttl_seconds`` is the absolute time the claim is reserved for;+ after that the reaper deletes it. With ``autoRenew=true`` the lane+ auto-renew timer in pool-operator pushes this forward, so the+ customer's effective TTL is "as long as the lane exists".++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[LaneResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ body=body,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: LaneCreateRequest,+) -> LaneResponse | None:+ """Create Lane++ Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.++ The lane id is the stable handle the customer holds. The+ underlying claim CR's name rotates on swap; the lane id does+ not. The initial bind is via the normal queue+CAS-PATCH flow,+ same as /reset.++ Args:+ pool (str):+ body (LaneCreateRequest): Body of POST /lanes.++ ``ttl_seconds`` is the absolute time the claim is reserved for;+ after that the reaper deletes it. With ``autoRenew=true`` the lane+ auto-renew timer in pool-operator pushes this forward, so the+ customer's effective TTL is "as long as the lane exists".++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ LaneResponse+ """++ return sync_detailed(+ pool=pool,+ client=client,+ body=body,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: LaneCreateRequest,+) -> Response[LaneResponse]:+ """Create Lane++ Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.++ The lane id is the stable handle the customer holds. The+ underlying claim CR's name rotates on swap; the lane id does+ not. The initial bind is via the normal queue+CAS-PATCH flow,+ same as /reset.++ Args:+ pool (str):+ body (LaneCreateRequest): Body of POST /lanes.++ ``ttl_seconds`` is the absolute time the claim is reserved for;+ after that the reaper deletes it. With ``autoRenew=true`` the lane+ auto-renew timer in pool-operator pushes this forward, so the+ customer's effective TTL is "as long as the lane exists".++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[LaneResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ body=body,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ *,+ client: AuthenticatedClient | Client,+ body: LaneCreateRequest,+) -> LaneResponse | None:+ """Create Lane++ Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.++ The lane id is the stable handle the customer holds. The+ underlying claim CR's name rotates on swap; the lane id does+ not. The initial bind is via the normal queue+CAS-PATCH flow,+ same as /reset.++ Args:+ pool (str):+ body (LaneCreateRequest): Body of POST /lanes.++ ``ttl_seconds`` is the absolute time the claim is reserved for;+ after that the reaper deletes it. With ``autoRenew=true`` the lane+ auto-renew timer in pool-operator pushes this forward, so the+ customer's effective TTL is "as long as the lane exists".++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ LaneResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ client=client,+ body=body,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/lanes/delete_lane_lanes_lane_id_delete.py b/libs/fleet/python-sdk/cua_train/api/lanes/delete_lane_lanes_lane_id_delete.pynew file mode 100644index 0000000000..970656aa75--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/lanes/delete_lane_lanes_lane_id_delete.py@@ -0,0 +1,173 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.lane_delete_response import LaneDeleteResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ lane_id: str,+) -> dict[str, Any]:++ _kwargs: dict[str, Any] = {+ "method": "delete",+ "url": "/api/gateway/{pool}/lanes/{lane_id}".format(+ pool=quote(str(pool), safe=""),+ lane_id=quote(str(lane_id), safe=""),+ ),+ }++ return _kwargs+++def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> LaneDeleteResponse | None:+ if response.status_code == 200:+ response_200 = LaneDeleteResponse.from_dict(response.json())++ return response_200++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[LaneDeleteResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ lane_id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[LaneDeleteResponse]:+ """Delete Lane++ Release the lane's bound claim. Idempotent.++ Args:+ pool (str):+ lane_id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[LaneDeleteResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ lane_id=lane_id,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ lane_id: str,+ *,+ client: AuthenticatedClient | Client,+) -> LaneDeleteResponse | None:+ """Delete Lane++ Release the lane's bound claim. Idempotent.++ Args:+ pool (str):+ lane_id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ LaneDeleteResponse+ """++ return sync_detailed(+ pool=pool,+ lane_id=lane_id,+ client=client,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ lane_id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[LaneDeleteResponse]:+ """Delete Lane++ Release the lane's bound claim. Idempotent.++ Args:+ pool (str):+ lane_id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[LaneDeleteResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ lane_id=lane_id,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ lane_id: str,+ *,+ client: AuthenticatedClient | Client,+) -> LaneDeleteResponse | None:+ """Delete Lane++ Release the lane's bound claim. Idempotent.++ Args:+ pool (str):+ lane_id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ LaneDeleteResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ lane_id=lane_id,+ client=client,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/lanes/swap_lanes_lane_id_swap_post.py b/libs/fleet/python-sdk/cua_train/api/lanes/swap_lanes_lane_id_swap_post.pynew file mode 100644index 0000000000..5373481c33--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/api/lanes/swap_lanes_lane_id_swap_post.py@@ -0,0 +1,193 @@+from http import HTTPStatus+from typing import Any+from urllib.parse import quote++import httpx++from ... import errors+from ...client import AuthenticatedClient, Client+from ...models.lane_swap_response import LaneSwapResponse+from ...types import Response+++def _get_kwargs(+ pool: str,+ lane_id: str,+) -> dict[str, Any]:++ _kwargs: dict[str, Any] = {+ "method": "post",+ "url": "/api/gateway/{pool}/lanes/{lane_id}/swap".format(+ pool=quote(str(pool), safe=""),+ lane_id=quote(str(lane_id), safe=""),+ ),+ }++ return _kwargs+++def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> LaneSwapResponse | None:+ if response.status_code == 200:+ response_200 = LaneSwapResponse.from_dict(response.json())++ return response_200++ if client.raise_on_unexpected_status:+ raise errors.UnexpectedStatus(response.status_code, response.content)+ else:+ return None+++def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[LaneSwapResponse]:+ return Response(+ status_code=HTTPStatus(response.status_code),+ content=response.content,+ headers=response.headers,+ parsed=_parse_response(client=client, response=response),+ )+++def sync_detailed(+ pool: str,+ lane_id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[LaneSwapResponse]:+ """Swap++ New-first claim rotation for ``lane_id``.++ Calls into the pure protocol body in osgym/lane_swap.py with a+ K8s-backed SwapDeps. The lane keeps its bound VM if the swap+ bind times out (SwapAtomicity); the new vm_id is returned on+ success.++ Args:+ pool (str):+ lane_id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[LaneSwapResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ lane_id=lane_id,+ )++ response = client.get_httpx_client().request(+ **kwargs,+ )++ return _build_response(client=client, response=response)+++def sync(+ pool: str,+ lane_id: str,+ *,+ client: AuthenticatedClient | Client,+) -> LaneSwapResponse | None:+ """Swap++ New-first claim rotation for ``lane_id``.++ Calls into the pure protocol body in osgym/lane_swap.py with a+ K8s-backed SwapDeps. The lane keeps its bound VM if the swap+ bind times out (SwapAtomicity); the new vm_id is returned on+ success.++ Args:+ pool (str):+ lane_id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ LaneSwapResponse+ """++ return sync_detailed(+ pool=pool,+ lane_id=lane_id,+ client=client,+ ).parsed+++async def asyncio_detailed(+ pool: str,+ lane_id: str,+ *,+ client: AuthenticatedClient | Client,+) -> Response[LaneSwapResponse]:+ """Swap++ New-first claim rotation for ``lane_id``.++ Calls into the pure protocol body in osgym/lane_swap.py with a+ K8s-backed SwapDeps. The lane keeps its bound VM if the swap+ bind times out (SwapAtomicity); the new vm_id is returned on+ success.++ Args:+ pool (str):+ lane_id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ Response[LaneSwapResponse]+ """++ kwargs = _get_kwargs(+ pool=pool,+ lane_id=lane_id,+ )++ response = await client.get_async_httpx_client().request(**kwargs)++ return _build_response(client=client, response=response)+++async def asyncio(+ pool: str,+ lane_id: str,+ *,+ client: AuthenticatedClient | Client,+) -> LaneSwapResponse | None:+ """Swap++ New-first claim rotation for ``lane_id``.++ Calls into the pure protocol body in osgym/lane_swap.py with a+ K8s-backed SwapDeps. The lane keeps its bound VM if the swap+ bind times out (SwapAtomicity); the new vm_id is returned on+ success.++ Args:+ pool (str):+ lane_id (str):++ Raises:+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.+ httpx.TimeoutException: If the request takes longer than Client.timeout.++ Returns:+ LaneSwapResponse+ """++ return (+ await asyncio_detailed(+ pool=pool,+ lane_id=lane_id,+ client=client,+ )+ ).parseddiff --git a/libs/fleet/python-sdk/cua_train/client.py b/libs/fleet/python-sdk/cua_train/client.pynew file mode 100644index 0000000000..1b7055ab87--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/client.py@@ -0,0 +1,268 @@+import ssl+from typing import Any++import httpx+from attrs import define, evolve, field+++@define+class Client:+ """A class for keeping track of data related to the API++ The following are accepted as keyword arguments and will be used to construct httpx Clients internally:++ ``base_url``: The base URL for the API, all requests are made to a relative path to this URL++ ``cookies``: A dictionary of cookies to be sent with every request++ ``headers``: A dictionary of headers to be sent with every request++ ``timeout``: The maximum amount of a time a request can take. API functions will raise+ httpx.TimeoutException if this is exceeded.++ ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,+ but can be set to False for testing purposes.++ ``follow_redirects``: Whether or not to follow redirects. Default value is False.++ ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.+++ Attributes:+ raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a+ status code that was not documented in the source OpenAPI document. Can also be provided as a keyword+ argument to the constructor.+ """++ raise_on_unexpected_status: bool = field(default=False, kw_only=True)+ _base_url: str = field(alias="base_url")+ _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")+ _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")+ _timeout: httpx.Timeout | None = field(default=None, kw_only=True, alias="timeout")+ _verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl")+ _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")+ _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")+ _client: httpx.Client | None = field(default=None, init=False)+ _async_client: httpx.AsyncClient | None = field(default=None, init=False)++ def with_headers(self, headers: dict[str, str]) -> "Client":+ """Get a new client matching this one with additional headers"""+ if self._client is not None:+ self._client.headers.update(headers)+ if self._async_client is not None:+ self._async_client.headers.update(headers)+ return evolve(self, headers={**self._headers, **headers})++ def with_cookies(self, cookies: dict[str, str]) -> "Client":+ """Get a new client matching this one with additional cookies"""+ if self._client is not None:+ self._client.cookies.update(cookies)+ if self._async_client is not None:+ self._async_client.cookies.update(cookies)+ return evolve(self, cookies={**self._cookies, **cookies})++ def with_timeout(self, timeout: httpx.Timeout) -> "Client":+ """Get a new client matching this one with a new timeout configuration"""+ if self._client is not None:+ self._client.timeout = timeout+ if self._async_client is not None:+ self._async_client.timeout = timeout+ return evolve(self, timeout=timeout)++ def set_httpx_client(self, client: httpx.Client) -> "Client":+ """Manually set the underlying httpx.Client++ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.+ """+ self._client = client+ return self++ def get_httpx_client(self) -> httpx.Client:+ """Get the underlying httpx.Client, constructing a new one if not previously set"""+ if self._client is None:+ self._client = httpx.Client(+ base_url=self._base_url,+ cookies=self._cookies,+ headers=self._headers,+ timeout=self._timeout,+ verify=self._verify_ssl,+ follow_redirects=self._follow_redirects,+ **self._httpx_args,+ )+ return self._client++ def __enter__(self) -> "Client":+ """Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""+ self.get_httpx_client().__enter__()+ return self++ def __exit__(self, *args: Any, **kwargs: Any) -> None:+ """Exit a context manager for internal httpx.Client (see httpx docs)"""+ self.get_httpx_client().__exit__(*args, **kwargs)++ def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Client":+ """Manually set the underlying httpx.AsyncClient++ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.+ """+ self._async_client = async_client+ return self++ def get_async_httpx_client(self) -> httpx.AsyncClient:+ """Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""+ if self._async_client is None:+ self._async_client = httpx.AsyncClient(+ base_url=self._base_url,+ cookies=self._cookies,+ headers=self._headers,+ timeout=self._timeout,+ verify=self._verify_ssl,+ follow_redirects=self._follow_redirects,+ **self._httpx_args,+ )+ return self._async_client++ async def __aenter__(self) -> "Client":+ """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""+ await self.get_async_httpx_client().__aenter__()+ return self++ async def __aexit__(self, *args: Any, **kwargs: Any) -> None:+ """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""+ await self.get_async_httpx_client().__aexit__(*args, **kwargs)+++@define+class AuthenticatedClient:+ """A Client which has been authenticated for use on secured endpoints++ The following are accepted as keyword arguments and will be used to construct httpx Clients internally:++ ``base_url``: The base URL for the API, all requests are made to a relative path to this URL++ ``cookies``: A dictionary of cookies to be sent with every request++ ``headers``: A dictionary of headers to be sent with every request++ ``timeout``: The maximum amount of a time a request can take. API functions will raise+ httpx.TimeoutException if this is exceeded.++ ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,+ but can be set to False for testing purposes.++ ``follow_redirects``: Whether or not to follow redirects. Default value is False.++ ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.+++ Attributes:+ raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a+ status code that was not documented in the source OpenAPI document. Can also be provided as a keyword+ argument to the constructor.+ token: The token to use for authentication+ prefix: The prefix to use for the Authorization header+ auth_header_name: The name of the Authorization header+ """++ raise_on_unexpected_status: bool = field(default=False, kw_only=True)+ _base_url: str = field(alias="base_url")+ _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")+ _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")+ _timeout: httpx.Timeout | None = field(default=None, kw_only=True, alias="timeout")+ _verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl")+ _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")+ _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")+ _client: httpx.Client | None = field(default=None, init=False)+ _async_client: httpx.AsyncClient | None = field(default=None, init=False)++ token: str+ prefix: str = "Bearer"+ auth_header_name: str = "Authorization"++ def with_headers(self, headers: dict[str, str]) -> "AuthenticatedClient":+ """Get a new client matching this one with additional headers"""+ if self._client is not None:+ self._client.headers.update(headers)+ if self._async_client is not None:+ self._async_client.headers.update(headers)+ return evolve(self, headers={**self._headers, **headers})++ def with_cookies(self, cookies: dict[str, str]) -> "AuthenticatedClient":+ """Get a new client matching this one with additional cookies"""+ if self._client is not None:+ self._client.cookies.update(cookies)+ if self._async_client is not None:+ self._async_client.cookies.update(cookies)+ return evolve(self, cookies={**self._cookies, **cookies})++ def with_timeout(self, timeout: httpx.Timeout) -> "AuthenticatedClient":+ """Get a new client matching this one with a new timeout configuration"""+ if self._client is not None:+ self._client.timeout = timeout+ if self._async_client is not None:+ self._async_client.timeout = timeout+ return evolve(self, timeout=timeout)++ def set_httpx_client(self, client: httpx.Client) -> "AuthenticatedClient":+ """Manually set the underlying httpx.Client++ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.+ """+ self._client = client+ return self++ def get_httpx_client(self) -> httpx.Client:+ """Get the underlying httpx.Client, constructing a new one if not previously set"""+ if self._client is None:+ self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token+ self._client = httpx.Client(+ base_url=self._base_url,+ cookies=self._cookies,+ headers=self._headers,+ timeout=self._timeout,+ verify=self._verify_ssl,+ follow_redirects=self._follow_redirects,+ **self._httpx_args,+ )+ return self._client++ def __enter__(self) -> "AuthenticatedClient":+ """Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""+ self.get_httpx_client().__enter__()+ return self++ def __exit__(self, *args: Any, **kwargs: Any) -> None:+ """Exit a context manager for internal httpx.Client (see httpx docs)"""+ self.get_httpx_client().__exit__(*args, **kwargs)++ def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "AuthenticatedClient":+ """Manually set the underlying httpx.AsyncClient++ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.+ """+ self._async_client = async_client+ return self++ def get_async_httpx_client(self) -> httpx.AsyncClient:+ """Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""+ if self._async_client is None:+ self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token+ self._async_client = httpx.AsyncClient(+ base_url=self._base_url,+ cookies=self._cookies,+ headers=self._headers,+ timeout=self._timeout,+ verify=self._verify_ssl,+ follow_redirects=self._follow_redirects,+ **self._httpx_args,+ )+ return self._async_client++ async def __aenter__(self) -> "AuthenticatedClient":+ """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""+ await self.get_async_httpx_client().__aenter__()+ return self++ async def __aexit__(self, *args: Any, **kwargs: Any) -> None:+ """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""+ await self.get_async_httpx_client().__aexit__(*args, **kwargs)diff --git a/libs/fleet/python-sdk/cua_train/errors.py b/libs/fleet/python-sdk/cua_train/errors.pynew file mode 100644index 0000000000..5f92e76aca--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/errors.py@@ -0,0 +1,16 @@+"""Contains shared errors types that can be raised from API functions"""+++class UnexpectedStatus(Exception):+ """Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True"""++ def __init__(self, status_code: int, content: bytes):+ self.status_code = status_code+ self.content = content++ super().__init__(+ f"Unexpected status code: {status_code}\n\nResponse content:\n{content.decode(errors='ignore')}"+ )+++__all__ = ["UnexpectedStatus"]diff --git a/libs/fleet/python-sdk/cua_train/models/__init__.py b/libs/fleet/python-sdk/cua_train/models/__init__.pynew file mode 100644index 0000000000..39cb3e01a1--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/__init__.py@@ -0,0 +1,93 @@+"""Contains all the data models used in inputs/outputs"""++from .acquire_lanes_request import AcquireLanesRequest+from .acquire_lanes_response import AcquireLanesResponse+from .action import Action+from .action_parameters import ActionParameters+from .batch_in_progress_response import BatchInProgressResponse+from .batch_progress import BatchProgress+from .batch_results_response import BatchResultsResponse+from .batch_status_response import BatchStatusResponse+from .batch_submit_request import BatchSubmitRequest+from .batch_submit_response import BatchSubmitResponse+from .batch_summary import BatchSummary+from .cancel_batch_response import CancelBatchResponse+from .cancel_label_batch_item import CancelLabelBatchItem+from .cancel_label_response import CancelLabelResponse+from .create_key_request import CreateKeyRequest+from .create_key_response import CreateKeyResponse+from .error_response import ErrorResponse+from .health_response import HealthResponse+from .healthz_response import HealthzResponse+from .key_client import KeyClient+from .label_batch_summary import LabelBatchSummary+from .label_in_progress_response import LabelInProgressResponse+from .label_results_response import LabelResultsResponse+from .label_status_response import LabelStatusResponse+from .lane_create_request import LaneCreateRequest+from .lane_delete_response import LaneDeleteResponse+from .lane_response import LaneResponse+from .lane_swap_response import LaneSwapResponse+from .list_keys_response import ListKeysResponse+from .pool_list_response import PoolListResponse+from .pool_list_response_vms_item import PoolListResponseVmsItem+from .release_lanes_request import ReleaseLanesRequest+from .release_lanes_response import ReleaseLanesResponse+from .reset_request import ResetRequest+from .reset_request_task_config import ResetRequestTaskConfig+from .reset_response import ResetResponse+from .run_config import RunConfig+from .run_result import RunResult+from .screenshot_response import ScreenshotResponse+from .shutdown_request import ShutdownRequest+from .shutdown_response import ShutdownResponse+from .step_request import StepRequest+from .step_response import StepResponse+from .timing_stats import TimingStats++__all__ = (+ "AcquireLanesRequest",+ "AcquireLanesResponse",+ "Action",+ "ActionParameters",+ "BatchInProgressResponse",+ "BatchProgress",+ "BatchResultsResponse",+ "BatchStatusResponse",+ "BatchSubmitRequest",+ "BatchSubmitResponse",+ "BatchSummary",+ "CancelBatchResponse",+ "CancelLabelBatchItem",+ "CancelLabelResponse",+ "CreateKeyRequest",+ "CreateKeyResponse",+ "ErrorResponse",+ "HealthResponse",+ "HealthzResponse",+ "KeyClient",+ "LabelBatchSummary",+ "LabelInProgressResponse",+ "LabelResultsResponse",+ "LabelStatusResponse",+ "LaneCreateRequest",+ "LaneDeleteResponse",+ "LaneResponse",+ "LaneSwapResponse",+ "ListKeysResponse",+ "PoolListResponse",+ "PoolListResponseVmsItem",+ "ReleaseLanesRequest",+ "ReleaseLanesResponse",+ "ResetRequest",+ "ResetRequestTaskConfig",+ "ResetResponse",+ "RunConfig",+ "RunResult",+ "ScreenshotResponse",+ "ShutdownRequest",+ "ShutdownResponse",+ "StepRequest",+ "StepResponse",+ "TimingStats",+)diff --git a/libs/fleet/python-sdk/cua_train/models/acquire_lanes_request.py b/libs/fleet/python-sdk/cua_train/models/acquire_lanes_request.pynew file mode 100644index 0000000000..0c4d559eef--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/acquire_lanes_request.py@@ -0,0 +1,61 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="AcquireLanesRequest")+++@_attrs_define+class AcquireLanesRequest:+ """+ Attributes:+ n (int): Number of warm VM lanes to acquire.+ """++ n: int+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ n = self.n++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "n": n,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ n = d.pop("n")++ acquire_lanes_request = cls(+ n=n,+ )++ acquire_lanes_request.additional_properties = d+ return acquire_lanes_request++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/acquire_lanes_response.py b/libs/fleet/python-sdk/cua_train/models/acquire_lanes_response.pynew file mode 100644index 0000000000..94a07a9934--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/acquire_lanes_response.py@@ -0,0 +1,63 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar, cast++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="AcquireLanesResponse")+++@_attrs_define+class AcquireLanesResponse:+ """+ Attributes:+ vm_ids (list[str] | Unset): One warm VM id per acquired lane. Use as RunConfig.vm_id.+ """++ vm_ids: list[str] | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ vm_ids: list[str] | Unset = UNSET+ if not isinstance(self.vm_ids, Unset):+ vm_ids = self.vm_ids++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if vm_ids is not UNSET:+ field_dict["vm_ids"] = vm_ids++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ vm_ids = cast(list[str], d.pop("vm_ids", UNSET))++ acquire_lanes_response = cls(+ vm_ids=vm_ids,+ )++ acquire_lanes_response.additional_properties = d+ return acquire_lanes_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/action.py b/libs/fleet/python-sdk/cua_train/models/action.pynew file mode 100644index 0000000000..885240e29c--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/action.py@@ -0,0 +1,85 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.action_parameters import ActionParameters+++T = TypeVar("T", bound="Action")+++@_attrs_define+class Action:+ """+ Attributes:+ action_type (str): OSGym action type (e.g. CLICK, TYPE, KEY). Example: CLICK.+ parameters (ActionParameters | Unset): Action-type-specific parameters (e.g. `{x, y, button}` for CLICK).+ """++ action_type: str+ parameters: ActionParameters | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ action_type = self.action_type++ parameters: dict[str, Any] | Unset = UNSET+ if not isinstance(self.parameters, Unset):+ parameters = self.parameters.to_dict()++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "action_type": action_type,+ }+ )+ if parameters is not UNSET:+ field_dict["parameters"] = parameters++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.action_parameters import ActionParameters++ d = dict(src_dict)+ action_type = d.pop("action_type")++ _parameters = d.pop("parameters", UNSET)+ parameters: ActionParameters | Unset+ if isinstance(_parameters, Unset):+ parameters = UNSET+ else:+ parameters = ActionParameters.from_dict(_parameters)++ action = cls(+ action_type=action_type,+ parameters=parameters,+ )++ action.additional_properties = d+ return action++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/action_parameters.py b/libs/fleet/python-sdk/cua_train/models/action_parameters.pynew file mode 100644index 0000000000..be814ccb07--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/action_parameters.py@@ -0,0 +1,47 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="ActionParameters")+++@_attrs_define+class ActionParameters:+ """Action-type-specific parameters (e.g. `{x, y, button}` for CLICK)."""++ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ action_parameters = cls()++ action_parameters.additional_properties = d+ return action_parameters++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_in_progress_response.py b/libs/fleet/python-sdk/cua_train/models/batch_in_progress_response.pynew file mode 100644index 0000000000..e5fe35fb10--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/batch_in_progress_response.py@@ -0,0 +1,79 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="BatchInProgressResponse")+++@_attrs_define+class BatchInProgressResponse:+ """+ Attributes:+ batch_id (str | Unset):+ status (str | Unset):+ message (str | Unset):+ """++ batch_id: str | Unset = UNSET+ status: str | Unset = UNSET+ message: str | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ batch_id = self.batch_id++ status = self.status++ message = self.message++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if batch_id is not UNSET:+ field_dict["batch_id"] = batch_id+ if status is not UNSET:+ field_dict["status"] = status+ if message is not UNSET:+ field_dict["message"] = message++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ batch_id = d.pop("batch_id", UNSET)++ status = d.pop("status", UNSET)++ message = d.pop("message", UNSET)++ batch_in_progress_response = cls(+ batch_id=batch_id,+ status=status,+ message=message,+ )++ batch_in_progress_response.additional_properties = d+ return batch_in_progress_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_progress.py b/libs/fleet/python-sdk/cua_train/models/batch_progress.pynew file mode 100644index 0000000000..c5e3f97322--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/batch_progress.py@@ -0,0 +1,88 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="BatchProgress")+++@_attrs_define+class BatchProgress:+ """+ Attributes:+ completed (int | Unset):+ total (int | Unset):+ ok (int | Unset):+ failed (int | Unset):+ """++ completed: int | Unset = UNSET+ total: int | Unset = UNSET+ ok: int | Unset = UNSET+ failed: int | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ completed = self.completed++ total = self.total++ ok = self.ok++ failed = self.failed++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if completed is not UNSET:+ field_dict["completed"] = completed+ if total is not UNSET:+ field_dict["total"] = total+ if ok is not UNSET:+ field_dict["ok"] = ok+ if failed is not UNSET:+ field_dict["failed"] = failed++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ completed = d.pop("completed", UNSET)++ total = d.pop("total", UNSET)++ ok = d.pop("ok", UNSET)++ failed = d.pop("failed", UNSET)++ batch_progress = cls(+ completed=completed,+ total=total,+ ok=ok,+ failed=failed,+ )++ batch_progress.additional_properties = d+ return batch_progress++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_results_response.py b/libs/fleet/python-sdk/cua_train/models/batch_results_response.pynew file mode 100644index 0000000000..1d9590fbc6--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/batch_results_response.py@@ -0,0 +1,151 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.batch_summary import BatchSummary+ from ..models.run_result import RunResult+++T = TypeVar("T", bound="BatchResultsResponse")+++@_attrs_define+class BatchResultsResponse:+ """+ Attributes:+ batch_id (str | Unset):+ name (str | Unset):+ status (str | Unset):+ runs (list[RunResult] | Unset):+ s3_bucket (str | Unset):+ s3_key (str | Unset):+ s3_presigned_url (str | Unset):+ summary (BatchSummary | Unset):+ """++ batch_id: str | Unset = UNSET+ name: str | Unset = UNSET+ status: str | Unset = UNSET+ runs: list[RunResult] | Unset = UNSET+ s3_bucket: str | Unset = UNSET+ s3_key: str | Unset = UNSET+ s3_presigned_url: str | Unset = UNSET+ summary: BatchSummary | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ batch_id = self.batch_id++ name = self.name++ status = self.status++ runs: list[dict[str, Any]] | Unset = UNSET+ if not isinstance(self.runs, Unset):+ runs = []+ for runs_item_data in self.runs:+ runs_item = runs_item_data.to_dict()+ runs.append(runs_item)++ s3_bucket = self.s3_bucket++ s3_key = self.s3_key++ s3_presigned_url = self.s3_presigned_url++ summary: dict[str, Any] | Unset = UNSET+ if not isinstance(self.summary, Unset):+ summary = self.summary.to_dict()++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if batch_id is not UNSET:+ field_dict["batch_id"] = batch_id+ if name is not UNSET:+ field_dict["name"] = name+ if status is not UNSET:+ field_dict["status"] = status+ if runs is not UNSET:+ field_dict["runs"] = runs+ if s3_bucket is not UNSET:+ field_dict["s3_bucket"] = s3_bucket+ if s3_key is not UNSET:+ field_dict["s3_key"] = s3_key+ if s3_presigned_url is not UNSET:+ field_dict["s3_presigned_url"] = s3_presigned_url+ if summary is not UNSET:+ field_dict["summary"] = summary++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.batch_summary import BatchSummary+ from ..models.run_result import RunResult++ d = dict(src_dict)+ batch_id = d.pop("batch_id", UNSET)++ name = d.pop("name", UNSET)++ status = d.pop("status", UNSET)++ _runs = d.pop("runs", UNSET)+ runs: list[RunResult] | Unset = UNSET+ if _runs is not UNSET:+ runs = []+ for runs_item_data in _runs:+ runs_item = RunResult.from_dict(runs_item_data)++ runs.append(runs_item)++ s3_bucket = d.pop("s3_bucket", UNSET)++ s3_key = d.pop("s3_key", UNSET)++ s3_presigned_url = d.pop("s3_presigned_url", UNSET)++ _summary = d.pop("summary", UNSET)+ summary: BatchSummary | Unset+ if isinstance(_summary, Unset):+ summary = UNSET+ else:+ summary = BatchSummary.from_dict(_summary)++ batch_results_response = cls(+ batch_id=batch_id,+ name=name,+ status=status,+ runs=runs,+ s3_bucket=s3_bucket,+ s3_key=s3_key,+ s3_presigned_url=s3_presigned_url,+ summary=summary,+ )++ batch_results_response.additional_properties = d+ return batch_results_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_status_response.py b/libs/fleet/python-sdk/cua_train/models/batch_status_response.pynew file mode 100644index 0000000000..8287aea218--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/batch_status_response.py@@ -0,0 +1,134 @@+from __future__ import annotations++import datetime+from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.batch_progress import BatchProgress+++T = TypeVar("T", bound="BatchStatusResponse")+++@_attrs_define+class BatchStatusResponse:+ """+ Attributes:+ batch_id (str | Unset):+ name (str | Unset):+ status (str | Unset):+ progress (BatchProgress | Unset):+ created_at (datetime.datetime | Unset):+ updated_at (datetime.datetime | Unset):+ """++ batch_id: str | Unset = UNSET+ name: str | Unset = UNSET+ status: str | Unset = UNSET+ progress: BatchProgress | Unset = UNSET+ created_at: datetime.datetime | Unset = UNSET+ updated_at: datetime.datetime | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ batch_id = self.batch_id++ name = self.name++ status = self.status++ progress: dict[str, Any] | Unset = UNSET+ if not isinstance(self.progress, Unset):+ progress = self.progress.to_dict()++ created_at: str | Unset = UNSET+ if not isinstance(self.created_at, Unset):+ created_at = self.created_at.isoformat()++ updated_at: str | Unset = UNSET+ if not isinstance(self.updated_at, Unset):+ updated_at = self.updated_at.isoformat()++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if batch_id is not UNSET:+ field_dict["batch_id"] = batch_id+ if name is not UNSET:+ field_dict["name"] = name+ if status is not UNSET:+ field_dict["status"] = status+ if progress is not UNSET:+ field_dict["progress"] = progress+ if created_at is not UNSET:+ field_dict["created_at"] = created_at+ if updated_at is not UNSET:+ field_dict["updated_at"] = updated_at++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.batch_progress import BatchProgress++ d = dict(src_dict)+ batch_id = d.pop("batch_id", UNSET)++ name = d.pop("name", UNSET)++ status = d.pop("status", UNSET)++ _progress = d.pop("progress", UNSET)+ progress: BatchProgress | Unset+ if isinstance(_progress, Unset):+ progress = UNSET+ else:+ progress = BatchProgress.from_dict(_progress)++ _created_at = d.pop("created_at", UNSET)+ created_at: datetime.datetime | Unset+ if isinstance(_created_at, Unset):+ created_at = UNSET+ else:+ created_at = datetime.datetime.fromisoformat(_created_at)++ _updated_at = d.pop("updated_at", UNSET)+ updated_at: datetime.datetime | Unset+ if isinstance(_updated_at, Unset):+ updated_at = UNSET+ else:+ updated_at = datetime.datetime.fromisoformat(_updated_at)++ batch_status_response = cls(+ batch_id=batch_id,+ name=name,+ status=status,+ progress=progress,+ created_at=created_at,+ updated_at=updated_at,+ )++ batch_status_response.additional_properties = d+ return batch_status_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_submit_request.py b/libs/fleet/python-sdk/cua_train/models/batch_submit_request.pynew file mode 100644index 0000000000..37b2956ce1--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/batch_submit_request.py@@ -0,0 +1,115 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.run_config import RunConfig+++T = TypeVar("T", bound="BatchSubmitRequest")+++@_attrs_define+class BatchSubmitRequest:+ """+ Attributes:+ runs (list[RunConfig]):+ concurrency (int | Unset): Default: 10.+ pool_name (str | Unset): Optional — must match the URL `{pool}` if provided; ignored otherwise.+ name (str | Unset): Optional batch name. Overridden by the URL `{label}` on label routes.+ keep_warm (bool | Unset): Leave each run's VM running when the run ends (instead of shutting it down), so a+ follow-up batch can reattach to it via RunConfig.vm_id (read each lane's surviving id from RunResult.vm_id).+ Best-effort: a warm VM is reaped after its claim TTL (~minutes), after which reattach falls back to a fresh VM.+ """++ runs: list[RunConfig]+ concurrency: int | Unset = 10+ pool_name: str | Unset = UNSET+ name: str | Unset = UNSET+ keep_warm: bool | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ runs = []+ for runs_item_data in self.runs:+ runs_item = runs_item_data.to_dict()+ runs.append(runs_item)++ concurrency = self.concurrency++ pool_name = self.pool_name++ name = self.name++ keep_warm = self.keep_warm++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "runs": runs,+ }+ )+ if concurrency is not UNSET:+ field_dict["concurrency"] = concurrency+ if pool_name is not UNSET:+ field_dict["pool_name"] = pool_name+ if name is not UNSET:+ field_dict["name"] = name+ if keep_warm is not UNSET:+ field_dict["keep_warm"] = keep_warm++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.run_config import RunConfig++ d = dict(src_dict)+ runs = []+ _runs = d.pop("runs")+ for runs_item_data in _runs:+ runs_item = RunConfig.from_dict(runs_item_data)++ runs.append(runs_item)++ concurrency = d.pop("concurrency", UNSET)++ pool_name = d.pop("pool_name", UNSET)++ name = d.pop("name", UNSET)++ keep_warm = d.pop("keep_warm", UNSET)++ batch_submit_request = cls(+ runs=runs,+ concurrency=concurrency,+ pool_name=pool_name,+ name=name,+ keep_warm=keep_warm,+ )++ batch_submit_request.additional_properties = d+ return batch_submit_request++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_submit_response.py b/libs/fleet/python-sdk/cua_train/models/batch_submit_response.pynew file mode 100644index 0000000000..679370ff0e--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/batch_submit_response.py@@ -0,0 +1,96 @@+from __future__ import annotations++import datetime+from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="BatchSubmitResponse")+++@_attrs_define+class BatchSubmitResponse:+ """+ Attributes:+ batch_id (str | Unset):+ name (str | Unset):+ status (str | Unset):+ created_at (datetime.datetime | Unset):+ """++ batch_id: str | Unset = UNSET+ name: str | Unset = UNSET+ status: str | Unset = UNSET+ created_at: datetime.datetime | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ batch_id = self.batch_id++ name = self.name++ status = self.status++ created_at: str | Unset = UNSET+ if not isinstance(self.created_at, Unset):+ created_at = self.created_at.isoformat()++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if batch_id is not UNSET:+ field_dict["batch_id"] = batch_id+ if name is not UNSET:+ field_dict["name"] = name+ if status is not UNSET:+ field_dict["status"] = status+ if created_at is not UNSET:+ field_dict["created_at"] = created_at++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ batch_id = d.pop("batch_id", UNSET)++ name = d.pop("name", UNSET)++ status = d.pop("status", UNSET)++ _created_at = d.pop("created_at", UNSET)+ created_at: datetime.datetime | Unset+ if isinstance(_created_at, Unset):+ created_at = UNSET+ else:+ created_at = datetime.datetime.fromisoformat(_created_at)++ batch_submit_response = cls(+ batch_id=batch_id,+ name=name,+ status=status,+ created_at=created_at,+ )++ batch_submit_response.additional_properties = d+ return batch_submit_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_summary.py b/libs/fleet/python-sdk/cua_train/models/batch_summary.pynew file mode 100644index 0000000000..a4113f6db9--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/batch_summary.py@@ -0,0 +1,133 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.timing_stats import TimingStats+++T = TypeVar("T", bound="BatchSummary")+++@_attrs_define+class BatchSummary:+ """+ Attributes:+ n_ok (int | Unset):+ n_fail (int | Unset):+ total_wall_ms (int | Unset):+ reset_stats (TimingStats | Unset):+ step_stats (TimingStats | Unset):+ shutdown_stats (TimingStats | Unset):+ """++ n_ok: int | Unset = UNSET+ n_fail: int | Unset = UNSET+ total_wall_ms: int | Unset = UNSET+ reset_stats: TimingStats | Unset = UNSET+ step_stats: TimingStats | Unset = UNSET+ shutdown_stats: TimingStats | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ n_ok = self.n_ok++ n_fail = self.n_fail++ total_wall_ms = self.total_wall_ms++ reset_stats: dict[str, Any] | Unset = UNSET+ if not isinstance(self.reset_stats, Unset):+ reset_stats = self.reset_stats.to_dict()++ step_stats: dict[str, Any] | Unset = UNSET+ if not isinstance(self.step_stats, Unset):+ step_stats = self.step_stats.to_dict()++ shutdown_stats: dict[str, Any] | Unset = UNSET+ if not isinstance(self.shutdown_stats, Unset):+ shutdown_stats = self.shutdown_stats.to_dict()++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if n_ok is not UNSET:+ field_dict["n_ok"] = n_ok+ if n_fail is not UNSET:+ field_dict["n_fail"] = n_fail+ if total_wall_ms is not UNSET:+ field_dict["total_wall_ms"] = total_wall_ms+ if reset_stats is not UNSET:+ field_dict["reset_stats"] = reset_stats+ if step_stats is not UNSET:+ field_dict["step_stats"] = step_stats+ if shutdown_stats is not UNSET:+ field_dict["shutdown_stats"] = shutdown_stats++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.timing_stats import TimingStats++ d = dict(src_dict)+ n_ok = d.pop("n_ok", UNSET)++ n_fail = d.pop("n_fail", UNSET)++ total_wall_ms = d.pop("total_wall_ms", UNSET)++ _reset_stats = d.pop("reset_stats", UNSET)+ reset_stats: TimingStats | Unset+ if isinstance(_reset_stats, Unset):+ reset_stats = UNSET+ else:+ reset_stats = TimingStats.from_dict(_reset_stats)++ _step_stats = d.pop("step_stats", UNSET)+ step_stats: TimingStats | Unset+ if isinstance(_step_stats, Unset):+ step_stats = UNSET+ else:+ step_stats = TimingStats.from_dict(_step_stats)++ _shutdown_stats = d.pop("shutdown_stats", UNSET)+ shutdown_stats: TimingStats | Unset+ if isinstance(_shutdown_stats, Unset):+ shutdown_stats = UNSET+ else:+ shutdown_stats = TimingStats.from_dict(_shutdown_stats)++ batch_summary = cls(+ n_ok=n_ok,+ n_fail=n_fail,+ total_wall_ms=total_wall_ms,+ reset_stats=reset_stats,+ step_stats=step_stats,+ shutdown_stats=shutdown_stats,+ )++ batch_summary.additional_properties = d+ return batch_summary++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/cancel_batch_response.py b/libs/fleet/python-sdk/cua_train/models/cancel_batch_response.pynew file mode 100644index 0000000000..ace0ea24ae--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/cancel_batch_response.py@@ -0,0 +1,70 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="CancelBatchResponse")+++@_attrs_define+class CancelBatchResponse:+ """+ Attributes:+ batch_id (str | Unset):+ status (str | Unset):+ """++ batch_id: str | Unset = UNSET+ status: str | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ batch_id = self.batch_id++ status = self.status++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if batch_id is not UNSET:+ field_dict["batch_id"] = batch_id+ if status is not UNSET:+ field_dict["status"] = status++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ batch_id = d.pop("batch_id", UNSET)++ status = d.pop("status", UNSET)++ cancel_batch_response = cls(+ batch_id=batch_id,+ status=status,+ )++ cancel_batch_response.additional_properties = d+ return cancel_batch_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/cancel_label_batch_item.py b/libs/fleet/python-sdk/cua_train/models/cancel_label_batch_item.pynew file mode 100644index 0000000000..0040b5eeb4--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/cancel_label_batch_item.py@@ -0,0 +1,70 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="CancelLabelBatchItem")+++@_attrs_define+class CancelLabelBatchItem:+ """+ Attributes:+ batch_id (str | Unset):+ status (str | Unset):+ """++ batch_id: str | Unset = UNSET+ status: str | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ batch_id = self.batch_id++ status = self.status++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if batch_id is not UNSET:+ field_dict["batch_id"] = batch_id+ if status is not UNSET:+ field_dict["status"] = status++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ batch_id = d.pop("batch_id", UNSET)++ status = d.pop("status", UNSET)++ cancel_label_batch_item = cls(+ batch_id=batch_id,+ status=status,+ )++ cancel_label_batch_item.additional_properties = d+ return cancel_label_batch_item++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/cancel_label_response.py b/libs/fleet/python-sdk/cua_train/models/cancel_label_response.pynew file mode 100644index 0000000000..a135405c7c--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/cancel_label_response.py@@ -0,0 +1,115 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.cancel_label_batch_item import CancelLabelBatchItem+++T = TypeVar("T", bound="CancelLabelResponse")+++@_attrs_define+class CancelLabelResponse:+ """+ Attributes:+ label (str | Unset):+ batch_count (int | Unset):+ cancelled_count (int | Unset):+ already_done (int | Unset):+ batches (list[CancelLabelBatchItem] | Unset):+ """++ label: str | Unset = UNSET+ batch_count: int | Unset = UNSET+ cancelled_count: int | Unset = UNSET+ already_done: int | Unset = UNSET+ batches: list[CancelLabelBatchItem] | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ label = self.label++ batch_count = self.batch_count++ cancelled_count = self.cancelled_count++ already_done = self.already_done++ batches: list[dict[str, Any]] | Unset = UNSET+ if not isinstance(self.batches, Unset):+ batches = []+ for batches_item_data in self.batches:+ batches_item = batches_item_data.to_dict()+ batches.append(batches_item)++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if label is not UNSET:+ field_dict["label"] = label+ if batch_count is not UNSET:+ field_dict["batch_count"] = batch_count+ if cancelled_count is not UNSET:+ field_dict["cancelled_count"] = cancelled_count+ if already_done is not UNSET:+ field_dict["already_done"] = already_done+ if batches is not UNSET:+ field_dict["batches"] = batches++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.cancel_label_batch_item import CancelLabelBatchItem++ d = dict(src_dict)+ label = d.pop("label", UNSET)++ batch_count = d.pop("batch_count", UNSET)++ cancelled_count = d.pop("cancelled_count", UNSET)++ already_done = d.pop("already_done", UNSET)++ _batches = d.pop("batches", UNSET)+ batches: list[CancelLabelBatchItem] | Unset = UNSET+ if _batches is not UNSET:+ batches = []+ for batches_item_data in _batches:+ batches_item = CancelLabelBatchItem.from_dict(batches_item_data)++ batches.append(batches_item)++ cancel_label_response = cls(+ label=label,+ batch_count=batch_count,+ cancelled_count=cancelled_count,+ already_done=already_done,+ batches=batches,+ )++ cancel_label_response.additional_properties = d+ return cancel_label_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/create_key_request.py b/libs/fleet/python-sdk/cua_train/models/create_key_request.pynew file mode 100644index 0000000000..5a8a891095--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/create_key_request.py@@ -0,0 +1,69 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="CreateKeyRequest")+++@_attrs_define+class CreateKeyRequest:+ """+ Attributes:+ name (str): Example: ci-prod.+ namespace (str): Example: test-pool.+ """++ name: str+ namespace: str+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ name = self.name++ namespace = self.namespace++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "name": name,+ "namespace": namespace,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ name = d.pop("name")++ namespace = d.pop("namespace")++ create_key_request = cls(+ name=name,+ namespace=namespace,+ )++ create_key_request.additional_properties = d+ return create_key_request++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/create_key_response.py b/libs/fleet/python-sdk/cua_train/models/create_key_response.pynew file mode 100644index 0000000000..78b3a35ca9--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/create_key_response.py@@ -0,0 +1,97 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="CreateKeyResponse")+++@_attrs_define+class CreateKeyResponse:+ """+ Attributes:+ client_id (str | Unset):+ client_secret (str | Unset):+ name (str | Unset):+ namespace (str | Unset):+ token_url (str | Unset):+ """++ client_id: str | Unset = UNSET+ client_secret: str | Unset = UNSET+ name: str | Unset = UNSET+ namespace: str | Unset = UNSET+ token_url: str | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ client_id = self.client_id++ client_secret = self.client_secret++ name = self.name++ namespace = self.namespace++ token_url = self.token_url++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if client_id is not UNSET:+ field_dict["client_id"] = client_id+ if client_secret is not UNSET:+ field_dict["client_secret"] = client_secret+ if name is not UNSET:+ field_dict["name"] = name+ if namespace is not UNSET:+ field_dict["namespace"] = namespace+ if token_url is not UNSET:+ field_dict["token_url"] = token_url++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ client_id = d.pop("client_id", UNSET)++ client_secret = d.pop("client_secret", UNSET)++ name = d.pop("name", UNSET)++ namespace = d.pop("namespace", UNSET)++ token_url = d.pop("token_url", UNSET)++ create_key_response = cls(+ client_id=client_id,+ client_secret=client_secret,+ name=name,+ namespace=namespace,+ token_url=token_url,+ )++ create_key_response.additional_properties = d+ return create_key_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/error_response.py b/libs/fleet/python-sdk/cua_train/models/error_response.pynew file mode 100644index 0000000000..3cd602cb1e--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/error_response.py@@ -0,0 +1,61 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="ErrorResponse")+++@_attrs_define+class ErrorResponse:+ """+ Attributes:+ error (str | Unset):+ """++ error: str | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ error = self.error++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if error is not UNSET:+ field_dict["error"] = error++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ error = d.pop("error", UNSET)++ error_response = cls(+ error=error,+ )++ error_response.additional_properties = d+ return error_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/health_response.py b/libs/fleet/python-sdk/cua_train/models/health_response.pynew file mode 100644index 0000000000..8172423767--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/health_response.py@@ -0,0 +1,61 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="HealthResponse")+++@_attrs_define+class HealthResponse:+ """+ Attributes:+ ok (bool | Unset):+ """++ ok: bool | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ ok = self.ok++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if ok is not UNSET:+ field_dict["ok"] = ok++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ ok = d.pop("ok", UNSET)++ health_response = cls(+ ok=ok,+ )++ health_response.additional_properties = d+ return health_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/healthz_response.py b/libs/fleet/python-sdk/cua_train/models/healthz_response.pynew file mode 100644index 0000000000..b0d829863d--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/healthz_response.py@@ -0,0 +1,61 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="HealthzResponse")+++@_attrs_define+class HealthzResponse:+ """+ Attributes:+ status (str):+ """++ status: str+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ status = self.status++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "status": status,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ status = d.pop("status")++ healthz_response = cls(+ status=status,+ )++ healthz_response.additional_properties = d+ return healthz_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/key_client.py b/libs/fleet/python-sdk/cua_train/models/key_client.pynew file mode 100644index 0000000000..54bb017434--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/key_client.py@@ -0,0 +1,97 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="KeyClient")+++@_attrs_define+class KeyClient:+ """+ Attributes:+ id (str | Unset):+ client_id (str | Unset):+ name (str | Unset):+ namespace (str | Unset):+ owner_sub (str | Unset):+ """++ id: str | Unset = UNSET+ client_id: str | Unset = UNSET+ name: str | Unset = UNSET+ namespace: str | Unset = UNSET+ owner_sub: str | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ id = self.id++ client_id = self.client_id++ name = self.name++ namespace = self.namespace++ owner_sub = self.owner_sub++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if id is not UNSET:+ field_dict["id"] = id+ if client_id is not UNSET:+ field_dict["client_id"] = client_id+ if name is not UNSET:+ field_dict["name"] = name+ if namespace is not UNSET:+ field_dict["namespace"] = namespace+ if owner_sub is not UNSET:+ field_dict["owner_sub"] = owner_sub++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ id = d.pop("id", UNSET)++ client_id = d.pop("client_id", UNSET)++ name = d.pop("name", UNSET)++ namespace = d.pop("namespace", UNSET)++ owner_sub = d.pop("owner_sub", UNSET)++ key_client = cls(+ id=id,+ client_id=client_id,+ name=name,+ namespace=namespace,+ owner_sub=owner_sub,+ )++ key_client.additional_properties = d+ return key_client++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/label_batch_summary.py b/libs/fleet/python-sdk/cua_train/models/label_batch_summary.pynew file mode 100644index 0000000000..91f67ac805--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/label_batch_summary.py@@ -0,0 +1,143 @@+from __future__ import annotations++import datetime+from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.batch_progress import BatchProgress+++T = TypeVar("T", bound="LabelBatchSummary")+++@_attrs_define+class LabelBatchSummary:+ """+ Attributes:+ batch_id (str | Unset):+ status (str | Unset):+ progress (BatchProgress | Unset):+ created_at (datetime.datetime | Unset):+ updated_at (datetime.datetime | Unset):+ s3_key (str | Unset):+ s3_presigned_url (str | Unset):+ """++ batch_id: str | Unset = UNSET+ status: str | Unset = UNSET+ progress: BatchProgress | Unset = UNSET+ created_at: datetime.datetime | Unset = UNSET+ updated_at: datetime.datetime | Unset = UNSET+ s3_key: str | Unset = UNSET+ s3_presigned_url: str | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ batch_id = self.batch_id++ status = self.status++ progress: dict[str, Any] | Unset = UNSET+ if not isinstance(self.progress, Unset):+ progress = self.progress.to_dict()++ created_at: str | Unset = UNSET+ if not isinstance(self.created_at, Unset):+ created_at = self.created_at.isoformat()++ updated_at: str | Unset = UNSET+ if not isinstance(self.updated_at, Unset):+ updated_at = self.updated_at.isoformat()++ s3_key = self.s3_key++ s3_presigned_url = self.s3_presigned_url++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if batch_id is not UNSET:+ field_dict["batch_id"] = batch_id+ if status is not UNSET:+ field_dict["status"] = status+ if progress is not UNSET:+ field_dict["progress"] = progress+ if created_at is not UNSET:+ field_dict["created_at"] = created_at+ if updated_at is not UNSET:+ field_dict["updated_at"] = updated_at+ if s3_key is not UNSET:+ field_dict["s3_key"] = s3_key+ if s3_presigned_url is not UNSET:+ field_dict["s3_presigned_url"] = s3_presigned_url++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.batch_progress import BatchProgress++ d = dict(src_dict)+ batch_id = d.pop("batch_id", UNSET)++ status = d.pop("status", UNSET)++ _progress = d.pop("progress", UNSET)+ progress: BatchProgress | Unset+ if isinstance(_progress, Unset):+ progress = UNSET+ else:+ progress = BatchProgress.from_dict(_progress)++ _created_at = d.pop("created_at", UNSET)+ created_at: datetime.datetime | Unset+ if isinstance(_created_at, Unset):+ created_at = UNSET+ else:+ created_at = datetime.datetime.fromisoformat(_created_at)++ _updated_at = d.pop("updated_at", UNSET)+ updated_at: datetime.datetime | Unset+ if isinstance(_updated_at, Unset):+ updated_at = UNSET+ else:+ updated_at = datetime.datetime.fromisoformat(_updated_at)++ s3_key = d.pop("s3_key", UNSET)++ s3_presigned_url = d.pop("s3_presigned_url", UNSET)++ label_batch_summary = cls(+ batch_id=batch_id,+ status=status,+ progress=progress,+ created_at=created_at,+ updated_at=updated_at,+ s3_key=s3_key,+ s3_presigned_url=s3_presigned_url,+ )++ label_batch_summary.additional_properties = d+ return label_batch_summary++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/label_in_progress_response.py b/libs/fleet/python-sdk/cua_train/models/label_in_progress_response.pynew file mode 100644index 0000000000..aeaf99e06a--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/label_in_progress_response.py@@ -0,0 +1,88 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="LabelInProgressResponse")+++@_attrs_define+class LabelInProgressResponse:+ """+ Attributes:+ label (str | Unset):+ batch_count (int | Unset):+ all_completed (bool | Unset):+ message (str | Unset):+ """++ label: str | Unset = UNSET+ batch_count: int | Unset = UNSET+ all_completed: bool | Unset = UNSET+ message: str | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ label = self.label++ batch_count = self.batch_count++ all_completed = self.all_completed++ message = self.message++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if label is not UNSET:+ field_dict["label"] = label+ if batch_count is not UNSET:+ field_dict["batch_count"] = batch_count+ if all_completed is not UNSET:+ field_dict["all_completed"] = all_completed+ if message is not UNSET:+ field_dict["message"] = message++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ label = d.pop("label", UNSET)++ batch_count = d.pop("batch_count", UNSET)++ all_completed = d.pop("all_completed", UNSET)++ message = d.pop("message", UNSET)++ label_in_progress_response = cls(+ label=label,+ batch_count=batch_count,+ all_completed=all_completed,+ message=message,+ )++ label_in_progress_response.additional_properties = d+ return label_in_progress_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/label_results_response.py b/libs/fleet/python-sdk/cua_train/models/label_results_response.pynew file mode 100644index 0000000000..0ddc78efba--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/label_results_response.py@@ -0,0 +1,133 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.batch_results_response import BatchResultsResponse+ from ..models.batch_summary import BatchSummary+++T = TypeVar("T", bound="LabelResultsResponse")+++@_attrs_define+class LabelResultsResponse:+ """+ Attributes:+ label (str | Unset):+ batch_count (int | Unset):+ completed_batch_count (int | Unset):+ all_completed (bool | Unset):+ batches (list[BatchResultsResponse] | Unset):+ summary (BatchSummary | Unset):+ """++ label: str | Unset = UNSET+ batch_count: int | Unset = UNSET+ completed_batch_count: int | Unset = UNSET+ all_completed: bool | Unset = UNSET+ batches: list[BatchResultsResponse] | Unset = UNSET+ summary: BatchSummary | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ label = self.label++ batch_count = self.batch_count++ completed_batch_count = self.completed_batch_count++ all_completed = self.all_completed++ batches: list[dict[str, Any]] | Unset = UNSET+ if not isinstance(self.batches, Unset):+ batches = []+ for batches_item_data in self.batches:+ batches_item = batches_item_data.to_dict()+ batches.append(batches_item)++ summary: dict[str, Any] | Unset = UNSET+ if not isinstance(self.summary, Unset):+ summary = self.summary.to_dict()++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if label is not UNSET:+ field_dict["label"] = label+ if batch_count is not UNSET:+ field_dict["batch_count"] = batch_count+ if completed_batch_count is not UNSET:+ field_dict["completed_batch_count"] = completed_batch_count+ if all_completed is not UNSET:+ field_dict["all_completed"] = all_completed+ if batches is not UNSET:+ field_dict["batches"] = batches+ if summary is not UNSET:+ field_dict["summary"] = summary++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.batch_results_response import BatchResultsResponse+ from ..models.batch_summary import BatchSummary++ d = dict(src_dict)+ label = d.pop("label", UNSET)++ batch_count = d.pop("batch_count", UNSET)++ completed_batch_count = d.pop("completed_batch_count", UNSET)++ all_completed = d.pop("all_completed", UNSET)++ _batches = d.pop("batches", UNSET)+ batches: list[BatchResultsResponse] | Unset = UNSET+ if _batches is not UNSET:+ batches = []+ for batches_item_data in _batches:+ batches_item = BatchResultsResponse.from_dict(batches_item_data)++ batches.append(batches_item)++ _summary = d.pop("summary", UNSET)+ summary: BatchSummary | Unset+ if isinstance(_summary, Unset):+ summary = UNSET+ else:+ summary = BatchSummary.from_dict(_summary)++ label_results_response = cls(+ label=label,+ batch_count=batch_count,+ completed_batch_count=completed_batch_count,+ all_completed=all_completed,+ batches=batches,+ summary=summary,+ )++ label_results_response.additional_properties = d+ return label_results_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/label_status_response.py b/libs/fleet/python-sdk/cua_train/models/label_status_response.pynew file mode 100644index 0000000000..92148a1df7--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/label_status_response.py@@ -0,0 +1,124 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.batch_progress import BatchProgress+ from ..models.label_batch_summary import LabelBatchSummary+++T = TypeVar("T", bound="LabelStatusResponse")+++@_attrs_define+class LabelStatusResponse:+ """+ Attributes:+ label (str | Unset):+ batch_count (int | Unset):+ all_completed (bool | Unset):+ progress (BatchProgress | Unset):+ batches (list[LabelBatchSummary] | Unset):+ """++ label: str | Unset = UNSET+ batch_count: int | Unset = UNSET+ all_completed: bool | Unset = UNSET+ progress: BatchProgress | Unset = UNSET+ batches: list[LabelBatchSummary] | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ label = self.label++ batch_count = self.batch_count++ all_completed = self.all_completed++ progress: dict[str, Any] | Unset = UNSET+ if not isinstance(self.progress, Unset):+ progress = self.progress.to_dict()++ batches: list[dict[str, Any]] | Unset = UNSET+ if not isinstance(self.batches, Unset):+ batches = []+ for batches_item_data in self.batches:+ batches_item = batches_item_data.to_dict()+ batches.append(batches_item)++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if label is not UNSET:+ field_dict["label"] = label+ if batch_count is not UNSET:+ field_dict["batch_count"] = batch_count+ if all_completed is not UNSET:+ field_dict["all_completed"] = all_completed+ if progress is not UNSET:+ field_dict["progress"] = progress+ if batches is not UNSET:+ field_dict["batches"] = batches++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.batch_progress import BatchProgress+ from ..models.label_batch_summary import LabelBatchSummary++ d = dict(src_dict)+ label = d.pop("label", UNSET)++ batch_count = d.pop("batch_count", UNSET)++ all_completed = d.pop("all_completed", UNSET)++ _progress = d.pop("progress", UNSET)+ progress: BatchProgress | Unset+ if isinstance(_progress, Unset):+ progress = UNSET+ else:+ progress = BatchProgress.from_dict(_progress)++ _batches = d.pop("batches", UNSET)+ batches: list[LabelBatchSummary] | Unset = UNSET+ if _batches is not UNSET:+ batches = []+ for batches_item_data in _batches:+ batches_item = LabelBatchSummary.from_dict(batches_item_data)++ batches.append(batches_item)++ label_status_response = cls(+ label=label,+ batch_count=batch_count,+ all_completed=all_completed,+ progress=progress,+ batches=batches,+ )++ label_status_response.additional_properties = d+ return label_status_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/lane_create_request.py b/libs/fleet/python-sdk/cua_train/models/lane_create_request.pynew file mode 100644index 0000000000..cfc634808e--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/lane_create_request.py@@ -0,0 +1,67 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="LaneCreateRequest")+++@_attrs_define+class LaneCreateRequest:+ """Body of POST /lanes.++ ``ttl_seconds`` is the absolute time the claim is reserved for;+ after that the reaper deletes it. With ``autoRenew=true`` the lane+ auto-renew timer in pool-operator pushes this forward, so the+ customer's effective TTL is "as long as the lane exists".++ Attributes:+ ttl_seconds (int | Unset): Default: 300.+ """++ ttl_seconds: int | Unset = 300+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ ttl_seconds = self.ttl_seconds++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if ttl_seconds is not UNSET:+ field_dict["ttl_seconds"] = ttl_seconds++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ ttl_seconds = d.pop("ttl_seconds", UNSET)++ lane_create_request = cls(+ ttl_seconds=ttl_seconds,+ )++ lane_create_request.additional_properties = d+ return lane_create_request++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/lane_delete_response.py b/libs/fleet/python-sdk/cua_train/models/lane_delete_response.pynew file mode 100644index 0000000000..cc9af25268--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/lane_delete_response.py@@ -0,0 +1,61 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="LaneDeleteResponse")+++@_attrs_define+class LaneDeleteResponse:+ """+ Attributes:+ lane_id (str):+ """++ lane_id: str+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ lane_id = self.lane_id++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "lane_id": lane_id,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ lane_id = d.pop("lane_id")++ lane_delete_response = cls(+ lane_id=lane_id,+ )++ lane_delete_response.additional_properties = d+ return lane_delete_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/lane_response.py b/libs/fleet/python-sdk/cua_train/models/lane_response.pynew file mode 100644index 0000000000..3d1b680806--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/lane_response.py@@ -0,0 +1,91 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar, cast++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="LaneResponse")+++@_attrs_define+class LaneResponse:+ """+ Attributes:+ lane_id (str):+ vm_id (str):+ screenshot (None | str | Unset):+ """++ lane_id: str+ vm_id: str+ screenshot: None | str | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ lane_id = self.lane_id++ vm_id = self.vm_id++ screenshot: None | str | Unset+ if isinstance(self.screenshot, Unset):+ screenshot = UNSET+ else:+ screenshot = self.screenshot++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "lane_id": lane_id,+ "vm_id": vm_id,+ }+ )+ if screenshot is not UNSET:+ field_dict["screenshot"] = screenshot++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ lane_id = d.pop("lane_id")++ vm_id = d.pop("vm_id")++ def _parse_screenshot(data: object) -> None | str | Unset:+ if data is None:+ return data+ if isinstance(data, Unset):+ return data+ return cast(None | str | Unset, data)++ screenshot = _parse_screenshot(d.pop("screenshot", UNSET))++ lane_response = cls(+ lane_id=lane_id,+ vm_id=vm_id,+ screenshot=screenshot,+ )++ lane_response.additional_properties = d+ return lane_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/lane_swap_response.py b/libs/fleet/python-sdk/cua_train/models/lane_swap_response.pynew file mode 100644index 0000000000..46272c5edf--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/lane_swap_response.py@@ -0,0 +1,77 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="LaneSwapResponse")+++@_attrs_define+class LaneSwapResponse:+ """+ Attributes:+ lane_id (str):+ vm_id (str):+ wait_seconds (float):+ """++ lane_id: str+ vm_id: str+ wait_seconds: float+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ lane_id = self.lane_id++ vm_id = self.vm_id++ wait_seconds = self.wait_seconds++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "lane_id": lane_id,+ "vm_id": vm_id,+ "wait_seconds": wait_seconds,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ lane_id = d.pop("lane_id")++ vm_id = d.pop("vm_id")++ wait_seconds = d.pop("wait_seconds")++ lane_swap_response = cls(+ lane_id=lane_id,+ vm_id=vm_id,+ wait_seconds=wait_seconds,+ )++ lane_swap_response.additional_properties = d+ return lane_swap_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/list_keys_response.py b/libs/fleet/python-sdk/cua_train/models/list_keys_response.pynew file mode 100644index 0000000000..97a45082fa--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/list_keys_response.py@@ -0,0 +1,79 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.key_client import KeyClient+++T = TypeVar("T", bound="ListKeysResponse")+++@_attrs_define+class ListKeysResponse:+ """+ Attributes:+ keys (list[KeyClient] | Unset):+ """++ keys: list[KeyClient] | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ keys: list[dict[str, Any]] | Unset = UNSET+ if not isinstance(self.keys, Unset):+ keys = []+ for keys_item_data in self.keys:+ keys_item = keys_item_data.to_dict()+ keys.append(keys_item)++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if keys is not UNSET:+ field_dict["keys"] = keys++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.key_client import KeyClient++ d = dict(src_dict)+ _keys = d.pop("keys", UNSET)+ keys: list[KeyClient] | Unset = UNSET+ if _keys is not UNSET:+ keys = []+ for keys_item_data in _keys:+ keys_item = KeyClient.from_dict(keys_item_data)++ keys.append(keys_item)++ list_keys_response = cls(+ keys=keys,+ )++ list_keys_response.additional_properties = d+ return list_keys_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/pool_list_response.py b/libs/fleet/python-sdk/cua_train/models/pool_list_response.pynew file mode 100644index 0000000000..cbfb8db4c5--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/pool_list_response.py@@ -0,0 +1,83 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++if TYPE_CHECKING:+ from ..models.pool_list_response_vms_item import PoolListResponseVmsItem+++T = TypeVar("T", bound="PoolListResponse")+++@_attrs_define+class PoolListResponse:+ """+ Attributes:+ vms (list[PoolListResponseVmsItem]):+ count (int):+ """++ vms: list[PoolListResponseVmsItem]+ count: int+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ vms = []+ for vms_item_data in self.vms:+ vms_item = vms_item_data.to_dict()+ vms.append(vms_item)++ count = self.count++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "vms": vms,+ "count": count,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.pool_list_response_vms_item import PoolListResponseVmsItem++ d = dict(src_dict)+ vms = []+ _vms = d.pop("vms")+ for vms_item_data in _vms:+ vms_item = PoolListResponseVmsItem.from_dict(vms_item_data)++ vms.append(vms_item)++ count = d.pop("count")++ pool_list_response = cls(+ vms=vms,+ count=count,+ )++ pool_list_response.additional_properties = d+ return pool_list_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/pool_list_response_vms_item.py b/libs/fleet/python-sdk/cua_train/models/pool_list_response_vms_item.pynew file mode 100644index 0000000000..79d2871fc2--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/pool_list_response_vms_item.py@@ -0,0 +1,47 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="PoolListResponseVmsItem")+++@_attrs_define+class PoolListResponseVmsItem:+ """ """++ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ pool_list_response_vms_item = cls()++ pool_list_response_vms_item.additional_properties = d+ return pool_list_response_vms_item++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/release_lanes_request.py b/libs/fleet/python-sdk/cua_train/models/release_lanes_request.pynew file mode 100644index 0000000000..69ae98df1c--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/release_lanes_request.py@@ -0,0 +1,61 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar, cast++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="ReleaseLanesRequest")+++@_attrs_define+class ReleaseLanesRequest:+ """+ Attributes:+ vm_ids (list[str]): VM ids to shut down (lanes to release).+ """++ vm_ids: list[str]+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ vm_ids = self.vm_ids++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "vm_ids": vm_ids,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ vm_ids = cast(list[str], d.pop("vm_ids"))++ release_lanes_request = cls(+ vm_ids=vm_ids,+ )++ release_lanes_request.additional_properties = d+ return release_lanes_request++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/release_lanes_response.py b/libs/fleet/python-sdk/cua_train/models/release_lanes_response.pynew file mode 100644index 0000000000..494ea6cc48--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/release_lanes_response.py@@ -0,0 +1,61 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="ReleaseLanesResponse")+++@_attrs_define+class ReleaseLanesResponse:+ """+ Attributes:+ released (int | Unset): Number of vm_ids submitted for release.+ """++ released: int | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ released = self.released++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if released is not UNSET:+ field_dict["released"] = released++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ released = d.pop("released", UNSET)++ release_lanes_response = cls(+ released=released,+ )++ release_lanes_response.additional_properties = d+ return release_lanes_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/reset_request.py b/libs/fleet/python-sdk/cua_train/models/reset_request.pynew file mode 100644index 0000000000..1d69fc2fd1--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/reset_request.py@@ -0,0 +1,75 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++if TYPE_CHECKING:+ from ..models.reset_request_task_config import ResetRequestTaskConfig+++T = TypeVar("T", bound="ResetRequest")+++@_attrs_define+class ResetRequest:+ """+ Attributes:+ task_config (ResetRequestTaskConfig):+ timeout (int):+ """++ task_config: ResetRequestTaskConfig+ timeout: int+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ task_config = self.task_config.to_dict()++ timeout = self.timeout++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "task_config": task_config,+ "timeout": timeout,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.reset_request_task_config import ResetRequestTaskConfig++ d = dict(src_dict)+ task_config = ResetRequestTaskConfig.from_dict(d.pop("task_config"))++ timeout = d.pop("timeout")++ reset_request = cls(+ task_config=task_config,+ timeout=timeout,+ )++ reset_request.additional_properties = d+ return reset_request++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/reset_request_task_config.py b/libs/fleet/python-sdk/cua_train/models/reset_request_task_config.pynew file mode 100644index 0000000000..e8cc4a55c7--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/reset_request_task_config.py@@ -0,0 +1,47 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="ResetRequestTaskConfig")+++@_attrs_define+class ResetRequestTaskConfig:+ """ """++ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ reset_request_task_config = cls()++ reset_request_task_config.additional_properties = d+ return reset_request_task_config++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/reset_response.py b/libs/fleet/python-sdk/cua_train/models/reset_response.pynew file mode 100644index 0000000000..de7d5d14b3--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/reset_response.py@@ -0,0 +1,77 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="ResetResponse")+++@_attrs_define+class ResetResponse:+ """+ Attributes:+ screenshot (str):+ problem (str):+ vm_id (str):+ """++ screenshot: str+ problem: str+ vm_id: str+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ screenshot = self.screenshot++ problem = self.problem++ vm_id = self.vm_id++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "screenshot": screenshot,+ "problem": problem,+ "vm_id": vm_id,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ screenshot = d.pop("screenshot")++ problem = d.pop("problem")++ vm_id = d.pop("vm_id")++ reset_response = cls(+ screenshot=screenshot,+ problem=problem,+ vm_id=vm_id,+ )++ reset_response.additional_properties = d+ return reset_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/run_config.py b/libs/fleet/python-sdk/cua_train/models/run_config.pynew file mode 100644index 0000000000..16cd10739c--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/run_config.py@@ -0,0 +1,99 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.action import Action+++T = TypeVar("T", bound="RunConfig")+++@_attrs_define+class RunConfig:+ """+ Attributes:+ steps (list[Action]): Ordered actions to execute on the rollout VM. A step with `action_type: "RESET"` is a+ reserved control action: instead of being forwarded to the VM, it hard-resets the VM in place (new vm_id, clean+ baseline desktop), so one run can execute several independent episodes on a warm instance.+ timeout (int | Unset): Per-rollout timeout in seconds (max 24h).+ vm_id (str | Unset): Reattach this run to an existing warm VM (instance reuse / "lane"), typically a vm_id+ returned by a previous `keep_warm` batch, instead of acquiring a fresh one. If that claim has already expired,+ the run transparently falls back to a fresh VM.+ """++ steps: list[Action]+ timeout: int | Unset = UNSET+ vm_id: str | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ steps = []+ for steps_item_data in self.steps:+ steps_item = steps_item_data.to_dict()+ steps.append(steps_item)++ timeout = self.timeout++ vm_id = self.vm_id++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "steps": steps,+ }+ )+ if timeout is not UNSET:+ field_dict["timeout"] = timeout+ if vm_id is not UNSET:+ field_dict["vm_id"] = vm_id++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.action import Action++ d = dict(src_dict)+ steps = []+ _steps = d.pop("steps")+ for steps_item_data in _steps:+ steps_item = Action.from_dict(steps_item_data)++ steps.append(steps_item)++ timeout = d.pop("timeout", UNSET)++ vm_id = d.pop("vm_id", UNSET)++ run_config = cls(+ steps=steps,+ timeout=timeout,+ vm_id=vm_id,+ )++ run_config.additional_properties = d+ return run_config++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/run_result.py b/libs/fleet/python-sdk/cua_train/models/run_result.pynew file mode 100644index 0000000000..ee264934a5--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/run_result.py@@ -0,0 +1,139 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar, cast++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="RunResult")+++@_attrs_define+class RunResult:+ """+ Attributes:+ run_id (int | Unset):+ vm_id (str | Unset):+ ok (bool | Unset):+ error (str | Unset):+ reset_ms (int | Unset):+ step_ms (list[int] | Unset):+ shutdown_ms (int | Unset):+ actions (list[str] | Unset):+ screenshots (list[str] | Unset):+ """++ run_id: int | Unset = UNSET+ vm_id: str | Unset = UNSET+ ok: bool | Unset = UNSET+ error: str | Unset = UNSET+ reset_ms: int | Unset = UNSET+ step_ms: list[int] | Unset = UNSET+ shutdown_ms: int | Unset = UNSET+ actions: list[str] | Unset = UNSET+ screenshots: list[str] | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ run_id = self.run_id++ vm_id = self.vm_id++ ok = self.ok++ error = self.error++ reset_ms = self.reset_ms++ step_ms: list[int] | Unset = UNSET+ if not isinstance(self.step_ms, Unset):+ step_ms = self.step_ms++ shutdown_ms = self.shutdown_ms++ actions: list[str] | Unset = UNSET+ if not isinstance(self.actions, Unset):+ actions = self.actions++ screenshots: list[str] | Unset = UNSET+ if not isinstance(self.screenshots, Unset):+ screenshots = self.screenshots++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if run_id is not UNSET:+ field_dict["run_id"] = run_id+ if vm_id is not UNSET:+ field_dict["vm_id"] = vm_id+ if ok is not UNSET:+ field_dict["ok"] = ok+ if error is not UNSET:+ field_dict["error"] = error+ if reset_ms is not UNSET:+ field_dict["reset_ms"] = reset_ms+ if step_ms is not UNSET:+ field_dict["step_ms"] = step_ms+ if shutdown_ms is not UNSET:+ field_dict["shutdown_ms"] = shutdown_ms+ if actions is not UNSET:+ field_dict["actions"] = actions+ if screenshots is not UNSET:+ field_dict["screenshots"] = screenshots++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ run_id = d.pop("run_id", UNSET)++ vm_id = d.pop("vm_id", UNSET)++ ok = d.pop("ok", UNSET)++ error = d.pop("error", UNSET)++ reset_ms = d.pop("reset_ms", UNSET)++ step_ms = cast(list[int], d.pop("step_ms", UNSET))++ shutdown_ms = d.pop("shutdown_ms", UNSET)++ actions = cast(list[str], d.pop("actions", UNSET))++ screenshots = cast(list[str], d.pop("screenshots", UNSET))++ run_result = cls(+ run_id=run_id,+ vm_id=vm_id,+ ok=ok,+ error=error,+ reset_ms=reset_ms,+ step_ms=step_ms,+ shutdown_ms=shutdown_ms,+ actions=actions,+ screenshots=screenshots,+ )++ run_result.additional_properties = d+ return run_result++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/screenshot_response.py b/libs/fleet/python-sdk/cua_train/models/screenshot_response.pynew file mode 100644index 0000000000..ac733c46b3--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/screenshot_response.py@@ -0,0 +1,69 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="ScreenshotResponse")+++@_attrs_define+class ScreenshotResponse:+ """+ Attributes:+ screenshot (str):+ vm_id (str):+ """++ screenshot: str+ vm_id: str+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ screenshot = self.screenshot++ vm_id = self.vm_id++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "screenshot": screenshot,+ "vm_id": vm_id,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ screenshot = d.pop("screenshot")++ vm_id = d.pop("vm_id")++ screenshot_response = cls(+ screenshot=screenshot,+ vm_id=vm_id,+ )++ screenshot_response.additional_properties = d+ return screenshot_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/shutdown_request.py b/libs/fleet/python-sdk/cua_train/models/shutdown_request.pynew file mode 100644index 0000000000..41efd71c6b--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/shutdown_request.py@@ -0,0 +1,61 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="ShutdownRequest")+++@_attrs_define+class ShutdownRequest:+ """+ Attributes:+ vm_id (str):+ """++ vm_id: str+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ vm_id = self.vm_id++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "vm_id": vm_id,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ vm_id = d.pop("vm_id")++ shutdown_request = cls(+ vm_id=vm_id,+ )++ shutdown_request.additional_properties = d+ return shutdown_request++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/shutdown_response.py b/libs/fleet/python-sdk/cua_train/models/shutdown_response.pynew file mode 100644index 0000000000..ba86618657--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/shutdown_response.py@@ -0,0 +1,61 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="ShutdownResponse")+++@_attrs_define+class ShutdownResponse:+ """+ Attributes:+ vm_id (str):+ """++ vm_id: str+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ vm_id = self.vm_id++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "vm_id": vm_id,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ vm_id = d.pop("vm_id")++ shutdown_response = cls(+ vm_id=vm_id,+ )++ shutdown_response.additional_properties = d+ return shutdown_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/step_request.py b/libs/fleet/python-sdk/cua_train/models/step_request.pynew file mode 100644index 0000000000..ac578484c7--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/step_request.py@@ -0,0 +1,80 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="StepRequest")+++@_attrs_define+class StepRequest:+ """+ Attributes:+ action (str):+ vm_id (str):+ timeout (int | Unset): Default: 300.+ """++ action: str+ vm_id: str+ timeout: int | Unset = 300+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ action = self.action++ vm_id = self.vm_id++ timeout = self.timeout++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "action": action,+ "vm_id": vm_id,+ }+ )+ if timeout is not UNSET:+ field_dict["timeout"] = timeout++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ action = d.pop("action")++ vm_id = d.pop("vm_id")++ timeout = d.pop("timeout", UNSET)++ step_request = cls(+ action=action,+ vm_id=vm_id,+ timeout=timeout,+ )++ step_request.additional_properties = d+ return step_request++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/step_response.py b/libs/fleet/python-sdk/cua_train/models/step_response.pynew file mode 100644index 0000000000..e9a2e89dd5--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/step_response.py@@ -0,0 +1,84 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar, cast++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="StepResponse")+++@_attrs_define+class StepResponse:+ """+ Attributes:+ screenshot (None | str):+ is_finish (bool):+ reward (float):+ """++ screenshot: None | str+ is_finish: bool+ reward: float+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ screenshot: None | str+ screenshot = self.screenshot++ is_finish = self.is_finish++ reward = self.reward++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "screenshot": screenshot,+ "is_finish": is_finish,+ "reward": reward,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)++ def _parse_screenshot(data: object) -> None | str:+ if data is None:+ return data+ return cast(None | str, data)++ screenshot = _parse_screenshot(d.pop("screenshot"))++ is_finish = d.pop("is_finish")++ reward = d.pop("reward")++ step_response = cls(+ screenshot=screenshot,+ is_finish=is_finish,+ reward=reward,+ )++ step_response.additional_properties = d+ return step_response++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/timing_stats.py b/libs/fleet/python-sdk/cua_train/models/timing_stats.pynew file mode 100644index 0000000000..6bd6ebedf6--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/models/timing_stats.py@@ -0,0 +1,88 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="TimingStats")+++@_attrs_define+class TimingStats:+ """+ Attributes:+ n (int | Unset):+ min_ (int | Unset):+ mean (float | Unset):+ max_ (int | Unset):+ """++ n: int | Unset = UNSET+ min_: int | Unset = UNSET+ mean: float | Unset = UNSET+ max_: int | Unset = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ n = self.n++ min_ = self.min_++ mean = self.mean++ max_ = self.max_++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update({})+ if n is not UNSET:+ field_dict["n"] = n+ if min_ is not UNSET:+ field_dict["min"] = min_+ if mean is not UNSET:+ field_dict["mean"] = mean+ if max_ is not UNSET:+ field_dict["max"] = max_++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ n = d.pop("n", UNSET)++ min_ = d.pop("min", UNSET)++ mean = d.pop("mean", UNSET)++ max_ = d.pop("max", UNSET)++ timing_stats = cls(+ n=n,+ min_=min_,+ mean=mean,+ max_=max_,+ )++ timing_stats.additional_properties = d+ return timing_stats++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/py.typed b/libs/fleet/python-sdk/cua_train/py.typednew file mode 100644index 0000000000..1aad32711f--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/py.typed@@ -0,0 +1 @@+# Marker file for PEP 561\ No newline at end of filediff --git a/libs/fleet/python-sdk/cua_train/types.py b/libs/fleet/python-sdk/cua_train/types.pynew file mode 100644index 0000000000..b64af09529--- /dev/null+++ b/libs/fleet/python-sdk/cua_train/types.py@@ -0,0 +1,54 @@+"""Contains some shared types for properties"""++from collections.abc import Mapping, MutableMapping+from http import HTTPStatus+from typing import IO, BinaryIO, Generic, Literal, TypeVar++from attrs import define+++class Unset:+ def __bool__(self) -> Literal[False]:+ return False+++UNSET: Unset = Unset()++# The types that `httpx.Client(files=)` can accept, copied from that library.+FileContent = IO[bytes] | bytes | str+FileTypes = (+ # (filename, file (or bytes), content_type)+ tuple[str | None, FileContent, str | None]+ # (filename, file (or bytes), content_type, headers)+ | tuple[str | None, FileContent, str | None, Mapping[str, str]]+)+RequestFiles = list[tuple[str, FileTypes]]+++@define+class File:+ """Contains information for file uploads"""++ payload: BinaryIO+ file_name: str | None = None+ mime_type: str | None = None++ def to_tuple(self) -> FileTypes:+ """Return a tuple representation that httpx will accept for multipart/form-data"""+ return self.file_name, self.payload, self.mime_type+++T = TypeVar("T")+++@define+class Response(Generic[T]):+ """A response from an endpoint"""++ status_code: HTTPStatus+ content: bytes+ headers: MutableMapping[str, str]+ parsed: T | None+++__all__ = ["UNSET", "File", "FileTypes", "RequestFiles", "Response", "Unset"]diff --git a/libs/fleet/python-sdk/examples/claim_and_connect.py b/libs/fleet/python-sdk/examples/claim_and_connect.pynew file mode 100644index 0000000000..51fa463194--- /dev/null+++ b/libs/fleet/python-sdk/examples/claim_and_connect.py@@ -0,0 +1,224 @@+#!/usr/bin/env python3+"""Claim a sandbox from a pool, wait for it to bind, then call one of its+service endpoints — all through the cyclops-cs backend with a client id/secret.++What it illustrates:+ * ``TrainClient.from_key`` for the client_credentials exchange + transparent+ token refresh, reused as a plain authenticated httpx client for endpoints+ that are NOT in the generated SDK surface+ * creating an ``OSGymSandboxClaim`` CR via the ``/api/k8s`` kubectl-proxy+ (the same path the SPA uses — the pool-operator binds it to a warm sandbox)+ * reaching the claimed sandbox through ``/api/svc/{namespace}/{service}/``++Auth — use a per-USER key (``ukey-...``), not a per-pool key:+``/api/k8s`` impersonates the token's owner so Capsule tenant RBAC applies.+Per-user keys (POST /api/user-keys) act on behalf of their owner and can+create claims; per-pool keys (POST /api/keys, ``key-...``) have no K8s+identity and are rejected on the claim step.++Setup::++ pip install cua-train --extra-index-url https://wheels.cua.ai/simple/+ export CUA_CLIENT_ID=ukey-xxxxxxxx # from POST /api/user-keys+ export CUA_CLIENT_SECRET=...+ python claim_and_connect.py --pool my-pool # first pool service+ python claim_and_connect.py --pool my-pool --service vnc --path /healthz+ python claim_and_connect.py --pool win --service cua-driver --mcp++``--mcp`` runs the cua-driver MCP handshake (initialize → session id →+tools/list) instead of a plain GET — proof the desktop is drivable, not+just that something answers HTTP.++The claim is released (DELETE) on exit unless ``--keep`` is passed.++A sandbox released by an earlier claim is hard-reset in place and rejoins+the pool, but its guest OS reboots — the in-guest service answers 502+("upstream unavailable") for a few minutes after the claim binds. The+script polls the service until it responds (``--ready-timeout``).++Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+import time+import uuid++import httpx++from cua_train import TrainClient++# OSGymSandboxClaim CRD coordinates (osgym.cua.ai group — the pool-operator+# watches these and binds each claim to a warm sandbox from the pool).+CLAIM_GROUP = "osgym.cua.ai"+CLAIM_VERSION = "v1alpha1"+CLAIM_PLURAL = "osgymsandboxclaims"++DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"+DEFAULT_BASE_URL = "https://run.cua.ai"+++def claims_url(pool: str, name: str | None = None) -> str:+ base = f"/api/k8s/apis/{CLAIM_GROUP}/{CLAIM_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"+ return f"{base}/{name}" if name else base+++def first_pool_service(http: httpx.Client, pool: str) -> str:+ """Name of the pool's first declared service (spec.services[0].name)."""+ r = http.get(f"/api/k8s/apis/cua.ai/v1/namespaces/{pool}/osgymworkspacepools/{pool}")+ r.raise_for_status()+ services = r.json().get("spec", {}).get("services") or []+ if not services:+ sys.exit(f"pool {pool!r} declares no services — pass --service or add one to the pool spec")+ return services[0]["name"]+++def create_claim(http: httpx.Client, pool: str, name: str) -> None:+ r = http.post(+ claims_url(pool),+ json={+ "apiVersion": f"{CLAIM_GROUP}/{CLAIM_VERSION}",+ "kind": "OSGymSandboxClaim",+ "metadata": {"name": name},+ # Pool name = namespace name (1:1), and each pool ships a template+ # named "<pool>-template" — same convention the SPA uses.+ "spec": {"sandboxTemplateRef": {"name": f"{pool}-template"}},+ },+ )+ if r.status_code == 403:+ sys.exit(+ "403 creating claim — is this a per-pool key? Claims need a per-USER "+ "key (client id starting with 'ukey-', from POST /api/user-keys)."+ )+ r.raise_for_status()+++def wait_bound(http: httpx.Client, pool: str, name: str, timeout: float) -> str:+ """Poll the claim until status.phase == Bound; return the sandbox name."""+ deadline = time.monotonic() + timeout+ while True:+ r = http.get(claims_url(pool, name))+ r.raise_for_status()+ status = r.json().get("status") or {}+ phase = status.get("phase", "Pending")+ sandbox = (status.get("sandbox") or {}).get("name")+ if phase == "Bound" and sandbox:+ return sandbox+ if phase == "Failed":+ sys.exit(f"claim {name} failed: {status}")+ if time.monotonic() > deadline:+ sys.exit(f"timed out after {timeout:.0f}s waiting for claim {name} (phase={phase})")+ print(f" claim {name}: {phase} …")+ time.sleep(2)+++def wait_service_ready(http, url: str, timeout: float) -> httpx.Response:+ """GET url until the in-guest service answers with something other than+ a proxy 502/503/504 (the guest OS is still booting after a reset)."""+ deadline = time.monotonic() + timeout+ while True:+ resp = http().get(url)+ if resp.status_code not in (502, 503, 504):+ return resp+ if time.monotonic() > deadline:+ sys.exit(f"timed out after {timeout:.0f}s waiting for the service (last: HTTP {resp.status_code})")+ print(f" HTTP {resp.status_code} — guest still booting …")+ time.sleep(15)+++def mcp_handshake(http, base: str) -> None:+ """initialize → notifications/initialized → tools/list against the+ cua-driver Streamable HTTP MCP endpoint at {base}/mcp."""+ url = f"{base}/mcp"+ headers = {+ "Content-Type": "application/json",+ "Accept": "application/json, text/event-stream",+ }+ r = http().post(url, headers=headers, json={+ "jsonrpc": "2.0", "id": 1, "method": "initialize",+ "params": {+ "protocolVersion": "2025-03-26",+ "capabilities": {},+ "clientInfo": {"name": "claim_and_connect", "version": "0.1.0"},+ },+ })+ r.raise_for_status()+ session = r.headers.get("mcp-session-id")+ print(f"MCP initialize: HTTP {r.status_code}, session {session}")+ if session:+ headers["Mcp-Session-Id"] = session+ http().post(url, headers=headers, json={"jsonrpc": "2.0", "method": "notifications/initialized"})+ r = http().post(url, headers=headers, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"})+ r.raise_for_status()+ # Streamable HTTP returns SSE ("event: message\ndata: {...}"); the JSON+ # payload is on the data: line.+ data = next((ln[6:] for ln in r.text.splitlines() if ln.startswith("data: ")), r.text)+ tools = [t.get("name") for t in json.loads(data).get("result", {}).get("tools", [])]+ print(f"MCP tools ({len(tools)}): {', '.join(sorted(tools)[:12])}{', …' if len(tools) > 12 else ''}")+++def main() -> None:+ p = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ p.add_argument("--pool", required=True, help="pool name (= namespace)")+ p.add_argument("--service", help="pool service name (default: first service in the pool spec)")+ p.add_argument("--path", default="/", help="path to request on the service (default: /)")+ p.add_argument("--claim-name", help="claim name (default: claim-<random>)")+ p.add_argument("--timeout", type=float, default=300, help="seconds to wait for Bound (default: 300)")+ p.add_argument("--ready-timeout", type=float, default=420,+ help="seconds to wait for the in-guest service after binding (default: 420)")+ p.add_argument("--mcp", action="store_true",+ help="run the cua-driver MCP handshake (initialize + tools/list) instead of GET --path")+ p.add_argument("--keep", action="store_true", help="keep the claim instead of releasing it on exit")+ args = p.parse_args()++ client_id = os.environ.get("CUA_CLIENT_ID")+ client_secret = os.environ.get("CUA_CLIENT_SECRET")+ if not client_id or not client_secret:+ sys.exit("set CUA_CLIENT_ID and CUA_CLIENT_SECRET (per-user key, POST /api/user-keys)")++ client = TrainClient.from_key(+ token_url=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),+ client_id=client_id,+ client_secret=client_secret,+ base_url=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),+ )++ # get_httpx_client() re-mints the bearer token when it is close to expiry,+ # so fetch it per request rather than holding one reference.+ http = client.get_httpx_client+ claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"++ service = args.service or first_pool_service(http(), args.pool)++ print(f"creating claim {claim_name} on pool {args.pool} (template {args.pool}-template)")+ create_claim(http(), args.pool, claim_name)++ try:+ sandbox = wait_bound(http(), args.pool, claim_name, args.timeout)+ # Per-sandbox K8s Services are named "<sandbox>-<service>" and exposed+ # on port 80 by the operator; /api/svc proxies to them in-cluster.+ svc_base = f"/api/svc/{args.pool}/{sandbox}-{service}"+ url = f"{svc_base}/{args.path.lstrip('/')}"+ print(f"bound to sandbox {sandbox}; GET {url}")++ resp = wait_service_ready(http, url, args.ready_timeout)+ print(f"HTTP {resp.status_code} {resp.headers.get('content-type', '')}")+ body = resp.text+ print(body[:2000] + ("…" if len(body) > 2000 else ""))++ if args.mcp:+ mcp_handshake(http, svc_base)+ finally:+ if args.keep:+ print(f"keeping claim {claim_name} (release with: DELETE {claims_url(args.pool, claim_name)})")+ else:+ r = http().delete(claims_url(args.pool, claim_name))+ print(f"released claim {claim_name} (HTTP {r.status_code})")+++if __name__ == "__main__":+ main()diff --git a/libs/fleet/python-sdk/examples/create_pool_and_list_tools.py b/libs/fleet/python-sdk/examples/create_pool_and_list_tools.pynew file mode 100644index 0000000000..71e15fb50f--- /dev/null+++ b/libs/fleet/python-sdk/examples/create_pool_and_list_tools.py@@ -0,0 +1,592 @@+#!/usr/bin/env -S uv run --script+# /// script+# requires-python = ">=3.10"+# dependencies = [+# "cua-train",+# "httpx",+# ]+#+# [tool.uv]+# extra-index-url = ["https://wheels.cua.ai/simple/"]+# ///+"""Create a workspace pool on cyclops-cs / run.cua.ai, claim a sandbox from it,+and list the cua-driver MCP tools it exposes — end to end, from nothing but a+client id/secret.++This is the "create it too" companion to ``claim_and_connect.py`` (which only+claims from a pool that already exists). Here we drive the whole lifecycle and+narrate every step so you can follow along in the console:++ 1. exchange the client_credentials for a bearer token (``TrainClient.from_key``)+ 2. create the per-user namespace (``POST /api/namespaces`` — same path the SPA+ uses, so Capsule sets up tenant ownership + RBAC; pool name == namespace)+ 3. create an ``OSGymWorkspacePool`` (``cua.ai/v1``) via the ``/api/k8s``+ kubectl-proxy — image, replicas, and a service on the chosen port. The+ pool-operator's compat shim projects it into an ``OSGymSandboxTemplate``+ (``<pool>-template``) + ``OSGymSandboxWarmPool`` pair and warms the VMs.+ 4. claim a sandbox (``OSGymSandboxClaim``) and wait for it to bind+ 5. reach the bound sandbox through ``/api/svc/{ns}/{sandbox}-{service}/`` and+ run the cua-driver MCP handshake (initialize -> tools/list)++Auth — use a per-USER key (``ukey-...``), NOT a per-pool key:+``/api/k8s`` impersonates the token's owner so Capsule tenant RBAC applies.+Per-user keys (POST /api/user-keys) act on behalf of their owner and can create+namespaces, pools, and claims; per-pool keys (POST /api/keys, ``key-...``) have+no K8s identity and are rejected on those steps.++The default image is the Linux ``desktop-workspace`` — it serves the cua-driver+computer-use MCP server over Streamable HTTP on :3000/mcp (with /healthz),+and nothing else (no :5000 Flask server). So we set the pool's readiness probe+to the MCP port: a warm sandbox is only advertised as "available" (and a claim+only binds) once MCP is actually answering, which is exactly what we want+before listing tools.++Setup (zero-install with uv)::++ export CUA_CLIENT_ID=ukey-xxxxxxxx # from POST /api/user-keys+ export CUA_CLIENT_SECRET=...+ uv run create_pool_and_list_tools.py --name my-pool++…or pass credentials as flags, and/or pin everything explicitly::++ uv run create_pool_and_list_tools.py \+ --name my-pool \+ --client-id ukey-xxxxxxxx --client-secret ... \+ --image 296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace:latest \+ --port 3000++If your uv is too old to read the inline extra-index-url, run it the explicit+way (same as the other examples)::++ uv run --with cua-train --with httpx \+ --extra-index-url https://wheels.cua.ai/simple/ \+ create_pool_and_list_tools.py --name my-pool++The claim is released on exit (so the warm VM returns to the pool); the pool is+kept — it is the thing you asked to create. Pass ``--keep-claim`` to hold the+claim, or ``--delete-pool`` to tear the whole thing (pool + namespace) down.++Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+import time+import uuid+from collections.abc import Callable++import httpx++from cua_train import TrainClient++DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"+DEFAULT_BASE_URL = "https://run.cua.ai"+# NOTE: ':latest' is NOT reliably published for the Linux workspace repos — the+# build workflow only tags 'latest' on pushes to main, and ECR lifecycle rules+# expire old tags. A pool pointed at a missing tag never warms (the VM sits in+# ImagePullBackOff). Pass --image with a tag you've confirmed exists, e.g.:+# aws ecr describe-images --repository-name desktop-workspace --region us-west-2+# (verified working at the time of writing: a desktop-workspace gym-seed tag+# 'amazon-feature-gym-uv-seed-openshot-<sha>-base' — Linux, cua-driver MCP on :3000.)+DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace:latest"++# OSGymWorkspacePool — the legacy single-object pool CR the cyclops-cs SPA+# creates (cua.ai/v1). The pool-operator compat shim translates it into the+# native OSGymSandboxTemplate + OSGymSandboxWarmPool pair.+POOL_GROUP = "cua.ai"+POOL_VERSION = "v1"+POOL_PLURAL = "osgymworkspacepools"++# OSGymSandboxTemplate / OSGymSandboxClaim live in the osgym.cua.ai group.+EXT_GROUP = "osgym.cua.ai"+EXT_VERSION = "v1alpha1"+TEMPLATE_PLURAL = "osgymsandboxtemplates"+CLAIM_PLURAL = "osgymsandboxclaims"+++# ── URL builders (relative to base_url, e.g. https://run.cua.ai) ──────────+++def pool_url(pool: str, name: str | None = None) -> str:+ base = f"/api/k8s/apis/{POOL_GROUP}/{POOL_VERSION}/namespaces/{pool}/{POOL_PLURAL}"+ return f"{base}/{name}" if name else base+++def template_url(pool: str, name: str) -> str:+ return f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}/{name}"+++def claims_url(pool: str, name: str | None = None) -> str:+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"+ return f"{base}/{name}" if name else base+++# ── Console helpers ───────────────────────────────────────────────────────+++def step(msg: str) -> None:+ print(f"\n==> {msg}", flush=True)+++def info(msg: str) -> None:+ print(f" {msg}", flush=True)+++def die(msg: str) -> None:+ sys.exit(f"\nERROR: {msg}")+++# ── Lifecycle steps ───────────────────────────────────────────────────────+++def create_namespace(http: httpx.Client, name: str) -> None:+ """Create the per-user namespace via the Capsule-backed SPA endpoint.++ Pool name == namespace name (1:1). Going through /api/namespaces (rather+ than a raw /api/k8s namespace create) is what makes Capsule stamp tenant+ ownership + RBAC, so the impersonated pool create below is allowed. A 409+ just means we are reusing a namespace from an earlier run.+ """+ r = http.post("/api/namespaces", json={"name": name})+ if r.status_code == 409:+ info(f"namespace {name!r} already exists — reusing it")+ return+ if r.status_code == 403:+ die(+ "403 creating namespace — is this a per-pool key? Namespaces/pools/"+ "claims need a per-USER key (client id starting with 'ukey-', from "+ "POST /api/user-keys)."+ )+ r.raise_for_status()+ info(f"namespace {name!r} created")+++def create_pool(+ http: httpx.Client,+ *,+ pool: str,+ image: str,+ cpu: int,+ ram: str,+ replicas: int,+ firmware: str,+ service_name: str,+ port: int,+ readiness_port: int,+) -> None:+ """Create the OSGymWorkspacePool. Mirrors cyclops-cs api.createPool exactly."""+ template: dict = {+ "containerDiskImage": image,+ "imagePullSecret": "ecr-credentials",+ "cpuCores": cpu,+ "memory": ram,+ }+ # The SPA only sends firmware when it differs from KubeVirt's bios default.+ if firmware != "bios":+ template["firmware"] = firmware+ # Gate "Ready" (and therefore claim binding) on the in-guest service being+ # bound — for desktop-workspace that's the MCP port. Without a probe the VM+ # is advertised ready ~30s before the guest finishes booting (CUA-535).+ # readiness_port == 0 disables the probe (KubeVirt's launcher-up default).+ if readiness_port:+ template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}++ body = {+ "apiVersion": f"{POOL_GROUP}/{POOL_VERSION}",+ "kind": "OSGymWorkspacePool",+ "metadata": {"name": pool, "labels": {"cua.ai/pool": pool}},+ "spec": {+ "replicas": replicas,+ "template": template,+ # Each entry becomes a per-sandbox K8s Service "<sandbox>-<name>"+ # mapping port 80 -> targetPort on the VM.+ "services": [+ {"name": service_name, "targetPort": port, "protocol": "TCP"}+ ],+ },+ }++ r = http.post(pool_url(pool), json=body)+ if r.status_code == 409:+ info(f"pool {pool!r} already exists — reusing it (services/replicas unchanged)")+ return+ if r.status_code == 403:+ die(+ "403 creating pool — per-pool keys cannot reach /api/k8s. Use a "+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."+ )+ r.raise_for_status()+ info(f"pool {pool!r} created")+ info(f"image: {image}")+ info(f"size: {cpu} vCPU / {ram} / replicas={replicas} / firmware={firmware}")+ info(f"service: {service_name} -> targetPort {port} (reachable on Service port 80)")+ info(f"readiness: {'tcpSocket :' + str(readiness_port) if readiness_port else 'launcher-up (no probe)'}")+++def wait_template(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:+ """Wait for the compat shim to project the pool into <pool>-template.++ The claim below references the template by name; waiting for it to exist+ keeps the claim from sitting Pending purely because the projection hasn't+ happened yet. Best-effort: if it never appears we still try the claim.++ Takes the ``http`` accessor (not a client) and re-fetches it each poll so+ the bearer token is re-minted as it nears expiry.+ """+ tmpl = f"{pool}-template"+ deadline = time.monotonic() + timeout+ while True:+ r = get_http().get(template_url(pool, tmpl))+ if r.status_code == 200:+ info(f"pool-operator projected template {tmpl!r} + warm pool {pool!r}")+ return+ if r.status_code not in (404, 403):+ r.raise_for_status()+ if time.monotonic() > deadline:+ info(f"template {tmpl!r} not visible after {timeout:.0f}s — claiming anyway")+ return+ info(f"waiting for pool-operator to project template {tmpl!r} …")+ time.sleep(poll)+++def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int, str]:+ """(totalCount, availableCount, phase) from the pool status, best-effort."""+ try:+ r = get_http().get(pool_url(pool, pool))+ r.raise_for_status()+ st = r.json().get("status") or {}+ return (+ int(st.get("totalCount", 0)),+ int(st.get("availableCount", 0)),+ st.get("phase", "Unknown"),+ )+ except Exception:+ return (0, 0, "Unknown")+++def wait_pool_warm(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:+ """Wait until the pool reports an available (warm, Ready) VM.++ This is the key to a reliable first claim: a brand-new pool has to pull the+ (multi-GB) containerDisk image, boot the guest, and bring the in-guest+ service up on the readiness port before a Sandbox becomes adoptable. That+ cold start routinely exceeds the operator's 300s *claim* bind deadline+ (claim_handlers.BIND_DEADLINE_DEFAULT_S). If we claim first, the deadline+ burns down during the image pull and the claim Fails with+ ``BindDeadlineExceeded`` — exactly the failure mode this avoids.++ So we let the warm pool reach availableCount>=1 (phase "Ready") *before*+ claiming; the subsequent claim then binds in seconds. Re-fetches the+ ``http`` accessor each poll to keep the bearer token fresh over a long pull.+ """+ start = time.monotonic()+ deadline = start + timeout+ while True:+ total, avail, phase = pool_counts(get_http, pool)+ if avail >= 1:+ info(f"pool warm: {avail}/{total} VM(s) ready (phase {phase})")+ return+ if time.monotonic() > deadline:+ die(f"timed out after {timeout:.0f}s waiting for a warm VM "+ f"(pool {phase}, {avail}/{total} ready).\n"+ f" Most common cause: the --image tag does not exist in the registry, "+ f"so the VM sits in ImagePullBackOff and never boots. Note that "+ f"'desktop-workspace:latest' / 'osgym-workspace:latest' are typically "+ f"NOT published — list real tags with:\n"+ f" aws ecr describe-images --repository-name desktop-workspace --region us-west-2\n"+ f" Less commonly the cold pull just needs longer — raise --warm-timeout.")+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] pool={phase} ({avail}/{total} VMs ready) — warming "+ f"(image pull + guest boot + service on the readiness port) …")+ time.sleep(poll)+++def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int = 0) -> None:+ spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}+ # The pool-operator fails an unbound claim after spec.bindDeadline seconds+ # (default 300, claim_handlers.BIND_DEADLINE_DEFAULT_S). We claim only after+ # the pool is already warm, so binding is near-instant — but a non-zero+ # deadline is a safety margin in case the warm VM is mid hard-reset.+ if bind_deadline:+ spec["bindDeadline"] = bind_deadline+ r = http.post(+ claims_url(pool),+ json={+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",+ "kind": "OSGymSandboxClaim",+ "metadata": {"name": name},+ # Same convention the SPA uses: the pool's template is <pool>-template.+ "spec": spec,+ },+ )+ if r.status_code == 403:+ die(+ "403 creating claim — per-pool keys have no K8s identity. Use a "+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."+ )+ r.raise_for_status()+ info(f"claim {name!r} created")+++def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:+ """Poll the claim until status.phase == Bound; return the sandbox name.++ While we wait we also surface the pool's warm-VM counts, so a cold start+ (image pull + guest boot + MCP coming up on the readiness port) is visible+ rather than a silent hang. Re-fetches the ``http`` accessor each poll so the+ bearer token stays fresh across a long (cold-boot) wait.+ """+ start = time.monotonic()+ deadline = start + timeout+ while True:+ r = get_http().get(claims_url(pool, name))+ r.raise_for_status()+ status = r.json().get("status") or {}+ phase = status.get("phase", "Pending")+ sandbox = (status.get("sandbox") or {}).get("name")+ if phase == "Bound" and sandbox:+ return sandbox+ if phase == "Failed":+ die(f"claim {name} failed: {status}")+ if time.monotonic() > deadline:+ die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")+ total, avail, pphase = pool_counts(get_http, pool)+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] claim={phase} pool={pphase} ({avail}/{total} VMs ready) …")+ time.sleep(poll)+++def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:+ """GET url until the in-guest service answers (not a proxy 502/503/504).++ Backstop for the slim window where the sandbox is Bound but the in-guest+ HTTP server hasn't finished accepting connections yet. Re-fetches the+ ``http`` accessor each poll to keep the bearer token fresh.+ """+ start = time.monotonic()+ deadline = start + timeout+ while True:+ try:+ resp = get_http().get(url, timeout=15.0)+ except httpx.HTTPError as e:+ resp = None+ reason = type(e).__name__+ else:+ reason = f"HTTP {resp.status_code}"+ if resp is not None and resp.status_code not in (502, 503, 504):+ info(f"service responding ({reason})")+ return+ if time.monotonic() > deadline:+ die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] {reason} — guest still booting …")+ time.sleep(poll)+++def list_mcp_tools(http: httpx.Client, base: str, mcp_path: str) -> None:+ """cua-driver MCP handshake over Streamable HTTP:+ initialize -> notifications/initialized -> tools/list, then print the tools."""+ url = f"{base}/{mcp_path.lstrip('/')}"+ headers = {+ "Content-Type": "application/json",+ # Streamable HTTP requires advertising both content types.+ "Accept": "application/json, text/event-stream",+ }++ r = http.post(+ url,+ headers=headers,+ timeout=30.0,+ json={+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": "2025-03-26",+ "capabilities": {},+ "clientInfo": {"name": "create_pool_and_list_tools", "version": "0.1.0"},+ },+ },+ )+ r.raise_for_status()+ session = r.headers.get("mcp-session-id")+ info(f"MCP initialize: HTTP {r.status_code}" + (f", session {session}" if session else ""))+ if session:+ headers["Mcp-Session-Id"] = session++ # Notify the server we're ready (no response expected).+ http.post(+ url,+ headers=headers,+ timeout=30.0,+ json={"jsonrpc": "2.0", "method": "notifications/initialized"},+ )++ r = http.post(+ url,+ headers=headers,+ timeout=30.0,+ json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"},+ )+ r.raise_for_status()+ # Streamable HTTP returns SSE ("event: message\ndata: {...}"); the JSON+ # payload is on the data: line. Fall back to the raw body for plain JSON.+ data = next((ln[6:] for ln in r.text.splitlines() if ln.startswith("data: ")), r.text)+ tools = json.loads(data).get("result", {}).get("tools", [])++ print(f"\nMCP tools ({len(tools)}):", flush=True)+ for i, t in enumerate(sorted(tools, key=lambda t: t.get("name", "")), 1):+ name = t.get("name", "?")+ desc = " ".join((t.get("description") or "").split())+ if len(desc) > 70:+ desc = desc[:67] + "…"+ print(f" {i:3d}. {name:<24} {desc}", flush=True)+ if not tools:+ print(" (the server returned an empty tool list)", flush=True)+++def delete_pool(http: httpx.Client, pool: str) -> None:+ r = http.delete(pool_url(pool, pool))+ info(f"deleted pool {pool!r} (HTTP {r.status_code})")+ r = http.delete(f"/api/namespaces/{pool}")+ info(f"deleted namespace {pool!r} (HTTP {r.status_code})")+++# ── Main ──────────────────────────────────────────────────────────────────+++def main() -> None:+ p = argparse.ArgumentParser(+ description="Create a pool on run.cua.ai, claim a sandbox, and list its MCP tools.",+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,+ )+ p.add_argument("--name", required=True, help="pool name (also the namespace; lowercase/dashes)")+ p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),+ help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")+ p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),+ help="OAuth client secret; env CUA_CLIENT_SECRET")+ p.add_argument("--image", default=DEFAULT_IMAGE, help="workspace containerDisk image")+ p.add_argument("--port", type=int, default=3000, help="service target port on the VM (MCP)")+ p.add_argument("--service-name", default="mcp", help="name for the per-sandbox Service")+ p.add_argument("--mcp-path", default="/mcp", help="path the MCP server is mounted at")+ p.add_argument("--replicas", type=int, default=1, help="pre-warmed VMs the pool keeps")+ p.add_argument("--cpu", type=int, default=4, help="vCPU cores per VM")+ p.add_argument("--ram", default="4Gi", help="memory per VM (K8s quantity)")+ p.add_argument("--firmware", choices=["bios", "efi"], default="bios",+ help="VM firmware (efi for GPT/UEFI-only images, e.g. Windows)")+ p.add_argument("--readiness-port", type=int, default=None,+ help="TCP readiness port (default: --port; 0 disables the probe)")+ p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),+ help="OIDC token endpoint")+ p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),+ help="cyclops-cs base URL")+ p.add_argument("--claim-name", help="claim name (default: claim-<random>)")+ p.add_argument("--template-timeout", type=float, default=120,+ help="seconds to wait for the pool->template projection")+ p.add_argument("--warm-timeout", type=float, default=900,+ help="seconds to wait for the pool's first warm VM before claiming "+ "(covers the cold image pull + guest boot)")+ p.add_argument("--bind-deadline", type=int, default=600,+ help="claim spec.bindDeadline (operator fails an unbound claim after "+ "this; 0 uses the operator default of 300s)")+ p.add_argument("--bind-timeout", type=float, default=300,+ help="seconds the script waits for the claim to bind (fast once warm)")+ p.add_argument("--ready-timeout", type=float, default=420,+ help="seconds to wait for the in-guest service after binding")+ p.add_argument("--poll-interval", type=float, default=5,+ help="seconds between status polls")+ p.add_argument("--keep-claim", action="store_true",+ help="keep the claim (and its VM) instead of releasing it on exit")+ p.add_argument("--delete-pool", action="store_true",+ help="tear down the pool AND namespace on exit (full cleanup)")+ args = p.parse_args()++ if not args.client_id or not args.client_secret:+ die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "+ "(per-user key from POST /api/user-keys)")+ if args.client_id.startswith("key-"):+ die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "+ "Creating namespaces/pools/claims needs a per-USER key ('ukey-…', "+ "from POST /api/user-keys).")++ readiness_port = args.port if args.readiness_port is None else args.readiness_port+ pool = args.name+ claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"++ step(f"Authenticating to {args.base_url} (client {args.client_id})")+ client = TrainClient.from_key(+ token_url=args.token_url,+ client_id=args.client_id,+ client_secret=args.client_secret,+ base_url=args.base_url,+ )+ # get_httpx_client() re-mints the bearer token near expiry, so fetch it+ # per request rather than holding one reference.+ http = client.get_httpx_client+ info("token acquired")++ step(f"Creating namespace {pool!r}")+ create_namespace(http(), pool)++ step(f"Creating pool {pool!r}")+ create_pool(+ http(),+ pool=pool,+ image=args.image,+ cpu=args.cpu,+ ram=args.ram,+ replicas=args.replicas,+ firmware=args.firmware,+ service_name=args.service_name,+ port=args.port,+ readiness_port=readiness_port,+ )++ step("Waiting for the pool-operator to project the template + warm pool")+ wait_template(http, pool, args.template_timeout, args.poll_interval)++ step("Waiting for the pool's first VM to warm up (so the claim binds fast)")+ info("(cold start = containerDisk image pull + guest boot + service on the readiness port)")+ wait_pool_warm(http, pool, args.warm_timeout, args.poll_interval)++ step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")+ create_claim(http(), pool, claim_name, args.bind_deadline)++ try:+ step("Waiting for the claim to bind to the warm sandbox")+ sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)+ info(f"bound to sandbox {sandbox!r}")++ # Per-sandbox Service is "<sandbox>-<service>" on port 80 -> targetPort.+ svc_base = f"/api/svc/{pool}/{sandbox}-{args.service_name}"++ step("Waiting for the in-guest MCP server to answer")+ wait_service_ready(http, f"{svc_base}/healthz", args.ready_timeout, args.poll_interval)++ step(f"Listing MCP tools at {svc_base}{args.mcp_path}")+ list_mcp_tools(http(), svc_base, args.mcp_path)+ finally:+ print(flush=True)+ if args.keep_claim:+ step(f"Keeping claim {claim_name!r} (its VM stays out of the pool)")+ info(f"release later with: DELETE {claims_url(pool, claim_name)}")+ else:+ step(f"Releasing claim {claim_name!r}")+ r = http().delete(claims_url(pool, claim_name))+ info(f"released (HTTP {r.status_code}) — the VM hard-resets and rejoins the pool")++ if args.delete_pool:+ step(f"Tearing down pool {pool!r}")+ delete_pool(http(), pool)+ else:+ step(f"Pool {pool!r} is live")+ info(f"claim more sandboxes: POST {claims_url(pool)} (spec.sandboxTemplateRef.name={pool}-template)")+ info(f"delete it when done: DELETE {pool_url(pool, pool)} (and DELETE /api/namespaces/{pool})")+++if __name__ == "__main__":+ main()diff --git a/libs/fleet/python-sdk/examples/lanes_fan_out.py b/libs/fleet/python-sdk/examples/lanes_fan_out.pynew file mode 100644index 0000000000..15b34b01f5--- /dev/null+++ b/libs/fleet/python-sdk/examples/lanes_fan_out.py@@ -0,0 +1,134 @@+#!/usr/bin/env python3+"""Minimal uv run example: send two batches to the same lane VMs.++Run:+ uv run --with cua-train --extra-index-url https://wheels.cua.ai/simple/ \+ lanes_fan_out.py \+ --client-id key-xxxxxxxx \+ --client-secret your-secret \+ --pool test-pool-please-ignore+"""++from __future__ import annotations++import argparse+import random+import time++from cua_train import TrainClient+from cua_train.models import (+ AcquireLanesRequest,+ Action,+ ActionParameters,+ BatchSubmitRequest,+ ReleaseLanesRequest,+ RunConfig,+)+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(description="Submit two batches to the same lane VMs.")+ parser.add_argument("--client-id", required=True, help="OAuth client id")+ parser.add_argument("--client-secret", required=True, help="OAuth client secret")+ parser.add_argument(+ "--token-url",+ default="https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token",+ help="OIDC token endpoint",+ )+ parser.add_argument("--pool", default="test-pool-please-ignore", help="Target pool name")+ parser.add_argument("--lanes", type=int, default=4, help="Number of lanes (VMs) to acquire")+ parser.add_argument("--steps", type=int, default=5, help="Clicks per run")+ parser.add_argument("--run-timeout", type=int, default=300, help="Run timeout seconds")+ parser.add_argument("--poll-interval", type=float, default=2.0, help="Poll interval seconds")+ return parser.parse_args()+++def random_click() -> Action:+ return Action(+ action_type="CLICK",+ parameters=ActionParameters.from_dict(+ {"x": random.randint(200, 1720), "y": random.randint(100, 980), "button": "left"}+ ),+ )+++def wait_for_label(client: TrainClient, pool: str, label: str, poll_interval: float) -> list:+ res = client.get_label_results(pool=pool, label=label, completed_only=True)+ while True:+ runs = [r for b in res.batches for r in b.runs] if getattr(res, "batches", None) else []+ if getattr(res, "all_completed", False) and runs:+ return runs+ time.sleep(poll_interval)+ res = client.get_label_results(pool=pool, label=label, completed_only=True)+++def submit_and_wait(+ client: TrainClient,+ pool: str,+ lanes: list[str],+ label: str,+ steps: int,+ run_timeout: int,+ poll_interval: float,+) -> tuple[int, int]:+ runs = [RunConfig(vm_id=vm_id, steps=[random_click() for _ in range(steps)], timeout=run_timeout) for vm_id in lanes]++ client.submit_label_batch(+ pool=pool,+ label=label,+ body=BatchSubmitRequest(+ runs=runs,+ concurrency=len(lanes),+ ),+ )+ print(f"submitted {label} with {len(runs)} runs")++ results = wait_for_label(client, pool, label, poll_interval)+ ok = sum(1 for r in results if getattr(r, "ok", False))+ return ok, len(results)+++def main() -> None:+ args = parse_args()++ client = TrainClient.from_key(+ token_url=args.token_url,+ client_id=args.client_id,+ client_secret=args.client_secret,+ )++ lanes = client.acquire_lanes(pool=args.pool, body=AcquireLanesRequest(n=args.lanes)).vm_ids+ print(f"acquired {len(lanes)} lanes")++ try:+ first_label = f"uv-example-{int(time.time())}-1"+ first_ok, first_total = submit_and_wait(+ client,+ args.pool,+ lanes,+ first_label,+ args.steps,+ args.run_timeout,+ args.poll_interval,+ )+ print(f"first batch completed: {first_ok}/{first_total} ok")++ # Reuses the exact same vm_ids from the acquired lanes for a second interaction.+ second_label = f"uv-example-{int(time.time())}-2"+ second_ok, second_total = submit_and_wait(+ client,+ args.pool,+ lanes,+ second_label,+ args.steps,+ args.run_timeout,+ args.poll_interval,+ )+ print(f"second batch completed: {second_ok}/{second_total} ok")+ finally:+ released = client.release_lanes(pool=args.pool, body=ReleaseLanesRequest(vm_ids=lanes)).released+ print(f"released {released} lanes")+++if __name__ == "__main__":+ main()diff --git a/libs/fleet/python-sdk/examples/linux-mini-swe.yaml b/libs/fleet/python-sdk/examples/linux-mini-swe.yamlnew file mode 100644index 0000000000..0a72c9b06d--- /dev/null+++ b/libs/fleet/python-sdk/examples/linux-mini-swe.yaml@@ -0,0 +1,54 @@+apiVersion: cua.ai/v1alpha1+kind: AgentWindowsDoubleMCPRun+metadata:+ name: linux-mini-swe-demo++spec:+ pool:+ image: 296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace-duo:claude-duo-mcp-tools-assert+ cpu: 4+ ram: 4Gi+ firmware: bios # Linux workspace image boots on KubeVirt's default BIOS (efi is for the Windows image)+ replicas: 2+ minAvailable: 1+ readinessPort: 8000+ services:+ - type: mcp+ label: computer-server+ service: server+ port: 8000+ mcpPath: /mcp+ health: /status+ - type: mcp+ label: cua-driver+ service: mcp+ port: 3000+ mcpPath: /mcp+ health: /healthz+ - type: auxiliary+ label: novnc+ service: novnc+ port: 6080+ claim:+ bindDeadline: 600+ agent:+ model: us.anthropic.claude-sonnet-4-6+ task: >-+ install and launch firefox in this linux env, open+ https://news.yahoo.com/, inspect the Yahoo News front page, and then+ report the visible page contents in a concise final message. Do all work+ inside this remote Windows sandbox, not on the local machine.+ maxSteps: 60+ keepImages: 2+ rollout:+ templateTimeout: 120+ warmTimeout: 0+ bindTimeout: 0+ readyTimeout: 0+ pollInterval: 10+ teardown:+ # keepPool:false so `--delete-pool` actually tears down (the script's+ # if-keep/elif-delete precedence ignores --delete-pool when keepPool is+ # true). With no teardown flags the pool is still left live for reuse.+ keepPool: false+ deletePool: falsediff --git a/libs/fleet/python-sdk/examples/live_demo.py b/libs/fleet/python-sdk/examples/live_demo.pynew file mode 100644index 0000000000..417ca3cb2d--- /dev/null+++ b/libs/fleet/python-sdk/examples/live_demo.py@@ -0,0 +1,460 @@+#!/usr/bin/env python3+"""Live demo — N lanes loop ``square -> triangle -> RESET`` forever, streamed to+a local webserver (one live MJPEG per lane) with a metadata overlay.++What it illustrates (cyclops-cs 0.2.0):+ * explicit ``acquire_lanes`` / ``release_lanes``+ * the SAME warm VM reused across batches — square (batch 1) then triangle+ (batch 2) land on one desktop; the on-frame ``vm`` id stays the same+ * in-band ``RESET`` (batch 3) hard-resets the VM — watch the ``vm`` id change+ * the generic facade — every call is ``client.<op>(...)``, no ``.sync``++Each frame carries a banner (lane, iteration, phase, step, vm id); while a batch+is being provisioned/run you get a loading screen with an elapsed timer.++Setup::++ pip install cua-train --extra-index-url https://wheels.cua.ai/simple/+ pip install pillow boto3+ export CUA_CLIENT_ID=key-xxxxxxxx # from POST /api/keys+ export CUA_CLIENT_SECRET=...+ python live_demo.py # then open http://127.0.0.1:8000++Run-batch screenshots come back as S3 keys, so frames are pulled from the+results bucket (needs AWS read access). Ctrl-C releases the lanes.++Env knobs: CUA_POOL, CUA_LANES (default 4), CUA_DEMO_PORT (8000),+CUA_TOKEN_URL, CUA_RESULTS_BUCKET. Set CUA_DEMO_SELFTEST=1 to serve+loading/placeholder frames without touching the backend (preview the UI).+"""++from __future__ import annotations++import io+import os+import threading+import time+import uuid+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import boto3+from PIL import Image, ImageDraw, ImageFont++from cua_train import TrainClient+from cua_train.models import (+ AcquireLanesRequest,+ Action,+ ActionParameters,+ BatchSubmitRequest,+ ErrorResponse,+ ReleaseLanesRequest,+ RunConfig,+)++POOL = os.environ.get("CUA_POOL", "test-pool-please-ignore")+TOKEN_URL = os.environ.get(+ "CUA_TOKEN_URL",+ "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token",+)+RESULTS_BUCKET = os.environ.get("CUA_RESULTS_BUCKET", "cua-osgym-batch-results")+N_LANES = int(os.environ.get("CUA_LANES", "4"))+PORT = int(os.environ.get("CUA_DEMO_PORT", "8000"))+SELFTEST = os.environ.get("CUA_DEMO_SELFTEST") == "1"++W, H = 1920, 1080+SCALE = 960 / W+SW, SH = round(W * SCALE), round(H * SCALE)+ANIM_DT = 0.06 # loading-frame redraw + stream push interval (~16 fps)+RED, BLUE, ORANGE, GREY, INK = (255, 90, 90), (90, 150, 255), (255, 165, 50), (120, 120, 120), (190, 205, 230)++SQUARE = [(480, 270), (1440, 270), (1440, 810), (480, 810), (480, 270)]+TRIANGLE = [(960, 170), (1440, 880), (480, 880), (960, 170)]+++def _font(size):+ try:+ return ImageFont.load_default(size=size)+ except TypeError: # lint-ignore: swallowed-exception — old Pillow without size=+ return ImageFont.load_default()+++FONT, FONT_SM, FONT_BIG = _font(22), _font(16), _font(34)+++def _clicks(points):+ return [+ Action(action_type="CLICK", parameters=ActionParameters.from_dict({"x": x, "y": y, "button": "left"}))+ for x, y in points+ ]+++def _short(vm):+ return vm.rsplit("-", 1)[-1][:8] if vm else "?"+++# ── shared latest-frame buffers (one JPEG per lane) ────────────────────────────+_frames: list[bytes | None] = [None] * N_LANES+# Each lane's current VM id (changes on RESET); tracked so shutdown releases the+# live VMs rather than the now-stale ones returned by acquire_lanes.+_cur_vms: list[str | None] = [None] * N_LANES+_lock = threading.Lock()+++def set_frame(i, jpeg):+ with _lock:+ _frames[i] = jpeg+++def get_frame(i):+ with _lock:+ return _frames[i]+++def _jpeg(im):+ buf = io.BytesIO()+ im.convert("RGB").save(buf, "JPEG", quality=80)+ return buf.getvalue()+++def banner(im, lines, accent):+ """Top metadata strip: line 0 in the accent colour, the rest dimmed."""+ d = ImageDraw.Draw(im, "RGBA")+ d.rectangle([0, 0, im.width, 12 + 28 * len(lines)], fill=(0, 0, 0, 170))+ y = 8+ for i, ln in enumerate(lines):+ d.text((12, y), ln, fill=tuple(accent) if i == 0 else (235, 235, 235), font=FONT if i == 0 else FONT_SM)+ y += 28+++CYAN, MINT = (90, 165, 255), (110, 210, 160)+++def loading_frame(head, secs, status="waiting for VM…", sub="", accent=CYAN):+ """A status screen with a spinner + elapsed timer. `status`/`accent`+ distinguish the wait: acquiring a fresh VM vs. a batch running / waiting+ for its results."""+ im = Image.new("RGB", (SW, SH), (15, 17, 22))+ d = ImageDraw.Draw(im)+ cx, cy, r = SW // 2, SH // 2, 40+ d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=(40, 46, 58), width=6) # track+ a = (secs * 220) % 360 # rotating head+ d.arc([cx - r, cy - r, cx + r, cy + r], a, a + 110, fill=accent, width=6)+ d.text((cx, cy + r + 36), f"{status} {secs:0.1f}s", fill=INK, font=FONT, anchor="mm")+ banner(im, [head, sub], accent)+ return _jpeg(im)+++def path_frame(base, head, sub, accent, path, upto, prior=None):+ """A real screenshot with the click path traced + metadata banner."""+ im = base.resize((SW, SH)).convert("RGB")+ d = ImageDraw.Draw(im)+ if prior: # earlier shape on this same VM, faded+ d.line([(x * SCALE, y * SCALE) for x, y in prior], fill=GREY, width=3)+ pts = [(x * SCALE, y * SCALE) for x, y in path[: upto + 1]]+ if len(pts) >= 2:+ d.line(pts, fill=accent, width=4)+ for sx, sy in pts:+ d.ellipse([sx - 7, sy - 7, sx + 7, sy + 7], fill=accent)+ banner(im, [head, sub], accent)+ return _jpeg(im)+++def reset_frame(base, head, sub):+ im = base.resize((SW, SH)).convert("RGB")+ banner(im, [head, sub], ORANGE)+ return _jpeg(im)+++# ── backend helpers ────────────────────────────────────────────────────────────+def make_client():+ return TrainClient.from_key(+ token_url=TOKEN_URL,+ client_id=os.environ["CUA_CLIENT_ID"],+ client_secret=os.environ["CUA_CLIENT_SECRET"],+ )+++def wait_run(client, label, stop, idx, head, timeout=300):+ """Poll for the run; meanwhile paint a loading screen with a live timer.+ Raises on ErrorResponse (e.g. 401) so the caller can refresh the client."""+ t0 = time.time()+ last_poll = 0.0+ while not stop.is_set():+ # Redraw the spinner every frame (smooth); the VM already exists, so+ # this is "running / waiting for results", not "waiting for a VM".+ set_frame(+ idx,+ loading_frame(+ head,+ time.time() - t0,+ status="running — waiting for results…",+ sub="executing steps on the VM",+ accent=MINT,+ ),+ )+ if time.time() - last_poll >= 2:+ last_poll = time.time()+ try:+ res = client.get_label_results(pool=POOL, label=label, completed_only=True)+ except Exception as e: # transient network blip — keep waiting+ print(f"[lane {idx}] poll {label}: {e!r}", flush=True)+ else:+ if isinstance(res, ErrorResponse):+ raise RuntimeError(f"results error: {res}")+ runs = [r for b in res.batches for r in b.runs] if getattr(res, "batches", None) else []+ if getattr(res, "all_completed", False) and runs:+ return runs[0]+ if time.time() - t0 > timeout:+ return None+ stop.wait(ANIM_DT)+ return None+++def run_batch(client, idx, vm, steps, stop, head):+ label = f"demo-{idx}-{uuid.uuid4().hex[:6]}"+ resp = client.submit_label_batch(+ pool=POOL,+ label=label,+ body=BatchSubmitRequest(runs=[RunConfig(vm_id=vm, steps=steps, timeout=300)], concurrency=1, keep_warm=True),+ )+ if isinstance(resp, ErrorResponse):+ raise RuntimeError(f"submit error: {resp}")+ return wait_run(client, label, stop, idx, head)+++def play(idx, run, s3, stop, frame_fn):+ """Stream a run's screenshots (S3 keys) into the lane buffer, one per step."""+ shots = run.screenshots or []+ for j, k in enumerate(shots):+ if stop.is_set():+ return+ if not k:+ continue+ raw = s3.get_object(Bucket=RESULTS_BUCKET, Key=k)["Body"].read()+ set_frame(idx, frame_fn(Image.open(io.BytesIO(raw)), j, len(shots)))+ stop.wait(0.45)+++# ── per-lane worker: loop square (b1) → triangle (b2) → RESET (b3), forever ─────+def lane_worker(idx, vm0, stop):+ s3 = boto3.client("s3")+ client = make_client() # TrainClient refreshes its token transparently+ cur, it = vm0, 0+ _cur_vms[idx] = vm0+ while not stop.is_set():+ try:+ it += 1++ # batch 1 — square on the current warm VM+ r = run_batch(client, idx, cur, _clicks(SQUARE), stop, f"LANE {idx} · iter {it} · SQUARE (batch 1)")+ if r is None:+ continue+ cur = r.vm_id+ _cur_vms[idx] = cur+ play(+ idx,+ r,+ s3,+ stop,+ lambda im, j, n: path_frame(+ im, f"LANE {idx} iter {it} SQUARE {j + 1}/{n}", f"batch 1 · vm …{_short(cur)}", RED, SQUARE, j+ ),+ )++ # batch 2 — triangle on the SAME VM (reuse across batches)+ r = run_batch(client, idx, cur, _clicks(TRIANGLE), stop, f"LANE {idx} · iter {it} · TRIANGLE (batch 2)")+ if r is None:+ continue+ cur = r.vm_id+ _cur_vms[idx] = cur+ play(+ idx,+ r,+ s3,+ stop,+ lambda im, j, n: path_frame(+ im,+ f"LANE {idx} iter {it} TRIANGLE {j + 1}/{n}",+ f"batch 2 · vm …{_short(cur)} (same VM, reused)",+ BLUE,+ TRIANGLE,+ j,+ prior=SQUARE,+ ),+ )++ # batch 3 — in-band RESET: hard reset → new VM+ old = cur+ r = run_batch(+ client, idx, cur, [Action(action_type="RESET")], stop, f"LANE {idx} · iter {it} · RESET (batch 3)"+ )+ if r is None:+ continue+ cur = r.vm_id+ _cur_vms[idx] = cur+ play(+ idx,+ r,+ s3,+ stop,+ lambda im, j, n: reset_frame(+ im, "RESET — hard reset", f"vm …{_short(old)} → …{_short(cur)} (new VM, same lane {idx})"+ ),+ )+ except Exception as e: # transient network blip — log and retry the iteration+ print(f"[lane {idx}] iter {it} error: {e!r}; retrying", flush=True)+ stop.wait(2)+++# ── webserver: one MJPEG stream per lane ───────────────────────────────────────+class Handler(BaseHTTPRequestHandler):+ def log_message(self, *_):+ pass++ def do_GET(self):+ if self.path == "/":+ self._page()+ elif self.path.startswith("/lane/"):+ try:+ idx = int(self.path.split("/")[2])+ except (IndexError, ValueError): # lint-ignore: swallowed-exception — bad /lane path, handled as 404+ self.send_error(404)+ return+ self._stream(idx)+ else:+ self.send_error(404)++ def _page(self):+ cards = "".join(+ f'<figure><figcaption>lane {i}</figcaption><img src="/lane/{i}"></figure>' for i in range(N_LANES)+ )+ body = f"""<!doctype html><html><head><meta charset=utf-8>+<title>cyclops-cs — square / triangle / reset loop</title>+<style>body{{background:#111;color:#eee;font-family:system-ui;margin:0;padding:24px;text-align:center}}+.grid{{display:flex;flex-wrap:wrap;gap:18px;justify-content:center}}+figure{{margin:0}} img{{width:46vw;border:1px solid #333;border-radius:8px}}+figcaption{{margin:6px;color:#9cf}} .legend{{max-width:1000px;margin:8px auto 0;color:#bbb;line-height:1.5}}+b{{color:#eee}}</style></head>+<body><h2>cyclops-cs 0.2.0 — {N_LANES} lanes looping square → triangle → reset</h2>+<p class=legend>Each tile is one <b>lane</b> = a persistent VM. Per loop it runs three batches on+the <b>same warm VM</b>: <span style="color:#ff5a5a">square</span> (batch 1) →+<span style="color:#5a96ff">triangle</span> (batch 2, <b>VM reused</b>) →+<span style="color:#ffa532">RESET</span> (batch 3, <b>new VM</b> — watch the <code>vm</code> id change).+Then it repeats.</p>+<div class=grid>{cards}</div></body></html>""".encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def _stream(self, idx):+ self.send_response(200)+ self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=frame")+ self.send_header("Cache-Control", "no-cache")+ self.end_headers()+ try:+ while True:+ frame = get_frame(idx) or loading_frame("starting…", 0.0)+ self.wfile.write(b"--frame\r\nContent-Type: image/jpeg\r\n")+ self.wfile.write(f"Content-Length: {len(frame)}\r\n\r\n".encode())+ self.wfile.write(frame)+ self.wfile.write(b"\r\n")+ time.sleep(ANIM_DT)+ except (BrokenPipeError, ConnectionResetError): # lint-ignore: swallowed-exception — viewer closed stream+ pass+++def _acquire_with_timer(client, stop_anim):+ """Acquire N lanes while painting a loading+timer screen on every tile."""+ t0 = time.time()+ box = {}++ def anim():+ while not stop_anim.is_set():+ for i in range(N_LANES):+ set_frame(+ i,+ loading_frame(+ f"LANE {i} · acquiring",+ time.time() - t0,+ status="waiting for VM…",+ sub="acquire_lanes — provisioning a warm VM from the pool",+ ),+ )+ time.sleep(ANIM_DT)++ t = threading.Thread(target=anim, daemon=True)+ t.start()+ try:+ # The pool may not have N warm VMs yet (503 / ErrorResponse). Keep the+ # "waiting for VM…" screen up and retry instead of crashing.+ while not stop_anim.is_set():+ res = client.acquire_lanes(pool=POOL, body=AcquireLanesRequest(n=N_LANES))+ if isinstance(res, ErrorResponse):+ print(f"acquire_lanes: {res}; retrying…", flush=True)+ time.sleep(3)+ continue+ box["lanes"] = res.vm_ids+ break+ finally:+ stop_anim.set()+ t.join(timeout=2)+ return box["lanes"]+++def main():+ for i in range(N_LANES):+ set_frame(i, loading_frame("starting…", 0.0))++ server = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ print(f"streaming on http://127.0.0.1:{PORT} ({N_LANES} lanes)")++ if SELFTEST:+ print("SELFTEST: serving loading frames, no backend. Ctrl-C to stop.")+ t0 = time.time()+ try:+ while True:+ for i in range(N_LANES):+ state = (+ ("running — waiting for results…", "executing steps on the VM", MINT)+ if (int(t0) + i) % 2+ else ("waiting for VM…", "acquire_lanes — provisioning a warm VM", CYAN)+ )+ set_frame(+ i,+ loading_frame(+ f"LANE {i} · selftest", time.time() - t0, status=state[0], sub=state[1], accent=state[2]+ ),+ )+ time.sleep(ANIM_DT)+ except KeyboardInterrupt: # lint-ignore: swallowed-exception — Ctrl-C stops selftest+ return++ client = make_client()+ print(f"acquire_lanes(n={N_LANES}) …")+ lanes = _acquire_with_timer(client, threading.Event())++ stop = threading.Event()+ workers = [threading.Thread(target=lane_worker, args=(i, lanes[i], stop), daemon=True) for i in range(N_LANES)]+ for w in workers:+ w.start()+ try:+ while any(w.is_alive() for w in workers):+ time.sleep(1)+ except KeyboardInterrupt: # lint-ignore: swallowed-exception — Ctrl-C, releases in finally+ print("\nstopping …")+ finally:+ stop.set()+ for w in workers:+ w.join(timeout=10)+ # Release the VMs the lanes currently hold (RESET changes the id each+ # iteration), plus the originals, so nothing leaks back to the pool.+ to_release = sorted({*lanes, *(v for v in _cur_vms if v)})+ client.release_lanes(pool=POOL, body=ReleaseLanesRequest(vm_ids=to_release))+ print(f"released {len(to_release)} VMs; bye.")+++if __name__ == "__main__":+ main()diff --git a/libs/fleet/python-sdk/examples/provision_windows_and_drive_with_cua_sdk.py b/libs/fleet/python-sdk/examples/provision_windows_and_drive_with_cua_sdk.pynew file mode 100644index 0000000000..3655674331--- /dev/null+++ b/libs/fleet/python-sdk/examples/provision_windows_and_drive_with_cua_sdk.py@@ -0,0 +1,575 @@+#!/usr/bin/env -S uv run --script+# /// script+# requires-python = ">=3.12,<3.14"+# dependencies = [+# "cua-train",+# "httpx",+# # Direct-proxy support (api_base_url / api_headers) shipped in cua-computer+# # 0.5.19 — https://github.com/trycua/cua/pull/1932+# "cua-computer>=0.5.19",+# ]+#+# [tool.uv]+# extra-index-url = ["https://wheels.cua.ai/simple/"]+# ///+"""Provision a **Windows computer-server** pool on cyclops-cs / run.cua.ai, claim+a sandbox, then drive it with the real ``cua-computer`` SDK (screenshot, screen+size, a shell command) — and tear the whole thing back down afterward.++This is the SDK companion to ``provision_windows_and_list_mcp_tools.py`` (which+claims the same kind of sandbox but only lists its MCP tools). Both target the+Windows ``cua-server-windows`` image, which runs ``python -m computer_server`` on+:8000.++Connecting directly through the proxy (no forwarder)+----------------------------------------------------+cyclops-cs exposes a sandbox only through an authenticated reverse proxy at+``{base_url}/api/svc/{ns}/{sandbox}-{service}/...`` that wants an+``Authorization: Bearer <token>`` header. The ``cua-computer`` SDK now supports+pointing at exactly that kind of endpoint via two params (added in+https://github.com/trycua/cua/pull/1932):++ Computer(+ use_host_computer_server=True,+ os_type="windows",+ api_base_url="https://run.cua.ai/api/svc/<ns>/<sandbox>-api",+ api_headers={"Authorization": "Bearer <token>"},+ )++The SDK derives its REST/WebSocket URIs from ``api_base_url`` (keeping the path+prefix) and sends ``api_headers`` on every request — so it talks to the proxy+directly. No localhost forwarder, no subprocess.++> The bearer is short-lived, so we mint a fresh one right before connecting. For+> a long-running session you'd refresh it yourself (the proxy re-checks it per+> request); this example's actions finish in seconds.++Two modes+---------+* default — connect the SDK, take a screenshot + screen size + run a command,+ print the results, then tear down.+* ``--print-connection`` — print the ``api_base_url`` + a fresh bearer + a+ ready-to-paste ``Computer(...)`` snippet and hold the sandbox open so you can+ drive it from another process / your own agent. Ctrl-C tears it down.++Lifecycle is otherwise identical to the MCP example: create namespace → pool+(Windows image, **efi firmware**, service on :8000) → wait warm → claim → wait+bound → wait ``/status`` → [drive | print] → **teardown** (claim + pool ++namespace; this is a throwaway test scenario). Pass ``--keep`` to leave it up.++Auth — use a per-USER key (``ukey-...``, from POST /api/user-keys), not a+per-pool key. Windows is slow to first-boot; the defaults wait generously.++Setup (zero-install with uv)::++ export CUA_CLIENT_ID=ukey-xxxxxxxx+ export CUA_CLIENT_SECRET=...+ uv run provision_windows_and_drive_with_cua_sdk.py --name win-api-demo+ uv run provision_windows_and_drive_with_cua_sdk.py --name win-fwd-demo --print-connection++Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.+"""++from __future__ import annotations++import argparse+import asyncio+import os+import sys+import time+import uuid+from collections.abc import Callable++import httpx++from cua_train import TrainClient++DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"+DEFAULT_BASE_URL = "https://run.cua.ai"+# The Windows computer-server image: Windows Server 2022 + cua-computer-server on+# :8000. It is a dockur-built GPT/UEFI image, so the pool MUST boot it with efi+# firmware (see --firmware below).+DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest"++# OSGymWorkspacePool — the legacy single-object pool CR the cyclops-cs SPA+# creates (cua.ai/v1). The pool-operator compat shim translates it into the+# native OSGymSandboxTemplate + OSGymSandboxWarmPool pair.+POOL_GROUP = "cua.ai"+POOL_VERSION = "v1"+POOL_PLURAL = "osgymworkspacepools"++# OSGymSandboxTemplate / OSGymSandboxClaim live in the osgym.cua.ai group.+EXT_GROUP = "osgym.cua.ai"+EXT_VERSION = "v1alpha1"+TEMPLATE_PLURAL = "osgymsandboxtemplates"+CLAIM_PLURAL = "osgymsandboxclaims"+++# ── URL builders (relative to base_url, e.g. https://run.cua.ai) ──────────+++def pool_url(pool: str, name: str | None = None) -> str:+ base = f"/api/k8s/apis/{POOL_GROUP}/{POOL_VERSION}/namespaces/{pool}/{POOL_PLURAL}"+ return f"{base}/{name}" if name else base+++def template_url(pool: str, name: str) -> str:+ return f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}/{name}"+++def claims_url(pool: str, name: str | None = None) -> str:+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"+ return f"{base}/{name}" if name else base+++# ── Console helpers ───────────────────────────────────────────────────────+++def step(msg: str) -> None:+ print(f"\n==> {msg}", flush=True)+++def info(msg: str) -> None:+ print(f" {msg}", flush=True)+++def die(msg: str) -> None:+ sys.exit(f"\nERROR: {msg}")+++# ── Lifecycle steps (identical to provision_windows_and_list_mcp_tools.py) ──+++def create_namespace(http: httpx.Client, name: str) -> None:+ """Create the per-user namespace via the Capsule-backed SPA endpoint.++ Pool name == namespace name (1:1). A 409 just means we are reusing a+ namespace from an earlier run.+ """+ r = http.post("/api/namespaces", json={"name": name})+ if r.status_code == 409:+ info(f"namespace {name!r} already exists — reusing it")+ return+ if r.status_code == 403:+ die(+ "403 creating namespace — is this a per-pool key? Namespaces/pools/"+ "claims need a per-USER key (client id starting with 'ukey-', from "+ "POST /api/user-keys)."+ )+ r.raise_for_status()+ info(f"namespace {name!r} created")+++def create_pool(+ http: httpx.Client,+ *,+ pool: str,+ image: str,+ cpu: int,+ ram: str,+ replicas: int,+ firmware: str,+ service_name: str,+ port: int,+ readiness_port: int,+) -> None:+ """Create the OSGymWorkspacePool. Mirrors cyclops-cs api.createPool exactly."""+ template: dict = {+ "containerDiskImage": image,+ "imagePullSecret": "ecr-credentials",+ "cpuCores": cpu,+ "memory": ram,+ }+ # Windows needs efi: the VM builder then auto-applies the Hyper-V+ # enlightenments + Windows-tuned clocks (vm_builders.vm_body, firmware=="efi").+ if firmware != "bios":+ template["firmware"] = firmware+ # Gate "Ready" (and claim binding) on the computer-server port being bound —+ # without a probe the VM is advertised ready before the guest finishes+ # booting (CUA-535). readiness_port == 0 disables the probe.+ if readiness_port:+ template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}++ body = {+ "apiVersion": f"{POOL_GROUP}/{POOL_VERSION}",+ "kind": "OSGymWorkspacePool",+ "metadata": {"name": pool, "labels": {"cua.ai/pool": pool}},+ "spec": {+ "replicas": replicas,+ "template": template,+ "services": [+ {"name": service_name, "targetPort": port, "protocol": "TCP"}+ ],+ },+ }++ r = http.post(pool_url(pool), json=body)+ if r.status_code == 409:+ info(f"pool {pool!r} already exists — reusing it (services/replicas unchanged)")+ return+ if r.status_code == 403:+ die(+ "403 creating pool — per-pool keys cannot reach /api/k8s. Use a "+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."+ )+ r.raise_for_status()+ info(f"pool {pool!r} created")+ info(f"image: {image}")+ info(f"size: {cpu} vCPU / {ram} / replicas={replicas} / firmware={firmware}")+ info(f"service: {service_name} -> targetPort {port} (reachable on Service port 80)")+ info(f"readiness: {'tcpSocket :' + str(readiness_port) if readiness_port else 'launcher-up (no probe)'}")+++def wait_template(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:+ """Wait for the compat shim to project the pool into <pool>-template.++ Best-effort: if it never appears we still try the claim. Re-fetches the+ ``http`` accessor each poll so the bearer token is re-minted near expiry.+ """+ tmpl = f"{pool}-template"+ deadline = time.monotonic() + timeout+ while True:+ r = get_http().get(template_url(pool, tmpl))+ if r.status_code == 200:+ info(f"pool-operator projected template {tmpl!r} + warm pool {pool!r}")+ return+ if r.status_code not in (404, 403):+ r.raise_for_status()+ if time.monotonic() > deadline:+ info(f"template {tmpl!r} not visible after {timeout:.0f}s — claiming anyway")+ return+ info(f"waiting for pool-operator to project template {tmpl!r} …")+ time.sleep(poll)+++def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int, str]:+ """(totalCount, availableCount, phase) from the pool status, best-effort."""+ try:+ r = get_http().get(pool_url(pool, pool))+ r.raise_for_status()+ st = r.json().get("status") or {}+ return (+ int(st.get("totalCount", 0)),+ int(st.get("availableCount", 0)),+ st.get("phase", "Unknown"),+ )+ except Exception:+ return (0, 0, "Unknown")+++def wait_pool_warm(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:+ """Wait until the pool reports an available (warm, Ready) VM before claiming.++ A brand-new Windows pool's cold start (UEFI image pull + Windows Server boot+ + the computer-server scheduled task) is *minutes* and routinely exceeds the+ operator's 300s claim bind deadline. Letting availableCount>=1 first means+ the subsequent claim binds in seconds. Re-fetches the ``http`` accessor each+ poll to keep the bearer token fresh over a long pull.+ """+ start = time.monotonic()+ deadline = start + timeout+ while True:+ total, avail, phase = pool_counts(get_http, pool)+ if avail >= 1:+ info(f"pool warm: {avail}/{total} VM(s) ready (phase {phase})")+ return+ if time.monotonic() > deadline:+ die(f"timed out after {timeout:.0f}s waiting for a warm VM "+ f"(pool {phase}, {avail}/{total} ready).\n"+ f" Most common cause: the --image tag does not exist in the registry, "+ f"so the VM sits in ImagePullBackOff and never boots. List real tags with:\n"+ f" aws ecr describe-images --repository-name cua-server-windows --region us-west-2\n"+ f" Less commonly the cold Windows boot just needs longer — raise --warm-timeout.")+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] pool={phase} ({avail}/{total} VMs ready) — warming "+ f"(image pull + Windows boot + computer-server on the readiness port) …")+ time.sleep(poll)+++def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int = 0) -> None:+ spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}+ if bind_deadline:+ spec["bindDeadline"] = bind_deadline+ r = http.post(+ claims_url(pool),+ json={+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",+ "kind": "OSGymSandboxClaim",+ "metadata": {"name": name},+ "spec": spec,+ },+ )+ if r.status_code == 403:+ die(+ "403 creating claim — per-pool keys have no K8s identity. Use a "+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."+ )+ r.raise_for_status()+ info(f"claim {name!r} created")+++def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:+ """Poll the claim until status.phase == Bound; return the sandbox name."""+ start = time.monotonic()+ deadline = start + timeout+ while True:+ r = get_http().get(claims_url(pool, name))+ r.raise_for_status()+ status = r.json().get("status") or {}+ phase = status.get("phase", "Pending")+ sandbox = (status.get("sandbox") or {}).get("name")+ if phase == "Bound" and sandbox:+ return sandbox+ if phase == "Failed":+ die(f"claim {name} failed: {status}")+ if time.monotonic() > deadline:+ die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")+ total, avail, pphase = pool_counts(get_http, pool)+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] claim={phase} pool={pphase} ({avail}/{total} VMs ready) …")+ time.sleep(poll)+++def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:+ """GET url until the in-guest service answers (not a proxy 502/503/504).++ For computer-server that endpoint is ``/status``.+ """+ start = time.monotonic()+ deadline = start + timeout+ while True:+ try:+ resp = get_http().get(url, timeout=15.0)+ except httpx.HTTPError as e:+ resp = None+ reason = type(e).__name__+ else:+ reason = f"HTTP {resp.status_code}"+ if resp is not None and resp.status_code not in (502, 503, 504):+ info(f"service responding ({reason})")+ return+ if time.monotonic() > deadline:+ die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] {reason} — guest still booting …")+ time.sleep(poll)+++def teardown(get_http: Callable[[], httpx.Client], pool: str, claim_name: str) -> None:+ """Best-effort full cleanup: delete the claim, the pool, then the namespace.++ Idempotent — a 404 just means something was already gone.+ """+ for what, url in (+ (f"claim {claim_name!r}", claims_url(pool, claim_name)),+ (f"pool {pool!r}", pool_url(pool, pool)),+ (f"namespace {pool!r}", f"/api/namespaces/{pool}"),+ ):+ try:+ r = get_http().delete(url)+ info(f"deleted {what} (HTTP {r.status_code})")+ except httpx.HTTPError as e:+ info(f"could not delete {what}: {type(e).__name__}: {e}")+++def bearer(client: TrainClient) -> str:+ """Mint/refresh and return the current bearer token value."""+ client.get_httpx_client() # forces TrainClient._refresh_token()+ return f"Bearer {client.token}"+++# ── Drive the box with the cua-computer SDK (directly through the proxy) ─────+++async def drive_with_sdk(api_base_url: str, auth: str, sandbox: str) -> None:+ """Connect the cua-computer SDK straight at the cyclops-cs proxy and do a few+ things — no forwarder (uses api_base_url + api_headers from cua#1932)."""+ # Imported lazily so --help and arg errors don't pay the cua-computer import.+ from computer import Computer++ step(f"Connecting the cua-computer SDK directly to {api_base_url}")+ computer = Computer(+ use_host_computer_server=True, # connect to an existing server, do not spawn a VM+ os_type="windows",+ api_base_url=api_base_url,+ api_headers={"Authorization": auth},+ )+ async with computer: # __aenter__ -> run() -> wait_for_ready (REST 'version' then get_screen_size)+ size = await computer.interface.get_screen_size()+ info(f"screen size: {size['width']}x{size['height']}")++ png = await computer.interface.screenshot()+ out = f"{sandbox}-screenshot.png"+ with open(out, "wb") as f:+ f.write(png)+ info(f"screenshot: wrote {len(png)} bytes to {out}")++ res = await computer.interface.run_command("echo hello-from-cua")+ info(f"run_command rc={res.returncode} stdout={res.stdout.strip()!r}")++ info("SDK actions complete")+++async def print_connection(api_base_url: str, auth: str) -> None:+ """Print connection details and hold the sandbox open until Ctrl-C."""+ step("Sandbox is live — point any cua-computer client straight at the proxy")+ info(f"api_base_url: {api_base_url}")+ info("paste into your own script / agent (the bearer below is short-lived):")+ print(+ "\n"+ " from computer import Computer\n"+ " computer = Computer(\n"+ " use_host_computer_server=True,\n"+ ' os_type="windows",\n'+ f' api_base_url="{api_base_url}",\n'+ f' api_headers={{"Authorization": "{auth}"}},\n'+ " )\n"+ " async with computer:\n"+ " await computer.interface.screenshot()\n",+ flush=True,+ )+ info("Ctrl-C to stop and tear everything down.")+ await asyncio.Event().wait() # block; KeyboardInterrupt propagates to main's finally+++# ── Main ──────────────────────────────────────────────────────────────────+++async def amain() -> None:+ p = argparse.ArgumentParser(+ description="Provision a Windows computer-server pool on run.cua.ai, claim a sandbox, "+ "drive it with the cua-computer SDK (directly through the proxy), then tear it down.",+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,+ )+ p.add_argument("--name", required=True, help="pool name (also the namespace; lowercase/dashes)")+ p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),+ help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")+ p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),+ help="OAuth client secret; env CUA_CLIENT_SECRET")+ p.add_argument("--image", default=DEFAULT_IMAGE, help="Windows workspace containerDisk image")+ p.add_argument("--port", type=int, default=8000, help="computer-server port on the VM")+ p.add_argument("--service-name", default="api", help="name for the per-sandbox Service")+ p.add_argument("--replicas", type=int, default=1, help="pre-warmed VMs the pool keeps")+ p.add_argument("--cpu", type=int, default=4, help="vCPU cores per VM")+ p.add_argument("--ram", default="8Gi", help="memory per VM (K8s quantity; Windows wants >=8Gi)")+ p.add_argument("--firmware", choices=["bios", "efi"], default="efi",+ help="VM firmware (efi for the GPT/UEFI-only Windows image)")+ p.add_argument("--readiness-port", type=int, default=None,+ help="TCP readiness port (default: --port; 0 disables the probe)")+ p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),+ help="OIDC token endpoint")+ p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),+ help="cyclops-cs base URL")+ p.add_argument("--claim-name", help="claim name (default: claim-<random>)")+ p.add_argument("--template-timeout", type=float, default=120,+ help="seconds to wait for the pool->template projection")+ p.add_argument("--warm-timeout", type=float, default=1200,+ help="seconds to wait for the pool's first warm VM before claiming "+ "(covers the cold image pull + slow Windows boot)")+ p.add_argument("--bind-deadline", type=int, default=600,+ help="claim spec.bindDeadline (0 uses the operator default of 300s)")+ p.add_argument("--bind-timeout", type=float, default=300,+ help="seconds the script waits for the claim to bind (fast once warm)")+ p.add_argument("--ready-timeout", type=float, default=420,+ help="seconds to wait for the in-guest service after binding")+ p.add_argument("--poll-interval", type=float, default=5,+ help="seconds between status polls")+ p.add_argument("--print-connection", action="store_true",+ help="instead of driving the SDK, print the api_base_url + a fresh bearer "+ "+ a Computer(...) snippet and hold the sandbox open (Ctrl-C to tear down)")+ p.add_argument("--keep", action="store_true",+ help="skip teardown — leave the pool, namespace, and claim up for debugging")+ args = p.parse_args()++ if not args.client_id or not args.client_secret:+ die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "+ "(per-user key from POST /api/user-keys)")+ if args.client_id.startswith("key-"):+ die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "+ "Creating namespaces/pools/claims needs a per-USER key ('ukey-…', "+ "from POST /api/user-keys).")++ readiness_port = args.port if args.readiness_port is None else args.readiness_port+ pool = args.name+ claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"++ step(f"Authenticating to {args.base_url} (client {args.client_id})")+ client = TrainClient.from_key(+ token_url=args.token_url,+ client_id=args.client_id,+ client_secret=args.client_secret,+ base_url=args.base_url,+ )+ http = client.get_httpx_client # callable: re-mints the bearer near expiry+ info("token acquired")++ step(f"Creating namespace {pool!r}")+ create_namespace(http(), pool)++ step(f"Creating pool {pool!r}")+ create_pool(+ http(),+ pool=pool,+ image=args.image,+ cpu=args.cpu,+ ram=args.ram,+ replicas=args.replicas,+ firmware=args.firmware,+ service_name=args.service_name,+ port=args.port,+ readiness_port=readiness_port,+ )++ step("Waiting for the pool-operator to project the template + warm pool")+ wait_template(http, pool, args.template_timeout, args.poll_interval)++ step("Waiting for the pool's first VM to warm up (so the claim binds fast)")+ info("(cold start = containerDisk image pull + Windows boot + computer-server on the readiness port)")+ wait_pool_warm(http, pool, args.warm_timeout, args.poll_interval)++ step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")+ create_claim(http(), pool, claim_name, args.bind_deadline)++ try:+ step("Waiting for the claim to bind to the warm sandbox")+ sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)+ info(f"bound to sandbox {sandbox!r}")++ # Per-sandbox Service is "<sandbox>-<service>" on port 80 -> targetPort.+ svc_path = f"/api/svc/{pool}/{sandbox}-{args.service_name}"++ step("Waiting for the in-guest computer-server to answer")+ wait_service_ready(http, f"{svc_path}/status", args.ready_timeout, args.poll_interval)++ # Full https URL of the proxied computer-server + a fresh short-lived bearer.+ api_base_url = f"{args.base_url}{svc_path}"+ auth = bearer(client)++ if args.print_connection:+ await print_connection(api_base_url, auth)+ else:+ await drive_with_sdk(api_base_url, auth, sandbox)+ except KeyboardInterrupt:+ info("interrupted — tearing down")+ finally:+ print(flush=True)+ if args.keep:+ step(f"Keeping infra ({pool!r}) — skipping teardown (--keep)")+ info(f"claim: {claims_url(pool, claim_name)}")+ info(f"pool: {pool_url(pool, pool)}")+ info(f"namespace: /api/namespaces/{pool}")+ else:+ step(f"Tearing down {pool!r} (claim + pool + namespace)")+ teardown(http, pool, claim_name)+ info("done — nothing left billing")+++def main() -> None:+ try:+ asyncio.run(amain())+ except KeyboardInterrupt:+ pass+++if __name__ == "__main__":+ main()diff --git a/libs/fleet/python-sdk/examples/provision_windows_and_list_mcp_tools.py b/libs/fleet/python-sdk/examples/provision_windows_and_list_mcp_tools.pynew file mode 100644index 0000000000..4d1c44fdf1--- /dev/null+++ b/libs/fleet/python-sdk/examples/provision_windows_and_list_mcp_tools.py@@ -0,0 +1,590 @@+#!/usr/bin/env -S uv run --script+# /// script+# requires-python = ">=3.10"+# dependencies = [+# "cua-train",+# "httpx",+# ]+#+# [tool.uv]+# extra-index-url = ["https://wheels.cua.ai/simple/"]+# ///+"""Provision a **Windows computer-server** pool on cyclops-cs / run.cua.ai, claim+a sandbox from it, list the MCP tools it exposes — then tear the whole thing back+down. End to end, from nothing but a client id/secret.++This is the MCP companion to ``provision_windows_and_drive_with_cua_sdk.py``+(which claims the same kind of sandbox but drives it with the ``cua-computer``+SDK instead). Both target the Windows ``cua-server-windows`` image, which runs+``python -m computer_server`` on :8000 and exposes, on that one port:++ * the HTTP/WebSocket computer-use API (``/cmd``, ``/ws``, ``/status``)+ * an MCP server over Streamable HTTP at ``/mcp``++Here we only do the MCP side: the Streamable-HTTP handshake+(``initialize`` → ``notifications/initialized`` → ``tools/list``) and print the+advertised tools.++Lifecycle (every step is narrated so you can follow along in the console):++ 1. exchange the client_credentials for a bearer token (``TrainClient.from_key``)+ 2. create the per-user namespace (``POST /api/namespaces`` — same path the SPA+ uses, so Capsule sets up tenant ownership + RBAC; pool name == namespace)+ 3. create an ``OSGymWorkspacePool`` (``cua.ai/v1``) via the ``/api/k8s``+ kubectl-proxy — the Windows image, **efi firmware**, and a service on :8000.+ The pool-operator's compat shim projects it into an ``OSGymSandboxTemplate``+ + ``OSGymSandboxWarmPool`` pair and warms the VM.+ 4. claim a sandbox (``OSGymSandboxClaim``) and wait for it to bind+ 5. reach the bound sandbox through ``/api/svc/{ns}/{sandbox}-{service}/`` and+ run the computer-server MCP handshake (initialize -> tools/list)+ 6. **tear it all down** — delete the claim, the pool, and the namespace. This+ is a throwaway test scenario, so nothing is left billing. Pass ``--keep``+ to leave the pool up for poking at.++Auth — use a per-USER key (``ukey-...``), NOT a per-pool key:+``/api/k8s`` impersonates the token's owner so Capsule tenant RBAC applies.+Per-user keys (POST /api/user-keys) can create namespaces, pools, and claims;+per-pool keys (POST /api/keys, ``key-...``) have no K8s identity and are rejected.++Heads up: Windows is **slow to first-boot** (UEFI image pull + Windows Server+boot + computer-server scheduled task coming up). The defaults wait generously;+raise ``--warm-timeout`` if your pull is cold.++Setup (zero-install with uv)::++ export CUA_CLIENT_ID=ukey-xxxxxxxx # from POST /api/user-keys+ export CUA_CLIENT_SECRET=...+ uv run provision_windows_and_list_mcp_tools.py --name win-mcp-demo++If your uv is too old to read the inline extra-index-url, run it the explicit+way::++ uv run --with cua-train --with httpx \+ --extra-index-url https://wheels.cua.ai/simple/ \+ provision_windows_and_list_mcp_tools.py --name win-mcp-demo++Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+import time+import uuid+from collections.abc import Callable++import httpx++from cua_train import TrainClient++DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"+DEFAULT_BASE_URL = "https://run.cua.ai"+# The Windows computer-server image: Windows Server 2022 + cua-computer-server on+# :8000 (HTTP/WS API at /cmd//ws, MCP at /mcp). It is a dockur-built GPT/UEFI+# image, so the pool MUST boot it with efi firmware (see --firmware below).+DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest"++# OSGymWorkspacePool — the legacy single-object pool CR the cyclops-cs SPA+# creates (cua.ai/v1). The pool-operator compat shim translates it into the+# native OSGymSandboxTemplate + OSGymSandboxWarmPool pair.+POOL_GROUP = "cua.ai"+POOL_VERSION = "v1"+POOL_PLURAL = "osgymworkspacepools"++# OSGymSandboxTemplate / OSGymSandboxClaim live in the osgym.cua.ai group.+EXT_GROUP = "osgym.cua.ai"+EXT_VERSION = "v1alpha1"+TEMPLATE_PLURAL = "osgymsandboxtemplates"+CLAIM_PLURAL = "osgymsandboxclaims"+++# ── URL builders (relative to base_url, e.g. https://run.cua.ai) ──────────+++def pool_url(pool: str, name: str | None = None) -> str:+ base = f"/api/k8s/apis/{POOL_GROUP}/{POOL_VERSION}/namespaces/{pool}/{POOL_PLURAL}"+ return f"{base}/{name}" if name else base+++def template_url(pool: str, name: str) -> str:+ return f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}/{name}"+++def claims_url(pool: str, name: str | None = None) -> str:+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"+ return f"{base}/{name}" if name else base+++# ── Console helpers ───────────────────────────────────────────────────────+++def step(msg: str) -> None:+ print(f"\n==> {msg}", flush=True)+++def info(msg: str) -> None:+ print(f" {msg}", flush=True)+++def die(msg: str) -> None:+ sys.exit(f"\nERROR: {msg}")+++# ── Lifecycle steps ───────────────────────────────────────────────────────+++def create_namespace(http: httpx.Client, name: str) -> None:+ """Create the per-user namespace via the Capsule-backed SPA endpoint.++ Pool name == namespace name (1:1). Going through /api/namespaces (rather+ than a raw /api/k8s namespace create) is what makes Capsule stamp tenant+ ownership + RBAC, so the impersonated pool create below is allowed. A 409+ just means we are reusing a namespace from an earlier run.+ """+ r = http.post("/api/namespaces", json={"name": name})+ if r.status_code == 409:+ info(f"namespace {name!r} already exists — reusing it")+ return+ if r.status_code == 403:+ die(+ "403 creating namespace — is this a per-pool key? Namespaces/pools/"+ "claims need a per-USER key (client id starting with 'ukey-', from "+ "POST /api/user-keys)."+ )+ r.raise_for_status()+ info(f"namespace {name!r} created")+++def create_pool(+ http: httpx.Client,+ *,+ pool: str,+ image: str,+ cpu: int,+ ram: str,+ replicas: int,+ firmware: str,+ service_name: str,+ port: int,+ readiness_port: int,+) -> None:+ """Create the OSGymWorkspacePool. Mirrors cyclops-cs api.createPool exactly."""+ template: dict = {+ "containerDiskImage": image,+ "imagePullSecret": "ecr-credentials",+ "cpuCores": cpu,+ "memory": ram,+ }+ # The SPA only sends firmware when it differs from KubeVirt's bios default.+ # Windows needs efi: the VM builder then auto-applies the Hyper-V+ # enlightenments + Windows-tuned clocks (vm_builders.vm_body, firmware=="efi").+ if firmware != "bios":+ template["firmware"] = firmware+ # Gate "Ready" (and therefore claim binding) on the computer-server port+ # being bound. Without a probe the VM is advertised ready ~30s before the+ # guest finishes booting (CUA-535) — doubly important for slow Windows boots.+ # readiness_port == 0 disables the probe (KubeVirt's launcher-up default).+ if readiness_port:+ template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}++ body = {+ "apiVersion": f"{POOL_GROUP}/{POOL_VERSION}",+ "kind": "OSGymWorkspacePool",+ "metadata": {"name": pool, "labels": {"cua.ai/pool": pool}},+ "spec": {+ "replicas": replicas,+ "template": template,+ # Each entry becomes a per-sandbox K8s Service "<sandbox>-<name>"+ # mapping port 80 -> targetPort on the VM.+ "services": [+ {"name": service_name, "targetPort": port, "protocol": "TCP"}+ ],+ },+ }++ r = http.post(pool_url(pool), json=body)+ if r.status_code == 409:+ info(f"pool {pool!r} already exists — reusing it (services/replicas unchanged)")+ return+ if r.status_code == 403:+ die(+ "403 creating pool — per-pool keys cannot reach /api/k8s. Use a "+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."+ )+ r.raise_for_status()+ info(f"pool {pool!r} created")+ info(f"image: {image}")+ info(f"size: {cpu} vCPU / {ram} / replicas={replicas} / firmware={firmware}")+ info(f"service: {service_name} -> targetPort {port} (reachable on Service port 80)")+ info(f"readiness: {'tcpSocket :' + str(readiness_port) if readiness_port else 'launcher-up (no probe)'}")+++def wait_template(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:+ """Wait for the compat shim to project the pool into <pool>-template.++ The claim below references the template by name; waiting for it to exist+ keeps the claim from sitting Pending purely because the projection hasn't+ happened yet. Best-effort: if it never appears we still try the claim.++ Takes the ``http`` accessor (not a client) and re-fetches it each poll so+ the bearer token is re-minted as it nears expiry.+ """+ tmpl = f"{pool}-template"+ deadline = time.monotonic() + timeout+ while True:+ r = get_http().get(template_url(pool, tmpl))+ if r.status_code == 200:+ info(f"pool-operator projected template {tmpl!r} + warm pool {pool!r}")+ return+ if r.status_code not in (404, 403):+ r.raise_for_status()+ if time.monotonic() > deadline:+ info(f"template {tmpl!r} not visible after {timeout:.0f}s — claiming anyway")+ return+ info(f"waiting for pool-operator to project template {tmpl!r} …")+ time.sleep(poll)+++def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int, str]:+ """(totalCount, availableCount, phase) from the pool status, best-effort."""+ try:+ r = get_http().get(pool_url(pool, pool))+ r.raise_for_status()+ st = r.json().get("status") or {}+ return (+ int(st.get("totalCount", 0)),+ int(st.get("availableCount", 0)),+ st.get("phase", "Unknown"),+ )+ except Exception:+ return (0, 0, "Unknown")+++def wait_pool_warm(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:+ """Wait until the pool reports an available (warm, Ready) VM.++ This is the key to a reliable first claim: a brand-new pool has to pull the+ (multi-GB) containerDisk image, boot the guest, and bring the in-guest+ service up on the readiness port before a Sandbox becomes adoptable. For the+ Windows image that cold start is *minutes* (UEFI image pull + Windows Server+ boot + the computer-server scheduled task), and routinely exceeds the+ operator's 300s *claim* bind deadline (claim_handlers.BIND_DEADLINE_DEFAULT_S).+ If we claim first, the deadline burns down during the image pull and the+ claim Fails with ``BindDeadlineExceeded`` — exactly the failure mode this+ avoids.++ So we let the warm pool reach availableCount>=1 (phase "Ready") *before*+ claiming; the subsequent claim then binds in seconds. Re-fetches the+ ``http`` accessor each poll to keep the bearer token fresh over a long pull.+ """+ start = time.monotonic()+ deadline = start + timeout+ while True:+ total, avail, phase = pool_counts(get_http, pool)+ if avail >= 1:+ info(f"pool warm: {avail}/{total} VM(s) ready (phase {phase})")+ return+ if time.monotonic() > deadline:+ die(f"timed out after {timeout:.0f}s waiting for a warm VM "+ f"(pool {phase}, {avail}/{total} ready).\n"+ f" Most common cause: the --image tag does not exist in the registry, "+ f"so the VM sits in ImagePullBackOff and never boots. List real tags with:\n"+ f" aws ecr describe-images --repository-name cua-server-windows --region us-west-2\n"+ f" Less commonly the cold Windows boot just needs longer — raise --warm-timeout.")+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] pool={phase} ({avail}/{total} VMs ready) — warming "+ f"(image pull + Windows boot + computer-server on the readiness port) …")+ time.sleep(poll)+++def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int = 0) -> None:+ spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}+ # The pool-operator fails an unbound claim after spec.bindDeadline seconds+ # (default 300, claim_handlers.BIND_DEADLINE_DEFAULT_S). We claim only after+ # the pool is already warm, so binding is near-instant — but a non-zero+ # deadline is a safety margin in case the warm VM is mid hard-reset.+ if bind_deadline:+ spec["bindDeadline"] = bind_deadline+ r = http.post(+ claims_url(pool),+ json={+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",+ "kind": "OSGymSandboxClaim",+ "metadata": {"name": name},+ "spec": spec,+ },+ )+ if r.status_code == 403:+ die(+ "403 creating claim — per-pool keys have no K8s identity. Use a "+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."+ )+ r.raise_for_status()+ info(f"claim {name!r} created")+++def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:+ """Poll the claim until status.phase == Bound; return the sandbox name.++ While we wait we also surface the pool's warm-VM counts, so a cold start is+ visible rather than a silent hang. Re-fetches the ``http`` accessor each poll+ so the bearer token stays fresh across a long (cold-boot) wait.+ """+ start = time.monotonic()+ deadline = start + timeout+ while True:+ r = get_http().get(claims_url(pool, name))+ r.raise_for_status()+ status = r.json().get("status") or {}+ phase = status.get("phase", "Pending")+ sandbox = (status.get("sandbox") or {}).get("name")+ if phase == "Bound" and sandbox:+ return sandbox+ if phase == "Failed":+ die(f"claim {name} failed: {status}")+ if time.monotonic() > deadline:+ die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")+ total, avail, pphase = pool_counts(get_http, pool)+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] claim={phase} pool={pphase} ({avail}/{total} VMs ready) …")+ time.sleep(poll)+++def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:+ """GET url until the in-guest service answers (not a proxy 502/503/504).++ Backstop for the slim window where the sandbox is Bound but the in-guest+ HTTP server hasn't finished accepting connections yet. For computer-server+ that endpoint is ``/status``. Re-fetches the ``http`` accessor each poll to+ keep the bearer token fresh.+ """+ start = time.monotonic()+ deadline = start + timeout+ while True:+ try:+ resp = get_http().get(url, timeout=15.0)+ except httpx.HTTPError as e:+ resp = None+ reason = type(e).__name__+ else:+ reason = f"HTTP {resp.status_code}"+ if resp is not None and resp.status_code not in (502, 503, 504):+ info(f"service responding ({reason})")+ return+ if time.monotonic() > deadline:+ die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] {reason} — guest still booting …")+ time.sleep(poll)+++def list_mcp_tools(http: httpx.Client, base: str, mcp_path: str) -> None:+ """computer-server MCP handshake over Streamable HTTP:+ initialize -> notifications/initialized -> tools/list, then print the tools."""+ url = f"{base}/{mcp_path.lstrip('/')}"+ headers = {+ "Content-Type": "application/json",+ # Streamable HTTP requires advertising both content types.+ "Accept": "application/json, text/event-stream",+ }++ r = http.post(+ url,+ headers=headers,+ timeout=30.0,+ json={+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": "2025-03-26",+ "capabilities": {},+ "clientInfo": {"name": "provision_windows_and_list_mcp_tools", "version": "0.1.0"},+ },+ },+ )+ r.raise_for_status()+ session = r.headers.get("mcp-session-id")+ info(f"MCP initialize: HTTP {r.status_code}" + (f", session {session}" if session else ""))+ if session:+ headers["Mcp-Session-Id"] = session++ # Notify the server we're ready (no response expected).+ http.post(+ url,+ headers=headers,+ timeout=30.0,+ json={"jsonrpc": "2.0", "method": "notifications/initialized"},+ )++ r = http.post(+ url,+ headers=headers,+ timeout=30.0,+ json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"},+ )+ r.raise_for_status()+ # Streamable HTTP returns SSE ("event: message\ndata: {...}"); the JSON+ # payload is on the data: line. Fall back to the raw body for plain JSON.+ data = next((ln[6:] for ln in r.text.splitlines() if ln.startswith("data: ")), r.text)+ tools = json.loads(data).get("result", {}).get("tools", [])++ print(f"\nMCP tools ({len(tools)}):", flush=True)+ for i, t in enumerate(sorted(tools, key=lambda t: t.get("name", "")), 1):+ name = t.get("name", "?")+ desc = " ".join((t.get("description") or "").split())+ if len(desc) > 70:+ desc = desc[:67] + "…"+ print(f" {i:3d}. {name:<24} {desc}", flush=True)+ if not tools:+ print(" (the server returned an empty tool list)", flush=True)+++def teardown(get_http: Callable[[], httpx.Client], pool: str, claim_name: str) -> None:+ """Best-effort full cleanup: delete the claim, the pool, then the namespace.++ Idempotent — a 404 just means something was already gone. This is a test+ scenario, so we remove everything we created and leave nothing billing.+ """+ for what, url in (+ (f"claim {claim_name!r}", claims_url(pool, claim_name)),+ (f"pool {pool!r}", pool_url(pool, pool)),+ (f"namespace {pool!r}", f"/api/namespaces/{pool}"),+ ):+ try:+ r = get_http().delete(url)+ info(f"deleted {what} (HTTP {r.status_code})")+ except httpx.HTTPError as e:+ info(f"could not delete {what}: {type(e).__name__}: {e}")+++# ── Main ──────────────────────────────────────────────────────────────────+++def main() -> None:+ p = argparse.ArgumentParser(+ description="Provision a Windows computer-server pool on run.cua.ai, claim a sandbox, "+ "list its MCP tools, then tear it all down.",+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,+ )+ p.add_argument("--name", required=True, help="pool name (also the namespace; lowercase/dashes)")+ p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),+ help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")+ p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),+ help="OAuth client secret; env CUA_CLIENT_SECRET")+ p.add_argument("--image", default=DEFAULT_IMAGE, help="Windows workspace containerDisk image")+ p.add_argument("--port", type=int, default=8000, help="computer-server port on the VM")+ p.add_argument("--service-name", default="api", help="name for the per-sandbox Service")+ p.add_argument("--mcp-path", default="/mcp", help="path the MCP server is mounted at")+ p.add_argument("--replicas", type=int, default=1, help="pre-warmed VMs the pool keeps")+ p.add_argument("--cpu", type=int, default=4, help="vCPU cores per VM")+ p.add_argument("--ram", default="8Gi", help="memory per VM (K8s quantity; Windows wants >=8Gi)")+ p.add_argument("--firmware", choices=["bios", "efi"], default="efi",+ help="VM firmware (efi for the GPT/UEFI-only Windows image)")+ p.add_argument("--readiness-port", type=int, default=None,+ help="TCP readiness port (default: --port; 0 disables the probe)")+ p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),+ help="OIDC token endpoint")+ p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),+ help="cyclops-cs base URL")+ p.add_argument("--claim-name", help="claim name (default: claim-<random>)")+ p.add_argument("--template-timeout", type=float, default=120,+ help="seconds to wait for the pool->template projection")+ p.add_argument("--warm-timeout", type=float, default=1200,+ help="seconds to wait for the pool's first warm VM before claiming "+ "(covers the cold image pull + slow Windows boot)")+ p.add_argument("--bind-deadline", type=int, default=600,+ help="claim spec.bindDeadline (operator fails an unbound claim after "+ "this; 0 uses the operator default of 300s)")+ p.add_argument("--bind-timeout", type=float, default=300,+ help="seconds the script waits for the claim to bind (fast once warm)")+ p.add_argument("--ready-timeout", type=float, default=420,+ help="seconds to wait for the in-guest service after binding")+ p.add_argument("--poll-interval", type=float, default=5,+ help="seconds between status polls")+ p.add_argument("--keep", action="store_true",+ help="skip teardown — leave the pool, namespace, and claim up for debugging")+ args = p.parse_args()++ if not args.client_id or not args.client_secret:+ die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "+ "(per-user key from POST /api/user-keys)")+ if args.client_id.startswith("key-"):+ die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "+ "Creating namespaces/pools/claims needs a per-USER key ('ukey-…', "+ "from POST /api/user-keys).")++ readiness_port = args.port if args.readiness_port is None else args.readiness_port+ pool = args.name+ claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"++ step(f"Authenticating to {args.base_url} (client {args.client_id})")+ client = TrainClient.from_key(+ token_url=args.token_url,+ client_id=args.client_id,+ client_secret=args.client_secret,+ base_url=args.base_url,+ )+ # get_httpx_client() re-mints the bearer token near expiry, so fetch it+ # per request rather than holding one reference.+ http = client.get_httpx_client+ info("token acquired")++ step(f"Creating namespace {pool!r}")+ create_namespace(http(), pool)++ step(f"Creating pool {pool!r}")+ create_pool(+ http(),+ pool=pool,+ image=args.image,+ cpu=args.cpu,+ ram=args.ram,+ replicas=args.replicas,+ firmware=args.firmware,+ service_name=args.service_name,+ port=args.port,+ readiness_port=readiness_port,+ )++ step("Waiting for the pool-operator to project the template + warm pool")+ wait_template(http, pool, args.template_timeout, args.poll_interval)++ step("Waiting for the pool's first VM to warm up (so the claim binds fast)")+ info("(cold start = containerDisk image pull + Windows boot + computer-server on the readiness port)")+ wait_pool_warm(http, pool, args.warm_timeout, args.poll_interval)++ step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")+ create_claim(http(), pool, claim_name, args.bind_deadline)++ try:+ step("Waiting for the claim to bind to the warm sandbox")+ sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)+ info(f"bound to sandbox {sandbox!r}")++ # Per-sandbox Service is "<sandbox>-<service>" on port 80 -> targetPort.+ svc_base = f"/api/svc/{pool}/{sandbox}-{args.service_name}"++ step("Waiting for the in-guest computer-server to answer")+ wait_service_ready(http, f"{svc_base}/status", args.ready_timeout, args.poll_interval)++ step(f"Listing MCP tools at {svc_base}{args.mcp_path}")+ list_mcp_tools(http(), svc_base, args.mcp_path)+ finally:+ print(flush=True)+ if args.keep:+ step(f"Keeping infra ({pool!r}) — skipping teardown (--keep)")+ info(f"claim: {claims_url(pool, claim_name)}")+ info(f"pool: {pool_url(pool, pool)}")+ info(f"namespace: /api/namespaces/{pool}")+ else:+ step(f"Tearing down {pool!r} (claim + pool + namespace)")+ teardown(http, pool, claim_name)+ info("done — nothing left billing")+++if __name__ == "__main__":+ main()diff --git a/libs/fleet/python-sdk/examples/requirements.txt b/libs/fleet/python-sdk/examples/requirements.txtnew file mode 100644index 0000000000..d37fafb796--- /dev/null+++ b/libs/fleet/python-sdk/examples/requirements.txt@@ -0,0 +1,6 @@+# Extra deps for the examples (the SDK itself only needs httpx + attrs).+# pip install cua-train --extra-index-url https://wheels.cua.ai/simple/+# pip install -r requirements.txt+pillow+boto3+pyyamldiff --git a/libs/fleet/python-sdk/examples/sample_agent.py b/libs/fleet/python-sdk/examples/sample_agent.pynew file mode 100644index 0000000000..36f5845b0f--- /dev/null+++ b/libs/fleet/python-sdk/examples/sample_agent.py@@ -0,0 +1,1219 @@+#!/usr/bin/env -S uv run --script+# /// script+# requires-python = ">=3.10"+# dependencies = [+# "boto3",+# "cua-train",+# "httpx",+# "pyyaml",+# ]+#+# [tool.uv]+# extra-index-url = ["https://wheels.cua.ai/simple/"]+# ///+"""Run **mini-swe-agent over TWO MCP servers** on a **Windows** CUA sandbox.++Self-contained, single-file — run it straight with ``uv`` (no venv, no+``pip install``); the inline script metadata pulls ``cua-train`` from the wheels+index automatically.++the sandbox runs **two** MCP servers at once:++ * CUA **computer-server** — Service ``<sandbox>-server`` (VM :8000), MCP /mcp+ * **cua-driver** — Service ``<sandbox>-mcp`` (VM :3000), MCP /mcp++Lifecycle (every step narrated in the console):++ 1. exchange the client_credentials for a bearer token (``TrainClient.from_key``)+ 2. create the per-user namespace (``POST /api/namespaces`` — Capsule tenant+ RBAC; pool name == namespace)+ 3. create an ``OSGymWorkspacePool`` (``cua.ai/v1``) with **one Service per MCP+ server**. The pool-operator compat shim projects it into an+ ``OSGymSandboxTemplate`` (``<pool>-template``) + ``OSGymSandboxWarmPool`` pair.+ 4. wait for a warm VM, then claim a sandbox (``OSGymSandboxClaim``)+ 5. open one MCP session per server, run the agent, release the claim++Auth needs a per-USER key (``ukey-…``, from POST /api/user-keys); the LLM runs+on **AWS Bedrock** via a direct ``boto3`` ``bedrock-runtime`` Converse call. AWS+credentials come straight from the standard environment / default chain (env+vars, a shared profile, SSO, or an instance role) — there is no LiteLLM layer.+Set AWS_REGION (or pass ``--aws-region``); the model id is a Bedrock id such as+``us.anthropic.claude-sonnet-4-6`` (a leading ``bedrock/`` is stripped).++ export CUA_CLIENT_ID=ukey-xxxxxxxx+ export CUA_CLIENT_SECRET=...+ export AWS_REGION=us-east-1+ export AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... # or AWS_PROFILE / role+ uv run sample_agent.py --name windows-agent-demo \+ --model us.anthropic.claude-sonnet-4-6 \+ --task "Open Microsoft Edge and browse to https://news.yahoo.com/."++…or, if your uv is too old to read the inline extra-index-url::++ uv run --with cua-train --with httpx --with boto3 \+ --extra-index-url https://wheels.cua.ai/simple/ \+ sample_agent.py --name windows-agent-demo --task "…"++The sandbox claim is ALWAYS released on exit — success, error, or Ctrl-C. Pass+``--keep`` to leave the *pool/namespace* up (the claim is still released),+``--delete-pool`` to tear everything down.+Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL, AGENT_MODEL,+plus the standard AWS_* variables (AWS_REGION, AWS_ACCESS_KEY_ID, …) read by boto3.+"""++from __future__ import annotations++import argparse+import base64+import dataclasses+import json+import os+import re+import signal+import sys+import time+import uuid+from collections.abc import Callable++import boto3+import httpx+import yaml++from cua_train import TrainClient++DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"+DEFAULT_BASE_URL = "https://run.cua.ai"++# OSGymWorkspacePool — the legacy single-object pool CR the cyclops-cs SPA+# creates (cua.ai/v1). The pool-operator compat shim translates it into the+# native OSGymSandboxTemplate (<pool>-template) + OSGymSandboxWarmPool pair.+POOL_GROUP, POOL_VERSION, POOL_PLURAL = "cua.ai", "v1", "osgymworkspacepools"+# OSGymSandboxTemplate / OSGymSandboxClaim live in the osgym.cua.ai group.+EXT_GROUP, EXT_VERSION = "osgym.cua.ai", "v1alpha1"+TEMPLATE_PLURAL, CLAIM_PLURAL = "osgymsandboxtemplates", "osgymsandboxclaims"++SYSTEM = (+ "You operate a computer through the provided tools. You have access to "+ "MULTIPLE tool servers running inside the same machine — a CUA "+ "computer-server and a cua-driver — and their tool names are prefixed with "+ "the server they belong to (e.g. 'computer-server__screenshot', "+ "'cua-driver__click'). Pick whichever tool fits; they act on the same "+ "desktop. Inspect state (take a screenshot, read a file, run a command), "+ "then take ONE action at a time and observe the result before the next. "+ "When the task is fully complete, reply with a final message and no tool call."+)+++def default_run_manifest() -> dict:+ return {+ "apiVersion": "cua.ai/v1alpha1",+ "kind": "AgentWindowsDoubleMCPRun",+ "metadata": {"name": None},+ "spec": {+ "pool": {+ "image": DEFAULT_IMAGE,+ "cpu": DEFAULT_CPU,+ "ram": DEFAULT_RAM,+ "firmware": DEFAULT_FIRMWARE,+ "replicas": 1,+ "minAvailable": 1,+ "readinessPort": None,+ "services": [],+ },+ "claim": {+ "name": None,+ "bindDeadline": 600,+ },+ "agent": {+ "model": None,+ "task": None,+ "maxSteps": 40,+ "keepImages": 2,+ },+ "rollout": {+ "templateTimeout": 120,+ "warmTimeout": 0,+ "bindTimeout": 0,+ "readyTimeout": 0,+ "pollInterval": 5,+ },+ "teardown": {+ "keepPool": False,+ "deletePool": False,+ },+ },+ }+++def deep_merge(base: dict, override: dict) -> dict:+ merged = dict(base)+ for key, value in override.items():+ if isinstance(value, dict) and isinstance(base.get(key), dict):+ merged[key] = deep_merge(base[key], value)+ else:+ merged[key] = value+ return merged+++def load_run_manifest(path: str | None) -> dict:+ manifest = default_run_manifest()+ if not path:+ return manifest+ with open(path, "r", encoding="utf-8") as f:+ raw = yaml.safe_load(f) or {}+ if not isinstance(raw, dict):+ die(f"config {path!r} must be a YAML mapping/object")+ manifest = deep_merge(manifest, raw)+ kind = manifest.get("kind")+ if kind != "AgentWindowsDoubleMCPRun":+ die(f"config {path!r} must have kind: AgentWindowsDoubleMCPRun (got {kind!r})")+ return manifest+++def manifest_get(manifest: dict, *path: str, default=None):+ cur = manifest+ for part in path:+ if not isinstance(cur, dict):+ return default+ cur = cur.get(part)+ if cur is None:+ return default+ return cur+++def resolve_name_template(name: str | None) -> str | None:+ if not name:+ return name+ suffix = uuid.uuid4().hex[:6]+ if "{randhex6}" in name:+ return name.replace("{randhex6}", suffix)+ if name.endswith("-"):+ return f"{name}{suffix}"+ return name+++# Default LLM: Claude on AWS Bedrock (cross-region inference profile). Override+# with --model or AGENT_MODEL; whatever your AWS account/region has enabled.+DEFAULT_BEDROCK_MODEL = "us.anthropic.claude-sonnet-4-6"+MAX_OUTPUT_TOKENS = 4096+++def default_model() -> str:+ """Bedrock model id default (AGENT_MODEL overrides)."""+ return os.environ.get("AGENT_MODEL") or DEFAULT_BEDROCK_MODEL+++def env_first(name: str, *aliases: str) -> str | None:+ for key in (name, *aliases):+ value = os.environ.get(key)+ if value:+ return value+ return None+++def bedrock_model_id(model: str) -> str:+ """Strip an optional ``bedrock/`` prefix; the Converse API wants the bare id."""+ return model[len("bedrock/"):] if model.startswith("bedrock/") else model+++def make_bedrock_client(args: argparse.Namespace):+ """A boto3 bedrock-runtime client. Credentials and region come from the+ standard AWS environment / default chain (env vars, shared profile, SSO,+ instance role) — nothing LLM-specific to configure. --aws-region overrides+ the region; AWS_REGION/AWS_DEFAULT_REGION are honoured otherwise."""+ region = args.aws_region or env_first("AWS_REGION", "AWS_DEFAULT_REGION")+ client = boto3.client("bedrock-runtime", region_name=region) if region else boto3.client("bedrock-runtime")+ info(f"Bedrock client ready (region {client.meta.region_name})")+ return client+++# OS profile (Windows)++[email protected](frozen=True)+class McpServerSpec:+ """One MCP server exposed by the sandbox VM.++ ``label`` — short name; tool names are namespaced ``<label>__<tool>``.+ ``service`` — per-sandbox Service suffix: ``/api/svc/{ns}/{sandbox}-{service}``.+ ``port`` — targetPort on the VM the Service maps :80 -> .+ ``mcp_path`` — path the MCP server is mounted at (Streamable HTTP).+ ``health`` — a cheap GET that returns non-5xx once the guest service is up.+ """++ label: str+ service: str+ port: int+ mcp_path: str = "/mcp"+ health: str = "/healthz"++[email protected](frozen=True)+class ServiceSpec:+ """One non-MCP service exposed by the sandbox VM."""++ label: str+ service: str+ port: int+++OS_NAME = "windows"+DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest"+# KubeVirt VM firmware (OSGymWorkspacePool template field; CRD enum [bios, efi]).+# efi — GPT/UEFI-only guest images (the dockur-built Windows desktop-workspace);+# the operator also flips on Hyper-V enlightenments + clock config for it.+# bios — KubeVirt's default; what the Linux workspace images boot with.+# The SPA/operator only send firmware when it differs from bios, so we omit it for+# bios and let the operator default apply. Default here is efi (this script's+# Windows lineage); per-run configs set spec.pool.firmware for non-Windows images.+DEFAULT_FIRMWARE = "efi"+FIRMWARE_CHOICES = ("bios", "efi")+DEFAULT_RAM = "4Gi"+DEFAULT_CPU = 4+DEFAULT_WARM_TIMEOUT = 900 # cold image pull + Windows boot+++# URL builders (relative to base_url, e.g. https://run.cua.ai)+++def pool_url(pool: str, name: str | None = None) -> str:+ base = f"/api/k8s/apis/{POOL_GROUP}/{POOL_VERSION}/namespaces/{pool}/{POOL_PLURAL}"+ return f"{base}/{name}" if name else base+++def claims_url(pool: str, name: str | None = None) -> str:+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"+ return f"{base}/{name}" if name else base+++def load_pool_services(manifest: dict) -> tuple[tuple[McpServerSpec, ...], tuple[ServiceSpec, ...]]:+ raw_services = manifest_get(manifest, "spec", "pool", "services")+ if not isinstance(raw_services, list) or not raw_services:+ die("config must define spec.pool.services as a non-empty list")++ mcp_servers: list[McpServerSpec] = []+ extra_services: list[ServiceSpec] = []+ labels: set[str] = set()+ names: set[str] = set()++ for idx, raw in enumerate(raw_services):+ if not isinstance(raw, dict):+ die(f"spec.pool.services[{idx}] must be a YAML mapping/object")+ kind = raw.get("type")+ label = raw.get("label")+ service = raw.get("service")+ port = raw.get("port")+ if kind not in {"mcp", "auxiliary"}:+ die(f"spec.pool.services[{idx}].type must be 'mcp' or 'auxiliary'")+ if not isinstance(label, str) or not label:+ die(f"spec.pool.services[{idx}].label must be a non-empty string")+ if not isinstance(service, str) or not service:+ die(f"spec.pool.services[{idx}].service must be a non-empty string")+ if not isinstance(port, int) or port <= 0:+ die(f"spec.pool.services[{idx}].port must be a positive integer")+ if label in labels:+ die(f"duplicate spec.pool.services label: {label!r}")+ if service in names:+ die(f"duplicate spec.pool.services service: {service!r}")+ labels.add(label)+ names.add(service)+ if kind == "mcp":+ mcp_path = raw.get("mcpPath", "/mcp")+ health = raw.get("health", "/healthz")+ if not isinstance(mcp_path, str) or not mcp_path.startswith("/"):+ die(f"spec.pool.services[{idx}].mcpPath must be an absolute path string")+ if not isinstance(health, str) or not health.startswith("/"):+ die(f"spec.pool.services[{idx}].health must be an absolute path string")+ mcp_servers.append(+ McpServerSpec(label=label, service=service, port=port, mcp_path=mcp_path, health=health)+ )+ else:+ extra_services.append(ServiceSpec(label=label, service=service, port=port))++ if not mcp_servers:+ die("spec.pool.services must include at least one MCP service")+ return tuple(mcp_servers), tuple(extra_services)+++def pool_services(+ mcp_servers: tuple[McpServerSpec, ...],+ extra_services: tuple[ServiceSpec, ...],+) -> tuple[ServiceSpec, ...]:+ base = tuple(ServiceSpec(label=s.label, service=s.service, port=s.port) for s in mcp_servers)+ return base + extra_services+++# Status formatting helpers+++def _fmt_conditions(conditions: list[dict] | None) -> str:+ if not conditions:+ return "none"+ parts = []+ for cond in conditions:+ ctype = cond.get("type", "?")+ status = cond.get("status", "?")+ reason = cond.get("reason", "?")+ msg = " ".join(str(cond.get("message", "")).split())+ chunk = f"{ctype}={status}/{reason}"+ if msg:+ chunk += f" ({msg})"+ parts.append(chunk)+ return "; ".join(parts)+++def pool_status(http: httpx.Client, pool: str) -> dict:+ r = http.get(pool_url(pool, pool))+ r.raise_for_status()+ return r.json().get("status") or {}+++def claim_status(http: httpx.Client, pool: str, name: str) -> dict:+ r = http.get(claims_url(pool, name))+ r.raise_for_status()+ return r.json().get("status") or {}+++def claim_obj(http: httpx.Client, pool: str, name: str) -> dict:+ r = http.get(claims_url(pool, name))+ r.raise_for_status()+ return r.json()+++def pool_summary(status: dict) -> str:+ return (+ f"phase={status.get('phase', 'Unknown')} "+ f"ready={int(status.get('availableCount', 0))}/{int(status.get('totalCount', 0))} "+ f"claimed={int(status.get('claimedCount', 0))}"+ )+++def claim_summary(status: dict) -> str:+ sandbox = (status.get("sandbox") or {}).get("name")+ summary = f"phase={status.get('phase', 'Pending')}"+ if sandbox:+ summary += f" sandbox={sandbox}"+ conds = _fmt_conditions(status.get("conditions"))+ if conds != "none":+ summary += f" conditions=[{conds}]"+ return summary+++def claim_operator_progress(obj: dict) -> str | None:+ raw = (obj.get("metadata") or {}).get("annotations", {}).get("kopf.zalando.org/on_claim_create")+ if not raw:+ return None+ try:+ data = json.loads(raw)+ except Exception:+ return raw+ retries = data.get("retries")+ message = " ".join(str(data.get("message", "")).split())+ parts = []+ if retries is not None:+ parts.append(f"retries={retries}")+ if message:+ parts.append(message)+ return "; ".join(parts) or None+++# Console helpers+++def step(msg: str) -> None:+ print(f"\n==> {msg}", flush=True)+++def info(msg: str) -> None:+ print(f" {msg}", flush=True)+++def die(msg: str) -> None:+ sys.exit(f"\nERROR: {msg}")+++class TeeWriter:+ def __init__(self, *streams) -> None:+ self.streams = streams++ def write(self, data: str) -> int:+ for stream in self.streams:+ stream.write(data)+ return len(data)++ def flush(self) -> None:+ for stream in self.streams:+ stream.flush()++ def isatty(self) -> bool:+ return any(getattr(stream, "isatty", lambda: False)() for stream in self.streams)+++def configure_logging(log_file: str | None) -> None:+ if not log_file:+ return+ log_path = os.path.abspath(log_file)+ os.makedirs(os.path.dirname(log_path), exist_ok=True)+ log_stream = open(log_path, "a", encoding="utf-8", buffering=1)+ sys.stdout = TeeWriter(sys.stdout, log_stream)+ sys.stderr = TeeWriter(sys.stderr, log_stream)+ info(f"logging to {log_path}")+++# Pool / claim lifecycle (mirrors create_pool_and_list_tools.py)+++def create_namespace(http: httpx.Client, name: str) -> None:+ """Create the per-user namespace via the Capsule-backed SPA endpoint.++ Pool name == namespace name (1:1). Going through /api/namespaces is what+ makes Capsule stamp tenant ownership + RBAC, so the impersonated pool create+ below is allowed. 409 just means we are reusing an earlier run's namespace.+ """+ r = http.post("/api/namespaces", json={"name": name})+ if r.status_code == 409:+ info(f"namespace {name!r} already exists — reusing it")+ return+ if r.status_code == 403:+ die("403 creating namespace — namespaces/pools/claims need a per-USER key "+ "(client id 'ukey-…', from POST /api/user-keys).")+ r.raise_for_status()+ info(f"namespace {name!r} created")+++def delete_namespace(http: httpx.Client, name: str) -> None:+ r = http.delete(f"/api/namespaces/{name}")+ if r.status_code in (200, 202, 204, 404):+ info(f"namespace {name!r} delete requested (HTTP {r.status_code})")+ return+ if r.status_code == 403:+ die("403 deleting namespace — the user key cannot replace this pool namespace.")+ r.raise_for_status()+++def recreate_namespace(get_http: Callable[[], httpx.Client], name: str, poll: float) -> None:+ delete_namespace(get_http(), name)+ while True:+ r = get_http().post("/api/namespaces", json={"name": name})+ if r.status_code == 409:+ info(f"namespace {name!r} still terminating — waiting to recreate …")+ time.sleep(poll)+ continue+ if r.status_code == 403:+ die("403 creating namespace during replacement — namespaces/pools/claims need a per-USER key.")+ r.raise_for_status()+ info(f"namespace {name!r} recreated")+ return+++def desired_pool_spec(+ *,+ image: str,+ cpu: int,+ ram: str,+ firmware: str,+ replicas: int,+ readiness_port: int | None,+ services: tuple[ServiceSpec, ...],+) -> dict:+ template: dict = {+ "containerDiskImage": image,+ "imagePullSecret": "ecr-credentials",+ "cpuCores": cpu,+ "memory": ram,+ }+ # Match the SPA/operator: only send firmware when it differs from the bios default.+ if firmware != "bios":+ template["firmware"] = firmware+ if readiness_port:+ template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}+ rendered_services = [{"name": s.service, "targetPort": s.port, "protocol": "TCP"} for s in services]+ return {"replicas": replicas, "template": template, "services": rendered_services}+++def _json_canonical(value: dict) -> str:+ return json.dumps(value, sort_keys=True, separators=(",", ":"))+++def _flatten_json(value, prefix: str = "") -> dict[str, str]:+ flat: dict[str, str] = {}+ if isinstance(value, dict):+ for key in sorted(value):+ child = f"{prefix}.{key}" if prefix else str(key)+ flat.update(_flatten_json(value[key], child))+ if not value and prefix:+ flat[prefix] = "{}"+ elif isinstance(value, list):+ for idx, item in enumerate(value):+ child = f"{prefix}[{idx}]"+ flat.update(_flatten_json(item, child))+ if not value and prefix:+ flat[prefix] = "[]"+ else:+ flat[prefix] = json.dumps(value, sort_keys=True)+ return flat+++def log_pool_spec_diff(current_spec: dict, desired_spec: dict) -> None:+ current_flat = _flatten_json(current_spec, "spec")+ desired_flat = _flatten_json(desired_spec, "spec")+ keys = sorted(set(current_flat) | set(desired_flat))+ diffs = []+ for key in keys:+ current_value = current_flat.get(key, "<missing>")+ desired_value = desired_flat.get(key, "<missing>")+ if current_value == desired_value:+ continue+ diffs.append((key, current_value, desired_value))+ if not diffs:+ info("pool spec diff: none")+ return+ info(f"pool spec diff: {len(diffs)} field(s) differ")+ for key, current_value, desired_value in diffs:+ info(f" {key}: current={current_value} desired={desired_value}")+++def pool_reconcile_action(current_spec: dict, desired_spec: dict) -> str:+ if current_spec == desired_spec:+ return "noop"+ # always replace because thats simpler and more robust+ return "replace"+++def create_pool(+ get_http: Callable[[], httpx.Client],+ *,+ pool: str,+ image: str,+ cpu: int,+ ram: str,+ firmware: str,+ replicas: int,+ readiness_port: int | None,+ mcp_servers: tuple[McpServerSpec, ...],+ extra_services: tuple[ServiceSpec, ...],+ poll: float,+ allow_replace: bool = True,+) -> None:+ """Create the OSGymWorkspacePool with MCP and auxiliary services.++ Each service becomes a per-sandbox Service ``<sandbox>-<name>`` (port 80 ->+ targetPort). The MCP services are used by the agent; auxiliary services such+ as noVNC are exposed for debugging but are not opened as MCP sessions.+ """+ spec = desired_pool_spec(+ image=image,+ cpu=cpu,+ ram=ram,+ firmware=firmware,+ replicas=replicas,+ readiness_port=readiness_port,+ services=pool_services(mcp_servers, extra_services),+ )+ body = {+ "apiVersion": f"{POOL_GROUP}/{POOL_VERSION}",+ "kind": "OSGymWorkspacePool",+ "metadata": {"name": pool, "labels": {"cua.ai/pool": pool}},+ "spec": spec,+ }++ r = get_http().post(pool_url(pool), json=body)+ if r.status_code == 409:+ current = get_http().get(pool_url(pool, pool))+ current.raise_for_status()+ current_spec = current.json().get("spec") or {}+ log_pool_spec_diff(current_spec, spec)+ action = pool_reconcile_action(current_spec, spec)+ if action == "noop":+ info(f"pool {pool!r} already exists — reusing it (spec unchanged)")+ elif action == "scale":+ info(f"pool {pool!r} already exists — scaling replicas in place")+ rp = get_http().patch(+ pool_url(pool, pool),+ headers={"Content-Type": "application/merge-patch+json"},+ json={"spec": {"replicas": replicas}},+ )+ if rp.status_code == 403:+ die("403 updating pool replicas — the user key can create pools but cannot patch this pool spec.")+ rp.raise_for_status()+ info(f"pool {pool!r} scaled to replicas={replicas}")+ else:+ if not allow_replace:+ die(f"pool {pool!r} still differs from desired state after replacement attempt")+ info(f"pool {pool!r} already exists — desired template differs, replacing pool namespace")+ recreate_namespace(get_http, pool, poll)+ return create_pool(+ get_http,+ pool=pool,+ image=image,+ cpu=cpu,+ ram=ram,+ firmware=firmware,+ replicas=replicas,+ readiness_port=readiness_port,+ mcp_servers=mcp_servers,+ extra_services=extra_services,+ poll=poll,+ allow_replace=False,+ )+ info(f"image: {image}")+ info(f"size: {cpu} vCPU / {ram} / replicas={replicas} / firmware={firmware}")+ for s in mcp_servers:+ info(f"service: {s.service:<14} -> targetPort {s.port} (MCP at {s.mcp_path}, health {s.health})")+ for s in extra_services:+ info(f"service: {s.service:<14} -> targetPort {s.port} (auxiliary {s.label})")+ info(f"readiness: {'disabled' if not readiness_port else f'tcpSocket :{readiness_port}'}")+ return+ if r.status_code == 403:+ die("403 creating pool — /api/k8s needs a per-USER key ('ukey-…', POST /api/user-keys).")+ r.raise_for_status()+ info(f"pool {pool!r} created")+ info(f"image: {image}")+ info(f"size: {cpu} vCPU / {ram} / replicas={replicas} / firmware={firmware}")+ for s in mcp_servers:+ info(f"service: {s.service:<14} -> targetPort {s.port} (MCP at {s.mcp_path}, health {s.health})")+ for s in extra_services:+ info(f"service: {s.service:<14} -> targetPort {s.port} (auxiliary {s.label})")+ info(f"readiness: {'disabled' if not readiness_port else f'tcpSocket :{readiness_port}'}")+++def wait_template(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:+ """Wait for the compat shim to project the pool into <pool>-template."""+ tmpl = f"{pool}-template"+ deadline = time.monotonic() + timeout+ while True:+ r = get_http().get(template_url(pool, tmpl))+ if r.status_code == 200:+ info(f"pool-operator projected template {tmpl!r} + warm pool {pool!r}")+ return+ if r.status_code not in (404, 403):+ r.raise_for_status()+ if timeout > 0 and time.monotonic() > deadline:+ info(f"template {tmpl!r} not visible after {timeout:.0f}s — claiming anyway")+ try:+ info(f"pool status: {pool_summary(pool_status(get_http(), pool))}")+ except Exception:+ pass+ return+ info(f"waiting for pool-operator to project template {tmpl!r} …")+ time.sleep(poll)+++def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int, str]:+ """(totalCount, availableCount, phase) from the pool status, best-effort."""+ try:+ st = pool_status(get_http(), pool)+ return int(st.get("totalCount", 0)), int(st.get("availableCount", 0)), st.get("phase", "Unknown")+ except Exception:+ return 0, 0, "Unknown"+++def wait_pool_warm(+ get_http: Callable[[], httpx.Client],+ pool: str,+ timeout: float,+ poll: float,+ *,+ replicas: int,+ min_available: int,+) -> None:+ """Wait until the pool reports a warm (Ready) VM, so the first claim binds fast.++ A cold pool has to pull the multi-GB containerDisk, boot the guest, and bring+ the readiness-port service up before a Sandbox is adoptable. Letting the pool+ warm first keeps the claim's bindDeadline from burning down during the pull.+ """+ start = time.monotonic()+ deadline = start + timeout+ last_summary = ""+ while True:+ try:+ st = pool_status(get_http(), pool)+ total = int(st.get("totalCount", 0))+ avail = int(st.get("availableCount", 0))+ phase = st.get("phase", "Unknown")+ summary = pool_summary(st)+ except Exception:+ total, avail, phase = 0, 0, "Unknown"+ summary = "phase=Unknown ready=0/0 claimed=0"+ if total >= replicas and avail >= min_available:+ info(f"pool warm: {avail}/{total} VM(s) ready (phase {phase})")+ return+ if summary != last_summary:+ info(f"pool detail: {summary}")+ last_summary = summary+ if timeout > 0 and time.monotonic() > deadline:+ info(f"timed out after {timeout:.0f}s waiting for a warm VM (pool {phase}, {avail}/{total})")+ info("continuing anyway — the claim may still bind once the VM finishes pulling/booting")+ return+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] pool={phase} ({avail}/{total} VMs ready, target total={replicas}, "+ f"target available={min_available}) — warming (image pull + guest boot + service on the readiness port) …")+ time.sleep(poll)+++def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int) -> None:+ spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}+ if bind_deadline:+ spec["bindDeadline"] = bind_deadline+ r = http.post(claims_url(pool), json={+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}", "kind": "OSGymSandboxClaim",+ "metadata": {"name": name}, "spec": spec})+ if r.status_code == 403:+ die("403 creating claim — per-pool keys have no K8s identity. Use a per-USER key ('ukey-…').")+ r.raise_for_status()+ info(f"claim {name!r} created")+++def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:+ """Poll the claim until status.phase == Bound; return the sandbox name."""+ start = time.monotonic()+ deadline = start + timeout+ last_claim = ""+ last_pool = ""+ last_operator = ""+ while True:+ claim = claim_obj(get_http(), pool, name)+ status = claim.get("status") or {}+ phase = status.get("phase", "Pending")+ sandbox = (status.get("sandbox") or {}).get("name")+ if phase == "Bound" and sandbox:+ return sandbox+ if phase == "Failed":+ die(f"claim {name} failed: {status}")+ if timeout > 0 and time.monotonic() > deadline:+ die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")+ claim_line = claim_summary(status)+ if claim_line != last_claim:+ info(f"claim detail: {claim_line}")+ last_claim = claim_line+ operator_line = claim_operator_progress(claim)+ if operator_line and operator_line != last_operator:+ info(f"claim operator: {operator_line}")+ last_operator = operator_line+ try:+ pst = pool_status(get_http(), pool)+ total = int(pst.get("totalCount", 0))+ avail = int(pst.get("availableCount", 0))+ pphase = pst.get("phase", "Unknown")+ pool_line = pool_summary(pst)+ except Exception:+ total, avail, pphase = 0, 0, "Unknown"+ pool_line = "phase=Unknown ready=0/0 claimed=0"+ if pool_line != last_pool:+ info(f"pool detail: {pool_line}")+ last_pool = pool_line+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] claim={phase} pool={pphase} ({avail}/{total} VMs ready) …")+ time.sleep(poll)+++def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:+ """GET url until the in-guest service answers (not a proxy 502/503/504)."""+ start = time.monotonic()+ deadline = start + timeout+ while True:+ try:+ resp = get_http().get(url, timeout=15.0)+ except httpx.HTTPError as e:+ resp, reason = None, type(e).__name__+ else:+ reason = f"HTTP {resp.status_code}"+ if resp is not None and resp.status_code not in (502, 503, 504):+ info(f"service responding ({reason})")+ return+ if timeout > 0 and time.monotonic() > deadline:+ die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")+ elapsed = int(time.monotonic() - start)+ info(f"[{elapsed:4d}s] {reason} — guest still booting …")+ time.sleep(poll)+++# MCP (Streamable HTTP) multi-server+++def _sse_json(resp: httpx.Response) -> dict:+ """Streamable HTTP replies are SSE ('event: message\\ndata: {...}'); the JSON+ is on the data: line. Fall back to the raw body for plain JSON."""+ line = next((ln[6:] for ln in resp.text.splitlines() if ln.startswith("data: ")), resp.text)+ return json.loads(line)+++class McpConn:+ """A live MCP session against one server of the bound sandbox."""++ spec: McpServerSpec+ svc_base: str # /api/svc/{ns}/{sandbox}-{service}+ session_id: str | None+ tools: list[dict] # this server's raw tools/list++ @property+ def url(self) -> str:+ return f"{self.svc_base}{self.spec.mcp_path}"++ def _headers(self) -> dict:+ h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}+ if self.session_id:+ h["Mcp-Session-Id"] = self.session_id+ return h+++def mcp_open(http: httpx.Client, spec: McpServerSpec, svc_base: str, client_name: str) -> McpConn:+ """initialize -> notifications/initialized -> tools/list for one server."""+ url = f"{svc_base}{spec.mcp_path}"+ headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}+ init = http.post(url, headers=headers, timeout=30.0, json={+ "jsonrpc": "2.0", "id": 1, "method": "initialize",+ "params": {"protocolVersion": "2025-03-26", "capabilities": {},+ "clientInfo": {"name": client_name, "version": "0.1.0"}}})+ init.raise_for_status()+ sid = init.headers.get("mcp-session-id")+ if sid:+ headers["Mcp-Session-Id"] = sid+ http.post(url, headers=headers, timeout=30.0, json={"jsonrpc": "2.0", "method": "notifications/initialized"})+ r = http.post(url, headers=headers, timeout=30.0, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"})+ r.raise_for_status()+ tools = _sse_json(r).get("result", {}).get("tools", [])+ return McpConn(spec=spec, svc_base=svc_base, session_id=sid, tools=tools)+++_BEDROCK_IMAGE_FORMATS = {"png", "jpeg", "gif", "webp"}+++def mcp_call(http: httpx.Client, conn: McpConn, name: str, arguments: dict) -> dict:+ """Dispatch one tools/call on a specific server. Returns text + inline images+ (decoded to raw bytes + Bedrock image format) + isError. Raises on a+ transport/proxy error so the caller can surface it."""+ r = http.post(conn.url, headers=conn._headers(), timeout=600.0, json={+ "jsonrpc": "2.0", "id": 1, "method": "tools/call",+ "params": {"name": name, "arguments": arguments}})+ if r.status_code in (502, 503, 504):+ raise httpx.HTTPError(f"proxy {r.status_code}")+ r.raise_for_status()+ result = _sse_json(r).get("result", {})+ text_parts, images = [], []+ for block in result.get("content", []):+ if block.get("type") == "text":+ text_parts.append(block.get("text", ""))+ elif block.get("type") == "image":+ mime = block.get("mimeType", "image/png")+ fmt = mime.split("/")[-1].lower()+ fmt = "jpeg" if fmt == "jpg" else fmt+ if fmt not in _BEDROCK_IMAGE_FORMATS:+ fmt = "png"+ images.append({"format": fmt, "bytes": base64.b64decode(block["data"])})+ return {"text": "\n".join(text_parts), "images": images, "is_error": bool(result.get("isError"))}+++def _sanitize(label: str) -> str:+ return re.sub(r"[^a-zA-Z0-9_-]", "-", label)+++def build_tool_registry(conns: list[McpConn]) -> tuple[list[dict], dict[str, tuple[McpConn, str]]]:+ """Union every server's tools into one Bedrock Converse toolConfig tool list,+ namespacing names as ``<server>__<tool>`` so two servers can expose the same+ tool without colliding. Returns (llm_tools, registry) where registry maps the+ namespaced name back to (connection, original tool name) for dispatch."""+ llm_tools: list[dict] = []+ registry: dict[str, tuple[McpConn, str]] = {}+ for conn in conns:+ prefix = _sanitize(conn.spec.label)+ for t in conn.tools:+ orig = t["name"]+ llm_name = f"{prefix}__{orig}"[:64] # Bedrock caps tool names at 64+ # Extremely unlikely, but keep names unique if truncation collides.+ while llm_name in registry:+ llm_name = f"{llm_name[:60]}_{len(registry)}"+ registry[llm_name] = (conn, orig)+ desc = f"[{conn.spec.label}] " + " ".join((t.get("description") or "").split())+ schema = t.get("inputSchema") or {"type": "object", "properties": {}}+ llm_tools.append({"toolSpec": {+ "name": llm_name,+ "description": desc or llm_name,+ "inputSchema": {"json": schema}}})+ return llm_tools, registry+++def _msg_has_image(m: dict) -> bool:+ return isinstance(m.get("content"), list) and any(+ "toolResult" in b and any("image" in c for c in b["toolResult"].get("content", []))+ for b in m["content"])+++def _prune_images(messages: list[dict], keep: int) -> None:+ """Drop all but the last `keep` screenshots — image tokens dominate a+ computer-use trajectory's cost and stale frames mislead the model. Images live+ inside toolResult content blocks; replace each with a text placeholder so the+ toolResult stays valid (Converse requires non-empty toolResult content)."""+ idx = [i for i, m in enumerate(messages) if _msg_has_image(m)]+ for i in (idx[:-keep] if keep else idx):+ for b in messages[i]["content"]:+ tr = b.get("toolResult")+ if not tr:+ continue+ tr["content"] = [+ {"text": "[older screenshot dropped from context]"} if "image" in c else c+ for c in tr.get("content", [])]+++# The agent loop (mini-swe-agent, multi-MCP)+++def _converse_text(content: list[dict]) -> str:+ return "\n".join(b["text"] for b in content if "text" in b).strip()+++def run_agent(http_get: Callable[[], httpx.Client], conns: list[McpConn], bedrock, *,+ task: str, model_id: str, max_steps: int, keep_images: int) -> str:+ """Canonical mini-swe-agent loop over the UNION of every server's tools, driven+ by the Bedrock Converse API (one tool turn per step)."""+ llm_tools, registry = build_tool_registry(conns)+ info(f"action space: {len(llm_tools)} tools across {len(conns)} MCP server(s)")+ for conn in conns:+ names = ", ".join(sorted(t["name"] for t in conn.tools)) or "(none)"+ info(f" {conn.spec.label}: {names}")++ system = [{"text": SYSTEM}]+ tool_config = {"tools": llm_tools}+ messages: list[dict] = [{"role": "user", "content": [{"text": task}]}]+ for n in range(1, max_steps + 1):+ resp = bedrock.converse(+ modelId=model_id,+ system=system,+ messages=messages,+ toolConfig=tool_config,+ inferenceConfig={"temperature": 0.0, "maxTokens": MAX_OUTPUT_TOKENS},+ )+ out = resp["output"]["message"]+ messages.append(out)+ tool_uses = [b["toolUse"] for b in out["content"] if "toolUse" in b]+ if not tool_uses:+ step(f"agent finished after {n - 1} action(s)")+ final = _converse_text(out["content"])+ print(final or "(no final message)", flush=True)+ return final or "done"++ result_blocks: list[dict] = []+ for tu in tool_uses:+ llm_name, tuid = tu["name"], tu["toolUseId"]+ tool_args = tu.get("input") or {}+ entry = registry.get(llm_name)+ if entry is None:+ result_blocks.append({"toolResult": {"toolUseId": tuid,+ "content": [{"text": f"unknown tool {llm_name!r}"}], "status": "error"}})+ continue+ conn, orig = entry+ info(f"[step {n}] {conn.spec.label} -> {orig}({json.dumps(tool_args)[:120]})")+ try:+ res = mcp_call(http_get(), conn, orig, tool_args)+ except httpx.HTTPError as e:+ result_blocks.append({"toolResult": {"toolUseId": tuid,+ "content": [{"text": f"tool transport error: {e}"}], "status": "error"}})+ continue+ content: list[dict] = []+ if res["text"]:+ content.append({"text": res["text"]})+ for img in res["images"]:+ content.append({"image": {"format": img["format"], "source": {"bytes": img["bytes"]}}})+ if not content:+ content.append({"text": "(no output)"})+ result_blocks.append({"toolResult": {"toolUseId": tuid, "content": content,+ "status": "error" if res["is_error"] else "success"}})+ messages.append({"role": "user", "content": result_blocks})+ _prune_images(messages, keep_images)+ return "max_steps_exceeded"+++# Main+++def main() -> None:+ pre = argparse.ArgumentParser(add_help=False)+ pre.add_argument("--config")+ pre_args, remaining = pre.parse_known_args()+ manifest = load_run_manifest(pre_args.config)+ mcp_servers, extra_services = load_pool_services(manifest)++ p = argparse.ArgumentParser(+ description=f"Provision a {OS_NAME} double-MCP pool on run.cua.ai, claim a sandbox, "+ "and run mini-swe-agent against BOTH its MCP servers.",+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,+ parents=[pre],+ )+ cfg_name = manifest_get(manifest, "metadata", "name")+ cfg_task = manifest_get(manifest, "spec", "agent", "task")+ p.add_argument("--name", required=cfg_name is None, default=cfg_name,+ help="pool name (also the namespace; lowercase/dashes). Reuse the same name across retries "+ "to keep the same provisioning pool warm.")+ p.add_argument("--task", required=cfg_task is None, default=cfg_task, help="the task prompt for the agent")+ p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),+ help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")+ p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),+ help="OAuth client secret; env CUA_CLIENT_SECRET")+ p.add_argument("--model", default=manifest_get(manifest, "spec", "agent", "model", default=default_model()) or default_model(),+ help="Bedrock model id (a leading 'bedrock/' is stripped). Uses AGENT_MODEL if set, "+ f"else {DEFAULT_BEDROCK_MODEL}.")+ p.add_argument("--aws-region", default=None,+ help="AWS region for the Bedrock client. Defaults to AWS_REGION/AWS_DEFAULT_REGION "+ "(or your ~/.aws config). Credentials always come from the AWS env / default chain.")+ p.add_argument("--image", default=manifest_get(manifest, "spec", "pool", "image"), help="workspace containerDisk image")+ p.add_argument("--cpu", type=int, default=manifest_get(manifest, "spec", "pool", "cpu"), help="vCPU cores per VM")+ p.add_argument("--ram", default=manifest_get(manifest, "spec", "pool", "ram"), help="memory per VM (K8s quantity)")+ p.add_argument("--firmware", choices=FIRMWARE_CHOICES,+ default=manifest_get(manifest, "spec", "pool", "firmware", default=DEFAULT_FIRMWARE) or DEFAULT_FIRMWARE,+ help="VM firmware. 'efi' for GPT/UEFI-only images (Windows desktop-workspace); "+ "'bios' (KubeVirt default) for the Linux workspace images.")+ p.add_argument("--replicas", type=int, default=manifest_get(manifest, "spec", "pool", "replicas"), help="pre-warmed VMs the pool keeps")+ p.add_argument("--min-available", type=int, default=manifest_get(manifest, "spec", "pool", "minAvailable"),+ help="minimum warm/available VMs to wait for before claiming. Set to 2+ to keep a small surplus warm.")+ p.add_argument("--readiness-port", type=int, default=manifest_get(manifest, "spec", "pool", "readinessPort"),+ help="TCP port used for readiness probing. Set to 0 to disable readiness probes in the pool template.")+ p.add_argument("--max-steps", type=int, default=manifest_get(manifest, "spec", "agent", "maxSteps"), help="agent step budget")+ p.add_argument("--keep-images", type=int, default=manifest_get(manifest, "spec", "agent", "keepImages"), help="screenshots kept in LLM context")+ p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL))+ p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL))+ p.add_argument("--claim-name", default=manifest_get(manifest, "spec", "claim", "name"), help="claim name (default: claim-<random>)")+ p.add_argument("--template-timeout", type=float, default=manifest_get(manifest, "spec", "rollout", "templateTimeout"))+ p.add_argument("--warm-timeout", type=float, default=manifest_get(manifest, "spec", "rollout", "warmTimeout"),+ help="seconds to wait for warm pool capacity. 0 waits indefinitely.")+ p.add_argument("--bind-deadline", type=int, default=manifest_get(manifest, "spec", "claim", "bindDeadline"))+ p.add_argument("--bind-timeout", type=float, default=manifest_get(manifest, "spec", "rollout", "bindTimeout"),+ help="seconds to wait for claim binding. 0 waits indefinitely.")+ p.add_argument("--ready-timeout", type=float, default=manifest_get(manifest, "spec", "rollout", "readyTimeout"),+ help="seconds to wait for each MCP server to answer after binding. 0 waits indefinitely.")+ p.add_argument("--poll-interval", type=float, default=manifest_get(manifest, "spec", "rollout", "pollInterval"))+ p.add_argument("--log-file", default=None,+ help="append all console output to this file while the run is active")+ p.add_argument("--keep", action="store_true", default=manifest_get(manifest, "spec", "teardown", "keepPool"),+ help="skip teardown — leave the pool/namespace/claim up for debugging or for reuse on the next retry")+ p.add_argument("--delete-pool", action="store_true", default=manifest_get(manifest, "spec", "teardown", "deletePool"),+ help="on exit also delete the pool AND namespace (full cleanup)")+ args = p.parse_args(remaining)+ args.name = resolve_name_template(args.name)+ args.claim_name = resolve_name_template(args.claim_name)+ configure_logging(args.log_file)++ if not args.client_id or not args.client_secret:+ die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "+ "(per-user key from POST /api/user-keys)")+ if args.client_id.startswith("key-"):+ die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "+ "Creating namespaces/pools/claims needs a per-USER key ('ukey-…').")++ model_id = bedrock_model_id(args.model)+ bedrock = make_bedrock_client(args)++ pool = args.name+ claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"++ step(f"Authenticating to {args.base_url} (client {args.client_id})")+ client = TrainClient.from_key(token_url=args.token_url, client_id=args.client_id,+ client_secret=args.client_secret, base_url=args.base_url)+ http = client.get_httpx_client # call per request — re-mints the bearer near expiry+ info("token acquired")++ step(f"Creating namespace {pool!r}")+ create_namespace(http(), pool)++ step(f"Creating {OS_NAME} double-MCP pool {pool!r}")+ readiness_port = args.readiness_port or None+ create_pool(+ http,+ pool=pool,+ image=args.image,+ cpu=args.cpu,+ ram=args.ram,+ firmware=args.firmware,+ replicas=args.replicas,+ readiness_port=readiness_port,+ mcp_servers=mcp_servers,+ extra_services=extra_services,+ poll=args.poll_interval,+ )++ step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")++ # The claim is ALWAYS released — on success, on error, or on Ctrl-C — so an+ # interrupted or failed run never leaks a claimed VM. --keep only preserves the+ # pool/namespace, NOT the claim. The `released` flag makes release idempotent+ # across the SIGINT handler and the finally block.+ released = False++ def release_claim() -> None:+ nonlocal released+ if released:+ return+ released = True+ step(f"Releasing claim {claim_name!r}")+ try:+ r = http().delete(claims_url(pool, claim_name))+ info(f"released (HTTP {r.status_code}) — the VM hard-resets and rejoins the pool")+ except httpx.HTTPError as e:+ info(f"could not release claim: {type(e).__name__}: {e}")++ def _sigint_handler(signum, frame):+ print(flush=True)+ step("Interrupted (Ctrl-C) — releasing claim before exit")+ release_claim()+ sys.exit(130)++ signal.signal(signal.SIGINT, _sigint_handler)++ try:+ # Inside the try so the finally still releases even if create/bind fails midway.+ create_claim(http(), pool, claim_name, args.bind_deadline)+ step("Waiting for the claim to bind to the warm sandbox")+ sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)+ info(f"bound to sandbox {sandbox!r}")++ # Connect to EVERY MCP server the double image exposes. Best-effort for+ # dev: a server that fails to connect is logged and skipped rather than+ # aborting the whole run, so a partial action space is still usable.+ conns: list[McpConn] = []+ for spec in mcp_servers:+ svc_base = f"/api/svc/{pool}/{sandbox}-{spec.service}"+ step(f"Waiting for the {spec.label} server (svc {sandbox}-{spec.service}, health {spec.health})")+ # wait_service_ready(http, f"{svc_base}{spec.health}", args.ready_timeout, args.poll_interval)+ step(f"Opening MCP session: {spec.label} at {svc_base}{spec.mcp_path}")+ try:+ conn = mcp_open(http(), spec, svc_base, client_name=f"mini-swe-multi-mcp-{OS_NAME}")+ except Exception as e:+ info(f"could not connect to {spec.label} MCP server: {type(e).__name__}: {e} — skipping (best effort)")+ continue+ info(f"session {conn.session_id or '(stateless)'} — {len(conn.tools)} tool(s)")+ conns.append(conn)++ if not conns:+ die("no MCP servers connected — cannot run the agent")++ step(f"Running mini-swe-agent (bedrock {model_id}) against {len(conns)} MCP server(s)")+ info(f"task: {args.task}")+ result = run_agent(http, conns, bedrock, task=args.task, model_id=model_id,+ max_steps=args.max_steps, keep_images=args.keep_images)+ step(f"Agent result: {result[:200]}")+ finally:+ print(flush=True)+ # Always release the claim — success, error, or interrupt — no matter what.+ release_claim()+ if args.keep:+ step(f"Keeping pool/namespace {pool!r} — skipping pool teardown (--keep)")+ info(f"claim again: POST {claims_url(pool)} (spec.sandboxTemplateRef.name={pool}-template)")+ info(f"delete it: DELETE {pool_url(pool, pool)} (and DELETE /api/namespaces/{pool})")+ elif args.delete_pool:+ step(f"Tearing down pool {pool!r} (pool + namespace)")+ for what, url in ((f"pool {pool!r}", pool_url(pool, pool)),+ (f"namespace {pool!r}", f"/api/namespaces/{pool}")):+ try:+ r = http().delete(url)+ info(f"deleted {what} (HTTP {r.status_code})")+ except httpx.HTTPError as e:+ info(f"could not delete {what}: {type(e).__name__}: {e}")+ else:+ step(f"Pool {pool!r} is live")+ info(f"claim again: POST {claims_url(pool)} (spec.sandboxTemplateRef.name={pool}-template)")+ info(f"delete it: DELETE {pool_url(pool, pool)} (and DELETE /api/namespaces/{pool})")+++if __name__ == "__main__":+ main()diff --git a/libs/fleet/python-sdk/examples/windows-mini-swe.yaml b/libs/fleet/python-sdk/examples/windows-mini-swe.yamlnew file mode 100644index 0000000000..3f55ee71c7--- /dev/null+++ b/libs/fleet/python-sdk/examples/windows-mini-swe.yaml@@ -0,0 +1,54 @@+apiVersion: cua.ai/v1alpha1+kind: AgentWindowsDoubleMCPRun+metadata:+ name: windows-mini-swe++spec:+ pool:+ image: 296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest+ cpu: 4+ ram: 4Gi+ firmware: efi # GPT/UEFI-only Windows image; operator also enables Hyper-V enlightenments for efi+ replicas: 2+ minAvailable: 1+ readinessPort: 8000+ services:+ - type: mcp+ label: computer-server+ service: server+ port: 8000+ mcpPath: /mcp+ health: /status+ - type: mcp+ label: cua-driver+ service: mcp+ port: 3000+ mcpPath: /mcp+ health: /healthz+ - type: auxiliary+ label: novnc+ service: novnc+ port: 6080+ claim:+ bindDeadline: 600+ agent:+ model: us.anthropic.claude-sonnet-4-6+ task: >-+ Launch Microsoft Edge in this Windows environment, open+ https://news.yahoo.com/, inspect the Yahoo News front page, and then+ report the visible page contents in a concise final message. Do all work+ inside this remote Windows sandbox, not on the local machine.+ maxSteps: 60+ keepImages: 2+ rollout:+ templateTimeout: 120+ warmTimeout: 0+ bindTimeout: 0+ readyTimeout: 0+ pollInterval: 10+ teardown:+ # keepPool:false so `--delete-pool` actually tears down (the script's+ # if-keep/elif-delete precedence ignores --delete-pool when keepPool is+ # true). With no teardown flags the pool is still left live for reuse.+ keepPool: false+ deletePool: falsediff --git a/libs/fleet/python-sdk/openapi3.yaml b/libs/fleet/python-sdk/openapi3.yamlnew file mode 100644index 0000000000..b4056a5e26--- /dev/null+++ b/libs/fleet/python-sdk/openapi3.yaml@@ -0,0 +1,1246 @@+openapi: 3.0.3+info:+ title: Cyclops CS Backend API+ description: "Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key\n\+ management, authenticated reverse proxies (gateway / k8s / orch), and\nthe in-process\+ \ OSGym batch driver.\n\nThe batch driver exposes two pool-scoped surfaces:\n\+ - `/api/batch/{pool}/...` — submit, poll, cancel a single batch by ID\n- `/api/label/{pool}/{label}/...`\+ \ — aggregate operations across batches\n in `{pool}` that share a `name` field\+ \ (the \"label\")\n"+ version: '0.2'+ contact:+ name: API Support+ url: https://cua.ai/support+ email: [email protected]+servers:+- url: https://run.cua.ai+ description: Production+security:+- BearerAuth: []+paths:+ /healthz:+ get:+ summary: Liveness/readiness probe+ operationId: healthz+ tags:+ - health+ security: []+ responses:+ '200':+ description: OK+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HealthResponse'+ /api/keys:+ get:+ summary: List the calling user's API keys+ operationId: listKeys+ tags:+ - keys+ responses:+ '200':+ description: OK+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ListKeysResponse'+ '401':+ $ref: '#/components/responses/Unauthorized'+ post:+ summary: Create a new API key+ operationId: createKey+ description: Creates a Keycloak service-account client owned by the calling+ user. The returned `client_secret` is shown exactly once.+ tags:+ - keys+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CreateKeyRequest'+ responses:+ '201':+ description: Created+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CreateKeyResponse'+ '400':+ $ref: '#/components/responses/BadRequest'+ '401':+ $ref: '#/components/responses/Unauthorized'+ '403':+ $ref: '#/components/responses/Forbidden'+ /api/keys/{id}:+ delete:+ summary: Revoke an API key by Keycloak client UUID+ operationId: deleteKey+ tags:+ - keys+ parameters:+ - name: id+ in: path+ required: true+ description: Keycloak client UUID+ schema:+ type: string+ responses:+ '204':+ description: No Content+ '401':+ $ref: '#/components/responses/Unauthorized'+ '403':+ $ref: '#/components/responses/Forbidden'+ /api/batch/{pool}/submit:+ post:+ summary: Submit a batch of rollouts+ operationId: submitBatch+ description: 'Asynchronously queues a batch of OSGym rollouts under `{pool}`.++ Returns immediately with a `batch_id`; poll++ `/api/batch/{pool}/{id}/status` for progress and++ `/api/batch/{pool}/{id}/results` for the final payload.+++ The pool is bound by the URL path; any `pool_name` in the body must++ match the URL pool or the request is rejected with 400.++ '+ tags:+ - batch+ parameters:+ - name: pool+ in: path+ required: true+ description: Pool name (DNS-1123 label)+ schema:+ type: string+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BatchSubmitRequest'+ responses:+ '202':+ description: Accepted+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BatchSubmitResponse'+ '400':+ $ref: '#/components/responses/BadRequest'+ '401':+ $ref: '#/components/responses/Unauthorized'+ /api/batch/{pool}/lanes:+ post:+ summary: Acquire warm VM lanes+ operationId: acquireLanes+ description: 'Explicitly provisions N warm VMs ("lanes") and returns their vm_ids.+ Pass each as `RunConfig.vm_id` to run actions on it (state persists across+ batches), and `DELETE` this route to release them. All-or-nothing: a partial+ acquisition is rolled back, and 503 is returned if the pool can''t supply+ every lane in time.'+ tags:+ - batch+ parameters:+ - name: pool+ in: path+ required: true+ description: Pool name+ schema:+ type: string+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/AcquireLanesRequest'+ responses:+ '200':+ description: Lanes acquired+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/AcquireLanesResponse'+ '400':+ $ref: '#/components/responses/BadRequest'+ '401':+ $ref: '#/components/responses/Unauthorized'+ '503':+ description: Pool could not supply the requested lanes+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorResponse'+ delete:+ summary: Release warm VM lanes+ operationId: releaseLanes+ description: Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s+ returned by a `keep_warm` batch). Best-effort and idempotent — unknown or+ already-gone ids are ignored.+ tags:+ - batch+ parameters:+ - name: pool+ in: path+ required: true+ description: Pool name+ schema:+ type: string+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ReleaseLanesRequest'+ responses:+ '200':+ description: Release accepted+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ReleaseLanesResponse'+ '400':+ $ref: '#/components/responses/BadRequest'+ '401':+ $ref: '#/components/responses/Unauthorized'+ /api/batch/{pool}/{id}/status:+ get:+ summary: Poll batch progress+ operationId: getBatchStatus+ tags:+ - batch+ parameters:+ - name: pool+ in: path+ required: true+ description: Pool name+ schema:+ type: string+ - name: id+ in: path+ required: true+ description: Batch ID (UUID returned by submit)+ schema:+ type: string+ responses:+ '200':+ description: OK+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BatchStatusResponse'+ '401':+ $ref: '#/components/responses/Unauthorized'+ '404':+ $ref: '#/components/responses/NotFound'+ /api/batch/{pool}/{id}/results:+ get:+ summary: Final batch results+ operationId: getBatchResults+ description: 'Returns 200 with the full results once the batch is in a terminal++ status (completed/failed). While still running, returns 202 with a++ `message` field.++ '+ tags:+ - batch+ parameters:+ - name: pool+ in: path+ required: true+ description: Pool name+ schema:+ type: string+ - name: id+ in: path+ required: true+ description: Batch ID+ schema:+ type: string+ responses:+ '200':+ description: Completed — full results+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BatchResultsResponse'+ '202':+ description: Still running+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BatchInProgressResponse'+ '401':+ $ref: '#/components/responses/Unauthorized'+ '404':+ $ref: '#/components/responses/NotFound'+ /api/batch/{pool}/{id}:+ delete:+ summary: Cancel a batch+ operationId: cancelBatch+ description: 'Hard-cancels the batch — aborts in-flight /reset and /step calls++ and stops dispatch. Idempotent on terminal batches. Returns 200++ with the final status.++ '+ tags:+ - batch+ parameters:+ - name: pool+ in: path+ required: true+ description: Pool name+ schema:+ type: string+ - name: id+ in: path+ required: true+ description: Batch ID+ schema:+ type: string+ responses:+ '200':+ description: OK+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CancelBatchResponse'+ '401':+ $ref: '#/components/responses/Unauthorized'+ '404':+ $ref: '#/components/responses/NotFound'+ /api/label/{pool}/{label}/batch:+ post:+ summary: Submit a batch under a pool and label+ operationId: submitLabelBatch+ description: 'Same as `/api/batch/{pool}/submit` but pins the batch''s `name`++ field to the URL label, overriding any value in the body. The++ label is scoped to `{pool}`; aggregate routes under++ `/api/label/{pool}/{label}/*` only see batches submitted to the++ same pool.++ '+ tags:+ - label+ parameters:+ - name: pool+ in: path+ required: true+ description: Pool name (DNS-1123 label)+ schema:+ type: string+ - name: label+ in: path+ required: true+ description: Batch label / name+ schema:+ type: string+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BatchSubmitRequest'+ responses:+ '202':+ description: Accepted+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BatchSubmitResponse'+ '400':+ $ref: '#/components/responses/BadRequest'+ '401':+ $ref: '#/components/responses/Unauthorized'+ /api/label/{pool}/{label}/status:+ get:+ summary: Aggregate status for all batches under a pool+label+ operationId: getLabelStatus+ description: Aggregates only batches submitted under `{pool}`; batches with+ the same label in other pools are invisible.+ tags:+ - label+ parameters:+ - name: pool+ in: path+ required: true+ description: Pool name+ schema:+ type: string+ - name: label+ in: path+ required: true+ description: Batch label+ schema:+ type: string+ responses:+ '200':+ description: OK+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LabelStatusResponse'+ '401':+ $ref: '#/components/responses/Unauthorized'+ '404':+ $ref: '#/components/responses/NotFound'+ /api/label/{pool}/{label}/results:+ get:+ summary: Aggregate results for all batches under a pool+label+ operationId: getLabelResults+ description: 'Default mode returns 200 only once every matched batch is completed.++ Pass `?completed_only=true` to drain partial results (200 with the++ filtered subset; non-completed batches are visible via status).++ Aggregates only batches submitted under `{pool}`.++ '+ tags:+ - label+ parameters:+ - name: pool+ in: path+ required: true+ description: Pool name+ schema:+ type: string+ - name: label+ in: path+ required: true+ description: Batch label+ schema:+ type: string+ - name: completed_only+ in: query+ required: false+ description: Return completed batches only (drain mode)+ schema:+ type: boolean+ responses:+ '200':+ description: OK — all batches completed (or drain mode)+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LabelResultsResponse'+ '202':+ description: Still running (non-drain mode)+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LabelInProgressResponse'+ '401':+ $ref: '#/components/responses/Unauthorized'+ '404':+ $ref: '#/components/responses/NotFound'+ /api/label/{pool}/{label}:+ delete:+ summary: Cancel every non-terminal batch under a label (scoped to pool)+ operationId: cancelLabel+ description: Cancels only batches submitted under `{pool}`; same label in other+ pools is untouched.+ tags:+ - label+ parameters:+ - name: pool+ in: path+ required: true+ description: Pool name+ schema:+ type: string+ - name: label+ in: path+ required: true+ description: Batch label+ schema:+ type: string+ responses:+ '200':+ description: OK+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CancelLabelResponse'+ '401':+ $ref: '#/components/responses/Unauthorized'+ '404':+ $ref: '#/components/responses/NotFound'+ /api/gateway/{pool}/lanes:+ post:+ summary: Create Lane+ description: 'Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.+++ The lane id is the stable handle the customer holds. The++ underlying claim CR''s name rotates on swap; the lane id does++ not. The initial bind is via the normal queue+CAS-PATCH flow,++ same as /reset.'+ operationId: create_lane_lanes_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LaneCreateRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LaneResponse'+ '503':+ description: Bind timeout — warm pool exhausted+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LaneErrorResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ parameters:+ - name: pool+ in: path+ required: true+ schema:+ type: string+ description: Pool name (DNS-1123 label)+ tags:+ - lanes+ /api/gateway/{pool}/lanes/{lane_id}/swap:+ post:+ summary: Swap+ description: 'New-first claim rotation for ``lane_id``.+++ Calls into the pure protocol body in osgym/lane_swap.py with a++ K8s-backed SwapDeps. The lane keeps its bound VM if the swap++ bind times out (SwapAtomicity); the new vm_id is returned on++ success.'+ operationId: swap_lanes__lane_id__swap_post+ parameters:+ - name: pool+ in: path+ required: true+ schema:+ type: string+ description: Pool name (DNS-1123 label)+ - name: lane_id+ in: path+ required: true+ schema:+ type: string+ title: Lane Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LaneSwapResponse'+ '404':+ description: Lane not found+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LaneErrorResponse'+ '503':+ description: Swap bind timeout — old VM retained+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LaneErrorResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ tags:+ - lanes+ /api/gateway/{pool}/lanes/{lane_id}:+ delete:+ summary: Delete Lane+ description: Release the lane's bound claim. Idempotent.+ operationId: delete_lane_lanes__lane_id__delete+ parameters:+ - name: pool+ in: path+ required: true+ schema:+ type: string+ description: Pool name (DNS-1123 label)+ - name: lane_id+ in: path+ required: true+ schema:+ type: string+ title: Lane Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LaneDeleteResponse'+ '404':+ description: Lane not found+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LaneErrorResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ tags:+ - lanes+components:+ securitySchemes:+ BearerAuth:+ type: http+ scheme: bearer+ description: "Keycloak access token.\n- For `/api/keys` and `/api/{k8s,orch}`:\+ \ SPA user JWT (azp=cyclops-cs-spa).\n- For `/api/batch/{pool}/*` and `/api/label/{pool}/*`:\+ \ service-account JWT\n minted via `client_credentials` against a per-key\+ \ client; the token's\n `namespace` claim must equal `pool-{pool}` (OPA-enforced).\+ \ SPA tokens\n may target any pool.\n"+ responses:+ BadRequest:+ description: Bad Request+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorResponse'+ Unauthorized:+ description: Unauthorized+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorResponse'+ Forbidden:+ description: Forbidden+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorResponse'+ NotFound:+ description: Not Found+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorResponse'+ schemas:+ ErrorResponse:+ type: object+ properties:+ error:+ type: string+ HealthResponse:+ type: object+ properties:+ ok:+ type: boolean+ KeyClient:+ type: object+ properties:+ id:+ type: string+ client_id:+ type: string+ name:+ type: string+ namespace:+ type: string+ owner_sub:+ type: string+ ListKeysResponse:+ type: object+ properties:+ keys:+ type: array+ items:+ $ref: '#/components/schemas/KeyClient'+ CreateKeyRequest:+ type: object+ required:+ - name+ - namespace+ properties:+ name:+ type: string+ example: ci-prod+ namespace:+ type: string+ example: test-pool+ CreateKeyResponse:+ type: object+ properties:+ client_id:+ type: string+ client_secret:+ type: string+ name:+ type: string+ namespace:+ type: string+ token_url:+ type: string+ Action:+ type: object+ required:+ - action_type+ properties:+ action_type:+ type: string+ description: OSGym action type (e.g. CLICK, TYPE, KEY).+ example: CLICK+ parameters:+ type: object+ additionalProperties: true+ description: Action-type-specific parameters (e.g. `{x, y, button}` for+ CLICK).+ RunConfig:+ type: object+ required:+ - steps+ properties:+ steps:+ type: array+ description: 'Ordered actions to execute on the rollout VM. A step with+ `action_type: "RESET"` is a reserved control action: instead of being+ forwarded to the VM, it hard-resets the VM in place (new vm_id, clean+ baseline desktop), so one run can execute several independent episodes+ on a warm instance.'+ items:+ $ref: '#/components/schemas/Action'+ maxItems: 10000+ timeout:+ type: integer+ minimum: 0+ maximum: 86400+ description: Per-rollout timeout in seconds (max 24h).+ vm_id:+ type: string+ description: Reattach this run to an existing warm VM (instance reuse /+ "lane"), typically a vm_id returned by a previous `keep_warm` batch, instead+ of acquiring a fresh one. If that claim has already expired, the run transparently+ falls back to a fresh VM.+ BatchSubmitRequest:+ type: object+ required:+ - runs+ properties:+ runs:+ type: array+ items:+ $ref: '#/components/schemas/RunConfig'+ maxItems: 10000+ concurrency:+ type: integer+ default: 10+ minimum: 1+ maximum: 1000+ pool_name:+ type: string+ description: Optional — must match the URL `{pool}` if provided; ignored+ otherwise.+ name:+ type: string+ description: Optional batch name. Overridden by the URL `{label}` on label+ routes.+ maxLength: 256+ keep_warm:+ type: boolean+ description: 'Leave each run''s VM running when the run ends (instead of+ shutting it down), so a follow-up batch can reattach to it via RunConfig.vm_id+ (read each lane''s surviving id from RunResult.vm_id). Best-effort: a+ warm VM is reaped after its claim TTL (~minutes), after which reattach+ falls back to a fresh VM.'+ BatchSubmitResponse:+ type: object+ properties:+ batch_id:+ type: string+ name:+ type: string+ status:+ type: string+ created_at:+ type: string+ format: date-time+ AcquireLanesRequest:+ type: object+ required:+ - n+ properties:+ n:+ type: integer+ minimum: 1+ maximum: 1000+ description: Number of warm VM lanes to acquire.+ AcquireLanesResponse:+ type: object+ properties:+ vm_ids:+ type: array+ description: One warm VM id per acquired lane. Use as RunConfig.vm_id.+ items:+ type: string+ ReleaseLanesRequest:+ type: object+ required:+ - vm_ids+ properties:+ vm_ids:+ type: array+ description: VM ids to shut down (lanes to release).+ items:+ type: string+ ReleaseLanesResponse:+ type: object+ properties:+ released:+ type: integer+ description: Number of vm_ids submitted for release.+ BatchProgress:+ type: object+ properties:+ completed:+ type: integer+ total:+ type: integer+ ok:+ type: integer+ failed:+ type: integer+ BatchStatusResponse:+ type: object+ properties:+ batch_id:+ type: string+ name:+ type: string+ status:+ type: string+ progress:+ $ref: '#/components/schemas/BatchProgress'+ created_at:+ type: string+ format: date-time+ updated_at:+ type: string+ format: date-time+ BatchInProgressResponse:+ type: object+ properties:+ batch_id:+ type: string+ status:+ type: string+ message:+ type: string+ CancelBatchResponse:+ type: object+ properties:+ batch_id:+ type: string+ status:+ type: string+ TimingStats:+ type: object+ properties:+ n:+ type: integer+ min:+ type: integer+ format: int64+ mean:+ type: number+ format: double+ max:+ type: integer+ format: int64+ BatchSummary:+ type: object+ properties:+ n_ok:+ type: integer+ n_fail:+ type: integer+ total_wall_ms:+ type: integer+ format: int64+ reset_stats:+ $ref: '#/components/schemas/TimingStats'+ step_stats:+ $ref: '#/components/schemas/TimingStats'+ shutdown_stats:+ $ref: '#/components/schemas/TimingStats'+ RunResult:+ type: object+ properties:+ run_id:+ type: integer+ vm_id:+ type: string+ ok:+ type: boolean+ error:+ type: string+ reset_ms:+ type: integer+ format: int64+ step_ms:+ type: array+ items:+ type: integer+ format: int64+ shutdown_ms:+ type: integer+ format: int64+ actions:+ type: array+ items:+ type: string+ screenshots:+ type: array+ items:+ type: string+ BatchResultsResponse:+ type: object+ properties:+ batch_id:+ type: string+ name:+ type: string+ status:+ type: string+ runs:+ type: array+ items:+ $ref: '#/components/schemas/RunResult'+ s3_bucket:+ type: string+ s3_key:+ type: string+ s3_presigned_url:+ type: string+ summary:+ $ref: '#/components/schemas/BatchSummary'+ LabelBatchSummary:+ type: object+ properties:+ batch_id:+ type: string+ status:+ type: string+ progress:+ $ref: '#/components/schemas/BatchProgress'+ created_at:+ type: string+ format: date-time+ updated_at:+ type: string+ format: date-time+ s3_key:+ type: string+ s3_presigned_url:+ type: string+ LabelStatusResponse:+ type: object+ properties:+ label:+ type: string+ batch_count:+ type: integer+ all_completed:+ type: boolean+ progress:+ $ref: '#/components/schemas/BatchProgress'+ batches:+ type: array+ items:+ $ref: '#/components/schemas/LabelBatchSummary'+ LabelInProgressResponse:+ type: object+ properties:+ label:+ type: string+ batch_count:+ type: integer+ all_completed:+ type: boolean+ message:+ type: string+ LabelResultsResponse:+ type: object+ properties:+ label:+ type: string+ batch_count:+ type: integer+ completed_batch_count:+ type: integer+ all_completed:+ type: boolean+ batches:+ type: array+ items:+ $ref: '#/components/schemas/BatchResultsResponse'+ summary:+ $ref: '#/components/schemas/BatchSummary'+ CancelLabelBatchItem:+ type: object+ properties:+ batch_id:+ type: string+ status:+ type: string+ CancelLabelResponse:+ type: object+ properties:+ label:+ type: string+ batch_count:+ type: integer+ cancelled_count:+ type: integer+ already_done:+ type: integer+ batches:+ type: array+ items:+ $ref: '#/components/schemas/CancelLabelBatchItem'+ HealthzResponse:+ properties:+ status:+ type: string+ title: Status+ type: object+ required:+ - status+ title: HealthzResponse+ LaneCreateRequest:+ properties:+ ttl_seconds:+ type: integer+ title: Ttl Seconds+ default: 300+ type: object+ title: LaneCreateRequest+ description: 'Body of POST /lanes.+++ ``ttl_seconds`` is the absolute time the claim is reserved for;++ after that the reaper deletes it. With ``autoRenew=true`` the lane++ auto-renew timer in pool-operator pushes this forward, so the++ customer''s effective TTL is "as long as the lane exists".'+ LaneDeleteResponse:+ properties:+ lane_id:+ type: string+ title: Lane Id+ type: object+ required:+ - lane_id+ title: LaneDeleteResponse+ LaneResponse:+ properties:+ lane_id:+ type: string+ title: Lane Id+ vm_id:+ type: string+ title: Vm Id+ screenshot:+ anyOf:+ - type: string+ - type: 'null'+ title: Screenshot+ type: object+ required:+ - lane_id+ - vm_id+ title: LaneResponse+ LaneSwapResponse:+ properties:+ lane_id:+ type: string+ title: Lane Id+ vm_id:+ type: string+ title: Vm Id+ wait_seconds:+ type: number+ title: Wait Seconds+ type: object+ required:+ - lane_id+ - vm_id+ - wait_seconds+ title: LaneSwapResponse+ PoolListResponse:+ properties:+ vms:+ items:+ additionalProperties: true+ type: object+ type: array+ title: Vms+ count:+ type: integer+ title: Count+ type: object+ required:+ - vms+ - count+ title: PoolListResponse+ ResetRequest:+ properties:+ task_config:+ additionalProperties: true+ type: object+ title: Task Config+ timeout:+ type: integer+ title: Timeout+ type: object+ required:+ - task_config+ - timeout+ title: ResetRequest+ ResetResponse:+ properties:+ screenshot:+ type: string+ title: Screenshot+ problem:+ type: string+ title: Problem+ vm_id:+ type: string+ title: Vm Id+ type: object+ required:+ - screenshot+ - problem+ - vm_id+ title: ResetResponse+ ScreenshotResponse:+ properties:+ screenshot:+ type: string+ title: Screenshot+ vm_id:+ type: string+ title: Vm Id+ type: object+ required:+ - screenshot+ - vm_id+ title: ScreenshotResponse+ ShutdownRequest:+ properties:+ vm_id:+ type: string+ title: Vm Id+ type: object+ required:+ - vm_id+ title: ShutdownRequest+ ShutdownResponse:+ properties:+ vm_id:+ type: string+ title: Vm Id+ type: object+ required:+ - vm_id+ title: ShutdownResponse+ StepRequest:+ properties:+ action:+ type: string+ title: Action+ vm_id:+ type: string+ title: Vm Id+ timeout:+ type: integer+ title: Timeout+ default: 300+ type: object+ required:+ - action+ - vm_id+ title: StepRequest+ StepResponse:+ properties:+ screenshot:+ anyOf:+ - type: string+ - type: 'null'+ title: Screenshot+ is_finish:+ type: boolean+ title: Is Finish+ reward:+ type: number+ title: Reward+ type: object+ required:+ - screenshot+ - is_finish+ - reward+ title: StepResponse+ LaneErrorResponse:+ properties:+ message:+ anyOf:+ - type: string+ - type: 'null'+ title: Message+ reason:+ anyOf:+ - type: string+ - type: 'null'+ title: Reason+ lane_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Lane Id+ type: object+ title: ErrorResponsediff --git a/libs/fleet/python-sdk/package.nix b/libs/fleet/python-sdk/package.nixnew file mode 100644index 0000000000..19a7e53785--- /dev/null+++ b/libs/fleet/python-sdk/package.nix@@ -0,0 +1,134 @@+# Nix package for the cua-train Python SDK.+#+# Single-step build:+# 1. Import the osgym FastAPI app (fake backend) → dump openapi.json+# 2. Merge lane endpoints into parent openapi3.yaml+# 3. Regenerate api/ + models/ with openapi-python-client+# 4. Format with ruff+# 5. Build the wheel+#+# Usage:+# nix build .#cua-train-sdk+# pip install result/*.whl+{+ pkgs,+ lib ? pkgs.lib,+ # Build against a caller-supplied interpreter so consumers (e.g. the+ # cua-temporal-agent worker env) can keep the package on the same Python as+ # the rest of their closure. Defaults to 3.12 for the standalone `nix build`.+ python ? pkgs.python312,+}:++let+ pp = python.pkgs;++ osgymSrc = builtins.path {+ path = ../../osgym;+ name = "osgym-src";+ };++ # Python with deps needed to import the osgym FastAPI app (fake backend)+ # AND to run the merge script.+ genPython = python.withPackages (+ ps: with ps; [+ fastapi+ pydantic+ uvicorn+ aiohttp+ prometheus-client+ kubernetes+ pyyaml+ ruff+ ]+ );++in+pp.buildPythonPackage {+ pname = "cua-train";+ version = "0.1.0";+ pyproject = true;++ src = builtins.path {+ path = ./.;+ name = "cua-train-sdk-src";+ filter =+ path: type:+ let+ base = builtins.baseNameOf path;+ in+ !(+ base == ".venv"+ || base == "__pycache__"+ || base == "dist"+ || base == ".pytest_cache"+ || lib.hasSuffix ".egg-info" base+ );+ };++ build-system = [ pp.hatchling ];++ nativeBuildInputs = [+ genPython+ pkgs.openapi-python-client+ ];++ dependencies = with pp; [+ httpx+ attrs+ python-dateutil+ ];++ preBuild = ''+ echo "==> Generating orchestrator OpenAPI spec"+ PYTHONPATH="${osgymSrc}" \+ OSGYM_POOL_BACKEND=fake \+ OSGYM_ALLOWED_IPS=0.0.0.0/0 \+ ${genPython}/bin/python -c "+ import json, sys, io++ # Suppress all stdout noise from osgym imports (log messages, banners)+ real_stdout = sys.stdout+ sys.stdout = io.StringIO()+ try:+ # Lanes were decoupled out of the orchestrator (osgym #4953), so the+ # old \`from lane_endpoints import register\` no longer exists. The lane+ # paths now live in the committed openapi3.yaml (the merge below only+ # ADDS osgym paths, never drops the parent's), so plain app.openapi()+ # is the correct spec source.+ from main import app+ spec = app.openapi()+ finally:+ sys.stdout = real_stdout++ json.dump(spec, sys.stdout, indent=2)+ " > /tmp/orch-spec.json+ echo " Spec: $(wc -l < /tmp/orch-spec.json) lines"+ test -s /tmp/orch-spec.json || { echo "FATAL: empty spec"; exit 1; }++ echo "==> Merging lane endpoints"+ cat /tmp/orch-spec.json | head -3+ ${genPython}/bin/python scripts/merge_orchestrator_spec.py \+ --parent openapi3.yaml \+ --orchestrator /tmp/orch-spec.json \+ --output openapi3.yaml++ echo "==> Regenerating SDK"+ openapi-python-client update --path openapi3.yaml || true # lint-ignore: error-masking — may fail on first run++ echo "==> Formatting"+ ${genPython}/bin/python -m ruff check --fix cua_train/ 2>/dev/null || true # lint-ignore: error-masking — best-effort autofix+ ${genPython}/bin/python -m ruff format cua_train/+ '';++ nativeCheckInputs = with pp; [+ pytestCheckHook+ pytest-httpx+ ];++ pythonImportsCheck = [ "cua_train" ];++ meta = {+ description = "Python SDK for the CUA training / batch backend API";+ license = lib.licenses.mit;+ };+}diff --git a/libs/fleet/python-sdk/pyproject.toml b/libs/fleet/python-sdk/pyproject.tomlnew file mode 100644index 0000000000..c554822f59--- /dev/null+++ b/libs/fleet/python-sdk/pyproject.toml@@ -0,0 +1,37 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[project]+name = "cua-train"+version = "0.1.0"+description = "Python SDK for the CUA training / batch backend API — generated from OpenAPI spec."+readme = "README.md"+license = { text = "MIT" }+authors = [{ name = "TryCua", email = "[email protected]" }]+requires-python = ">=3.10"+dependencies = [+ "httpx>=0.23.0",+ "attrs>=22.2.0",+ "python-dateutil>=2.8.0",+]++[project.urls]+Repository = "https://github.com/trycua/cloud"+"Issue Tracker" = "https://github.com/trycua/cloud/issues"++[tool.hatch.build.targets.wheel]+packages = ["cua_train"]++[project.optional-dependencies]+dev = [+ "pytest>=7.0",+ "pytest-httpx>=0.30.0",+ "ruff>=0.6",+]++[tool.ruff]+line-length = 120++[tool.ruff.lint]+select = ["F", "I", "UP"]diff --git a/libs/fleet/python-sdk/scripts/generate.sh b/libs/fleet/python-sdk/scripts/generate.shnew file mode 100755index 0000000000..a960d5d9e5--- /dev/null+++ b/libs/fleet/python-sdk/scripts/generate.sh@@ -0,0 +1,54 @@+#!/usr/bin/env bash+# Generate the cua_train SDK from the osgym orchestrator's OpenAPI spec.+#+# Usage:+# ./scripts/generate.sh+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+SDK_DIR="$(dirname "$SCRIPT_DIR")"+OSGYM_DIR="$(cd "$SDK_DIR/../../osgym" && pwd)"++# Bootstrap: re-exec inside nix-shell with a proper Python environment+if [ -z "${IN_NIX_SHELL:-}" ]; then+ exec nix-shell --pure -E '+ let pkgs = import <nixpkgs> {};+ python = pkgs.python312.withPackages (ps: with ps; [+ fastapi pydantic uvicorn aiohttp prometheus-client+ kubernetes pyyaml ruff+ ]);+ in pkgs.mkShell {+ buildInputs = [ python pkgs.openapi-python-client ];+ shellHook = "export IN_NIX_SHELL=1";+ }+ ' --run "bash $0"+fi++echo "==> Step 1: Generate orchestrator OpenAPI spec"+ORCH_SPEC=$(mktemp /tmp/osgym-openapi-XXXXXX.json)+PYTHONPATH="$OSGYM_DIR" \+ OSGYM_POOL_BACKEND=fake \+ OSGYM_ALLOWED_IPS=0.0.0.0/0 \+ python3 -c "+import json+from main import app+print(json.dumps(app.openapi(), indent=2))+" > "$ORCH_SPEC"+echo " Wrote $ORCH_SPEC ($(wc -l < "$ORCH_SPEC") lines)"++echo "==> Step 2: Merge lane endpoints into parent openapi3.yaml"+python3 "$SCRIPT_DIR/merge_orchestrator_spec.py" \+ --parent "$SDK_DIR/openapi3.yaml" \+ --orchestrator "$ORCH_SPEC" \+ --output "$SDK_DIR/openapi3.yaml"++echo "==> Step 3: Regenerate Python SDK"+cd "$SDK_DIR"+openapi-python-client update --path openapi3.yaml || true # lint-ignore: error-masking — may fail on first run++echo "==> Step 4: Format"+python3 -m ruff check --fix cua_train/ 2>/dev/null || true # lint-ignore: error-masking — best-effort autofix+python3 -m ruff format cua_train/++rm -f "$ORCH_SPEC"+echo "==> Done. Review changes with: git diff cyclops-cs/python-sdk/"diff --git a/libs/fleet/python-sdk/scripts/merge_orchestrator_spec.py b/libs/fleet/python-sdk/scripts/merge_orchestrator_spec.pynew file mode 100644index 0000000000..6a59862a7d--- /dev/null+++ b/libs/fleet/python-sdk/scripts/merge_orchestrator_spec.py@@ -0,0 +1,123 @@+#!/usr/bin/env python3+"""Merge the osgym orchestrator's OpenAPI spec into the parent SDK spec.++Rewrites orchestrator paths like /lanes → /api/gateway/{pool}/lanes+and adds a {pool} path parameter. Merges schemas into components.+Only merges /lanes endpoints (not /reset, /step, etc. which are+already covered by the batch driver).+"""+import argparse+import copy+import json+import sys++import yaml+++# Paths from the orchestrator to include (prefix match)+INCLUDE_PREFIXES = ["/lanes"]++# Schemas to always skip (already in parent or not needed)+SKIP_SCHEMAS = {"HTTPValidationError", "ValidationError"}+++def rewrite_path(path: str) -> str:+ """Rewrite /lanes/... → /api/gateway/{pool}/lanes/..."""+ return f"/api/gateway/{{pool}}{path}"+++def add_pool_param(operation: dict) -> None:+ """Add {pool} path parameter to an operation if not present."""+ params = operation.setdefault("parameters", [])+ if any(p.get("name") == "pool" for p in params):+ return+ params.insert(0, {+ "name": "pool",+ "in": "path",+ "required": True,+ "schema": {"type": "string"},+ "description": "Pool name (DNS-1123 label)",+ })+++def fix_ref(obj, old_prefix="#/components/schemas/", renames=None):+ """Recursively fix $ref pointers after schema renames."""+ if isinstance(obj, dict):+ if "$ref" in obj:+ ref = obj["$ref"]+ if ref.startswith(old_prefix) and renames:+ schema_name = ref[len(old_prefix):]+ if schema_name in renames:+ obj["$ref"] = f"{old_prefix}{renames[schema_name]}"+ for v in obj.values():+ fix_ref(v, old_prefix, renames)+ elif isinstance(obj, list):+ for item in obj:+ fix_ref(item, old_prefix, renames)+++def merge(parent_path: str, orch_path: str, output_path: str) -> None:+ with open(parent_path) as f:+ parent = yaml.safe_load(f)+ with open(orch_path) as f:+ orch = json.load(f)++ orch_paths = orch.get("paths", {})+ orch_schemas = orch.get("components", {}).get("schemas", {})++ # Determine which schemas are referenced by included paths+ included_paths = {}+ for path, methods in orch_paths.items():+ if not any(path.startswith(p) for p in INCLUDE_PREFIXES):+ continue+ included_paths[path] = methods++ # Rename schemas with module prefixes (e.g. lane_endpoints__ErrorResponse → LaneErrorResponse)+ renames = {}+ for name in orch_schemas:+ if "__" in name:+ # lane_endpoints__ErrorResponse → LaneErrorResponse+ new_name = name.split("__")[-1]+ # Prefix with "Lane" if it would conflict+ if new_name in orch_schemas and new_name != name:+ new_name = f"Lane{new_name}"+ renames[name] = new_name++ # Add rewritten paths to parent+ parent_paths = parent.setdefault("paths", {})+ for path, methods in included_paths.items():+ new_path = rewrite_path(path)+ methods = copy.deepcopy(methods)+ for method, operation in methods.items():+ if isinstance(operation, dict):+ add_pool_param(operation)+ # Tag as "lanes" for SDK grouping+ operation["tags"] = ["lanes"]+ fix_ref(operation, renames=renames)+ parent_paths[new_path] = methods++ # Add schemas to parent+ parent_schemas = parent.setdefault("components", {}).setdefault("schemas", {})+ for name, schema in orch_schemas.items():+ if name in SKIP_SCHEMAS:+ continue+ final_name = renames.get(name, name)+ if final_name not in parent_schemas:+ schema = copy.deepcopy(schema)+ fix_ref(schema, renames=renames)+ parent_schemas[final_name] = schema++ with open(output_path, "w") as f:+ yaml.dump(parent, f, default_flow_style=False, sort_keys=False, allow_unicode=True)++ added = len(included_paths)+ print(f" Merged {added} path(s), {len(orch_schemas) - len(SKIP_SCHEMAS)} schema(s)")+++if __name__ == "__main__":+ p = argparse.ArgumentParser()+ p.add_argument("--parent", required=True)+ p.add_argument("--orchestrator", required=True)+ p.add_argument("--output", required=True)+ args = p.parse_args()+ merge(args.parent, args.orchestrator, args.output)diff --git a/libs/fleet/python-sdk/tests/__init__.py b/libs/fleet/python-sdk/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/libs/fleet/python-sdk/tests/test_endpoints.py b/libs/fleet/python-sdk/tests/test_endpoints.pynew file mode 100644index 0000000000..3efa39dfed--- /dev/null+++ b/libs/fleet/python-sdk/tests/test_endpoints.py@@ -0,0 +1,672 @@+"""+Parametrized tests for every endpoint in the cyclops-cs SDK.++Uses pytest-httpx to intercept httpx calls so no real server is needed.+Each endpoint has three test categories:+ - base: happy-path / golden response+ - error: 4xx responses parsed into ErrorResponse+ - generated: edge-case parameter variants+"""++import pytest+from pytest_httpx import HTTPXMock++from cua_train import TrainClient+from cua_train.api.batch import cancel_batch, get_batch_results, get_batch_status, submit_batch+from cua_train.api.health import healthz+from cua_train.api.keys import create_key, delete_key, list_keys+from cua_train.api.label import cancel_label, get_label_results, get_label_status, submit_label_batch+from cua_train.client import AuthenticatedClient, Client+from cua_train.models import (+ Action,+ ActionParameters,+ BatchInProgressResponse,+ BatchResultsResponse,+ BatchStatusResponse,+ BatchSubmitRequest,+ BatchSubmitResponse,+ CancelBatchResponse,+ CancelLabelResponse,+ CreateKeyRequest,+ CreateKeyResponse,+ ErrorResponse,+ HealthResponse,+ LabelInProgressResponse,+ LabelResultsResponse,+ LabelStatusResponse,+ ListKeysResponse,+ RunConfig,+)++BASE_URL = "https://cyclops-cs.trycua.com"+TOKEN = "test-bearer-token"+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def anon_client() -> Client:+ return Client(base_url=BASE_URL, raise_on_unexpected_status=True)+++def auth_client() -> AuthenticatedClient:+ # TrainClient is a drop-in AuthenticatedClient that also exposes every+ # generated endpoint as a method; using it here exercises both the low-level+ # api.* calls (client=auth_client) and the generic facade (auth_client.<op>).+ return TrainClient(base_url=BASE_URL, token=TOKEN, raise_on_unexpected_status=True)+++def test_train_client_refreshes_token(httpx_mock: HTTPXMock):+ """from_key mints a token, then get_httpx_client() transparently re-mints it+ once it's near expiry — no caller involvement."""+ token_ep = "https://auth.example/realms/x/token"+ # First exchange returns an already-stale token (expires_in=0).+ httpx_mock.add_response(method="POST", url=token_ep, json={"access_token": "t1", "expires_in": 0})+ c = TrainClient.from_key(token_url=token_ep, client_id="key-x", client_secret="s", base_url=BASE_URL)+ assert c.token == "t1"++ # Next use refreshes (deadline already passed) and bakes the new bearer.+ httpx_mock.add_response(method="POST", url=token_ep, json={"access_token": "t2", "expires_in": 300})+ client = c.get_httpx_client()+ assert c.token == "t2"+ assert client.headers["Authorization"] == "Bearer t2"+++# ---------------------------------------------------------------------------+# /healthz+# ---------------------------------------------------------------------------+++class TestHealthz:+ def test_base_ok(self, httpx_mock: HTTPXMock, anon_client):+ """Golden: healthz returns 200 {ok: true}."""+ httpx_mock.add_response(+ method="GET",+ url=f"{BASE_URL}/healthz",+ status_code=200,+ json={"ok": True},+ )+ resp = healthz.sync_detailed(client=anon_client)+ assert resp.status_code.value == 200+ assert isinstance(resp.parsed, HealthResponse)+ assert resp.parsed.ok is True++ def test_base_degraded(self, httpx_mock: HTTPXMock, anon_client):+ """Edge: ok=false still parses cleanly."""+ httpx_mock.add_response(+ method="GET",+ url=f"{BASE_URL}/healthz",+ status_code=200,+ json={"ok": False},+ )+ assert healthz.sync_detailed(client=anon_client).parsed.ok is False++ def test_unexpected_status(self, httpx_mock: HTTPXMock, anon_client):+ """Error: unexpected 503 raises when raise_on_unexpected_status=True."""+ httpx_mock.add_response(+ method="GET", url=f"{BASE_URL}/healthz", status_code=503, json={"error": "svc unavailable"}+ )+ from cua_train import errors++ with pytest.raises(errors.UnexpectedStatus):+ healthz.sync_detailed(client=anon_client)+++# ---------------------------------------------------------------------------+# /api/keys GET+# ---------------------------------------------------------------------------+++GOLDEN_KEY = {+ "id": "kc-uuid-1",+ "client_id": "key-abc123",+ "name": "ci-prod",+ "namespace": "test-pool",+ "owner_sub": "user-sub-1",+}+++class TestListKeys:+ def test_base(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(method="GET", url=f"{BASE_URL}/api/keys", status_code=200, json={"keys": [GOLDEN_KEY]})+ resp = list_keys.sync_detailed(client=auth_client)+ assert resp.status_code.value == 200+ assert isinstance(resp.parsed, ListKeysResponse)+ assert len(resp.parsed.keys) == 1+ assert resp.parsed.keys[0].name == "ci-prod"++ def test_empty_list(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(method="GET", url=f"{BASE_URL}/api/keys", status_code=200, json={"keys": []})+ assert list_keys.sync_detailed(client=auth_client).parsed.keys == []++ def test_unauthorized(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET", url=f"{BASE_URL}/api/keys", status_code=401, json={"error": "unauthorized"}+ )+ resp = list_keys.sync_detailed(client=auth_client)+ assert resp.status_code.value == 401+ assert isinstance(resp.parsed, ErrorResponse)+++# ---------------------------------------------------------------------------+# /api/keys POST+# ---------------------------------------------------------------------------+++class TestCreateKey:+ @pytest.mark.parametrize(+ "name,namespace",+ [+ ("ci-prod", "test-pool"),+ ("my-key", "default"),+ ("key-with-dashes", "namespace-123"),+ ],+ )+ def test_base(self, httpx_mock: HTTPXMock, auth_client, name, namespace):+ httpx_mock.add_response(+ method="POST",+ url=f"{BASE_URL}/api/keys",+ status_code=201,+ json={+ "client_id": f"key-{name}",+ "client_secret": "super-secret",+ "name": name,+ "namespace": namespace,+ "token_url": "https://auth.example.com/token",+ },+ )+ resp = create_key.sync_detailed(client=auth_client, body=CreateKeyRequest(name=name, namespace=namespace))+ assert resp.status_code.value == 201+ assert isinstance(resp.parsed, CreateKeyResponse)+ assert resp.parsed.client_secret == "super-secret"++ def test_bad_request(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="POST", url=f"{BASE_URL}/api/keys", status_code=400, json={"error": "name is required"}+ )+ resp = create_key.sync_detailed(client=auth_client, body=CreateKeyRequest(name="", namespace="pool"))+ assert resp.status_code.value == 400+ assert isinstance(resp.parsed, ErrorResponse)++ def test_forbidden(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="POST", url=f"{BASE_URL}/api/keys", status_code=403, json={"error": "key limit reached"}+ )+ resp = create_key.sync_detailed(client=auth_client, body=CreateKeyRequest(name="extra", namespace="pool"))+ assert resp.status_code.value == 403+++# ---------------------------------------------------------------------------+# /api/keys/{id} DELETE+# ---------------------------------------------------------------------------+++class TestDeleteKey:+ @pytest.mark.parametrize("key_id", ["kc-uuid-1", "kc-uuid-2", "00000000-0000-0000-0000-000000000000"])+ def test_base(self, httpx_mock: HTTPXMock, auth_client, key_id):+ httpx_mock.add_response(method="DELETE", url=f"{BASE_URL}/api/keys/{key_id}", status_code=204)+ assert delete_key.sync_detailed(id=key_id, client=auth_client).status_code.value == 204++ def test_forbidden(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="DELETE", url=f"{BASE_URL}/api/keys/other-uuid", status_code=403, json={"error": "not your key"}+ )+ assert delete_key.sync_detailed(id="other-uuid", client=auth_client).status_code.value == 403+++# ---------------------------------------------------------------------------+# /api/batch/{pool}/submit POST+# ---------------------------------------------------------------------------+++GOLDEN_SUBMIT_RESP = {+ "batch_id": "batch-abc",+ "name": "my-batch",+ "status": "queued",+ "created_at": "2026-05-01T00:00:00Z",+}+GOLDEN_RUN = RunConfig(+ steps=[Action(action_type="CLICK", parameters=ActionParameters.from_dict({"x": 1, "y": 2}))],+ timeout=60,+)+++class TestSubmitBatch:+ @pytest.mark.parametrize(+ "pool,concurrency",+ [+ ("test-pool", 1),+ ("prod-pool", 10),+ ("staging", 50),+ ],+ )+ def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, concurrency):+ httpx_mock.add_response(+ method="POST", url=f"{BASE_URL}/api/batch/{pool}/submit", status_code=202, json=GOLDEN_SUBMIT_RESP+ )+ resp = submit_batch.sync_detailed(+ pool=pool, client=auth_client, body=BatchSubmitRequest(runs=[GOLDEN_RUN], concurrency=concurrency)+ )+ assert resp.status_code.value == 202+ assert isinstance(resp.parsed, BatchSubmitResponse)+ assert resp.parsed.batch_id == "batch-abc"++ def test_bad_request_empty_runs(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="POST",+ url=f"{BASE_URL}/api/batch/pool/submit",+ status_code=400,+ json={"error": "runs must not be empty"},+ )+ resp = submit_batch.sync_detailed(pool="pool", client=auth_client, body=BatchSubmitRequest(runs=[]))+ assert resp.status_code.value == 400+ assert isinstance(resp.parsed, ErrorResponse)++ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="POST", url=f"{BASE_URL}/api/label/test-pool/my-run/batch", status_code=202, json=GOLDEN_SUBMIT_RESP+ )+ result = auth_client.submit_label_batch(+ pool="test-pool", label="my-run", body=BatchSubmitRequest(runs=[GOLDEN_RUN])+ )+ assert isinstance(result, BatchSubmitResponse)+++# ---------------------------------------------------------------------------+# /api/batch/{pool}/{id}/status GET+# ---------------------------------------------------------------------------+++GOLDEN_BATCH_STATUS = {+ "batch_id": "batch-abc",+ "name": "my-batch",+ "status": "running",+ "progress": {"completed": 3, "total": 10, "ok": 2, "failed": 1},+ "created_at": "2026-05-01T00:00:00Z",+ "updated_at": "2026-05-01T00:05:00Z",+}+++class TestGetBatchStatus:+ def test_base(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET",+ url=f"{BASE_URL}/api/batch/test-pool/batch-abc/status",+ status_code=200,+ json=GOLDEN_BATCH_STATUS,+ )+ resp = get_batch_status.sync_detailed(pool="test-pool", id="batch-abc", client=auth_client)+ assert resp.status_code.value == 200+ assert isinstance(resp.parsed, BatchStatusResponse)+ assert resp.parsed.status == "running"++ def test_not_found(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET",+ url=f"{BASE_URL}/api/batch/test-pool/unknown/status",+ status_code=404,+ json={"error": "batch not found"},+ )+ resp = get_batch_status.sync_detailed(pool="test-pool", id="unknown", client=auth_client)+ assert resp.status_code.value == 404+ assert isinstance(resp.parsed, ErrorResponse)++ @pytest.mark.parametrize("status_val", ["queued", "running", "completed", "failed", "cancelled"])+ def test_all_statuses(self, httpx_mock: HTTPXMock, auth_client, status_val):+ body = {**GOLDEN_BATCH_STATUS, "status": status_val}+ httpx_mock.add_response(+ method="GET", url=f"{BASE_URL}/api/batch/pool/batch-abc/status", status_code=200, json=body+ )+ resp = get_batch_status.sync_detailed(pool="pool", id="batch-abc", client=auth_client)+ assert resp.parsed.status == status_val++ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET", url=f"{BASE_URL}/api/label/pool/test-label/status", status_code=200, json=GOLDEN_LABEL_STATUS+ )+ result = auth_client.get_label_status(pool="pool", label="test-label")+ assert isinstance(result, LabelStatusResponse)+++# ---------------------------------------------------------------------------+# /api/batch/{pool}/{id}/results GET+# ---------------------------------------------------------------------------+++GOLDEN_BATCH_RESULTS = {+ "batch_id": "batch-abc",+ "name": "my-batch",+ "status": "completed",+ "runs": [+ {+ "run_id": 1,+ "vm_id": "vm-1",+ "ok": True,+ "reset_ms": 100,+ "step_ms": [200],+ "shutdown_ms": 50,+ "actions": [],+ "screenshots": [],+ }+ ],+ "s3_bucket": "my-bucket",+ "s3_key": "results/batch-abc.json",+ "s3_presigned_url": "https://s3.example.com/presigned",+ "summary": {+ "n_ok": 1,+ "n_fail": 0,+ "total_wall_ms": 350,+ "reset_stats": {"n": 1, "min": 100, "mean": 100.0, "max": 100},+ "step_stats": {"n": 1, "min": 200, "mean": 200.0, "max": 200},+ "shutdown_stats": {"n": 1, "min": 50, "mean": 50.0, "max": 50},+ },+}+++class TestGetBatchResults:+ def test_base_completed(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET", url=f"{BASE_URL}/api/batch/pool/batch-abc/results", status_code=200, json=GOLDEN_BATCH_RESULTS+ )+ resp = get_batch_results.sync_detailed(pool="pool", id="batch-abc", client=auth_client)+ assert resp.status_code.value == 200+ assert isinstance(resp.parsed, BatchResultsResponse)+ assert resp.parsed.status == "completed"++ def test_in_progress_202(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET",+ url=f"{BASE_URL}/api/batch/pool/batch-abc/results",+ status_code=202,+ json={"batch_id": "batch-abc", "status": "running", "message": "batch still running"},+ )+ resp = get_batch_results.sync_detailed(pool="pool", id="batch-abc", client=auth_client)+ assert resp.status_code.value == 202+ assert isinstance(resp.parsed, BatchInProgressResponse)++ def test_not_found(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET", url=f"{BASE_URL}/api/batch/pool/unknown/results", status_code=404, json={"error": "not found"}+ )+ assert get_batch_results.sync_detailed(pool="pool", id="unknown", client=auth_client).status_code.value == 404++ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET", url=f"{BASE_URL}/api/label/pool/lbl/results", status_code=200, json=GOLDEN_LABEL_RESULTS+ )+ result = auth_client.get_label_results(pool="pool", label="lbl")+ assert isinstance(result, LabelResultsResponse)+++# ---------------------------------------------------------------------------+# /api/batch/{pool}/{id} DELETE+# ---------------------------------------------------------------------------+++class TestCancelBatch:+ @pytest.mark.parametrize(+ "pool,id,expected_status",+ [+ ("test-pool", "batch-abc", "cancelling"),+ ("prod-pool", "batch-xyz", "completed"),+ ("staging", "batch-999", "cancelled"),+ ],+ )+ def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, id, expected_status):+ httpx_mock.add_response(+ method="DELETE",+ url=f"{BASE_URL}/api/batch/{pool}/{id}",+ status_code=200,+ json={"batch_id": id, "status": expected_status},+ )+ resp = cancel_batch.sync_detailed(pool=pool, id=id, client=auth_client)+ assert resp.status_code.value == 200+ assert isinstance(resp.parsed, CancelBatchResponse)+ assert resp.parsed.status == expected_status++ def test_not_found(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="DELETE", url=f"{BASE_URL}/api/batch/pool/unknown", status_code=404, json={"error": "not found"}+ )+ assert cancel_batch.sync_detailed(pool="pool", id="unknown", client=auth_client).status_code.value == 404++ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="DELETE", url=f"{BASE_URL}/api/label/pool/test-label", status_code=200, json=GOLDEN_CANCEL_LABEL+ )+ result = auth_client.cancel_label(pool="pool", label="test-label")+ assert isinstance(result, CancelLabelResponse)+++# ---------------------------------------------------------------------------+# /api/label/{pool}/{label}/batch POST+# ---------------------------------------------------------------------------+++class TestSubmitLabelBatch:+ @pytest.mark.parametrize(+ "pool,label,concurrency",+ [+ ("test-pool", "test-label", 1),+ ("prod-pool", "prod-run-2026-05-20", 10),+ ("staging", "label-with-dashes", 50),+ ],+ )+ def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, label, concurrency):+ resp_body = {**GOLDEN_SUBMIT_RESP, "name": label}+ httpx_mock.add_response(+ method="POST", url=f"{BASE_URL}/api/label/{pool}/{label}/batch", status_code=202, json=resp_body+ )+ resp = submit_label_batch.sync_detailed(+ pool=pool,+ label=label,+ client=auth_client,+ body=BatchSubmitRequest(runs=[GOLDEN_RUN], concurrency=concurrency),+ )+ assert resp.status_code.value == 202+ assert isinstance(resp.parsed, BatchSubmitResponse)++ def test_bad_request(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="POST",+ url=f"{BASE_URL}/api/label/pool/test/batch",+ status_code=400,+ json={"error": "runs must not be empty"},+ )+ resp = submit_label_batch.sync_detailed(+ pool="pool", label="test", client=auth_client, body=BatchSubmitRequest(runs=[])+ )+ assert resp.status_code.value == 400+ assert isinstance(resp.parsed, ErrorResponse)++ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="POST", url=f"{BASE_URL}/api/label/test-pool/my-run/batch", status_code=202, json=GOLDEN_SUBMIT_RESP+ )+ result = auth_client.submit_label_batch(+ pool="test-pool", label="my-run", body=BatchSubmitRequest(runs=[GOLDEN_RUN])+ )+ assert isinstance(result, BatchSubmitResponse)+++# ---------------------------------------------------------------------------+# /api/label/{pool}/{label}/status GET+# ---------------------------------------------------------------------------+++GOLDEN_LABEL_STATUS = {+ "label": "test-label",+ "batch_count": 2,+ "all_completed": False,+ "progress": {"completed": 5, "total": 10, "ok": 4, "failed": 1},+ "batches": [+ {+ "batch_id": "batch-abc",+ "status": "running",+ "progress": {"completed": 5, "total": 10, "ok": 4, "failed": 1},+ "created_at": "2026-05-01T00:00:00Z",+ "updated_at": "2026-05-01T01:00:00Z",+ }+ ],+}+++class TestGetLabelStatus:+ def test_base(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET",+ url=f"{BASE_URL}/api/label/test-pool/test-label/status",+ status_code=200,+ json=GOLDEN_LABEL_STATUS,+ )+ resp = get_label_status.sync_detailed(pool="test-pool", label="test-label", client=auth_client)+ assert resp.status_code.value == 200+ assert isinstance(resp.parsed, LabelStatusResponse)+ assert resp.parsed.all_completed is False++ def test_all_completed(self, httpx_mock: HTTPXMock, auth_client):+ body = {**GOLDEN_LABEL_STATUS, "all_completed": True}+ httpx_mock.add_response(method="GET", url=f"{BASE_URL}/api/label/pool/done/status", status_code=200, json=body)+ assert (+ get_label_status.sync_detailed(pool="pool", label="done", client=auth_client).parsed.all_completed is True+ )++ def test_not_found(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET",+ url=f"{BASE_URL}/api/label/pool/unknown/status",+ status_code=404,+ json={"error": "label not found"},+ )+ assert get_label_status.sync_detailed(pool="pool", label="unknown", client=auth_client).status_code.value == 404++ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET", url=f"{BASE_URL}/api/label/pool/lbl/status", status_code=200, json=GOLDEN_LABEL_STATUS+ )+ result = auth_client.get_label_status(pool="pool", label="lbl")+ assert isinstance(result, LabelStatusResponse)+++# ---------------------------------------------------------------------------+# /api/label/{pool}/{label}/results GET+# ---------------------------------------------------------------------------+++GOLDEN_LABEL_RESULTS = {+ "label": "test-label",+ "batch_count": 1,+ "completed_batch_count": 1,+ "all_completed": True,+ "batches": [GOLDEN_BATCH_RESULTS],+ "summary": GOLDEN_BATCH_RESULTS["summary"],+}+++class TestGetLabelResults:+ def test_base_completed(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET", url=f"{BASE_URL}/api/label/pool/lbl/results", status_code=200, json=GOLDEN_LABEL_RESULTS+ )+ resp = get_label_results.sync_detailed(pool="pool", label="lbl", client=auth_client)+ assert resp.status_code.value == 200+ assert isinstance(resp.parsed, LabelResultsResponse)+ assert resp.parsed.all_completed is True++ def test_drain_mode(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET",+ url=f"{BASE_URL}/api/label/pool/lbl/results?completed_only=true",+ status_code=200,+ json=GOLDEN_LABEL_RESULTS,+ )+ resp = get_label_results.sync_detailed(pool="pool", label="lbl", client=auth_client, completed_only=True)+ assert resp.status_code.value == 200++ def test_in_progress_202(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET",+ url=f"{BASE_URL}/api/label/pool/lbl/results",+ status_code=202,+ json={"label": "lbl", "batch_count": 1, "all_completed": False, "message": "still running"},+ )+ resp = get_label_results.sync_detailed(pool="pool", label="lbl", client=auth_client)+ assert resp.status_code.value == 202+ assert isinstance(resp.parsed, LabelInProgressResponse)++ @pytest.mark.parametrize(+ "pool,label",+ [+ ("test-pool", "test-label"),+ ("prod-pool", "prod-2026"),+ ("staging", "my-experiment"),+ ],+ )+ def test_generated_pool_label(self, httpx_mock: HTTPXMock, auth_client, pool, label):+ body = {**GOLDEN_LABEL_RESULTS, "label": label}+ httpx_mock.add_response(+ method="GET", url=f"{BASE_URL}/api/label/{pool}/{label}/results", status_code=200, json=body+ )+ resp = get_label_results.sync_detailed(pool=pool, label=label, client=auth_client)+ assert resp.parsed.label == label++ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="GET", url=f"{BASE_URL}/api/label/pool/lbl/results", status_code=200, json=GOLDEN_LABEL_RESULTS+ )+ result = auth_client.get_label_results(pool="pool", label="lbl")+ assert isinstance(result, LabelResultsResponse)+++# ---------------------------------------------------------------------------+# /api/label/{pool}/{label} DELETE+# ---------------------------------------------------------------------------+++GOLDEN_CANCEL_LABEL = {+ "label": "test-label",+ "batch_count": 2,+ "cancelled_count": 1,+ "already_done": 1,+ "batches": [+ {"batch_id": "batch-abc", "status": "cancelling"},+ {"batch_id": "batch-xyz", "status": "completed"},+ ],+}+++class TestCancelLabel:+ @pytest.mark.parametrize(+ "pool,label",+ [+ ("test-pool", "test-label"),+ ("prod-pool", "prod-run"),+ ("staging", "experiment-42"),+ ],+ )+ def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, label):+ body = {**GOLDEN_CANCEL_LABEL, "label": label}+ httpx_mock.add_response(method="DELETE", url=f"{BASE_URL}/api/label/{pool}/{label}", status_code=200, json=body)+ resp = cancel_label.sync_detailed(pool=pool, label=label, client=auth_client)+ assert resp.status_code.value == 200+ assert isinstance(resp.parsed, CancelLabelResponse)++ def test_not_found(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="DELETE",+ url=f"{BASE_URL}/api/label/pool/unknown",+ status_code=404,+ json={"error": "label not found"},+ )+ assert cancel_label.sync_detailed(pool="pool", label="unknown", client=auth_client).status_code.value == 404++ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):+ httpx_mock.add_response(+ method="DELETE", url=f"{BASE_URL}/api/label/pool/lbl", status_code=200, json=GOLDEN_CANCEL_LABEL+ )+ result = auth_client.cancel_label(pool="pool", label="lbl")+ assert isinstance(result, CancelLabelResponse)diff --git a/libs/fleet/python-sdk/tests/test_models.py b/libs/fleet/python-sdk/tests/test_models.pynew file mode 100644index 0000000000..cb6ce7df94--- /dev/null+++ b/libs/fleet/python-sdk/tests/test_models.py@@ -0,0 +1,61 @@+"""Smoke tests — verify models and TrainClient can be imported and instantiated."""++from cua_train import AuthenticatedClient, TrainClient+from cua_train.models import (+ Action,+ ActionParameters,+ BatchProgress,+ BatchSubmitRequest,+ LabelStatusResponse,+ RunConfig,+)+++def test_batch_submit_request_instantiation():+ click = Action(action_type="CLICK", parameters=ActionParameters.from_dict({"x": 1, "y": 2}))+ req = BatchSubmitRequest(+ runs=[RunConfig(steps=[click], timeout=60)],+ concurrency=2,+ )+ assert len(req.runs) == 1+ assert req.runs[0].steps[0].action_type == "CLICK"+++def test_label_status_response_instantiation():+ resp = LabelStatusResponse(+ label="test-label",+ batch_count=1,+ all_completed=False,+ progress=BatchProgress(completed=0, total=1, ok=0, failed=0),+ batches=[],+ )+ assert resp.label == "test-label"+++def test_train_client_is_subclass():+ """TrainClient must be a drop-in for AuthenticatedClient."""+ assert issubclass(TrainClient, AuthenticatedClient)+++def test_client_exposes_generated_operations():+ """Every generated endpoint is reachable as a method on the client+ (its sync(), client pre-bound), with no hand-written wrapper."""+ import pytest++ c = TrainClient(base_url="https://example.invalid", token="t")++ # A representative op from each tag is exposed and callable.+ for op in (+ "acquire_lanes",+ "release_lanes",+ "submit_batch",+ "submit_label_batch",+ "get_label_results",+ "list_keys",+ "healthz",+ ):+ assert callable(getattr(c, op)), f"client.{op} should be callable"++ # Unknown attributes still raise AttributeError (so copy/pickle/etc. behave).+ with pytest.raises(AttributeError):+ c.definitely_not_an_endpointdiff --git a/libs/fleet/rbac-e2e/go.mod b/libs/fleet/rbac-e2e/go.modnew file mode 100644index 0000000000..3477baf2c9--- /dev/null+++ b/libs/fleet/rbac-e2e/go.mod@@ -0,0 +1,54 @@+module cyclops-cs-rbac-e2e++go 1.24.7++require (+ k8s.io/api v0.31.3+ k8s.io/apimachinery v0.31.3+ k8s.io/client-go v0.31.3+ sigs.k8s.io/controller-runtime v0.19.3+ sigs.k8s.io/yaml v1.4.0+)++require (+ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect+ github.com/emicklei/go-restful/v3 v3.11.0 // indirect+ github.com/evanphx/json-patch/v5 v5.9.0 // indirect+ github.com/fxamacker/cbor/v2 v2.7.0 // indirect+ github.com/go-logr/logr v1.4.2 // indirect+ github.com/go-openapi/jsonpointer v0.19.6 // indirect+ github.com/go-openapi/jsonreference v0.20.2 // indirect+ github.com/go-openapi/swag v0.22.4 // indirect+ github.com/gogo/protobuf v1.3.2 // indirect+ github.com/golang/protobuf v1.5.4 // indirect+ github.com/google/gnostic-models v0.6.8 // indirect+ github.com/google/go-cmp v0.6.0 // indirect+ github.com/google/gofuzz v1.2.0 // indirect+ github.com/google/uuid v1.6.0 // indirect+ github.com/imdario/mergo v0.3.6 // indirect+ github.com/josharian/intern v1.0.0 // indirect+ github.com/json-iterator/go v1.1.12 // indirect+ github.com/mailru/easyjson v0.7.7 // indirect+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect+ github.com/modern-go/reflect2 v1.0.2 // indirect+ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect+ github.com/pkg/errors v0.9.1 // indirect+ github.com/spf13/pflag v1.0.5 // indirect+ github.com/x448/float16 v0.8.4 // indirect+ golang.org/x/net v0.26.0 // indirect+ golang.org/x/oauth2 v0.21.0 // indirect+ golang.org/x/sys v0.21.0 // indirect+ golang.org/x/term v0.21.0 // indirect+ golang.org/x/text v0.16.0 // indirect+ golang.org/x/time v0.3.0 // indirect+ google.golang.org/protobuf v1.34.2 // indirect+ gopkg.in/inf.v0 v0.9.1 // indirect+ gopkg.in/yaml.v2 v2.4.0 // indirect+ gopkg.in/yaml.v3 v3.0.1 // indirect+ k8s.io/apiextensions-apiserver v0.31.0 // indirect+ k8s.io/klog/v2 v2.130.1 // indirect+ k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 // indirect+ k8s.io/utils v0.0.0-20240711033017-18e509b52bc8 // indirect+ sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect+ sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect+)diff --git a/libs/fleet/rbac-e2e/go.sum b/libs/fleet/rbac-e2e/go.sumnew file mode 100644index 0000000000..4cf3c463a7--- /dev/null+++ b/libs/fleet/rbac-e2e/go.sum@@ -0,0 +1,188 @@+github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=+github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g=+github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=+github.com/evanphx/json-patch/v5 v5.9.0 h1:kcBlZQbplgElYIlo/n1hJbls2z/1awpXxpRi0/FOJfg=+github.com/evanphx/json-patch/v5 v5.9.0/go.mod h1:VNkHZ/282BpEyt/tObQO8s5CMPmYYq14uClGH4abBuQ=+github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E=+github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=+github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=+github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=+github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ=+github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg=+github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE=+github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs=+github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE=+github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k=+github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=+github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogBU=+github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=+github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=+github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=+github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=+github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=+github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=+github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=+github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I=+github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U=+github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=+github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=+github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=+github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=+github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=+github.com/google/pprof v0.0.0-20240525223248-4bfdf5a9a2af h1:kmjWCqn2qkEml422C2Rrd27c3VGxi6a/6HNq8QmHRKM=+github.com/google/pprof v0.0.0-20240525223248-4bfdf5a9a2af/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/imdario/mergo v0.3.6 h1:xTNEAn+kxVO7dTZGu0CegyqKZmoWFI0rF8UxjlB2d28=+github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=+github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=+github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=+github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=+github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=+github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=+github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=+github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=+github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=+github.com/onsi/ginkgo/v2 v2.19.0 h1:9Cnnf7UHo57Hy3k6/m5k3dRfGTMXGvxhHFvkDTCTpvA=+github.com/onsi/ginkgo/v2 v2.19.0/go.mod h1:rlwLi9PilAFJ8jCg9UE1QP6VBpd6/xj3SRC0d6TU0To=+github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk=+github.com/onsi/gomega v1.33.1/go.mod h1:U4R44UsT+9eLIaYRB2a5qajjtQYn0hauxvRm16AVYg0=+github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=+github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/prometheus/client_golang v1.19.1 h1:wZWJDwK+NameRJuPGDhlnFgx8e8HN3XHQeLaYJFJBOE=+github.com/prometheus/client_golang v1.19.1/go.mod h1:mP78NwGzrVks5S2H6ab8+ZZGJLZUq1hoULYBAYBw1Ho=+github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=+github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=+github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc=+github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8=+github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=+github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=+github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=+github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=+github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=+github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=+github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=+github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=+github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=+github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=+github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=+github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=+github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=+go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=+go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=+go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=+go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=+golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc h1:mCRnTeVUjcrhlRmO0VK8a6k6Rrf6TF9htwo2pJVSjIU=+golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w=+golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=+golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=+golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=+golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=+golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=+golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=+golang.org/x/oauth2 v0.21.0 h1:tsimM75w1tF/uws5rbeHzIWxEqElMehnc+iW793zsZs=+golang.org/x/oauth2 v0.21.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI=+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=+golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=+golang.org/x/term v0.21.0 h1:WVXCp+/EBEHOj53Rvu+7KiT/iElMrO8ACK16SMZ3jaA=+golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0=+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=+golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=+golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=+golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=+golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=+golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=+golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=+golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=+golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw=+gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY=+google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=+google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=+gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSPG+6V4=+gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M=+gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=+gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=+gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+k8s.io/api v0.31.3 h1:umzm5o8lFbdN/hIXbrK9oRpOproJO62CV1zqxXrLgk8=+k8s.io/api v0.31.3/go.mod h1:UJrkIp9pnMOI9K2nlL6vwpxRzzEX5sWgn8kGQe92kCE=+k8s.io/apiextensions-apiserver v0.31.0 h1:fZgCVhGwsclj3qCw1buVXCV6khjRzKC5eCFt24kyLSk=+k8s.io/apiextensions-apiserver v0.31.0/go.mod h1:b9aMDEYaEe5sdK+1T0KU78ApR/5ZVp4i56VacZYEHxk=+k8s.io/apimachinery v0.31.3 h1:6l0WhcYgasZ/wk9ktLq5vLaoXJJr5ts6lkaQzgeYPq4=+k8s.io/apimachinery v0.31.3/go.mod h1:rsPdaZJfTfLsNJSQzNHQvYoTmxhoOEofxtOsF3rtsMo=+k8s.io/client-go v0.31.3 h1:CAlZuM+PH2cm+86LOBemaJI/lQ5linJ6UFxKX/SoG+4=+k8s.io/client-go v0.31.3/go.mod h1:2CgjPUTpv3fE5dNygAr2NcM8nhHzXvxB8KL5gYc3kJs=+k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk=+k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE=+k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 h1:BZqlfIlq5YbRMFko6/PM7FjZpUb45WallggurYhKGag=+k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340/go.mod h1:yD4MZYeKMBwQKVht279WycxKyM84kkAx2DPrTXaeb98=+k8s.io/utils v0.0.0-20240711033017-18e509b52bc8 h1:pUdcCO1Lk/tbT5ztQWOBi5HBgbBP1J8+AsQnQCKsi8A=+k8s.io/utils v0.0.0-20240711033017-18e509b52bc8/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=+sigs.k8s.io/controller-runtime v0.19.3 h1:XO2GvC9OPftRst6xWCpTgBZO04S2cbp0Qqkj8bX1sPw=+sigs.k8s.io/controller-runtime v0.19.3/go.mod h1:j4j87DqtsThvwTv5/Tc5NFRyyF/RF0ip4+62tbTSIUM=+sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo=+sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0=+sigs.k8s.io/structured-merge-diff/v4 v4.4.1 h1:150L+0vs/8DA78h1u02ooW1/fFq/Lwr+sGiqlzvrtq4=+sigs.k8s.io/structured-merge-diff/v4 v4.4.1/go.mod h1:N8hJocpFajUSSeSJ9bOZ77VzejKZaXsTtZo4/u7Io08=+sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E=+sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY=diff --git a/libs/fleet/rbac-e2e/pool_rbac_test.go b/libs/fleet/rbac-e2e/pool_rbac_test.gonew file mode 100644index 0000000000..577ee0d5df--- /dev/null+++ b/libs/fleet/rbac-e2e/pool_rbac_test.go@@ -0,0 +1,286 @@+// Package rbace2e reproduces — against a real kube-apiserver (envtest, no+// cluster/VM/Docker) — the production 403 a cyclops-cs user hit creating a+// workspace pool:+//+// osgymworkspacepools.cua.ai is forbidden: User+// "oidc:f70ef30e-9282-4a3b-b630-8a6bb4528c5d" cannot create resource+// "osgymworkspacepools" in API group "cua.ai" in the namespace+// "godot-qa-godot-qa"+//+// Why this is the faithful layer: the 403 is an apiserver RBAC decision, not+// anything cyclops computes. The backend's OPA policy ALLOWS namespaced pool+// creation (authz.rego) and forwards the request to the apiserver with+// impersonation headers (handlers.k8sImpersonate sets Impersonate-User:+// oidc:<sub>, Impersonate-Group: oidc:user-<sub>). The apiserver authorizes+// that impersonated identity via RBAC.+//+// Since commit 5516dcf7 ("Fix cross-tenant pool/claim data leak via RBAC+// enforcement") pool CRUD is granted ONLY per-namespace, through the `admin`+// ClusterRole that Capsule binds inside each tenant owner's namespaces —+// clusters/kopf-k3s/capsule/pool-manager-clusterrole.yaml aggregates the pool+// verbs into `admin`. Capsule creates that binding only for a governed owner.+// This package preserves the historical group-owner regression from the+// retired Kopf lifecycle: dynamic oidc:user-<sub> groups could be removed when+// Flux reapplied CapsuleConfiguration.userGroups. The current backend creates+// and validates direct User owners before namespace creation; its first-use+// lifecycle is covered by the backend Tenant tests, not by this historical+// negative-control package.+//+// Two tests, both against a real apiserver with no Capsule operator:+//+// - TestPoolCreate_Forbidden_WhenOwnerUngoverned reproduces the denial (no+// binding -> the exact 403) and shows the per-namespace fix (bind the+// owner's group, the way a governed owner is bound -> create succeeds).+//+// - TestPoolCreate_Succeeds_WhenRemovedClusterWideGrantRestored is a negative+// control: with the same apiserver/user/namespace and NO per-namespace+// binding, restoring the exact cluster-wide grant that 5516dcf7 deleted+// flips the 403 to success — pinning the regression to that removal.+//+// Run:+//+// cd cyclops-cs/rbac-e2e+// KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/[email protected] use 1.31.0 -p path)" \+// go test -run TestPoolCreate -v+package rbace2e++import (+ "context"+ "os"+ "strings"+ "testing"+ "time"++ corev1 "k8s.io/api/core/v1"+ rbacv1 "k8s.io/api/rbac/v1"+ apierrors "k8s.io/apimachinery/pkg/api/errors"+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"+ "k8s.io/apimachinery/pkg/runtime/schema"+ "k8s.io/client-go/dynamic"+ "k8s.io/client-go/kubernetes"+ "k8s.io/client-go/rest"+ "sigs.k8s.io/controller-runtime/pkg/envtest"+ "sigs.k8s.io/yaml"+)++// The exact identity and namespace from the bug report.+const (+ userSub = "f70ef30e-9282-4a3b-b630-8a6bb4528c5d"+ impUser = "oidc:" + userSub // Impersonate-User+ impGroup = "oidc:user-" + userSub // Impersonate-Group+ namespace = "godot-qa-godot-qa" // the user's workspace namespace+)++// poolClusterRole is the real production manifest whose rules Capsule folds+// into the per-namespace `admin` binding. Referencing the live file keeps the+// test honest: if the grant changes, the test reflects it.+const poolClusterRole = "../../clusters/kopf-k3s/capsule/pool-manager-clusterrole.yaml"++var poolGVR = schema.GroupVersionResource{Group: "cua.ai", Version: "v1", Resource: "osgymworkspacepools"}++func newPool(name string) *unstructured.Unstructured {+ return &unstructured.Unstructured{Object: map[string]any{+ "apiVersion": "cua.ai/v1",+ "kind": "OSGymWorkspacePool",+ "metadata": map[string]any{"name": name},+ "spec": map[string]any{"replicas": int64(1)},+ }}+}++// startReproEnv boots a real apiserver (envtest) with RBAC enforced, installs+// the pool CRD, creates the target namespace, and returns an admin clientset+// (system:masters — used only for setup) plus a dynamic pool client that+// impersonates the reported user exactly like handlers.k8sImpersonate().+func startReproEnv(t *testing.T) (*kubernetes.Clientset, dynamic.NamespaceableResourceInterface) {+ t.Helper()+ if os.Getenv("KUBEBUILDER_ASSETS") == "" {+ t.Skip("KUBEBUILDER_ASSETS unset; see the package doc for the setup-envtest one-liner")+ }++ env := &envtest.Environment{+ CRDDirectoryPaths: []string{"testdata"},+ ErrorIfCRDPathMissing: true,+ }+ // Enforce RBAC for impersonated identities, exactly like the real cluster.+ // (The default envtest client is in system:masters and bypasses RBAC, so it+ // can still perform setup; impersonated users are authorized by RBAC.)+ env.ControlPlane.GetAPIServer().Configure().Set("authorization-mode", "Node,RBAC")++ cfg, err := env.Start()+ if err != nil {+ t.Fatalf("start envtest apiserver: %v", err)+ }+ t.Cleanup(func() { _ = env.Stop() })++ admin := kubernetes.NewForConfigOrDie(cfg)++ // The namespace exists. In prod the backend creates it via the cluster-wide+ // `create namespaces` grant to system:authenticated (capsule-rbac/rbac.yaml);+ // here we create it directly. It is NOT adopted into the owner's tenant,+ // because Capsule only adopts/binds for users it governs.+ if _, err := admin.CoreV1().Namespaces().Create(context.Background(), &corev1.Namespace{+ ObjectMeta: metav1.ObjectMeta{Name: namespace},+ }, metav1.CreateOptions{}); err != nil {+ t.Fatalf("create namespace %q: %v", namespace, err)+ }++ // Impersonate the user the way handlers.k8sImpersonate() does.+ impCfg := rest.CopyConfig(cfg)+ impCfg.Impersonate = rest.ImpersonationConfig{+ UserName: impUser,+ Groups: []string{impGroup, "system:authenticated"},+ }+ pools := dynamic.NewForConfigOrDie(impCfg).Resource(poolGVR)+ return admin, pools+}++// createPool attempts to create a pool in the target namespace as the+// impersonated user, returning the apiserver error (nil on success).+func createPool(ctx context.Context, pools dynamic.NamespaceableResourceInterface) error {+ _, err := pools.Namespace(namespace).Create(ctx, newPool("godot-qa"), metav1.CreateOptions{})+ return err+}++// createPoolEventually retries createPool to absorb RBAC cache propagation+// (the authorizer sees a new binding near-instantly, but not synchronously).+func createPoolEventually(ctx context.Context, pools dynamic.NamespaceableResourceInterface) error {+ var err error+ for i := 0; i < 50; i++ {+ if err = createPool(ctx, pools); err == nil {+ return nil+ }+ time.Sleep(200 * time.Millisecond)+ }+ return err+}++func TestPoolCreate_Forbidden_WhenOwnerUngoverned(t *testing.T) {+ admin, pools := startReproEnv(t)+ ctx := context.Background()++ // ── Reproduce the reported 403 ───────────────────────────────────────+ // The owner's group has no RoleBinding in this namespace, and the+ // cluster-wide pool grant was removed in 5516dcf7, so nothing authorizes+ // the create.+ err := createPool(ctx, pools)+ if err == nil {+ t.Fatal("expected the reported 403, but pool creation SUCCEEDED for the ungoverned owner")+ }+ if !apierrors.IsForbidden(err) {+ t.Fatalf("expected a Forbidden (403) error, got: %v", err)+ }+ // Assert it is the exact apiserver RBAC denial from the report.+ msg := err.Error()+ for _, want := range []string{+ `cannot create resource "osgymworkspacepools"`,+ `in API group "cua.ai"`,+ impUser,+ namespace,+ } {+ if !strings.Contains(msg, want) {+ t.Fatalf("denial message missing %q\nfull message: %s", want, msg)+ }+ }+ t.Logf("REPRODUCED the reported error:\n %s", msg)++ // ── Prove the per-namespace fix (the Capsule-governed path) ──────────+ // Apply the REAL repo ClusterRole and bind the owner's group to it in the+ // namespace — what Capsule does for a governed owner (it binds the owner to+ // `admin`, into which this ClusterRole aggregates; the ClusterRole also+ // carries the pool verbs directly). Now the identical create must succeed.+ applyRealPoolClusterRole(t, ctx, admin)+ if _, err := admin.RbacV1().RoleBindings(namespace).Create(ctx, &rbacv1.RoleBinding{+ ObjectMeta: metav1.ObjectMeta{Name: "owner-pools", Namespace: namespace},+ Subjects: []rbacv1.Subject{{+ Kind: rbacv1.GroupKind,+ APIGroup: rbacv1.GroupName,+ Name: impGroup,+ }},+ RoleRef: rbacv1.RoleRef{+ APIGroup: rbacv1.GroupName,+ Kind: "ClusterRole",+ Name: "cua:aggregate-pools-to-admin",+ },+ }, metav1.CreateOptions{}); err != nil {+ t.Fatalf("create RoleBinding for the owner: %v", err)+ }+ if err := createPoolEventually(ctx, pools); err != nil {+ t.Fatalf("once the owner's group is bound in the namespace, pool creation should succeed; got: %v", err)+ }+ t.Log("CONFIRMED: binding the owner's group in the namespace (what Capsule does for a governed owner) restores pool creation")+}++// TestPoolCreate_Succeeds_WhenRemovedClusterWideGrantRestored is a negative+// control that pins the 403 to commit 5516dcf7 specifically. That commit+// removed a cluster-wide grant from clusters/kopf-k3s/capsule-rbac/rbac.yaml:+// the `capsule-tenant-cluster-resources` ClusterRole used to grant+// system:authenticated cluster-wide CRUD on cua.ai/osgymworkspacepools (bound+// via a ClusterRoleBinding to system:authenticated).+//+// Same apiserver, same user, same namespace, NO per-namespace binding — the+// ONLY variable is that grant. Without it the create 403s (the bug); restore+// exactly the deleted rule and the identical create succeeds. So the 403 is+// caused by that removal, not by some unrelated artifact of the test harness.+func TestPoolCreate_Succeeds_WhenRemovedClusterWideGrantRestored(t *testing.T) {+ admin, pools := startReproEnv(t)+ ctx := context.Background()++ // Baseline = post-5516dcf7 state (no grant, no binding): the reported 403.+ if err := createPool(ctx, pools); !apierrors.IsForbidden(err) {+ t.Fatalf("baseline: expected Forbidden without the cluster-wide grant, got: %v", err)+ }++ // Restore EXACTLY the rule 5516dcf7 deleted (pre-regression state):+ // ClusterRole capsule-tenant-cluster-resources+ // - apiGroups: ["cua.ai"]+ // resources: ["osgymworkspacepools"]+ // verbs: ["list","get","create","update","patch","delete"]+ // + ClusterRoleBinding of it to group system:authenticated.+ if _, err := admin.RbacV1().ClusterRoles().Create(ctx, &rbacv1.ClusterRole{+ ObjectMeta: metav1.ObjectMeta{Name: "capsule-tenant-cluster-resources"},+ Rules: []rbacv1.PolicyRule{{+ APIGroups: []string{"cua.ai"},+ Resources: []string{"osgymworkspacepools"},+ Verbs: []string{"list", "get", "create", "update", "patch", "delete"},+ }},+ }, metav1.CreateOptions{}); err != nil {+ t.Fatalf("recreate the removed ClusterRole: %v", err)+ }+ if _, err := admin.RbacV1().ClusterRoleBindings().Create(ctx, &rbacv1.ClusterRoleBinding{+ ObjectMeta: metav1.ObjectMeta{Name: "capsule-tenant-cluster-resources"},+ Subjects: []rbacv1.Subject{{+ Kind: rbacv1.GroupKind,+ APIGroup: rbacv1.GroupName,+ Name: "system:authenticated",+ }},+ RoleRef: rbacv1.RoleRef{+ APIGroup: rbacv1.GroupName,+ Kind: "ClusterRole",+ Name: "capsule-tenant-cluster-resources",+ },+ }, metav1.CreateOptions{}); err != nil {+ t.Fatalf("recreate the removed ClusterRoleBinding: %v", err)+ }++ // Pre-regression: the identical create now succeeds — nothing else changed.+ if err := createPoolEventually(ctx, pools); err != nil {+ t.Fatalf("with the cluster-wide grant restored, pool creation should succeed; got: %v", err)+ }+ t.Log("CONFIRMED: restoring the cluster-wide grant that 5516dcf7 removed flips the identical create to success — the 403 is that regression")+}++func applyRealPoolClusterRole(t *testing.T, ctx context.Context, admin *kubernetes.Clientset) {+ t.Helper()+ raw, err := os.ReadFile(poolClusterRole)+ if err != nil {+ t.Fatalf("read %s: %v", poolClusterRole, err)+ }+ var cr rbacv1.ClusterRole+ if err := yaml.Unmarshal(raw, &cr); err != nil {+ t.Fatalf("parse ClusterRole from %s: %v", poolClusterRole, err)+ }+ if _, err := admin.RbacV1().ClusterRoles().Create(ctx, &cr, metav1.CreateOptions{}); err != nil {+ t.Fatalf("create ClusterRole %q: %v", cr.Name, err)+ }+}diff --git a/libs/fleet/rbac-e2e/testdata/osgym-pool-crd.yaml b/libs/fleet/rbac-e2e/testdata/osgym-pool-crd.yamlnew file mode 100644index 0000000000..aa54487a15--- /dev/null+++ b/libs/fleet/rbac-e2e/testdata/osgym-pool-crd.yaml@@ -0,0 +1,30 @@+# Minimal OSGymWorkspacePool CRD — just enough for the apiserver to serve the+# resource the RBAC test targets. Schema is irrelevant to authorization (RBAC+# keys off apiGroup/resource/verb), so this mirrors the e2e fixture+# (nixos/tenant-rbac/osgym-pool-crd.yaml) and keeps the test self-contained.+apiVersion: apiextensions.k8s.io/v1+kind: CustomResourceDefinition+metadata:+ name: osgymworkspacepools.cua.ai+spec:+ group: cua.ai+ scope: Namespaced+ names:+ plural: osgymworkspacepools+ singular: osgymworkspacepool+ kind: OSGymWorkspacePool+ shortNames: ["owp"]+ versions:+ - name: v1+ served: true+ storage: true+ schema:+ openAPIV3Schema:+ type: object+ properties:+ spec:+ type: object+ x-kubernetes-preserve-unknown-fields: true+ status:+ type: object+ x-kubernetes-preserve-unknown-fields: truediff --git a/libs/fleet/src/App.tsx b/libs/fleet/src/App.tsxnew file mode 100644index 0000000000..040dbfebd0--- /dev/null+++ b/libs/fleet/src/App.tsx@@ -0,0 +1,271 @@+import {+ BrowserRouter,+ Navigate,+ Outlet,+ Route,+ Routes,+ useLocation,+ useNavigate,+} from "react-router-dom"+import AppLayout from "@cloudscape-design/components/app-layout"+import Button from "@cloudscape-design/components/button"+import SideNavigation from "@cloudscape-design/components/side-navigation"+import TopNavigation, {+ type TopNavigationProps,+} from "@cloudscape-design/components/top-navigation"+import Flashbar, {+ type FlashbarProps,+} from "@cloudscape-design/components/flashbar"+import { useCallback, useEffect, useMemo, useRef, useState } from "react"+import { PoolsList } from "./pages/PoolsList"+import { ClaimDetail } from "./pages/ClaimDetail"+import { PoolDetail } from "./pages/PoolDetail"+import { PoolNew } from "./pages/PoolNew"+import { PoolReplicaDetail } from "./pages/PoolReplicaDetail"+import { NodesList } from "./pages/NodesList"+import { OperatorEvents } from "./pages/OperatorEvents"+import { ApiKeys } from "./pages/ApiKeys"+import { UserApiKeys } from "./pages/UserApiKeys"+import { Settings } from "./pages/Settings"+import { FlashContext, type FlashMsg } from "./components/FlashContext"+import { FeatureFlagProvider, useFeatureFlags } from "./components/FeatureFlagContext"+import { logout, userInfo } from "./auth/keycloak"++const VERSION_CHECK_INTERVAL_MS = 60_000++function useStaleCheck(): { stale: boolean } {+ const [stale, setStale] = useState(false)+ const currentEntry = useRef<string | null>(null)++ useEffect(() => {+ if (stale) return++ // The entry script is what's actually executing; lazy chunk hashes+ // changing don't make the running app stale on their own.+ const entry = Array.from(+ document.querySelectorAll<HTMLScriptElement>('script[type="module"][src]'),+ )+ .map(s => s.src)+ .find(src => src.includes('/assets/'))+ if (!entry) return+ currentEntry.current = entry++ const check = async () => {+ try {+ // High-signal: if the CDN no longer serves our entry chunk,+ // the deploy invalidated us — next dynamic import would fail anyway.+ const head = await fetch(currentEntry.current!, { method: 'HEAD', cache: 'no-cache' })+ if (head.status === 404) {+ setStale(true)+ return+ }++ const res = await fetch('/', { cache: 'no-cache' })+ const html = await res.text()+ const match = html.match(/<script[^>]+type="module"[^>]+src="(\/assets\/[^"']+)"/)+ const latestEntry = match?.[1]+ if (latestEntry && !currentEntry.current!.endsWith(latestEntry)) {+ setStale(true)+ }+ } catch {+ // Network error — ignore+ }+ }++ const id = window.setInterval(check, VERSION_CHECK_INTERVAL_MS)+ return () => window.clearInterval(id)+ }, [stale])++ return { stale }+}++function Shell() {+ const location = useLocation()+ const navigate = useNavigate()+ const [flashes, setFlashes] = useState<FlashbarProps.MessageDefinition[]>([])+ const { stale } = useStaleCheck()+ const [staleDismissed, setStaleDismissed] = useState(false)+ const { admin } = useFeatureFlags()+ const user = userInfo()+ const pushFlash = useCallback((msg: FlashMsg) => {+ const id = crypto.randomUUID()+ const dismiss = () =>+ setFlashes(prev => prev.filter(f => f.id !== id))+ setFlashes(prev => [+ ...prev,+ {+ ...msg,+ id,+ dismissible: true,+ onDismiss: dismiss,+ },+ ])+ if (msg.type === "success") {+ window.setTimeout(dismiss, 5000)+ }+ }, [])+ const flashContext = useMemo(() => ({ push: pushFlash }), [pushFlash])++ return (+ <FlashContext.Provider value={flashContext}>+ <TopNavigation+ identity={{ href: "#/", title: "Pools" }}+ utilities={[+ {+ type: "button",+ text: "Pools",+ href: "#/pools",+ onClick: e => {+ e.preventDefault()+ navigate("/pools")+ },+ },+ ...(admin+ ? ([+ {+ type: "button",+ text: "Nodes",+ href: "#/nodes",+ onClick: e => {+ e.preventDefault()+ navigate("/nodes")+ },+ },+ {+ type: "button",+ text: "Operator events",+ href: "#/operator-events",+ onClick: e => {+ e.preventDefault()+ navigate("/operator-events")+ },+ },+ ] satisfies TopNavigationProps.Utility[])+ : []),+ {+ type: "menu-dropdown",+ text: user.name ?? user.email ?? "Account",+ description: user.email,+ iconName: "user-profile",+ items: [{ id: "signout", text: "Sign out" }],+ onItemClick: e => {+ if (e.detail.id === "signout") logout()+ },+ },+ ]}+ />+ <AppLayout+ toolsHide+ navigation={+ <div style={{ fontSize: "1.25rem" }}>+ <SideNavigation+ header={{ href: "#/", text: "Pools" }}+ activeHref={`#${location.pathname}`}+ onFollow={e => {+ if (!e.detail.external) {+ e.preventDefault()+ navigate(e.detail.href.replace(/^#/, ""))+ }+ }}+ items={[+ { type: "link", text: "Pools", href: "#/pools" },+ ...(admin+ ? [+ { type: "link" as const, text: "Nodes", href: "#/nodes" },+ {+ type: "link" as const,+ text: "Operator events",+ href: "#/operator-events",+ },+ ]+ : []),+ { type: "link", text: "User API keys", href: "#/user-keys" },+ { type: "link", text: "Settings", href: "#/settings" },+ ]}+ />+ </div>+ }+ notifications={+ <Flashbar+ items={[+ ...(stale && !staleDismissed+ ? [+ {+ type: "info" as const,+ header: "A new version is available",+ content: "Refresh to get the latest features and fixes.",+ action: (+ <Button onClick={() => window.location.reload()}>+ Refresh now+ </Button>+ ),+ dismissible: true,+ onDismiss: () => setStaleDismissed(true),+ id: "__stale__",+ },+ ]+ : []),+ ...flashes,+ ]}+ stackItems+ />+ }+ content={<Outlet />}+ contentType="default"+ />+ </FlashContext.Provider>+ )+}++export function App() {+ return (+ <BrowserRouter>+ <FeatureFlagProvider>+ <Routes>+ <Route element={<Shell />}>+ <Route index element={<Navigate to="/pools" replace />} />+ <Route path="/pools" element={<PoolsList />} />+ <Route path="/pools/new" element={<PoolNew />} />+ {/* Templates feature removed — keep old links working. */}+ <Route+ path="/pools/templates"+ element={<Navigate to="/pools" replace />}+ />+ <Route path="/pools/:namespace/:name" element={<PoolDetail />} />+ <Route path="/nodes" element={<NodesList />} />+ <Route path="/operator-events" element={<OperatorEvents />} />+ <Route+ path="/operator-logs"+ element={<Navigate to="/operator-events" replace />}+ />+ <Route path="/api-keys" element={<ApiKeys />} />+ <Route path="/user-keys" element={<UserApiKeys />} />+ <Route path="/settings" element={<Settings />} />+ <Route+ path="/pools/:namespace/:poolName/claims/:claimName"+ element={<ClaimDetail />}+ />+ <Route+ path="/pools/:namespace/:poolName/replicas/:vmName"+ element={<PoolReplicaDetail />}+ />+ {/* Back-compat for old bookmarks. */}+ <Route path="/modules" element={<Navigate to="/pools" replace />} />+ <Route+ path="/modules/new"+ element={<Navigate to="/pools/new" replace />}+ />+ <Route path="/modules/:name" element={<RedirectModule />} />+ {/* Back-compat: old /pools/:name URLs (no namespace) redirect to list. */}+ <Route path="/pools/:name" element={<Navigate to="/pools" replace />} />+ </Route>+ </Routes>+ </FeatureFlagProvider>+ </BrowserRouter>+ )+}++function RedirectModule() {+ const path = window.location.pathname.replace(/^\/modules/, "/pools")+ return <Navigate to={path} replace />+}diff --git a/libs/fleet/src/api/client.ts b/libs/fleet/src/api/client.tsnew file mode 100644index 0000000000..7c1ea77409--- /dev/null+++ b/libs/fleet/src/api/client.ts@@ -0,0 +1,23 @@+// Singleton instance of the generated cyclops-cs-backend Api client.+//+// The generated client (src/api/generated/cyclops-cs-backend.ts) is+// produced by `pnpm gen:api` from backend/docs/swagger.json. We don't+// hand-edit it — instead we configure it here with a securityWorker+// that pulls a fresh Keycloak access token before every authenticated+// request, so all SPA → backend calls share one auth pipeline.+//+// `baseUrl` is "" so the generated `/api/...` paths resolve against the+// SPA's own origin (nginx routes /api/{keys,gateway,k8s,orch,swagger}+// to the backend sidecar).++import { Api } from "./generated/cyclops-cs-backend"+import { getToken } from "../auth/keycloak"++export const apiClient = new Api({+ baseUrl: "",+ securityWorker: async () => {+ const token = await getToken()+ if (!token) return {}+ return { headers: { Authorization: `Bearer ${token}` } }+ },+})diff --git a/libs/fleet/src/api/cyclops.ts b/libs/fleet/src/api/cyclops.tsnew file mode 100644index 0000000000..d30e232acd--- /dev/null+++ b/libs/fleet/src/api/cyclops.ts@@ -0,0 +1,791 @@+// © 2024 CUA - gateway proxy+// API client for the cyclops-cs SPA. All calls go through the+// kubectl-proxy sidecar (/k8s-api/) or the nginx orch-api proxy+// (/orch-api/).++// ── K8s API types (only the bits we use) ────────────────────────────────++export interface PodContainerStatus {+ name: string+ ready?: boolean+ restartCount?: number+ state?: {+ waiting?: { reason?: string; message?: string }+ running?: { startedAt?: string }+ terminated?: {+ exitCode?: number+ reason?: string+ message?: string+ startedAt?: string+ finishedAt?: string+ }+ }+}++export interface PodSummary {+ metadata: {+ name: string+ namespace: string+ labels?: Record<string, string>+ creationTimestamp?: string+ }+ spec?: {+ nodeName?: string+ containers?: { name: string }[]+ }+ status?: {+ phase?: string+ podIP?: string+ startTime?: string+ containerStatuses?: PodContainerStatus[]+ }+}++export interface PodList {+ items: PodSummary[]+}++export interface NodeSummary {+ metadata: {+ name: string+ labels?: Record<string, string>+ creationTimestamp?: string+ }+ status?: {+ capacity?: Record<string, string>+ allocatable?: Record<string, string>+ nodeInfo?: {+ kubeletVersion?: string+ osImage?: string+ architecture?: string+ }+ conditions?: { type: string; status: string }[]+ }+ spec?: {+ taints?: { key: string; effect: string }[]+ unschedulable?: boolean+ }+}++export interface NodeList {+ items: NodeSummary[]+}++// Pool VMs only schedule onto kubevirt worker nodes. Use this to scope any+// node listing or capacity math to the nodes that can actually host pools.+export const POOL_WORKER_NODE_PREFIX = "kubevirt-k3s-worker-"+export function isPoolWorkerNode(n: NodeSummary): boolean {+ return n.metadata.name.startsWith(POOL_WORKER_NODE_PREFIX)+}++export interface PodMetricsContainer {+ name: string+ usage: { cpu: string; memory: string } // e.g. "159687357n", "1450060Ki"+}++export interface PodMetrics {+ metadata: {+ name: string+ namespace: string+ timestamp?: string+ window?: string+ }+ containers: PodMetricsContainer[]+}++// One row from the osgym orchestrator's `GET /pool` (osgym/main.py).+export interface PoolVm {+ name: string+ // KubeVirt VM `printableStatus` — observed: "Running" | "Stopped" |+ // "Provisioning" | "Starting" | "Stopping" | "Terminating" | "Unknown".+ phase: string+ claimed_by: string | null+ available: boolean+}++export interface OrchestratorPoolStatus {+ count: number+ vms: PoolVm[]+}++// One row from osgym/observability.py's `GET /events`. Backed by a Redis+// LIST capped at 2000 entries.+export interface OrchestratorEvent {+ ts: number // unix seconds (float)+ method: string+ path: string+ status: number+ duration_ms: number+ vm_id: string | null+}++export interface OrchestratorEventsResponse {+ events: OrchestratorEvent[]+ pool: string+ key: string+}++// Prometheus HTTP API `/api/v1/query` response shape (only the bits we use).+export interface PromQueryResult {+ metric: Record<string, string>+ value: [number, string] // [unix_secs, sample_value_as_string]+}++export interface PromQueryResponse {+ status: "success" | "error"+ data: { resultType: "vector" | "scalar" | "matrix" | "string"; result: PromQueryResult[] }+ errorType?: string+ error?: string+}++export interface KubernetesEvent {+ metadata: {+ name: string+ namespace: string+ uid?: string+ creationTimestamp?: string+ }+ involvedObject: {+ kind: string+ name: string+ namespace?: string+ }+ reason?: string+ message?: string+ type?: string // "Normal" | "Warning"+ count?: number+ firstTimestamp?: string+ lastTimestamp?: string+ eventTime?: string+ source?: { component?: string; host?: string }+ reportingComponent?: string+ reportingInstance?: string+}++export interface KubernetesEventList {+ items: KubernetesEvent[]+}++async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {+ // Inject Authorization: Bearer ${kc.token} for backend-mediated paths+ // (everything served by the cyclops-cs sidecar).+ const authHeader: Record<string, string> = {}+ if (+ url.startsWith("/api/keys") ||+ url.startsWith("/api/user-keys") ||+ url.startsWith("/api/gateway") ||+ url.startsWith("/api/k8s") ||+ url.startsWith("/api/orch") ||+ url.startsWith("/api/namespaces") ||+ url.startsWith("/api/pool-templates")+ ) {+ const { getToken } = await import("../auth/keycloak")+ const token = await getToken()+ if (token) authHeader.Authorization = `Bearer ${token}`+ }+ const res = await fetch(url, {+ ...init,+ headers: {+ "Content-Type": "application/json",+ ...authHeader,+ ...(init?.headers ?? {}),+ },+ })+ if (!res.ok) {+ const body = await res.text().catch(() => "")+ throw new Error(`${res.status} ${res.statusText}${body ? `: ${body}` : ""}`)+ }+ // Some endpoints return empty bodies on success.+ const text = await res.text()+ return text ? (JSON.parse(text) as T) : (undefined as T)+}++// `/api/orch/<ns>/<svc>/<path>` → osgym orchestrator, via the cyclops-cs+// backend sidecar (Keycloak SSO + OPA). Replaces the older /orch-api/+// nginx block; fetchJson injects Authorization: Bearer ${kc.token}.+const httpOrch = <T>(+ namespace: string,+ service: string,+ path: string,+ init?: RequestInit,+) =>+ fetchJson<T>(+ `/api/orch/${encodeURIComponent(namespace)}/` ++ `${encodeURIComponent(service)}/${path.replace(/^\//, "")}`,+ init,+ )++// `/api/k8s/<path>` → kubectl-proxy sidecar via the cyclops-cs backend+// (Keycloak SSO + OPA). Replaces /k8s-api/. Used for arbitrary K8s API+// reads — pod listing by label, PodMetrics, etc. The cyclops-cs+// ClusterRole on the pod's ServiceAccount limits what's reachable.+const httpK8s = <T>(path: string, init?: RequestInit) =>+ fetchJson<T>(`/api/k8s/${path.replace(/^\//, "")}`, init)++export const api = {+ // Pool CRUD via K8s API (kubectl-proxy sidecar with impersonation).+ // The proxy adds Impersonate-User/Group headers so Capsule enforces+ // tenant RBAC — users can only operate in their own namespaces.+ // The pool-operator watches OSGymWorkspacePool CRs and creates all+ // resources (orchestrator, RBAC, namespace, etc.) automatically.+ createPool: async (name: string, values: {+ cpu: number; ram: string; ociImage: string; replicas: number;+ firmware?: "bios" | "efi";+ // runtime=macos provisions macOS sandboxes (ADMIN-ONLY; the backend+ // rejects macos pool writes from non-admins). Omitted/kubevirt = a VM pool.+ runtime?: "kubevirt" | "macos" | "gvisor";+ services?: { name: string; targetPort: number; protocol: string }[];+ probes?: { readinessProbe?: Record<string, unknown>; livenessProbe?: Record<string, unknown> };+ autoscaling?: PoolAutoscalingConfig;+ }) => {+ // Pool name = namespace name (1:1 mapping).+ // Auto-create the namespace before creating the pool. Tolerate "already+ // exists": the namespace can be left over from a previous attempt that+ // failed at the pool step (e.g. an adoption race), and create-or-reuse+ // makes pool creation retryable under the same name.+ const namespace = name+ try {+ await namespacesApi.create(namespace)+ } catch (e) {+ if (!String((e as Error).message).startsWith("409")) throw e+ }+ return httpK8s<void>(+ `apis/cua.ai/v1/namespaces/${encodeURIComponent(namespace)}/osgymworkspacepools`,+ {+ method: "POST",+ body: JSON.stringify({+ apiVersion: "cua.ai/v1",+ kind: "OSGymWorkspacePool",+ metadata: { name, labels: { "cua.ai/pool": name } },+ spec: {+ replicas: values.replicas,+ template: {+ // A pod runtime (macos / gvisor) flows verbatim through the compat+ // shim into the OSGymSandboxTemplate vmTemplate, where the operator's+ // pod_backend dispatches on runtime and applies that runtime's+ // placement defaults (RuntimeClass, nodeSelector, tolerations).+ ...(values.runtime && values.runtime !== "kubevirt"+ ? { runtime: values.runtime }+ : {}),+ containerDiskImage: values.ociImage,+ imagePullSecret: "ecr-credentials",+ cpuCores: values.cpu,+ memory: values.ram,+ ...(values.firmware && values.firmware !== "bios" ? { firmware: values.firmware } : {}),+ ...(values.probes ? { probes: values.probes } : {}),+ },+ ...(values.services?.length ? { services: values.services } : {}),+ ...(values.autoscaling ? { autoscaling: values.autoscaling } : {}),+ },+ }),+ },+ )+ },++ updatePoolServices: (namespace: string, name: string, services: { name: string; targetPort: number; protocol: string }[]) =>+ httpK8s<void>(+ `apis/cua.ai/v1/namespaces/${encodeURIComponent(namespace)}/osgymworkspacepools/${encodeURIComponent(name)}`,+ {+ method: "PATCH",+ headers: { "Content-Type": "application/merge-patch+json" },+ body: JSON.stringify({ spec: { services } }),+ },+ ),++ deletePool: (namespace: string, name: string) =>+ httpK8s<void>(+ `apis/cua.ai/v1/namespaces/${encodeURIComponent(namespace)}/osgymworkspacepools/${encodeURIComponent(name)}`,+ { method: "DELETE" },+ ),++ getPool: async (namespace: string, name: string): Promise<{+ name: string+ namespace: string+ replicas: number+ cpu: number+ ram: string+ ociImage: string+ firmware?: "bios" | "efi"+ services: { name: string; targetPort: number; protocol: string }[]+ probes?: { readinessProbe?: Record<string, unknown>; livenessProbe?: Record<string, unknown> }+ phase: string+ totalCount: number+ availableCount: number+ claimedCount: number+ }> => {+ const pool = await httpK8s<{+ metadata: { name: string; namespace: string }+ spec: {+ replicas: number+ template: { containerDiskImage: string; cpuCores: number; memory: string; firmware?: string; probes?: Record<string, unknown> }+ services?: { name: string; targetPort: number; protocol?: string }[]+ }+ status?: {+ phase?: string+ totalCount?: number+ availableCount?: number+ claimedCount?: number+ }+ }>(`apis/cua.ai/v1/namespaces/${encodeURIComponent(namespace)}/osgymworkspacepools/${encodeURIComponent(name)}`)+ return {+ name: pool.metadata.name,+ namespace: pool.metadata.namespace,+ replicas: pool.spec.replicas,+ cpu: pool.spec.template.cpuCores,+ ram: pool.spec.template.memory,+ ociImage: pool.spec.template.containerDiskImage,+ firmware: pool.spec.template.firmware as "bios" | "efi" | undefined,+ services: (pool.spec.services ?? []).map(s => ({+ name: s.name,+ targetPort: s.targetPort,+ protocol: s.protocol ?? "TCP",+ })),+ probes: pool.spec.template.probes as { readinessProbe?: Record<string, unknown>; livenessProbe?: Record<string, unknown> } | undefined,+ phase: pool.status?.phase ?? "Unknown",+ totalCount: pool.status?.totalCount ?? 0,+ availableCount: pool.status?.availableCount ?? 0,+ claimedCount: pool.status?.claimedCount ?? 0,+ }+ },++ listPools: async (): Promise<{+ name: string+ namespace: string+ replicas: number+ phase: string+ availableCount: number+ }[]> => {+ // Capsule restricts users to their own namespaces — cluster-wide list+ // is forbidden. Instead, fetch the user's namespaces and list pools+ // in each one.+ const namespaces = await namespacesApi.list()+ const pools: {+ name: string+ namespace: string+ replicas: number+ phase: string+ availableCount: number+ }[] = []+ await Promise.all(+ namespaces.map(async (ns) => {+ try {+ const list = await httpK8s<{+ items: {+ metadata: { name: string; namespace: string }+ spec: { replicas: number }+ status?: { phase?: string; availableCount?: number }+ }[]+ }>(`apis/cua.ai/v1/namespaces/${encodeURIComponent(ns.name)}/osgymworkspacepools`)+ for (const p of list.items) {+ pools.push({+ name: p.metadata.name,+ namespace: p.metadata.namespace,+ replicas: p.spec.replicas,+ phase: p.status?.phase ?? "Unknown",+ availableCount: p.status?.availableCount ?? 0,+ })+ }+ } catch {+ // Namespace may not have pool CRD access — skip+ }+ }),+ )+ return pools.sort((a, b) => a.name.localeCompare(b.name))+ },++ // Per-pool orchestrator (osgym FastAPI inside the pool's namespace).+ listPoolVms: (namespace: string, poolName: string) =>+ httpOrch<OrchestratorPoolStatus>(+ namespace,+ `${poolName}-orchestrator`,+ "/pool",+ ),++ listOrchestratorEvents: (+ namespace: string,+ poolName: string,+ limit = 200,+ ) =>+ httpOrch<OrchestratorEventsResponse>(+ namespace,+ `${poolName}-orchestrator`,+ `/events?limit=${limit}`,+ ),++ // Shared Prom in cyclops-cs ns; Service listens on port 80 → 9090, so+ // the existing /orch-api/<ns>/<svc>/<path> proxy hits it unchanged.+ queryProm: (promql: string) =>+ httpOrch<PromQueryResponse>(+ "cyclops-cs",+ "prometheus",+ `/api/v1/query?query=${encodeURIComponent(promql)}`,+ ),++ // K8s direct (via kubectl-proxy sidecar). The replica detail page uses+ // these to find the virt-launcher pod for a given VM and read its metrics.+ findLauncherPod: async (+ namespace: string,+ vmName: string,+ ): Promise<PodSummary | null> => {+ const list = await httpK8s<PodList>(+ `api/v1/namespaces/${encodeURIComponent(namespace)}/pods` ++ `?labelSelector=${encodeURIComponent(`vm.kubevirt.io/name=${vmName}`)}` ++ "&limit=1",+ )+ return list.items[0] ?? null+ },++ // Locate the orchestrator (osgym) pod for a pool. The orchestrator+ // Deployment sets `app=<poolName>-orchestrator` (see+ // charts/osgym-workspace-test/templates/orchestrator-deploy.yaml).+ findPoolOrchestratorPod: async (+ namespace: string,+ poolName: string,+ ): Promise<PodSummary | null> => {+ const list = await httpK8s<PodList>(+ `api/v1/namespaces/${encodeURIComponent(namespace)}/pods` ++ `?labelSelector=${encodeURIComponent(`app=${poolName}-orchestrator`)}` ++ "&limit=1",+ )+ return list.items[0] ?? null+ },++ // Locate the centralized pool-operator pod. Deployed cluster-wide in the+ // `osgym` namespace with label `app=osgym-pool-operator` (see+ // clusters/kopf-k3s/osgym/pool-operator.yaml).+ findPoolOperatorPod: async (): Promise<PodSummary | null> => {+ const list = await httpK8s<PodList>(+ "api/v1/namespaces/osgym/pods" ++ `?labelSelector=${encodeURIComponent("app=osgym-pool-operator")}` ++ "&limit=1",+ )+ return list.items[0] ?? null+ },++ listNodes: () => httpK8s<NodeList>("api/v1/nodes"),++ // Cluster-wide list of KubeVirt launcher pods (one per VM replica).+ // Filters by the `vm.kubevirt.io/name` label so we only return virt-launcher+ // pods, not the orchestrator or other workloads.+ listVmPods: () =>+ httpK8s<PodList>(+ `api/v1/pods?labelSelector=${encodeURIComponent("vm.kubevirt.io/name")}`,+ ),++ getPodMetrics: (namespace: string, podName: string) =>+ httpK8s<PodMetrics>(+ "apis/metrics.k8s.io/v1beta1/namespaces/" ++ `${encodeURIComponent(namespace)}/pods/${encodeURIComponent(podName)}`,+ ),++ // K8s events for OSGymWorkspacePool resources — what the pool-operator+ // emits via kopf for handler outcomes (Normal/Warning, reason, message).+ // Cluster-wide; filtered server-side by involvedObject.kind.+ listOperatorEvents: () =>+ httpK8s<KubernetesEventList>(+ `api/v1/events?fieldSelector=${encodeURIComponent("involvedObject.kind=OSGymWorkspacePool")}&limit=500`,+ ),++ // Stream pod logs via K8s API (follow mode). Returns the URL for+ // fetch() with ReadableStream — the caller reads lines incrementally.+ // Routed through the cyclops-cs backend sidecar (Keycloak SSO + OPA),+ // which proxies to the kubectl-proxy sidecar.+ podLogsUrl: (namespace: string, podName: string, container: string) =>+ `/api/k8s/api/v1/namespaces/${encodeURIComponent(namespace)}/pods/` ++ `${encodeURIComponent(podName)}/log?container=${encodeURIComponent(container)}` ++ "&follow=true&tailLines=200",++ // Restart a KubeVirt VM replica via the subresources API.+ // This is equivalent to `virtctl restart <vm>` — the VMI is+ // terminated and a new one is started from the same VM spec.+ // Requires the subresources.kubevirt.io/virtualmachines/restart ClusterRole+ // rule added in clusters/kopf-k3s/cyclops-cs/rbac.yaml.+ restartVm: (namespace: string, vmName: string) =>+ httpK8s<void>(+ `apis/subresources.kubevirt.io/v1/namespaces/` ++ `${encodeURIComponent(namespace)}/virtualmachines/` ++ `${encodeURIComponent(vmName)}/restart`,+ { method: "PUT", body: JSON.stringify({}) },+ ),++ // Rollout-restart the pool's orchestrator Deployment.+ // Equivalent to `kubectl rollout restart deployment/<poolName>-orchestrator`.+ // Patches spec.template.metadata.annotations with a restartedAt timestamp+ // so K8s triggers a new rollout without changing the Deployment spec.+ // Requires apps/deployments patch permission in the ClusterRole.+ restartOrchestrator: (namespace: string, poolName: string) =>+ httpK8s<void>(+ `apis/apps/v1/namespaces/${encodeURIComponent(namespace)}/` ++ `deployments/${encodeURIComponent(`${poolName}-orchestrator`)}`,+ {+ method: "PATCH",+ headers: { "Content-Type": "application/strategic-merge-patch+json" },+ body: JSON.stringify({+ spec: {+ template: {+ metadata: {+ annotations: {+ "kubectl.kubernetes.io/restartedAt": new Date().toISOString(),+ },+ },+ },+ },+ }),+ },+ ),+}++// ── Namespace types ────────────────────────────────────────────────────++export interface Namespace {+ name: string+ status: string+ createdAt: string+ labels: Record<string, string> | null+}++// `/api/namespaces` — Capsule-backed per-user namespace CRUD.+const httpNamespaces = <T>(path: string, init?: RequestInit) =>+ fetchJson<T>(`/api/namespaces${path}`, init)++export const namespacesApi = {+ list: () => httpNamespaces<Namespace[]>(""),++ create: (name: string) =>+ httpNamespaces<Namespace>("", {+ method: "POST",+ body: JSON.stringify({ name }),+ }),++ remove: (name: string) =>+ httpNamespaces<void>(`/${encodeURIComponent(name)}`, {+ method: "DELETE",+ }),+}++// ── Pool templates ─────────────────────────────────────────────────────+//+// Per-user saved pool configs, persisted in Redis by the backend+// (/api/pool-templates). The stored `config` is exactly the object the SPA+// passes to api.createPool — so creating a pool from a template just feeds+// it back into the New pool form.++// Optional autoscaling extension. Threaded verbatim onto the pool's+// generated OSGymSandboxWarmPool.spec.autoscaling by the compat shim,+// opting the pool into KEDA autoscaling on claim demand.+export interface PoolAutoscalingConfig {+ minPoolSize?: number+ initialPoolSize?: number+ maxPoolSize?: number+}++export interface PoolTemplateConfig {+ cpu: number+ ram: string+ ociImage: string+ replicas: number+ // VM firmware: "efi" for GPT/UEFI-only images (e.g. the Windows+ // desktop-workspace); omitted/"bios" boots KubeVirt's legacy-BIOS default.+ firmware?: "bios" | "efi"+ // runtime=macos provisions macOS sandboxes (admin-only). Omitted =+ // a KubeVirt VM pool (the default for all customer pools).+ runtime?: "kubevirt" | "macos" | "gvisor"+ services?: { name: string; targetPort: number; protocol: string }[]+ probes?: {+ readinessProbe?: Record<string, unknown>+ livenessProbe?: Record<string, unknown>+ }+ autoscaling?: PoolAutoscalingConfig+}++export interface PoolTemplate {+ user: string+ name: string+ createdAt: string+ config: PoolTemplateConfig+}++const httpPoolTemplates = <T>(path: string, init?: RequestInit) =>+ fetchJson<T>(`/api/pool-templates${path}`, init)++export const poolTemplatesApi = {+ list: async (): Promise<PoolTemplate[]> => {+ const res = await httpPoolTemplates<PoolTemplate[]>("")+ return res ?? []+ },++ create: (name: string, config: PoolTemplateConfig) =>+ httpPoolTemplates<PoolTemplate>("", {+ method: "POST",+ body: JSON.stringify({ name, config }),+ }),++ remove: (name: string) =>+ httpPoolTemplates<void>(`/${encodeURIComponent(name)}`, {+ method: "DELETE",+ }),+}++// ── User API keys ─────────────────────────────────────────────────────++export interface UserApiKey {+ id: string+ client_id: string+ name: string+ scope: string[]+}++export interface NewUserApiKey {+ client_id: string+ client_secret: string+ token_url: string+ name: string+ scope: string[]+}++export const userKeysApi = {+ list: async (): Promise<UserApiKey[]> => {+ const res = await fetchJson<{ keys: UserApiKey[] }>("/api/user-keys")+ return res.keys ?? []+ },++ create: async (name: string, scope?: string[]): Promise<NewUserApiKey> => {+ return fetchJson<NewUserApiKey>("/api/user-keys", {+ method: "POST",+ body: JSON.stringify({ name, scope: scope ?? [] }),+ })+ },++ remove: async (id: string): Promise<void> => {+ await fetchJson<void>(`/api/user-keys/${encodeURIComponent(id)}`, {+ method: "DELETE",+ })+ },+}++// ── OSGymSandboxClaim (osgym.cua.ai/v1alpha1) ────────────────────────++export interface Claim {+ name: string+ namespace: string+ templateRef: string+ warmpool: string+ phase: string+ sandboxName?: string+ sandboxService?: string+ createdAt: string+}++function parseClaim(raw: any): Claim {+ const meta = raw.metadata || {}+ const spec = raw.spec || {}+ const status = raw.status || {}+ return {+ name: meta.name ?? "",+ namespace: meta.namespace ?? "",+ templateRef: (spec.sandboxTemplateRef || {}).name ?? "",+ warmpool: spec.warmpool ?? "default",+ phase: status.phase ?? "Pending",+ sandboxName: (status.sandbox || {}).name,+ sandboxService: (status.sandbox || {}).service,+ createdAt: meta.creationTimestamp ?? "",+ }+}++const CLAIM_GROUP = "osgym.cua.ai"+const CLAIM_VERSION = "v1alpha1"+const CLAIM_PLURAL = "osgymsandboxclaims"++export const claimsApi = {+ list: async (namespace: string): Promise<Claim[]> => {+ const data = await httpK8s<{ items: any[] }>(+ `apis/${CLAIM_GROUP}/${CLAIM_VERSION}/namespaces/${encodeURIComponent(namespace)}/${CLAIM_PLURAL}`,+ )+ return (data.items || []).map(parseClaim)+ },++ create: async (+ namespace: string,+ name: string,+ templateRef: string,+ ): Promise<Claim> => {+ const raw = await httpK8s<any>(+ `apis/${CLAIM_GROUP}/${CLAIM_VERSION}/namespaces/${encodeURIComponent(namespace)}/${CLAIM_PLURAL}`,+ {+ method: "POST",+ body: JSON.stringify({+ apiVersion: `${CLAIM_GROUP}/${CLAIM_VERSION}`,+ kind: "OSGymSandboxClaim",+ metadata: { name },+ spec: {+ sandboxTemplateRef: { name: templateRef },+ },+ }),+ },+ )+ return parseClaim(raw)+ },++ get: async (namespace: string, name: string): Promise<Claim> => {+ const raw = await httpK8s<any>(+ `apis/${CLAIM_GROUP}/${CLAIM_VERSION}/namespaces/${encodeURIComponent(namespace)}/${CLAIM_PLURAL}/${encodeURIComponent(name)}`,+ )+ return parseClaim(raw)+ },++ remove: async (namespace: string, name: string): Promise<void> => {+ await httpK8s<void>(+ `apis/${CLAIM_GROUP}/${CLAIM_VERSION}/namespaces/${encodeURIComponent(namespace)}/${CLAIM_PLURAL}/${encodeURIComponent(name)}`,+ { method: "DELETE" },+ )+ },+}++// ── Unit parsing ────────────────────────────────────────────────────────+//+// metrics-server returns CPU as `<n>n` (nanocores) and memory as+// `<n>Ki|Mi|Gi` (binary suffix). Helpers convert to floats.++const MEM_SUFFIX: Record<string, number> = {+ "": 1,+ Ki: 1024,+ Mi: 1024 ** 2,+ Gi: 1024 ** 3,+ Ti: 1024 ** 4,+ // Decimal suffixes (rare) — handled defensively.+ K: 1000,+ M: 1000 ** 2,+ G: 1000 ** 3,+ T: 1000 ** 4,+}++export function parseCpuCores(v: string): number {+ // Forms seen: "159687357n", "0.250", "100m"+ if (!v) return 0+ if (v.endsWith("n")) return parseInt(v.slice(0, -1), 10) / 1e9+ if (v.endsWith("u")) return parseInt(v.slice(0, -1), 10) / 1e6+ if (v.endsWith("m")) return parseInt(v.slice(0, -1), 10) / 1000+ return parseFloat(v)+}++export function parseMemoryBytes(v: string): number {+ if (!v) return 0+ const m = v.match(/^(\d+(?:\.\d+)?)([KMGTP]i?)?$/)+ if (!m) return parseFloat(v) || 0+ const mult = MEM_SUFFIX[m[2] ?? ""] ?? 1+ return parseFloat(m[1]) * mult+}++export function sumPodUsage(metrics: PodMetrics): {+ cpuCores: number+ memBytes: number+} {+ let cpu = 0+ let mem = 0+ for (const c of metrics.containers ?? []) {+ cpu += parseCpuCores(c.usage?.cpu ?? "0")+ mem += parseMemoryBytes(c.usage?.memory ?? "0")+ }+ return { cpuCores: cpu, memBytes: mem }+}+diff --git a/libs/fleet/src/api/featureFlags.ts b/libs/fleet/src/api/featureFlags.tsnew file mode 100644index 0000000000..77a32d0049--- /dev/null+++ b/libs/fleet/src/api/featureFlags.ts@@ -0,0 +1,54 @@+// Feature flags client — fetches /api/config to get per-user flags.+// The backend derives admin status from the OpenFeature flag+// `/feature-flags/cyclops-cs/admin-subs` (AWS SSM Parameter Store in prod,+// or the CYCLOPS_CS_ADMIN_SUBS env var in dev) — a JSON array of Keycloak+// sub UUIDs. Access to infra-only resources is also enforced server-side by+// the backend's OPA policy, not just by hiding nav here.++import { getToken } from "../auth/keycloak"++export interface FeatureFlags {+ /** Admin users see the full infra UI: Nodes and Operator events. */+ admin: boolean+}++const DEFAULT_FLAGS: FeatureFlags = {+ admin: false,+}++let _cache: FeatureFlags | null = null+let _fetchPromise: Promise<FeatureFlags> | null = null++export async function fetchFeatureFlags(): Promise<FeatureFlags> {+ if (_cache) return _cache+ if (_fetchPromise) return _fetchPromise++ _fetchPromise = (async () => {+ try {+ const token = await getToken()+ const res = await fetch("/api/config", {+ headers: {+ Authorization: token ? `Bearer ${token}` : "",+ "Content-Type": "application/json",+ },+ })+ if (!res.ok) return DEFAULT_FLAGS+ const data = (await res.json()) as FeatureFlags+ _cache = {+ admin: data.admin ?? false,+ }+ return _cache+ } catch {+ return DEFAULT_FLAGS+ } finally {+ _fetchPromise = null+ }+ })()++ return _fetchPromise+}++/** Invalidate the cache (e.g., after login). */+export function invalidateFeatureFlags(): void {+ _cache = null+}diff --git a/libs/fleet/src/api/generated/cyclops-cs-backend.ts b/libs/fleet/src/api/generated/cyclops-cs-backend.tsnew file mode 100644index 0000000000..0e3a03978e--- /dev/null+++ b/libs/fleet/src/api/generated/cyclops-cs-backend.ts@@ -0,0 +1,1025 @@+/* eslint-disable */+/* tslint:disable */+// @ts-nocheck+/*+ * ---------------------------------------------------------------+ * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##+ * ## ##+ * ## AUTHOR: acacode ##+ * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##+ * ---------------------------------------------------------------+ */++export interface HandlersConfigResponse {+ /**+ * Admin is true when the caller is in input.flags.admin_subs (OPA-evaluated).+ * Non-admins get the customer view: infra-only nav (Nodes, Operator events)+ * is hidden in the SPA and the corresponding kubectl-proxy paths are denied+ * server-side by authz.rego.+ */+ admin?: boolean;+}++export interface HandlersCreateKeyRequest {+ /** @example "ci-prod" */+ name?: string;+ /** @example "test-pool" */+ namespace?: string;+}++export interface HandlersCreateKeyResponse {+ client_id?: string;+ client_secret?: string;+ name?: string;+ namespace?: string;+ token_url?: string;+}++export interface HandlersCreateNamespaceRequest {+ /** @example "my-workspace" */+ name?: string;+}++export interface HandlersCreatePoolTemplateRequest {+ config?: object;+ /** @example "gpu-large" */+ name?: string;+}++export interface HandlersCreateUserKeyRequest {+ /** @example "my-ci-key" */+ name?: string;+ /** @example ["[\"ns1\"","\"ns2\"]"] */+ scope?: string[];+}++export interface HandlersCreateUserKeyResponse {+ client_id?: string;+ client_secret?: string;+ name?: string;+ scope?: string[];+ token_url?: string;+}++export interface HandlersErrorResponse {+ error?: string;+}++export interface HandlersHealthResponse {+ ok?: boolean;+}++export interface HandlersListKeysResponse {+ keys?: KeycloakKeyClient[];+}++export interface HandlersListUserKeysResponse {+ keys?: HandlersUserKeyResponse[];+}++export interface HandlersNamespaceResponse {+ createdAt?: string;+ labels?: Record<string, string>;+ name?: string;+ status?: string;+}++export interface HandlersPoolTemplateResponse {+ config?: object;+ createdAt?: string;+ name?: string;+ user?: string;+}++export interface HandlersUserKeyResponse {+ client_id?: string;+ id?: string;+ name?: string;+ scope?: string[];+}++export interface KeycloakKeyClient {+ client_id?: string;+ id?: string;+ name?: string;+ namespace?: string;+ owner_sub?: string;+}++export type BatchLanesCreateError = Record<string, string>;++export type BatchLanesDeleteError = Record<string, string>;++export type BatchSubmitCreateError = Record<string, string>;++export type BatchDeleteError = Record<string, string>;++export type BatchResultsListError = Record<string, string>;++export type BatchStatusListError = Record<string, string>;++export type ConfigListData = HandlersConfigResponse;++export type ConfigListError = HandlersErrorResponse;++export type GatewayDetailData = string;++export type GatewayDetailError = HandlersErrorResponse;++export type GetK8SData = string;++export type GetK8SError = HandlersErrorResponse;++export type KeysListData = HandlersListKeysResponse;++export type KeysListError = HandlersErrorResponse;++export type KeysCreateData = HandlersCreateKeyResponse;++export type KeysCreateError = HandlersErrorResponse;++export type KeysDeleteData = any;++export type KeysDeleteError = HandlersErrorResponse;++export type LabelDeleteError = Record<string, string>;++export type LabelBatchCreateError = Record<string, string>;++export type LabelResultsListError = Record<string, string>;++export type LabelStatusListError = Record<string, string>;++export type NamespacesListData = HandlersNamespaceResponse[];++export type NamespacesListError = HandlersErrorResponse;++export type NamespacesCreateData = HandlersNamespaceResponse;++export type NamespacesCreateError = HandlersErrorResponse;++export type NamespacesDeleteData = any;++export type NamespacesDeleteError = HandlersErrorResponse;++export type OrchDetailData = string;++export type OrchDetailError = HandlersErrorResponse;++export type PoolTemplatesListData = HandlersPoolTemplateResponse[];++export type PoolTemplatesListError = HandlersErrorResponse;++export type PoolTemplatesCreateData = HandlersPoolTemplateResponse;++export type PoolTemplatesCreateError = HandlersErrorResponse;++export type PoolTemplatesDetailData = HandlersPoolTemplateResponse;++export type PoolTemplatesDetailError = HandlersErrorResponse;++export type PoolTemplatesDeleteData = any;++export type PoolTemplatesDeleteError = HandlersErrorResponse;++export type GetSvcData = string;++export type GetSvcError = HandlersErrorResponse;++export type UserKeysListData = HandlersListUserKeysResponse;++export type UserKeysListError = HandlersErrorResponse;++export type UserKeysCreateData = HandlersCreateUserKeyResponse;++export type UserKeysCreateError = HandlersErrorResponse;++export type UserKeysDeleteData = any;++export type UserKeysDeleteError = HandlersErrorResponse;++export type HealthzListData = HandlersHealthResponse;++export type QueryParamsType = Record<string | number, any>;+export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;++export interface FullRequestParams extends Omit<RequestInit, "body"> {+ /** set parameter to `true` for call `securityWorker` for this request */+ secure?: boolean;+ /** request path */+ path: string;+ /** content type of request body */+ type?: ContentType;+ /** query params */+ query?: QueryParamsType;+ /** format of response (i.e. response.json() -> format: "json") */+ format?: ResponseFormat;+ /** request body */+ body?: unknown;+ /** base url */+ baseUrl?: string;+ /** request cancellation token */+ cancelToken?: CancelToken;+}++export type RequestParams = Omit<+ FullRequestParams,+ "body" | "method" | "query" | "path"+>;++export interface ApiConfig<SecurityDataType = unknown> {+ baseUrl?: string;+ baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;+ securityWorker?: (+ securityData: SecurityDataType | null,+ ) => Promise<RequestParams | void> | RequestParams | void;+ customFetch?: typeof fetch;+}++export interface HttpResponse<D extends unknown, E extends unknown = unknown>+ extends Response {+ data: D;+ error: E;+}++type CancelToken = Symbol | string | number;++export enum ContentType {+ Json = "application/json",+ JsonApi = "application/vnd.api+json",+ FormData = "multipart/form-data",+ UrlEncoded = "application/x-www-form-urlencoded",+ Text = "text/plain",+}++export class HttpClient<SecurityDataType = unknown> {+ public baseUrl: string = "/";+ private securityData: SecurityDataType | null = null;+ private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];+ private abortControllers = new Map<CancelToken, AbortController>();+ private customFetch = (...fetchParams: Parameters<typeof fetch>) =>+ fetch(...fetchParams);++ private baseApiParams: RequestParams = {+ credentials: "same-origin",+ headers: {},+ redirect: "follow",+ referrerPolicy: "no-referrer",+ };++ constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {+ Object.assign(this, apiConfig);+ }++ public setSecurityData = (data: SecurityDataType | null) => {+ this.securityData = data;+ };++ protected encodeQueryParam(key: string, value: any) {+ const encodedKey = encodeURIComponent(key);+ return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`;+ }++ protected addQueryParam(query: QueryParamsType, key: string) {+ return this.encodeQueryParam(key, query[key]);+ }++ protected addArrayQueryParam(query: QueryParamsType, key: string) {+ const value = query[key];+ return value.map((v: any) => this.encodeQueryParam(key, v)).join("&");+ }++ protected toQueryString(rawQuery?: QueryParamsType): string {+ const query = rawQuery || {};+ const keys = Object.keys(query).filter(+ (key) => "undefined" !== typeof query[key],+ );+ return keys+ .map((key) =>+ Array.isArray(query[key])+ ? this.addArrayQueryParam(query, key)+ : this.addQueryParam(query, key),+ )+ .join("&");+ }++ protected addQueryParams(rawQuery?: QueryParamsType): string {+ const queryString = this.toQueryString(rawQuery);+ return queryString ? `?${queryString}` : "";+ }++ private contentFormatters: Record<ContentType, (input: any) => any> = {+ [ContentType.Json]: (input: any) =>+ input !== null && (typeof input === "object" || typeof input === "string")+ ? JSON.stringify(input)+ : input,+ [ContentType.JsonApi]: (input: any) =>+ input !== null && (typeof input === "object" || typeof input === "string")+ ? JSON.stringify(input)+ : input,+ [ContentType.Text]: (input: any) =>+ input !== null && typeof input !== "string"+ ? JSON.stringify(input)+ : input,+ [ContentType.FormData]: (input: any) =>+ Object.keys(input || {}).reduce((formData, key) => {+ const property = input[key];+ formData.append(+ key,+ property instanceof Blob+ ? property+ : typeof property === "object" && property !== null+ ? JSON.stringify(property)+ : `${property}`,+ );+ return formData;+ }, new FormData()),+ [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),+ };++ protected mergeRequestParams(+ params1: RequestParams,+ params2?: RequestParams,+ ): RequestParams {+ return {+ ...this.baseApiParams,+ ...params1,+ ...(params2 || {}),+ headers: {+ ...(this.baseApiParams.headers || {}),+ ...(params1.headers || {}),+ ...((params2 && params2.headers) || {}),+ },+ };+ }++ protected createAbortSignal = (+ cancelToken: CancelToken,+ ): AbortSignal | undefined => {+ if (this.abortControllers.has(cancelToken)) {+ const abortController = this.abortControllers.get(cancelToken);+ if (abortController) {+ return abortController.signal;+ }+ return void 0;+ }++ const abortController = new AbortController();+ this.abortControllers.set(cancelToken, abortController);+ return abortController.signal;+ };++ public abortRequest = (cancelToken: CancelToken) => {+ const abortController = this.abortControllers.get(cancelToken);++ if (abortController) {+ abortController.abort();+ this.abortControllers.delete(cancelToken);+ }+ };++ public request = async <T = any, E = any>({+ body,+ secure,+ path,+ type,+ query,+ format,+ baseUrl,+ cancelToken,+ ...params+ }: FullRequestParams): Promise<HttpResponse<T, E>> => {+ const secureParams =+ ((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&+ this.securityWorker &&+ (await this.securityWorker(this.securityData))) ||+ {};+ const requestParams = this.mergeRequestParams(params, secureParams);+ const queryString = query && this.toQueryString(query);+ const payloadFormatter = this.contentFormatters[type || ContentType.Json];+ const responseFormat = format || requestParams.format;++ return this.customFetch(+ `${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`,+ {+ ...requestParams,+ headers: {+ ...(requestParams.headers || {}),+ ...(type && type !== ContentType.FormData+ ? { "Content-Type": type }+ : {}),+ },+ signal:+ (cancelToken+ ? this.createAbortSignal(cancelToken)+ : requestParams.signal) || null,+ body:+ typeof body === "undefined" || body === null+ ? null+ : payloadFormatter(body),+ },+ ).then(async (response) => {+ const r = response.clone() as HttpResponse<T, E>;+ r.data = null as unknown as T;+ r.error = null as unknown as E;++ const data = !responseFormat+ ? r+ : await response[responseFormat]()+ .then((data) => {+ if (r.ok) {+ r.data = data;+ } else {+ r.error = data;+ }+ return r;+ })+ .catch((e) => {+ r.error = e;+ return r;+ });++ if (cancelToken) {+ this.abortControllers.delete(cancelToken);+ }++ if (!response.ok) throw data;+ return data;+ });+ };+}++/**+ * @title Cyclops CS Backend API+ * @version 0.1+ * @baseUrl /+ * @contact+ *+ * Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key management, service proxies (k8s / orch / svc), namespace management, and deprecated gateway / batch / label routes that now return 410 Gone. All pool operations use OSGymSandboxClaim CRs (Path B).+ */+export class Api<+ SecurityDataType extends unknown,+> extends HttpClient<SecurityDataType> {+ /**+ * No description+ *+ * @tags health+ * @name HealthzList+ * @summary Liveness/readiness probe+ * @request GET:/healthz+ */+ healthzList = (params: RequestParams = {}) =>+ this.request<HealthzListData, any>({+ path: `/healthz`,+ method: "GET",+ format: "json",+ ...params,+ });++ batch = {+ /**+ * @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.+ *+ * @tags batch+ * @name BatchLanesCreate+ * @summary Deprecated batch lane acquisition route+ * @request POST:/api/batch/{pool}/lanes+ * @deprecated+ * @secure+ */+ batchLanesCreate: (pool: string, params: RequestParams = {}) =>+ this.request<any, BatchLanesCreateError>({+ path: `/api/batch/${pool}/lanes`,+ method: "POST",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name BatchLanesDelete+ * @summary Deprecated batch lane release route+ * @request DELETE:/api/batch/{pool}/lanes+ * @deprecated+ * @secure+ */+ batchLanesDelete: (pool: string, params: RequestParams = {}) =>+ this.request<any, BatchLanesDeleteError>({+ path: `/api/batch/${pool}/lanes`,+ method: "DELETE",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name BatchSubmitCreate+ * @summary Deprecated batch submission route+ * @request POST:/api/batch/{pool}/submit+ * @deprecated+ * @secure+ */+ batchSubmitCreate: (pool: string, params: RequestParams = {}) =>+ this.request<any, BatchSubmitCreateError>({+ path: `/api/batch/${pool}/submit`,+ method: "POST",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name BatchDelete+ * @summary Deprecated batch cancellation route+ * @request DELETE:/api/batch/{pool}/{id}+ * @deprecated+ * @secure+ */+ batchDelete: (pool: string, id: string, params: RequestParams = {}) =>+ this.request<any, BatchDeleteError>({+ path: `/api/batch/${pool}/${id}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name BatchResultsList+ * @summary Deprecated batch results route+ * @request GET:/api/batch/{pool}/{id}/results+ * @deprecated+ * @secure+ */+ batchResultsList: (pool: string, id: string, params: RequestParams = {}) =>+ this.request<any, BatchResultsListError>({+ path: `/api/batch/${pool}/${id}/results`,+ method: "GET",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name BatchStatusList+ * @summary Deprecated batch status route+ * @request GET:/api/batch/{pool}/{id}/status+ * @deprecated+ * @secure+ */+ batchStatusList: (pool: string, id: string, params: RequestParams = {}) =>+ this.request<any, BatchStatusListError>({+ path: `/api/batch/${pool}/${id}/status`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ config = {+ /**+ * @description Returns OPA-evaluated feature flags for the authenticated SPA user. `admin` is true when the caller's JWT sub appears in input.flags.admin_subs.+ *+ * @tags config+ * @name ConfigList+ * @summary Per-user feature flags+ * @request GET:/api/config+ * @secure+ */+ configList: (params: RequestParams = {}) =>+ this.request<ConfigListData, ConfigListError>({+ path: `/api/config`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),+ };+ gateway = {+ /**+ * @description DEPRECATED (CUA-609): The per-pool orchestrator HTTP layer has been removed. This route returns 410 Gone for all requests. All pool operations must use OSGymSandboxClaim CRs (Path B) directly.+ *+ * @tags gateway+ * @name GatewayDetail+ * @summary Reverse-proxy to the per-pool orchestrator (sole ingress path — CUA-527)+ * @request GET:/api/gateway/{name}/{path}+ * @secure+ */+ gatewayDetail: (name: string, path?: string, params: RequestParams = {}) =>+ this.request<GatewayDetailData, GatewayDetailError>({+ path: `/api/gateway/${name}/${path}`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ 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).+ *+ * @tags passthrough+ * @name GetK8S+ * @summary Authenticated proxy to the in-pod kubectl-proxy sidecar+ * @request GET:/api/k8s/{path}+ * @secure+ */+ getK8S: (path: string, params: RequestParams = {}) =>+ this.request<GetK8SData, GetK8SError>({+ path: `/api/k8s/${path}`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ keys = {+ /**+ * No description+ *+ * @tags keys+ * @name KeysList+ * @summary List the calling user's API keys+ * @request GET:/api/keys+ * @secure+ */+ keysList: (params: RequestParams = {}) =>+ this.request<KeysListData, KeysListError>({+ path: `/api/keys`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * @description Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is shown exactly once.+ *+ * @tags keys+ * @name KeysCreate+ * @summary Create a new API key+ * @request POST:/api/keys+ * @secure+ */+ keysCreate: (body: HandlersCreateKeyRequest, params: RequestParams = {}) =>+ this.request<KeysCreateData, KeysCreateError>({+ path: `/api/keys`,+ method: "POST",+ body: body,+ secure: true,+ type: ContentType.Json,+ format: "json",+ ...params,+ }),++ /**+ * No description+ *+ * @tags keys+ * @name KeysDelete+ * @summary Revoke an API key by Keycloak client UUID+ * @request DELETE:/api/keys/{id}+ * @secure+ */+ keysDelete: (id: string, params: RequestParams = {}) =>+ this.request<KeysDeleteData, KeysDeleteError>({+ path: `/api/keys/${id}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),+ };+ label = {+ /**+ * @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.+ *+ * @tags batch+ * @name LabelDelete+ * @summary Deprecated label cancellation route+ * @request DELETE:/api/label/{pool}/{label}+ * @deprecated+ * @secure+ */+ labelDelete: (pool: string, label: string, params: RequestParams = {}) =>+ this.request<any, LabelDeleteError>({+ path: `/api/label/${pool}/${label}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name LabelBatchCreate+ * @summary Deprecated label batch submission route+ * @request POST:/api/label/{pool}/{label}/batch+ * @deprecated+ * @secure+ */+ labelBatchCreate: (+ pool: string,+ label: string,+ params: RequestParams = {},+ ) =>+ this.request<any, LabelBatchCreateError>({+ path: `/api/label/${pool}/${label}/batch`,+ method: "POST",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name LabelResultsList+ * @summary Deprecated label results route+ * @request GET:/api/label/{pool}/{label}/results+ * @deprecated+ * @secure+ */+ labelResultsList: (+ pool: string,+ label: string,+ params: RequestParams = {},+ ) =>+ this.request<any, LabelResultsListError>({+ path: `/api/label/${pool}/${label}/results`,+ method: "GET",+ secure: true,+ ...params,+ }),++ /**+ * @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.+ *+ * @tags batch+ * @name LabelStatusList+ * @summary Deprecated label status route+ * @request GET:/api/label/{pool}/{label}/status+ * @deprecated+ * @secure+ */+ labelStatusList: (+ pool: string,+ label: string,+ params: RequestParams = {},+ ) =>+ this.request<any, LabelStatusListError>({+ path: `/api/label/${pool}/${label}/status`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ namespaces = {+ /**+ * @description Returns namespaces owned by the caller's Capsule Tenant. The list is scoped by a capsule.clastix.io/tenant=<tenant> label selector built from the authenticated subject, so it stays fail-closed even when Capsule Proxy isn't filtering.+ *+ * @tags namespaces+ * @name NamespacesList+ * @summary List the calling user's namespaces+ * @request GET:/api/namespaces+ * @secure+ */+ namespacesList: (params: RequestParams = {}) =>+ this.request<NamespacesListData, NamespacesListError>({+ path: `/api/namespaces`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * @description Creates a K8s namespace via impersonation. Capsule's webhook intercepts the creation and assigns it to the user's Tenant.+ *+ * @tags namespaces+ * @name NamespacesCreate+ * @summary Create a namespace for the calling user+ * @request POST:/api/namespaces+ * @secure+ */+ namespacesCreate: (+ body: HandlersCreateNamespaceRequest,+ params: RequestParams = {},+ ) =>+ this.request<NamespacesCreateData, NamespacesCreateError>({+ path: `/api/namespaces`,+ method: "POST",+ body: body,+ secure: true,+ type: ContentType.Json,+ format: "json",+ ...params,+ }),++ /**+ * @description Deletes a K8s namespace via impersonation. Capsule blocks deletion if the namespace doesn't belong to the user's Tenant.+ *+ * @tags namespaces+ * @name NamespacesDelete+ * @summary Delete a namespace owned by the calling user+ * @request DELETE:/api/namespaces/{name}+ * @secure+ */+ namespacesDelete: (name: string, params: RequestParams = {}) =>+ this.request<NamespacesDeleteData, NamespacesDeleteError>({+ path: `/api/namespaces/${name}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),+ };+ orch = {+ /**+ * @description Resolves <service>.<namespace>.svc.cluster.local at request time (in-cluster DNS). The caller must hold RBAC in {namespace} (verified via an impersonated RoleBinding probe); OPA additionally validates that namespace and service look like DNS-1123 labels.+ *+ * @tags passthrough+ * @name OrchDetail+ * @summary SPA-authenticated proxy to a per-namespace orchestrator service+ * @request GET:/api/orch/{namespace}/{service}/{path}+ * @secure+ */+ orchDetail: (+ namespace: string,+ service: string,+ path: string,+ params: RequestParams = {},+ ) =>+ this.request<OrchDetailData, OrchDetailError>({+ path: `/api/orch/${namespace}/${service}/${path}`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ poolTemplates = {+ /**+ * @description Returns every pool template owned by the calling user, newest first.+ *+ * @tags pool-templates+ * @name PoolTemplatesList+ * @summary List the calling user's pool templates+ * @request GET:/api/pool-templates+ * @secure+ */+ poolTemplatesList: (params: RequestParams = {}) =>+ this.request<PoolTemplatesListData, PoolTemplatesListError>({+ path: `/api/pool-templates`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * @description Stores the given pool config under a name owned by the calling user. Re-saving an existing name overwrites the config while preserving the original creation time. Use GET /api/pool-templates to list them and seed a new pool.+ *+ * @tags pool-templates+ * @name PoolTemplatesCreate+ * @summary Save a pool config as a reusable template+ * @request POST:/api/pool-templates+ * @secure+ */+ poolTemplatesCreate: (+ body: HandlersCreatePoolTemplateRequest,+ params: RequestParams = {},+ ) =>+ this.request<PoolTemplatesCreateData, PoolTemplatesCreateError>({+ path: `/api/pool-templates`,+ method: "POST",+ body: body,+ secure: true,+ type: ContentType.Json,+ format: "json",+ ...params,+ }),++ /**+ * No description+ *+ * @tags pool-templates+ * @name PoolTemplatesDetail+ * @summary Get one of the calling user's pool templates+ * @request GET:/api/pool-templates/{name}+ * @secure+ */+ poolTemplatesDetail: (name: string, params: RequestParams = {}) =>+ this.request<PoolTemplatesDetailData, PoolTemplatesDetailError>({+ path: `/api/pool-templates/${name}`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * No description+ *+ * @tags pool-templates+ * @name PoolTemplatesDelete+ * @summary Delete one of the calling user's pool templates+ * @request DELETE:/api/pool-templates/{name}+ * @secure+ */+ poolTemplatesDelete: (name: string, params: RequestParams = {}) =>+ this.request<PoolTemplatesDeleteData, PoolTemplatesDeleteError>({+ path: `/api/pool-templates/${name}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),+ };+ svc = {+ /**+ * @description Proxies to {service}.{namespace}.svc.cluster.local:80. Per-key tokens are bound to their `namespace` claim; all other principals (SPA, user keys, oauth2-proxy browser sessions) must hold RBAC in {namespace}, verified via an impersonated RoleBinding probe. Strips Authorization before forwarding.+ *+ * @tags gateway+ * @name GetSvc+ * @summary Authenticated reverse proxy to a K8s Service in a namespace the caller owns+ * @request GET:/api/svc/{namespace}/{service}/{path}+ * @secure+ */+ getSvc: (+ namespace: string,+ service: string,+ path?: string,+ params: RequestParams = {},+ ) =>+ this.request<GetSvcData, GetSvcError>({+ path: `/api/svc/${namespace}/${service}/${path}`,+ method: "GET",+ secure: true,+ ...params,+ }),+ };+ userKeys = {+ /**+ * No description+ *+ * @tags user-keys+ * @name UserKeysList+ * @summary List the calling user's API keys+ * @request GET:/api/user-keys+ * @secure+ */+ userKeysList: (params: RequestParams = {}) =>+ this.request<UserKeysListData, UserKeysListError>({+ path: `/api/user-keys`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * @description Creates a Keycloak service-account client that acts on behalf of the calling user. The client_secret is returned exactly once; it cannot be retrieved later.+ *+ * @tags user-keys+ * @name UserKeysCreate+ * @summary Create a per-user API key+ * @request POST:/api/user-keys+ * @secure+ */+ userKeysCreate: (+ body: HandlersCreateUserKeyRequest,+ params: RequestParams = {},+ ) =>+ this.request<UserKeysCreateData, UserKeysCreateError>({+ path: `/api/user-keys`,+ method: "POST",+ body: body,+ secure: true,+ type: ContentType.Json,+ format: "json",+ ...params,+ }),++ /**+ * No description+ *+ * @tags user-keys+ * @name UserKeysDelete+ * @summary Revoke a per-user API key+ * @request DELETE:/api/user-keys/{id}+ * @secure+ */+ userKeysDelete: (id: string, params: RequestParams = {}) =>+ this.request<UserKeysDeleteData, UserKeysDeleteError>({+ path: `/api/user-keys/${id}`,+ method: "DELETE",+ secure: true,+ ...params,+ }),+ };+}diff --git a/libs/fleet/src/api/keys.ts b/libs/fleet/src/api/keys.tsnew file mode 100644index 0000000000..7c90b4dd45--- /dev/null+++ b/libs/fleet/src/api/keys.ts@@ -0,0 +1,36 @@+// Thin facade over the generated cyclops-cs-backend client.+//+// Existing components import { ApiKey, NewApiKey, keysApi } from "./keys"+// — keep that surface stable while delegating the actual HTTP calls to+// the swagger-generated client (src/api/generated/cyclops-cs-backend.ts).+// To regenerate the client after backend changes: pnpm gen:api++import { apiClient } from "./client"+import type {+ HandlersCreateKeyResponse,+ KeycloakKeyClient,+} from "./generated/cyclops-cs-backend"++export type ApiKey = Required<+ Pick<KeycloakKeyClient, "id" | "client_id" | "name" | "namespace" | "owner_sub">+>+export type NewApiKey = Required<+ Pick<+ HandlersCreateKeyResponse,+ "client_id" | "client_secret" | "token_url" | "name" | "namespace"+ >+>++export const keysApi = {+ list: async (): Promise<{ keys: ApiKey[] }> => {+ const res = await apiClient.keys.keysList()+ return { keys: (res.data.keys ?? []) as ApiKey[] }+ },+ create: async (name: string, namespace: string): Promise<NewApiKey> => {+ const res = await apiClient.keys.keysCreate({ name, namespace })+ return res.data as NewApiKey+ },+ remove: async (id: string): Promise<void> => {+ await apiClient.keys.keysDelete(id)+ },+}diff --git a/libs/fleet/src/api/pools.ts b/libs/fleet/src/api/pools.tsnew file mode 100644index 0000000000..4fc3544d04--- /dev/null+++ b/libs/fleet/src/api/pools.ts@@ -0,0 +1,34 @@+const tombstones = new Set<string>()++export function tombstonePool(name: string): void {+ tombstones.add(name)+}++export function reconcileTombstones(present: Iterable<string>): void {+ const names = new Set(present)+ for (const t of tombstones) if (!names.has(t)) tombstones.delete(t)+}++export function isTombstoned(name: string): boolean {+ return tombstones.has(name)+}++export type PoolStatus =+ | { kind: "healthy"; label: "Healthy" }+ | { kind: "provisioning"; label: "Provisioning" }+ | { kind: "terminating"; label: "Terminating" }+ | { kind: "unknown"; label: "Unknown" }++export function derivePoolStatus(pool: { name: string; phase: string }): PoolStatus {+ if (isTombstoned(pool.name)) {+ return { kind: "terminating", label: "Terminating" }+ }+ const phase = (pool.phase ?? "").toLowerCase()+ if (phase === "ready") {+ return { kind: "healthy", label: "Healthy" }+ }+ if (phase === "provisioning") {+ return { kind: "provisioning", label: "Provisioning" }+ }+ return { kind: "unknown", label: "Unknown" }+}diff --git a/libs/fleet/src/auth/AuthProvider.tsx b/libs/fleet/src/auth/AuthProvider.tsxnew file mode 100644index 0000000000..ea1cb35944--- /dev/null+++ b/libs/fleet/src/auth/AuthProvider.tsx@@ -0,0 +1,44 @@+// AuthProvider — wraps the app, gates rendering until Keycloak login+// resolves. With onLoad: "login-required" the user is redirected to+// Keycloak before the React tree mounts; this component only renders+// children once we have a valid session.++import { useEffect, useState } from "react"+import { initKc } from "./keycloak"++interface Props {+ children: React.ReactNode+}++export function AuthProvider({ children }: Props) {+ const [ready, setReady] = useState(false)+ const [error, setError] = useState<string | null>(null)++ useEffect(() => {+ initKc()+ .then(authed => {+ if (!authed) {+ setError("Not authenticated")+ return+ }+ setReady(true)+ })+ .catch(e => setError(String(e)))+ }, [])++ if (error) {+ return (+ <div style={{ padding: 24, fontFamily: "monospace" }}>+ Auth error: {error}+ </div>+ )+ }+ if (!ready) {+ return (+ <div style={{ padding: 24, fontFamily: "monospace" }}>+ Signing in…+ </div>+ )+ }+ return <>{children}</>+}diff --git a/libs/fleet/src/auth/keycloak.ts b/libs/fleet/src/auth/keycloak.tsnew file mode 100644index 0000000000..6c28ff41ce--- /dev/null+++ b/libs/fleet/src/auth/keycloak.ts@@ -0,0 +1,72 @@+// Keycloak singleton — initialised once by AuthProvider.+//+// Runtime config comes from window.__CYCLOPS_CS_CFG__, written into+// /config.js by nginx envsubst at container start (see nginx.conf).+// This avoids baking the auth URL into the Vite bundle so a single+// image works across staging/prod/dev.++import Keycloak from "keycloak-js"++declare global {+ interface Window {+ __CYCLOPS_CS_CFG__?: {+ kcUrl?: string+ kcRealm?: string+ kcClientId?: string+ }+ }+}++const cfg = (typeof window !== "undefined" && window.__CYCLOPS_CS_CFG__) || {}++export const kc = new Keycloak({+ url: cfg.kcUrl ?? "https://auth.cua.ai",+ realm: cfg.kcRealm ?? "cyclops-cs",+ clientId: cfg.kcClientId ?? "cyclops-cs-spa",+})++let initialised = false++export async function initKc(): Promise<boolean> {+ if (initialised) return kc.authenticated ?? false+ initialised = true+ const authed = await kc.init({+ onLoad: "login-required",+ pkceMethod: "S256",+ checkLoginIframe: false,+ })+ // Refresh proactively when the token is about to expire — keycloak-js+ // fires onTokenExpired *after* expiry, which would race the next API+ // call. updateToken(30) refreshes if <30s remain.+ kc.onTokenExpired = () => {+ kc.updateToken(30).catch(() => kc.login())+ }+ return authed+}++// getToken returns a fresh access token, refreshing it if it's within+// 30s of expiry. Used by the API client's fetchJson injector.+export async function getToken(): Promise<string | undefined> {+ if (!kc.authenticated) return undefined+ try {+ await kc.updateToken(30)+ } catch {+ kc.login()+ return undefined+ }+ return kc.token+}++export function logout() {+ kc.logout()+}++export function userInfo(): { sub?: string; email?: string; name?: string } {+ const t = kc.tokenParsed as Record<string, unknown> | undefined+ if (!t) return {}+ return {+ sub: t.sub as string | undefined,+ email: t.email as string | undefined,+ name: (t.preferred_username ?? t.name) as string | undefined,+ }+}diff --git a/libs/fleet/src/components/DesktopPane.tsx b/libs/fleet/src/components/DesktopPane.tsxnew file mode 100644index 0000000000..6d4cbbf5c2--- /dev/null+++ b/libs/fleet/src/components/DesktopPane.tsx@@ -0,0 +1,127 @@+/**+ * DesktopPane — live macOS sandbox desktop via noVNC.+ *+ * Renders the macOS sandbox's screen (RFB) in the browser. The sandbox exposes+ * its desktop as RFB-over-WebSocket (a noVNC RFB server bound to the+ * sandbox's routable IP, bridged by websockify — see docs/macos-novnc-plane.md).+ * That WebSocket is reached through the SAME cyclops-cs `/api/svc` proxy the rest+ * of the app uses; the proxy already supports the WebSocket upgrade (handlers.go+ * `statusCapture.Hijack` — "noVNC's /websockify"). So the connect URL is just:+ *+ * wss://<host>/api/svc/<namespace>/<sandbox>-<vncService>/websockify+ *+ * No new gateway route, no direct pod exposure — the sandbox's routable IP stays+ * private to the node; the browser only ever talks to run.cua.ai.+ */+import { useEffect, useRef, useState } from "react"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import SpaceBetween from "@cloudscape-design/components/space-between"+import StatusIndicator from "@cloudscape-design/components/status-indicator"+// noVNC RFB client (browser-side VNC over WebSocket).+import RFB from "@novnc/novnc"++type Props = {+ /** Pool namespace. */+ namespace: string+ /** Bound sandbox name (claim.status.sandbox). */+ sandboxName: string+ /** The VNC service name on the pool (default "vnc"); the K8s service is+ * `<sandboxName>-<vncService>` and the websockify path is under it. */+ vncService?: string+}++type Phase = "idle" | "connecting" | "connected" | "disconnected" | "error"++/** Build the wss:// URL to the sandbox's websockify endpoint via /api/svc. */+function websockifyUrl(namespace: string, sandboxName: string, vncService: string): string {+ const proto = window.location.protocol === "https:" ? "wss:" : "ws:"+ const svc = `${sandboxName}-${vncService}`+ return `${proto}//${window.location.host}/api/svc/${namespace}/${svc}/websockify`+}++export function DesktopPane({ namespace, sandboxName, vncService = "vnc" }: Props) {+ const screenRef = useRef<HTMLDivElement>(null)+ const rfbRef = useRef<RFB | null>(null)+ const [phase, setPhase] = useState<Phase>("idle")+ const [nonce, setNonce] = useState(0) // bump to force a reconnect++ useEffect(() => {+ if (!screenRef.current) return+ const url = websockifyUrl(namespace, sandboxName, vncService)+ setPhase("connecting")++ let rfb: RFB+ try {+ // RFB security type "None" on the sandbox side (loopback-bound server,+ // reached only via the authenticated proxy) — no VNC password here.+ rfb = new RFB(screenRef.current, url, {})+ } catch {+ setPhase("error")+ return+ }+ rfb.viewOnly = false+ rfb.scaleViewport = true+ rfb.resizeSession = false+ rfb.background = "#1b1b1b"++ const onConnect = () => setPhase("connected")+ const onDisconnect = () => setPhase("disconnected")+ const onSecurityFailure = () => setPhase("error")+ rfb.addEventListener("connect", onConnect)+ rfb.addEventListener("disconnect", onDisconnect)+ rfb.addEventListener("securityfailure", onSecurityFailure)+ rfbRef.current = rfb++ return () => {+ rfb.removeEventListener("connect", onConnect)+ rfb.removeEventListener("disconnect", onDisconnect)+ rfb.removeEventListener("securityfailure", onSecurityFailure)+ try { rfb.disconnect() } catch { /* already gone */ }+ rfbRef.current = null+ }+ }, [namespace, sandboxName, vncService, nonce])++ const status = {+ idle: <StatusIndicator type="pending">Idle</StatusIndicator>,+ connecting: <StatusIndicator type="loading">Connecting…</StatusIndicator>,+ connected: <StatusIndicator type="success">Connected</StatusIndicator>,+ disconnected: <StatusIndicator type="stopped">Disconnected</StatusIndicator>,+ error: <StatusIndicator type="error">Connection failed</StatusIndicator>,+ }[phase]++ return (+ <SpaceBetween size="s">+ <Box>+ {status}+ <Box float="right">+ <Button iconName="refresh" onClick={() => setNonce(n => n + 1)}>+ Reconnect+ </Button>+ </Box>+ </Box>+ <div+ ref={screenRef}+ style={{+ width: "100%",+ height: 640,+ background: "#1b1b1b",+ borderRadius: 4,+ overflow: "hidden",+ }}+ />+ {phase === "disconnected" && (+ <Box color="text-status-inactive">+ The sandbox closed the desktop stream (session ended or reset). Use+ Reconnect once it is Ready again.+ </Box>+ )}+ {phase === "error" && (+ <Box color="text-status-inactive">+ Could not reach the desktop. Confirm the pool exposes a{" "}+ <code>{vncService}</code> service and the sandbox is Ready.+ </Box>+ )}+ </SpaceBetween>+ )+}diff --git a/libs/fleet/src/components/FeatureFlagContext.tsx b/libs/fleet/src/components/FeatureFlagContext.tsxnew file mode 100644index 0000000000..322fcc5d33--- /dev/null+++ b/libs/fleet/src/components/FeatureFlagContext.tsx@@ -0,0 +1,35 @@+import { createContext, useContext, useEffect, useState, type ReactNode } from "react"+import { fetchFeatureFlags, type FeatureFlags } from "../api/featureFlags"++const DEFAULT_FLAGS: FeatureFlags = { admin: false }++const FeatureFlagContext = createContext<FeatureFlags>(DEFAULT_FLAGS)++/**+ * Fetches /api/config once at app startup and provides the result via+ * context. All children can call useFeatureFlags() to read flags.+ */+export function FeatureFlagProvider({ children }: { children: ReactNode }) {+ const [flags, setFlags] = useState<FeatureFlags>(DEFAULT_FLAGS)++ useEffect(() => {+ fetchFeatureFlags().then(setFlags).catch(() => setFlags(DEFAULT_FLAGS))+ }, [])++ return (+ <FeatureFlagContext.Provider value={flags}>+ {children}+ </FeatureFlagContext.Provider>+ )+}++/**+ * Returns the current user's feature flags.+ *+ * @example+ * const { admin } = useFeatureFlags()+ * if (admin) { ... }+ */+export function useFeatureFlags(): FeatureFlags {+ return useContext(FeatureFlagContext)+}diff --git a/libs/fleet/src/components/FlashContext.tsx b/libs/fleet/src/components/FlashContext.tsxnew file mode 100644index 0000000000..6f93f29e9d--- /dev/null+++ b/libs/fleet/src/components/FlashContext.tsx@@ -0,0 +1,13 @@+import { createContext, useContext } from "react"+import { FlashbarProps } from "@cloudscape-design/components/flashbar"++export type FlashMsg = Omit<+ FlashbarProps.MessageDefinition,+ "id" | "onDismiss" | "dismissible"+>++export const FlashContext = createContext<{+ push: (msg: FlashMsg) => void+}>({ push: () => {} })++export const useFlash = () => useContext(FlashContext)diff --git a/libs/fleet/src/components/LogsPanel.tsx b/libs/fleet/src/components/LogsPanel.tsxnew file mode 100644index 0000000000..b103497a1d--- /dev/null+++ b/libs/fleet/src/components/LogsPanel.tsx@@ -0,0 +1,164 @@+import { useEffect, useRef, useState } from "react"+import AnsiToHtml from "ansi-to-html"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import Container from "@cloudscape-design/components/container"+import Header from "@cloudscape-design/components/header"+import SpaceBetween from "@cloudscape-design/components/space-between"+import StatusIndicator from "@cloudscape-design/components/status-indicator"+import { api } from "../api/cyclops"++const MAX_LOG_LINES = 2000++// SGR-only ANSI → HTML converter shared by every line append. ansi-to-html+// HTML-escapes its input first (escapeXML: true), so `<script>` in a log+// line lands as `<script>`.+const ANSI = new AnsiToHtml({+ fg: "#d1d5db",+ bg: "#0f1419",+ newline: false,+ escapeXML: true,+})++export function LogsPanel({+ namespace,+ podName,+ container,+ title,+ waitingText,+}: {+ namespace?: string+ podName?: string+ container: string+ title: string+ waitingText?: string+}) {+ const [lines, setLines] = useState<string[]>([])+ const [paused, setPaused] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const preRef = useRef<HTMLPreElement>(null)+ const stickToBottomRef = useRef(true)++ useEffect(() => {+ setLines([])+ }, [namespace, podName, container])++ useEffect(() => {+ if (!namespace || !podName || paused) return+ setError(null)+ const url = api.podLogsUrl(namespace, podName, container)+ const ctrl = new AbortController()+ ;(async () => {+ try {+ const { getToken } = await import("../auth/keycloak")+ const token = await getToken()+ const headers: Record<string, string> = {}+ if (token) headers.Authorization = `Bearer ${token}`+ const res = await fetch(url, { signal: ctrl.signal, headers })+ if (!res.ok || !res.body) {+ setError(`Log stream failed: ${res.status}`)+ return+ }+ const reader = res.body.getReader()+ const decoder = new TextDecoder()+ let buffer = ""+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ buffer += decoder.decode(value, { stream: true })+ const parts = buffer.split("\n")+ buffer = parts.pop() ?? ""+ if (parts.length > 0) {+ const htmlLines = parts.map(l => ANSI.toHtml(l))+ setLines(prev => {+ const next = [...prev, ...htmlLines]+ return next.length > MAX_LOG_LINES+ ? next.slice(next.length - MAX_LOG_LINES)+ : next+ })+ }+ }+ } catch {+ if (!ctrl.signal.aborted) {+ setError("Log stream interrupted. Click Resume to retry.")+ }+ }+ })()+ return () => ctrl.abort()+ }, [namespace, podName, container, paused])++ useEffect(() => {+ const el = preRef.current+ if (!el || !stickToBottomRef.current) return+ el.scrollTop = el.scrollHeight+ }, [lines])++ const onScroll = () => {+ const el = preRef.current+ if (!el) return+ const distanceFromBottom = el.scrollHeight - (el.scrollTop + el.clientHeight)+ stickToBottomRef.current = distanceFromBottom < 40+ }++ return (+ <Container+ header={+ <Header+ variant="h2"+ counter={`(${lines.length})`}+ actions={+ <SpaceBetween direction="horizontal" size="xs">+ <Button+ onClick={() => setPaused(p => !p)}+ iconName={paused ? "caret-right-filled" : "close"}+ >+ {paused ? "Resume" : "Pause"}+ </Button>+ <Button onClick={() => setLines([])}>Clear</Button>+ </SpaceBetween>+ }+ >+ {title}+ </Header>+ }+ >+ {error && (+ <Box color="text-status-warning" margin={{ bottom: "xs" }}>+ <StatusIndicator type="warning">{error}</StatusIndicator>+ </Box>+ )}+ {lines.length === 0 ? (+ <Box color="text-body-secondary" textAlign="center" padding="m">+ {!namespace || !podName+ ? (waitingText ?? "Waiting for pod…")+ : paused+ ? "Paused."+ : "Connecting…"}+ </Box>+ ) : (+ <pre+ ref={preRef}+ onScroll={onScroll}+ // ansi-to-html HTML-escapes input first (escapeXML: true), so+ // dangerouslySetInnerHTML here is safe — log payload can't+ // inject markup.+ dangerouslySetInnerHTML={{ __html: lines.join("\n") }}+ style={{+ maxHeight: 480,+ overflow: "auto",+ margin: 0,+ padding: "0.75rem",+ backgroundColor: "#0f1419",+ color: "#d1d5db",+ fontSize: 12,+ fontFamily:+ "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",+ borderRadius: 4,+ whiteSpace: "pre-wrap",+ wordBreak: "break-all",+ }}+ />+ )}+ </Container>+ )+}diff --git a/libs/fleet/src/components/PoolLifecycleEvents.tsx b/libs/fleet/src/components/PoolLifecycleEvents.tsxnew file mode 100644index 0000000000..f4df1832d6--- /dev/null+++ b/libs/fleet/src/components/PoolLifecycleEvents.tsx@@ -0,0 +1,264 @@+import { useEffect, useState } from "react"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import Container from "@cloudscape-design/components/container"+import Header from "@cloudscape-design/components/header"+import StatusIndicator from "@cloudscape-design/components/status-indicator"+import Table, { type TableProps } from "@cloudscape-design/components/table"+import { api, type KubernetesEvent } from "../api/cyclops"++// ── Shared helpers ─────────────────────────────────────────────────────────++export function eventTime(e: KubernetesEvent): string {+ return e.lastTimestamp ?? e.eventTime ?? e.firstTimestamp ?? e.metadata.creationTimestamp ?? ""+}++function fmtAge(ts: string): string {+ if (!ts) return "—"+ const ms = Date.now() - new Date(ts).getTime()+ if (Number.isNaN(ms)) return "—"+ const s = Math.max(0, Math.round(ms / 1000))+ if (s < 60) return `${s}s`+ const m = Math.round(s / 60)+ if (m < 60) return `${m}m`+ const h = Math.round(m / 60)+ if (h < 48) return `${h}h`+ return `${Math.round(h / 24)}d`+}++function AgeCell({ e }: { e: KubernetesEvent }) {+ return (+ <Box variant="small" color="text-body-secondary">+ {fmtAge(eventTime(e))}+ </Box>+ )+}++function TypeCell({ e }: { e: KubernetesEvent }) {+ return e.type === "Warning" ? (+ <StatusIndicator type="warning">Warning</StatusIndicator>+ ) : (+ <StatusIndicator type="success">Normal</StatusIndicator>+ )+}++// ── Strategy interface ─────────────────────────────────────────────────────++/**+ * EventViewStrategy determines what events are visible and how they render.+ * Each concrete strategy encapsulates one audience's view of lifecycle events.+ * Adding a new audience (e.g. "support tier") is a new class, not a new branch.+ */+interface EventViewStrategy {+ /** Filter the full sorted event list to what this audience should see. */+ filter(events: KubernetesEvent[]): KubernetesEvent[]+ /** Column definitions for the Cloudscape Table. */+ columns(): TableProps.ColumnDefinition<KubernetesEvent>[]+}++// ── Customer strategy ──────────────────────────────────────────────────────++// Mapping of K8s event reason → marketing-friendly display label.+// Used purely for display translation — filtering is now done server-side+// by OPA's visible_events rule before events reach the SPA.+const CUSTOMER_REASON_LABELS: Record<string, string> = {+ PoolCreated: "Pool created",+ PoolUpdated: "Pool updated",+ PoolDeleted: "Pool deleted",+ PoolScaled: "Replicas changed",+ PoolReady: "Pool ready",+ PoolDegraded: "Pool degraded",+ PoolFailed: "Pool failed",+ VmStarted: "VM started",+ VmStopped: "VM stopped",+ VmFailed: "VM failed",+ VmProvisioning: "Provisioning VM",+ OrchestratorReady: "Orchestrator ready",+ OrchestratorDown: "Orchestrator restarted",+}++// Optional user-facing subtitles for actionable/notable events.+const CUSTOMER_REASON_DESC: Record<string, string> = {+ PoolDegraded: "The pool has fewer ready replicas than requested.",+ PoolFailed: "The pool encountered an error. Check your configuration.",+ VmFailed: "A VM replica failed. It will be replaced automatically.",+ OrchestratorDown: "The orchestrator pod was replaced.",+}++class CustomerEventView implements EventViewStrategy {+ /** No client-side filtering — server already applied visible_events via OPA. */+ filter(events: KubernetesEvent[]): KubernetesEvent[] {+ return events+ }++ columns(): TableProps.ColumnDefinition<KubernetesEvent>[] {+ return [+ {+ id: "age",+ header: "Age",+ cell: e => <AgeCell e={e} />,+ width: 80,+ },+ {+ id: "type",+ header: "Status",+ cell: e => <TypeCell e={e} />,+ width: 120,+ },+ {+ id: "event",+ header: "Event",+ isRowHeader: true,+ cell: e => {+ const label = e.reason ? (CUSTOMER_REASON_LABELS[e.reason] ?? e.reason) : "—"+ const desc = e.reason ? CUSTOMER_REASON_DESC[e.reason] : undefined+ return (+ <Box>+ <Box variant="span">{label}</Box>+ {desc && (+ <Box variant="small" color="text-body-secondary">+ {desc}+ </Box>+ )}+ </Box>+ )+ },+ },+ ]+ }+}++// ── Admin strategy ─────────────────────────────────────────────────────────++class AdminEventView implements EventViewStrategy {+ /** Admins see every event for this pool — no filtering. */+ filter(events: KubernetesEvent[]): KubernetesEvent[] {+ return events+ }++ columns(): TableProps.ColumnDefinition<KubernetesEvent>[] {+ return [+ {+ id: "age",+ header: "Age",+ cell: e => <AgeCell e={e} />,+ width: 80,+ },+ {+ id: "type",+ header: "Type",+ cell: e => <TypeCell e={e} />,+ width: 120,+ },+ {+ id: "reason",+ header: "Reason",+ isRowHeader: true,+ cell: e => <code>{e.reason ?? "—"}</code>,+ width: 200,+ },+ {+ id: "message",+ header: "Message",+ cell: e => <Box variant="small">{e.message ?? "—"}</Box>,+ },+ {+ id: "count",+ header: "Count",+ cell: e => e.count ?? 1,+ width: 70,+ },+ ]+ }+}++// ── Strategy factory ───────────────────────────────────────────────────────++/** Returns the correct strategy for the given audience. */+function eventViewStrategyFor(admin: boolean): EventViewStrategy {+ return admin ? new AdminEventView() : new CustomerEventView()+}++// ── Component ──────────────────────────────────────────────────────────────++const REFRESH_MS = 15_000++interface PoolLifecycleEventsProps {+ /** Pool name (without the pool- prefix). Used to filter events to this pool. */+ poolName: string+ /** Whether the current user has admin access. Selects the AdminEventView strategy. */+ admin?: boolean+}++/**+ * Shows Kubernetes operator events for a specific pool.+ * The rendering strategy (columns, event filter, labels) is selected+ * by `admin` via `eventViewStrategyFor` — no if-statements in render.+ */+export function PoolLifecycleEvents({ poolName, admin = false }: PoolLifecycleEventsProps) {+ const [events, setEvents] = useState<KubernetesEvent[]>([])+ const [loading, setLoading] = useState(true)+ const [error, setError] = useState<string | null>(null)++ const strategy = eventViewStrategyFor(admin)++ const load = async () => {+ setLoading(true)+ try {+ const list = await api.listOperatorEvents()+ const poolEvents = list.items+ .filter(e => e.involvedObject.name === poolName)+ .sort((a, b) => eventTime(b).localeCompare(eventTime(a)))+ setEvents(poolEvents)+ setError(null)+ } catch (e) {+ setError(String((e as Error).message))+ } finally {+ setLoading(false)+ }+ }++ useEffect(() => {+ load()+ const id = window.setInterval(load, REFRESH_MS)+ return () => window.clearInterval(id)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [poolName])++ const visibleEvents = strategy.filter(events)++ return (+ <Container+ header={+ <Header+ variant="h2"+ counter={loading ? undefined : `(${visibleEvents.length})`}+ description="Recent lifecycle events for this pool."+ actions={<Button iconName="refresh" onClick={load} disabled={loading} />}+ >+ Lifecycle events+ </Header>+ }+ >+ <Table+ variant="embedded"+ items={visibleEvents}+ loading={loading}+ loadingText="Loading events"+ trackBy={e => e.metadata.uid ?? e.metadata.name + eventTime(e)}+ columnDefinitions={strategy.columns()}+ empty={+ error ? (+ <Box color="text-status-warning" textAlign="center" padding="m">+ Could not load events.+ </Box>+ ) : (+ <Box textAlign="center" color="text-body-secondary" padding="m">+ No lifecycle events yet.+ </Box>+ )+ }+ />+ </Container>+ )+}diff --git a/libs/fleet/src/components/PoolStatus.tsx b/libs/fleet/src/components/PoolStatus.tsxnew file mode 100644index 0000000000..e408bc2523--- /dev/null+++ b/libs/fleet/src/components/PoolStatus.tsx@@ -0,0 +1,19 @@+import StatusIndicator, {+ StatusIndicatorProps,+} from "@cloudscape-design/components/status-indicator"+import { PoolStatus } from "../api/pools"++const POOL_STATUS_TYPE: Record<PoolStatus["kind"], StatusIndicatorProps.Type> = {+ healthy: "success",+ provisioning: "in-progress",+ terminating: "in-progress",+ unknown: "pending",+}++export function PoolStatusPill({ status }: { status: PoolStatus }) {+ return (+ <StatusIndicator type={POOL_STATUS_TYPE[status.kind]}>+ {status.label}+ </StatusIndicator>+ )+}diff --git a/libs/fleet/src/main.tsx b/libs/fleet/src/main.tsxnew file mode 100644index 0000000000..434ab27c98--- /dev/null+++ b/libs/fleet/src/main.tsx@@ -0,0 +1,16 @@+import React from "react"+import ReactDOM from "react-dom/client"+import "@cloudscape-design/global-styles/index.css"+import { applyMode, Mode } from "@cloudscape-design/global-styles"+import { App } from "./App"+import { AuthProvider } from "./auth/AuthProvider"++applyMode(Mode.Dark)++ReactDOM.createRoot(document.getElementById("root")!).render(+ <React.StrictMode>+ <AuthProvider>+ <App />+ </AuthProvider>+ </React.StrictMode>,+)diff --git a/libs/fleet/src/pages/ApiKeys.tsx b/libs/fleet/src/pages/ApiKeys.tsxnew file mode 100644index 0000000000..f58e837f4a--- /dev/null+++ b/libs/fleet/src/pages/ApiKeys.tsx@@ -0,0 +1,195 @@+// API keys management.+//+// Lists the calling user's keys, lets them mint new ones (showing the+// generated client_secret exactly once), and revoke existing keys. Each+// key is a Keycloak service-account client with a `namespace` claim+// mapper, which gates which orchestrator the resulting JWT can reach via+// /api/gateway/:name.++import { useEffect, useState } from "react"+import Alert from "@cloudscape-design/components/alert"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import Container from "@cloudscape-design/components/container"+import CopyToClipboard from "@cloudscape-design/components/copy-to-clipboard"+import Form from "@cloudscape-design/components/form"+import FormField from "@cloudscape-design/components/form-field"+import Header from "@cloudscape-design/components/header"+import Input from "@cloudscape-design/components/input"+import Modal from "@cloudscape-design/components/modal"+import Select, { type SelectProps } from "@cloudscape-design/components/select"+import SpaceBetween from "@cloudscape-design/components/space-between"+import Table from "@cloudscape-design/components/table"+import { ApiKey, NewApiKey, keysApi } from "../api/keys"+import { api } from "../api/cyclops"++export function ApiKeys() {+ const [keys, setKeys] = useState<ApiKey[]>([])+ const [loading, setLoading] = useState(true)+ const [error, setError] = useState<string | null>(null)+ const [name, setName] = useState("")+ const [selectedNs, setSelectedNs] = useState<SelectProps.Option | null>(null)+ const [nsOptions, setNsOptions] = useState<SelectProps.Option[]>([])+ const [creating, setCreating] = useState(false)+ const [created, setCreated] = useState<NewApiKey | null>(null)++ const refresh = async () => {+ setLoading(true)+ try {+ const [r, pools] = await Promise.all([+ keysApi.list(),+ api.listPools(),+ ])+ setKeys(r.keys)+ const poolOpts = pools.map(p => ({+ label: `${p.name} (pool-${p.name})`,+ value: `pool-${p.name}`,+ }))+ setNsOptions(poolOpts)+ setError(null)+ } catch (e) {+ setError(String(e))+ } finally {+ setLoading(false)+ }+ }++ useEffect(() => {+ refresh()+ }, [])++ const create = async () => {+ setCreating(true)+ try {+ const k = await keysApi.create(name, selectedNs!.value!)+ setCreated(k)+ setName("")+ setSelectedNs(null)+ await refresh()+ } catch (e) {+ setError(String(e))+ } finally {+ setCreating(false)+ }+ }++ const remove = async (id: string) => {+ try {+ await keysApi.remove(id)+ await refresh()+ } catch (e) {+ setError(String(e))+ }+ }++ return (+ <SpaceBetween size="l">+ {error && (+ <Alert type="error" dismissible onDismiss={() => setError(null)}>+ {error}+ </Alert>+ )}++ <Container header={<Header variant="h2">Issue a new API key</Header>}>+ <Form+ actions={+ <Button+ variant="primary"+ loading={creating}+ disabled={!name || !selectedNs}+ onClick={create}+ >+ Create key+ </Button>+ }+ >+ <SpaceBetween size="m">+ <FormField label="Name" description="Free-text label for this key">+ <Input value={name} onChange={e => setName(e.detail.value)} />+ </FormField>+ <FormField+ label="Namespace"+ description="Pool namespace this key may proxy to"+ >+ <Select+ selectedOption={selectedNs}+ onChange={e => setSelectedNs(e.detail.selectedOption)}+ options={nsOptions}+ placeholder="Select a pool"+ loadingText="Loading pools..."+ statusType={loading ? "loading" : "finished"}+ empty="No pools found"+ />+ </FormField>+ </SpaceBetween>+ </Form>+ </Container>++ <Table+ loading={loading}+ items={keys}+ columnDefinitions={[+ { id: "client_id", header: "Client ID", cell: r => r.client_id },+ { id: "name", header: "Name", cell: r => r.name },+ { id: "namespace", header: "Namespace", cell: r => r.namespace },+ {+ id: "actions",+ header: "",+ cell: r => (+ <Button onClick={() => remove(r.id)}>Revoke</Button>+ ),+ },+ ]}+ empty={<Box textAlign="center">No keys yet.</Box>}+ header={<Header variant="h2">Existing keys</Header>}+ />++ {created && (+ <Modal+ visible+ header="API key created"+ onDismiss={() => setCreated(null)}+ footer={+ <Box float="right">+ <Button variant="primary" onClick={() => setCreated(null)}>+ I have copied the secret+ </Button>+ </Box>+ }+ >+ <SpaceBetween size="m">+ <Alert type="warning">+ The client secret is shown <b>once</b>. Copy it now — it+ can’t be retrieved later. To rotate, revoke this key and+ create a new one.+ </Alert>+ <Container>+ <SpaceBetween size="m">+ <FormField label="Client ID">+ <CopyToClipboard+ variant="inline"+ textToCopy={created.client_id}+ textToDisplay={<code>{created.client_id}</code>}+ copyButtonAriaLabel="Copy Client ID"+ copySuccessText="Client ID copied"+ copyErrorText="Failed to copy"+ />+ </FormField>+ <FormField label="Client secret">+ <CopyToClipboard+ variant="inline"+ textToCopy={created.client_secret}+ textToDisplay={<code>{created.client_secret}</code>}+ copyButtonAriaLabel="Copy Client secret"+ copySuccessText="Client secret copied"+ copyErrorText="Failed to copy"+ />+ </FormField>+ </SpaceBetween>+ </Container>+ </SpaceBetween>+ </Modal>+ )}+ </SpaceBetween>+ )+}diff --git a/libs/fleet/src/pages/ClaimDetail.tsx b/libs/fleet/src/pages/ClaimDetail.tsxnew file mode 100644index 0000000000..2ce243007f--- /dev/null+++ b/libs/fleet/src/pages/ClaimDetail.tsx@@ -0,0 +1,241 @@+import { useEffect, useState } from "react"+import { useNavigate, useParams } from "react-router-dom"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import ColumnLayout from "@cloudscape-design/components/column-layout"+import Container from "@cloudscape-design/components/container"+import Header from "@cloudscape-design/components/header"+import Link from "@cloudscape-design/components/link"+import Modal from "@cloudscape-design/components/modal"+import SpaceBetween from "@cloudscape-design/components/space-between"+import Spinner from "@cloudscape-design/components/spinner"+import StatusIndicator from "@cloudscape-design/components/status-indicator"+import { api, claimsApi, type Claim } from "../api/cyclops"+import { useFlash } from "../components/FlashContext"+import { DesktopPane } from "../components/DesktopPane"++function phaseType(phase: string): "success" | "pending" | "error" | "info" {+ switch (phase) {+ case "Bound":+ return "success"+ case "Pending":+ return "pending"+ case "Failed":+ return "error"+ default:+ return "info"+ }+}++export function ClaimDetail() {+ const { namespace = "", poolName = "", claimName = "" } = useParams()+ const navigate = useNavigate()+ const flash = useFlash()++ const [claim, setClaim] = useState<Claim | null>(null)+ const [services, setServices] = useState<{ name: string; targetPort: number; protocol: string }[]>([])+ const [loading, setLoading] = useState(true)+ const [confirmRelease, setConfirmRelease] = useState(false)+ const [releasing, setReleasing] = useState(false)++ const load = async () => {+ setLoading(true)+ try {+ const [claimData, poolData] = await Promise.all([+ claimsApi.get(namespace, claimName),+ api.getPool(namespace, poolName),+ ])+ setClaim(claimData)+ setServices(poolData.services)+ } catch (e) {+ flash.push({+ type: "error",+ header: "Failed to load claim",+ content: String((e as Error).message),+ })+ } finally {+ setLoading(false)+ }+ }++ useEffect(() => {+ if (namespace && poolName && claimName) load()+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [namespace, poolName, claimName])++ // Auto-refresh while Pending — only refetch the claim (pool data+ // doesn't change during binding). Errors are silent to avoid+ // spamming flash notifications every 3s.+ useEffect(() => {+ if (!claim || claim.phase !== "Pending") return+ const id = setInterval(async () => {+ try {+ const c = await claimsApi.get(namespace, claimName)+ setClaim(c)+ } catch {+ // Silent — next tick will retry+ }+ }, 3000)+ return () => clearInterval(id)+ }, [claim?.phase, namespace, claimName])++ const release = async () => {+ setReleasing(true)+ try {+ await claimsApi.remove(namespace, claimName)+ flash.push({ type: "success", header: `Released claim ${claimName}` })+ navigate(`/pools/${namespace}/${poolName}`)+ } catch (e) {+ flash.push({+ type: "error",+ header: "Failed to release claim",+ content: String((e as Error).message),+ })+ setReleasing(false)+ }+ }++ if (loading && !claim) {+ return (+ <Container header={<Header variant="h1">{claimName}</Header>}>+ <Box textAlign="center" padding="l">+ <Spinner /> Loading claim…+ </Box>+ </Container>+ )+ }+ if (!claim) return null++ const sandboxName = claim.sandboxName+ const isBound = claim.phase === "Bound" && sandboxName++ return (+ <SpaceBetween size="l">+ <Container+ header={+ <Header+ variant="h1"+ actions={+ <SpaceBetween direction="horizontal" size="xs">+ <Button iconName="refresh" onClick={load} />+ <Button onClick={() => navigate(`/pools/${namespace}/${poolName}`)}>+ Back to pool+ </Button>+ <Button onClick={() => setConfirmRelease(true)}>+ Release+ </Button>+ </SpaceBetween>+ }+ >+ {claimName}+ </Header>+ }+ >+ <ColumnLayout columns={2} variant="text-grid">+ <div>+ <Box variant="awsui-key-label">Status</Box>+ <StatusIndicator type={phaseType(claim.phase)}>+ {claim.phase}+ </StatusIndicator>+ </div>+ <div>+ <Box variant="awsui-key-label">Pool</Box>+ <Link+ href={`#/pools/${namespace}/${poolName}`}+ onFollow={e => {+ e.preventDefault()+ navigate(`/pools/${namespace}/${poolName}`)+ }}+ >+ {poolName}+ </Link>+ </div>+ <div>+ <Box variant="awsui-key-label">Sandbox</Box>+ <div>{sandboxName ?? "-"}</div>+ </div>+ <div>+ <Box variant="awsui-key-label">Template</Box>+ <div><code>{claim.templateRef}</code></div>+ </div>+ </ColumnLayout>+ </Container>++ {isBound && sandboxName && services.some(s => s.name === "vnc") && (+ <Container+ header={+ <Header variant="h2" description="Live macOS desktop streamed from the macOS sandbox via noVNC.">+ Desktop+ </Header>+ }+ >+ <DesktopPane namespace={namespace} sandboxName={sandboxName} vncService="vnc" />+ </Container>+ )}++ {isBound && services.length > 0 && (+ <Container header={<Header variant="h2">Services</Header>}>+ <SpaceBetween size="s">+ {services.map(svc => {+ const svcK8sName = `${sandboxName}-${svc.name}`+ const svcUrl = `/api/svc/${namespace}/${svcK8sName}/`+ return (+ <ColumnLayout key={svc.name} columns={3}>+ <div>+ <Box variant="awsui-key-label">{svc.name}</Box>+ <div>port 80 → {svc.targetPort} ({svc.protocol})</div>+ </div>+ <div>+ <Box variant="awsui-key-label">K8s Service</Box>+ <div><code>{svcK8sName}</code></div>+ </div>+ <div>+ <Box variant="awsui-key-label">URL</Box>+ <Link href={svcUrl} external>{svcUrl}</Link>+ </div>+ </ColumnLayout>+ )+ })}+ </SpaceBetween>+ </Container>+ )}++ {isBound && services.length === 0 && (+ <Container header={<Header variant="h2">Services</Header>}>+ <Box color="text-status-inactive">+ No services defined on this pool. Add services in the pool configuration to expose extra ports.+ </Box>+ </Container>+ )}++ {!isBound && (+ <Container header={<Header variant="h2">Services</Header>}>+ <Box color="text-status-inactive">+ Claim is not yet bound to a sandbox. Services will appear once a sandbox is assigned.+ </Box>+ </Container>+ )}++ <Modal+ visible={confirmRelease}+ onDismiss={() => { if (!releasing) setConfirmRelease(false) }}+ header={`Release claim ${claimName}?`}+ footer={+ <Box float="right">+ <SpaceBetween direction="horizontal" size="xs">+ <Button onClick={() => setConfirmRelease(false)} disabled={releasing}>+ Cancel+ </Button>+ <Button variant="primary" onClick={release} loading={releasing}>+ Release+ </Button>+ </SpaceBetween>+ </Box>+ }+ >+ This will delete the claim and return its sandbox VM back to the warm pool.+ The VM will be restarted with a clean state.+ </Modal>+ </SpaceBetween>+ )+}diff --git a/libs/fleet/src/pages/NodesList.tsx b/libs/fleet/src/pages/NodesList.tsxnew file mode 100644index 0000000000..1746f9ffdb--- /dev/null+++ b/libs/fleet/src/pages/NodesList.tsx@@ -0,0 +1,149 @@+import { useEffect, useState } from "react"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import Header from "@cloudscape-design/components/header"+import Table from "@cloudscape-design/components/table"+import {+ api,+ isPoolWorkerNode,+ NodeSummary,+ parseCpuCores,+ parseMemoryBytes,+ POOL_WORKER_NODE_PREFIX,+} from "../api/cyclops"+import { useFlash } from "../components/FlashContext"++function readyCondition(n: NodeSummary): string {+ const c = (n.status?.conditions ?? []).find(c => c.type === "Ready")+ if (!c) return "Unknown"+ return c.status === "True" ? "Ready" : "NotReady"+}++function fmtMemGi(s?: string): string {+ if (!s) return "—"+ const b = parseMemoryBytes(s)+ return `${(b / 1024 ** 3).toFixed(1)}Gi`+}++interface NodeRow {+ node: NodeSummary+ totalVms: number+}++export function NodesList() {+ const flash = useFlash()+ const [rows, setRows] = useState<NodeRow[]>([])+ const [loading, setLoading] = useState(true)++ const load = async () => {+ setLoading(true)+ try {+ const [nodes, pods, pools] = await Promise.all([+ api.listNodes(),+ api.listVmPods(),+ api.listPools().catch(() => []),+ ])++ const knownPoolNs = new Set(+ pools.map(p => `pool-${p.name}`),+ )++ const byNode = new Map<string, number>()+ for (const p of pods.items) {+ const node = p.spec?.nodeName+ if (!node) continue+ const ns = p.metadata.namespace+ if (!knownPoolNs.has(ns)) continue+ byNode.set(node, (byNode.get(node) ?? 0) + 1)+ }++ setRows(+ nodes.items.filter(isPoolWorkerNode).map(n => ({+ node: n,+ totalVms: byNode.get(n.metadata.name) ?? 0,+ })),+ )+ } catch (e) {+ flash.push({+ type: "error",+ header: "Failed to list nodes",+ content: String((e as Error).message),+ })+ } finally {+ setLoading(false)+ }+ }+ useEffect(() => {+ load()+ }, [])++ const totalVms = rows.reduce((s, r) => s + r.totalVms, 0)++ return (+ <Table+ header={+ <Header+ variant="h1"+ counter={loading ? undefined : `(${rows.length})`}+ description={+ loading+ ? undefined+ : `${totalVms} pool VM${totalVms === 1 ? "" : "s"} scheduled across ${rows.length} node${rows.length === 1 ? "" : "s"}.`+ }+ actions={+ <Button iconName="refresh" onClick={load} disabled={loading} />+ }+ >+ Nodes+ </Header>+ }+ items={rows}+ loading={loading}+ loadingText="Loading nodes"+ trackBy={r => r.node.metadata.name}+ empty={+ <Box textAlign="center" padding="m" color="text-body-secondary">+ No nodes+ </Box>+ }+ columnDefinitions={[+ {+ id: "name",+ header: "Name",+ cell: r => (+ <code title={r.node.metadata.name}>+ {r.node.metadata.name.startsWith(POOL_WORKER_NODE_PREFIX)+ ? r.node.metadata.name.slice(POOL_WORKER_NODE_PREFIX.length)+ : r.node.metadata.name}+ </code>+ ),+ sortingField: "node.metadata.name",+ isRowHeader: true,+ },+ {+ id: "status",+ header: "Status",+ cell: r => readyCondition(r.node),+ },+ {+ id: "cpu",+ header: "CPU (alloc.)",+ cell: r => {+ const c = r.node.status?.allocatable?.cpu+ return c ? parseCpuCores(c).toFixed(1) : "—"+ },+ },+ {+ id: "mem",+ header: "Memory (alloc.)",+ cell: r => fmtMemGi(r.node.status?.allocatable?.memory),+ },+ {+ id: "vms",+ header: "Pool VMs",+ cell: r => r.totalVms,+ },+ ]}+ />+ )+}diff --git a/libs/fleet/src/pages/OperatorEvents.tsx b/libs/fleet/src/pages/OperatorEvents.tsxnew file mode 100644index 0000000000..d391116aa0--- /dev/null+++ b/libs/fleet/src/pages/OperatorEvents.tsx@@ -0,0 +1,136 @@+import { useEffect, useState } from "react"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import Header from "@cloudscape-design/components/header"+import StatusIndicator from "@cloudscape-design/components/status-indicator"+import Table from "@cloudscape-design/components/table"+import { api, type KubernetesEvent } from "../api/cyclops"+import { useFlash } from "../components/FlashContext"++const REFRESH_MS = 15_000++function eventTime(e: KubernetesEvent): string {+ return (+ e.lastTimestamp ??+ e.eventTime ??+ e.firstTimestamp ??+ e.metadata.creationTimestamp ??+ ""+ )+}++function fmtAge(ts: string): string {+ if (!ts) return "—"+ const ms = Date.now() - new Date(ts).getTime()+ if (Number.isNaN(ms)) return "—"+ const s = Math.max(0, Math.round(ms / 1000))+ if (s < 60) return `${s}s`+ const m = Math.round(s / 60)+ if (m < 60) return `${m}m`+ const h = Math.round(m / 60)+ if (h < 48) return `${h}h`+ return `${Math.round(h / 24)}d`+}++export function OperatorEvents() {+ const flash = useFlash()+ const [events, setEvents] = useState<KubernetesEvent[]>([])+ const [loading, setLoading] = useState(true)++ const load = async () => {+ setLoading(true)+ try {+ const list = await api.listOperatorEvents()+ const sorted = [...list.items].sort((a, b) =>+ eventTime(b).localeCompare(eventTime(a)),+ )+ setEvents(sorted)+ } catch (e) {+ flash.push({+ type: "error",+ header: "Failed to list events",+ content: String((e as Error).message),+ })+ } finally {+ setLoading(false)+ }+ }++ useEffect(() => {+ load()+ const id = window.setInterval(load, REFRESH_MS)+ return () => window.clearInterval(id)+ }, [])++ return (+ <Table+ header={+ <Header+ variant="h1"+ counter={loading ? undefined : `(${events.length})`}+ description="Kubernetes events emitted by the pool-operator on OSGymWorkspacePool resources."+ actions={+ <Button iconName="refresh" onClick={load} disabled={loading} />+ }+ >+ Operator events+ </Header>+ }+ items={events}+ loading={loading}+ loadingText="Loading events"+ trackBy={e => e.metadata.uid ?? e.metadata.name}+ empty={+ <Box textAlign="center" padding="m" color="text-body-secondary">+ No events+ </Box>+ }+ columnDefinitions={[+ {+ id: "age",+ header: "Age",+ cell: e => fmtAge(eventTime(e)),+ width: 90,+ },+ {+ id: "type",+ header: "Type",+ cell: e =>+ e.type === "Warning" ? (+ <StatusIndicator type="warning">Warning</StatusIndicator>+ ) : (+ <StatusIndicator type="success">Normal</StatusIndicator>+ ),+ width: 130,+ },+ {+ id: "reason",+ header: "Reason",+ cell: e => <code>{e.reason ?? "—"}</code>,+ width: 220,+ },+ {+ id: "object",+ header: "Object",+ cell: e => (+ <code title={`${e.involvedObject.kind}/${e.involvedObject.name}`}>+ {e.involvedObject.name}+ </code>+ ),+ width: 200,+ },+ {+ id: "message",+ header: "Message",+ cell: e => e.message ?? "",+ },+ {+ id: "count",+ header: "Count",+ cell: e => e.count ?? 1,+ width: 80,+ },+ ]}+ />+ )+}diff --git a/libs/fleet/src/pages/PoolDetail.tsx b/libs/fleet/src/pages/PoolDetail.tsxnew file mode 100644index 0000000000..cef154e297--- /dev/null+++ b/libs/fleet/src/pages/PoolDetail.tsx@@ -0,0 +1,731 @@+import { useCallback, useEffect, useRef, useState } from "react"+import { useNavigate, useParams } from "react-router-dom"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import ColumnLayout from "@cloudscape-design/components/column-layout"+import Container from "@cloudscape-design/components/container"+import Header from "@cloudscape-design/components/header"+import Input from "@cloudscape-design/components/input"+import Link from "@cloudscape-design/components/link"+import Modal from "@cloudscape-design/components/modal"+import Select from "@cloudscape-design/components/select"+import SpaceBetween from "@cloudscape-design/components/space-between"+import Spinner from "@cloudscape-design/components/spinner"+import StatusIndicator from "@cloudscape-design/components/status-indicator"+import Table from "@cloudscape-design/components/table"+import Tabs from "@cloudscape-design/components/tabs"+import { api, claimsApi, type Claim } from "../api/cyclops"+import { derivePoolStatus, tombstonePool } from "../api/pools"+import { useFeatureFlags } from "../components/FeatureFlagContext"+import { useFlash } from "../components/FlashContext"+import { PoolStatusPill } from "../components/PoolStatus"++interface ServiceDef {+ name: string+ targetPort: number+ protocol: string+}++interface PoolData {+ name: string+ namespace: string+ replicas: number+ cpu: number+ ram: string+ ociImage: string+ services: ServiceDef[]+ probes?: { readinessProbe?: Record<string, unknown>; livenessProbe?: Record<string, unknown> }+ phase: string+ totalCount: number+ availableCount: number+ claimedCount: number+}++export function PoolDetail() {+ const { namespace = "", name = "" } = useParams()+ const navigate = useNavigate()+ const flash = useFlash()+ const { admin } = useFeatureFlags()++ const [pool, setPool] = useState<PoolData | null>(null)+ const [loading, setLoading] = useState(true)+ const [confirmingDelete, setConfirmingDelete] = useState(false)+ const [deleting, setDeleting] = useState(false)++ // Orchestrator restart state (admin-only)+ const [confirmingOrchestratorRestart, setConfirmingOrchestratorRestart] = useState(false)+ const [orchestratorRestarting, setOrchestratorRestarting] = useState(false)++ const load = async () => {+ setLoading(true)+ try {+ const p = await api.getPool(namespace, name)+ setPool(p)+ } catch (e) {+ flash.push({+ type: "error",+ header: `Failed to load pool "${name}"`,+ content: String((e as Error).message),+ })+ } finally {+ setLoading(false)+ }+ }+ useEffect(() => {+ if (namespace && name) load()+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [namespace, name])++ const remove = async () => {+ setDeleting(true)+ try {+ await api.deletePool(namespace, name)+ tombstonePool(name)+ flash.push({ type: "success", header: `Deleted ${name}` })+ navigate("/pools")+ } catch (e) {+ flash.push({+ type: "error",+ header: "Delete failed",+ content: String((e as Error).message),+ })+ setDeleting(false)+ }+ }++ const restartOrchestrator = async () => {+ if (!pool) return+ setOrchestratorRestarting(true)+ try {+ await api.restartOrchestrator(`pool-${pool.name}`, pool.name)+ flash.push({+ type: "success",+ header: `Restarting orchestrator for ${pool.name}`,+ content:+ "A rollout restart has been triggered. The orchestrator pod will be replaced momentarily.",+ })+ } catch (e) {+ flash.push({+ type: "error",+ header: "Orchestrator restart failed",+ content: String((e as Error).message),+ })+ } finally {+ setOrchestratorRestarting(false)+ setConfirmingOrchestratorRestart(false)+ }+ }++ if (loading && !pool) {+ return (+ <Container header={<Header variant="h1">{name}</Header>}>+ <Box textAlign="center" padding="l">+ <Spinner /> Loading pool…+ </Box>+ </Container>+ )+ }+ if (!pool) return null++ const status = derivePoolStatus(pool)++ return (+ <SpaceBetween size="l">+ <Container+ header={+ <Header+ variant="h1"+ actions={+ <SpaceBetween direction="horizontal" size="xs">+ <Button iconName="refresh" onClick={load} />+ <Button+ onClick={() =>+ pool && navigate("/pools/new", { state: { source: pool } })+ }+ >+ Duplicate+ </Button>+ {admin && (+ <Button+ onClick={() => setConfirmingOrchestratorRestart(true)}+ disabled={orchestratorRestarting}+ >+ Restart orchestrator+ </Button>+ )}+ <Button onClick={() => setConfirmingDelete(true)}>+ Delete+ </Button>+ </SpaceBetween>+ }+ >+ {pool.name}+ </Header>+ }+ >+ <ColumnLayout columns={admin ? 3 : 2} variant="text-grid">+ <div>+ <Box variant="awsui-key-label">Status</Box>+ <PoolStatusPill status={status} />+ </div>+ <div>+ <Box variant="awsui-key-label">Namespace</Box>+ <div>{pool.namespace}</div>+ </div>+ {admin && (+ <div>+ <Box variant="awsui-key-label">Gateway</Box>+ <div>+ <code>{window.location.origin}/api/gateway/{pool.name}</code>+ </div>+ </div>+ )}+ </ColumnLayout>+ </Container>++ <Tabs+ tabs={[+ {+ label: "Claims",+ id: "claims",+ content: <ClaimsTable pool={pool} />,+ },+ {+ label: "Configuration",+ id: "configuration",+ content: <ConfigurationTab pool={pool} onServicesUpdated={load} />,+ },+ ]}+ />++ <Modal+ visible={confirmingDelete}+ onDismiss={() => setConfirmingDelete(false)}+ header={`Delete ${name}?`}+ footer={+ <Box float="right">+ <SpaceBetween direction="horizontal" size="xs">+ <Button onClick={() => setConfirmingDelete(false)}>+ Cancel+ </Button>+ <Button variant="primary" onClick={remove} loading={deleting}>+ Delete+ </Button>+ </SpaceBetween>+ </Box>+ }+ >+ This deletes the pool and tears down all VMs and the orchestrator+ in <b>{pool.namespace}</b>.+ </Modal>++ {admin && (+ <Modal+ visible={confirmingOrchestratorRestart}+ onDismiss={() => { if (!orchestratorRestarting) setConfirmingOrchestratorRestart(false) }}+ header={`Restart orchestrator for ${name}?`}+ footer={+ <Box float="right">+ <SpaceBetween direction="horizontal" size="xs">+ <Button+ onClick={() => setConfirmingOrchestratorRestart(false)}+ disabled={orchestratorRestarting}+ >+ Cancel+ </Button>+ <Button+ variant="primary"+ onClick={restartOrchestrator}+ loading={orchestratorRestarting}+ >+ Restart orchestrator+ </Button>+ </SpaceBetween>+ </Box>+ }+ >+ This will trigger a rolling restart of the{" "}+ <b>{name}-orchestrator</b> Deployment in{" "}+ <b>{pool.namespace}</b>. Equivalent to{" "}+ <code>kubectl rollout restart deployment/{name}-orchestrator</code>.+ In-flight requests will be drained before the old pod is terminated.+ </Modal>+ )}+ </SpaceBetween>+ )+}++function probePort(probe?: Record<string, unknown>): string {+ if (!probe) return ""+ const tcp = probe.tcpSocket as { port?: number } | undefined+ if (tcp?.port) return `TCP :${tcp.port}`+ const http = probe.httpGet as { port?: number; path?: string } | undefined+ if (http?.port) return `HTTP :${http.port}${http.path ?? ""}`+ return JSON.stringify(probe)+}++// -- Configuration tab ----------------------------------------------------------++function ConfigurationTab({+ pool,+ onServicesUpdated,+}: {+ pool: PoolData+ onServicesUpdated: () => void+}) {+ return (+ <SpaceBetween size="l">+ <Container header={<Header variant="h2">Configuration</Header>}>+ <ColumnLayout columns={2} variant="text-grid">+ <div>+ <Box variant="awsui-key-label">vCPU cores</Box>+ <div>{pool.cpu}</div>+ </div>+ <div>+ <Box variant="awsui-key-label">RAM</Box>+ <div>{pool.ram}</div>+ </div>+ <div>+ <Box variant="awsui-key-label">OCI image</Box>+ <div><code>{pool.ociImage}</code></div>+ </div>+ <div>+ <Box variant="awsui-key-label">Replicas</Box>+ <div>{pool.replicas}</div>+ </div>+ <div>+ <Box variant="awsui-key-label">Available / Total</Box>+ <div>{pool.availableCount} / {pool.totalCount}</div>+ </div>+ <div>+ <Box variant="awsui-key-label">Claimed</Box>+ <div>{pool.claimedCount}</div>+ </div>+ <div>+ <Box variant="awsui-key-label">Readiness probe</Box>+ <div>{probePort(pool.probes?.readinessProbe) || "None"}</div>+ </div>+ <div>+ <Box variant="awsui-key-label">Liveness probe</Box>+ <div>{probePort(pool.probes?.livenessProbe) || "None"}</div>+ </div>+ </ColumnLayout>+ </Container>+ <ServicesEditor pool={pool} onSaved={onServicesUpdated} />+ </SpaceBetween>+ )+}++// -- Services editor ------------------------------------------------------------++interface ServiceRow {+ id: string+ name: string+ targetPort: string+ protocol: string+}++const PROTOCOL_OPTIONS = [+ { label: "TCP", value: "TCP" },+ { label: "UDP", value: "UDP" },+]++let _svcId = 0+function svcId(): string {+ return String(++_svcId)+}++function ServicesEditor({+ pool,+ onSaved,+}: {+ pool: PoolData+ onSaved: () => void+}) {+ const flash = useFlash()+ const [rows, setRows] = useState<ServiceRow[]>(() =>+ pool.services.map(s => ({+ id: svcId(),+ name: s.name,+ targetPort: String(s.targetPort),+ protocol: s.protocol,+ })),+ )+ const [saving, setSaving] = useState(false)++ // Reset rows when pool data changes (e.g. after reload)+ useEffect(() => {+ setRows(+ pool.services.map(s => ({+ id: svcId(),+ name: s.name,+ targetPort: String(s.targetPort),+ protocol: s.protocol,+ })),+ )+ }, [pool.services])++ const addRow = () =>+ setRows(prev => [...prev, { id: svcId(), name: "", targetPort: "", protocol: "TCP" }])++ const updateRow = (id: string, field: keyof ServiceRow, value: string) =>+ setRows(prev => prev.map(r => (r.id === id ? { ...r, [field]: value } : r)))++ const removeRow = (id: string) =>+ setRows(prev => prev.filter(r => r.id !== id))++ const save = async () => {+ const filled = rows.filter(r => r.name && r.targetPort)+ // Validate port range+ for (const r of filled) {+ const p = parseInt(r.targetPort, 10)+ if (isNaN(p) || p < 1 || p > 65535) {+ flash.push({+ type: "error",+ header: "Invalid port",+ content: `"${r.targetPort}" is not a valid port (1-65535).`,+ })+ return+ }+ }+ // Validate no duplicate names+ const seen = new Set<string>()+ for (const r of filled) {+ if (seen.has(r.name)) {+ flash.push({+ type: "error",+ header: "Duplicate service name",+ content: `"${r.name}" is used more than once.`,+ })+ return+ }+ seen.add(r.name)+ }++ setSaving(true)+ try {+ const services = filled.map(r => ({+ name: r.name,+ targetPort: parseInt(r.targetPort, 10),+ protocol: r.protocol || "TCP",+ }))+ await api.updatePoolServices(pool.namespace, pool.name, services)+ flash.push({ type: "success", header: "Services updated" })+ onSaved()+ } catch (e) {+ flash.push({+ type: "error",+ header: "Failed to update services",+ content: String((e as Error).message),+ })+ } finally {+ setSaving(false)+ }+ }++ return (+ <Container+ header={+ <Header+ variant="h2"+ actions={+ <SpaceBetween direction="horizontal" size="xs">+ <Button iconName="add-plus" onClick={addRow}>+ Add service+ </Button>+ <Button variant="primary" loading={saving} onClick={save}>+ Save+ </Button>+ </SpaceBetween>+ }+ >+ Services+ </Header>+ }+ >+ {rows.length === 0 ? (+ <Box color="text-status-inactive">+ No services defined. Add one to expose extra ports on each sandbox.+ </Box>+ ) : (+ <SpaceBetween size="s">+ {rows.map(row => (+ <ColumnLayout key={row.id} columns={4}>+ <Input+ value={row.name}+ onChange={({ detail }) => updateRow(row.id, "name", detail.value)}+ placeholder="Service name"+ />+ <Input+ type="number"+ value={row.targetPort}+ onChange={({ detail }) => updateRow(row.id, "targetPort", detail.value)}+ placeholder="Target port"+ />+ <Select+ selectedOption={+ PROTOCOL_OPTIONS.find(o => o.value === row.protocol) ?? PROTOCOL_OPTIONS[0]+ }+ onChange={({ detail }) =>+ updateRow(row.id, "protocol", detail.selectedOption.value ?? "TCP")+ }+ options={PROTOCOL_OPTIONS}+ />+ <Button iconName="remove" variant="icon" onClick={() => removeRow(row.id)} />+ </ColumnLayout>+ ))}+ </SpaceBetween>+ )}+ </Container>+ )+}++// ── Claims table ──────────────────────────────────────────────────────────++function claimStatusType(phase: string): "success" | "pending" | "error" | "info" {+ switch (phase) {+ case "Bound":+ return "success"+ case "Pending":+ return "pending"+ case "Failed":+ return "error"+ default:+ return "info"+ }+}++function age(iso: string): string {+ if (!iso) return "-"+ const ms = Date.now() - new Date(iso).getTime()+ if (ms < 0) return "just now"+ const secs = Math.floor(ms / 1000)+ if (secs < 60) return `${secs}s`+ const mins = Math.floor(secs / 60)+ if (mins < 60) return `${mins}m`+ const hrs = Math.floor(mins / 60)+ if (hrs < 24) return `${hrs}h`+ return `${Math.floor(hrs / 24)}d`+}++function ClaimsTable({ pool }: { pool: PoolData }) {+ const navigate = useNavigate()+ const flash = useFlash()+ const [claims, setClaims] = useState<Claim[]>([])+ const [loading, setLoading] = useState(true)+ const [showCreate, setShowCreate] = useState(false)+ const [creating, setCreating] = useState(false)+ const [confirmRelease, setConfirmRelease] = useState<string | null>(null)+ const [releasing, setReleasing] = useState(false)+ const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)++ // Pool name = namespace name (1:1 mapping).+ const claimNamespace = pool.namespace+ // The compat shim names the template <pool-name>-template.+ const templateRef = `${pool.name}-template`++ const loadClaims = useCallback(async () => {+ try {+ const list = await claimsApi.list(claimNamespace)+ setClaims(list)+ } catch {+ // Silently ignore polling errors — the table will show stale data+ // until the next successful poll.+ } finally {+ setLoading(false)+ }+ }, [claimNamespace])++ // Initial load + 5-second auto-refresh.+ useEffect(() => {+ loadClaims()+ timerRef.current = setInterval(loadClaims, 5000)+ return () => {+ if (timerRef.current) clearInterval(timerRef.current)+ }+ }, [loadClaims])++ const createClaim = async () => {+ setCreating(true)+ try {+ const id = `claim-${Math.random().toString(36).slice(2, 10)}`+ await claimsApi.create(claimNamespace, id, templateRef)+ flash.push({ type: "success", header: `Created claim ${id}` })+ setShowCreate(false)+ await loadClaims()+ } catch (e) {+ flash.push({+ type: "error",+ header: "Failed to create claim",+ content: String((e as Error).message),+ })+ } finally {+ setCreating(false)+ }+ }++ const releaseClaim = async (claimName: string) => {+ setReleasing(true)+ try {+ await claimsApi.remove(claimNamespace, claimName)+ flash.push({ type: "success", header: `Released claim ${claimName}` })+ setConfirmRelease(null)+ await loadClaims()+ } catch (e) {+ flash.push({+ type: "error",+ header: "Failed to release claim",+ content: String((e as Error).message),+ })+ } finally {+ setReleasing(false)+ }+ }++ return (+ <>+ <Table+ loading={loading}+ items={claims}+ header={+ <Header+ variant="h2"+ counter={`(${claims.length})`}+ actions={+ <SpaceBetween direction="horizontal" size="xs">+ <Button iconName="refresh" onClick={loadClaims} />+ <Button variant="primary" onClick={() => setShowCreate(true)}>+ Create claim+ </Button>+ </SpaceBetween>+ }+ >+ Claims+ </Header>+ }+ columnDefinitions={[+ {+ id: "name",+ header: "Name",+ cell: (c: Claim) => (+ <Link+ href={`#/pools/${pool.namespace}/${pool.name}/claims/${c.name}`}+ onFollow={e => {+ e.preventDefault()+ navigate(`/pools/${pool.namespace}/${pool.name}/claims/${c.name}`)+ }}+ >+ {c.name}+ </Link>+ ),+ sortingField: "name",+ },+ {+ id: "status",+ header: "Status",+ cell: (c: Claim) => (+ <StatusIndicator type={claimStatusType(c.phase)}>+ {c.phase}+ </StatusIndicator>+ ),+ sortingField: "phase",+ },+ {+ id: "sandbox",+ header: "VM Name",+ cell: (c: Claim) => c.sandboxName ?? "-",+ },+ {+ id: "age",+ header: "Age",+ cell: (c: Claim) => age(c.createdAt),+ },+ {+ id: "actions",+ header: "Actions",+ cell: (c: Claim) => (+ <Button+ variant="inline-link"+ onClick={() => setConfirmRelease(c.name)}+ >+ Release+ </Button>+ ),+ },+ ]}+ empty={+ <Box textAlign="center" color="text-status-inactive" padding="l">+ No claims. Create one to get a VM from this pool.+ </Box>+ }+ />++ {/* Create claim modal */}+ <Modal+ visible={showCreate}+ onDismiss={() => { if (!creating) setShowCreate(false) }}+ header="Create claim"+ footer={+ <Box float="right">+ <SpaceBetween direction="horizontal" size="xs">+ <Button+ onClick={() => setShowCreate(false)}+ disabled={creating}+ >+ Cancel+ </Button>+ <Button+ variant="primary"+ onClick={createClaim}+ loading={creating}+ >+ Create+ </Button>+ </SpaceBetween>+ </Box>+ }+ >+ <SpaceBetween size="m">+ <div>+ <Box variant="awsui-key-label">Namespace</Box>+ <div>{claimNamespace}</div>+ </div>+ <div>+ <Box variant="awsui-key-label">Name</Box>+ <div>Auto-generated (claim-<random>)</div>+ </div>+ </SpaceBetween>+ </Modal>++ {/* Release confirmation modal */}+ <Modal+ visible={confirmRelease !== null}+ onDismiss={() => { if (!releasing) setConfirmRelease(null) }}+ header={`Release claim ${confirmRelease}?`}+ footer={+ <Box float="right">+ <SpaceBetween direction="horizontal" size="xs">+ <Button+ onClick={() => setConfirmRelease(null)}+ disabled={releasing}+ >+ Cancel+ </Button>+ <Button+ variant="primary"+ onClick={() => confirmRelease && releaseClaim(confirmRelease)}+ loading={releasing}+ >+ Release+ </Button>+ </SpaceBetween>+ </Box>+ }+ >+ This will delete the claim and return its sandbox VM back to the+ warm pool (default Retain policy). The VM will be restarted with a+ clean state.+ </Modal>+ </>+ )+}diff --git a/libs/fleet/src/pages/PoolNew.tsx b/libs/fleet/src/pages/PoolNew.tsxnew file mode 100644index 0000000000..7dfa68a210--- /dev/null+++ b/libs/fleet/src/pages/PoolNew.tsx@@ -0,0 +1,430 @@+import { useMemo, useState } from "react"+import { useLocation, useNavigate } from "react-router-dom"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import ColumnLayout from "@cloudscape-design/components/column-layout"+import Container from "@cloudscape-design/components/container"+import Form from "@cloudscape-design/components/form"+import FormField from "@cloudscape-design/components/form-field"+import Header from "@cloudscape-design/components/header"+import Input from "@cloudscape-design/components/input"+import Select from "@cloudscape-design/components/select"+import SpaceBetween from "@cloudscape-design/components/space-between"+import Toggle from "@cloudscape-design/components/toggle"+import { api, type PoolTemplateConfig } from "../api/cyclops"+import { useFlash } from "../components/FlashContext"+import { useFeatureFlags } from "../components/FeatureFlagContext"++const NAME_PATTERN = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/++const RUNTIME_OPTIONS = [+ { label: "KubeVirt VM (Linux / Windows)", value: "kubevirt" },+ { label: "macOS VM", value: "macos" },+ { label: "gVisor pod (sandboxed Linux)", value: "gvisor" },+]+// A macOS pool's default desktop image (admin-only). Overridable in the field.+const MACOS_DEFAULT_IMAGE = "127.0.0.1:5000/cua/macos-desktop-workspace:latest"++const DEFAULTS = {+ cpu: 4,+ ram: "4Gi",+ ociImage: "296062593712.dkr.ecr.us-west-2.amazonaws.com/osgym-workspace:latest",+ replicas: 1,+}++const PROTOCOL_OPTIONS = [+ { label: "TCP", value: "TCP" },+ { label: "UDP", value: "UDP" },+]++const FIRMWARE_OPTIONS = [+ { label: "BIOS (default)", value: "bios", description: "Legacy boot — the Linux workspace images." },+ { label: "UEFI", value: "efi", description: "Required for GPT/UEFI-only images, e.g. the Windows desktop-workspace." },+]++interface ServiceEntry {+ id: string+ name: string+ targetPort: string+ protocol: string+}++interface PoolSource {+ name: string+ cpu?: number+ ram?: string+ ociImage?: string+ firmware?: "bios" | "efi"+ replicas?: number+ services?: { name: string; targetPort: number; protocol: string }[]+}++// Navigation state PoolNew accepts:+// { source } — duplicate an existing pool (from the Pools list)+interface PoolNewState {+ source?: PoolSource+}++let nextId = 0+function genId(): string {+ return String(++nextId)+}++// Recover the TCP port from a {tcpSocket:{port}} probe so the form's+// readiness/liveness fields round-trip through a duplicated pool.+function portFromProbe(probe?: Record<string, unknown>): string {+ const sock = probe?.tcpSocket as { port?: number } | undefined+ return sock?.port ? String(sock.port) : ""+}++export function PoolNew() {+ const navigate = useNavigate()+ const location = useLocation()+ const flash = useFlash()++ const navState = location.state as PoolNewState | null+ const source = navState?.source ?? null+ // Seed from the duplicated pool, if any.+ const seed: Partial<PoolTemplateConfig> = source ?? {}++ const [name, setName] = useState(source ? `${source.name}-copy` : "")+ const [cpu, setCpu] = useState(String(seed.cpu ?? DEFAULTS.cpu))+ const [ram, setRam] = useState(seed.ram ?? DEFAULTS.ram)+ const [ociImage, setOciImage] = useState(seed.ociImage ?? DEFAULTS.ociImage)+ const [firmware, setFirmware] = useState<"bios" | "efi">(seed.firmware ?? "bios")+ const [replicas, setReplicas] = useState(String(seed.replicas ?? DEFAULTS.replicas))+ const [readinessPort, setReadinessPort] = useState(+ portFromProbe(seed.probes?.readinessProbe),+ )+ const [livenessPort, setLivenessPort] = useState(+ portFromProbe(seed.probes?.livenessProbe),+ )+ const [services, setServices] = useState<ServiceEntry[]>(+ (seed.services ?? []).map(s => ({+ id: genId(),+ name: s.name,+ targetPort: String(s.targetPort),+ protocol: s.protocol,+ })),+ )+ // Autoscaling extension (optional). When enabled, the pool gets a KEDA+ // ScaledObject that scales it to claim demand.+ const [autoscalingEnabled, setAutoscalingEnabled] = useState(!!seed.autoscaling)+ const [minPoolSize, setMinPoolSize] = useState(String(seed.autoscaling?.minPoolSize ?? 0))+ const [initialPoolSize, setInitialPoolSize] = useState(String(seed.autoscaling?.initialPoolSize ?? 0))+ const [maxPoolSize, setMaxPoolSize] = useState(String(seed.autoscaling?.maxPoolSize ?? 20))+ const [submitting, setSubmitting] = useState(false)+ // macOS is an admin-only capability — the selector is only rendered for+ // admins, and the backend independently rejects macos pool writes from+ // non-admins (handlers/k8s.go macosPoolNeedsAdmin). Non-admins never see it.+ const { admin } = useFeatureFlags()+ const [runtime, setRuntime] = useState<"kubevirt" | "macos" | "gvisor">(seed.runtime ?? "kubevirt")+ // Pod runtimes (macos, gvisor) are gated to admins in the UI; the backend+ // independently rejects macos writes from non-admins (handlers/k8s.go).+ const isPodRuntime = admin && runtime !== "kubevirt"+ const isMacos = admin && runtime === "macos"++ const nameError = useMemo(() => {+ if (!name) return undefined+ if (!NAME_PATTERN.test(name)) {+ return "Lowercase letters, digits, and dashes only; no leading/trailing dash."+ }+ return undefined+ }, [name])++ const addService = () => {+ setServices(prev => [...prev, { id: genId(), name: "", targetPort: "", protocol: "TCP" }])+ }++ const updateService = (id: string, field: keyof ServiceEntry, value: string) => {+ setServices(prev => prev.map(s => (s.id === id ? { ...s, [field]: value } : s)))+ }++ const removeService = (id: string) => {+ setServices(prev => prev.filter(s => s.id !== id))+ }++ // Collect the current form into the config object that api.createPool+ // consumes.+ const buildValues = (): PoolTemplateConfig => {+ const validServices = services+ .filter(s => s.name.trim() && s.targetPort)+ .map(s => ({+ name: s.name.trim(),+ targetPort: parseInt(s.targetPort, 10),+ protocol: s.protocol || "TCP",+ }))+ const readPort = parseInt(readinessPort, 10)+ const livePort = parseInt(livenessPort, 10)+ const probes: {+ readinessProbe?: Record<string, unknown>+ livenessProbe?: Record<string, unknown>+ } = {}+ if (readPort) probes.readinessProbe = { tcpSocket: { port: readPort } }+ if (livePort) probes.livenessProbe = { tcpSocket: { port: livePort } }+ // A macOS pool auto-gets a `vnc` service (unless the user added one) so its+ // desktop streams to the ClaimDetail DesktopPane over noVNC.+ const svcs = isMacos && !validServices.some(s => s.name === "vnc")+ ? [...validServices, { name: "vnc", targetPort: 6080, protocol: "TCP" }]+ : validServices+ return {+ cpu: parseInt(cpu, 10) || DEFAULTS.cpu,+ ram: ram.trim() || DEFAULTS.ram,+ // Trim pasted whitespace: K8s rejects pod images with leading/trailing+ // spaces, which wedges the pool's VM in Starting forever.+ ociImage: ociImage.trim() || (isMacos ? MACOS_DEFAULT_IMAGE : DEFAULTS.ociImage),+ firmware: firmware !== "bios" ? firmware : undefined,+ runtime: isPodRuntime ? runtime : undefined,+ replicas: parseInt(replicas, 10) || DEFAULTS.replicas,+ services: svcs.length ? svcs : undefined,+ probes: Object.keys(probes).length ? probes : undefined,+ autoscaling: autoscalingEnabled+ ? {+ minPoolSize: parseInt(minPoolSize, 10) || 0,+ initialPoolSize: parseInt(initialPoolSize, 10) || 0,+ maxPoolSize: parseInt(maxPoolSize, 10) || 20,+ }+ : undefined,+ }+ }++ const create = async () => {+ if (!name || nameError) return+ setSubmitting(true)+ try {+ await api.createPool(name, buildValues())+ flash.push({ type: "success", header: `Created pool ${name}` })+ // Pool name = namespace name (1:1 mapping).+ navigate(`/pools/${name}/${name}`)+ } catch (e) {+ flash.push({+ type: "error",+ header: "Create failed",+ content: String((e as Error).message),+ })+ } finally {+ setSubmitting(false)+ }+ }++ const submitDisabled = !name || !!nameError || submitting++ return (+ <Container+ header={+ <Header+ variant="h1"+ description={+ source+ ? `Duplicating "${source.name}". Edit and save as a new pool.`+ : "Create a new pool."+ }+ >+ {source ? "Duplicate pool" : "New pool"}+ </Header>+ }+ >+ <Form+ actions={+ <SpaceBetween direction="horizontal" size="xs">+ <Button onClick={() => navigate("/pools")}>Cancel</Button>+ <Button+ variant="primary"+ loading={submitting}+ disabled={submitDisabled}+ onClick={create}+ >+ Create+ </Button>+ </SpaceBetween>+ }+ >+ <SpaceBetween size="l">+ <FormField+ label="Name"+ description={+ name+ ? `Pool: ${name}`+ : "Lowercase letters, digits, and dashes."+ }+ errorText={nameError}+ >+ <Input+ value={name}+ onChange={({ detail }) => setName(detail.value)}+ placeholder="my-pool"+ />+ </FormField>++ <FormField label="vCPU cores">+ <Input+ type="number"+ value={cpu}+ onChange={({ detail }) => setCpu(detail.value)}+ />+ </FormField>++ <FormField label="RAM" description="Kubernetes quantity, e.g. 4Gi.">+ <Input+ value={ram}+ onChange={({ detail }) => setRam(detail.value)}+ />+ </FormField>++ {admin && (+ <FormField+ label="Runtime"+ description="Admin-only. macOS provisions a macOS sandbox (streamable over noVNC) instead of a KubeVirt VM."+ >+ <Select+ selectedOption={RUNTIME_OPTIONS.find(o => o.value === runtime) ?? RUNTIME_OPTIONS[0]}+ onChange={({ detail }) => setRuntime((detail.selectedOption.value as "kubevirt" | "macos" | "gvisor") ?? "kubevirt")}+ options={RUNTIME_OPTIONS}+ />+ </FormField>+ )}++ <FormField+ label="OCI image"+ description={isMacos+ ? "macOS sandbox image ref (defaults to the macos-desktop-workspace image if left blank)."+ : "Workspace containerDisk image (and the image used by /reset-created VMs)."}+ >+ <Input+ value={ociImage}+ onChange={({ detail }) => setOciImage(detail.value)}+ />+ </FormField>++ <FormField+ label="Firmware"+ description="UEFI is required for GPT/UEFI-only images like the Windows desktop-workspace; Linux workspace images use BIOS."+ >+ <Select+ selectedOption={FIRMWARE_OPTIONS.find(o => o.value === firmware) ?? FIRMWARE_OPTIONS[0]}+ onChange={({ detail }) => setFirmware((detail.selectedOption.value as "bios" | "efi") ?? "bios")}+ options={FIRMWARE_OPTIONS}+ />+ </FormField>++ <FormField+ label="Replicas"+ description="Static number of pre-warmed VMs the orchestrator keeps. When lane autoscaling is on (below), KEDA takes over this value."+ >+ <Input+ type="number"+ value={replicas}+ onChange={({ detail }) => setReplicas(detail.value)}+ />+ </FormField>++ <FormField+ label="Autoscaling"+ description="Optional. KEDA scales the pool to its claim demand (the number of claims/VMs in use), and back down when idle (never below Min pool size). Off = the static Replicas above."+ >+ <Toggle+ checked={autoscalingEnabled}+ onChange={({ detail }) => setAutoscalingEnabled(detail.checked)}+ >+ Scale to claim demand+ </Toggle>+ </FormField>++ {autoscalingEnabled && (+ <ColumnLayout columns={2}>+ <FormField+ label="Min pool size"+ description="Durable warm floor (KEDA minReplicaCount). Set > 0 to keep spare VMs so a fresh claim binds without a cold start."+ >+ <Input+ type="number"+ value={minPoolSize}+ onChange={({ detail }) => setMinPoolSize(detail.value)}+ />+ </FormField>+ <FormField+ label="Initial pool size"+ description="One-time warm head-start seeded on create; KEDA then manages the size."+ >+ <Input+ type="number"+ value={initialPoolSize}+ onChange={({ detail }) => setInitialPoolSize(detail.value)}+ />+ </FormField>+ <FormField+ label="Max pool size"+ description="Hard ceiling (KEDA maxReplicaCount)."+ >+ <Input+ type="number"+ value={maxPoolSize}+ onChange={({ detail }) => setMaxPoolSize(detail.value)}+ />+ </FormField>+ </ColumnLayout>+ )}++ <FormField+ label="Readiness port"+ description="TCP port the VM must be listening on before it's marked ready. Default: 5000."+ >+ <Input+ type="number"+ value={readinessPort}+ onChange={({ detail }) => setReadinessPort(detail.value)}+ placeholder="5000"+ />+ </FormField>++ <FormField+ label="Liveness port"+ description="TCP port checked periodically to restart unresponsive VMs. Optional."+ >+ <Input+ type="number"+ value={livenessPort}+ onChange={({ detail }) => setLivenessPort(detail.value)}+ placeholder=""+ />+ </FormField>++ <FormField+ label="Services"+ description="Extra K8s Services created per sandbox. Each maps port 80 to the target port on the VM."+ >+ <SpaceBetween size="s">+ {services.map(svc => (+ <ColumnLayout key={svc.id} columns={4}>+ <Input+ value={svc.name}+ onChange={({ detail }) => updateService(svc.id, "name", detail.value)}+ placeholder="Service name"+ />+ <Input+ type="number"+ value={svc.targetPort}+ onChange={({ detail }) => updateService(svc.id, "targetPort", detail.value)}+ placeholder="Target port"+ />+ <Select+ selectedOption={PROTOCOL_OPTIONS.find(o => o.value === svc.protocol) ?? PROTOCOL_OPTIONS[0]}+ onChange={({ detail }) => updateService(svc.id, "protocol", detail.selectedOption.value ?? "TCP")}+ options={PROTOCOL_OPTIONS}+ />+ <Button iconName="remove" variant="icon" onClick={() => removeService(svc.id)} />+ </ColumnLayout>+ ))}+ {services.length === 0 && (+ <Box color="text-status-inactive">No services defined.</Box>+ )}+ <Button iconName="add-plus" onClick={addService}>+ Add service+ </Button>+ </SpaceBetween>+ </FormField>+ </SpaceBetween>+ </Form>+ </Container>+ )+}diff --git a/libs/fleet/src/pages/PoolReplicaDetail.tsx b/libs/fleet/src/pages/PoolReplicaDetail.tsxnew file mode 100644index 0000000000..23272f093e--- /dev/null+++ b/libs/fleet/src/pages/PoolReplicaDetail.tsx@@ -0,0 +1,305 @@+import { useEffect, useMemo, useState } from "react"+import { useNavigate, useParams } from "react-router-dom"+import BreadcrumbGroup from "@cloudscape-design/components/breadcrumb-group"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import ColumnLayout from "@cloudscape-design/components/column-layout"+import Container from "@cloudscape-design/components/container"+import Header from "@cloudscape-design/components/header"+import Modal from "@cloudscape-design/components/modal"+import ProgressBar from "@cloudscape-design/components/progress-bar"+import SpaceBetween from "@cloudscape-design/components/space-between"+import Spinner from "@cloudscape-design/components/spinner"+import StatusIndicator from "@cloudscape-design/components/status-indicator"+import { api, parseMemoryBytes, sumPodUsage } from "../api/cyclops"+import type { PodMetrics, PodSummary } from "../api/cyclops"+import { useFlash } from "../components/FlashContext"+import { LogsPanel } from "../components/LogsPanel"++const LOG_CONTAINER = "guest-console-log"+const METRICS_INTERVAL_MS = 5000++export function PoolReplicaDetail() {+ const { namespace: nsParam = "", poolName = "", vmName = "" } = useParams()+ const navigate = useNavigate()+ const flash = useFlash()++ const [namespace, setNamespace] = useState<string | null>(null)+ const [launcher, setLauncher] = useState<PodSummary | null>(null)+ const [launcherLoading, setLauncherLoading] = useState(true)+ const [launcherError, setLauncherError] = useState<string | null>(null)++ const [metrics, setMetrics] = useState<PodMetrics | null>(null)+ const [metricsError, setMetricsError] = useState<string | null>(null)++ // Pool's spec.cpu / spec.ram (denominators for the progress bars).+ const [cpuLimit, setCpuLimit] = useState<number | null>(null)+ const [memLimit, setMemLimit] = useState<number | null>(null)++ // Restart confirmation dialog state.+ const [confirmingRestart, setConfirmingRestart] = useState(false)+ const [restarting, setRestarting] = useState(false)++ useEffect(() => {+ if (!nsParam || !poolName) return+ api+ .getPool(nsParam, poolName)+ .then(p => {+ setNamespace(p.namespace)+ setCpuLimit(p.cpu)+ setMemLimit(parseMemoryBytes(p.ram))+ })+ .catch(e => setLauncherError(String((e as Error).message)))+ }, [nsParam, poolName])++ // Once we have the namespace, find the launcher pod.+ useEffect(() => {+ if (!namespace || !vmName) return+ setLauncherLoading(true)+ setLauncherError(null)+ api+ .findLauncherPod(namespace, vmName)+ .then(p => setLauncher(p))+ .catch(e => setLauncherError(String((e as Error).message)))+ .finally(() => setLauncherLoading(false))+ }, [namespace, vmName])++ // Poll metrics every 5s once we have a launcher pod.+ useEffect(() => {+ if (!launcher) return+ let cancelled = false+ const tick = async () => {+ try {+ const m = await api.getPodMetrics(+ launcher.metadata.namespace,+ launcher.metadata.name,+ )+ if (!cancelled) {+ setMetrics(m)+ setMetricsError(null)+ }+ } catch (e) {+ if (!cancelled) setMetricsError(String((e as Error).message))+ }+ }+ tick()+ const id = window.setInterval(tick, METRICS_INTERVAL_MS)+ return () => {+ cancelled = true+ window.clearInterval(id)+ }+ }, [launcher])++ const usage = useMemo(() => (metrics ? sumPodUsage(metrics) : null), [metrics])++ const refresh = () => {+ if (!namespace) return+ setLauncherLoading(true)+ setLauncherError(null)+ api+ .findLauncherPod(namespace, vmName)+ .then(p => setLauncher(p))+ .catch(e => setLauncherError(String((e as Error).message)))+ .finally(() => setLauncherLoading(false))+ }++ const restart = async () => {+ if (!namespace) return+ setRestarting(true)+ try {+ await api.restartVm(namespace, vmName)+ flash.push({+ type: "success",+ header: `Restarting ${vmName}`,+ content:+ "The VM restart has been requested. The VMI will terminate and a fresh instance will start from the same spec.",+ })+ setConfirmingRestart(false)+ // Refresh after a short delay to pick up the new launcher pod.+ setTimeout(refresh, 3000)+ } catch (e) {+ flash.push({+ type: "error",+ header: "Restart failed",+ content: String((e as Error).message),+ })+ } finally {+ setRestarting(false)+ setConfirmingRestart(false)+ }+ }++ return (+ <SpaceBetween size="l">+ <BreadcrumbGroup+ items={[+ { text: "Pools", href: "#/pools" },+ { text: poolName, href: `#/pools/${nsParam}/${poolName}` },+ { text: vmName, href: "#" },+ ]}+ onFollow={e => {+ if (e.detail.href === "#") return+ e.preventDefault()+ navigate(e.detail.href.replace(/^#/, ""))+ }}+ />++ <Container+ header={+ <Header+ variant="h1"+ actions={+ <SpaceBetween direction="horizontal" size="xs">+ <Button iconName="refresh" onClick={refresh} disabled={launcherLoading}>+ Refresh+ </Button>+ <Button+ onClick={() => setConfirmingRestart(true)}+ disabled={restarting}+ >+ Restart+ </Button>+ </SpaceBetween>+ }+ >+ {vmName}+ </Header>+ }+ >+ <ColumnLayout columns={2}>+ <div>+ <Box variant="awsui-key-label">CPU</Box>+ <MetricTile+ error={metricsError}+ loading={!metrics && !metricsError}+ value={usage?.cpuCores}+ limit={cpuLimit}+ format={fmtCores}+ />+ </div>+ <div>+ <Box variant="awsui-key-label">Memory</Box>+ <MetricTile+ error={metricsError}+ loading={!metrics && !metricsError}+ value={usage?.memBytes}+ limit={memLimit}+ format={fmtBytes}+ />+ </div>+ </ColumnLayout>+ </Container>++ <LogsPanel+ namespace={launcher?.metadata.namespace}+ podName={launcher?.metadata.name}+ container={LOG_CONTAINER}+ title="Logs (guest console)"+ waitingText="Waiting for launcher pod…"+ />++ {launcherError && !launcherLoading && !launcher && (+ <Box color="text-status-warning" textAlign="center" padding="m">+ <SpaceBetween size="xs">+ <b>Couldn't find the launcher pod</b>+ <Box variant="small">+ <code>{launcherError}</code>+ </Box>+ </SpaceBetween>+ </Box>+ )}++ <Modal+ visible={confirmingRestart}+ onDismiss={() => { if (!restarting) setConfirmingRestart(false) }}+ header={`Restart ${vmName}?`}+ footer={+ <Box float="right">+ <SpaceBetween direction="horizontal" size="xs">+ <Button+ onClick={() => setConfirmingRestart(false)}+ disabled={restarting}+ >+ Cancel+ </Button>+ <Button+ variant="primary"+ onClick={restart}+ loading={restarting}+ >+ Restart+ </Button>+ </SpaceBetween>+ </Box>+ }+ >+ This will restart replica <b>{vmName}</b> via the KubeVirt subresource+ API (equivalent to <code>virtctl restart {vmName}</code>). The VM's+ current instance will be terminated and a fresh one started from the+ same spec. Any in-progress session on this replica will be interrupted.+ </Modal>+ </SpaceBetween>+ )+}++// ── Metric tile ────────────────────────────────────────────────────────────++function MetricTile({+ loading,+ error,+ value,+ limit,+ format,+}: {+ loading: boolean+ error: string | null+ value: number | undefined+ limit: number | null+ format: (n: number) => string+}) {+ if (loading) {+ return (+ <Box textAlign="center" padding="m">+ <Spinner /> Loading metrics…+ </Box>+ )+ }+ if (error) {+ return (+ <Box color="text-body-secondary" padding="m">+ <StatusIndicator type="warning">{error}</StatusIndicator>+ </Box>+ )+ }+ if (value === undefined) return null+ const denom = limit ?? 0+ const pct = denom > 0 ? Math.min(100, (value / denom) * 100) : 0+ return (+ <SpaceBetween size="xs">+ <Box variant="h2" fontSize="display-l">+ {format(value)}+ </Box>+ {limit ? (+ <ProgressBar+ value={pct}+ additionalInfo={`${format(value)} of ${format(denom)}`}+ />+ ) : (+ <Box variant="small" color="text-body-secondary">+ No limit configured.+ </Box>+ )}+ </SpaceBetween>+ )+}++function fmtCores(n: number): string {+ return `${n.toFixed(2)} cores`+}++function fmtBytes(n: number): string {+ if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GiB`+ if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MiB`+ if (n >= 1024) return `${(n / 1024).toFixed(0)} KiB`+ return `${n} B`+}diff --git a/libs/fleet/src/pages/PoolsList.tsx b/libs/fleet/src/pages/PoolsList.tsxnew file mode 100644index 0000000000..a2b5a6f6a2--- /dev/null+++ b/libs/fleet/src/pages/PoolsList.tsx@@ -0,0 +1,247 @@+import { useEffect, useState } from "react"+import { useNavigate } from "react-router-dom"+import { useCollection } from "@cloudscape-design/collection-hooks"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import Header from "@cloudscape-design/components/header"+import Link from "@cloudscape-design/components/link"+import Pagination from "@cloudscape-design/components/pagination"+import PropertyFilter from "@cloudscape-design/components/property-filter"+import SpaceBetween from "@cloudscape-design/components/space-between"+import Table from "@cloudscape-design/components/table"+import { api } from "../api/cyclops"+import {+ derivePoolStatus,+ reconcileTombstones,+ tombstonePool,+} from "../api/pools"+import { PoolStatusPill } from "../components/PoolStatus"+import { useFlash } from "../components/FlashContext"++interface PoolRow {+ name: string+ namespace: string+ replicas: number+ phase: string+ availableCount: number+ statusText: string+}++export function PoolsList() {+ const navigate = useNavigate()+ const flash = useFlash()+ const [rows, setRows] = useState<PoolRow[]>([])+ const [loading, setLoading] = useState(true)+ const [selected, setSelected] = useState<PoolRow[]>([])+ const [busy, setBusy] = useState(false)+ const [duplicating, setDuplicating] = useState(false)++ const load = async () => {+ setLoading(true)+ try {+ const poolList = await api.listPools()+ reconcileTombstones(poolList.map(p => p.name))+ setRows(+ poolList.map(p => ({+ ...p,+ statusText: derivePoolStatus(p).kind,+ })),+ )+ } catch (e) {+ flash.push({+ type: "error",+ header: "Failed to list pools",+ content: String((e as Error).message),+ })+ } finally {+ setLoading(false)+ }+ }+ useEffect(() => {+ load()+ }, [])++ const removeSelected = async () => {+ if (selected.length === 0) return+ setBusy(true)+ try {+ await Promise.all(selected.map(p => api.deletePool(p.namespace, p.name)))+ for (const p of selected) tombstonePool(p.name)+ flash.push({+ type: "success",+ header: `Deleted ${selected.length} pool${selected.length > 1 ? "s" : ""}`,+ })+ setSelected([])+ await load()+ } catch (e) {+ flash.push({+ type: "error",+ header: "Delete failed",+ content: String((e as Error).message),+ })+ } finally {+ setBusy(false)+ }+ }++ // A list row only carries summary fields (name/replicas/phase/available),+ // so fetch the full pool spec (cpu/ram/image/services) before navigating —+ // otherwise the New pool form falls back to defaults. Mirrors the Duplicate+ // action on the pool detail page, which passes the full getPool result.+ const duplicate = async () => {+ const src = selected[0]+ if (!src) return+ setDuplicating(true)+ try {+ const full = await api.getPool(src.namespace, src.name)+ navigate("/pools/new", { state: { source: full } })+ } catch (e) {+ flash.push({+ type: "error",+ header: "Failed to load pool for duplication",+ content: String((e as Error).message),+ })+ } finally {+ setDuplicating(false)+ }+ }++ const {+ items,+ collectionProps,+ propertyFilterProps,+ filteredItemsCount,+ paginationProps,+ actions,+ } = useCollection(rows, {+ propertyFiltering: {+ filteringProperties: [+ { key: "name", propertyLabel: "Name", groupValuesLabel: "Name values", operators: [":", "!:", "=", "!=", "^"] },+ { key: "replicas", propertyLabel: "Replicas", groupValuesLabel: "Replica counts", operators: ["=", "!=", "<", "<=", ">", ">="] },+ { key: "statusText", propertyLabel: "Status", groupValuesLabel: "Status values", operators: ["=", "!="] },+ ],+ empty: (+ <Box textAlign="center" padding="m">+ <SpaceBetween size="xs">+ <b>No pools</b>+ <Box variant="p" color="text-body-secondary">+ Create one to get started.+ </Box>+ <Button onClick={() => navigate("/pools/new")}>New pool</Button>+ </SpaceBetween>+ </Box>+ ),+ noMatch: (+ <Box textAlign="center" color="text-body-secondary" padding="m">+ <SpaceBetween size="xs">+ <b>No matches</b>+ <Button onClick={() => actions.setPropertyFiltering({ tokens: [], operation: "and" })}>+ Clear filter+ </Button>+ </SpaceBetween>+ </Box>+ ),+ },+ pagination: { pageSize: 25 },+ sorting: {},+ })++ return (+ <Table+ {...collectionProps}+ header={+ <Header+ variant="h1"+ counter={loading ? undefined : `(${rows.length})`}+ actions={+ <SpaceBetween direction="horizontal" size="xs">+ <Button iconName="refresh" onClick={load} disabled={loading} />+ <Button+ disabled={selected.length !== 1 || duplicating}+ loading={duplicating}+ onClick={duplicate}+ >+ Duplicate+ </Button>+ <Button+ disabled={selected.length === 0 || busy}+ loading={busy}+ onClick={removeSelected}+ >+ Delete+ </Button>+ <Button+ variant="primary"+ onClick={() => navigate("/pools/new")}+ >+ New pool+ </Button>+ </SpaceBetween>+ }+ >+ Pools+ </Header>+ }+ items={items}+ loading={loading}+ loadingText="Loading pools"+ selectionType="multi"+ trackBy={(p) => `${p.namespace}/${p.name}`}+ selectedItems={selected}+ onSelectionChange={({ detail }) => setSelected(detail.selectedItems)}+ filter={+ <PropertyFilter+ {...propertyFilterProps}+ countText={`${filteredItemsCount} match${filteredItemsCount === 1 ? "" : "es"}`}+ i18nStrings={{+ filteringAriaLabel: "Filter pools",+ filteringPlaceholder: "Filter pools by property",+ operationAndText: "and",+ operationOrText: "or",+ clearFiltersText: "Clear filters",+ applyActionText: "Apply",+ cancelActionText: "Cancel",+ }}+ />+ }+ pagination={<Pagination {...paginationProps} />}+ columnDefinitions={[+ {+ id: "name",+ header: "Name",+ cell: p => (+ <Link+ href={`#/pools/${p.namespace}/${p.name}`}+ onFollow={e => {+ e.preventDefault()+ navigate(`/pools/${p.namespace}/${p.name}`)+ }}+ >+ {p.name}+ </Link>+ ),+ sortingField: "name",+ isRowHeader: true,+ },+ {+ id: "replicas",+ header: "Replicas",+ cell: p => p.replicas,+ sortingField: "replicas",+ },+ {+ id: "available",+ header: "Available",+ cell: p => p.availableCount,+ sortingField: "availableCount",+ },+ {+ id: "status",+ header: "Status",+ cell: p => <PoolStatusPill status={derivePoolStatus(p)} />,+ sortingField: "statusText",+ },+ ]}+ />+ )+}diff --git a/libs/fleet/src/pages/Settings.tsx b/libs/fleet/src/pages/Settings.tsxnew file mode 100644index 0000000000..e49cb2f68e--- /dev/null+++ b/libs/fleet/src/pages/Settings.tsx@@ -0,0 +1,51 @@+// Settings page — shows the signed-in user's identity (username and+// subject) read from the Keycloak token, with copy-to-clipboard for each.++import Box from "@cloudscape-design/components/box"+import Container from "@cloudscape-design/components/container"+import CopyToClipboard from "@cloudscape-design/components/copy-to-clipboard"+import FormField from "@cloudscape-design/components/form-field"+import Header from "@cloudscape-design/components/header"+import SpaceBetween from "@cloudscape-design/components/space-between"+import { userInfo } from "../auth/keycloak"++export function Settings() {+ const { sub, name } = userInfo()++ return (+ <SpaceBetween size="l">+ <Container header={<Header variant="h2">Account</Header>}>+ <SpaceBetween size="m">+ <FormField label="Username">+ {name ? (+ <CopyToClipboard+ variant="inline"+ textToCopy={name}+ textToDisplay={<code>{name}</code>}+ copyButtonAriaLabel="Copy username"+ copySuccessText="Username copied"+ copyErrorText="Failed to copy username"+ />+ ) : (+ <Box color="text-status-inactive">Unknown</Box>+ )}+ </FormField>+ <FormField label="Subject (sub)">+ {sub ? (+ <CopyToClipboard+ variant="inline"+ textToCopy={sub}+ textToDisplay={<code>{sub}</code>}+ copyButtonAriaLabel="Copy subject"+ copySuccessText="Subject copied"+ copyErrorText="Failed to copy subject"+ />+ ) : (+ <Box color="text-status-inactive">Unknown</Box>+ )}+ </FormField>+ </SpaceBetween>+ </Container>+ </SpaceBetween>+ )+}diff --git a/libs/fleet/src/pages/UserApiKeys.tsx b/libs/fleet/src/pages/UserApiKeys.tsxnew file mode 100644index 0000000000..4a2a6d8f7b--- /dev/null+++ b/libs/fleet/src/pages/UserApiKeys.tsx@@ -0,0 +1,243 @@+// Per-user API key management.+//+// Lists the calling user's personal API keys, lets them create new ones+// (showing the credentials exactly once), and revoke existing keys.+// Each key is a Keycloak service-account client; the client_secret is+// returned once on creation and cannot be retrieved later.++import { useEffect, useState } from "react"+import Alert from "@cloudscape-design/components/alert"+import Box from "@cloudscape-design/components/box"+import Button from "@cloudscape-design/components/button"+import Container from "@cloudscape-design/components/container"+import CopyToClipboard from "@cloudscape-design/components/copy-to-clipboard"+import Form from "@cloudscape-design/components/form"+import FormField from "@cloudscape-design/components/form-field"+import Header from "@cloudscape-design/components/header"+import Input from "@cloudscape-design/components/input"+import Modal from "@cloudscape-design/components/modal"+import Multiselect, {+ type MultiselectProps,+} from "@cloudscape-design/components/multiselect"+import SpaceBetween from "@cloudscape-design/components/space-between"+import Table from "@cloudscape-design/components/table"+import {+ type UserApiKey,+ type NewUserApiKey,+ userKeysApi,+ namespacesApi,+} from "../api/cyclops"++export function UserApiKeys() {+ const [keys, setKeys] = useState<UserApiKey[]>([])+ const [loading, setLoading] = useState(true)+ const [error, setError] = useState<string | null>(null)+ const [name, setName] = useState("")+ const [selectedScope, setSelectedScope] = useState<+ MultiselectProps.Option[]+ >([])+ const [nsOptions, setNsOptions] = useState<MultiselectProps.Option[]>([])+ const [creating, setCreating] = useState(false)+ const [created, setCreated] = useState<NewUserApiKey | null>(null)+ const [confirmRevoke, setConfirmRevoke] = useState<string | null>(null)++ const refresh = async () => {+ setLoading(true)+ try {+ const [userKeys, namespaces] = await Promise.all([+ userKeysApi.list(),+ namespacesApi.list().catch(() => []),+ ])+ setKeys(userKeys)+ setNsOptions(+ namespaces.map(ns => ({+ label: ns.name,+ value: ns.name,+ })),+ )+ setError(null)+ } catch (e) {+ setError(String(e))+ } finally {+ setLoading(false)+ }+ }++ useEffect(() => {+ refresh()+ }, [])++ const create = async () => {+ setCreating(true)+ try {+ const scope = selectedScope.map(o => o.value!).filter(Boolean)+ const k = await userKeysApi.create(+ name,+ scope.length > 0 ? scope : undefined,+ )+ setCreated(k)+ setName("")+ setSelectedScope([])+ await refresh()+ } catch (e) {+ setError(String(e))+ } finally {+ setCreating(false)+ }+ }++ const remove = async (id: string) => {+ try {+ await userKeysApi.remove(id)+ setConfirmRevoke(null)+ await refresh()+ } catch (e) {+ setError(String(e))+ }+ }++ return (+ <SpaceBetween size="l">+ {error && (+ <Alert type="error" dismissible onDismiss={() => setError(null)}>+ {error}+ </Alert>+ )}++ <Container header={<Header variant="h2">Create a new API key</Header>}>+ <Form+ actions={+ <Button+ variant="primary"+ loading={creating}+ disabled={!name}+ onClick={create}+ >+ Create key+ </Button>+ }+ >+ <SpaceBetween size="m">+ <FormField label="Name" description="A label to identify this key">+ <Input value={name} onChange={e => setName(e.detail.value)} />+ </FormField>+ <FormField+ label="Scope (optional)"+ description="Restrict this key to specific namespaces. Leave empty for full access."+ >+ <Multiselect+ selectedOptions={selectedScope}+ onChange={e =>+ setSelectedScope([...e.detail.selectedOptions])+ }+ options={nsOptions}+ placeholder="All namespaces (no restriction)"+ loadingText="Loading namespaces..."+ statusType={loading ? "loading" : "finished"}+ empty="No namespaces found"+ />+ </FormField>+ </SpaceBetween>+ </Form>+ </Container>++ <Table+ loading={loading}+ items={keys}+ columnDefinitions={[+ { id: "name", header: "Name", cell: r => r.name },+ { id: "client_id", header: "Client ID", cell: r => <code>{r.client_id}</code> },+ {+ id: "scope",+ header: "Scope",+ cell: r =>+ r.scope && r.scope.length > 0+ ? r.scope.join(", ")+ : "All namespaces",+ },+ {+ id: "actions",+ header: "",+ cell: r => (+ <Button onClick={() => setConfirmRevoke(r.id)}>Revoke</Button>+ ),+ },+ ]}+ empty={<Box textAlign="center">No API keys yet.</Box>}+ header={<Header variant="h2">Your API keys</Header>}+ />++ {/* Key-created modal -- shows credentials once */}+ {created && (+ <Modal+ visible+ header="API key created"+ onDismiss={() => setCreated(null)}+ footer={+ <Box float="right">+ <Button variant="primary" onClick={() => setCreated(null)}>+ I have copied the credentials+ </Button>+ </Box>+ }+ >+ <SpaceBetween size="m">+ <Alert type="warning">+ These credentials will only be shown <b>once</b>. Copy them now+ -- they cannot be retrieved later.+ </Alert>+ <Container>+ <SpaceBetween size="m">+ <FormField label="Client ID">+ <CopyToClipboard+ variant="inline"+ textToCopy={created.client_id}+ textToDisplay={<code>{created.client_id}</code>}+ copyButtonAriaLabel="Copy client ID"+ copySuccessText="Client ID copied"+ copyErrorText="Failed to copy"+ />+ </FormField>+ <FormField label="Client Secret">+ <CopyToClipboard+ variant="inline"+ textToCopy={created.client_secret}+ textToDisplay={<code>{created.client_secret}</code>}+ copyButtonAriaLabel="Copy client secret"+ copySuccessText="Client secret copied"+ copyErrorText="Failed to copy"+ />+ </FormField>+ </SpaceBetween>+ </Container>+ </SpaceBetween>+ </Modal>+ )}++ {/* Revoke confirmation modal */}+ {confirmRevoke && (+ <Modal+ visible+ header="Revoke API key?"+ onDismiss={() => setConfirmRevoke(null)}+ footer={+ <Box float="right">+ <SpaceBetween direction="horizontal" size="xs">+ <Button onClick={() => setConfirmRevoke(null)}>Cancel</Button>+ <Button+ variant="primary"+ onClick={() => remove(confirmRevoke)}+ >+ Revoke+ </Button>+ </SpaceBetween>+ </Box>+ }+ >+ This action cannot be undone. Any systems using this key will lose+ access immediately.+ </Modal>+ )}+ </SpaceBetween>+ )+}diff --git a/libs/fleet/src/types/novnc.d.ts b/libs/fleet/src/types/novnc.d.tsnew file mode 100644index 0000000000..b879ba64fa--- /dev/null+++ b/libs/fleet/src/types/novnc.d.ts@@ -0,0 +1,24 @@+/**+ * Minimal type shim for @novnc/novnc's ESM RFB entrypoint (the package ships no+ * .d.ts for the deep `core/rfb.js` import). Declares only the surface DesktopPane+ * uses. See https://github.com/novnc/noVNC for the full API.+ */+declare module "@novnc/novnc" {+ export default class RFB extends EventTarget {+ constructor(+ target: HTMLElement,+ url: string,+ options?: {+ credentials?: { username?: string; password?: string; target?: string }+ shared?: boolean+ repeaterID?: string+ wsProtocols?: string[]+ },+ )+ viewOnly: boolean+ scaleViewport: boolean+ resizeSession: boolean+ background: string+ disconnect(): void+ }+}diff --git a/libs/fleet/terraform-provider-cyclops/README.md b/libs/fleet/terraform-provider-cyclops/README.mdnew file mode 100644index 0000000000..fb4fe73081--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/README.md@@ -0,0 +1,43 @@+# Terraform Provider for Cyclops++This provider manages `OSGymWorkspacePool` resources through the Cyclops API. It uses the same user-key OAuth credentials and tenant-scoped authorization as the Cyclops Python SDK and dashboard.++## Development++```bash+go test ./...+go build ./...++# Real Terraform protocol + kube-apiserver/CRD acceptance test+KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/[email protected] use 1.31.0 -p path)" \+ TF_ACC=1 go test -tags=acceptance ./internal/provider -run TestAccPoolLifecycle -v+```++The provider source address is `trycua/cyclops`. A pool owns the same-named Cyclops namespace: create bootstraps the namespace, and destroy deletes the pool followed by that namespace.++## Authentication++Create a user API key in Cyclops and configure its returned `client_id`, `client_secret`, and `token_url`. For short-lived workflows, `access_token` can be supplied instead.++All provider arguments support environment variables:++- `CYCLOPS_ENDPOINT`+- `CYCLOPS_ACCESS_TOKEN`+- `CYCLOPS_CLIENT_ID`+- `CYCLOPS_CLIENT_SECRET`+- `CYCLOPS_TOKEN_URL`++## Pool resource generation++The Terraform models, schema, CRD-derived descriptions, enum validators, numeric validators, and nested object types are generated deterministically from:++- `clusters/base/osgym/crd.yaml`, the production `OSGymWorkspacePool` CRD+- `internal/provider/generate/pool_mapping.json`, the explicit CRD-to-Terraform shape mapping++From `cyclops-cs/terraform-provider-cyclops/`, run:++```bash+go generate ./...+```++`internal/provider/pool_generated.go` is committed. CI regenerates it and fails on drift. CRUD, namespace ownership, import behavior, default normalization, and API error handling remain handwritten in `internal/provider/pool_resource.go`.diff --git a/libs/fleet/terraform-provider-cyclops/cmd/generate-pool-resource/main.go b/libs/fleet/terraform-provider-cyclops/cmd/generate-pool-resource/main.gonew file mode 100644index 0000000000..73da3b8014--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/cmd/generate-pool-resource/main.go@@ -0,0 +1,434 @@+package main++import (+ "bytes"+ "encoding/json"+ "flag"+ "fmt"+ "go/format"+ "io"+ "os"+ "sort"+ "strconv"+ "strings"++ yamlv3 "gopkg.in/yaml.v3"+)++type field struct {+ Name string `json:"name"`+ GoName string `json:"go_name"`+ ValueType string `json:"value_type"`+ Mode string `json:"mode"`+ CRDPath string `json:"crd_path"`+ Description string `json:"description"`+ DNSLabel bool `json:"dns_label"`+ RequiresReplace bool `json:"requires_replace"`+ Minimum *int64 `json:"minimum"`+ Maximum *int64 `json:"maximum"`+}++type block struct {+ Name string `json:"name"`+ GoName string `json:"go_name"`+ Model string `json:"model"`+ Collection string `json:"collection"`+ CRDPath string `json:"crd_path"`+ Fields []field `json:"fields"`+}++type mapping struct {+ ResourceDescription string `json:"resource_description"`+ Attributes []field `json:"attributes"`+ Blocks []block `json:"blocks"`+}++type schemaInfo struct {+ Type string+ Description string+ Enum []string+ Minimum *int64+ Maximum *int64+}++func main() {+ crdPath := flag.String("crd", "", "path to the OSGymWorkspacePool CRD")+ mappingPath := flag.String("mapping", "", "path to the Terraform mapping JSON")+ outputPath := flag.String("out", "", "generated Go output path")+ flag.Parse()+ if *crdPath == "" || *mappingPath == "" || *outputPath == "" {+ fatalf("-crd, -mapping, and -out are required")+ }++ var config mapping+ readJSON(*mappingPath, &config)+ root := readCRDSchema(*crdPath)+ validateMapping(root, config)++ generated, err := format.Source(render(root, config))+ if err != nil {+ fatalf("format generated source: %v\n%s", err, render(root, config))+ }+ if err := os.WriteFile(*outputPath, generated, 0o644); err != nil {+ fatalf("write generated source: %v", err)+ }+}++func readJSON(path string, target any) {+ data, err := os.ReadFile(path)+ if err != nil {+ fatalf("read %s: %v", path, err)+ }+ if err := json.Unmarshal(data, target); err != nil {+ fatalf("decode %s: %v", path, err)+ }+}++func readCRDSchema(path string) map[string]any {+ data, err := os.ReadFile(path)+ if err != nil {+ fatalf("read CRD: %v", err)+ }+ decoder := yamlv3.NewDecoder(bytes.NewReader(data))+ for {+ var document map[string]any+ if err := decoder.Decode(&document); err != nil {+ if err == io.EOF {+ break+ }+ fatalf("decode CRD: %v", err)+ }+ metadata, _ := document["metadata"].(map[string]any)+ if metadata["name"] != "osgymworkspacepools.cua.ai" {+ continue+ }+ versions := mustSlice(mustMap(document["spec"], "spec")["versions"], "spec.versions")+ for _, rawVersion := range versions {+ version := mustMap(rawVersion, "version")+ if version["name"] == "v1" {+ return mustMap(mustMap(version["schema"], "schema")["openAPIV3Schema"], "openAPIV3Schema")+ }+ }+ }+ fatalf("OSGymWorkspacePool CRD has no v1 schema")+ return nil+}++func validateMapping(root map[string]any, config mapping) {+ seenNames := map[string]bool{}+ seenGoNames := map[string]bool{}+ registerTopLevel := func(name, goName string) {+ if seenNames[name] {+ fatalf("duplicate top-level Terraform name %q", name)+ }+ seenNames[name] = true+ if seenGoNames[goName] {+ fatalf("duplicate top-level Go name %q", goName)+ }+ seenGoNames[goName] = true+ }++ for _, item := range config.Attributes {+ validateFieldConfig(item)+ registerTopLevel(item.Name, item.GoName)+ validateField(root, item, item.CRDPath)+ }+ for _, item := range config.Blocks {+ registerTopLevel(item.Name, item.GoName)+ if item.Collection != "single" && item.Collection != "set" {+ fatalf("block %q has unsupported collection %q", item.Name, item.Collection)+ }++ blockSchema := lookup(root, item.CRDPath)+ expectedType := "object"+ if item.Collection == "set" {+ expectedType = "array"+ }+ if actual, _ := blockSchema["type"].(string); actual != expectedType {+ fatalf("block %s maps to CRD type %q, expected %q", item.Name, actual, expectedType)+ }+ if item.Collection == "set" {+ blockSchema = mustMap(blockSchema["items"], item.CRDPath+".items")+ }++ seenNestedNames := map[string]bool{}+ seenNestedGoNames := map[string]bool{}+ for _, nested := range item.Fields {+ validateFieldConfig(nested)+ if seenNestedNames[nested.Name] {+ fatalf("duplicate Terraform field %q in block %q", nested.Name, item.Name)+ }+ seenNestedNames[nested.Name] = true+ if seenNestedGoNames[nested.GoName] {+ fatalf("duplicate Go field %q in block %q", nested.GoName, item.Name)+ }+ seenNestedGoNames[nested.GoName] = true+ validateField(blockSchema, nested, nested.CRDPath)+ }+ }+}++func validateFieldConfig(item field) {+ switch item.ValueType {+ case "string", "int64", "normalized_json":+ default:+ fatalf("field %q has unsupported value_type %q", item.Name, item.ValueType)+ }+ switch item.Mode {+ case "required", "optional", "computed", "optional_computed":+ default:+ fatalf("field %q has unsupported mode %q", item.Name, item.Mode)+ }+ if item.RequiresReplace && item.ValueType != "string" {+ fatalf("field %q sets requires_replace with value_type %q", item.Name, item.ValueType)+ }+}++func validateField(root map[string]any, item field, path string) {+ if path == "" {+ return+ }+ info := inspect(lookup(root, path))+ expectedType := baseType(item.ValueType)+ if expectedType == "int64" {+ expectedType = "integer"+ }+ if item.ValueType == "normalized_json" {+ expectedType = "object"+ }+ if info.Type != expectedType {+ fatalf("field %s maps to CRD type %q, expected %q", item.Name, info.Type, expectedType)+ }+}++func render(root map[string]any, config mapping) []byte {+ var out bytes.Buffer+ out.WriteString("// Code generated by cmd/generate-pool-resource; DO NOT EDIT.\n\n")+ out.WriteString("package provider\n\n")+ out.WriteString("import (\n\t\"regexp\"\n\n")+ out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework-jsontypes/jsontypes\"\n")+ out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework-validators/int64validator\"\n")+ out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator\"\n")+ out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/attr\"\n")+ out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema\"\n")+ out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier\"\n")+ out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier\"\n")+ out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/schema/validator\"\n")+ out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/types\"\n")+ out.WriteString(")\n\n")++ renderModel(&out, "poolResourceModel", config.Attributes, config.Blocks)+ for _, item := range config.Blocks {+ renderModel(&out, item.Model, item.Fields, nil)+ }++ fmt.Fprintf(&out, "func poolResourceSchema() schema.Schema {\n\treturn schema.Schema{Description: %s,\n", strconv.Quote(config.ResourceDescription))+ out.WriteString("\t\tAttributes: map[string]schema.Attribute{\n")+ for _, item := range config.Attributes {+ renderAttribute(&out, root, item, item.CRDPath, "\t\t\t")+ }+ out.WriteString("\t\t},\n\t\tBlocks: map[string]schema.Block{\n")+ for _, item := range config.Blocks {+ blockSchema := lookup(root, item.CRDPath)+ if item.Collection == "set" {+ blockSchema = mustMap(blockSchema["items"], item.CRDPath+".items")+ }+ fmt.Fprintf(&out, "\t\t\t%q: schema.%sNestedBlock{", item.Name, title(item.Collection))+ if item.Collection == "set" {+ out.WriteString("NestedObject: schema.NestedBlockObject{")+ }+ out.WriteString("Attributes: map[string]schema.Attribute{\n")+ for _, nested := range item.Fields {+ renderAttribute(&out, blockSchema, nested, nested.CRDPath, "\t\t\t\t")+ }+ if item.Collection == "set" {+ out.WriteString("\t\t\t}}},\n")+ } else {+ out.WriteString("\t\t\t}},\n")+ }+ }+ out.WriteString("\t\t},\n\t}\n}\n\n")++ for _, item := range config.Blocks {+ fmt.Fprintf(&out, "func %sObjectType() map[string]attr.Type {\n\treturn map[string]attr.Type{", item.Name)+ for index, nested := range item.Fields {+ if index > 0 {+ out.WriteString(", ")+ }+ fmt.Fprintf(&out, "%q: %s", nested.Name, attrType(nested.ValueType))+ }+ out.WriteString("}\n}\n\n")+ }+ out.WriteString("var dnsLabelRegex = regexp.MustCompile(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$`)\n")+ return out.Bytes()+}++func renderModel(out *bytes.Buffer, name string, fields []field, blocks []block) {+ fmt.Fprintf(out, "type %s struct {\n", name)+ for _, item := range fields {+ fmt.Fprintf(out, "\t%s %s `tfsdk:%q`\n", item.GoName, modelType(item.ValueType), item.Name)+ }+ for _, item := range blocks {+ valueType := "types.Object"+ if item.Collection == "set" {+ valueType = "types.Set"+ }+ fmt.Fprintf(out, "\t%s %s `tfsdk:%q`\n", item.GoName, valueType, item.Name)+ }+ out.WriteString("}\n\n")+}++func renderAttribute(out *bytes.Buffer, root map[string]any, item field, path, indent string) {+ info := schemaInfo{}+ if path != "" {+ info = inspect(lookup(root, path))+ }+ if item.Minimum != nil {+ info.Minimum = item.Minimum+ }+ if item.Maximum != nil {+ info.Maximum = item.Maximum+ }+ description := item.Description+ if description == "" {+ description = info.Description+ }+ fmt.Fprintf(out, "%s%q: schema.%sAttribute{", indent, item.Name, attributeType(item.ValueType))+ switch item.Mode {+ case "required":+ out.WriteString("Required: true")+ case "optional":+ out.WriteString("Optional: true")+ case "computed":+ out.WriteString("Computed: true")+ case "optional_computed":+ out.WriteString("Optional: true, Computed: true")+ default:+ fatalf("unsupported mode %q", item.Mode)+ }+ if item.ValueType == "normalized_json" {+ out.WriteString(", CustomType: jsontypes.NormalizedType{}")+ }+ if description != "" {+ fmt.Fprintf(out, ", Description: %s", strconv.Quote(strings.TrimSpace(description)))+ }+ validators := validatorsFor(item, info)+ if len(validators) > 0 {+ fmt.Fprintf(out, ", Validators: []validator.%s{%s}", title(baseType(item.ValueType)), strings.Join(validators, ", "))+ }+ if item.RequiresReplace {+ out.WriteString(", PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()}")+ }+ out.WriteString("},\n")+}++func validatorsFor(item field, info schemaInfo) []string {+ var result []string+ if item.DNSLabel {+ result = append(result, "stringvalidator.LengthBetween(1, 63)", "stringvalidator.RegexMatches(dnsLabelRegex, \"must be a lowercase DNS label\")")+ }+ if len(info.Enum) > 0 {+ quoted := make([]string, len(info.Enum))+ for index, value := range info.Enum {+ quoted[index] = strconv.Quote(value)+ }+ result = append(result, "stringvalidator.OneOf("+strings.Join(quoted, ", ")+")")+ }+ if info.Minimum != nil && item.ValueType == "int64" {+ if info.Maximum != nil {+ result = append(result, fmt.Sprintf("int64validator.Between(%d, %d)", *info.Minimum, *info.Maximum))+ } else {+ result = append(result, fmt.Sprintf("int64validator.AtLeast(%d)", *info.Minimum))+ }+ }+ return result+}++func lookup(root map[string]any, path string) map[string]any {+ current := root+ for _, part := range strings.Split(path, ".") {+ properties := mustMap(current["properties"], path+".properties")+ current = mustMap(properties[part], path)+ }+ return current+}++func inspect(value map[string]any) schemaInfo {+ info := schemaInfo{}+ if valueType, ok := value["type"].(string); ok {+ info.Type = valueType+ }+ if description, ok := value["description"].(string); ok {+ info.Description = description+ }+ if rawEnum, ok := value["enum"].([]any); ok {+ for _, item := range rawEnum {+ info.Enum = append(info.Enum, fmt.Sprint(item))+ }+ sort.Strings(info.Enum)+ }+ info.Minimum = integerPointer(value["minimum"])+ info.Maximum = integerPointer(value["maximum"])+ return info+}++func integerPointer(value any) *int64 {+ switch typed := value.(type) {+ case float64:+ result := int64(typed)+ return &result+ case int:+ result := int64(typed)+ return &result+ case int64:+ return &typed+ default:+ return nil+ }+}++func modelType(valueType string) string {+ if valueType == "normalized_json" {+ return "jsontypes.Normalized"+ }+ return "types." + title(valueType)+}++func attrType(valueType string) string {+ if valueType == "int64" {+ return "types.Int64Type"+ }+ return "types.StringType"+}++func attributeType(valueType string) string { return title(baseType(valueType)) }+func baseType(valueType string) string {+ if valueType == "normalized_json" {+ return "string"+ }+ return valueType+}+func title(value string) string {+ if value == "int64" {+ return "Int64"+ }+ return strings.ToUpper(value[:1]) + value[1:]+}+func mustMap(value any, name string) map[string]any {+ result, ok := value.(map[string]any)+ if !ok {+ fatalf("%s is not an object", name)+ }+ return result+}+func mustSlice(value any, name string) []any {+ result, ok := value.([]any)+ if !ok {+ fatalf("%s is not an array", name)+ }+ return result+}+func fatalf(format string, args ...any) {+ fmt.Fprintf(os.Stderr, format+"\n", args...)+ os.Exit(1)+}diff --git a/libs/fleet/terraform-provider-cyclops/cmd/generate-pool-resource/main_test.go b/libs/fleet/terraform-provider-cyclops/cmd/generate-pool-resource/main_test.gonew file mode 100644index 0000000000..b7a64bfa80--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/cmd/generate-pool-resource/main_test.go@@ -0,0 +1,139 @@+package main++import (+ "bytes"+ "os"+ "os/exec"+ "strings"+ "testing"+)++func TestValidateMappingAcceptsValidMapping(t *testing.T) {+ stderr, err := runValidationHelper(t, "valid")+ if err != nil {+ t.Fatalf("validateMapping() failed: %v\nstderr:\n%s", err, stderr)+ }+}++func TestValidateMappingRejectsInvalidMapping(t *testing.T) {+ tests := []struct {+ name string+ scenario string+ wantStderr string+ }{+ {name: "unsupported value type", scenario: "unsupported_value_type", wantStderr: `field "name" has unsupported value_type "bool"`},+ {name: "unsupported mode", scenario: "unsupported_mode", wantStderr: `field "name" has unsupported mode "write_only"`},+ {name: "requires replace on non-string", scenario: "requires_replace_int64", wantStderr: `field "replicas" sets requires_replace with value_type "int64"`},+ {name: "unsupported collection", scenario: "unsupported_collection", wantStderr: `block "service" has unsupported collection "list"`},+ {name: "duplicate top-level name", scenario: "duplicate_top_level_name", wantStderr: `duplicate top-level Terraform name "name"`},+ {name: "duplicate top-level Go name", scenario: "duplicate_top_level_go_name", wantStderr: `duplicate top-level Go name "Name"`},+ {name: "duplicate block name", scenario: "duplicate_block_name", wantStderr: `duplicate top-level Terraform name "service"`},+ {name: "duplicate nested name", scenario: "duplicate_nested_name", wantStderr: `duplicate Terraform field "name" in block "service"`},+ {name: "duplicate nested Go name", scenario: "duplicate_nested_go_name", wantStderr: `duplicate Go field "Name" in block "service"`},+ {name: "missing CRD path", scenario: "missing_crd_path", wantStderr: `spec.missing is not an object`},+ {name: "wrong CRD type", scenario: "wrong_crd_type", wantStderr: `field replicas maps to CRD type "string", expected "integer"`},+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ stderr, err := runValidationHelper(t, test.scenario)+ if err == nil {+ t.Fatalf("validateMapping() succeeded, want failure")+ }+ if !strings.Contains(stderr, test.wantStderr) {+ t.Fatalf("stderr = %q, want it to contain %q", stderr, test.wantStderr)+ }+ })+ }+}++func TestRenderIsDeterministic(t *testing.T) {+ root, config := validationFixture("valid")+ first := render(root, config)+ second := render(root, config)+ if !bytes.Equal(first, second) {+ t.Fatal("render() produced different output for identical input")+ }+}++func TestValidationHelperProcess(t *testing.T) {+ scenario := os.Getenv("GO_GENERATOR_VALIDATION_SCENARIO")+ if scenario == "" {+ return+ }+ root, config := validationFixture(scenario)+ validateMapping(root, config)+}++func runValidationHelper(t *testing.T, scenario string) (string, error) {+ t.Helper()+ command := exec.Command(os.Args[0], "-test.run=^TestValidationHelperProcess$")+ command.Env = append(os.Environ(), "GO_GENERATOR_VALIDATION_SCENARIO="+scenario)+ output, err := command.CombinedOutput()+ return string(output), err+}++func validationFixture(scenario string) (map[string]any, mapping) {+ root := map[string]any{+ "properties": map[string]any{+ "spec": map[string]any{+ "type": "object",+ "properties": map[string]any{+ "replicas": map[string]any{"type": "integer"},+ "services": map[string]any{+ "type": "array",+ "items": map[string]any{+ "type": "object",+ "properties": map[string]any{+ "name": map[string]any{"type": "string"},+ "targetPort": map[string]any{"type": "integer"},+ },+ },+ },+ },+ },+ },+ }+ config := mapping{+ Attributes: []field{+ {Name: "name", GoName: "Name", ValueType: "string", Mode: "required", RequiresReplace: true},+ {Name: "replicas", GoName: "Replicas", ValueType: "int64", Mode: "required", CRDPath: "spec.replicas"},+ },+ Blocks: []block{{+ Name: "service", GoName: "Services", Model: "serviceModel", Collection: "set", CRDPath: "spec.services",+ Fields: []field{{Name: "name", GoName: "Name", ValueType: "string", Mode: "required", CRDPath: "name"}},+ }},+ }++ switch scenario {+ case "valid":+ case "unsupported_value_type":+ config.Attributes[0].ValueType = "bool"+ case "unsupported_mode":+ config.Attributes[0].Mode = "write_only"+ case "requires_replace_int64":+ config.Attributes[1].RequiresReplace = true+ case "unsupported_collection":+ config.Blocks[0].Collection = "list"+ case "duplicate_top_level_name":+ config.Blocks[0].Name = "name"+ case "duplicate_top_level_go_name":+ config.Blocks[0].GoName = "Name"+ case "duplicate_block_name":+ duplicate := config.Blocks[0]+ duplicate.GoName = "OtherServices"+ duplicate.Model = "otherServiceModel"+ config.Blocks = append(config.Blocks, duplicate)+ case "duplicate_nested_name":+ config.Blocks[0].Fields = append(config.Blocks[0].Fields, field{Name: "name", GoName: "OtherName", ValueType: "string", Mode: "required", CRDPath: "name"})+ case "duplicate_nested_go_name":+ config.Blocks[0].Fields = append(config.Blocks[0].Fields, field{Name: "target_port", GoName: "Name", ValueType: "int64", Mode: "required", CRDPath: "targetPort"})+ case "missing_crd_path":+ config.Attributes[1].CRDPath = "spec.missing"+ case "wrong_crd_type":+ root["properties"].(map[string]any)["spec"].(map[string]any)["properties"].(map[string]any)["replicas"].(map[string]any)["type"] = "string"+ default:+ panic("unknown validation scenario: " + scenario)+ }+ return root, config+}diff --git a/libs/fleet/terraform-provider-cyclops/docs/index.md b/libs/fleet/terraform-provider-cyclops/docs/index.mdnew file mode 100644index 0000000000..a85d67ac54--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/docs/index.md@@ -0,0 +1,28 @@+---+page_title: "Provider: Cyclops"+description: |-+ Manage Cyclops computer-use pools with Terraform.+---++# Cyclops Provider++The Cyclops provider creates and manages tenant-scoped computer-use pools through the Cyclops API.++```terraform+terraform {+ required_providers {+ cyclops = {+ source = "trycua/cyclops"+ }+ }+}++provider "cyclops" {+ endpoint = "https://cyclops.example.com"+ client_id = var.cyclops_client_id+ client_secret = var.cyclops_client_secret+ token_url = var.cyclops_token_url+}+```++Use either `access_token`, or all three OAuth user-key fields: `client_id`, `client_secret`, and `token_url`. The corresponding `CYCLOPS_*` environment variables may be used instead.diff --git a/libs/fleet/terraform-provider-cyclops/docs/resources/pool.md b/libs/fleet/terraform-provider-cyclops/docs/resources/pool.mdnew file mode 100644index 0000000000..f2ce799d2d--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/docs/resources/pool.md@@ -0,0 +1,55 @@+---+page_title: "cyclops_pool Resource - Cyclops"+description: |-+ Creates a Cyclops computer-use pool.+---++# cyclops_pool++Creates an `OSGymWorkspacePool` and its same-named namespace. Destroy removes both. Import IDs are pool names.++```terraform+resource "cyclops_pool" "linux" {+ name = "training-linux"+ replicas = 3+ cpu_cores = 4+ memory = "8Gi"+ container_disk_image = "296062593712.dkr.ecr.us-west-2.amazonaws.com/osgym-workspace:latest"++ autoscaling {+ min_pool_size = 0+ initial_pool_size = 3+ max_pool_size = 20+ }++ service {+ name = "ssh"+ target_port = 22+ protocol = "TCP"+ }+}+```++## Arguments++- `name` - Pool and namespace DNS label. Changing it replaces the resource.+- `replicas` - Desired warm pool size.+- `cpu_cores` - Virtual CPUs per sandbox.+- `memory` - Kubernetes memory quantity per sandbox.+- `container_disk_image` - OCI containerDisk or runtime image.+- `image_pull_secret` - Image pull secret; defaults to `ecr-credentials`.+- `runtime` - `kubevirt`, `macos`, or `gvisor`; defaults to `kubevirt`.+- `firmware` - `bios` or `efi`; defaults to `bios`.+- `readiness_probe_json` / `liveness_probe_json` - Kubernetes probe objects encoded as JSON.+- `service` - Repeatable service with `name`, `target_port`, and optional `protocol`.+- `autoscaling` - Optional claim-driven autoscaling limits.++## Read-only Attributes++`namespace`, `phase`, `total_count`, `available_count`, and `claimed_count` are populated from Cyclops.++## Import++```shell+terraform import cyclops_pool.linux training-linux+```diff --git a/libs/fleet/terraform-provider-cyclops/examples/provider/provider.tf b/libs/fleet/terraform-provider-cyclops/examples/provider/provider.tfnew file mode 100644index 0000000000..f0a903479b--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/examples/provider/provider.tf@@ -0,0 +1,3 @@+provider "cyclops" {+ endpoint = "https://cyclops.example.com"+}diff --git a/libs/fleet/terraform-provider-cyclops/examples/resources/cyclops_pool/resource.tf b/libs/fleet/terraform-provider-cyclops/examples/resources/cyclops_pool/resource.tfnew file mode 100644index 0000000000..ca7fa036e7--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/examples/resources/cyclops_pool/resource.tf@@ -0,0 +1,7 @@+resource "cyclops_pool" "example" {+ name = "example-linux"+ replicas = 1+ cpu_cores = 4+ memory = "8Gi"+ container_disk_image = "296062593712.dkr.ecr.us-west-2.amazonaws.com/osgym-workspace:latest"+}diff --git a/libs/fleet/terraform-provider-cyclops/go.mod b/libs/fleet/terraform-provider-cyclops/go.modnew file mode 100644index 0000000000..5fab5a460d--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/go.mod@@ -0,0 +1,103 @@+module github.com/trycua/terraform-provider-cyclops++go 1.25.8++require (+ github.com/hashicorp/terraform-plugin-framework v1.19.0+ github.com/hashicorp/terraform-plugin-framework-jsontypes v0.2.0+ github.com/hashicorp/terraform-plugin-framework-validators v0.19.0+ github.com/hashicorp/terraform-plugin-go v0.31.0+ github.com/hashicorp/terraform-plugin-testing v1.16.0+ gopkg.in/yaml.v3 v3.0.1+ k8s.io/api v0.31.4+ k8s.io/apimachinery v0.31.4+ k8s.io/client-go v0.31.4+ sigs.k8s.io/controller-runtime v0.19.7+)++require (+ github.com/ProtonMail/go-crypto v1.4.1 // indirect+ github.com/agext/levenshtein v1.2.3 // indirect+ github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect+ github.com/cloudflare/circl v1.6.3 // indirect+ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect+ github.com/emicklei/go-restful/v3 v3.11.0 // indirect+ github.com/evanphx/json-patch/v5 v5.9.0 // indirect+ github.com/fatih/color v1.18.0 // indirect+ github.com/fxamacker/cbor/v2 v2.7.0 // indirect+ github.com/go-logr/logr v1.4.3 // indirect+ github.com/go-openapi/jsonpointer v0.19.6 // indirect+ github.com/go-openapi/jsonreference v0.20.2 // indirect+ github.com/go-openapi/swag v0.22.4 // indirect+ github.com/gogo/protobuf v1.3.2 // indirect+ github.com/golang/protobuf v1.5.4 // indirect+ github.com/google/gnostic-models v0.6.8 // indirect+ github.com/google/go-cmp v0.7.0 // indirect+ github.com/google/gofuzz v1.2.0 // indirect+ github.com/google/uuid v1.6.0 // indirect+ github.com/hashicorp/errwrap v1.1.0 // indirect+ github.com/hashicorp/go-checkpoint v0.5.0 // indirect+ github.com/hashicorp/go-cleanhttp v0.5.2 // indirect+ github.com/hashicorp/go-cty v1.5.0 // indirect+ github.com/hashicorp/go-hclog v1.6.3 // indirect+ github.com/hashicorp/go-multierror v1.1.1 // indirect+ github.com/hashicorp/go-plugin v1.7.0 // indirect+ github.com/hashicorp/go-retryablehttp v0.7.8 // indirect+ github.com/hashicorp/go-uuid v1.0.3 // indirect+ github.com/hashicorp/go-version v1.9.0 // indirect+ github.com/hashicorp/hc-install v0.9.4 // indirect+ github.com/hashicorp/hcl/v2 v2.24.0 // indirect+ github.com/hashicorp/logutils v1.0.0 // indirect+ github.com/hashicorp/terraform-exec v0.25.1 // indirect+ github.com/hashicorp/terraform-json v0.27.2 // indirect+ github.com/hashicorp/terraform-plugin-log v0.10.0 // indirect+ github.com/hashicorp/terraform-plugin-sdk/v2 v2.40.0 // indirect+ github.com/hashicorp/terraform-registry-address v0.4.0 // indirect+ github.com/hashicorp/terraform-svchost v0.2.1 // indirect+ github.com/hashicorp/yamux v0.1.2 // indirect+ github.com/imdario/mergo v0.3.15 // indirect+ github.com/josharian/intern v1.0.0 // indirect+ github.com/json-iterator/go v1.1.12 // indirect+ github.com/mailru/easyjson v0.7.7 // indirect+ github.com/mattn/go-colorable v0.1.14 // indirect+ github.com/mattn/go-isatty v0.0.20 // indirect+ github.com/mitchellh/copystructure v1.2.0 // indirect+ github.com/mitchellh/go-testing-interface v1.14.1 // indirect+ github.com/mitchellh/go-wordwrap v1.0.1 // indirect+ github.com/mitchellh/mapstructure v1.5.0 // indirect+ github.com/mitchellh/reflectwalk v1.0.2 // indirect+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect+ github.com/modern-go/reflect2 v1.0.2 // indirect+ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect+ github.com/oklog/run v1.2.0 // indirect+ github.com/pkg/errors v0.9.1 // indirect+ github.com/spf13/pflag v1.0.5 // indirect+ github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect+ github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect+ github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect+ github.com/x448/float16 v0.8.4 // indirect+ github.com/zclconf/go-cty v1.18.1 // indirect+ golang.org/x/crypto v0.50.0 // indirect+ golang.org/x/mod v0.35.0 // indirect+ golang.org/x/net v0.52.0 // indirect+ golang.org/x/oauth2 v0.34.0 // indirect+ golang.org/x/sync v0.20.0 // indirect+ golang.org/x/sys v0.43.0 // indirect+ golang.org/x/term v0.42.0 // indirect+ golang.org/x/text v0.36.0 // indirect+ golang.org/x/time v0.3.0 // indirect+ golang.org/x/tools v0.43.0 // indirect+ google.golang.org/appengine v1.6.8 // indirect+ google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect+ google.golang.org/grpc v1.79.3 // indirect+ google.golang.org/protobuf v1.36.11 // indirect+ gopkg.in/inf.v0 v0.9.1 // indirect+ gopkg.in/yaml.v2 v2.4.0 // indirect+ k8s.io/apiextensions-apiserver v0.31.0 // indirect+ k8s.io/klog/v2 v2.130.1 // indirect+ k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 // indirect+ k8s.io/utils v0.0.0-20240711033017-18e509b52bc8 // indirect+ sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect+ sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect+ sigs.k8s.io/yaml v1.4.0 // indirect+)diff --git a/libs/fleet/terraform-provider-cyclops/go.sum b/libs/fleet/terraform-provider-cyclops/go.sumnew file mode 100644index 0000000000..662c69b3ac--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/go.sum@@ -0,0 +1,381 @@+dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk=+dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=+github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=+github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=+github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=+github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=+github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo=+github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=+github.com/apparentlymart/go-textseg/v12 v12.0.0/go.mod h1:S/4uRK2UtaQttw1GenVJEynmyUenKwP++x/+DdGV/Ec=+github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY=+github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4=+github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=+github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=+github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=+github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=+github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=+github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=+github.com/cyphar/filepath-securejoin v0.4.1 h1:JyxxyPEaktOD+GAnqIqTf9A8tHyAG22rowi7HkoSU1s=+github.com/cyphar/filepath-securejoin v0.4.1/go.mod h1:Sdj7gXlvMcPZsbhwhQ33GguGLDGQL7h7bg04C/+u9jI=+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g=+github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=+github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=+github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=+github.com/evanphx/json-patch/v5 v5.9.0 h1:kcBlZQbplgElYIlo/n1hJbls2z/1awpXxpRi0/FOJfg=+github.com/evanphx/json-patch/v5 v5.9.0/go.mod h1:VNkHZ/282BpEyt/tObQO8s5CMPmYYq14uClGH4abBuQ=+github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=+github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=+github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=+github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=+github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=+github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E=+github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=+github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=+github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic=+github.com/go-git/go-billy/v5 v5.8.0 h1:I8hjc3LbBlXTtVuFNJuwYuMiHvQJDq1AT6u4DwDzZG0=+github.com/go-git/go-billy/v5 v5.8.0/go.mod h1:RpvI/rw4Vr5QA+Z60c6d6LXH0rYJo0uD5SqfmrrheCY=+github.com/go-git/go-git/v5 v5.18.0 h1:O831KI+0PR51hM2kep6T8k+w0/LIAD490gvqMCvL5hM=+github.com/go-git/go-git/v5 v5.18.0/go.mod h1:pW/VmeqkanRFqR6AljLcs7EA7FbZaN5MQqO7oZADXpo=+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=+github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ=+github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg=+github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE=+github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs=+github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE=+github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k=+github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=+github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogBU=+github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=+github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=+github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=+github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=+github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=+github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=+github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=+github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=+github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=+github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=+github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=+github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=+github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I=+github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U=+github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=+github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=+github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=+github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=+github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=+github.com/google/pprof v0.0.0-20240525223248-4bfdf5a9a2af h1:kmjWCqn2qkEml422C2Rrd27c3VGxi6a/6HNq8QmHRKM=+github.com/google/pprof v0.0.0-20240525223248-4bfdf5a9a2af/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=+github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=+github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=+github.com/hashicorp/go-checkpoint v0.5.0 h1:MFYpPZCnQqQTE18jFwSII6eUQrD/oxMFp3mlgcqk5mU=+github.com/hashicorp/go-checkpoint v0.5.0/go.mod h1:7nfLNL10NsxqO4iWuW6tWW0HjZuDrwkBuEQsVcpCOgg=+github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=+github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=+github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=+github.com/hashicorp/go-cty v1.5.0 h1:EkQ/v+dDNUqnuVpmS5fPqyY71NXVgT5gf32+57xY8g0=+github.com/hashicorp/go-cty v1.5.0/go.mod h1:lFUCG5kd8exDobgSfyj4ONE/dc822kiYMguVKdHGMLM=+github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=+github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=+github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=+github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=+github.com/hashicorp/go-plugin v1.7.0 h1:YghfQH/0QmPNc/AZMTFE3ac8fipZyZECHdDPshfk+mA=+github.com/hashicorp/go-plugin v1.7.0/go.mod h1:BExt6KEaIYx804z8k4gRzRLEvxKVb+kn0NMcihqOqb8=+github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48=+github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw=+github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=+github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=+github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=+github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA=+github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=+github.com/hashicorp/hc-install v0.9.4 h1:KKWOpUG0EqIV63Qk2GGFrZ0s275NVs5lKf9N5vjBNoc=+github.com/hashicorp/hc-install v0.9.4/go.mod h1:4LRYeEN2bMIFfIv57ldMWt9awfuZhvpbRt0vWmv51WU=+github.com/hashicorp/hcl/v2 v2.24.0 h1:2QJdZ454DSsYGoaE6QheQZjtKZSUs9Nh2izTWiwQxvE=+github.com/hashicorp/hcl/v2 v2.24.0/go.mod h1:oGoO1FIQYfn/AgyOhlg9qLC6/nOJPX3qGbkZpYAcqfM=+github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y=+github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=+github.com/hashicorp/terraform-exec v0.25.1 h1:PRutYRGM8pixV3B8812NYoBK5O+yuf3qcB/70KFKGiU=+github.com/hashicorp/terraform-exec v0.25.1/go.mod h1:+izOYrs9sKMQK4OYvGDnrSSJHY/pm4e4eXFqSL2Q5mA=+github.com/hashicorp/terraform-json v0.27.2 h1:BwGuzM6iUPqf9JYM/Z4AF1OJ5VVJEEzoKST/tRDBJKU=+github.com/hashicorp/terraform-json v0.27.2/go.mod h1:GzPLJ1PLdUG5xL6xn1OXWIjteQRT2CNT9o/6A9mi9hE=+github.com/hashicorp/terraform-plugin-framework v1.19.0 h1:q0bwyhxAOR3vfdgbk9iplv3MlTv/dhBHTXjQOtQDoBA=+github.com/hashicorp/terraform-plugin-framework v1.19.0/go.mod h1:YRXOBu0jvs7xp4AThBbX4mAzYaMJ1JgtFH//oGKxwLc=+github.com/hashicorp/terraform-plugin-framework-jsontypes v0.2.0 h1:SJXL5FfJJm17554Kpt9jFXngdM6fXbnUnZ6iT2IeiYA=+github.com/hashicorp/terraform-plugin-framework-jsontypes v0.2.0/go.mod h1:p0phD0IYhsu9bR4+6OetVvvH59I6LwjXGnTVEr8ox6E=+github.com/hashicorp/terraform-plugin-framework-validators v0.19.0 h1:Zz3iGgzxe/1XBkooZCewS0nJAaCFPFPHdNJd8FgE4Ow=+github.com/hashicorp/terraform-plugin-framework-validators v0.19.0/go.mod h1:GBKTNGbGVJohU03dZ7U8wHqc2zYnMUawgCN+gC0itLc=+github.com/hashicorp/terraform-plugin-go v0.31.0 h1:0Fz2r9DQ+kNNl6bx8HRxFd1TfMKUvnrOtvJPmp3Z0q8=+github.com/hashicorp/terraform-plugin-go v0.31.0/go.mod h1:A88bDhd/cW7FnwqxQRz3slT+QY6yzbHKc6AOTtmdeS8=+github.com/hashicorp/terraform-plugin-log v0.10.0 h1:eu2kW6/QBVdN4P3Ju2WiB2W3ObjkAsyfBsL3Wh1fj3g=+github.com/hashicorp/terraform-plugin-log v0.10.0/go.mod h1:/9RR5Cv2aAbrqcTSdNmY1NRHP4E3ekrXRGjqORpXyB0=+github.com/hashicorp/terraform-plugin-sdk/v2 v2.40.0 h1:MKS/2URqeJRwJdbOfcbdsZCq/IRrNkqJNN0GtVIsuGs=+github.com/hashicorp/terraform-plugin-sdk/v2 v2.40.0/go.mod h1:PuG4P97Ju3QXW6c6vRkRadWJbvnEu2Xh+oOuqcYOqX4=+github.com/hashicorp/terraform-plugin-testing v1.16.0 h1:GB97nGnJ1hESpDrCjqZig38RodSF0gdRzxlDupLXP38=+github.com/hashicorp/terraform-plugin-testing v1.16.0/go.mod h1:eQPYAy9xFMV7xtIFX8Y+wJGtUB++HBl329zCF6PBMZk=+github.com/hashicorp/terraform-registry-address v0.4.0 h1:S1yCGomj30Sao4l5BMPjTGZmCNzuv7/GDTDX99E9gTk=+github.com/hashicorp/terraform-registry-address v0.4.0/go.mod h1:LRS1Ay0+mAiRkUyltGT+UHWkIqTFvigGn/LbMshfflE=+github.com/hashicorp/terraform-svchost v0.2.1 h1:ubvrTFw3Q7CsoEaX7V06PtCTKG3wu7GyyobAoN4eF3Q=+github.com/hashicorp/terraform-svchost v0.2.1/go.mod h1:zDMheBLvNzu7Q6o9TBvPqiZToJcSuCLXjAXxBslSky4=+github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8=+github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns=+github.com/imdario/mergo v0.3.15 h1:M8XP7IuFNsqUx6VPK2P9OSmsYsI/YFaGil0uD21V3dM=+github.com/imdario/mergo v0.3.15/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY=+github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=+github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=+github.com/jhump/protoreflect v1.17.0 h1:qOEr613fac2lOuTgWN4tPAtLL7fUSbuJL5X5XumQh94=+github.com/jhump/protoreflect v1.17.0/go.mod h1:h9+vUUL38jiBzck8ck+6G/aeMX8Z4QUY/NiJPwPNi+8=+github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=+github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=+github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4=+github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=+github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=+github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=+github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=+github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=+github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=+github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=+github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=+github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=+github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=+github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=+github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=+github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=+github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=+github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU=+github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8=+github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=+github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=+github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=+github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=+github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=+github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=+github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=+github.com/oklog/run v1.2.0 h1:O8x3yXwah4A73hJdlrwo/2X6J62gE5qTMusH0dvz60E=+github.com/oklog/run v1.2.0/go.mod h1:mgDbKRSwPhJfesJ4PntqFUbKQRZ50NgmZTSPlFA0YFk=+github.com/onsi/ginkgo/v2 v2.19.0 h1:9Cnnf7UHo57Hy3k6/m5k3dRfGTMXGvxhHFvkDTCTpvA=+github.com/onsi/ginkgo/v2 v2.19.0/go.mod h1:rlwLi9PilAFJ8jCg9UE1QP6VBpd6/xj3SRC0d6TU0To=+github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk=+github.com/onsi/gomega v1.33.1/go.mod h1:U4R44UsT+9eLIaYRB2a5qajjtQYn0hauxvRm16AVYg0=+github.com/pjbgf/sha1cd v0.3.2 h1:a9wb0bp1oC2TGwStyn0Umc/IGKQnEgF0vVaZ8QF8eo4=+github.com/pjbgf/sha1cd v0.3.2/go.mod h1:zQWigSxVmsHEZow5qaLtPYxpcKMMQpa09ixqBxuCS6A=+github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=+github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/prometheus/client_golang v1.19.1 h1:wZWJDwK+NameRJuPGDhlnFgx8e8HN3XHQeLaYJFJBOE=+github.com/prometheus/client_golang v1.19.1/go.mod h1:mP78NwGzrVks5S2H6ab8+ZZGJLZUq1hoULYBAYBw1Ho=+github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=+github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=+github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc=+github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8=+github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=+github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=+github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8=+github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=+github.com/skeema/knownhosts v1.3.1 h1:X2osQ+RAjK76shCbvhHHHVl3ZlgDm8apHEHFqRjnBY8=+github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQNxPwTcfiY=+github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=+github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=+github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=+github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=+github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI=+github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=+github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=+github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=+github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=+github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=+github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=+github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=+github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=+github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw=+github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=+github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=+github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=+github.com/zclconf/go-cty v1.18.1 h1:yEGE8M4iIZlyKQURZNb2SnEyZlZHUcBCnx6KF81KuwM=+github.com/zclconf/go-cty v1.18.1/go.mod h1:qpnV6EDNgC1sns/AleL1fvatHw72j+S+nS+MJ+T2CSg=+github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940 h1:4r45xpDWB6ZMSMNJFMOjqrGHynW3DIBuR2H9j0ug+Mo=+github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940/go.mod h1:CmBdvvj3nqzfzJ6nTCIwDTPZ56aVGvDrmztiO5g3qrM=+go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=+go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=+go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=+go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=+go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=+go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=+go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=+go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=+go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=+go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=+go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=+go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=+go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=+go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=+go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=+go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=+golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=+golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=+golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc h1:mCRnTeVUjcrhlRmO0VK8a6k6Rrf6TF9htwo2pJVSjIU=+golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w=+golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=+golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=+golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=+golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=+golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=+golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=+golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=+golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=+golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=+golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=+golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=+golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=+golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=+golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=+golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=+golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=+golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=+golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=+golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=+golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=+golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=+golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=+golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=+golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=+golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=+golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=+golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s=+golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw=+gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY=+gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=+gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=+google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=+google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM=+google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds=+google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww=+google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=+google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=+google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=+google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=+google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=+gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSPG+6V4=+gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M=+gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=+gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=+gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME=+gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=+gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+k8s.io/api v0.31.4 h1:I2QNzitPVsPeLQvexMEsj945QumYraqv9m74isPDKhM=+k8s.io/api v0.31.4/go.mod h1:d+7vgXLvmcdT1BCo79VEgJxHHryww3V5np2OYTr6jdw=+k8s.io/apiextensions-apiserver v0.31.0 h1:fZgCVhGwsclj3qCw1buVXCV6khjRzKC5eCFt24kyLSk=+k8s.io/apiextensions-apiserver v0.31.0/go.mod h1:b9aMDEYaEe5sdK+1T0KU78ApR/5ZVp4i56VacZYEHxk=+k8s.io/apimachinery v0.31.4 h1:8xjE2C4CzhYVm9DGf60yohpNUh5AEBnPxCryPBECmlM=+k8s.io/apimachinery v0.31.4/go.mod h1:rsPdaZJfTfLsNJSQzNHQvYoTmxhoOEofxtOsF3rtsMo=+k8s.io/client-go v0.31.4 h1:t4QEXt4jgHIkKKlx06+W3+1JOwAFU/2OPiOo7H92eRQ=+k8s.io/client-go v0.31.4/go.mod h1:kvuMro4sFYIa8sulL5Gi5GFqUPvfH2O/dXuKstbaaeg=+k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk=+k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE=+k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 h1:BZqlfIlq5YbRMFko6/PM7FjZpUb45WallggurYhKGag=+k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340/go.mod h1:yD4MZYeKMBwQKVht279WycxKyM84kkAx2DPrTXaeb98=+k8s.io/utils v0.0.0-20240711033017-18e509b52bc8 h1:pUdcCO1Lk/tbT5ztQWOBi5HBgbBP1J8+AsQnQCKsi8A=+k8s.io/utils v0.0.0-20240711033017-18e509b52bc8/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=+sigs.k8s.io/controller-runtime v0.19.7 h1:DLABZfMr20A+AwCZOHhcbcu+TqBXnJZaVBri9K3EO48=+sigs.k8s.io/controller-runtime v0.19.7/go.mod h1:iRmWllt8IlaLjvTTDLhRBXIEtkCK6hwVBJJsYS9Ajf4=+sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo=+sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0=+sigs.k8s.io/structured-merge-diff/v4 v4.4.1 h1:150L+0vs/8DA78h1u02ooW1/fFq/Lwr+sGiqlzvrtq4=+sigs.k8s.io/structured-merge-diff/v4 v4.4.1/go.mod h1:N8hJocpFajUSSeSJ9bOZ77VzejKZaXsTtZo4/u7Io08=+sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E=+sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY=diff --git a/libs/fleet/terraform-provider-cyclops/internal/client/client.go b/libs/fleet/terraform-provider-cyclops/internal/client/client.gonew file mode 100644index 0000000000..48a4450c13--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/internal/client/client.go@@ -0,0 +1,184 @@+package client++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+ "sync"+ "time"+)++const defaultTimeout = 30 * time.Second++type Config struct {+ Endpoint string+ AccessToken string+ ClientID string+ ClientSecret string+ TokenURL string+ HTTPClient *http.Client+}++type Client struct {+ endpoint string+ accessToken string+ clientID string+ clientSecret string+ tokenURL string+ httpClient *http.Client++ mu sync.Mutex+ cachedToken string+ tokenExpiry time.Time+}++type APIError struct {+ StatusCode int+ Method string+ URL string+ Body string+}++func (e *APIError) Error() string {+ return fmt.Sprintf("cyclops API %s %s returned %d: %s", e.Method, e.URL, e.StatusCode, e.Body)+}++func IsNotFound(err error) bool {+ var apiErr *APIError+ return errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound+}++func IsConflict(err error) bool {+ var apiErr *APIError+ return errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusConflict+}++func New(cfg Config) (*Client, error) {+ endpoint := strings.TrimRight(strings.TrimSpace(cfg.Endpoint), "/")+ if endpoint == "" {+ return nil, errors.New("endpoint is required")+ }+ if _, err := url.ParseRequestURI(endpoint); err != nil {+ return nil, fmt.Errorf("invalid endpoint: %w", err)+ }+ if cfg.AccessToken == "" && (cfg.ClientID == "" || cfg.ClientSecret == "" || cfg.TokenURL == "") {+ return nil, errors.New("set access_token or client_id, client_secret, and token_url")+ }+ httpClient := cfg.HTTPClient+ if httpClient == nil {+ httpClient = &http.Client{Timeout: defaultTimeout}+ }+ return &Client{+ endpoint: endpoint, accessToken: cfg.AccessToken, clientID: cfg.ClientID,+ clientSecret: cfg.ClientSecret, tokenURL: cfg.TokenURL, httpClient: httpClient,+ }, nil+}++func (c *Client) token(ctx context.Context) (string, error) {+ if c.accessToken != "" {+ return c.accessToken, nil+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ if c.cachedToken != "" && time.Now().Add(30*time.Second).Before(c.tokenExpiry) {+ return c.cachedToken, nil+ }+ form := url.Values{"grant_type": {"client_credentials"}}+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.tokenURL, strings.NewReader(form.Encode()))+ if err != nil {+ return "", err+ }+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ req.SetBasicAuth(c.clientID, c.clientSecret)+ resp, err := c.httpClient.Do(req)+ if err != nil {+ return "", fmt.Errorf("request OAuth token: %w", err)+ }+ defer resp.Body.Close()+ body, err := io.ReadAll(resp.Body)+ if err != nil {+ return "", fmt.Errorf("read OAuth token response: %w", err)+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return "", &APIError{StatusCode: resp.StatusCode, Method: http.MethodPost, URL: c.tokenURL, Body: compactBody(body)}+ }+ var token struct {+ AccessToken string `json:"access_token"`+ ExpiresIn int64 `json:"expires_in"`+ }+ if err := json.Unmarshal(body, &token); err != nil {+ return "", fmt.Errorf("decode OAuth token response: %w", err)+ }+ if token.AccessToken == "" {+ return "", errors.New("OAuth token response did not contain access_token")+ }+ c.cachedToken = token.AccessToken+ if token.ExpiresIn <= 0 {+ token.ExpiresIn = 300+ }+ c.tokenExpiry = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)+ return c.cachedToken, nil+}++func (c *Client) do(ctx context.Context, method, path, contentType string, requestBody, responseBody any) error {+ var body io.Reader+ if requestBody != nil {+ encoded, err := json.Marshal(requestBody)+ if err != nil {+ return fmt.Errorf("encode request: %w", err)+ }+ body = bytes.NewReader(encoded)+ }+ token, err := c.token(ctx)+ if err != nil {+ return err+ }+ requestURL := c.endpoint + path+ req, err := http.NewRequestWithContext(ctx, method, requestURL, body)+ if err != nil {+ return err+ }+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("Accept", "application/json")+ if requestBody != nil {+ if contentType == "" {+ contentType = "application/json"+ }+ req.Header.Set("Content-Type", contentType)+ }+ resp, err := c.httpClient.Do(req)+ if err != nil {+ return fmt.Errorf("request Cyclops API: %w", err)+ }+ defer resp.Body.Close()+ responseBytes, err := io.ReadAll(resp.Body)+ if err != nil {+ return fmt.Errorf("read Cyclops API response: %w", err)+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return &APIError{StatusCode: resp.StatusCode, Method: method, URL: requestURL, Body: compactBody(responseBytes)}+ }+ if responseBody != nil && len(responseBytes) > 0 {+ if err := json.Unmarshal(responseBytes, responseBody); err != nil {+ return fmt.Errorf("decode Cyclops API response: %w", err)+ }+ }+ return nil+}++func compactBody(body []byte) string {+ const limit = 2048+ text := strings.TrimSpace(string(body))+ if len(text) > limit {+ return text[:limit] + "..."+ }+ return text+}++func escape(value string) string { return url.PathEscape(value) }diff --git a/libs/fleet/terraform-provider-cyclops/internal/client/client_test.go b/libs/fleet/terraform-provider-cyclops/internal/client/client_test.gonew file mode 100644index 0000000000..6099dab36a--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/internal/client/client_test.go@@ -0,0 +1,128 @@+package client++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "reflect"+ "sync"+ "testing"+)++func TestPoolLifecycle(t *testing.T) {+ t.Parallel()++ var mu sync.Mutex+ var requests []string+ var created Pool+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mu.Lock()+ requests = append(requests, r.Method+" "+r.URL.Path)+ mu.Unlock()++ if r.URL.Path == "/token" {+ if id, secret, ok := r.BasicAuth(); !ok || id != "client" || secret != "secret" {+ t.Fatalf("unexpected OAuth credentials: %q %q %v", id, secret, ok)+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"access_token": "token", "expires_in": 300})+ return+ }+ if got := r.Header.Get("Authorization"); got != "Bearer token" {+ t.Fatalf("unexpected authorization header %q", got)+ }++ switch r.Method + " " + r.URL.Path {+ case "POST /api/namespaces":+ w.WriteHeader(http.StatusCreated)+ case "POST /api/k8s/apis/cua.ai/v1/namespaces/demo/osgymworkspacepools":+ if err := json.NewDecoder(r.Body).Decode(&created); err != nil {+ t.Fatal(err)+ }+ w.WriteHeader(http.StatusCreated)+ case "GET /api/k8s/apis/cua.ai/v1/namespaces/demo/osgymworkspacepools/demo":+ created.Metadata.Namespace = "demo"+ created.Status = PoolStatus{Phase: "Ready", AvailableCount: 2}+ _ = json.NewEncoder(w).Encode(created)+ case "PATCH /api/k8s/apis/cua.ai/v1/namespaces/demo/osgymworkspacepools/demo":+ if got := r.Header.Get("Content-Type"); got != "application/merge-patch+json" {+ t.Fatalf("unexpected patch content type %q", got)+ }+ w.WriteHeader(http.StatusOK)+ case "DELETE /api/k8s/apis/cua.ai/v1/namespaces/demo/osgymworkspacepools/demo",+ "DELETE /api/namespaces/demo":+ w.WriteHeader(http.StatusNoContent)+ default:+ http.Error(w, "unexpected request", http.StatusNotFound)+ }+ }))+ defer server.Close()++ api, err := New(Config{Endpoint: server.URL, ClientID: "client", ClientSecret: "secret", TokenURL: server.URL + "/token"})+ if err != nil {+ t.Fatal(err)+ }+ pool := Pool{Metadata: PoolMetadata{Name: "demo"}, Spec: PoolSpec{+ Replicas: 2,+ Template: PoolTemplate{ContainerDiskImage: "example/image:latest", ImagePullSecret: "ecr-credentials", CPUCores: 4, Memory: "8Gi"},+ Services: []Service{{Name: "ssh", TargetPort: 22, Protocol: "TCP"}},+ }}+ ctx := context.Background()+ if err := api.CreatePool(ctx, pool); err != nil {+ t.Fatal(err)+ }+ if created.APIVersion != "cua.ai/v1" || created.Kind != "OSGymWorkspacePool" {+ t.Fatalf("unexpected resource type: %#v", created)+ }+ if !reflect.DeepEqual(created.Metadata.Labels, map[string]string{"cua.ai/pool": "demo"}) {+ t.Fatalf("unexpected labels: %#v", created.Metadata.Labels)+ }+ got, err := api.GetPool(ctx, "demo", "demo")+ if err != nil {+ t.Fatal(err)+ }+ if got.Status.Phase != "Ready" || got.Status.AvailableCount != 2 {+ t.Fatalf("unexpected status: %#v", got.Status)+ }+ if err := api.UpdatePool(ctx, "demo", "demo", pool.Spec); err != nil {+ t.Fatal(err)+ }+ if err := api.DeletePool(ctx, "demo", "demo"); err != nil {+ t.Fatal(err)+ }++ mu.Lock()+ defer mu.Unlock()+ want := []string{+ "POST /token",+ "POST /api/namespaces",+ "POST /api/k8s/apis/cua.ai/v1/namespaces/demo/osgymworkspacepools",+ "GET /api/k8s/apis/cua.ai/v1/namespaces/demo/osgymworkspacepools/demo",+ "PATCH /api/k8s/apis/cua.ai/v1/namespaces/demo/osgymworkspacepools/demo",+ "DELETE /api/k8s/apis/cua.ai/v1/namespaces/demo/osgymworkspacepools/demo",+ "DELETE /api/namespaces/demo",+ }+ if !reflect.DeepEqual(requests, want) {+ t.Fatalf("requests mismatch\n got: %#v\nwant: %#v", requests, want)+ }+}++func TestCreatePoolReusesExistingNamespace(t *testing.T) {+ t.Parallel()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/api/namespaces" {+ http.Error(w, `{"error":"already exists"}`, http.StatusConflict)+ return+ }+ w.WriteHeader(http.StatusCreated)+ }))+ defer server.Close()++ api, err := New(Config{Endpoint: server.URL, AccessToken: "token"})+ if err != nil {+ t.Fatal(err)+ }+ if err := api.CreatePool(context.Background(), Pool{Metadata: PoolMetadata{Name: "demo"}}); err != nil {+ t.Fatal(err)+ }+}diff --git a/libs/fleet/terraform-provider-cyclops/internal/client/pools.go b/libs/fleet/terraform-provider-cyclops/internal/client/pools.gonew file mode 100644index 0000000000..182db90c67--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/internal/client/pools.go@@ -0,0 +1,97 @@+package client++import (+ "context"+ "net/http"+)++type Pool struct {+ APIVersion string `json:"apiVersion,omitempty"`+ Kind string `json:"kind,omitempty"`+ Metadata PoolMetadata `json:"metadata"`+ Spec PoolSpec `json:"spec"`+ Status PoolStatus `json:"status,omitempty"`+}++type PoolMetadata struct {+ Name string `json:"name"`+ Namespace string `json:"namespace,omitempty"`+ Labels map[string]string `json:"labels,omitempty"`+}++type PoolSpec struct {+ Replicas int64 `json:"replicas"`+ Template PoolTemplate `json:"template"`+ Services []Service `json:"services,omitempty"`+ Autoscaling *Autoscaling `json:"autoscaling,omitempty"`+}++type PoolTemplate struct {+ Runtime string `json:"runtime,omitempty"`+ ContainerDiskImage string `json:"containerDiskImage"`+ ImagePullSecret string `json:"imagePullSecret,omitempty"`+ CPUCores int64 `json:"cpuCores"`+ Memory string `json:"memory"`+ Firmware string `json:"firmware,omitempty"`+ Probes map[string]any `json:"probes,omitempty"`+}++type Service struct {+ Name string `json:"name"`+ TargetPort int64 `json:"targetPort"`+ Protocol string `json:"protocol,omitempty"`+}++type Autoscaling struct {+ MinPoolSize int64 `json:"minPoolSize"`+ InitialPoolSize int64 `json:"initialPoolSize"`+ MaxPoolSize int64 `json:"maxPoolSize"`+}++type PoolStatus struct {+ Phase string `json:"phase,omitempty"`+ TotalCount int64 `json:"totalCount,omitempty"`+ AvailableCount int64 `json:"availableCount,omitempty"`+ ClaimedCount int64 `json:"claimedCount,omitempty"`+}++func (c *Client) CreatePool(ctx context.Context, pool Pool) error {+ if err := c.do(ctx, http.MethodPost, "/api/namespaces", "", map[string]string{"name": pool.Metadata.Name}, nil); err != nil && !IsConflict(err) {+ return err+ }+ pool.APIVersion = "cua.ai/v1"+ pool.Kind = "OSGymWorkspacePool"+ pool.Metadata.Namespace = ""+ if pool.Metadata.Labels == nil {+ pool.Metadata.Labels = map[string]string{"cua.ai/pool": pool.Metadata.Name}+ }+ return c.do(ctx, http.MethodPost, poolCollectionPath(pool.Metadata.Name), "", pool, nil)+}++func (c *Client) GetPool(ctx context.Context, namespace, name string) (Pool, error) {+ var pool Pool+ err := c.do(ctx, http.MethodGet, poolPath(namespace, name), "", nil, &pool)+ return pool, err+}++func (c *Client) UpdatePool(ctx context.Context, namespace, name string, spec PoolSpec) error {+ return c.do(ctx, http.MethodPatch, poolPath(namespace, name), "application/merge-patch+json", map[string]any{"spec": spec}, nil)+}++func (c *Client) DeletePool(ctx context.Context, namespace, name string) error {+ if err := c.do(ctx, http.MethodDelete, poolPath(namespace, name), "", nil, nil); err != nil && !IsNotFound(err) {+ return err+ }+ if err := c.do(ctx, http.MethodDelete, "/api/namespaces/"+escape(namespace), "", nil, nil); err != nil && !IsNotFound(err) {+ return err+ }+ return nil+}++func poolCollectionPath(namespace string) string {+ return "/api/k8s/apis/cua.ai/v1/namespaces/" + escape(namespace) + "/osgymworkspacepools"+}++func poolPath(namespace, name string) string {+ return poolCollectionPath(namespace) + "/" + escape(name)+}diff --git a/libs/fleet/terraform-provider-cyclops/internal/provider/generate/pool_mapping.json b/libs/fleet/terraform-provider-cyclops/internal/provider/generate/pool_mapping.jsonnew file mode 100644index 0000000000..e5a1909162--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/internal/provider/generate/pool_mapping.json@@ -0,0 +1,182 @@+{+ "resource_description": "A Cyclops computer-use pool. The pool name also owns its same-named namespace.",+ "attributes": [+ {+ "name": "id",+ "go_name": "ID",+ "value_type": "string",+ "mode": "computed"+ },+ {+ "name": "name",+ "go_name": "Name",+ "value_type": "string",+ "mode": "required",+ "description": "DNS label used for both pool and namespace.",+ "dns_label": true,+ "requires_replace": true+ },+ {+ "name": "namespace",+ "go_name": "Namespace",+ "value_type": "string",+ "mode": "computed"+ },+ {+ "name": "replicas",+ "go_name": "Replicas",+ "value_type": "int64",+ "mode": "required",+ "crd_path": "spec.replicas"+ },+ {+ "name": "cpu_cores",+ "go_name": "CPUCores",+ "value_type": "int64",+ "mode": "required",+ "crd_path": "spec.template.cpuCores"+ },+ {+ "name": "memory",+ "go_name": "Memory",+ "value_type": "string",+ "mode": "required",+ "crd_path": "spec.template.memory"+ },+ {+ "name": "container_disk_image",+ "go_name": "ContainerDiskImage",+ "value_type": "string",+ "mode": "required",+ "crd_path": "spec.template.containerDiskImage"+ },+ {+ "name": "image_pull_secret",+ "go_name": "ImagePullSecret",+ "value_type": "string",+ "mode": "optional_computed",+ "crd_path": "spec.template.imagePullSecret",+ "description": "Kubernetes image pull secret. Defaults to ecr-credentials."+ },+ {+ "name": "runtime",+ "go_name": "Runtime",+ "value_type": "string",+ "mode": "optional_computed",+ "crd_path": "spec.template.runtime"+ },+ {+ "name": "firmware",+ "go_name": "Firmware",+ "value_type": "string",+ "mode": "optional_computed",+ "crd_path": "spec.template.firmware"+ },+ {+ "name": "readiness_probe_json",+ "go_name": "ReadinessProbeJSON",+ "value_type": "normalized_json",+ "mode": "optional",+ "crd_path": "spec.template.probes",+ "description": "JSON object for the VMI readinessProbe."+ },+ {+ "name": "liveness_probe_json",+ "go_name": "LivenessProbeJSON",+ "value_type": "normalized_json",+ "mode": "optional",+ "crd_path": "spec.template.probes",+ "description": "JSON object for the VMI livenessProbe."+ },+ {+ "name": "phase",+ "go_name": "Phase",+ "value_type": "string",+ "mode": "computed",+ "crd_path": "status.phase"+ },+ {+ "name": "total_count",+ "go_name": "TotalCount",+ "value_type": "int64",+ "mode": "computed",+ "crd_path": "status.totalCount"+ },+ {+ "name": "available_count",+ "go_name": "AvailableCount",+ "value_type": "int64",+ "mode": "computed",+ "crd_path": "status.availableCount"+ },+ {+ "name": "claimed_count",+ "go_name": "ClaimedCount",+ "value_type": "int64",+ "mode": "computed",+ "crd_path": "status.claimedCount"+ }+ ],+ "blocks": [+ {+ "name": "service",+ "model": "serviceModel",+ "collection": "set",+ "crd_path": "spec.services",+ "fields": [+ {+ "name": "name",+ "go_name": "Name",+ "value_type": "string",+ "mode": "required",+ "crd_path": "name"+ },+ {+ "name": "target_port",+ "go_name": "TargetPort",+ "value_type": "int64",+ "mode": "required",+ "crd_path": "targetPort"+ },+ {+ "name": "protocol",+ "go_name": "Protocol",+ "value_type": "string",+ "mode": "optional_computed",+ "crd_path": "protocol"+ }+ ],+ "go_name": "Services"+ },+ {+ "name": "autoscaling",+ "model": "autoscalingModel",+ "collection": "single",+ "crd_path": "spec.autoscaling",+ "fields": [+ {+ "name": "min_pool_size",+ "go_name": "MinPoolSize",+ "value_type": "int64",+ "mode": "optional_computed",+ "crd_path": "minPoolSize"+ },+ {+ "name": "initial_pool_size",+ "go_name": "InitialPoolSize",+ "value_type": "int64",+ "mode": "optional_computed",+ "crd_path": "initialPoolSize"+ },+ {+ "name": "max_pool_size",+ "go_name": "MaxPoolSize",+ "value_type": "int64",+ "mode": "required",+ "crd_path": "maxPoolSize"+ }+ ],+ "go_name": "Autoscaling"+ }+ ]+}diff --git a/libs/fleet/terraform-provider-cyclops/internal/provider/pool_generated.go b/libs/fleet/terraform-provider-cyclops/internal/provider/pool_generated.gonew file mode 100644index 0000000000..56819105f2--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/internal/provider/pool_generated.go@@ -0,0 +1,95 @@+// Code generated by cmd/generate-pool-resource; DO NOT EDIT.++package provider++import (+ "regexp"++ "github.com/hashicorp/terraform-plugin-framework-jsontypes/jsontypes"+ "github.com/hashicorp/terraform-plugin-framework-validators/int64validator"+ "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"+ "github.com/hashicorp/terraform-plugin-framework/attr"+ "github.com/hashicorp/terraform-plugin-framework/resource/schema"+ "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"+ "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"+ "github.com/hashicorp/terraform-plugin-framework/schema/validator"+ "github.com/hashicorp/terraform-plugin-framework/types"+)++type poolResourceModel struct {+ ID types.String `tfsdk:"id"`+ Name types.String `tfsdk:"name"`+ Namespace types.String `tfsdk:"namespace"`+ Replicas types.Int64 `tfsdk:"replicas"`+ CPUCores types.Int64 `tfsdk:"cpu_cores"`+ Memory types.String `tfsdk:"memory"`+ ContainerDiskImage types.String `tfsdk:"container_disk_image"`+ ImagePullSecret types.String `tfsdk:"image_pull_secret"`+ Runtime types.String `tfsdk:"runtime"`+ Firmware types.String `tfsdk:"firmware"`+ ReadinessProbeJSON jsontypes.Normalized `tfsdk:"readiness_probe_json"`+ LivenessProbeJSON jsontypes.Normalized `tfsdk:"liveness_probe_json"`+ Phase types.String `tfsdk:"phase"`+ TotalCount types.Int64 `tfsdk:"total_count"`+ AvailableCount types.Int64 `tfsdk:"available_count"`+ ClaimedCount types.Int64 `tfsdk:"claimed_count"`+ Services types.Set `tfsdk:"service"`+ Autoscaling types.Object `tfsdk:"autoscaling"`+}++type serviceModel struct {+ Name types.String `tfsdk:"name"`+ TargetPort types.Int64 `tfsdk:"target_port"`+ Protocol types.String `tfsdk:"protocol"`+}++type autoscalingModel struct {+ MinPoolSize types.Int64 `tfsdk:"min_pool_size"`+ InitialPoolSize types.Int64 `tfsdk:"initial_pool_size"`+ MaxPoolSize types.Int64 `tfsdk:"max_pool_size"`+}++func poolResourceSchema() schema.Schema {+ return schema.Schema{Description: "A Cyclops computer-use pool. The pool name also owns its same-named namespace.",+ Attributes: map[string]schema.Attribute{+ "id": schema.StringAttribute{Computed: true},+ "name": schema.StringAttribute{Required: true, Description: "DNS label used for both pool and namespace.", Validators: []validator.String{stringvalidator.LengthBetween(1, 63), stringvalidator.RegexMatches(dnsLabelRegex, "must be a lowercase DNS label")}, PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()}},+ "namespace": schema.StringAttribute{Computed: true},+ "replicas": schema.Int64Attribute{Required: true, Validators: []validator.Int64{int64validator.AtLeast(0)}},+ "cpu_cores": schema.Int64Attribute{Required: true, Validators: []validator.Int64{int64validator.AtLeast(1)}},+ "memory": schema.StringAttribute{Required: true},+ "container_disk_image": schema.StringAttribute{Required: true},+ "image_pull_secret": schema.StringAttribute{Optional: true, Computed: true, Description: "Kubernetes image pull secret. Defaults to ecr-credentials."},+ "runtime": schema.StringAttribute{Optional: true, Computed: true, Description: "Pool backend. \"kubevirt\" (default) provisions a KubeVirt VM. \"macos\" provisions a macOS sandbox (ADMIN-ONLY — the cyclops-cs backend rejects macos pool writes from non-admins; the SPA hides the option). Flows verbatim through the compat shim into the OSGymSandboxTemplate vmTemplate, where macos_backend dispatches on it.", Validators: []validator.String{stringvalidator.OneOf("gvisor", "kubevirt", "macos")}},+ "firmware": schema.StringAttribute{Optional: true, Computed: true, Description: "VM firmware. Use \"efi\" for GPT/UEFI-only guest images (e.g. the dockur-built Windows desktop-workspace); \"bios\" is KubeVirt's default and what the Linux workspace images boot with.", Validators: []validator.String{stringvalidator.OneOf("bios", "efi")}},+ "readiness_probe_json": schema.StringAttribute{Optional: true, CustomType: jsontypes.NormalizedType{}, Description: "JSON object for the VMI readinessProbe."},+ "liveness_probe_json": schema.StringAttribute{Optional: true, CustomType: jsontypes.NormalizedType{}, Description: "JSON object for the VMI livenessProbe."},+ "phase": schema.StringAttribute{Computed: true},+ "total_count": schema.Int64Attribute{Computed: true},+ "available_count": schema.Int64Attribute{Computed: true},+ "claimed_count": schema.Int64Attribute{Computed: true},+ },+ Blocks: map[string]schema.Block{+ "service": schema.SetNestedBlock{NestedObject: schema.NestedBlockObject{Attributes: map[string]schema.Attribute{+ "name": schema.StringAttribute{Required: true, Description: "Service name suffix (sandbox name is prepended)."},+ "target_port": schema.Int64Attribute{Required: true, Description: "Port on the VM pod to forward to.", Validators: []validator.Int64{int64validator.Between(1, 65535)}},+ "protocol": schema.StringAttribute{Optional: true, Computed: true, Validators: []validator.String{stringvalidator.OneOf("TCP", "UDP")}},+ }}},+ "autoscaling": schema.SingleNestedBlock{Attributes: map[string]schema.Attribute{+ "min_pool_size": schema.Int64Attribute{Optional: true, Computed: true, Description: "Durable warm floor (KEDA minReplicaCount).", Validators: []validator.Int64{int64validator.AtLeast(0)}},+ "initial_pool_size": schema.Int64Attribute{Optional: true, Computed: true, Description: "One-time warm head-start seeded on create.", Validators: []validator.Int64{int64validator.AtLeast(0)}},+ "max_pool_size": schema.Int64Attribute{Required: true, Description: "Hard ceiling (KEDA maxReplicaCount).", Validators: []validator.Int64{int64validator.AtLeast(1)}},+ }},+ },+ }+}++func serviceObjectType() map[string]attr.Type {+ return map[string]attr.Type{"name": types.StringType, "target_port": types.Int64Type, "protocol": types.StringType}+}++func autoscalingObjectType() map[string]attr.Type {+ return map[string]attr.Type{"min_pool_size": types.Int64Type, "initial_pool_size": types.Int64Type, "max_pool_size": types.Int64Type}+}++var dnsLabelRegex = regexp.MustCompile(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$`)diff --git a/libs/fleet/terraform-provider-cyclops/internal/provider/pool_resource.go b/libs/fleet/terraform-provider-cyclops/internal/provider/pool_resource.gonew file mode 100644index 0000000000..cb67502b1b--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/internal/provider/pool_resource.go@@ -0,0 +1,245 @@+package provider++//go:generate go run ../../cmd/generate-pool-resource -crd ../../../../clusters/base/osgym/crd.yaml -mapping generate/pool_mapping.json -out pool_generated.go++import (+ "context"+ "encoding/json"+ "fmt"++ "github.com/hashicorp/terraform-plugin-framework-jsontypes/jsontypes"+ "github.com/hashicorp/terraform-plugin-framework/attr"+ "github.com/hashicorp/terraform-plugin-framework/diag"+ "github.com/hashicorp/terraform-plugin-framework/path"+ "github.com/hashicorp/terraform-plugin-framework/resource"+ "github.com/hashicorp/terraform-plugin-framework/types"+ "github.com/trycua/terraform-provider-cyclops/internal/client"+)++type poolResource struct{ client *client.Client }++func NewPoolResource() resource.Resource { return &poolResource{} }++func (r *poolResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {+ resp.TypeName = req.ProviderTypeName + "_pool"+}++func (r *poolResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {+ resp.Schema = poolResourceSchema()+}++func (r *poolResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {+ if req.ProviderData == nil {+ return+ }+ apiClient, ok := req.ProviderData.(*client.Client)+ if !ok {+ resp.Diagnostics.AddError("Unexpected provider data", fmt.Sprintf("expected *client.Client, got %T", req.ProviderData))+ return+ }+ r.client = apiClient+}++func (r *poolResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {+ var plan poolResourceModel+ resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)+ if resp.Diagnostics.HasError() {+ return+ }+ pool := plan.toPool(ctx, &resp.Diagnostics)+ if resp.Diagnostics.HasError() {+ return+ }+ if err := r.client.CreatePool(ctx, pool); err != nil {+ resp.Diagnostics.AddError("Unable to create Cyclops pool", err.Error())+ return+ }+ created, err := r.client.GetPool(ctx, plan.Name.ValueString(), plan.Name.ValueString())+ if err != nil {+ resp.Diagnostics.AddError("Pool created but could not be read", err.Error())+ return+ }+ plan.fromPool(ctx, created, &resp.Diagnostics)+ resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)+}++func (r *poolResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {+ var state poolResourceModel+ resp.Diagnostics.Append(req.State.Get(ctx, &state)...)+ if resp.Diagnostics.HasError() {+ return+ }+ pool, err := r.client.GetPool(ctx, state.Namespace.ValueString(), state.Name.ValueString())+ if client.IsNotFound(err) {+ resp.State.RemoveResource(ctx)+ return+ }+ if err != nil {+ resp.Diagnostics.AddError("Unable to read Cyclops pool", err.Error())+ return+ }+ state.fromPool(ctx, pool, &resp.Diagnostics)+ resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)+}++func (r *poolResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {+ var plan poolResourceModel+ resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)+ if resp.Diagnostics.HasError() {+ return+ }+ pool := plan.toPool(ctx, &resp.Diagnostics)+ if resp.Diagnostics.HasError() {+ return+ }+ namespace := plan.Name.ValueString()+ if err := r.client.UpdatePool(ctx, namespace, plan.Name.ValueString(), pool.Spec); err != nil {+ resp.Diagnostics.AddError("Unable to update Cyclops pool", err.Error())+ return+ }+ updated, err := r.client.GetPool(ctx, namespace, plan.Name.ValueString())+ if err != nil {+ resp.Diagnostics.AddError("Pool updated but could not be read", err.Error())+ return+ }+ plan.fromPool(ctx, updated, &resp.Diagnostics)+ resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)+}++func (r *poolResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {+ var state poolResourceModel+ resp.Diagnostics.Append(req.State.Get(ctx, &state)...)+ if resp.Diagnostics.HasError() {+ return+ }+ if err := r.client.DeletePool(ctx, state.Namespace.ValueString(), state.Name.ValueString()); err != nil {+ resp.Diagnostics.AddError("Unable to delete Cyclops pool", err.Error())+ }+}++func (r *poolResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {+ resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...)+ resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), req.ID)...)+ resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("namespace"), req.ID)...)+}++func (m poolResourceModel) toPool(ctx context.Context, diagnostics *diag.Diagnostics) client.Pool {+ services := []client.Service{}+ if !m.Services.IsNull() && !m.Services.IsUnknown() {+ var values []serviceModel+ diagnostics.Append(m.Services.ElementsAs(ctx, &values, false)...)+ for _, value := range values {+ protocol := value.Protocol.ValueString()+ if protocol == "" {+ protocol = "TCP"+ }+ services = append(services, client.Service{Name: value.Name.ValueString(), TargetPort: value.TargetPort.ValueInt64(), Protocol: protocol})+ }+ }+ var autoscaling *client.Autoscaling+ var autoscalingValue autoscalingModel+ if objectValue(ctx, m.Autoscaling, &autoscalingValue, diagnostics) {+ autoscaling = &client.Autoscaling{MinPoolSize: autoscalingValue.MinPoolSize.ValueInt64(), InitialPoolSize: autoscalingValue.InitialPoolSize.ValueInt64(), MaxPoolSize: autoscalingValue.MaxPoolSize.ValueInt64()}+ }+ probes := map[string]any{}+ decodeProbe("readinessProbe", m.ReadinessProbeJSON, probes, diagnostics)+ decodeProbe("livenessProbe", m.LivenessProbeJSON, probes, diagnostics)+ if len(probes) == 0 {+ probes = nil+ }+ runtime := m.Runtime.ValueString()+ if runtime == "kubevirt" {+ runtime = ""+ }+ firmware := m.Firmware.ValueString()+ if firmware == "bios" {+ firmware = ""+ }+ imagePullSecret := m.ImagePullSecret.ValueString()+ if imagePullSecret == "" {+ imagePullSecret = "ecr-credentials"+ }+ return client.Pool{Metadata: client.PoolMetadata{Name: m.Name.ValueString()}, Spec: client.PoolSpec{+ Replicas: m.Replicas.ValueInt64(), Services: services, Autoscaling: autoscaling,+ Template: client.PoolTemplate{Runtime: runtime, ContainerDiskImage: m.ContainerDiskImage.ValueString(), ImagePullSecret: imagePullSecret, CPUCores: m.CPUCores.ValueInt64(), Memory: m.Memory.ValueString(), Firmware: firmware, Probes: probes},+ }}+}++func (m *poolResourceModel) fromPool(ctx context.Context, pool client.Pool, diagnostics *diag.Diagnostics) {+ m.ID = types.StringValue(pool.Metadata.Name)+ m.Name = types.StringValue(pool.Metadata.Name)+ m.Namespace = types.StringValue(pool.Metadata.Namespace)+ m.Replicas = types.Int64Value(pool.Spec.Replicas)+ m.CPUCores = types.Int64Value(pool.Spec.Template.CPUCores)+ m.Memory = types.StringValue(pool.Spec.Template.Memory)+ m.ContainerDiskImage = types.StringValue(pool.Spec.Template.ContainerDiskImage)+ imagePullSecret := pool.Spec.Template.ImagePullSecret+ if imagePullSecret == "" {+ imagePullSecret = "ecr-credentials"+ }+ m.ImagePullSecret = types.StringValue(imagePullSecret)+ runtime := pool.Spec.Template.Runtime+ if runtime == "" {+ runtime = "kubevirt"+ }+ m.Runtime = types.StringValue(runtime)+ firmware := pool.Spec.Template.Firmware+ if firmware == "" {+ firmware = "bios"+ }+ m.Firmware = types.StringValue(firmware)+ m.ReadinessProbeJSON = encodeProbe(pool.Spec.Template.Probes["readinessProbe"], diagnostics)+ m.LivenessProbeJSON = encodeProbe(pool.Spec.Template.Probes["livenessProbe"], diagnostics)+ serviceType := serviceObjectType()+ serviceValues := make([]attr.Value, 0, len(pool.Spec.Services))+ for _, value := range pool.Spec.Services {+ protocol := value.Protocol+ if protocol == "" {+ protocol = "TCP"+ }+ object, diags := types.ObjectValue(serviceType, map[string]attr.Value{"name": types.StringValue(value.Name), "target_port": types.Int64Value(value.TargetPort), "protocol": types.StringValue(protocol)})+ diagnostics.Append(diags...)+ serviceValues = append(serviceValues, object)+ }+ services, diags := types.SetValue(types.ObjectType{AttrTypes: serviceType}, serviceValues)+ diagnostics.Append(diags...)+ m.Services = services+ if pool.Spec.Autoscaling == nil {+ m.Autoscaling = types.ObjectNull(autoscalingObjectType())+ } else {+ object, diags := types.ObjectValue(autoscalingObjectType(), map[string]attr.Value{"min_pool_size": types.Int64Value(pool.Spec.Autoscaling.MinPoolSize), "initial_pool_size": types.Int64Value(pool.Spec.Autoscaling.InitialPoolSize), "max_pool_size": types.Int64Value(pool.Spec.Autoscaling.MaxPoolSize)})+ diagnostics.Append(diags...)+ m.Autoscaling = object+ }+ m.Phase = types.StringValue(pool.Status.Phase)+ m.TotalCount = types.Int64Value(pool.Status.TotalCount)+ m.AvailableCount = types.Int64Value(pool.Status.AvailableCount)+ m.ClaimedCount = types.Int64Value(pool.Status.ClaimedCount)+}++func decodeProbe(name string, value jsontypes.Normalized, probes map[string]any, diagnostics *diag.Diagnostics) {+ if value.IsNull() || value.IsUnknown() || value.ValueString() == "" {+ return+ }+ var decoded any+ if err := json.Unmarshal([]byte(value.ValueString()), &decoded); err != nil {+ diagnostics.AddError("Invalid probe JSON", err.Error())+ return+ }+ probes[name] = decoded+}+func encodeProbe(value any, diagnostics *diag.Diagnostics) jsontypes.Normalized {+ if value == nil {+ return jsontypes.NewNormalizedNull()+ }+ encoded, err := json.Marshal(value)+ if err != nil {+ diagnostics.AddError("Unable to encode probe JSON", err.Error())+ return jsontypes.NewNormalizedNull()+ }+ return jsontypes.NewNormalizedValue(string(encoded))+}++var _ resource.Resource = (*poolResource)(nil)+var _ resource.ResourceWithConfigure = (*poolResource)(nil)+var _ resource.ResourceWithImportState = (*poolResource)(nil)diff --git a/libs/fleet/terraform-provider-cyclops/internal/provider/pool_resource_acc_test.go b/libs/fleet/terraform-provider-cyclops/internal/provider/pool_resource_acc_test.gonew file mode 100644index 0000000000..d819883205--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/internal/provider/pool_resource_acc_test.go@@ -0,0 +1,240 @@+//go:build acceptance++package provider_test++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "testing"++ "github.com/hashicorp/terraform-plugin-framework/providerserver"+ "github.com/hashicorp/terraform-plugin-go/tfprotov6"+ "github.com/hashicorp/terraform-plugin-testing/helper/resource"+ "github.com/hashicorp/terraform-plugin-testing/terraform"+ cyclopsprovider "github.com/trycua/terraform-provider-cyclops/internal/provider"+ corev1 "k8s.io/api/core/v1"+ apierrors "k8s.io/apimachinery/pkg/api/errors"+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"+ "k8s.io/apimachinery/pkg/runtime/schema"+ "k8s.io/apimachinery/pkg/types"+ "k8s.io/client-go/dynamic"+ "k8s.io/client-go/kubernetes"+ "sigs.k8s.io/controller-runtime/pkg/envtest"+)++var poolGVR = schema.GroupVersionResource{Group: "cua.ai", Version: "v1", Resource: "osgymworkspacepools"}++func TestAccPoolLifecycle(t *testing.T) {+ if os.Getenv("TF_ACC") == "" {+ t.Skip("TF_ACC must be set for acceptance tests")+ }+ if os.Getenv("KUBEBUILDER_ASSETS") == "" {+ t.Skip("KUBEBUILDER_ASSETS must point to envtest binaries")+ }++ testEnvironment := &envtest.Environment{+ CRDDirectoryPaths: []string{"../../../rbac-e2e/testdata"},+ ErrorIfCRDPathMissing: true,+ }+ config, err := testEnvironment.Start()+ if err != nil {+ t.Fatalf("start envtest: %v", err)+ }+ t.Cleanup(func() {+ if err := testEnvironment.Stop(); err != nil {+ t.Errorf("stop envtest: %v", err)+ }+ })++ clientset, err := kubernetes.NewForConfig(config)+ if err != nil {+ t.Fatal(err)+ }+ dynamicClient, err := dynamic.NewForConfig(config)+ if err != nil {+ t.Fatal(err)+ }+ apiServer := newCyclopsTestServer(t, clientset, dynamicClient)+ defer apiServer.Close()++ providerConfig := fmt.Sprintf(`+provider "cyclops" {+ endpoint = %q+ client_id = "terraform-e2e"+ client_secret = "terraform-secret"+ token_url = %q+}+`, apiServer.URL, apiServer.URL+"/token")++ resource.Test(t, resource.TestCase{+ ProtoV6ProviderFactories: map[string]func() (tfprotov6.ProviderServer, error){+ "cyclops": providerserver.NewProtocol6WithError(cyclopsprovider.New("test")()),+ },+ CheckDestroy: func(_ *terraform.State) error {+ _, err := dynamicClient.Resource(poolGVR).Namespace("terraform-e2e").Get(context.Background(), "terraform-e2e", metav1.GetOptions{})+ if err == nil {+ return fmt.Errorf("pool still exists after destroy")+ }+ return nil+ },+ Steps: []resource.TestStep{+ {+ Config: providerConfig + poolConfig(1, "4Gi"),+ Check: resource.ComposeAggregateTestCheckFunc(+ resource.TestCheckResourceAttr("cyclops_pool.test", "name", "terraform-e2e"),+ resource.TestCheckResourceAttr("cyclops_pool.test", "namespace", "terraform-e2e"),+ resource.TestCheckResourceAttr("cyclops_pool.test", "replicas", "1"),+ resource.TestCheckResourceAttr("cyclops_pool.test", "service.#", "1"),+ resource.TestCheckResourceAttr("cyclops_pool.test", "autoscaling.max_pool_size", "5"),+ ),+ },+ {+ Config: providerConfig + poolConfig(2, "8Gi"),+ Check: resource.ComposeAggregateTestCheckFunc(+ resource.TestCheckResourceAttr("cyclops_pool.test", "replicas", "2"),+ resource.TestCheckResourceAttr("cyclops_pool.test", "memory", "8Gi"),+ ),+ },+ {+ ResourceName: "cyclops_pool.test",+ ImportState: true,+ ImportStateVerify: true,+ },+ },+ })+}++func poolConfig(replicas int, memory string) string {+ return fmt.Sprintf(`+resource "cyclops_pool" "test" {+ name = "terraform-e2e"+ replicas = %d+ cpu_cores = 2+ memory = %q+ container_disk_image = "example.invalid/cyclops/e2e:latest"++ autoscaling {+ min_pool_size = 0+ initial_pool_size = 1+ max_pool_size = 5+ }++ service {+ name = "ssh"+ target_port = 22+ protocol = "TCP"+ }+}+`, replicas, memory)+}++func newCyclopsTestServer(t *testing.T, clientset *kubernetes.Clientset, dynamicClient dynamic.Interface) *httptest.Server {+ t.Helper()+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/token" {+ clientID, secret, ok := r.BasicAuth()+ if !ok || clientID != "terraform-e2e" || secret != "terraform-secret" {+ http.Error(w, "invalid client credentials", http.StatusUnauthorized)+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{"access_token": "terraform-e2e-token", "expires_in": 300})+ return+ }+ if r.Header.Get("Authorization") != "Bearer terraform-e2e-token" {+ http.Error(w, "missing bearer token", http.StatusUnauthorized)+ return+ }++ ctx := r.Context()+ if r.URL.Path == "/api/namespaces" && r.Method == http.MethodPost {+ var request struct {+ Name string `json:"name"`+ }+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }+ _, err := clientset.CoreV1().Namespaces().Create(ctx, namespaceObject(request.Name), metav1.CreateOptions{})+ writeKubernetesResult(w, http.StatusCreated, nil, err)+ return+ }+ if strings.HasPrefix(r.URL.Path, "/api/namespaces/") && r.Method == http.MethodDelete {+ name := strings.TrimPrefix(r.URL.Path, "/api/namespaces/")+ err := clientset.CoreV1().Namespaces().Delete(ctx, name, metav1.DeleteOptions{})+ writeKubernetesResult(w, http.StatusNoContent, nil, err)+ return+ }++ const prefix = "/api/k8s/apis/cua.ai/v1/namespaces/"+ if !strings.HasPrefix(r.URL.Path, prefix) {+ http.NotFound(w, r)+ return+ }+ parts := strings.Split(strings.TrimPrefix(r.URL.Path, prefix), "/")+ if len(parts) < 2 || parts[1] != "osgymworkspacepools" {+ http.NotFound(w, r)+ return+ }+ namespace := parts[0]+ pools := dynamicClient.Resource(poolGVR).Namespace(namespace)+ switch {+ case r.Method == http.MethodPost && len(parts) == 2:+ var object unstructured.Unstructured+ if err := json.NewDecoder(r.Body).Decode(&object.Object); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }+ created, err := pools.Create(ctx, &object, metav1.CreateOptions{})+ writeKubernetesResult(w, http.StatusCreated, created, err)+ case r.Method == http.MethodGet && len(parts) == 3:+ object, err := pools.Get(ctx, parts[2], metav1.GetOptions{})+ writeKubernetesResult(w, http.StatusOK, object, err)+ case r.Method == http.MethodPatch && len(parts) == 3:+ body, err := io.ReadAll(r.Body)+ if err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }+ object, err := pools.Patch(ctx, parts[2], types.MergePatchType, body, metav1.PatchOptions{})+ writeKubernetesResult(w, http.StatusOK, object, err)+ case r.Method == http.MethodDelete && len(parts) == 3:+ err := pools.Delete(ctx, parts[2], metav1.DeleteOptions{})+ writeKubernetesResult(w, http.StatusNoContent, nil, err)+ default:+ http.NotFound(w, r)+ }+ }))+}++func namespaceObject(name string) *corev1.Namespace {+ return &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: name}}+}++func writeKubernetesResult(w http.ResponseWriter, successStatus int, value any, err error) {+ if err != nil {+ status := http.StatusInternalServerError+ if apierrors.IsNotFound(err) {+ status = http.StatusNotFound+ } else if apierrors.IsAlreadyExists(err) {+ status = http.StatusConflict+ }+ writeJSON(w, status, map[string]string{"error": err.Error()})+ return+ }+ writeJSON(w, successStatus, value)+}++func writeJSON(w http.ResponseWriter, status int, value any) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ if value != nil {+ _ = json.NewEncoder(w).Encode(value)+ }+}diff --git a/libs/fleet/terraform-provider-cyclops/internal/provider/provider.go b/libs/fleet/terraform-provider-cyclops/internal/provider/provider.gonew file mode 100644index 0000000000..0185cd45fa--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/internal/provider/provider.go@@ -0,0 +1,88 @@+package provider++import (+ "context"+ "os"++ "github.com/hashicorp/terraform-plugin-framework/datasource"+ "github.com/hashicorp/terraform-plugin-framework/diag"+ "github.com/hashicorp/terraform-plugin-framework/provider"+ "github.com/hashicorp/terraform-plugin-framework/provider/schema"+ "github.com/hashicorp/terraform-plugin-framework/resource"+ "github.com/hashicorp/terraform-plugin-framework/types"+ "github.com/hashicorp/terraform-plugin-framework/types/basetypes"+ "github.com/trycua/terraform-provider-cyclops/internal/client"+)++type cyclopsProvider struct{ version string }++type providerModel struct {+ Endpoint types.String `tfsdk:"endpoint"`+ AccessToken types.String `tfsdk:"access_token"`+ ClientID types.String `tfsdk:"client_id"`+ ClientSecret types.String `tfsdk:"client_secret"`+ TokenURL types.String `tfsdk:"token_url"`+}++func New(version string) func() provider.Provider {+ return func() provider.Provider { return &cyclopsProvider{version: version} }+}++func (p *cyclopsProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {+ resp.TypeName = "cyclops"+ resp.Version = p.version+}++func (p *cyclopsProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {+ resp.Schema = schema.Schema{+ Description: "Manage Cyclops computer-use pools.",+ Attributes: map[string]schema.Attribute{+ "endpoint": schema.StringAttribute{Required: true, Description: "Cyclops base URL, for example https://cyclops.example.com."},+ "access_token": schema.StringAttribute{Optional: true, Sensitive: true, Description: "Bearer token. May also be set with CYCLOPS_ACCESS_TOKEN."},+ "client_id": schema.StringAttribute{Optional: true, Description: "Cyclops user-key client ID. May also be set with CYCLOPS_CLIENT_ID."},+ "client_secret": schema.StringAttribute{Optional: true, Sensitive: true, Description: "Cyclops user-key client secret. May also be set with CYCLOPS_CLIENT_SECRET."},+ "token_url": schema.StringAttribute{Optional: true, Description: "OAuth token endpoint returned with the Cyclops user key. May also be set with CYCLOPS_TOKEN_URL."},+ },+ }+}++func (p *cyclopsProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {+ var data providerModel+ resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)+ if resp.Diagnostics.HasError() {+ return+ }+ value := func(config types.String, env string) string {+ if !config.IsNull() && !config.IsUnknown() && config.ValueString() != "" {+ return config.ValueString()+ }+ return os.Getenv(env)+ }+ apiClient, err := client.New(client.Config{+ Endpoint: value(data.Endpoint, "CYCLOPS_ENDPOINT"), AccessToken: value(data.AccessToken, "CYCLOPS_ACCESS_TOKEN"),+ ClientID: value(data.ClientID, "CYCLOPS_CLIENT_ID"), ClientSecret: value(data.ClientSecret, "CYCLOPS_CLIENT_SECRET"),+ TokenURL: value(data.TokenURL, "CYCLOPS_TOKEN_URL"),+ })+ if err != nil {+ resp.Diagnostics.AddError("Invalid Cyclops provider configuration", err.Error())+ return+ }+ resp.DataSourceData = apiClient+ resp.ResourceData = apiClient+}++func (p *cyclopsProvider) Resources(_ context.Context) []func() resource.Resource {+ return []func() resource.Resource{NewPoolResource}+}++func (p *cyclopsProvider) DataSources(_ context.Context) []func() datasource.DataSource { return nil }++var _ provider.Provider = (*cyclopsProvider)(nil)++func objectValue(ctx context.Context, object types.Object, target any, diagnostics *diag.Diagnostics) bool {+ if object.IsNull() || object.IsUnknown() {+ return false+ }+ diagnostics.Append(object.As(ctx, target, basetypes.ObjectAsOptions{})...)+ return !diagnostics.HasError()+}diff --git a/libs/fleet/terraform-provider-cyclops/main.go b/libs/fleet/terraform-provider-cyclops/main.gonew file mode 100644index 0000000000..9196220a1f--- /dev/null+++ b/libs/fleet/terraform-provider-cyclops/main.go@@ -0,0 +1,26 @@+package main++import (+ "context"+ "flag"+ "log"++ "github.com/hashicorp/terraform-plugin-framework/providerserver"+ "github.com/trycua/terraform-provider-cyclops/internal/provider"+)++var version = "dev"++func main() {+ var debug bool+ flag.BoolVar(&debug, "debug", false, "run the provider with debugger support")+ flag.Parse()++ opts := providerserver.ServeOpts{+ Address: "registry.terraform.io/trycua/cyclops",+ Debug: debug,+ }+ if err := providerserver.Serve(context.Background(), provider.New(version), opts); err != nil {+ log.Fatal(err)+ }+}diff --git a/libs/fleet/tsconfig.json b/libs/fleet/tsconfig.jsonnew file mode 100644index 0000000000..b4eea310ca--- /dev/null+++ b/libs/fleet/tsconfig.json@@ -0,0 +1,20 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "jsx": "react-jsx",+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noFallthroughCasesInSwitch": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "resolveJsonModule": true,+ "isolatedModules": true,+ "useDefineForClassFields": true,+ "noEmit": true+ },+ "include": ["src"]+}diff --git a/libs/fleet/vite.config.ts b/libs/fleet/vite.config.tsnew file mode 100644index 0000000000..78b63fbe45--- /dev/null+++ b/libs/fleet/vite.config.ts@@ -0,0 +1,66 @@+import { defineConfig } from "vite"+import react from "@vitejs/plugin-react"++// API requests in dev are proxied to a port-forwarded cyclops-ctrl on+// localhost:8080:+// kubectl -n cyclops port-forward svc/cyclops-ctrl 8080:8080+const CYCLOPS_CTRL = process.env.CYCLOPS_CTRL ?? "http://localhost:8080"++// /api/k8s and /api/orch are served by the cyclops-cs backend sidecar+// (Keycloak SSO + OPA), which isn't reachable from a laptop. In dev,+// route them through the deployed cyclops-cs Tailscale ingress so the+// in-cluster nginx forwards to the sidecar.+const ORCH_API = process.env.ORCH_API ?? "https://cyclops-cs.tail204509.ts.net"++export default defineConfig({+ plugins: [react()],+ // @novnc/novnc (1.7+) uses top-level await; es2020 (esbuild's default here)+ // rejects it. es2022 is supported by all evergreen browsers the app targets.+ build: { target: "es2022" },+ esbuild: { target: "es2022" },+ server: {+ port: 5180,+ proxy: {+ // More specific /api/* rules must come before the catchall /api so+ // they're matched first.+ "/api/k8s": {+ target: ORCH_API,+ changeOrigin: true,+ secure: true,+ },+ "/api/orch": {+ target: ORCH_API,+ changeOrigin: true,+ secure: true,+ },+ "/api/keys": {+ target: ORCH_API,+ changeOrigin: true,+ secure: true,+ },+ "/api/gateway": {+ target: ORCH_API,+ changeOrigin: true,+ secure: true,+ },+ "/api/swagger": {+ target: ORCH_API,+ changeOrigin: true,+ secure: true,+ },+ "/api": {+ target: CYCLOPS_CTRL,+ changeOrigin: true,+ rewrite: p => p.replace(/^\/api/, ""),+ },+ },+ },+ optimizeDeps: {+ include: ["@cloudscape-design/components"],+ // Dep pre-bundling (dev server) has its OWN esbuild target that ignores+ // build.target/esbuild.target above — it defaults to es2020, which rejects+ // @novnc/novnc's top-level await and crashes `vite dev` (Playwright then+ // sees ERR_CONNECTION_REFUSED). Pin it to es2022 too.+ esbuildOptions: { target: "es2022" },+ },+})