Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cyclops-cs): add GitHub OIDC trust policies (#5249)

r33drichardsbec308671745
diff --git a/libs/fleet/backend/auth/auth.go b/libs/fleet/backend/auth/auth.go
index 39d0fb10e0..983cb08f72 100644
--- a/libs/fleet/backend/auth/auth.go
+++ b/libs/fleet/backend/auth/auth.go
@@ -20,6 +20,7 @@ import (
"log"
"log/slog"
"net/http"
+ "slices"
"strings"
"time"
@@ -30,14 +31,33 @@ import (
)
var (
- authConfig *config.AuthConfiguration
- cachedJWKS *keyfunc.JWKS
+ authConfig *config.AuthConfiguration
+ cachedKeycloakJWKS *keyfunc.JWKS
+ cachedGitHubJWKS *keyfunc.JWKS
)
+type GitHubTrustPolicy struct {
+ ID string
+ OwnerSub string
+ Repository string
+ AllowedNamespaces []string
+ Enabled bool
+}
+
+type GitHubTrustResolver interface {
+ ResolveGitHubTrustPolicies(ctx context.Context, repository string) ([]GitHubTrustPolicy, error)
+}
+
+var githubTrustResolver GitHubTrustResolver
+
+func SetGitHubTrustResolver(resolver GitHubTrustResolver) {
+ githubTrustResolver = resolver
+}
+
// 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{
+ keycloakJWKS, 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 {
@@ -56,7 +76,30 @@ func Init(c *config.AuthConfiguration) error {
if err != nil {
return fmt.Errorf("fetch JWKS at %s: %w", c.JWKSUri, err)
}
- cachedJWKS = jwks
+ cachedKeycloakJWKS = keycloakJWKS
+ cachedGitHubJWKS = nil
+ if c.GitHubOIDCEnabled && c.GitHubOIDCJWKSUri != "" {
+ githubJWKS, err := keyfunc.Get(c.GitHubOIDCJWKSUri, 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("GitHub JWKS refresh", "error", err.Error())
+ },
+ })
+ if err != nil {
+ return fmt.Errorf("fetch GitHub JWKS at %s: %w", c.GitHubOIDCJWKSUri, err)
+ }
+ cachedGitHubJWKS = githubJWKS
+ }
return nil
}
@@ -89,7 +132,26 @@ func sliceContains[K comparable](s []K, e K) bool {
// 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,
+ return validateWithContext(context.Background(), raw)
+}
+
+func validateWithContext(ctx context.Context, raw string) (*User, error) {
+ claims, err := parseUnverifiedClaims(raw)
+ if err != nil {
+ return nil, err
+ }
+ switch iss := str(claims, "iss"); {
+ case iss == authConfig.Issuer:
+ return validateKeycloak(raw)
+ case authConfig != nil && authConfig.GitHubOIDCEnabled && iss == authConfig.GitHubOIDCIssuer:
+ return validateGitHub(ctx, raw)
+ default:
+ return nil, fmt.Errorf("unsupported token issuer")
+ }
+}
+
+func validateKeycloak(raw string) (*User, error) {
+ tok, err := jwt.Parse(raw, cachedKeycloakJWKS.Keyfunc,
jwt.WithLeeway(30*time.Second),
jwt.WithIssuer(authConfig.Issuer),
jwt.WithValidMethods(authConfig.SigningAlgs),
@@ -108,19 +170,100 @@ func validate(raw string) (*User, error) {
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"),
+ ID: str(claims, "sub"),
+ Name: str(claims, "name"),
+ Email: str(claims, "email"),
+ AZP: str(claims, "azp"),
+ Namespace: str(claims, "namespace"),
+ PrincipalType: PrincipalTypeUser,
Claims: map[string]string{
"preferred_username": str(claims, "preferred_username"),
- "user_sub": str(claims, "user_sub"),
- "user_groups": str(claims, "user_groups"),
+ "user_sub": str(claims, "user_sub"),
+ "user_groups": str(claims, "user_groups"),
+ },
+ }, nil
+}
+
+func validateGitHub(ctx context.Context, raw string) (*User, error) {
+ if cachedGitHubJWKS == nil {
+ return nil, fmt.Errorf("github oidc disabled")
+ }
+ tok, err := jwt.Parse(raw, cachedGitHubJWKS.Keyfunc,
+ jwt.WithLeeway(30*time.Second),
+ jwt.WithIssuer(authConfig.GitHubOIDCIssuer),
+ jwt.WithAudience(authConfig.GitHubOIDCAudience),
+ jwt.WithValidMethods(authConfig.GitHubOIDCAlgs),
+ )
+ if err != nil {
+ return nil, err
+ }
+ if !tok.Valid {
+ return nil, fmt.Errorf("invalid token")
+ }
+ claims, ok := tok.Claims.(jwt.MapClaims)
+ if !ok {
+ return nil, fmt.Errorf("unexpected claims type")
+ }
+ repository := str(claims, "repository")
+ if repository == "" {
+ return nil, fmt.Errorf("missing repository claim")
+ }
+ if githubTrustResolver == nil {
+ return nil, fmt.Errorf("github trust resolver not configured")
+ }
+ policies, err := githubTrustResolver.ResolveGitHubTrustPolicies(ctx, repository)
+ if err != nil {
+ return nil, err
+ }
+ ownerSub := ""
+ allowedSet := map[string]struct{}{}
+ policyIDs := make([]string, 0, len(policies))
+ for _, policy := range policies {
+ if !policy.Enabled || policy.Repository != repository {
+ continue
+ }
+ if ownerSub == "" {
+ ownerSub = policy.OwnerSub
+ }
+ if ownerSub != policy.OwnerSub {
+ return nil, fmt.Errorf("conflicting github trust policies")
+ }
+ policyIDs = append(policyIDs, policy.ID)
+ for _, ns := range policy.AllowedNamespaces {
+ allowedSet[ns] = struct{}{}
+ }
+ }
+ if ownerSub == "" {
+ return nil, fmt.Errorf("no matching github trust policy")
+ }
+ allowedNamespaces := make([]string, 0, len(allowedSet))
+ for ns := range allowedSet {
+ allowedNamespaces = append(allowedNamespaces, ns)
+ }
+ slices.Sort(allowedNamespaces)
+ slices.Sort(policyIDs)
+ return &User{
+ ID: ownerSub,
+ AZP: "github-oidc",
+ PrincipalType: PrincipalTypeGitHubOIDC,
+ Repository: repository,
+ AllowedNamespaces: allowedNamespaces,
+ PolicyIDs: policyIDs,
+ Claims: map[string]string{
+ "github_sub": str(claims, "sub"),
},
}, nil
}
+func parseUnverifiedClaims(raw string) (jwt.MapClaims, error) {
+ parser := jwt.NewParser()
+ claims := jwt.MapClaims{}
+ if _, _, err := parser.ParseUnverified(raw, claims); err != nil {
+ return nil, err
+ }
+ return claims, nil
+}
+
func str(c jwt.MapClaims, k string) string {
if v, ok := c[k]; ok {
if s, ok := v.(string); ok {
diff --git a/libs/fleet/backend/auth/authz.rego b/libs/fleet/backend/auth/authz.rego
index 7e54899c44..f6d2410c6c 100644
--- a/libs/fleet/backend/auth/authz.rego
+++ b/libs/fleet/backend/auth/authz.rego
@@ -100,6 +100,30 @@ allow {
is_interactive_client
}
+allow {
+ input.route == "/api/namespaces"
+ input.user.sub != ""
+ input.user.principal_type == "github_oidc"
+}
+
+allow {
+ input.route == "/api/namespaces/{name}"
+ input.user.sub != ""
+ input.user.principal_type == "github_oidc"
+}
+
+allow {
+ input.route == "/api/github-trust-policies"
+ input.user.sub != ""
+ is_interactive_client
+}
+
+allow {
+ input.route == "/api/github-trust-policies/{id}"
+ input.user.sub != ""
+ is_interactive_client
+}
+
# /api/k8s/{path...} — kubectl-proxy passthrough.
#
# Any exact interactive client may read customer-facing resources (their pools, the pods
@@ -122,6 +146,13 @@ allow {
is_admin
}
+allow {
+ input.route == "/api/k8s/{path...}"
+ input.user.sub != ""
+ input.user.principal_type == "github_oidc"
+ is_github_k8s_candidate(input.params.path)
+}
+
# is_infra_k8s_path matches the kubectl-proxy paths that expose cluster
# internals. `input.params.path` is the captured {path...} segment with no
# leading slash (e.g. "api/v1/nodes"); query strings are not included.
@@ -168,6 +199,9 @@ is_infra_k8s_path(path) {
parts[3] == "tenants"
}
+is_github_k8s_candidate(path) { startswith(path, "apis/cua.ai/v1/namespaces/") }
+is_github_k8s_candidate(path) { startswith(path, "apis/osgym.cua.ai/v1alpha1/namespaces/") }
+
# /api/orch/{namespace}/{service}/{path...} — per-namespace orchestrator
# catalog read. Exact interactive clients only; namespace + service must be DNS-1123 labels.
# Like /api/svc, this proxy dials Service DNS directly, so namespace
diff --git a/libs/fleet/backend/auth/github_oidc_test.go b/libs/fleet/backend/auth/github_oidc_test.go
new file mode 100644
index 0000000000..573821b54b
--- /dev/null
+++ b/libs/fleet/backend/auth/github_oidc_test.go
@@ -0,0 +1,176 @@
+package auth
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/rsa"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "cyclops-cs-backend/config"
+
+ jwt "github.com/golang-jwt/jwt/v5"
+)
+
+const (
+ testGitHubIssuer = "https://token.actions.githubusercontent.com"
+ testGitHubAudience = "cyclops-cs"
+ testGitHubKeyID = "github-test-key"
+)
+
+func TestValidate_GitHubOIDCResolvesOwnerAndNamespaces(t *testing.T) {
+ signingKey, jwksURL := newGitHubJWKS(t)
+ t.Cleanup(func() {
+ SetGitHubTrustResolver(nil)
+ })
+ if err := Init(&config.AuthConfiguration{
+ Issuer: "https://issuer.example.test/realms/cyclops-cs",
+ JWKSUri: jwksURL,
+ SigningAlgs: []string{"RS256"},
+ SPAClientID: "cyclops-cs-spa",
+ KeyClientPfx: "key-",
+ UserKeyClientPfx: "ukey-",
+ GitHubOIDCIssuer: testGitHubIssuer,
+ GitHubOIDCJWKSUri: jwksURL,
+ GitHubOIDCAudience: testGitHubAudience,
+ GitHubOIDCEnabled: true,
+ GitHubOIDCAlgs: []string{"RS256"},
+ }); err != nil {
+ t.Fatalf("Init err = %v", err)
+ }
+ SetGitHubTrustResolver(githubTrustResolverFunc(func(ctx context.Context, repository string) ([]GitHubTrustPolicy, error) {
+ _ = ctx
+ if repository != "trycua/cloud" {
+ t.Fatalf("repository = %q", repository)
+ }
+ return []GitHubTrustPolicy{
+ {ID: "p1", OwnerSub: "user-123", Repository: "trycua/cloud", AllowedNamespaces: []string{"ns-a"}, Enabled: true},
+ {ID: "p2", OwnerSub: "user-123", Repository: "trycua/cloud", AllowedNamespaces: []string{"ns-b"}, Enabled: true},
+ }, nil
+ }))
+
+ raw := signGitHubToken(t, signingKey, jwt.MapClaims{
+ "iss": testGitHubIssuer,
+ "aud": testGitHubAudience,
+ "sub": "repo:trycua/cloud:ref:refs/heads/main",
+ "repository": "trycua/cloud",
+ "exp": time.Now().Add(time.Hour).Unix(),
+ "iat": time.Now().Add(-time.Minute).Unix(),
+ })
+
+ user, err := validate(raw)
+ if err != nil {
+ t.Fatalf("validate err = %v", err)
+ }
+ if user.PrincipalType != PrincipalTypeGitHubOIDC {
+ t.Fatalf("principal_type = %q", user.PrincipalType)
+ }
+ if user.ID != "user-123" {
+ t.Fatalf("owner_sub = %q", user.ID)
+ }
+ if got, want := user.AllowedNamespaces, []string{"ns-a", "ns-b"}; len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
+ t.Fatalf("allowed_namespaces = %#v, want %#v", got, want)
+ }
+}
+
+func TestValidate_GitHubOIDCFailsOnCrossOwnerCollision(t *testing.T) {
+ signingKey, jwksURL := newGitHubJWKS(t)
+ t.Cleanup(func() {
+ SetGitHubTrustResolver(nil)
+ })
+ if err := Init(&config.AuthConfiguration{
+ Issuer: "https://issuer.example.test/realms/cyclops-cs",
+ JWKSUri: jwksURL,
+ SigningAlgs: []string{"RS256"},
+ SPAClientID: "cyclops-cs-spa",
+ KeyClientPfx: "key-",
+ UserKeyClientPfx: "ukey-",
+ GitHubOIDCIssuer: testGitHubIssuer,
+ GitHubOIDCJWKSUri: jwksURL,
+ GitHubOIDCAudience: testGitHubAudience,
+ GitHubOIDCEnabled: true,
+ GitHubOIDCAlgs: []string{"RS256"},
+ }); err != nil {
+ t.Fatalf("Init err = %v", err)
+ }
+ SetGitHubTrustResolver(githubTrustResolverFunc(func(ctx context.Context, repository string) ([]GitHubTrustPolicy, error) {
+ _ = ctx
+ _ = repository
+ return []GitHubTrustPolicy{
+ {ID: "p1", OwnerSub: "user-123", Repository: "trycua/cloud", AllowedNamespaces: []string{"ns-a"}, Enabled: true},
+ {ID: "p2", OwnerSub: "user-456", Repository: "trycua/cloud", AllowedNamespaces: []string{"ns-b"}, Enabled: true},
+ }, nil
+ }))
+
+ raw := signGitHubToken(t, signingKey, jwt.MapClaims{
+ "iss": testGitHubIssuer,
+ "aud": testGitHubAudience,
+ "sub": "repo:trycua/cloud:ref:refs/heads/main",
+ "repository": "trycua/cloud",
+ "exp": time.Now().Add(time.Hour).Unix(),
+ "iat": time.Now().Add(-time.Minute).Unix(),
+ })
+
+ if _, err := validate(raw); err == nil {
+ t.Fatal("expected cross-owner collision to fail")
+ }
+}
+
+type githubTrustResolverFunc func(context.Context, string) ([]GitHubTrustPolicy, error)
+
+func (fn githubTrustResolverFunc) ResolveGitHubTrustPolicies(ctx context.Context, repository string) ([]GitHubTrustPolicy, error) {
+ return fn(ctx, repository)
+}
+
+func newGitHubJWKS(t *testing.T) (*rsa.PrivateKey, string) {
+ t.Helper()
+ key, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ t.Fatalf("GenerateKey: %v", err)
+ }
+ jwksBody, err := json.Marshal(map[string]any{
+ "keys": []map[string]any{{
+ "kty": "RSA",
+ "use": "sig",
+ "alg": "RS256",
+ "kid": testGitHubKeyID,
+ "n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()),
+ "e": base64.RawURLEncoding.EncodeToString(bigEndianBytes(key.E)),
+ }},
+ })
+ if err != nil {
+ t.Fatalf("marshal jwks: %v", err)
+ }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write(jwksBody)
+ }))
+ t.Cleanup(server.Close)
+ return key, server.URL
+}
+
+func signGitHubToken(t *testing.T, key *rsa.PrivateKey, claims jwt.MapClaims) string {
+ t.Helper()
+ token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
+ token.Header["kid"] = testGitHubKeyID
+ raw, err := token.SignedString(key)
+ if err != nil {
+ t.Fatalf("SignedString: %v", err)
+ }
+ return raw
+}
+
+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/auth/middlewares.go b/libs/fleet/backend/auth/middlewares.go
index c420b8396e..d747dde291 100644
--- a/libs/fleet/backend/auth/middlewares.go
+++ b/libs/fleet/backend/auth/middlewares.go
@@ -351,7 +351,7 @@ func TokenAuthMiddleware(next http.Handler) http.Handler {
}
// ── JWT validation ─────────────────────────────────────────
- user, err := validate(raw)
+ user, err := validateWithContext(r.Context(), raw)
if err != nil {
result = err.Error()
writeJSONErr(w, http.StatusUnauthorized, "auth token is invalid")
@@ -429,11 +429,14 @@ func buildUserInput(user *User) map[string]any {
return map[string]any{}
}
return map[string]any{
- "sub": user.ID,
- "azp": user.AZP,
- "namespace": user.Namespace,
- "email": user.Email,
- "groups": user.Groups,
+ "sub": user.ID,
+ "azp": user.AZP,
+ "namespace": user.Namespace,
+ "email": user.Email,
+ "groups": user.Groups,
+ "principal_type": user.PrincipalType,
+ "repository": user.Repository,
+ "allowed_namespaces": user.AllowedNamespaces,
}
}
diff --git a/libs/fleet/backend/auth/user.go b/libs/fleet/backend/auth/user.go
index 8719c1e3c0..83957411a1 100644
--- a/libs/fleet/backend/auth/user.go
+++ b/libs/fleet/backend/auth/user.go
@@ -5,11 +5,20 @@ package auth
// 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
+ ID string // sub or mapped owner_sub for GitHub OIDC
+ 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
+ PrincipalType string
+ Repository string
+ AllowedNamespaces []string
+ PolicyIDs []string
}
+
+const (
+ PrincipalTypeUser = "user"
+ PrincipalTypeGitHubOIDC = "github_oidc"
+)
diff --git a/libs/fleet/backend/config/config.go b/libs/fleet/backend/config/config.go
index 4c0b5a4d5b..aee2ac1ed0 100644
--- a/libs/fleet/backend/config/config.go
+++ b/libs/fleet/backend/config/config.go
@@ -24,6 +24,7 @@ type Configuration struct {
Auth AuthConfiguration
Keycloak KeycloakConfiguration
Gateway GatewayConfiguration
+ Templates TemplatesConfiguration
Stripe StripeConfiguration
Metrics MetricsConfiguration
Telemetry TelemetryConfiguration
@@ -36,12 +37,17 @@ type WebServerConfiguration struct {
// 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-")
+ 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-")
+ GitHubOIDCEnabled bool
+ GitHubOIDCIssuer string
+ GitHubOIDCJWKSUri string
+ GitHubOIDCAudience string
+ GitHubOIDCAlgs []string
}
type KeycloakConfiguration struct {
@@ -72,6 +78,12 @@ type GatewayConfiguration struct {
ClusterDomain string
}
+// TemplatesConfiguration carries the Redis URL used by the original
+// GitHub trust-policy store. PR #5302 replaces this with DatabaseConfiguration.
+type TemplatesConfiguration struct {
+ RedisURL string
+}
+
type StripeConfiguration struct {
SecretKey string
WebhookSecret string
@@ -108,6 +120,9 @@ var specs = []flagSpec{
{"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"},
+ {"github.oidc-issuer", "github-oidc-issuer", "GITHUB_OIDC_ISSUER", "https://token.actions.githubusercontent.com", "GitHub Actions OIDC issuer"},
+ {"github.oidc-jwks-uri", "github-oidc-jwks-uri", "GITHUB_OIDC_JWKS_URI", "https://token.actions.githubusercontent.com/.well-known/jwks", "GitHub Actions OIDC JWKS URI"},
+ {"github.oidc-audience", "github-oidc-audience", "GITHUB_OIDC_AUDIENCE", "cyclops-cs", "Audience required on inbound GitHub OIDC tokens"},
{"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"},
@@ -117,6 +132,8 @@ var specs = []flagSpec{
{"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 GitHub trust-policy Redis URL fallback"},
+ {"templates.redis-url", "pool-templates-redis-url", "POOL_TEMPLATES_REDIS_URL", "", "GitHub trust-policy Redis URL (falls back to batch Redis)"},
{"stripe.secret-key", "stripe-secret-key", "STRIPE_SECRET_KEY", "", "Stripe secret key (server-only)"},
{"stripe.webhook-secret", "stripe-webhook-secret", "STRIPE_WEBHOOK_SECRET", "", "Stripe webhook signing secret"},
{"stripe.checkout-success-url", "stripe-checkout-success-url", "STRIPE_CHECKOUT_SUCCESS_URL", "", "Stripe Checkout success redirect URL"},
@@ -153,15 +170,25 @@ func LoadConfig() (*Configuration, error) {
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"),
+ 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"),
+ GitHubOIDCEnabled: true,
+ GitHubOIDCIssuer: viper.GetString("github.oidc-issuer"),
+ GitHubOIDCJWKSUri: viper.GetString("github.oidc-jwks-uri"),
+ GitHubOIDCAudience: viper.GetString("github.oidc-audience"),
+ GitHubOIDCAlgs: []string{"RS256"},
},
Keycloak: KeycloakConfiguration{
BaseURL: base,
@@ -182,6 +209,7 @@ func LoadConfig() (*Configuration, error) {
Port: viper.GetString("gateway.port"),
ClusterDomain: viper.GetString("gateway.cluster-domain"),
},
+ Templates: TemplatesConfiguration{RedisURL: templatesRedis},
Stripe: StripeConfiguration{
SecretKey: viper.GetString("stripe.secret-key"),
WebhookSecret: viper.GetString("stripe.webhook-secret"),
diff --git a/libs/fleet/backend/githubtrust/store.go b/libs/fleet/backend/githubtrust/store.go
new file mode 100644
index 0000000000..8dabf49830
--- /dev/null
+++ b/libs/fleet/backend/githubtrust/store.go
@@ -0,0 +1,222 @@
+package githubtrust
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/redis/go-redis/v9"
+)
+
+const (
+ keyPrefix = "ghtrust:policy:"
+ ownerIndexPrefix = "ghtrust:owner:"
+ repoIndexPrefix = "ghtrust:repo:"
+)
+
+type Store interface {
+ List(ctx context.Context, ownerSub string) ([]*Policy, error)
+ Create(ctx context.Context, policy *Policy) error
+ Get(ctx context.Context, ownerSub, id string) (*Policy, error)
+ Update(ctx context.Context, policy *Policy) error
+ Delete(ctx context.Context, ownerSub, id string) (bool, error)
+ ResolveByRepository(ctx context.Context, repository string) ([]*Policy, error)
+}
+
+type redisStore struct{ c *redis.Client }
+
+func policyKey(id string) string { return keyPrefix + id }
+func ownerKey(owner string) string { return ownerIndexPrefix + owner }
+func repoKey(repo string) string { return repoIndexPrefix + repo }
+
+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("githubtrust: redis ping failed at startup; will retry on demand", "err", err)
+ }
+ return &redisStore{c: c}, nil
+}
+
+func (s *redisStore) List(ctx context.Context, ownerSub string) ([]*Policy, error) {
+ ids, err := s.c.SMembers(ctx, ownerKey(ownerSub)).Result()
+ if err != nil {
+ return nil, fmt.Errorf("smembers owner index: %w", err)
+ }
+ out := make([]*Policy, 0, len(ids))
+ for _, id := range ids {
+ fields, err := s.c.HGetAll(ctx, policyKey(id)).Result()
+ if err != nil {
+ return nil, fmt.Errorf("hgetall %s: %w", id, err)
+ }
+ if len(fields) == 0 {
+ s.c.SRem(ctx, ownerKey(ownerSub), id)
+ continue
+ }
+ policy, err := hydrate(fields)
+ if err != nil {
+ return nil, err
+ }
+ if policy.OwnerSub != ownerSub {
+ continue
+ }
+ out = append(out, policy)
+ }
+ sortByUpdatedDesc(out)
+ return out, nil
+}
+
+func (s *redisStore) Create(ctx context.Context, policy *Policy) error {
+ now := time.Now().UTC()
+ if policy.ID == "" {
+ policy.ID = uuid.NewString()
+ }
+ if policy.CreatedAt.IsZero() {
+ policy.CreatedAt = now
+ }
+ policy.UpdatedAt = now
+ return s.save(ctx, nil, policy)
+}
+
+func (s *redisStore) Get(ctx context.Context, ownerSub, id string) (*Policy, error) {
+ fields, err := s.c.HGetAll(ctx, policyKey(id)).Result()
+ if err != nil {
+ return nil, fmt.Errorf("hgetall: %w", err)
+ }
+ if len(fields) == 0 {
+ return nil, nil
+ }
+ policy, err := hydrate(fields)
+ if err != nil {
+ return nil, err
+ }
+ if policy.OwnerSub != ownerSub {
+ return nil, nil
+ }
+ return policy, nil
+}
+
+func (s *redisStore) Update(ctx context.Context, policy *Policy) error {
+ current, err := s.Get(ctx, policy.OwnerSub, policy.ID)
+ if err != nil {
+ return err
+ }
+ if current == nil {
+ return redis.Nil
+ }
+ policy.CreatedAt = current.CreatedAt
+ policy.UpdatedAt = time.Now().UTC()
+ return s.save(ctx, current, policy)
+}
+
+func (s *redisStore) Delete(ctx context.Context, ownerSub, id string) (bool, error) {
+ current, err := s.Get(ctx, ownerSub, id)
+ if err != nil {
+ return false, err
+ }
+ if current == nil {
+ return false, nil
+ }
+ pipe := s.c.TxPipeline()
+ pipe.Del(ctx, policyKey(id))
+ pipe.SRem(ctx, ownerKey(ownerSub), id)
+ pipe.SRem(ctx, repoKey(current.Repository), id)
+ if _, err := pipe.Exec(ctx); err != nil {
+ return false, fmt.Errorf("delete policy: %w", err)
+ }
+ return true, nil
+}
+
+func (s *redisStore) ResolveByRepository(ctx context.Context, repository string) ([]*Policy, error) {
+ ids, err := s.c.SMembers(ctx, repoKey(repository)).Result()
+ if err != nil {
+ return nil, fmt.Errorf("smembers repo index: %w", err)
+ }
+ out := make([]*Policy, 0, len(ids))
+ for _, id := range ids {
+ fields, err := s.c.HGetAll(ctx, policyKey(id)).Result()
+ if err != nil {
+ return nil, fmt.Errorf("hgetall %s: %w", id, err)
+ }
+ if len(fields) == 0 {
+ s.c.SRem(ctx, repoKey(repository), id)
+ continue
+ }
+ policy, err := hydrate(fields)
+ if err != nil {
+ return nil, err
+ }
+ if policy.Repository != repository {
+ continue
+ }
+ out = append(out, policy)
+ }
+ sortByUpdatedDesc(out)
+ return out, nil
+}
+
+func (s *redisStore) save(ctx context.Context, previous, policy *Policy) error {
+ allowed, err := json.Marshal(policy.AllowedNamespaces)
+ if err != nil {
+ return fmt.Errorf("marshal allowed_namespaces: %w", err)
+ }
+ pipe := s.c.TxPipeline()
+ pipe.HSet(ctx, policyKey(policy.ID), map[string]any{
+ "id": policy.ID,
+ "owner_sub": policy.OwnerSub,
+ "name": policy.Name,
+ "repository": policy.Repository,
+ "allowed_namespaces": string(allowed),
+ "enabled": policy.Enabled,
+ "created_at": policy.CreatedAt.UTC().Format(time.RFC3339Nano),
+ "updated_at": policy.UpdatedAt.UTC().Format(time.RFC3339Nano),
+ })
+ pipe.SAdd(ctx, ownerKey(policy.OwnerSub), policy.ID)
+ pipe.SAdd(ctx, repoKey(policy.Repository), policy.ID)
+ if previous != nil && previous.Repository != "" && previous.Repository != policy.Repository {
+ pipe.SRem(ctx, repoKey(previous.Repository), policy.ID)
+ }
+ if _, err := pipe.Exec(ctx); err != nil {
+ return fmt.Errorf("save policy: %w", err)
+ }
+ return nil
+}
+
+func hydrate(fields map[string]string) (*Policy, error) {
+ policy := &Policy{
+ ID: fields["id"],
+ OwnerSub: fields["owner_sub"],
+ Name: fields["name"],
+ Repository: fields["repository"],
+ }
+ if v := fields["allowed_namespaces"]; v != "" {
+ if err := json.Unmarshal([]byte(v), &policy.AllowedNamespaces); err != nil {
+ return nil, fmt.Errorf("decode allowed_namespaces: %w", err)
+ }
+ }
+ if v := fields["enabled"]; v == "1" || v == "true" {
+ policy.Enabled = true
+ }
+ if v := fields["created_at"]; v != "" {
+ if parsed, err := time.Parse(time.RFC3339Nano, v); err == nil {
+ policy.CreatedAt = parsed
+ }
+ }
+ if v := fields["updated_at"]; v != "" {
+ if parsed, err := time.Parse(time.RFC3339Nano, v); err == nil {
+ policy.UpdatedAt = parsed
+ }
+ }
+ return policy, nil
+}
diff --git a/libs/fleet/backend/githubtrust/store_test.go b/libs/fleet/backend/githubtrust/store_test.go
new file mode 100644
index 0000000000..4651275c2f
--- /dev/null
+++ b/libs/fleet/backend/githubtrust/store_test.go
@@ -0,0 +1,47 @@
+package githubtrust
+
+import (
+ "testing"
+ "time"
+)
+
+func TestNormalizePolicyInput(t *testing.T) {
+ policy, err := NormalizePolicyInput(PolicyInput{
+ Name: "ci access",
+ Repository: "trycua/cloud",
+ AllowedNamespaces: []string{"ns-b", "ns-a", "ns-a"},
+ Enabled: true,
+ })
+ if err != nil {
+ t.Fatalf("NormalizePolicyInput err = %v", err)
+ }
+ if policy.Repository != "trycua/cloud" {
+ t.Fatalf("repository = %q", policy.Repository)
+ }
+ if got, want := policy.AllowedNamespaces, []string{"ns-a", "ns-b"}; len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
+ t.Fatalf("allowed_namespaces = %#v, want %#v", got, want)
+ }
+}
+
+func TestNormalizePolicyInput_RejectsInvalidRepository(t *testing.T) {
+ if _, err := NormalizePolicyInput(PolicyInput{
+ Name: "bad repo",
+ Repository: "not a repo",
+ AllowedNamespaces: []string{"ns-a"},
+ Enabled: true,
+ }); err == nil {
+ t.Fatal("expected invalid repository to fail")
+ }
+}
+
+func TestPolicySortNewestFirst(t *testing.T) {
+ policies := []*Policy{
+ {ID: "old", UpdatedAt: time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC)},
+ {ID: "new", UpdatedAt: time.Date(2026, 6, 3, 0, 0, 0, 0, time.UTC)},
+ {ID: "mid", UpdatedAt: time.Date(2026, 6, 2, 0, 0, 0, 0, time.UTC)},
+ }
+ sortByUpdatedDesc(policies)
+ if policies[0].ID != "new" || policies[1].ID != "mid" || policies[2].ID != "old" {
+ t.Fatalf("order = %s,%s,%s", policies[0].ID, policies[1].ID, policies[2].ID)
+ }
+}
diff --git a/libs/fleet/backend/githubtrust/types.go b/libs/fleet/backend/githubtrust/types.go
new file mode 100644
index 0000000000..4d0d2d6fe1
--- /dev/null
+++ b/libs/fleet/backend/githubtrust/types.go
@@ -0,0 +1,89 @@
+package githubtrust
+
+import (
+ "errors"
+ "regexp"
+ "slices"
+ "strings"
+ "time"
+)
+
+var (
+ repositoryPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$`)
+ namespacePattern = regexp.MustCompile(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$`)
+
+ ErrInvalidRepository = errors.New("repository must use owner/repo format")
+ ErrEmptyNamespaces = errors.New("allowed_namespaces must not be empty")
+ ErrInvalidNamespace = errors.New("allowed_namespaces must be DNS-1123 labels")
+)
+
+type Policy struct {
+ ID string `json:"id"`
+ OwnerSub string `json:"owner_sub"`
+ Name string `json:"name"`
+ Repository string `json:"repository"`
+ AllowedNamespaces []string `json:"allowed_namespaces"`
+ Enabled bool `json:"enabled"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+type PolicyInput struct {
+ Name string `json:"name"`
+ Repository string `json:"repository"`
+ AllowedNamespaces []string `json:"allowed_namespaces"`
+ Enabled bool `json:"enabled"`
+}
+
+func NormalizePolicyInput(input PolicyInput) (*Policy, error) {
+ repository := strings.TrimSpace(input.Repository)
+ if !repositoryPattern.MatchString(repository) {
+ return nil, ErrInvalidRepository
+ }
+ namespaces := normalizeNamespaces(input.AllowedNamespaces)
+ if len(namespaces) == 0 {
+ return nil, ErrEmptyNamespaces
+ }
+ for _, ns := range namespaces {
+ if !namespacePattern.MatchString(ns) || len(ns) > 63 {
+ return nil, ErrInvalidNamespace
+ }
+ }
+ return &Policy{
+ Name: strings.TrimSpace(input.Name),
+ Repository: repository,
+ AllowedNamespaces: namespaces,
+ Enabled: input.Enabled,
+ }, nil
+}
+
+func normalizeNamespaces(in []string) []string {
+ seen := map[string]struct{}{}
+ out := make([]string, 0, len(in))
+ for _, raw := range in {
+ ns := strings.TrimSpace(raw)
+ if ns == "" {
+ continue
+ }
+ if _, ok := seen[ns]; ok {
+ continue
+ }
+ seen[ns] = struct{}{}
+ out = append(out, ns)
+ }
+ slices.Sort(out)
+ return out
+}
+
+func sortByUpdatedDesc(policies []*Policy) {
+ slices.SortFunc(policies, func(a, b *Policy) int {
+ switch {
+ case a.UpdatedAt.After(b.UpdatedAt):
+ return -1
+ case a.UpdatedAt.Before(b.UpdatedAt):
+ return 1
+ default:
+ return strings.Compare(a.ID, b.ID)
+ }
+ })
+}
diff --git a/libs/fleet/backend/handlers/github_trust_policies.go b/libs/fleet/backend/handlers/github_trust_policies.go
new file mode 100644
index 0000000000..a38eaebe8f
--- /dev/null
+++ b/libs/fleet/backend/handlers/github_trust_policies.go
@@ -0,0 +1,225 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "time"
+
+ "cyclops-cs-backend/auth"
+ "cyclops-cs-backend/githubtrust"
+)
+
+type GitHubTrustPolicyResponse struct {
+ ID string `json:"id"`
+ OwnerSub string `json:"owner_sub"`
+ Name string `json:"name"`
+ Repository string `json:"repository"`
+ AllowedNamespaces []string `json:"allowed_namespaces"`
+ Enabled bool `json:"enabled"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+type GitHubTrustPolicyListResponse struct {
+ Policies []GitHubTrustPolicyResponse `json:"policies"`
+ OIDC struct {
+ Issuer string `json:"issuer"`
+ Audience string `json:"audience"`
+ } `json:"oidc"`
+}
+
+type GitHubTrustPolicyPatchRequest struct {
+ Name *string `json:"name"`
+ Repository *string `json:"repository"`
+ AllowedNamespaces *[]string `json:"allowed_namespaces"`
+ Enabled *bool `json:"enabled"`
+}
+
+func (h Handlers) ListGitHubTrustPolicies(w http.ResponseWriter, r *http.Request) {
+ user := currentUser(r)
+ if user == nil {
+ writeErr(w, http.StatusUnauthorized, "missing user")
+ return
+ }
+ if h.GitHubTrustPolicies == nil {
+ writeErr(w, http.StatusServiceUnavailable, "github trust policies are not configured")
+ return
+ }
+ policies, err := h.GitHubTrustPolicies.List(r.Context(), user.ID)
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, "failed to list github trust policies")
+ return
+ }
+ resp := GitHubTrustPolicyListResponse{
+ Policies: make([]GitHubTrustPolicyResponse, 0, len(policies)),
+ }
+ resp.OIDC.Issuer = h.AuthCfg.GitHubOIDCIssuer
+ resp.OIDC.Audience = h.AuthCfg.GitHubOIDCAudience
+ for _, policy := range policies {
+ resp.Policies = append(resp.Policies, policyResponse(policy))
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
+
+func (h Handlers) CreateGitHubTrustPolicy(w http.ResponseWriter, r *http.Request) {
+ user := currentUser(r)
+ if user == nil {
+ writeErr(w, http.StatusUnauthorized, "missing user")
+ return
+ }
+ if h.GitHubTrustPolicies == nil {
+ writeErr(w, http.StatusServiceUnavailable, "github trust policies are not configured")
+ return
+ }
+ var input githubtrust.PolicyInput
+ if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
+ writeErr(w, http.StatusBadRequest, "invalid body")
+ return
+ }
+ policy, err := githubtrust.NormalizePolicyInput(input)
+ if err != nil {
+ writeTrustPolicyValidationErr(w, err)
+ return
+ }
+ policy.OwnerSub = user.ID
+ if err := h.GitHubTrustPolicies.Create(r.Context(), policy); err != nil {
+ writeErr(w, http.StatusInternalServerError, "failed to create github trust policy")
+ return
+ }
+ writeJSON(w, http.StatusCreated, policyResponse(policy))
+}
+
+func (h Handlers) UpdateGitHubTrustPolicy(w http.ResponseWriter, r *http.Request) {
+ user := currentUser(r)
+ if user == nil {
+ writeErr(w, http.StatusUnauthorized, "missing user")
+ return
+ }
+ if h.GitHubTrustPolicies == nil {
+ writeErr(w, http.StatusServiceUnavailable, "github trust policies are not configured")
+ return
+ }
+ id := r.PathValue("id")
+ current, err := h.GitHubTrustPolicies.Get(r.Context(), user.ID, id)
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, "failed to load github trust policy")
+ return
+ }
+ if current == nil {
+ writeErr(w, http.StatusNotFound, "github trust policy not found")
+ return
+ }
+ var patch GitHubTrustPolicyPatchRequest
+ if err := json.NewDecoder(r.Body).Decode(&patch); err != nil {
+ writeErr(w, http.StatusBadRequest, "invalid body")
+ return
+ }
+ input := githubtrust.PolicyInput{
+ Name: current.Name,
+ Repository: current.Repository,
+ AllowedNamespaces: current.AllowedNamespaces,
+ Enabled: current.Enabled,
+ }
+ if patch.Name != nil {
+ input.Name = *patch.Name
+ }
+ if patch.Repository != nil {
+ input.Repository = *patch.Repository
+ }
+ if patch.AllowedNamespaces != nil {
+ input.AllowedNamespaces = *patch.AllowedNamespaces
+ }
+ if patch.Enabled != nil {
+ input.Enabled = *patch.Enabled
+ }
+ policy, err := githubtrust.NormalizePolicyInput(input)
+ if err != nil {
+ writeTrustPolicyValidationErr(w, err)
+ return
+ }
+ policy.ID = current.ID
+ policy.OwnerSub = current.OwnerSub
+ policy.CreatedAt = current.CreatedAt
+ if err := h.GitHubTrustPolicies.Update(r.Context(), policy); err != nil {
+ writeErr(w, http.StatusInternalServerError, "failed to update github trust policy")
+ return
+ }
+ writeJSON(w, http.StatusOK, policyResponse(policy))
+}
+
+func (h Handlers) DeleteGitHubTrustPolicy(w http.ResponseWriter, r *http.Request) {
+ user := currentUser(r)
+ if user == nil {
+ writeErr(w, http.StatusUnauthorized, "missing user")
+ return
+ }
+ if h.GitHubTrustPolicies == nil {
+ writeErr(w, http.StatusServiceUnavailable, "github trust policies are not configured")
+ return
+ }
+ found, err := h.GitHubTrustPolicies.Delete(r.Context(), user.ID, r.PathValue("id"))
+ if err != nil {
+ writeErr(w, http.StatusInternalServerError, "failed to delete github trust policy")
+ return
+ }
+ if !found {
+ writeErr(w, http.StatusNotFound, "github trust policy not found")
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+func NewGitHubTrustResolver(store githubtrust.Store) auth.GitHubTrustResolver {
+ if store == nil {
+ return nil
+ }
+ return githubTrustResolver{store: store}
+}
+
+type githubTrustResolver struct {
+ store githubtrust.Store
+}
+
+func (r githubTrustResolver) ResolveGitHubTrustPolicies(ctx context.Context, repository string) ([]auth.GitHubTrustPolicy, error) {
+ policies, err := r.store.ResolveByRepository(ctx, repository)
+ if err != nil {
+ return nil, err
+ }
+ out := make([]auth.GitHubTrustPolicy, 0, len(policies))
+ for _, policy := range policies {
+ out = append(out, auth.GitHubTrustPolicy{
+ ID: policy.ID,
+ OwnerSub: policy.OwnerSub,
+ Repository: policy.Repository,
+ AllowedNamespaces: policy.AllowedNamespaces,
+ Enabled: policy.Enabled,
+ })
+ }
+ return out, nil
+}
+
+func policyResponse(policy *githubtrust.Policy) GitHubTrustPolicyResponse {
+ return GitHubTrustPolicyResponse{
+ ID: policy.ID,
+ OwnerSub: policy.OwnerSub,
+ Name: policy.Name,
+ Repository: policy.Repository,
+ AllowedNamespaces: policy.AllowedNamespaces,
+ Enabled: policy.Enabled,
+ CreatedAt: policy.CreatedAt,
+ UpdatedAt: policy.UpdatedAt,
+ }
+}
+
+func writeTrustPolicyValidationErr(w http.ResponseWriter, err error) {
+ switch {
+ case errors.Is(err, githubtrust.ErrInvalidRepository),
+ errors.Is(err, githubtrust.ErrEmptyNamespaces),
+ errors.Is(err, githubtrust.ErrInvalidNamespace):
+ writeErr(w, http.StatusBadRequest, err.Error())
+ default:
+ writeErr(w, http.StatusBadRequest, "invalid github trust policy")
+ }
+}
diff --git a/libs/fleet/backend/handlers/github_trust_policies_test.go b/libs/fleet/backend/handlers/github_trust_policies_test.go
new file mode 100644
index 0000000000..675fd367b0
--- /dev/null
+++ b/libs/fleet/backend/handlers/github_trust_policies_test.go
@@ -0,0 +1,230 @@
+package handlers
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "cyclops-cs-backend/auth"
+ "cyclops-cs-backend/config"
+ "cyclops-cs-backend/githubtrust"
+)
+
+type fakeGitHubTrustStore struct {
+ listByOwner []*githubtrust.Policy
+ createInput *githubtrust.Policy
+ updateInput *githubtrust.Policy
+ deleteOwner string
+ deleteID string
+ deleteFound bool
+ deleteErr error
+ getResult *githubtrust.Policy
+ getErr error
+ listErr error
+ createErr error
+ updateErr error
+ resolveResult []*githubtrust.Policy
+ resolveErr error
+ resolvedRepoName string
+}
+
+func (f *fakeGitHubTrustStore) List(ctx context.Context, ownerSub string) ([]*githubtrust.Policy, error) {
+ _ = ctx
+ if f.listErr != nil {
+ return nil, f.listErr
+ }
+ out := make([]*githubtrust.Policy, len(f.listByOwner))
+ copy(out, f.listByOwner)
+ return out, nil
+}
+
+func (f *fakeGitHubTrustStore) Create(ctx context.Context, policy *githubtrust.Policy) error {
+ _ = ctx
+ if f.createErr != nil {
+ return f.createErr
+ }
+ cp := *policy
+ f.createInput = &cp
+ return nil
+}
+
+func (f *fakeGitHubTrustStore) Get(ctx context.Context, ownerSub, id string) (*githubtrust.Policy, error) {
+ _ = ctx
+ _ = ownerSub
+ _ = id
+ if f.getErr != nil {
+ return nil, f.getErr
+ }
+ if f.getResult == nil {
+ return nil, nil
+ }
+ cp := *f.getResult
+ return &cp, nil
+}
+
+func (f *fakeGitHubTrustStore) Update(ctx context.Context, policy *githubtrust.Policy) error {
+ _ = ctx
+ if f.updateErr != nil {
+ return f.updateErr
+ }
+ cp := *policy
+ f.updateInput = &cp
+ return nil
+}
+
+func (f *fakeGitHubTrustStore) Delete(ctx context.Context, ownerSub, id string) (bool, error) {
+ _ = ctx
+ f.deleteOwner = ownerSub
+ f.deleteID = id
+ if f.deleteErr != nil {
+ return false, f.deleteErr
+ }
+ return f.deleteFound, nil
+}
+
+func (f *fakeGitHubTrustStore) ResolveByRepository(ctx context.Context, repository string) ([]*githubtrust.Policy, error) {
+ _ = ctx
+ f.resolvedRepoName = repository
+ if f.resolveErr != nil {
+ return nil, f.resolveErr
+ }
+ out := make([]*githubtrust.Policy, len(f.resolveResult))
+ copy(out, f.resolveResult)
+ return out, nil
+}
+
+func TestListGitHubTrustPolicies_Success(t *testing.T) {
+ store := &fakeGitHubTrustStore{
+ listByOwner: []*githubtrust.Policy{{
+ ID: "policy-1",
+ OwnerSub: "user-123",
+ Name: "repo access",
+ Repository: "trycua/cloud",
+ AllowedNamespaces: []string{"ns-a", "ns-b"},
+ Enabled: true,
+ CreatedAt: time.Date(2026, 6, 26, 10, 0, 0, 0, time.UTC),
+ UpdatedAt: time.Date(2026, 6, 26, 11, 0, 0, 0, time.UTC),
+ }},
+ }
+
+ h := Handlers{GitHubTrustPolicies: store, AuthCfg: authConfigForHandlers()}
+ r := httptest.NewRequest(http.MethodGet, "/api/github-trust-policies", nil)
+ r = withUser(r, &auth.User{ID: "user-123", AZP: "cyclops-cs-spa"})
+ w := httptest.NewRecorder()
+
+ h.ListGitHubTrustPolicies(w, r)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
+ }
+
+ var resp GitHubTrustPolicyListResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp.OIDC.Issuer != "https://token.actions.githubusercontent.com" {
+ t.Fatalf("issuer = %q", resp.OIDC.Issuer)
+ }
+ if resp.OIDC.Audience != "cyclops-cs" {
+ t.Fatalf("audience = %q", resp.OIDC.Audience)
+ }
+ if len(resp.Policies) != 1 || resp.Policies[0].Repository != "trycua/cloud" {
+ t.Fatalf("unexpected policies payload: %+v", resp.Policies)
+ }
+}
+
+func TestCreateGitHubTrustPolicy_ValidatesAndPersists(t *testing.T) {
+ store := &fakeGitHubTrustStore{}
+ h := Handlers{GitHubTrustPolicies: store}
+ body := `{"name":"ci","repository":"trycua/cloud","allowed_namespaces":["ns-b","ns-a","ns-a"],"enabled":true}`
+ r := httptest.NewRequest(http.MethodPost, "/api/github-trust-policies", bytes.NewBufferString(body))
+ r = withUser(r, &auth.User{ID: "user-123", AZP: "cyclops-cs-spa"})
+ w := httptest.NewRecorder()
+
+ h.CreateGitHubTrustPolicy(w, r)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want 201; body = %s", w.Code, w.Body.String())
+ }
+ if store.createInput == nil {
+ t.Fatal("expected store.Create to be called")
+ }
+ if store.createInput.OwnerSub != "user-123" {
+ t.Fatalf("owner_sub = %q, want user-123", store.createInput.OwnerSub)
+ }
+ if got, want := store.createInput.AllowedNamespaces, []string{"ns-a", "ns-b"}; len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
+ t.Fatalf("allowed_namespaces = %#v, want %#v", got, want)
+ }
+}
+
+func TestPatchGitHubTrustPolicy_NotFound(t *testing.T) {
+ store := &fakeGitHubTrustStore{}
+ h := Handlers{GitHubTrustPolicies: store}
+ r := httptest.NewRequest(http.MethodPatch, "/api/github-trust-policies/missing", bytes.NewBufferString(`{"enabled":false}`))
+ r.SetPathValue("id", "missing")
+ r = withUser(r, &auth.User{ID: "user-123", AZP: "cyclops-cs-spa"})
+ w := httptest.NewRecorder()
+
+ h.UpdateGitHubTrustPolicy(w, r)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404; body = %s", w.Code, w.Body.String())
+ }
+}
+
+func TestDeleteGitHubTrustPolicy_Success(t *testing.T) {
+ store := &fakeGitHubTrustStore{deleteFound: true}
+ h := Handlers{GitHubTrustPolicies: store}
+ r := httptest.NewRequest(http.MethodDelete, "/api/github-trust-policies/policy-1", nil)
+ r.SetPathValue("id", "policy-1")
+ r = withUser(r, &auth.User{ID: "user-123", AZP: "cyclops-cs-spa"})
+ w := httptest.NewRecorder()
+
+ h.DeleteGitHubTrustPolicy(w, r)
+
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("status = %d, want 204; body = %s", w.Code, w.Body.String())
+ }
+ if store.deleteOwner != "user-123" || store.deleteID != "policy-1" {
+ t.Fatalf("delete args = %q/%q", store.deleteOwner, store.deleteID)
+ }
+}
+
+func TestGitHubTrustPolicies_DisabledStore(t *testing.T) {
+ h := Handlers{}
+ r := httptest.NewRequest(http.MethodGet, "/api/github-trust-policies", nil)
+ r = withUser(r, &auth.User{ID: "user-123", AZP: "cyclops-cs-spa"})
+ w := httptest.NewRecorder()
+
+ h.ListGitHubTrustPolicies(w, r)
+
+ if w.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want 503; body = %s", w.Code, w.Body.String())
+ }
+}
+
+func TestGitHubTrustPolicies_StoreError(t *testing.T) {
+ store := &fakeGitHubTrustStore{listErr: errors.New("redis down")}
+ h := Handlers{GitHubTrustPolicies: store}
+ r := httptest.NewRequest(http.MethodGet, "/api/github-trust-policies", nil)
+ r = withUser(r, &auth.User{ID: "user-123", AZP: "cyclops-cs-spa"})
+ w := httptest.NewRecorder()
+
+ h.ListGitHubTrustPolicies(w, r)
+
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want 500; body = %s", w.Code, w.Body.String())
+ }
+}
+
+func authConfigForHandlers() config.AuthConfiguration {
+ return config.AuthConfiguration{
+ GitHubOIDCIssuer: "https://token.actions.githubusercontent.com",
+ GitHubOIDCAudience: "cyclops-cs",
+ }
+}
diff --git a/libs/fleet/backend/handlers/handlers.go b/libs/fleet/backend/handlers/handlers.go
index 8411b965ce..7087b3616d 100644
--- a/libs/fleet/backend/handlers/handlers.go
+++ b/libs/fleet/backend/handlers/handlers.go
@@ -12,6 +12,7 @@ import (
"cyclops-cs-backend/auth"
"cyclops-cs-backend/config"
+ "cyclops-cs-backend/githubtrust"
"cyclops-cs-backend/keycloak"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
@@ -26,6 +27,8 @@ type Handlers struct {
Billing BillingService
WebhookVerifier WebhookVerifier
+ GitHubTrustPolicies githubtrust.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).
@@ -66,6 +69,19 @@ func currentUser(r *http.Request) *auth.User {
return auth.GetUser(r.Context())
}
+func isGitHubPrincipal(user *auth.User) bool {
+ return user != nil && user.PrincipalType == auth.PrincipalTypeGitHubOIDC
+}
+
+func namespaceAllowed(user *auth.User, namespace string) bool {
+ for _, allowed := range user.AllowedNamespaces {
+ if allowed == namespace {
+ return true
+ }
+ }
+ return false
+}
+
// statusCapture wraps http.ResponseWriter to capture the status code written
// by a reverse proxy for post-request metrics recording.
type statusCapture struct {
diff --git a/libs/fleet/backend/handlers/k8s.go b/libs/fleet/backend/handlers/k8s.go
index 7d7bc60f07..1d6904d189 100644
--- a/libs/fleet/backend/handlers/k8s.go
+++ b/libs/fleet/backend/handlers/k8s.go
@@ -60,6 +60,17 @@ func (h Handlers) K8s(w http.ResponseWriter, r *http.Request) {
// Extract the authenticated user for K8s impersonation — Capsule
// uses these headers to scope the request to the user's Tenant.
user := currentUser(r.WithContext(ctx))
+ if isGitHubPrincipal(user) {
+ namespace, ok := githubAllowedK8sPath(r.Method, strings.TrimPrefix(r.PathValue("path"), "/"))
+ if !ok {
+ writeErr(w, http.StatusForbidden, "k8s path is outside github trust policy scope")
+ return
+ }
+ if !namespaceAllowed(user, namespace) {
+ writeErr(w, http.StatusForbidden, "namespace is outside github trust policy scope")
+ return
+ }
+ }
if allowed, err := poolImagePullSecretAllowed(ctx, r); err != nil {
writeErr(w, http.StatusBadRequest, "could not inspect pool request")
@@ -212,6 +223,34 @@ func bodyRequestsMacOS(body []byte) bool {
return false
}
+func githubAllowedK8sPath(method, path string) (string, bool) {
+ parts := strings.Split(path, "/")
+ if len(parts) >= 6 &&
+ parts[0] == "apis" &&
+ parts[1] == "cua.ai" &&
+ parts[2] == "v1" &&
+ parts[3] == "namespaces" &&
+ parts[5] == "osgymworkspacepools" {
+ switch method {
+ case http.MethodGet, http.MethodPost, http.MethodPatch, http.MethodDelete:
+ if len(parts) == 6 || len(parts) == 7 {
+ return parts[4], true
+ }
+ }
+ }
+ if len(parts) >= 6 &&
+ parts[0] == "apis" &&
+ parts[1] == "osgym.cua.ai" &&
+ parts[2] == "v1alpha1" &&
+ parts[3] == "namespaces" &&
+ parts[5] == "osgymsandboxclaims" {
+ if method == http.MethodGet && (len(parts) == 6 || len(parts) == 7) {
+ return parts[4], true
+ }
+ }
+ return "", false
+}
+
// Orch godoc
//
// @Summary SPA-authenticated proxy to a per-namespace orchestrator service
diff --git a/libs/fleet/backend/handlers/k8s_test.go b/libs/fleet/backend/handlers/k8s_test.go
index f128aae79a..7d3d5279a6 100644
--- a/libs/fleet/backend/handlers/k8s_test.go
+++ b/libs/fleet/backend/handlers/k8s_test.go
@@ -277,3 +277,53 @@ func TestBodyRequestsMacOS(t *testing.T) {
})
}
}
+
+func TestK8sProxy_GitHubPrincipalAllowsNamespacedPoolCRUDPath(t *testing.T) {
+ var receivedPath string
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ receivedPath = r.URL.Path
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{}`))
+ }))
+ defer upstream.Close()
+ t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)
+
+ h := Handlers{}
+ r := httptest.NewRequest(http.MethodGet, "/api/k8s/apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", nil)
+ r.SetPathValue("path", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools")
+ r = withUser(r, &auth.User{
+ ID: "user-123",
+ AZP: "github-oidc",
+ PrincipalType: auth.PrincipalTypeGitHubOIDC,
+ AllowedNamespaces: []string{"ns-a"},
+ })
+ w := httptest.NewRecorder()
+
+ h.K8s(w, r)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
+ }
+ if receivedPath != "/apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools" {
+ t.Fatalf("upstream path = %q", receivedPath)
+ }
+}
+
+func TestK8sProxy_GitHubPrincipalRejectsClusterWidePath(t *testing.T) {
+ h := Handlers{}
+ r := httptest.NewRequest(http.MethodGet, "/api/k8s/api/v1/nodes", nil)
+ r.SetPathValue("path", "api/v1/nodes")
+ r = withUser(r, &auth.User{
+ ID: "user-123",
+ AZP: "github-oidc",
+ PrincipalType: auth.PrincipalTypeGitHubOIDC,
+ AllowedNamespaces: []string{"ns-a"},
+ })
+ w := httptest.NewRecorder()
+
+ h.K8s(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/namespaces.go b/libs/fleet/backend/handlers/namespaces.go
index ae4c1e2570..5e9bdf3db4 100644
--- a/libs/fleet/backend/handlers/namespaces.go
+++ b/libs/fleet/backend/handlers/namespaces.go
@@ -276,6 +276,9 @@ func (h Handlers) ListNamespaces(w http.ResponseWriter, r *http.Request) {
out := make([]NamespaceResponse, 0, len(nsList.Items))
for _, ns := range nsList.Items {
+ if isGitHubPrincipal(user) && !namespaceAllowed(user, ns.Metadata.Name) {
+ continue
+ }
out = append(out, NamespaceResponse{
Name: ns.Metadata.Name,
Status: ns.Status.Phase,
@@ -410,6 +413,10 @@ func (h Handlers) CreateNamespace(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "name must be a DNS-1123 label (lowercase alphanumeric + dashes, max 63 chars)")
return
}
+ if isGitHubPrincipal(user) && !namespaceAllowed(user, req.Name) {
+ writeErr(w, http.StatusForbidden, "namespace is outside github trust policy scope")
+ return
+ }
ctx, span := handlerTracer().Start(r.Context(), "namespaces.create", trace.WithAttributes(
attribute.String("http.route", "/api/namespaces"),
attribute.String("user.id", user.ID),
@@ -544,6 +551,10 @@ func (h Handlers) DeleteNamespace(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "invalid namespace name")
return
}
+ if isGitHubPrincipal(user) && !namespaceAllowed(user, name) {
+ writeErr(w, http.StatusForbidden, "namespace is outside github trust policy scope")
+ return
+ }
ctx, span := handlerTracer().Start(r.Context(), "namespaces.delete", trace.WithAttributes(
attribute.String("http.route", "/api/namespaces/{name}"),
attribute.String("user.id", user.ID),
diff --git a/libs/fleet/backend/handlers/namespaces_test.go b/libs/fleet/backend/handlers/namespaces_test.go
index 06324ab5cd..74c7949898 100644
--- a/libs/fleet/backend/handlers/namespaces_test.go
+++ b/libs/fleet/backend/handlers/namespaces_test.go
@@ -569,3 +569,69 @@ func TestListNamespaces_MissingUser(t *testing.T) {
t.Fatalf("status = %d, want %d", w.Code, http.StatusUnauthorized)
}
}
+
+func TestListNamespaces_GitHubPrincipalFiltersAllowedNamespaces(t *testing.T) {
+ fk := newFakeK8s(http.StatusOK, nsListResponse("ns-alpha", "ns-beta", "ns-gamma"))
+ 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",
+ AZP: "github-oidc",
+ PrincipalType: auth.PrincipalTypeGitHubOIDC,
+ AllowedNamespaces: []string{"ns-beta"},
+ })
+ w := httptest.NewRecorder()
+
+ h.ListNamespaces(w, r)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
+ }
+ var nsList []NamespaceResponse
+ if err := json.NewDecoder(w.Body).Decode(&nsList); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if len(nsList) != 1 || nsList[0].Name != "ns-beta" {
+ t.Fatalf("namespaces = %+v", nsList)
+ }
+}
+
+func TestCreateNamespace_GitHubPrincipalRejectsOutOfScopeNamespace(t *testing.T) {
+ h := Handlers{}
+ r := httptest.NewRequest(http.MethodPost, "/api/namespaces", strings.NewReader(`{"name":"other-ns"}`))
+ r = withUser(r, &auth.User{
+ ID: "test-uuid",
+ AZP: "github-oidc",
+ PrincipalType: auth.PrincipalTypeGitHubOIDC,
+ AllowedNamespaces: []string{"allowed-ns"},
+ })
+ w := httptest.NewRecorder()
+
+ h.CreateNamespace(w, r)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())
+ }
+}
+
+func TestDeleteNamespace_GitHubPrincipalRejectsOutOfScopeNamespace(t *testing.T) {
+ h := Handlers{}
+ r := httptest.NewRequest(http.MethodDelete, "/api/namespaces/other-ns", nil)
+ r.SetPathValue("name", "other-ns")
+ r = withUser(r, &auth.User{
+ ID: "test-uuid",
+ AZP: "github-oidc",
+ PrincipalType: auth.PrincipalTypeGitHubOIDC,
+ AllowedNamespaces: []string{"allowed-ns"},
+ })
+ w := httptest.NewRecorder()
+
+ h.DeleteNamespace(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/ownership.go b/libs/fleet/backend/handlers/ownership.go
index a82ced0016..f8093024c9 100644
--- a/libs/fleet/backend/handlers/ownership.go
+++ b/libs/fleet/backend/handlers/ownership.go
@@ -98,6 +98,13 @@ func (h Handlers) isPerKeyClient(user *auth.User) bool {
// RoleBinding probe. On deny/error it writes the response and returns
// false; callers must return immediately.
func (h Handlers) requireNamespaceAccess(w http.ResponseWriter, r *http.Request, user *auth.User, ns string) bool {
+ if isGitHubPrincipal(user) {
+ if namespaceAllowed(user, ns) {
+ return true
+ }
+ writeErr(w, http.StatusForbidden, "namespace access denied")
+ return false
+ }
// Per-key clients: bound to exactly one namespace by their token
// claim. No K8s call — the claim IS the grant.
if h.isPerKeyClient(user) {
diff --git a/libs/fleet/backend/handlers/ownership_test.go b/libs/fleet/backend/handlers/ownership_test.go
index 58d7d8fc7a..f8495fd330 100644
--- a/libs/fleet/backend/handlers/ownership_test.go
+++ b/libs/fleet/backend/handlers/ownership_test.go
@@ -216,6 +216,28 @@ func TestSvc_InvalidNamespace_BadRequest(t *testing.T) {
}
}
+func TestRequireNamespaceAccess_GitHubPrincipalAllowedWithoutProbe(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()
+ w := httptest.NewRecorder()
+ r := svcRequest(&auth.User{
+ ID: "user-123",
+ AZP: "github-oidc",
+ PrincipalType: auth.PrincipalTypeGitHubOIDC,
+ AllowedNamespaces: []string{"allowed-ns"},
+ }, "allowed-ns", "novnc")
+ if !h.requireNamespaceAccess(w, r, currentUser(r), "allowed-ns") {
+ t.Fatalf("authorized GitHub principal rejected; status = %d, body = %s", w.Code, w.Body.String())
+ }
+ if len(fk.requests) != 0 {
+ t.Fatalf("expected no K8s probe, got %d request(s)", len(fk.requests))
+ }
+}
+
func TestOrch_NonOwnedNamespace_Forbidden(t *testing.T) {
resetOwnershipCache()
fk := newFakeK8s(http.StatusForbidden, `{"kind":"Status"}`)
diff --git a/libs/fleet/backend/main.go b/libs/fleet/backend/main.go
index a539e9d8c5..3fd2ac23bf 100644
--- a/libs/fleet/backend/main.go
+++ b/libs/fleet/backend/main.go
@@ -46,6 +46,7 @@ import (
"cyclops-cs-backend/billing"
"cyclops-cs-backend/config"
_ "cyclops-cs-backend/docs" // generated by `swag init`
+ "cyclops-cs-backend/githubtrust"
"cyclops-cs-backend/handlers"
"cyclops-cs-backend/keycloak"
"cyclops-cs-backend/metrics"
@@ -142,6 +143,15 @@ func setupRouter(c handlers.Handlers) http.Handler {
r.Handle("DELETE /api/user-keys/{id}",
withMiddlewares("/api/user-keys/{id}", []string{"id"}, c.DeleteUserKey))
+ r.Handle("GET /api/github-trust-policies",
+ withMiddlewares("/api/github-trust-policies", nil, c.ListGitHubTrustPolicies))
+ r.Handle("POST /api/github-trust-policies",
+ withMiddlewares("/api/github-trust-policies", nil, c.CreateGitHubTrustPolicy))
+ r.Handle("PATCH /api/github-trust-policies/{id}",
+ withMiddlewares("/api/github-trust-policies/{id}", []string{"id"}, c.UpdateGitHubTrustPolicy))
+ r.Handle("DELETE /api/github-trust-policies/{id}",
+ withMiddlewares("/api/github-trust-policies/{id}", []string{"id"}, c.DeleteGitHubTrustPolicy))
+
r.Handle("/api/gateway/{name}",
withMiddlewares("/api/gateway/{name}", []string{"name"}, c.Gateway))
r.Handle("/api/gateway/{name}/{path...}",
@@ -306,6 +316,15 @@ func run() error {
h.WorkloadAdmin = workloadAdmin
h.WorkloadAudience = cfg.Keycloak.WorkloadAudience
h.WorkloadTokenURL = cfg.Keycloak.WorkloadTokenURL
+ if store, err := githubtrust.New(ctx, cfg.Templates.RedisURL); err != nil {
+ slog.Error("github trust policies: init failed; /api/github-trust-policies will return 503", "err", err)
+ } else if store != nil {
+ h.GitHubTrustPolicies = store
+ auth.SetGitHubTrustResolver(handlers.NewGitHubTrustResolver(store))
+ slog.Info("github trust policies: enabled")
+ } else {
+ slog.Info("github trust policies: disabled (no Redis URL configured)")
+ }
router := setupRouter(h)
diff --git a/libs/fleet/e2e/fixtures/mock-api.ts b/libs/fleet/e2e/fixtures/mock-api.ts
index 0b4852e601..ec7baab82d 100644
--- a/libs/fleet/e2e/fixtures/mock-api.ts
+++ b/libs/fleet/e2e/fixtures/mock-api.ts
@@ -244,6 +244,102 @@ export async function mockUserKeysApi(
})
}
+// ---------------------------------------------------------------------------
+// GitHub trust policies mocking
+// ---------------------------------------------------------------------------
+
+export interface MockGitHubTrustPolicy {
+ id: string
+ owner_sub: string
+ name: string
+ repository: string
+ allowed_namespaces: string[]
+ enabled: boolean
+ created_at: string
+ updated_at: string
+}
+
+const DEFAULT_GITHUB_TRUST_POLICIES: MockGitHubTrustPolicy[] = [
+ {
+ id: "gh-policy-1",
+ owner_sub: "test-user-id",
+ name: "cloud-ci",
+ repository: "trycua/cloud",
+ allowed_namespaces: ["my-workspace", "preview-a"],
+ enabled: true,
+ created_at: "2026-06-26T10:00:00Z",
+ updated_at: "2026-06-26T10:30:00Z",
+ },
+]
+
+export async function mockGitHubTrustPoliciesApi(
+ page: Page,
+ policies: MockGitHubTrustPolicy[] = DEFAULT_GITHUB_TRUST_POLICIES,
+): Promise<void> {
+ await page.route("**/api/github-trust-policies", async (route) => {
+ if (route.request().method() === "GET") {
+ await route.fulfill({
+ contentType: "application/json",
+ body: JSON.stringify({
+ policies,
+ oidc: {
+ issuer: "https://token.actions.githubusercontent.com",
+ audience: "cyclops-cs",
+ },
+ }),
+ })
+ return
+ }
+ if (route.request().method() === "POST") {
+ const body = route.request().postDataJSON()
+ const created: MockGitHubTrustPolicy = {
+ id: `gh-policy-${Date.now()}`,
+ owner_sub: "test-user-id",
+ name: body.name,
+ repository: body.repository,
+ allowed_namespaces: body.allowed_namespaces ?? [],
+ enabled: body.enabled ?? true,
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ }
+ policies.unshift(created)
+ await route.fulfill({
+ status: 201,
+ contentType: "application/json",
+ body: JSON.stringify(created),
+ })
+ return
+ }
+ await route.continue()
+ })
+
+ await page.route("**/api/github-trust-policies/*", async (route) => {
+ const url = new URL(route.request().url())
+ const id = url.pathname.split("/").pop()
+ const policy = policies.find(item => item.id === id)
+ if (route.request().method() === "PATCH") {
+ if (!policy) {
+ await route.fulfill({ status: 404, body: JSON.stringify({ error: "not found" }) })
+ return
+ }
+ const body = route.request().postDataJSON()
+ Object.assign(policy, body, { updated_at: new Date().toISOString() })
+ await route.fulfill({
+ contentType: "application/json",
+ body: JSON.stringify(policy),
+ })
+ return
+ }
+ if (route.request().method() === "DELETE") {
+ const idx = policies.findIndex(item => item.id === id)
+ if (idx >= 0) policies.splice(idx, 1)
+ await route.fulfill({ status: 204, body: "" })
+ return
+ }
+ await route.continue()
+ })
+}
+
// ---------------------------------------------------------------------------
// Pools API mocking (K8s CRD via kubectl-proxy sidecar)
// ---------------------------------------------------------------------------
@@ -402,4 +498,3 @@ export async function mockClaimsApi(page: Page): Promise<void> {
},
)
}
-
diff --git a/libs/fleet/e2e/settings.spec.ts b/libs/fleet/e2e/settings.spec.ts
new file mode 100644
index 0000000000..d12e39dce5
--- /dev/null
+++ b/libs/fleet/e2e/settings.spec.ts
@@ -0,0 +1,50 @@
+import { test, expect } from "@playwright/test"
+import {
+ mockAuth,
+ mockNamespacesApi,
+ mockGitHubTrustPoliciesApi,
+} from "./fixtures/mock-api"
+
+test.describe("Settings GitHub trust policies", () => {
+ test.beforeEach(async ({ page }) => {
+ await mockAuth(page)
+ await mockNamespacesApi(page)
+ await mockGitHubTrustPoliciesApi(page)
+ })
+
+ test("renders existing trust policies and workflow guidance", async ({ page }) => {
+ await page.goto("/settings")
+
+ await expect(
+ page.getByRole("heading", { name: "GitHub Actions OIDC" }),
+ ).toBeVisible()
+ await expect(page.getByText("cloud-ci")).toBeVisible()
+ await expect(page.getByText("trycua/cloud")).toBeVisible()
+ await expect(page.getByText("https://token.actions.githubusercontent.com")).toBeVisible()
+ await expect(page.getByText("permissions:")).toBeVisible()
+ })
+
+ test("can create, edit, disable, and delete a trust policy", async ({ page }) => {
+ await page.goto("/settings")
+
+ await page.getByLabel("Display name").fill("preview-ci")
+ await page.getByLabel("Repository").fill("trycua/preview")
+ await page.getByLabel("Additional namespaces").fill("preview-b, preview-c")
+ await page.getByRole("button", { name: "Create policy" }).click()
+
+ await expect(page.getByText("preview-ci")).toBeVisible()
+ await expect(page.getByText("trycua/preview")).toBeVisible()
+
+ await page.getByRole("button", { name: "Edit" }).nth(1).click()
+ await page.getByLabel("Display name").fill("preview-ci-updated")
+ await page.getByRole("button", { name: "Save policy" }).click()
+ await expect(page.getByText("preview-ci-updated")).toBeVisible()
+
+ await page.getByRole("button", { name: "Disable" }).nth(0).click()
+ await expect(page.getByText("No").first()).toBeVisible()
+
+ await page.getByRole("button", { name: "Delete" }).nth(1).click()
+ await page.getByRole("button", { name: "Delete" }).last().click()
+ await expect(page.getByText("preview-ci-updated")).toHaveCount(0)
+ })
+})
diff --git a/libs/fleet/js-sdk/README.md b/libs/fleet/js-sdk/README.md
index 1dc8892e34..799291b830 100644
--- a/libs/fleet/js-sdk/README.md
+++ b/libs/fleet/js-sdk/README.md
@@ -23,6 +23,9 @@ 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.
+This README lives under `cyclops-cs/`, which means documentation-only changes
+here still exercise the preview image build workflow for pull requests.
+
## Node.js and Fetch API support
The generated client uses the standard Fetch API. Node.js 18+ supplies it
diff --git a/libs/fleet/nginx.conf b/libs/fleet/nginx.conf
index 318fe0a8d8..7e9c5726bc 100644
--- a/libs/fleet/nginx.conf
+++ b/libs/fleet/nginx.conf
@@ -148,7 +148,7 @@ server {
proxy_set_header X-Forwarded-Proto $scheme;
}
- location ~ ^/api/(keys|user-keys|gateway|k8s|orch|swagger|batch|label|namespaces|config|billing)(/|$) {
+ location ~ ^/api/(keys|user-keys|github-trust-policies|gateway|k8s|orch|swagger|batch|label|namespaces|config|billing)(/|$) {
proxy_pass ${CYCLOPS_CS_BACKEND};
proxy_http_version 1.1;
proxy_set_header Host $host;
diff --git a/libs/fleet/src/pages/Settings.tsx b/libs/fleet/src/pages/Settings.tsx
index 381492a27d..d6142e3e75 100644
--- a/libs/fleet/src/pages/Settings.tsx
+++ b/libs/fleet/src/pages/Settings.tsx
@@ -1,24 +1,210 @@
-// Settings page — shows the signed-in user's identity (username and
-// subject) read from the Keycloak token, with copy-to-clipboard for each,
-// plus payment methods and recent invoices when the billing
-// feature flag is enabled.
+// Settings page — shows account identity plus GitHub Actions OIDC trust
+// policies for backend automation.
+import { useEffect, useMemo, 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 Textarea from "@cloudscape-design/components/textarea"
+import Toggle from "@cloudscape-design/components/toggle"
import { userInfo } from "../auth/keycloak"
import { useFeatureFlags } from "../components/FeatureFlagContext"
+import {
+ type GitHubTrustPolicy,
+ githubTrustPoliciesApi,
+ namespacesApi,
+} from "../sdk/githubTrustPolicies"
import { BillingSettings } from "./Billing"
export function Settings() {
const { sub, name } = userInfo()
const { billing } = useFeatureFlags()
+ const [policies, setPolicies] = useState<GitHubTrustPolicy[]>([])
+ const [namespaceOptions, setNamespaceOptions] = useState<MultiselectProps.Option[]>([])
+ const [selectedNamespaces, setSelectedNamespaces] = useState<MultiselectProps.Option[]>([])
+ const [extraNamespaces, setExtraNamespaces] = useState("")
+ const [policyName, setPolicyName] = useState("")
+ const [repository, setRepository] = useState("")
+ const [enabled, setEnabled] = useState(true)
+ const [editingId, setEditingId] = useState<string | null>(null)
+ const [oidc, setOidc] = useState({
+ issuer: "https://token.actions.githubusercontent.com",
+ audience: "cyclops-cs",
+ })
+ const [loading, setLoading] = useState(true)
+ const [saving, setSaving] = useState(false)
+ const [busyId, setBusyId] = useState<string | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [confirmDelete, setConfirmDelete] = useState<GitHubTrustPolicy | null>(null)
+
+ const allNamespaceOptions = useMemo(() => {
+ const byValue = new Map<string, MultiselectProps.Option>()
+ for (const option of namespaceOptions) {
+ if (option.value) byValue.set(option.value, option)
+ }
+ for (const option of selectedNamespaces) {
+ if (option.value) byValue.set(option.value, option)
+ }
+ return [...byValue.values()].sort((a, b) =>
+ (a.label ?? a.value ?? "").localeCompare(b.label ?? b.value ?? ""),
+ )
+ }, [namespaceOptions, selectedNamespaces])
+
+ const refresh = async () => {
+ setLoading(true)
+ try {
+ const [policyResp, namespaces] = await Promise.all([
+ githubTrustPoliciesApi.list(),
+ namespacesApi.list().catch(() => []),
+ ])
+ setPolicies(policyResp.policies)
+ setOidc(policyResp.oidc)
+ setNamespaceOptions(
+ namespaces.map(ns => ({
+ label: ns.name,
+ value: ns.name,
+ })),
+ )
+ setError(null)
+ } catch (e) {
+ setError(String(e))
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: one-time page load
+ useEffect(() => {
+ refresh()
+ }, [])
+
+ const resetForm = () => {
+ setEditingId(null)
+ setPolicyName("")
+ setRepository("")
+ setEnabled(true)
+ setSelectedNamespaces([])
+ setExtraNamespaces("")
+ }
+
+ const collectNamespaces = () => {
+ const merged = new Set<string>()
+ for (const option of selectedNamespaces) {
+ if (option.value) merged.add(option.value)
+ }
+ for (const value of extraNamespaces.split(/[\s,]+/)) {
+ if (value) merged.add(value)
+ }
+ return [...merged].sort()
+ }
+
+ const submit = async () => {
+ setSaving(true)
+ try {
+ const payload = {
+ name: policyName,
+ repository,
+ allowed_namespaces: collectNamespaces(),
+ enabled,
+ }
+ if (editingId) {
+ await githubTrustPoliciesApi.update(editingId, payload)
+ } else {
+ await githubTrustPoliciesApi.create(payload)
+ }
+ resetForm()
+ await refresh()
+ } catch (e) {
+ setError(String(e))
+ } finally {
+ setSaving(false)
+ }
+ }
+
+ const startEdit = (policy: GitHubTrustPolicy) => {
+ const existing = new Set(namespaceOptions.map(option => option.value))
+ setEditingId(policy.id)
+ setPolicyName(policy.name)
+ setRepository(policy.repository)
+ setEnabled(policy.enabled)
+ setSelectedNamespaces(
+ policy.allowed_namespaces
+ .filter(ns => existing.has(ns))
+ .map(ns => ({ label: ns, value: ns })),
+ )
+ setExtraNamespaces(
+ policy.allowed_namespaces.filter(ns => !existing.has(ns)).join(", "),
+ )
+ }
+
+ const togglePolicy = async (policy: GitHubTrustPolicy) => {
+ setBusyId(policy.id)
+ try {
+ await githubTrustPoliciesApi.update(policy.id, {
+ enabled: !policy.enabled,
+ })
+ await refresh()
+ } catch (e) {
+ setError(String(e))
+ } finally {
+ setBusyId(null)
+ }
+ }
+
+ const removePolicy = async () => {
+ if (!confirmDelete) return
+ setBusyId(confirmDelete.id)
+ try {
+ await githubTrustPoliciesApi.remove(confirmDelete.id)
+ setConfirmDelete(null)
+ if (editingId === confirmDelete.id) resetForm()
+ await refresh()
+ } catch (e) {
+ setError(String(e))
+ } finally {
+ setBusyId(null)
+ }
+ }
+
+ const workflowSnippet = `permissions:
+ id-token: write
+ contents: read
+
+steps:
+ - name: Request GitHub OIDC token for cyclops-cs
+ id: oidc
+ run: |
+ echo "token=$(curl -sSL \\
+ -H \\"Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN\\" \\
+ \\"$ACTIONS_ID_TOKEN_REQUEST_URL&audience=${oidc.audience}\\" | jq -r '.value')" >> "$GITHUB_OUTPUT"
+
+ - name: Call cyclops-cs
+ env:
+ CYCLOPS_CS_TOKEN: \${{ steps.oidc.outputs.token }}
+ run: |
+ curl -sSL https://cyclops.example.test/api/namespaces \\
+ -H "Authorization: Bearer $CYCLOPS_CS_TOKEN"`
return (
<SpaceBetween size="l">
+ {error && (
+ <Alert type="error" dismissible onDismiss={() => setError(null)}>
+ {error}
+ </Alert>
+ )}
+
<Container header={<Header variant="h2">Account</Header>}>
<SpaceBetween size="m">
<FormField label="Username">
@@ -51,7 +237,222 @@ export function Settings() {
</FormField>
</SpaceBetween>
</Container>
+
+ <Container
+ header={
+ <Header
+ variant="h2"
+ description="Trust GitHub repositories to call cyclops-cs directly with GitHub Actions OIDC tokens."
+ >
+ GitHub Actions OIDC
+ </Header>
+ }
+ >
+ <SpaceBetween size="l">
+ <Form
+ header={
+ <Header
+ variant="h3"
+ description="Create or update a repository trust policy. Existing namespaces are selectable, and you can add future namespaces below."
+ >
+ {editingId ? "Edit trust policy" : "Create trust policy"}
+ </Header>
+ }
+ actions={
+ <SpaceBetween direction="horizontal" size="xs">
+ {editingId && <Button onClick={resetForm}>Cancel</Button>}
+ <Button
+ variant="primary"
+ loading={saving}
+ disabled={!policyName || !repository}
+ onClick={submit}
+ >
+ {editingId ? "Save policy" : "Create policy"}
+ </Button>
+ </SpaceBetween>
+ }
+ >
+ <SpaceBetween size="m">
+ <FormField label="Display name">
+ <Input
+ value={policyName}
+ onChange={e => setPolicyName(e.detail.value)}
+ placeholder="CI access"
+ />
+ </FormField>
+ <FormField
+ label="Repository"
+ description="Exact owner/repo match from the GitHub OIDC repository claim."
+ >
+ <Input
+ value={repository}
+ onChange={e => setRepository(e.detail.value)}
+ placeholder="trycua/cloud"
+ />
+ </FormField>
+ <FormField
+ label="Existing namespaces"
+ description="Select namespaces you already own."
+ >
+ <Multiselect
+ selectedOptions={selectedNamespaces}
+ onChange={e =>
+ setSelectedNamespaces([...e.detail.selectedOptions])
+ }
+ options={allNamespaceOptions}
+ placeholder="Choose existing namespaces"
+ loadingText="Loading namespaces..."
+ statusType={loading ? "loading" : "finished"}
+ empty="No namespaces found"
+ />
+ </FormField>
+ <FormField
+ label="Additional namespaces"
+ description="Enter future namespaces as comma- or newline-separated DNS labels."
+ >
+ <Textarea
+ value={extraNamespaces}
+ onChange={e => setExtraNamespaces(e.detail.value)}
+ placeholder="preview-a, preview-b"
+ rows={3}
+ />
+ </FormField>
+ <Toggle
+ checked={enabled}
+ onChange={e => setEnabled(e.detail.checked)}
+ >
+ Policy enabled
+ </Toggle>
+ </SpaceBetween>
+ </Form>
+
+ <Table
+ loading={loading}
+ items={policies}
+ columnDefinitions={[
+ { id: "name", header: "Name", cell: policy => policy.name },
+ {
+ id: "repository",
+ header: "Repository",
+ cell: policy => <code>{policy.repository}</code>,
+ },
+ {
+ id: "namespaces",
+ header: "Namespaces",
+ cell: policy => policy.allowed_namespaces.join(", "),
+ },
+ {
+ id: "enabled",
+ header: "Enabled",
+ cell: policy => (policy.enabled ? "Yes" : "No"),
+ },
+ {
+ id: "updated",
+ header: "Updated",
+ cell: policy => new Date(policy.updated_at).toLocaleString(),
+ },
+ {
+ id: "actions",
+ header: "",
+ cell: policy => (
+ <SpaceBetween direction="horizontal" size="xs">
+ <Button onClick={() => startEdit(policy)}>Edit</Button>
+ <Button
+ loading={busyId === policy.id}
+ onClick={() => togglePolicy(policy)}
+ >
+ {policy.enabled ? "Disable" : "Enable"}
+ </Button>
+ <Button onClick={() => setConfirmDelete(policy)}>
+ Delete
+ </Button>
+ </SpaceBetween>
+ ),
+ },
+ ]}
+ empty={
+ <Box textAlign="center">
+ No GitHub trust policies yet.
+ </Box>
+ }
+ header={<Header variant="h3">Configured policies</Header>}
+ />
+
+ <Container
+ header={
+ <Header
+ variant="h3"
+ description="Use these exact values in your GitHub workflow when requesting an OIDC token."
+ >
+ Workflow guidance
+ </Header>
+ }
+ >
+ <SpaceBetween size="m">
+ <FormField label="Issuer">
+ <CopyToClipboard
+ variant="inline"
+ textToCopy={oidc.issuer}
+ textToDisplay={<code>{oidc.issuer}</code>}
+ copyButtonAriaLabel="Copy GitHub OIDC issuer"
+ copySuccessText="Issuer copied"
+ copyErrorText="Failed to copy issuer"
+ />
+ </FormField>
+ <FormField label="Audience">
+ <CopyToClipboard
+ variant="inline"
+ textToCopy={oidc.audience}
+ textToDisplay={<code>{oidc.audience}</code>}
+ copyButtonAriaLabel="Copy GitHub OIDC audience"
+ copySuccessText="Audience copied"
+ copyErrorText="Failed to copy audience"
+ />
+ </FormField>
+ <FormField label="Example workflow">
+ <Box variant="code" padding="m">
+ <pre style={{ margin: 0, whiteSpace: "pre-wrap" }}>
+ {workflowSnippet}
+ </pre>
+ </Box>
+ </FormField>
+ <Alert type="info">
+ Matching is exact on the GitHub OIDC <code>repository</code>{" "}
+ claim. The backend grants access only to the namespaces
+ listed in the matching trust policy.
+ </Alert>
+ </SpaceBetween>
+ </Container>
+ </SpaceBetween>
+ </Container>
+
{billing && <BillingSettings />}
+
+ {confirmDelete && (
+ <Modal
+ visible
+ header="Delete GitHub trust policy?"
+ onDismiss={() => setConfirmDelete(null)}
+ footer={
+ <Box float="right">
+ <SpaceBetween direction="horizontal" size="xs">
+ <Button onClick={() => setConfirmDelete(null)}>Cancel</Button>
+ <Button
+ variant="primary"
+ loading={busyId === confirmDelete.id}
+ onClick={removePolicy}
+ >
+ Delete
+ </Button>
+ </SpaceBetween>
+ </Box>
+ }
+ >
+ Delete <b>{confirmDelete.name}</b> for{" "}
+ <code>{confirmDelete.repository}</code>? GitHub workflows using
+ this policy will lose access immediately.
+ </Modal>
+ )}
</SpaceBetween>
)
}
diff --git a/libs/fleet/src/sdk/githubTrustPolicies.ts b/libs/fleet/src/sdk/githubTrustPolicies.ts
new file mode 100644
index 0000000000..0d7c918867
--- /dev/null
+++ b/libs/fleet/src/sdk/githubTrustPolicies.ts
@@ -0,0 +1,73 @@
+import { getToken } from "../auth/keycloak"
+
+export interface Namespace {
+ name: string
+ status: string
+ createdAt: string
+ labels: Record<string, string> | null
+}
+
+export interface GitHubTrustPolicy {
+ id: string
+ name: string
+ repository: string
+ allowed_namespaces: string[]
+ enabled: boolean
+ created_at: string
+ updated_at: string
+}
+
+export interface GitHubTrustPolicyListResponse {
+ policies: GitHubTrustPolicy[]
+ oidc: {
+ issuer: string
+ audience: string
+ }
+}
+
+export interface GitHubTrustPolicyInput {
+ name: string
+ repository: string
+ allowed_namespaces: string[]
+ enabled: boolean
+}
+
+async function request<T>(path: string, init?: RequestInit): Promise<T> {
+ const token = await getToken()
+ const response = await fetch(path, {
+ ...init,
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: token ? `Bearer ${token}` : "",
+ ...init?.headers,
+ },
+ })
+ if (!response.ok) {
+ const body = await response.text()
+ throw new Error(body || `request failed: ${response.status}`)
+ }
+ if (response.status === 204) return undefined as T
+ return response.json() as Promise<T>
+}
+
+export const githubTrustPoliciesApi = {
+ list: () => request<GitHubTrustPolicyListResponse>("/api/github-trust-policies"),
+ create: (input: GitHubTrustPolicyInput) =>
+ request<GitHubTrustPolicy>("/api/github-trust-policies", {
+ method: "POST",
+ body: JSON.stringify(input),
+ }),
+ update: (id: string, input: Partial<GitHubTrustPolicyInput>) =>
+ request<GitHubTrustPolicy>(`/api/github-trust-policies/${encodeURIComponent(id)}`, {
+ method: "PATCH",
+ body: JSON.stringify(input),
+ }),
+ remove: (id: string) =>
+ request<void>(`/api/github-trust-policies/${encodeURIComponent(id)}`, {
+ method: "DELETE",
+ }),
+}
+
+export const namespacesApi = {
+ list: () => request<Namespace[]>("/api/namespaces"),
+}
diff --git a/libs/fleet/tests/nginx-config.test.mjs b/libs/fleet/tests/nginx-config.test.mjs
new file mode 100644
index 0000000000..27c5706dc0
--- /dev/null
+++ b/libs/fleet/tests/nginx-config.test.mjs
@@ -0,0 +1,23 @@
+import test from "node:test"
+import assert from "node:assert/strict"
+import { readFile } from "node:fs/promises"
+import { fileURLToPath } from "node:url"
+import path from "node:path"
+
+const __filename = fileURLToPath(import.meta.url)
+const __dirname = path.dirname(__filename)
+const nginxConf = path.resolve(__dirname, "../nginx.conf")
+
+test("backend API nginx route includes GitHub trust policy endpoints", async () => {
+ const conf = await readFile(nginxConf, "utf8")
+ const backendRoute = conf.match(
+ /location ~ \^\/api\/\(([^)]+)\)\(\/\|\$\) \{/,
+ )
+
+ assert.ok(backendRoute, "expected backend API proxy route in nginx.conf")
+ assert.match(
+ backendRoute[1],
+ /\bgithub-trust-policies\b/,
+ "expected /api/github-trust-policies to proxy to cyclops-cs-backend",
+ )
+})