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): grandfather pre-cutoff billing users (#6833)

r33drichardsb762f256f8ad
diff --git a/libs/fleet/backend/auth/custom_resource_creation_admission.rego b/libs/fleet/backend/auth/custom_resource_creation_admission.rego
index 2f819078a9..df59d37123 100644
--- a/libs/fleet/backend/auth/custom_resource_creation_admission.rego
+++ b/libs/fleet/backend/auth/custom_resource_creation_admission.rego
@@ -7,6 +7,8 @@ default exempt = false
default has_qualifying_card = false
+default billing_eligible = false
+
custom_api_group(group) {
group == "cua.ai"
}
@@ -51,6 +53,14 @@ exempt {
input.flags.card_requirement_exempt_subs[_] == input.user.sub
}
+billing_eligible {
+ input.facts.stripe_cards.grandfathered == true
+}
+
+billing_eligible {
+ has_qualifying_card
+}
+
has_qualifying_card {
current_year := input.facts.time.current_year
input.facts.time.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
index 2d04ef32b3..56b0f331a0 100644
--- a/libs/fleet/backend/auth/custom_resource_creation_admission_test.rego
+++ b/libs/fleet/backend/auth/custom_resource_creation_admission_test.rego
@@ -63,6 +63,18 @@ test_non_admin_custom_resource_create_not_exempt {
)
}
+test_user_created_before_cutoff_is_grandfathered {
+ custom_resource_creation_admission.billing_eligible with input as {
+ "facts": {"stripe_cards": {"grandfathered": true, "cards": []}},
+ }
+}
+
+test_user_created_at_cutoff_without_card_is_not_eligible {
+ not custom_resource_creation_admission.billing_eligible with input as {
+ "facts": {"stripe_cards": {"grandfathered": false, "cards": []}},
+ }
+}
+
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",
diff --git a/libs/fleet/backend/auth/policy_routes.go b/libs/fleet/backend/auth/policy_routes.go
index 4c5d48c630..877fa32bc8 100644
--- a/libs/fleet/backend/auth/policy_routes.go
+++ b/libs/fleet/backend/auth/policy_routes.go
@@ -197,7 +197,7 @@ func CustomResourceCreationAdmissionPolicy() Node {
return Any(
leaf("data.custom_resource_creation_admission.exempt"),
leaf(
- "data.custom_resource_creation_admission.has_qualifying_card",
+ "data.custom_resource_creation_admission.billing_eligible",
WithFacts(StripeCardsFactNamespace, RegisteredFacts(StripeCardsFactProvider)),
WithFacts(TimeFactNamespace, RegisteredFacts(CurrentYearFactProvider)),
WithFacts(TimeFactNamespace, RegisteredFacts(CurrentMonthFactProvider)),
diff --git a/libs/fleet/backend/auth/testdata/k8s-route-plan.txt b/libs/fleet/backend/auth/testdata/k8s-route-plan.txt
index 2334be3850..eff10236e9 100644
--- a/libs/fleet/backend/auth/testdata/k8s-route-plan.txt
+++ b/libs/fleet/backend/auth/testdata/k8s-route-plan.txt
@@ -3,5 +3,5 @@ All
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.custom_resource_creation_admission.billing_eligible source=multi["registered:authz","registered:custom-resource-creation-admission"] facts=stripe_cards@registered-facts:stripe-cards facts=time@registered-facts:current-year facts=time@registered-facts:current-month
Leaf query=data.pool_admission.allow source=multi["registered:authz","registered:pool-admission"] body=1048576
diff --git a/libs/fleet/backend/handlers/billing_facts.go b/libs/fleet/backend/handlers/billing_facts.go
index d29a301982..dad38a843a 100644
--- a/libs/fleet/backend/handlers/billing_facts.go
+++ b/libs/fleet/backend/handlers/billing_facts.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"net/http"
+ "time"
"cyclops-cs-backend/auth"
)
@@ -12,18 +13,37 @@ func StripeCardFacts(handlers Handlers) auth.FactProvider {
return stripeCardFacts{handlers: handlers}
}
+var billingCardRequiredFrom = time.Date(2026, time.August, 15, 0, 0, 0, 0, time.UTC)
+
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")
+ if facts.handlers.UserAccounts == nil {
+ return nil, fmt.Errorf("user account 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")
}
+ createdAt, err := facts.handlers.UserAccounts.UserCreatedAt(ctx, user.ID)
+ if err != nil {
+ return nil, &auth.FactUnavailableError{
+ Namespace: auth.StripeCardsFactNamespace,
+ Err: fmt.Errorf("Keycloak user lookup failed"),
+ }
+ }
+ if createdAt.Before(billingCardRequiredFrom) {
+ return auth.FactSet{
+ "grandfathered": true,
+ "cards": []map[string]any{},
+ }, nil
+ }
+ if facts.handlers.Billing == nil {
+ return nil, fmt.Errorf("billing service is not configured")
+ }
+
cards, err := facts.handlers.Billing.AttachedCards(ctx, user.ID)
if err != nil {
return nil, &auth.FactUnavailableError{
diff --git a/libs/fleet/backend/handlers/billing_facts_test.go b/libs/fleet/backend/handlers/billing_facts_test.go
index 17fd58f3f2..7c626a7733 100644
--- a/libs/fleet/backend/handlers/billing_facts_test.go
+++ b/libs/fleet/backend/handlers/billing_facts_test.go
@@ -8,11 +8,25 @@ import (
"reflect"
"strings"
"testing"
+ "time"
"cyclops-cs-backend/auth"
"cyclops-cs-backend/billing"
)
+type cardEligibilityAccounts struct {
+ createdAt time.Time
+ err error
+ subject string
+ calls int
+}
+
+func (accounts *cardEligibilityAccounts) UserCreatedAt(_ context.Context, subject string) (time.Time, error) {
+ accounts.calls++
+ accounts.subject = subject
+ return accounts.createdAt, accounts.err
+}
+
type cardEligibilityBilling struct {
subject string
cards []billing.SavedCard
@@ -50,34 +64,54 @@ func stripeFactRequest(user *auth.User) *http.Request {
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 string
+ user *auth.User
+ cards []billing.SavedCard
+ createdAt time.Time
+ accountErr error
+ serviceErr error
+ withoutBilling bool
+ wantFacts auth.FactSet
+ wantUnavailable bool
+ wantError bool
+ wantCalls int
+ wantAccountCalls int
}{
{
- name: "projects only raw expiration fields",
- user: &auth.User{ID: "user-123"},
- cards: []billing.SavedCard{{Brand: "visa", Last4: "4242", ExpYear: 2027, ExpMonth: 3}},
+ name: "projects only raw expiration fields",
+ user: &auth.User{ID: "user-123"},
+ createdAt: time.Date(2026, time.August, 15, 0, 0, 0, 0, time.UTC),
+ 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,
+ wantCalls: 1,
+ wantAccountCalls: 1,
},
- {name: "empty cards are a definite fact", user: &auth.User{ID: "user-123"}, wantFacts: auth.FactSet{"cards": []map[string]any{}}, wantCalls: 1},
+ {
+ name: "user created through August 14 is grandfathered without Stripe",
+ user: &auth.User{ID: "user-123"},
+ createdAt: time.Date(2026, time.August, 14, 23, 59, 59, int(time.Second-time.Nanosecond), time.UTC),
+ wantFacts: auth.FactSet{"grandfathered": true, "cards": []map[string]any{}},
+ withoutBilling: true,
+ wantAccountCalls: 1,
+ },
+ {name: "empty cards are a definite fact at cutoff", user: &auth.User{ID: "user-123"}, createdAt: time.Date(2026, time.August, 15, 0, 0, 0, 0, time.UTC), wantFacts: auth.FactSet{"cards": []map[string]any{}}, wantCalls: 1, wantAccountCalls: 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},
+ {name: "Stripe error is unavailable", user: &auth.User{ID: "user-123"}, createdAt: time.Date(2026, time.August, 15, 0, 0, 0, 0, time.UTC), serviceErr: stripeErr, wantUnavailable: true, wantCalls: 1, wantAccountCalls: 1},
+ {name: "Keycloak error is unavailable before Stripe", user: &auth.User{ID: "user-123"}, accountErr: errors.New("keycloak unavailable"), wantUnavailable: true, wantAccountCalls: 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})
+ accounts := &cardEligibilityAccounts{createdAt: testCase.createdAt, err: testCase.accountErr}
+ var billingService BillingService = service
+ if testCase.withoutBilling {
+ billingService = nil
+ }
+ provider := StripeCardFacts(Handlers{Billing: billingService, UserAccounts: accounts})
facts, err := provider.LoadFacts(context.Background(), stripeFactRequest(testCase.user))
var unavailable *auth.FactUnavailableError
if testCase.wantUnavailable != errors.As(err, &unavailable) {
@@ -93,12 +127,15 @@ func TestStripeCardFacts(t *testing.T) {
t.Fatalf("facts = %#v, want %#v", facts, testCase.wantFacts)
}
if service.calls != testCase.wantCalls {
- t.Fatalf("calls = %d, want %d", service.calls, testCase.wantCalls)
+ t.Fatalf("billing calls = %d, want %d", service.calls, testCase.wantCalls)
+ }
+ if accounts.calls != testCase.wantAccountCalls {
+ t.Fatalf("account calls = %d, want %d", accounts.calls, testCase.wantAccountCalls)
}
if service.calls > 0 && service.subject != "user-123" {
t.Fatalf("subject = %q, want resolved User.ID", service.subject)
}
- if len(facts) > 1 {
+ if len(facts) > 2 {
t.Fatalf("fact leaked extra data: %#v", facts)
}
})
diff --git a/libs/fleet/backend/handlers/handlers.go b/libs/fleet/backend/handlers/handlers.go
index cb875d8566..7937890558 100644
--- a/libs/fleet/backend/handlers/handlers.go
+++ b/libs/fleet/backend/handlers/handlers.go
@@ -10,6 +10,7 @@ import (
"net"
"net/http"
"regexp"
+ "time"
"cyclops-cs-backend/auth"
"cyclops-cs-backend/chat"
@@ -20,6 +21,10 @@ import (
"go.opentelemetry.io/otel/trace"
)
+type UserAccountService interface {
+ UserCreatedAt(ctx context.Context, subject string) (time.Time, error)
+}
+
type Handlers struct {
Admin *keycloak.Admin
GatewayCfg config.GatewayConfiguration
@@ -27,6 +32,7 @@ type Handlers struct {
KC config.KeycloakConfiguration
Stripe config.StripeConfiguration
Billing BillingService
+ UserAccounts UserAccountService
WebhookVerifier WebhookVerifier
GitHubTrustPolicies githubtrust.Store
@@ -51,13 +57,14 @@ type Handlers struct {
func New(admin *keycloak.Admin, cfg *config.Configuration) Handlers {
return Handlers{
- Admin: admin,
- GatewayCfg: cfg.Gateway,
- AuthCfg: cfg.Auth,
- KC: cfg.Keycloak,
- Stripe: cfg.Stripe,
- ChatAccess: cfg.Chat.Access,
- chatLocks: newConversationLockRegistry(),
+ Admin: admin,
+ UserAccounts: admin,
+ GatewayCfg: cfg.Gateway,
+ AuthCfg: cfg.Auth,
+ KC: cfg.Keycloak,
+ Stripe: cfg.Stripe,
+ ChatAccess: cfg.Chat.Access,
+ chatLocks: newConversationLockRegistry(),
}
}
diff --git a/libs/fleet/backend/keycloak/admin.go b/libs/fleet/backend/keycloak/admin.go
index cbdbae8813..bee06a7304 100644
--- a/libs/fleet/backend/keycloak/admin.go
+++ b/libs/fleet/backend/keycloak/admin.go
@@ -61,6 +61,29 @@ func (a *Admin) token(ctx context.Context) (string, error) {
return t.AccessToken, nil
}
+func (a *Admin) UserCreatedAt(ctx context.Context, subject string) (createdAt time.Time, err error) {
+ ctx, span := adminTracer().Start(ctx, "keycloak.get_user_created_at", trace.WithAttributes(
+ attribute.String("keycloak.realm", a.realm),
+ ))
+ defer span.End()
+
+ start := time.Now()
+ defer func() { metrics.RecordKeycloakRequest("GetUserByID", time.Since(start), err) }()
+
+ tok, err := a.token(ctx)
+ if err != nil {
+ return time.Time{}, err
+ }
+ user, err := a.client.GetUserByID(ctx, tok, a.realm, subject)
+ if err != nil {
+ return time.Time{}, fmt.Errorf("get user by ID: %w", err)
+ }
+ if user.CreatedTimestamp == nil {
+ return time.Time{}, fmt.Errorf("user created timestamp is missing")
+ }
+ return time.UnixMilli(*user.CreatedTimestamp).UTC(), nil
+}
+
type KeyClient struct {
ID string `json:"id"`
ClientID string `json:"client_id"`
diff --git a/libs/fleet/backend/main_test.go b/libs/fleet/backend/main_test.go
index d55a87919a..822566055f 100644
--- a/libs/fleet/backend/main_test.go
+++ b/libs/fleet/backend/main_test.go
@@ -471,6 +471,12 @@ func TestNginxRoutesChatToBackend(t *testing.T) {
}
}
+type routerCardAccounts struct{}
+
+func (routerCardAccounts) UserCreatedAt(context.Context, string) (time.Time, error) {
+ return time.Date(2026, time.August, 15, 0, 0, 0, 0, time.UTC), nil
+}
+
type routerCardBilling struct {
cards []billing.SavedCard
err error
@@ -517,7 +523,7 @@ func TestK8sRouteRejectsCustomResourceCreateWithoutCardBeforeProxy(t *testing.T)
t.Setenv("KUBECTL_PROXY_ADDR", upstream.URL)
service := &routerCardBilling{}
- router := setupRouter(handlers.Handlers{Billing: service})
+ router := setupRouter(handlers.Handlers{Billing: service, UserAccounts: routerCardAccounts{}})
cases := []struct {
name string
path string