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): require card or admin for CR creation (#6796)

r33drichards69ed11122410
diff --git a/libs/fleet/backend/auth/custom_resource_creation_admission.rego b/libs/fleet/backend/auth/custom_resource_creation_admission.rego
new file mode 100644
index 0000000000..2f819078a9
--- /dev/null
+++ b/libs/fleet/backend/auth/custom_resource_creation_admission.rego
@@ -0,0 +1,67 @@
+# Admission for direct creation of custom-resource instances through /api/k8s.
+package custom_resource_creation_admission
+
+import data.authz
+
+default exempt = false
+
+default has_qualifying_card = false
+
+custom_api_group(group) {
+ group == "cua.ai"
+}
+
+custom_api_group(group) {
+ group == "osgym.cua.ai"
+}
+
+is_custom_resource_create {
+ input.method == "POST"
+ parts := split(input.params.path, "/")
+ count(parts) == 4
+ parts[0] == "apis"
+ custom_api_group(parts[1])
+ parts[3] != ""
+}
+
+is_custom_resource_create {
+ input.method == "POST"
+ parts := split(input.params.path, "/")
+ count(parts) == 6
+ parts[0] == "apis"
+ custom_api_group(parts[1])
+ parts[3] == "namespaces"
+ parts[4] != ""
+ parts[5] != ""
+}
+
+exempt {
+ object.get(input.flags, "require_card_for_custom_resource_creation", false) != true
+}
+
+exempt {
+ not is_custom_resource_create
+}
+
+exempt {
+ authz.is_admin
+}
+
+exempt {
+ input.flags.card_requirement_exempt_subs[_] == input.user.sub
+}
+
+has_qualifying_card {
+ current_year := input.facts.time.current_year
+ input.facts.time.current_month
+ card := input.facts.stripe_cards.cards[_]
+ card.exp_year > current_year
+}
+
+has_qualifying_card {
+ current_year := input.facts.time.current_year
+ current_month := input.facts.time.current_month
+ card := input.facts.stripe_cards.cards[_]
+ card.exp_year == current_year
+ card.exp_month >= current_month
+}
diff --git a/libs/fleet/backend/auth/custom_resource_creation_admission_test.rego b/libs/fleet/backend/auth/custom_resource_creation_admission_test.rego
new file mode 100644
index 0000000000..2d04ef32b3
--- /dev/null
+++ b/libs/fleet/backend/auth/custom_resource_creation_admission_test.rego
@@ -0,0 +1,190 @@
+package custom_resource_creation_admission_test
+
+import data.custom_resource_creation_admission
+
+input_for(method, path, enabled, admin_subs, sub, cards, current_year, current_month) := {
+ "method": method,
+ "params": {"path": path},
+ "flags": {
+ "admin_subs": admin_subs,
+ "require_card_for_custom_resource_creation": enabled,
+ },
+ "user": {"sub": sub},
+ "facts": {
+ "stripe_cards": {"cards": cards},
+ "time": {
+ "current_year": current_year,
+ "current_month": current_month,
+ },
+ },
+}
+
+test_disabled_bypasses_custom_resource_create {
+ custom_resource_creation_admission.exempt with input as input_for(
+ "POST", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", false, [], "user-1", [], 2026, 8,
+ )
+}
+
+test_admin_bypasses_custom_resource_create {
+ custom_resource_creation_admission.exempt with input as input_for(
+ "POST", "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxtemplates", true, ["admin-1"], "admin-1", [], 2026, 8,
+ )
+}
+
+test_configured_non_admin_sub_bypasses_custom_resource_create {
+ custom_resource_creation_admission.exempt with input as {
+ "method": "POST",
+ "params": {"path": "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools"},
+ "flags": {
+ "admin_subs": [],
+ "card_requirement_exempt_subs": ["exempt-user"],
+ "require_card_for_custom_resource_creation": true,
+ },
+ "user": {"sub": "exempt-user"},
+ }
+}
+
+test_unconfigured_non_admin_sub_does_not_bypass_custom_resource_create {
+ not custom_resource_creation_admission.exempt with input as {
+ "method": "POST",
+ "params": {"path": "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools"},
+ "flags": {
+ "admin_subs": [],
+ "card_requirement_exempt_subs": ["different-user"],
+ "require_card_for_custom_resource_creation": true,
+ },
+ "user": {"sub": "exempt-user"},
+ }
+}
+
+test_non_admin_custom_resource_create_not_exempt {
+ not custom_resource_creation_admission.exempt with input as input_for(
+ "POST", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", true, ["admin-1"], "user-1", [], 2026, 8,
+ )
+}
+
+test_current_month_card_qualifies {
+ custom_resource_creation_admission.has_qualifying_card with input as input_for(
+ "POST", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", true, [], "user-1",
+ [{"exp_year": 2026, "exp_month": 8}], 2026, 8,
+ )
+}
+
+test_future_month_same_year_qualifies {
+ custom_resource_creation_admission.has_qualifying_card with input as input_for(
+ "POST", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", true, [], "user-1",
+ [{"exp_year": 2026, "exp_month": 12}], 2026, 8,
+ )
+}
+
+test_future_year_qualifies {
+ custom_resource_creation_admission.has_qualifying_card with input as input_for(
+ "POST", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", true, [], "user-1",
+ [{"exp_year": 2027, "exp_month": 1}], 2026, 8,
+ )
+}
+
+test_expired_month_same_year_denies {
+ not custom_resource_creation_admission.has_qualifying_card with input as input_for(
+ "POST", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", true, [], "user-1",
+ [{"exp_year": 2026, "exp_month": 7}], 2026, 8,
+ )
+}
+
+test_expired_year_denies {
+ not custom_resource_creation_admission.has_qualifying_card with input as input_for(
+ "POST", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", true, [], "user-1",
+ [{"exp_year": 2025, "exp_month": 12}], 2026, 8,
+ )
+}
+
+test_mixed_list_qualifies {
+ custom_resource_creation_admission.has_qualifying_card with input as input_for(
+ "POST", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", true, [], "user-1",
+ [{"exp_year": 2025, "exp_month": 12}, {"exp_year": 2027, "exp_month": 1}], 2026, 8,
+ )
+}
+
+test_empty_list_denies {
+ not custom_resource_creation_admission.has_qualifying_card with input as input_for(
+ "POST", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", true, [], "user-1", [], 2026, 8,
+ )
+}
+
+test_missing_current_year_denies {
+ not custom_resource_creation_admission.has_qualifying_card with input as {
+ "facts": {
+ "stripe_cards": {"cards": [{"exp_year": 2027, "exp_month": 1}]},
+ "time": {"current_month": 8},
+ },
+ }
+}
+
+test_missing_current_month_denies {
+ not custom_resource_creation_admission.has_qualifying_card with input as {
+ "facts": {
+ "stripe_cards": {"cards": [{"exp_year": 2027, "exp_month": 1}]},
+ "time": {"current_year": 2026},
+ },
+ }
+}
+
+test_missing_cards_denies {
+ not custom_resource_creation_admission.has_qualifying_card with input as {
+ "facts": {"time": {"current_year": 2026, "current_month": 8}},
+ }
+}
+
+test_namespaced_custom_group_collection_is_create {
+ custom_resource_creation_admission.is_custom_resource_create with input as input_for(
+ "POST", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", true, [], "u", [], 2026, 8,
+ )
+}
+
+test_cluster_custom_group_collection_is_create {
+ custom_resource_creation_admission.is_custom_resource_create with input as input_for(
+ "POST", "apis/osgym.cua.ai/v1alpha1/osgymsandboxtemplates", true, [], "u", [], 2026, 8,
+ )
+}
+
+test_named_resource_is_not_create {
+ not custom_resource_creation_admission.is_custom_resource_create with input as input_for(
+ "POST", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools/pool-a", true, [], "u", [], 2026, 8,
+ )
+}
+
+test_subresource_is_not_create {
+ not custom_resource_creation_admission.is_custom_resource_create with input as input_for(
+ "POST", "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxtemplates/template-a/status", true, [], "u", [], 2026, 8,
+ )
+}
+
+test_core_resource_is_not_create {
+ not custom_resource_creation_admission.is_custom_resource_create with input as input_for(
+ "POST", "api/v1/namespaces/ns-a/configmaps", true, [], "u", [], 2026, 8,
+ )
+}
+
+test_builtin_api_is_not_create {
+ not custom_resource_creation_admission.is_custom_resource_create with input as input_for(
+ "POST", "apis/apps/v1/namespaces/ns-a/deployments", true, [], "u", [], 2026, 8,
+ )
+}
+
+test_crd_definition_is_not_create {
+ not custom_resource_creation_admission.is_custom_resource_create with input as input_for(
+ "POST", "apis/apiextensions.k8s.io/v1/customresourcedefinitions", true, [], "u", [], 2026, 8,
+ )
+}
+
+test_lookalike_group_is_not_create {
+ not custom_resource_creation_admission.is_custom_resource_create with input as input_for(
+ "POST", "apis/evil.cua.ai/v1/namespaces/ns-a/osgymworkspacepools", true, [], "u", [], 2026, 8,
+ )
+}
+
+test_non_post_is_not_create {
+ not custom_resource_creation_admission.is_custom_resource_create with input as input_for(
+ "PATCH", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools/pool-a", true, [], "u", [], 2026, 8,
+ )
+}
diff --git a/libs/fleet/backend/auth/facts.go b/libs/fleet/backend/auth/facts.go
index 837a9f8ff0..e2603c1a7c 100644
--- a/libs/fleet/backend/auth/facts.go
+++ b/libs/fleet/backend/auth/facts.go
@@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"sync"
+ "time"
)
// A FactProvider answers a question the token cannot: whether some other
@@ -88,3 +89,55 @@ const (
// input: authz_ownership.rego reads input.facts.namespace_rbac.allowed.
NamespaceRBACFactNamespace = "namespace_rbac"
)
+
+// Facts used by custom-resource creation admission.
+const (
+ StripeCardsFactProvider = "stripe-cards"
+ StripeCardsFactNamespace = "stripe_cards"
+ CurrentYearFactProvider = "current-year"
+ CurrentMonthFactProvider = "current-month"
+ TimeFactNamespace = "time"
+)
+
+type clockFactProvider struct {
+ cacheKey string
+ key string
+ now func() time.Time
+}
+
+type requestClockSnapshot struct {
+ once sync.Once
+ now time.Time
+}
+
+type requestClockSnapshotKey struct{}
+
+func (provider clockFactProvider) CacheKey() string { return provider.cacheKey }
+
+func (provider clockFactProvider) LoadFacts(_ context.Context, request *http.Request) (FactSet, error) {
+ var now time.Time
+ if snapshot, ok := request.Context().Value(requestClockSnapshotKey{}).(*requestClockSnapshot); ok {
+ snapshot.once.Do(func() { snapshot.now = provider.now().UTC() })
+ now = snapshot.now
+ } else {
+ now = provider.now().UTC()
+ }
+ if provider.key == "current_year" {
+ return FactSet{provider.key: now.Year()}, nil
+ }
+ return FactSet{provider.key: int(now.Month())}, nil
+}
+
+func CurrentYearFacts(now func() time.Time) FactProvider {
+ if now == nil {
+ panic("current-year fact provider requires a clock")
+ }
+ return clockFactProvider{cacheKey: CurrentYearFactProvider, key: "current_year", now: now}
+}
+
+func CurrentMonthFacts(now func() time.Time) FactProvider {
+ if now == nil {
+ panic("current-month fact provider requires a clock")
+ }
+ return clockFactProvider{cacheKey: CurrentMonthFactProvider, key: "current_month", now: now}
+}
diff --git a/libs/fleet/backend/auth/flags_test.go b/libs/fleet/backend/auth/flags_test.go
index b0e7ad3c19..405afafea4 100644
--- a/libs/fleet/backend/auth/flags_test.go
+++ b/libs/fleet/backend/auth/flags_test.go
@@ -79,6 +79,19 @@ func TestFlagsDataCachedAndRefreshes(t *testing.T) {
}
}
+func TestFlagsDataLoadsCardRequirementExemptSubs(t *testing.T) {
+ t.Setenv("CYCLOPS_CS_CARD_REQUIREMENT_EXEMPT_SUBS", `["exempt-a","exempt-b"]`)
+ if err := featureflags.SetupProvider(context.Background(), "development", featureflags.AWSCredentials{}); err != nil {
+ t.Fatalf("setup dev provider: %v", err)
+ }
+ resetFlagsCache()
+
+ got := asStrings(flagsData()["card_requirement_exempt_subs"])
+ if len(got) != 2 || got[0] != "exempt-a" || got[1] != "exempt-b" {
+ t.Fatalf("card_requirement_exempt_subs = %v, want [exempt-a exempt-b]", got)
+ }
+}
+
func asStrings(v any) []string {
items, ok := v.([]interface{})
if !ok {
diff --git a/libs/fleet/backend/auth/middlewares.go b/libs/fleet/backend/auth/middlewares.go
index ef31231e33..e6692ec805 100644
--- a/libs/fleet/backend/auth/middlewares.go
+++ b/libs/fleet/backend/auth/middlewares.go
@@ -35,6 +35,9 @@ var authzPolicy string
//go:embed pool_admission.rego
var poolAdmissionPolicy string
+//go:embed custom_resource_creation_admission.rego
+var customResourceCreationAdmissionPolicy string
+
// authzOwnershipPolicy is the namespace-ownership boundary. Like
// pool_admission.rego it is not a surface — it is a conjunct several surfaces
// carry — so it is registered by name below rather than through
@@ -112,7 +115,10 @@ var authzStateQueryPolicy string
// /feature-flags/cyclops-cs/admin-subs → CYCLOPS_CS_ADMIN_SUBS
//
// Values are JSON string arrays (e.g. '["sub1","sub2"]').
-const flagPrefix = "/feature-flags/cyclops-cs/"
+const (
+ flagPrefix = "/feature-flags/cyclops-cs/"
+ cardAdmissionFlag = flagPrefix + "require-card-for-custom-resource-creation"
+)
// flagsTTL bounds how long flagsData returns its last computed result
// before re-resolving via OpenFeature. Refresh is lazy and ad-hoc: the
@@ -195,12 +201,24 @@ func computeFlagsData(ctx context.Context) map[string]interface{} {
}
flags := map[string]interface{}{}
for _, key := range keys {
+ if key == cardAdmissionFlag {
+ continue
+ }
name := opaNameFromFlagKey(key)
if name == "" {
continue
}
flags[name] = loadStringList(ctx, ffClient, key)
}
+ callCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
+ defer cancel()
+ enabled, err := ffClient.BooleanValue(
+ callCtx, cardAdmissionFlag, false, openfeature.EvaluationContext{},
+ )
+ if err != nil {
+ slog.Warn("auth: flag eval failed; using false", "flag", cardAdmissionFlag, "err", err)
+ }
+ flags["require_card_for_custom_resource_creation"] = enabled
return flags
}
@@ -252,6 +270,7 @@ func loadStringList(ctx context.Context, client *openfeature.Client, flagKey str
func LoadOpa() {
RegisterPolicyModule("authz", "authz.rego", authzPolicy)
RegisterPolicyModule("pool-admission", "pool_admission.rego", poolAdmissionPolicy)
+ RegisterPolicyModule("custom-resource-creation-admission", "custom_resource_creation_admission.rego", customResourceCreationAdmissionPolicy)
RegisterPolicyModule("authz-ownership", "authz_ownership.rego", authzOwnershipPolicy)
for name, module := range surfacePolicySources {
RegisterPolicyModule(name, module.filename, module.source)
diff --git a/libs/fleet/backend/auth/policy_card_admission_test.go b/libs/fleet/backend/auth/policy_card_admission_test.go
new file mode 100644
index 0000000000..3876062661
--- /dev/null
+++ b/libs/fleet/backend/auth/policy_card_admission_test.go
@@ -0,0 +1,182 @@
+package auth
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+
+ "github.com/trycua/cloud/pkg/featureflags"
+)
+
+type countingAdmissionFacts struct {
+ cacheKey string
+ namespace string
+ facts FactSet
+ loads atomic.Int64
+ unavailable bool
+}
+
+func (facts *countingAdmissionFacts) CacheKey() string { return facts.cacheKey }
+
+func (facts *countingAdmissionFacts) LoadFacts(context.Context, *http.Request) (FactSet, error) {
+ facts.loads.Add(1)
+ if facts.unavailable {
+ return nil, &FactUnavailableError{Namespace: facts.namespace, Err: errors.New("dependency unavailable")}
+ }
+ return facts.facts, nil
+}
+
+func installAdmissionFacts(t *testing.T, name string, provider FactProvider) {
+ t.Helper()
+ factProviderRegistry.RLock()
+ previous, existed := factProviderRegistry.providers[name]
+ factProviderRegistry.RUnlock()
+ RegisterFactProvider(name, provider)
+ t.Cleanup(func() {
+ if existed {
+ RegisterFactProvider(name, previous)
+ return
+ }
+ factProviderRegistry.Lock()
+ delete(factProviderRegistry.providers, name)
+ factProviderRegistry.Unlock()
+ })
+}
+
+func setCardAdmissionFlags(t *testing.T, enabled bool, admins ...string) {
+ t.Helper()
+ if err := featureflags.SetupProvider(context.Background(), "development", featureflags.AWSCredentials{}); err != nil {
+ t.Fatalf("setup feature flags: %v", err)
+ }
+ if enabled {
+ t.Setenv("CYCLOPS_CS_REQUIRE_CARD_FOR_CUSTOM_RESOURCE_CREATION", "true")
+ } else {
+ t.Setenv("CYCLOPS_CS_REQUIRE_CARD_FOR_CUSTOM_RESOURCE_CREATION", "false")
+ }
+ adminJSON := `[]`
+ if len(admins) > 0 {
+ adminJSON = `["` + admins[0] + `"]`
+ }
+ t.Setenv("CYCLOPS_CS_ADMIN_SUBS", adminJSON)
+ resetFlagsCache()
+ LoadOpa()
+}
+
+func cardAdmissionRequest(method, path, sub string) *http.Request {
+ request := routeRequest(method, "/api/k8s/"+path, "/api/k8s/{path...}", map[string]string{"path": path}, `{}`)
+ ctx := context.WithValue(request.Context(), UserKey, &User{ID: sub, AZP: "cyclops-cs-spa", PrincipalType: PrincipalTypeUser})
+ return request.WithContext(ctx)
+}
+
+func runK8sPolicy(t *testing.T, request *http.Request) (int, bool) {
+ t.Helper()
+ reached := false
+ handler := PolicyMiddleware(K8sRoutePolicy())(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ reached = true
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ return response.Code, reached
+}
+
+func TestK8sCardAdmissionLazyTruthTable(t *testing.T) {
+ const createPath = "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims"
+ const readPath = "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims/claim-a"
+
+ cases := []struct {
+ name string
+ enabled bool
+ admins []string
+ exemptSubs []string
+ user string
+ method string
+ path string
+ cards []map[string]any
+ stripeUnavailable bool
+ wantStatus int
+ wantReached bool
+ wantStripeLoads int64
+ wantYearLoads int64
+ wantMonthLoads int64
+ }{
+ {name: "flag disabled bypass", enabled: false, user: "user-1", method: http.MethodPost, path: createPath, wantStatus: http.StatusNoContent, wantReached: true},
+ {name: "admin bypass", enabled: true, admins: []string{"admin-1"}, user: "admin-1", method: http.MethodPost, path: createPath, stripeUnavailable: true, wantStatus: http.StatusNoContent, wantReached: true},
+ {name: "configured non-admin bypass", enabled: true, exemptSubs: []string{"exempt-user"}, user: "exempt-user", method: http.MethodPost, path: createPath, stripeUnavailable: true, wantStatus: http.StatusNoContent, wantReached: true},
+ {name: "different non-admin is not exempt", enabled: true, exemptSubs: []string{"exempt-user"}, user: "user-1", method: http.MethodPost, path: createPath, wantStatus: http.StatusForbidden, wantStripeLoads: 1, wantYearLoads: 1, wantMonthLoads: 1},
+ {name: "email-like noncanonical identity is not admin", enabled: true, admins: []string{"[email protected]"}, user: "user-1", method: http.MethodPost, path: createPath, wantStatus: http.StatusForbidden, wantStripeLoads: 1, wantYearLoads: 1, wantMonthLoads: 1},
+ {name: "non-create bypass", enabled: true, user: "user-1", method: http.MethodGet, path: readPath, stripeUnavailable: true, wantStatus: http.StatusNoContent, wantReached: true},
+ {name: "current-month card allows", enabled: true, user: "user-1", method: http.MethodPost, path: createPath, cards: []map[string]any{{"exp_year": 2026, "exp_month": 8}}, wantStatus: http.StatusNoContent, wantReached: true, wantStripeLoads: 1, wantYearLoads: 1, wantMonthLoads: 1},
+ {name: "empty cards deny", enabled: true, user: "user-1", method: http.MethodPost, path: createPath, wantStatus: http.StatusForbidden, wantStripeLoads: 1, wantYearLoads: 1, wantMonthLoads: 1},
+ {name: "stripe outage fails closed", enabled: true, user: "user-1", method: http.MethodPost, path: createPath, stripeUnavailable: true, wantStatus: http.StatusBadGateway, wantStripeLoads: 1},
+ }
+
+ for _, testCase := range cases {
+ t.Run(testCase.name, func(t *testing.T) {
+ setCardAdmissionFlags(t, testCase.enabled, testCase.admins...)
+ if len(testCase.exemptSubs) > 0 {
+ t.Setenv("CYCLOPS_CS_CARD_REQUIREMENT_EXEMPT_SUBS", `["`+testCase.exemptSubs[0]+`"]`)
+ resetFlagsCache()
+ }
+ stripeCards := &countingAdmissionFacts{cacheKey: StripeCardsFactProvider, namespace: StripeCardsFactNamespace, facts: FactSet{"cards": testCase.cards}, unavailable: testCase.stripeUnavailable}
+ currentYear := &countingAdmissionFacts{cacheKey: CurrentYearFactProvider, namespace: TimeFactNamespace, facts: FactSet{"current_year": 2026}}
+ currentMonth := &countingAdmissionFacts{cacheKey: CurrentMonthFactProvider, namespace: TimeFactNamespace, facts: FactSet{"current_month": 8}}
+ installAdmissionFacts(t, StripeCardsFactProvider, stripeCards)
+ installAdmissionFacts(t, CurrentYearFactProvider, currentYear)
+ installAdmissionFacts(t, CurrentMonthFactProvider, currentMonth)
+
+ status, reached := runK8sPolicy(t, cardAdmissionRequest(testCase.method, testCase.path, testCase.user))
+ if status != testCase.wantStatus || reached != testCase.wantReached {
+ t.Fatalf("status, reached = %d, %v; want %d, %v", status, reached, testCase.wantStatus, testCase.wantReached)
+ }
+ for name, expected := range map[string]struct {
+ facts *countingAdmissionFacts
+ loads int64
+ }{
+ "stripe": {stripeCards, testCase.wantStripeLoads},
+ "year": {currentYear, testCase.wantYearLoads},
+ "month": {currentMonth, testCase.wantMonthLoads},
+ } {
+ if got := expected.facts.loads.Load(); got != expected.loads {
+ t.Fatalf("%s fact loads = %d, want %d", name, got, expected.loads)
+ }
+ }
+ })
+ }
+}
+
+func TestK8sCardAdmissionMissingProvidersFailClosed(t *testing.T) {
+ const path = "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims"
+ for _, missing := range []string{StripeCardsFactProvider, CurrentYearFactProvider, CurrentMonthFactProvider} {
+ t.Run(missing, func(t *testing.T) {
+ setCardAdmissionFlags(t, true)
+ providers := map[string]FactProvider{
+ StripeCardsFactProvider: &countingAdmissionFacts{cacheKey: StripeCardsFactProvider, facts: FactSet{"cards": []map[string]any{{"exp_year": 2027, "exp_month": 1}}}},
+ CurrentYearFactProvider: &countingAdmissionFacts{cacheKey: CurrentYearFactProvider, facts: FactSet{"current_year": 2026}},
+ CurrentMonthFactProvider: &countingAdmissionFacts{cacheKey: CurrentMonthFactProvider, facts: FactSet{"current_month": 8}},
+ }
+ for name, provider := range providers {
+ if name != missing {
+ installAdmissionFacts(t, name, provider)
+ }
+ }
+ factProviderRegistry.Lock()
+ previous, existed := factProviderRegistry.providers[missing]
+ delete(factProviderRegistry.providers, missing)
+ factProviderRegistry.Unlock()
+ t.Cleanup(func() {
+ if existed {
+ RegisterFactProvider(missing, previous)
+ }
+ })
+
+ status, reached := runK8sPolicy(t, cardAdmissionRequest(http.MethodPost, path, "user-1"))
+ if status != http.StatusInternalServerError || reached {
+ t.Fatalf("status, reached = %d, %v; want 500, false", status, reached)
+ }
+ })
+ }
+}
diff --git a/libs/fleet/backend/auth/policy_middleware.go b/libs/fleet/backend/auth/policy_middleware.go
index 59501fee9a..80e6b2713a 100644
--- a/libs/fleet/backend/auth/policy_middleware.go
+++ b/libs/fleet/backend/auth/policy_middleware.go
@@ -231,6 +231,7 @@ type requestPolicyInput struct {
}
func newRequestPolicyInput(request *http.Request, bodyBudget int64) *requestPolicyInput {
+ *request = *request.WithContext(context.WithValue(request.Context(), requestClockSnapshotKey{}, &requestClockSnapshot{}))
user, _ := request.Context().Value(UserKey).(*User)
route, _ := request.Context().Value(routeKey).(string)
params, _ := request.Context().Value(paramsKey).(map[string]string)
@@ -261,7 +262,17 @@ func (input *requestPolicyInput) forPolicy(ctx context.Context, config policyCon
if err != nil {
return nil, err
}
- facts[configured.namespace] = value
+ merged, ok := facts[configured.namespace].(map[string]any)
+ if !ok {
+ merged = map[string]any{}
+ facts[configured.namespace] = merged
+ }
+ for key, fact := range value {
+ if _, exists := merged[key]; exists {
+ return nil, fmt.Errorf("fact namespace %q contains duplicate key %q", configured.namespace, key)
+ }
+ merged[key] = fact
+ }
}
document["facts"] = facts
diff --git a/libs/fleet/backend/auth/policy_middleware_test.go b/libs/fleet/backend/auth/policy_middleware_test.go
index 957aec6121..a6b6cbad21 100644
--- a/libs/fleet/backend/auth/policy_middleware_test.go
+++ b/libs/fleet/backend/auth/policy_middleware_test.go
@@ -801,3 +801,32 @@ allow { input.body == "12345" }
t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusBadRequest, response.Body.String())
}
}
+
+func TestPolicyMiddlewareMergesFactsFromSeparateProvidersInOneNamespace(t *testing.T) {
+ year := &testFactProvider{cacheKey: "current-year", facts: FactSet{"current_year": 2026}}
+ month := &testFactProvider{cacheKey: "current-month", facts: FactSet{"current_month": 8}}
+ expression := Policy(
+ Inline("merged-time.rego", `package merged_time
+allow {
+ input.facts.time.current_year == 2026
+ input.facts.time.current_month == 8
+}
+`),
+ Query("data.merged_time.allow"),
+ WithFacts("time", year),
+ WithFacts("time", month),
+ )
+
+ handler := PolicyMiddleware(expression)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))
+
+ if response.Code != http.StatusNoContent {
+ t.Fatalf("status = %d, want 204; body = %s", response.Code, response.Body.String())
+ }
+ if year.loads != 1 || month.loads != 1 {
+ t.Fatalf("provider loads = year:%d month:%d, want 1 each", year.loads, month.loads)
+ }
+}
diff --git a/libs/fleet/backend/auth/policy_routes.go b/libs/fleet/backend/auth/policy_routes.go
index 3aeb09b56c..4c5d48c630 100644
--- a/libs/fleet/backend/auth/policy_routes.go
+++ b/libs/fleet/backend/auth/policy_routes.go
@@ -174,20 +174,42 @@ func StateQueryRoutePolicy() Node {
}
// K8sRoutePolicy guards /api/k8s/{path...}. It is the same base + surface shape
-// as every other route, with one extra conjunct: admission control over the
-// request body.
+// as every other route, with two admission conjuncts: card-or-admin admission
+// for custom-resource creation, and pool admission over the request body.
//
-// All three must pass. The admission leaf reads the raw body (bounded at 1 MiB)
+// Every conjunct must pass. The pool-admission leaf reads the raw body (bounded at 1 MiB)
// to inspect the object being created or patched, which is why it names
// pool_admission.rego alongside authz.rego — pool_admission imports
// data.authz.is_admin. It stays a separate leaf rather than rules inside
// authz_k8s.rego because it is the only thing on this surface that needs the
// body, and folding it in would put every k8s request's verdict behind a body
// read.
+func CustomResourceCreationAdmissionPolicy() Node {
+ leaf := func(query string, options ...PolicyOption) Node {
+ return Policy(
+ Modules(
+ Registered("authz"),
+ Registered("custom-resource-creation-admission"),
+ ),
+ append([]PolicyOption{Query(query)}, options...)...,
+ )
+ }
+ return Any(
+ leaf("data.custom_resource_creation_admission.exempt"),
+ leaf(
+ "data.custom_resource_creation_admission.has_qualifying_card",
+ WithFacts(StripeCardsFactNamespace, RegisteredFacts(StripeCardsFactProvider)),
+ WithFacts(TimeFactNamespace, RegisteredFacts(CurrentYearFactProvider)),
+ WithFacts(TimeFactNamespace, RegisteredFacts(CurrentMonthFactProvider)),
+ ),
+ )
+}
+
func K8sRoutePolicy() Node {
return All(
BasePolicy(),
surfaceLeaf("authz-k8s", "data.authz_k8s.allow"),
+ CustomResourceCreationAdmissionPolicy(),
Policy(
Modules(
Registered("authz"),
diff --git a/libs/fleet/backend/auth/policy_test.go b/libs/fleet/backend/auth/policy_test.go
index a5dfafb186..257e3db7ca 100644
--- a/libs/fleet/backend/auth/policy_test.go
+++ b/libs/fleet/backend/auth/policy_test.go
@@ -95,48 +95,46 @@ func evalAllow(t *testing.T, input map[string]any) bool {
if !ok {
t.Fatalf("input names route %q, which is bound to no authorization surface", route)
}
+ return evalPolicyNode(t, tree, input)
+}
- allowed := true
- for _, leaf := range conjunctiveLeaves(t, tree) {
- if leaf.MaxBody > 0 {
- continue
+func evalPolicyNode(t *testing.T, node Node, input map[string]any) bool {
+ t.Helper()
+ switch policy := node.(type) {
+ case Leaf:
+ if policy.MaxBody > 0 {
+ return true
}
- modules, err := leaf.Source.modules()
+ modules, err := policy.Source.modules()
if err != nil {
- t.Fatalf("load modules for %q: %v", leaf.Query, err)
+ t.Fatalf("load modules for %q: %v", policy.Query, err)
}
sources := make(map[string]string, len(modules))
for _, module := range modules {
sources[module.name] = module.source
}
- result, err := prepareQuery(t, leaf.Query, sources).Eval(context.Background(), rego.EvalInput(input))
+ result, err := prepareQuery(t, policy.Query, sources).Eval(context.Background(), rego.EvalInput(input))
if err != nil {
- t.Fatalf("eval %q: %v", leaf.Query, err)
- }
- if !result.Allowed() {
- allowed = false
+ t.Fatalf("eval %q: %v", policy.Query, err)
}
- }
- return allowed
-}
-
-// conjunctiveLeaves flattens a route tree into its leaves, refusing anything but
-// conjunction. Every route policy is All(...) today; a disjunction would make
-// "AND the leaves" the wrong fold, and silently so.
-func conjunctiveLeaves(t *testing.T, n Node) []Leaf {
- t.Helper()
- switch node := n.(type) {
- case Leaf:
- return []Leaf{node}
+ return result.Allowed()
case AllNode:
- var leaves []Leaf
- for _, child := range node.Children {
- leaves = append(leaves, conjunctiveLeaves(t, child)...)
+ for _, child := range policy.Children {
+ if !evalPolicyNode(t, child, input) {
+ return false
+ }
+ }
+ return true
+ case AnyNode:
+ for _, child := range policy.Children {
+ if evalPolicyNode(t, child, input) {
+ return true
+ }
}
- return leaves
+ return false
default:
- t.Fatalf("route policy contains a %T; this helper folds conjunctions only", n)
- return nil
+ t.Fatalf("route policy contains unknown node %T", node)
+ return false
}
}
diff --git a/libs/fleet/backend/auth/testdata/k8s-route-plan.txt b/libs/fleet/backend/auth/testdata/k8s-route-plan.txt
index 9069c597eb..2334be3850 100644
--- a/libs/fleet/backend/auth/testdata/k8s-route-plan.txt
+++ b/libs/fleet/backend/auth/testdata/k8s-route-plan.txt
@@ -1,4 +1,7 @@
All
Leaf query=data.authz_base.allow source=registered:authz-base
Leaf query=data.authz_k8s.allow source=multi["registered:authz","registered:authz-k8s"]
+ Any
+ Leaf query=data.custom_resource_creation_admission.exempt source=multi["registered:authz","registered:custom-resource-creation-admission"]
+ Leaf query=data.custom_resource_creation_admission.has_qualifying_card source=multi["registered:authz","registered:custom-resource-creation-admission"] facts=stripe_cards@registered-facts:stripe-cards facts=time@registered-facts:current-year facts=time@registered-facts:current-month
Leaf query=data.pool_admission.allow source=multi["registered:authz","registered:pool-admission"] body=1048576
diff --git a/libs/fleet/backend/auth/time_facts_test.go b/libs/fleet/backend/auth/time_facts_test.go
new file mode 100644
index 0000000000..503f1ef851
--- /dev/null
+++ b/libs/fleet/backend/auth/time_facts_test.go
@@ -0,0 +1,62 @@
+package auth
+
+import (
+ "context"
+ "net/http/httptest"
+ "testing"
+ "time"
+)
+
+func TestCurrentTimeFactsAreSeparateDeterministicScalars(t *testing.T) {
+ now := func() time.Time {
+ return time.Date(2026, time.August, 13, 23, 45, 0, 0, time.FixedZone("offset", -7*60*60))
+ }
+ request := httptest.NewRequest("GET", "/", nil)
+
+ yearFacts, err := CurrentYearFacts(now).LoadFacts(context.Background(), request)
+ if err != nil {
+ t.Fatalf("load current year: %v", err)
+ }
+ monthFacts, err := CurrentMonthFacts(now).LoadFacts(context.Background(), request)
+ if err != nil {
+ t.Fatalf("load current month: %v", err)
+ }
+ if len(yearFacts) != 1 || yearFacts["current_year"] != 2026 {
+ t.Fatalf("year facts = %#v, want current_year:2026", yearFacts)
+ }
+ if len(monthFacts) != 1 || monthFacts["current_month"] != 8 {
+ t.Fatalf("month facts = %#v, want current_month:8", monthFacts)
+ }
+ if CurrentYearFacts(now).CacheKey() == CurrentMonthFacts(now).CacheKey() {
+ t.Fatal("year and month providers must have distinct cache keys")
+ }
+}
+
+func TestCurrentTimeFactsShareOneLazyRequestSnapshot(t *testing.T) {
+ yearCalls := 0
+ monthCalls := 0
+ yearClock := func() time.Time {
+ yearCalls++
+ return time.Date(2026, time.December, 31, 23, 59, 59, 0, time.UTC)
+ }
+ monthClock := func() time.Time {
+ monthCalls++
+ return time.Date(2027, time.January, 1, 0, 0, 0, 0, time.UTC)
+ }
+ input := newRequestPolicyInput(httptest.NewRequest("GET", "/", nil), 0)
+
+ document, err := input.forPolicy(context.Background(), policyConfig{factProviders: []factProviderConfig{
+ {namespace: TimeFactNamespace, provider: CurrentYearFacts(yearClock)},
+ {namespace: TimeFactNamespace, provider: CurrentMonthFacts(monthClock)},
+ }})
+ if err != nil {
+ t.Fatalf("resolve time facts: %v", err)
+ }
+ timeFacts := document["facts"].(map[string]any)[TimeFactNamespace].(map[string]any)
+ if timeFacts["current_year"] != 2026 || timeFacts["current_month"] != 12 {
+ t.Fatalf("time facts = %#v, want one 2026-12 snapshot", timeFacts)
+ }
+ if yearCalls != 1 || monthCalls != 0 {
+ t.Fatalf("clock calls = year:%d month:%d, want 1/0", yearCalls, monthCalls)
+ }
+}
diff --git a/libs/fleet/backend/billing/service.go b/libs/fleet/backend/billing/service.go
index 903d90c313..bfe63ee11a 100644
--- a/libs/fleet/backend/billing/service.go
+++ b/libs/fleet/backend/billing/service.go
@@ -50,6 +50,7 @@ type Gateway interface {
CreateCustomer(ctx context.Context, metadata map[string]string, idempotencyKey string) (Customer, error)
UpdateCustomerMetadata(ctx context.Context, customerID string, metadata map[string]string) (Customer, error)
GetDefaultCard(ctx context.Context, customerID string) (SavedCard, error)
+ ListAttachedCards(ctx context.Context, customerID string) ([]SavedCard, error)
SetDefaultPaymentMethodForSetupGeneration(ctx context.Context, customerID, paymentMethodID, generation string) (bool, error)
CreateSetupSession(ctx context.Context, request SetupSessionRequest) (string, error)
CreatePortalSession(ctx context.Context, request PortalSessionRequest) (string, error)
@@ -87,6 +88,24 @@ func (s *Service) FindCustomer(ctx context.Context, subject string) (Customer, e
return Customer{}, ErrCustomerNotFound
}
+func (s *Service) findCustomerReadOnly(ctx context.Context, subject string) (Customer, error) {
+ customers, err := s.gateway.SearchCustomers(ctx, subject)
+ if err != nil {
+ return Customer{}, err
+ }
+ for _, customer := range customers {
+ if customer.Metadata[MetadataSubject] == subject {
+ return customer, nil
+ }
+ }
+ for _, customer := range customers {
+ if customer.Metadata[LegacyMetadataSubject] == subject && customer.Metadata[MetadataSubject] == "" {
+ return customer, nil
+ }
+ }
+ return Customer{}, ErrCustomerNotFound
+}
+
func (s *Service) FindOrCreateCustomer(ctx context.Context, subject string) (Customer, error) {
customer, err := s.FindCustomer(ctx, subject)
if err == nil {
@@ -112,6 +131,24 @@ type Summary struct {
Card *CardSummary `json:"card" binding:"required" extensions:"x-nullable"`
}
+func (s *Service) AttachedCards(ctx context.Context, subject string) ([]SavedCard, error) {
+ customer, err := s.findCustomerReadOnly(ctx, subject)
+ if errors.Is(err, ErrCustomerNotFound) {
+ return []SavedCard{}, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ cards, err := s.gateway.ListAttachedCards(ctx, customer.ID)
+ if err != nil {
+ return nil, err
+ }
+ if cards == nil {
+ return []SavedCard{}, nil
+ }
+ return cards, nil
+}
+
func (s *Service) Summary(ctx context.Context, subject string) (Summary, error) {
customer, err := s.FindCustomer(ctx, subject)
if errors.Is(err, ErrCustomerNotFound) {
diff --git a/libs/fleet/backend/billing/service_test.go b/libs/fleet/backend/billing/service_test.go
index 94a3cdff3a..0bbc564ff6 100644
--- a/libs/fleet/backend/billing/service_test.go
+++ b/libs/fleet/backend/billing/service_test.go
@@ -12,6 +12,10 @@ import (
type fakeGateway struct {
searchSubject string
customers []Customer
+ searchErr error
+ cards []SavedCard
+ cardsErr error
+ listCardsCalls int
createdMetadata map[string]string
createIdempotencyKey string
createdCustomer Customer
@@ -33,7 +37,7 @@ type fakeGateway struct {
func (f *fakeGateway) SearchCustomers(_ context.Context, subject string) ([]Customer, error) {
f.searchSubject = subject
- return f.customers, nil
+ return f.customers, f.searchErr
}
func (f *fakeGateway) CreateCustomer(_ context.Context, metadata map[string]string, idempotencyKey string) (Customer, error) {
@@ -55,6 +59,11 @@ func (f *fakeGateway) UpdateCustomerMetadata(_ context.Context, customerID strin
return Customer{ID: customerID, Metadata: metadata}, nil
}
+func (f *fakeGateway) ListAttachedCards(_ context.Context, _ string) ([]SavedCard, error) {
+ f.listCardsCalls++
+ return f.cards, f.cardsErr
+}
+
func (f *fakeGateway) GetDefaultCard(_ context.Context, _ string) (SavedCard, error) {
return f.defaultCard, f.defaultCardErr
}
@@ -350,3 +359,43 @@ func TestCreateSetupSessionReturnsNoURLWhenGenerationPublishFails(t *testing.T)
t.Fatalf("url/error/operations = %q/%v/%#v", url, err, gateway.operations)
}
}
+
+func TestAttachedCards(t *testing.T) {
+ gatewayErr := errors.New("stripe unavailable")
+
+ cases := []struct {
+ name string
+ customers []Customer
+ searchErr error
+ cards []SavedCard
+ cardsErr error
+ want []SavedCard
+ wantErr error
+ wantLists int
+ }{
+ {name: "no customer", want: []SavedCard{}},
+ {name: "empty attached card list", customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}}, want: []SavedCard{}, wantLists: 1},
+ {name: "legacy customer is read without metadata migration", customers: []Customer{{ID: "cus_legacy", Metadata: map[string]string{LegacyMetadataSubject: "subject-123"}}}, cards: []SavedCard{{Brand: "visa", Last4: "4242", ExpMonth: 9, ExpYear: 2026}}, want: []SavedCard{{Brand: "visa", Last4: "4242", ExpMonth: 9, ExpYear: 2026}}, wantLists: 1},
+ {name: "attached cards are returned without qualification", customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}}, cards: []SavedCard{{ExpMonth: 1, ExpYear: 2025}, {ExpMonth: 1, ExpYear: 2027}}, want: []SavedCard{{ExpMonth: 1, ExpYear: 2025}, {ExpMonth: 1, ExpYear: 2027}}, wantLists: 1},
+ {name: "customer search error", searchErr: gatewayErr, wantErr: gatewayErr},
+ {name: "card listing error", customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}}, cardsErr: gatewayErr, wantErr: gatewayErr, wantLists: 1},
+ }
+ for _, testCase := range cases {
+ t.Run(testCase.name, func(t *testing.T) {
+ gateway := &fakeGateway{customers: testCase.customers, searchErr: testCase.searchErr, cards: testCase.cards, cardsErr: testCase.cardsErr}
+ got, err := NewService(gateway).AttachedCards(context.Background(), "subject-123")
+ if !errors.Is(err, testCase.wantErr) || !reflect.DeepEqual(got, testCase.want) {
+ t.Fatalf("AttachedCards() = %#v, %v; want %#v, %v", got, err, testCase.want, testCase.wantErr)
+ }
+ if gateway.createCalls != 0 {
+ t.Fatalf("CreateCustomer calls = %d, want 0", gateway.createCalls)
+ }
+ if gateway.updatedMetadata != nil {
+ t.Fatalf("UpdateCustomerMetadata called during authorization: %#v", gateway.updatedMetadata)
+ }
+ if gateway.listCardsCalls != testCase.wantLists {
+ t.Fatalf("ListAttachedCards calls = %d, want %d", gateway.listCardsCalls, testCase.wantLists)
+ }
+ })
+ }
+}
diff --git a/libs/fleet/backend/billing/stripe_gateway.go b/libs/fleet/backend/billing/stripe_gateway.go
index e20193ceae..b657d6f235 100644
--- a/libs/fleet/backend/billing/stripe_gateway.go
+++ b/libs/fleet/backend/billing/stripe_gateway.go
@@ -101,6 +101,29 @@ func savedCardFromCustomer(customer *stripe.Customer) (SavedCard, error) {
}, nil
}
+func (g *StripeGateway) ListAttachedCards(ctx context.Context, customerID string) ([]SavedCard, error) {
+ params := &stripe.PaymentMethodListParams{
+ Customer: stripe.String(customerID),
+ Type: stripe.String(string(stripe.PaymentMethodTypeCard)),
+ }
+ cards := make([]SavedCard, 0)
+ for paymentMethod, err := range g.client.V1PaymentMethods.List(ctx, params).All(ctx) {
+ if err != nil {
+ return nil, err
+ }
+ if paymentMethod.Card == nil {
+ continue
+ }
+ cards = append(cards, SavedCard{
+ Brand: string(paymentMethod.Card.Brand),
+ Last4: paymentMethod.Card.Last4,
+ ExpMonth: paymentMethod.Card.ExpMonth,
+ ExpYear: paymentMethod.Card.ExpYear,
+ })
+ }
+ return cards, nil
+}
+
func (g *StripeGateway) GetDefaultCard(ctx context.Context, customerID string) (SavedCard, error) {
customer, err := g.client.V1Customers.Retrieve(ctx, customerID, defaultCardRetrieveParams())
if err != nil {
diff --git a/libs/fleet/backend/billing/stripe_gateway_test.go b/libs/fleet/backend/billing/stripe_gateway_test.go
index 67ee0873f7..57a5030cc4 100644
--- a/libs/fleet/backend/billing/stripe_gateway_test.go
+++ b/libs/fleet/backend/billing/stripe_gateway_test.go
@@ -1,7 +1,13 @@
package billing
import (
+ "context"
"errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "reflect"
"testing"
"github.com/stripe/stripe-go/v85"
@@ -162,3 +168,47 @@ func TestCurrentSetupGenerationIgnoresDuplicateAfterMarkerConsumption(t *testing
t.Fatal("duplicate delivery must not match a consumed marker")
}
}
+
+func TestListAttachedCardsFiltersAndPaginates(t *testing.T) {
+ var requests []url.Values
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet || r.URL.Path != "/v1/payment_methods" {
+ t.Fatalf("request = %s %s, want GET /v1/payment_methods", r.Method, r.URL.Path)
+ }
+ requests = append(requests, r.URL.Query())
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Query().Get("starting_after") == "" {
+ _, _ = io.WriteString(w, `{"object":"list","data":[{"id":"pm_1","object":"payment_method","type":"card","card":{"brand":"visa","last4":"4242","exp_month":8,"exp_year":2026}}],"has_more":true,"url":"/v1/payment_methods"}`)
+ return
+ }
+ _, _ = io.WriteString(w, `{"object":"list","data":[{"id":"pm_2","object":"payment_method","type":"card","card":{"brand":"mastercard","last4":"4444","exp_month":1,"exp_year":2027,"fingerprint":"must-not-leak"}}],"has_more":false,"url":"/v1/payment_methods"}`)
+ }))
+ defer server.Close()
+
+ backend := stripe.GetBackendWithConfig(stripe.APIBackend, &stripe.BackendConfig{URL: stripe.String(server.URL)})
+ client := stripe.NewClient("sk_test", stripe.WithBackends(&stripe.Backends{API: backend, Connect: backend, Uploads: backend, MeterEvents: backend}))
+ gateway := &StripeGateway{client: client}
+
+ cards, err := gateway.ListAttachedCards(context.Background(), "cus_owned")
+ if err != nil {
+ t.Fatalf("ListAttachedCards() error = %v", err)
+ }
+ want := []SavedCard{
+ {Brand: "visa", Last4: "4242", ExpMonth: 8, ExpYear: 2026},
+ {Brand: "mastercard", Last4: "4444", ExpMonth: 1, ExpYear: 2027},
+ }
+ if !reflect.DeepEqual(cards, want) {
+ t.Fatalf("cards = %#v, want %#v", cards, want)
+ }
+ if len(requests) != 2 {
+ t.Fatalf("request count = %d, want 2", len(requests))
+ }
+ for i, query := range requests {
+ if query.Get("customer") != "cus_owned" || query.Get("type") != "card" {
+ t.Fatalf("request %d query = %v, want customer=cus_owned and type=card", i+1, query)
+ }
+ }
+ if got := requests[1].Get("starting_after"); got != "pm_1" {
+ t.Fatalf("second page starting_after = %q, want pm_1", got)
+ }
+}
diff --git a/libs/fleet/backend/handlers/billing.go b/libs/fleet/backend/handlers/billing.go
index de83d071c8..c01de7e1c2 100644
--- a/libs/fleet/backend/handlers/billing.go
+++ b/libs/fleet/backend/handlers/billing.go
@@ -13,6 +13,7 @@ import (
)
type BillingService interface {
+ AttachedCards(ctx context.Context, subject string) ([]billing.SavedCard, error)
Summary(ctx context.Context, subject string) (billing.Summary, error)
CreateSetupSession(ctx context.Context, subject string, options billing.SetupOptions) (string, error)
CreatePortalSession(ctx context.Context, subject, returnURL string) (string, error)
diff --git a/libs/fleet/backend/handlers/billing_facts.go b/libs/fleet/backend/handlers/billing_facts.go
new file mode 100644
index 0000000000..d29a301982
--- /dev/null
+++ b/libs/fleet/backend/handlers/billing_facts.go
@@ -0,0 +1,42 @@
+package handlers
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+
+ "cyclops-cs-backend/auth"
+)
+
+func StripeCardFacts(handlers Handlers) auth.FactProvider {
+ return stripeCardFacts{handlers: handlers}
+}
+
+type stripeCardFacts struct{ handlers Handlers }
+
+func (stripeCardFacts) CacheKey() string { return auth.StripeCardsFactProvider }
+
+func (facts stripeCardFacts) LoadFacts(ctx context.Context, request *http.Request) (auth.FactSet, error) {
+ if facts.handlers.Billing == nil {
+ return nil, fmt.Errorf("billing service is not configured")
+ }
+ user := auth.GetUser(request.Context())
+ if user == nil || user.ID == "" {
+ return nil, fmt.Errorf("Stripe card fact requires an authenticated user subject")
+ }
+ cards, err := facts.handlers.Billing.AttachedCards(ctx, user.ID)
+ if err != nil {
+ return nil, &auth.FactUnavailableError{
+ Namespace: auth.StripeCardsFactNamespace,
+ Err: fmt.Errorf("Stripe attached-card lookup failed"),
+ }
+ }
+ projected := make([]map[string]any, 0, len(cards))
+ for _, card := range cards {
+ projected = append(projected, map[string]any{
+ "exp_year": card.ExpYear,
+ "exp_month": card.ExpMonth,
+ })
+ }
+ return auth.FactSet{"cards": projected}, nil
+}
diff --git a/libs/fleet/backend/handlers/billing_facts_test.go b/libs/fleet/backend/handlers/billing_facts_test.go
new file mode 100644
index 0000000000..17fd58f3f2
--- /dev/null
+++ b/libs/fleet/backend/handlers/billing_facts_test.go
@@ -0,0 +1,106 @@
+package handlers
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "testing"
+
+ "cyclops-cs-backend/auth"
+ "cyclops-cs-backend/billing"
+)
+
+type cardEligibilityBilling struct {
+ subject string
+ cards []billing.SavedCard
+ err error
+ calls int
+}
+
+func (service *cardEligibilityBilling) AttachedCards(_ context.Context, subject string) ([]billing.SavedCard, error) {
+ service.calls++
+ service.subject = subject
+ return service.cards, service.err
+}
+
+func (service *cardEligibilityBilling) Summary(context.Context, string) (billing.Summary, error) {
+ panic("unexpected Summary call")
+}
+func (service *cardEligibilityBilling) SetDefaultPaymentMethodForSetupGeneration(context.Context, string, string, string) (bool, error) {
+ panic("unexpected webhook call")
+}
+func (service *cardEligibilityBilling) CreateSetupSession(context.Context, string, billing.SetupOptions) (string, error) {
+ panic("unexpected setup call")
+}
+func (service *cardEligibilityBilling) CreatePortalSession(context.Context, string, string) (string, error) {
+ panic("unexpected portal call")
+}
+
+func stripeFactRequest(user *auth.User) *http.Request {
+ request := httptest.NewRequest("POST", "/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims", nil)
+ if user == nil {
+ return request
+ }
+ return request.WithContext(context.WithValue(request.Context(), auth.UserKey, user))
+}
+
+func TestStripeCardFacts(t *testing.T) {
+ stripeErr := errors.New("stripe unavailable: customer cus_secret payment method pm_secret")
+ cases := []struct {
+ name string
+ user *auth.User
+ cards []billing.SavedCard
+ serviceErr error
+ wantFacts auth.FactSet
+ wantUnavailable bool
+ wantError bool
+ wantCalls int
+ }{
+ {
+ name: "projects only raw expiration fields",
+ user: &auth.User{ID: "user-123"},
+ cards: []billing.SavedCard{{Brand: "visa", Last4: "4242", ExpYear: 2027, ExpMonth: 3}},
+ wantFacts: auth.FactSet{"cards": []map[string]any{{
+ "exp_year": int64(2027), "exp_month": int64(3),
+ }}},
+ wantCalls: 1,
+ },
+ {name: "empty cards are a definite fact", user: &auth.User{ID: "user-123"}, wantFacts: auth.FactSet{"cards": []map[string]any{}}, wantCalls: 1},
+ {name: "missing user is internal wiring error", wantError: true},
+ {name: "empty subject is internal wiring error", user: &auth.User{}, wantError: true},
+ {name: "Stripe error is unavailable", user: &auth.User{ID: "user-123"}, serviceErr: stripeErr, wantUnavailable: true, wantCalls: 1},
+ }
+
+ for _, testCase := range cases {
+ t.Run(testCase.name, func(t *testing.T) {
+ service := &cardEligibilityBilling{cards: testCase.cards, err: testCase.serviceErr}
+ provider := StripeCardFacts(Handlers{Billing: service})
+ facts, err := provider.LoadFacts(context.Background(), stripeFactRequest(testCase.user))
+ var unavailable *auth.FactUnavailableError
+ if testCase.wantUnavailable != errors.As(err, &unavailable) {
+ t.Fatalf("unavailable error = %v, want %v; err = %v", errors.As(err, &unavailable), testCase.wantUnavailable, err)
+ }
+ if testCase.wantUnavailable && (strings.Contains(err.Error(), "cus_secret") || strings.Contains(err.Error(), "pm_secret")) {
+ t.Fatalf("unavailable error leaked raw Stripe details: %v", err)
+ }
+ if testCase.wantError != (err != nil) && !testCase.wantUnavailable {
+ t.Fatalf("error = %v, wantError %v", err, testCase.wantError)
+ }
+ if !reflect.DeepEqual(facts, testCase.wantFacts) {
+ t.Fatalf("facts = %#v, want %#v", facts, testCase.wantFacts)
+ }
+ if service.calls != testCase.wantCalls {
+ t.Fatalf("calls = %d, want %d", service.calls, testCase.wantCalls)
+ }
+ if service.calls > 0 && service.subject != "user-123" {
+ t.Fatalf("subject = %q, want resolved User.ID", service.subject)
+ }
+ if len(facts) > 1 {
+ t.Fatalf("fact leaked extra data: %#v", facts)
+ }
+ })
+ }
+}
diff --git a/libs/fleet/backend/handlers/billing_test.go b/libs/fleet/backend/handlers/billing_test.go
index 8f79e03419..1596db3af0 100644
--- a/libs/fleet/backend/handlers/billing_test.go
+++ b/libs/fleet/backend/handlers/billing_test.go
@@ -32,6 +32,10 @@ type fakeBillingService struct {
defaultErr error
}
+func (f *fakeBillingService) AttachedCards(context.Context, string) ([]billing.SavedCard, error) {
+ return []billing.SavedCard{}, nil
+}
+
func (f *fakeBillingService) Summary(_ context.Context, subject string) (billing.Summary, error) {
f.summaryCalls++
f.summarySubject = subject
diff --git a/libs/fleet/backend/main.go b/libs/fleet/backend/main.go
index c07e2e1ab2..4683283d31 100644
--- a/libs/fleet/backend/main.go
+++ b/libs/fleet/backend/main.go
@@ -123,6 +123,9 @@ func setupRouter(c handlers.Handlers) http.Handler {
// before the first RouteMiddleware below, because that is what compiles the
// plans that refer to it.
auth.RegisterFactProvider(auth.NamespaceRBACFactProvider, handlers.NamespaceRBACFacts(c))
+ auth.RegisterFactProvider(auth.StripeCardsFactProvider, handlers.StripeCardFacts(c))
+ auth.RegisterFactProvider(auth.CurrentYearFactProvider, auth.CurrentYearFacts(time.Now))
+ auth.RegisterFactProvider(auth.CurrentMonthFactProvider, auth.CurrentMonthFacts(time.Now))
r := http.NewServeMux()
diff --git a/libs/fleet/backend/main_test.go b/libs/fleet/backend/main_test.go
index 3570088880..d55a87919a 100644
--- a/libs/fleet/backend/main_test.go
+++ b/libs/fleet/backend/main_test.go
@@ -15,6 +15,7 @@ import (
"net/http"
"net/http/httptest"
"os"
+ "os/exec"
"slices"
"strings"
"testing"
@@ -186,6 +187,11 @@ func TestMain(m *testing.M) {
}))
defer jwksServer.Close()
+ if os.Getenv("CARD_ADMISSION_ROUTER_HELPER") != "1" {
+ if err := os.Setenv("CYCLOPS_CS_REQUIRE_CARD_FOR_CUSTOM_RESOURCE_CREATION", "false"); err != nil {
+ panic(err)
+ }
+ }
if err := os.Setenv("CYCLOPS_CS_ADMIN_SUBS", `[]`); err != nil {
panic(err)
}
@@ -245,6 +251,10 @@ func bigEndianBytes(v int) []byte {
type routerBillingService struct{}
+func (routerBillingService) AttachedCards(context.Context, string) ([]billing.SavedCard, error) {
+ return []billing.SavedCard{}, nil
+}
+
func (routerBillingService) Summary(context.Context, string) (billing.Summary, error) {
return billing.Summary{}, nil
}
@@ -461,6 +471,96 @@ func TestNginxRoutesChatToBackend(t *testing.T) {
}
}
+type routerCardBilling struct {
+ cards []billing.SavedCard
+ err error
+ calls int
+}
+
+func (service *routerCardBilling) AttachedCards(context.Context, string) ([]billing.SavedCard, error) {
+ service.calls++
+ return service.cards, service.err
+}
+func (*routerCardBilling) Summary(context.Context, string) (billing.Summary, error) {
+ panic("unexpected Summary call")
+}
+func (*routerCardBilling) CreateSetupSession(context.Context, string, billing.SetupOptions) (string, error) {
+ panic("unexpected setup call")
+}
+func (*routerCardBilling) CreatePortalSession(context.Context, string, string) (string, error) {
+ panic("unexpected portal call")
+}
+func (*routerCardBilling) SetDefaultPaymentMethodForSetupGeneration(context.Context, string, string, string) (bool, error) {
+ panic("unexpected webhook call")
+}
+
+func TestK8sRouteRejectsCustomResourceCreateWithoutCardBeforeProxy(t *testing.T) {
+ if os.Getenv("CARD_ADMISSION_ROUTER_HELPER") != "1" {
+ command := exec.Command(os.Args[0], "-test.run=^TestK8sRouteRejectsCustomResourceCreateWithoutCardBeforeProxy$")
+ command.Env = append(os.Environ(),
+ "CARD_ADMISSION_ROUTER_HELPER=1",
+ "CYCLOPS_CS_REQUIRE_CARD_FOR_CUSTOM_RESOURCE_CREATION=true",
+ )
+ output, err := command.CombinedOutput()
+ if err != nil {
+ t.Fatalf("enabled router subprocess failed: %v\n%s", err, output)
+ }
+ return
+ }
+
+ upstreamCalled := false
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ upstreamCalled = true
+ w.WriteHeader(http.StatusCreated)
+ }))
+ defer upstream.Close()
+ t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)
+
+ service := &routerCardBilling{}
+ router := setupRouter(handlers.Handlers{Billing: service})
+ cases := []struct {
+ name string
+ path string
+ body string
+ }{
+ {
+ name: "legacy workspace pool",
+ path: "/api/k8s/apis/cua.ai/v1/namespaces/foo/osgymworkspacepools",
+ body: `{"spec":{"template":{"containerDiskImage":"public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:latest","imagePullSecret":"ecr-credentials"}}}`,
+ },
+ {
+ name: "native sandbox template",
+ path: "/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/foo/osgymsandboxtemplates",
+ body: `{"spec":{"vmTemplate":{"containerDiskImage":"public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:latest","imagePullSecret":"ecr-credentials"}}}`,
+ },
+ }
+ for _, testCase := range cases {
+ t.Run(testCase.name, func(t *testing.T) {
+ response := httptest.NewRecorder()
+ router.ServeHTTP(response, authorizedRequest(t, http.MethodPost, testCase.path, strings.NewReader(testCase.body)))
+ if response.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want 403; body = %s", response.Code, response.Body.String())
+ }
+ })
+ }
+ if upstreamCalled {
+ t.Fatal("denied custom-resource create reached kubectl proxy")
+ }
+
+ service.cards = []billing.SavedCard{{ExpYear: 2099, ExpMonth: 1}}
+ response := httptest.NewRecorder()
+ router.ServeHTTP(response, authorizedRequest(t, http.MethodPost, cases[0].path, strings.NewReader(cases[0].body)))
+ if response.Code != http.StatusCreated {
+ t.Fatalf("valid attached card status = %d, want 201; body = %s", response.Code, response.Body.String())
+ }
+ if !upstreamCalled {
+ t.Fatal("allowed custom-resource create did not reach kubectl proxy")
+ }
+ if service.calls != len(cases)+1 {
+ t.Fatalf("Stripe attached-card calls = %d, want %d", service.calls, len(cases)+1)
+ }
+}
+
func TestInitializeDatabaseFeatures(t *testing.T) {
tests := []struct {
name string