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.

Gate pool creation on payment card requirement (#7249)

r33drichards93601ad872a1
diff --git a/libs/fleet/backend/auth/middlewares.go b/libs/fleet/backend/auth/middlewares.go
index 1c2a596ad2..7945361ffd 100644
--- a/libs/fleet/backend/auth/middlewares.go
+++ b/libs/fleet/backend/auth/middlewares.go
@@ -34,6 +34,9 @@ var (
opaAdminQuery *rego.PreparedEvalQuery
opaChatQuery *rego.PreparedEvalQuery
opaUsageQuery *rego.PreparedEvalQuery
+
+ opaCardExemptQuery *rego.PreparedEvalQuery
+ opaCardEligibleQuery *rego.PreparedEvalQuery
)
// authzPolicy is the shared principal vocabulary every surface module imports.
@@ -395,6 +398,22 @@ func LoadOpa() {
opaChatQuery = prepareAuthzQuery("data.authz.chat_enabled")
opaUsageQuery = prepareAuthzQuery("data.authz.usage_enabled")
+ // Card-admission queries pair authz.rego with the admission module because
+ // custom_resource_creation_admission.rego imports data.authz for is_admin.
+ prepareCardAdmissionQuery := func(q string) *rego.PreparedEvalQuery {
+ pq, err := rego.New(
+ rego.Query(q),
+ rego.Module("authz.rego", authzPolicy),
+ rego.Module("custom_resource_creation_admission.rego", customResourceCreationAdmissionPolicy),
+ ).PrepareForEval(context.Background())
+ if err != nil {
+ log.Fatalf("opa: prepare card admission %q: %v", q, err)
+ }
+ return &pq
+ }
+ opaCardExemptQuery = prepareCardAdmissionQuery("data.custom_resource_creation_admission.exempt")
+ opaCardEligibleQuery = prepareCardAdmissionQuery("data.custom_resource_creation_admission.billing_eligible")
+
// Warm the flag cache once so the first request isn't slowed by the
// initial resolve and any SSM/provider misconfiguration surfaces in the
// startup logs rather than on a user's first call.
@@ -539,6 +558,81 @@ func EvalBillingEnabled(ctx context.Context, user *User) (bool, error) {
return ffClient.BooleanValue(callCtx, billingFlag, false, openfeature.NewEvaluationContext(user.ID, nil))
}
+// cardAdmissionProbePath is a representative custom-resource create path so
+// the admission module's is_custom_resource_create matches; without it the
+// "not is_custom_resource_create" rule would exempt everyone.
+const cardAdmissionProbePath = "apis/cua.ai/v1/namespaces/probe/osgymsandboxwarmpools"
+
+func cardAdmissionInput(user *User, stripeCards FactSet, now time.Time) map[string]interface{} {
+ input := map[string]interface{}{
+ "user": buildUserInput(user),
+ "flags": flagsData(),
+ "method": http.MethodPost,
+ "params": map[string]interface{}{"path": cardAdmissionProbePath},
+ }
+ if stripeCards != nil {
+ input["facts"] = map[string]interface{}{
+ StripeCardsFactNamespace: map[string]any(stripeCards),
+ TimeFactNamespace: map[string]interface{}{
+ "current_year": now.UTC().Year(),
+ "current_month": int(now.UTC().Month()),
+ },
+ }
+ }
+ return input
+}
+
+func evalPreparedBool(ctx context.Context, query *rego.PreparedEvalQuery, input map[string]interface{}) (bool, error) {
+ if query == nil {
+ return false, fmt.Errorf("opa card admission query is not prepared; call LoadOpa first")
+ }
+ res, err := query.Eval(ctx, rego.EvalInput(input))
+ if err != nil {
+ return false, err
+ }
+ if len(res) == 0 || len(res[0].Expressions) == 0 {
+ return false, nil
+ }
+ v, _ := res[0].Expressions[0].Value.(bool)
+ return v, nil
+}
+
+// EvalPoolCreateCardRequired reports whether the card-admission policy would
+// deny this user a custom-resource create (a pool, template, or claim) for
+// lack of a qualifying payment card. It evaluates the same Rego module the
+// /api/k8s route enforces, against a representative create request, so the
+// advisory answer the dashboard shows cannot drift from enforcement.
+// loadStripeCards is called only when the user is not otherwise exempt
+// (flag off, admin, exempt sub), mirroring the enforcement path's lazy fact
+// loading; it should return the StripeCardsFactNamespace fact set.
+func EvalPoolCreateCardRequired(
+ ctx context.Context,
+ user *User,
+ loadStripeCards func(context.Context) (FactSet, error),
+) (bool, error) {
+ if user == nil || user.ID == "" {
+ return false, nil
+ }
+ // The exempt rules read only input.flags and input.user, so no facts
+ // (and no clock) are attached to this first evaluation.
+ exempt, err := evalPreparedBool(ctx, opaCardExemptQuery, cardAdmissionInput(user, nil, time.Time{}))
+ if err != nil {
+ return false, err
+ }
+ if exempt {
+ return false, nil
+ }
+ stripeCards, err := loadStripeCards(ctx)
+ if err != nil {
+ return false, err
+ }
+ eligible, err := evalPreparedBool(ctx, opaCardEligibleQuery, cardAdmissionInput(user, stripeCards, time.Now()))
+ if err != nil {
+ return false, err
+ }
+ return !eligible, nil
+}
+
func writeJSONErr(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
diff --git a/libs/fleet/backend/billing/service.go b/libs/fleet/backend/billing/service.go
index c72096af5c..91444c448a 100644
--- a/libs/fleet/backend/billing/service.go
+++ b/libs/fleet/backend/billing/service.go
@@ -187,6 +187,12 @@ type CardSummary struct {
type Summary struct {
PaymentMethodPresent bool `json:"payment_method_present" binding:"required"`
Card *CardSummary `json:"card" binding:"required" extensions:"x-nullable"`
+ // PoolCreateCardRequired is advisory admission state the API handler
+ // fills in (Service.Summary always leaves it false): true when creating
+ // a pool or any other custom resource would be denied because the
+ // account has no qualifying payment card. The dashboard reads it to gate
+ // create flows before a request ever reaches the enforcing policy.
+ PoolCreateCardRequired bool `json:"pool_create_card_required" binding:"required"`
}
func (s *Service) AttachedCards(ctx context.Context, subject string) ([]SavedCard, error) {
diff --git a/libs/fleet/backend/billing/service_test.go b/libs/fleet/backend/billing/service_test.go
index dbf63bb065..3b23d0b495 100644
--- a/libs/fleet/backend/billing/service_test.go
+++ b/libs/fleet/backend/billing/service_test.go
@@ -312,7 +312,7 @@ func TestSummaryJSONContract(t *testing.T) {
{
name: "cardless",
summary: Summary{},
- want: `{"payment_method_present":false,"card":null}`,
+ want: `{"payment_method_present":false,"card":null,"pool_create_card_required":false}`,
},
{
name: "saved card",
@@ -320,7 +320,14 @@ func TestSummaryJSONContract(t *testing.T) {
PaymentMethodPresent: true,
Card: &CardSummary{Brand: "visa", Last4: "4242", ExpMonth: 12, ExpYear: 2030},
},
- want: `{"payment_method_present":true,"card":{"brand":"visa","last4":"4242","exp_month":12,"exp_year":2030}}`,
+ want: `{"payment_method_present":true,"card":{"brand":"visa","last4":"4242","exp_month":12,"exp_year":2030},"pool_create_card_required":false}`,
+ },
+ {
+ name: "card required for pool creation",
+ summary: Summary{
+ PoolCreateCardRequired: true,
+ },
+ want: `{"payment_method_present":false,"card":null,"pool_create_card_required":true}`,
},
}
diff --git a/libs/fleet/backend/docs/docs.go b/libs/fleet/backend/docs/docs.go
index ae73186213..4e18391c75 100644
--- a/libs/fleet/backend/docs/docs.go
+++ b/libs/fleet/backend/docs/docs.go
@@ -503,7 +503,7 @@ const docTemplate = `{
"BearerAuth": []
}
],
- "description": "Returns a sanitized Stripe-backed billing summary for the authenticated Cyclops subject.",
+ "description": "Returns a sanitized Stripe-backed billing summary for the authenticated Cyclops subject, including whether creating pools currently requires adding a payment card.",
"produces": [
"application/json"
],
@@ -1648,7 +1648,8 @@ const docTemplate = `{
"type": "object",
"required": [
"card",
- "payment_method_present"
+ "payment_method_present",
+ "pool_create_card_required"
],
"properties": {
"card": {
@@ -1661,6 +1662,10 @@ const docTemplate = `{
},
"payment_method_present": {
"type": "boolean"
+ },
+ "pool_create_card_required": {
+ "description": "PoolCreateCardRequired is advisory admission state the API handler\nfills in (Service.Summary always leaves it false): true when creating\na pool or any other custom resource would be denied because the\naccount has no qualifying payment card. The dashboard reads it to gate\ncreate flows before a request ever reaches the enforcing policy.",
+ "type": "boolean"
}
}
},
diff --git a/libs/fleet/backend/docs/swagger.json b/libs/fleet/backend/docs/swagger.json
index 464d8ba316..e44e61234b 100644
--- a/libs/fleet/backend/docs/swagger.json
+++ b/libs/fleet/backend/docs/swagger.json
@@ -496,7 +496,7 @@
"BearerAuth": []
}
],
- "description": "Returns a sanitized Stripe-backed billing summary for the authenticated Cyclops subject.",
+ "description": "Returns a sanitized Stripe-backed billing summary for the authenticated Cyclops subject, including whether creating pools currently requires adding a payment card.",
"produces": [
"application/json"
],
@@ -1641,7 +1641,8 @@
"type": "object",
"required": [
"card",
- "payment_method_present"
+ "payment_method_present",
+ "pool_create_card_required"
],
"properties": {
"card": {
@@ -1654,6 +1655,10 @@
},
"payment_method_present": {
"type": "boolean"
+ },
+ "pool_create_card_required": {
+ "description": "PoolCreateCardRequired is advisory admission state the API handler\nfills in (Service.Summary always leaves it false): true when creating\na pool or any other custom resource would be denied because the\naccount has no qualifying payment card. The dashboard reads it to gate\ncreate flows before a request ever reaches the enforcing policy.",
+ "type": "boolean"
}
}
},
diff --git a/libs/fleet/backend/docs/swagger.yaml b/libs/fleet/backend/docs/swagger.yaml
index 793f86ee13..8843b6082a 100644
--- a/libs/fleet/backend/docs/swagger.yaml
+++ b/libs/fleet/backend/docs/swagger.yaml
@@ -19,9 +19,18 @@ definitions:
x-nullable: true
payment_method_present:
type: boolean
+ pool_create_card_required:
+ description: |-
+ PoolCreateCardRequired is advisory admission state the API handler
+ fills in (Service.Summary always leaves it false): true when creating
+ a pool or any other custom resource would be denied because the
+ account has no qualifying payment card. The dashboard reads it to gate
+ create flows before a request ever reaches the enforcing policy.
+ type: boolean
required:
- card
- payment_method_present
+ - pool_create_card_required
type: object
billing.Usage:
properties:
@@ -727,7 +736,8 @@ paths:
/api/billing/summary:
get:
description: Returns a sanitized Stripe-backed billing summary for the authenticated
- Cyclops subject.
+ Cyclops subject, including whether creating pools currently requires adding
+ a payment card.
produces:
- application/json
responses:
diff --git a/libs/fleet/backend/handlers/billing.go b/libs/fleet/backend/handlers/billing.go
index 46dabb0af4..872886371d 100644
--- a/libs/fleet/backend/handlers/billing.go
+++ b/libs/fleet/backend/handlers/billing.go
@@ -80,9 +80,25 @@ func requireEmptyBillingBody(w http.ResponseWriter, r *http.Request) bool {
return true
}
+// poolCreateCardRequired resolves the advisory pool_create_card_required
+// summary field from the same admission policy /api/k8s enforces. The field
+// only pre-warns the dashboard — the policy still denies bypassing creates —
+// so evaluation failures fail open to not-required instead of erroring the
+// whole summary.
+func (h Handlers) poolCreateCardRequired(r *http.Request, user *auth.User) bool {
+ required, err := auth.EvalPoolCreateCardRequired(r.Context(), user, func(ctx context.Context) (auth.FactSet, error) {
+ return StripeCardFacts(h).LoadFacts(ctx, r)
+ })
+ if err != nil {
+ slog.WarnContext(r.Context(), "billing: card requirement eval failed; reporting not required", "err", err)
+ return false
+ }
+ return required
+}
+
// GetBillingSummary godoc
// @Summary Billing summary
-// @Description Returns a sanitized Stripe-backed billing summary for the authenticated Cyclops subject.
+// @Description Returns a sanitized Stripe-backed billing summary for the authenticated Cyclops subject, including whether creating pools currently requires adding a payment card.
// @Tags billing
// @Produce json
// @Success 200 {object} billing.Summary
@@ -104,6 +120,7 @@ func (h Handlers) GetBillingSummary(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadGateway, "could not load billing summary")
return
}
+ summary.PoolCreateCardRequired = h.poolCreateCardRequired(r, user)
writeJSON(w, http.StatusOK, summary)
}
diff --git a/libs/fleet/backend/handlers/billing_test.go b/libs/fleet/backend/handlers/billing_test.go
index b90df70e25..a2613ce8c9 100644
--- a/libs/fleet/backend/handlers/billing_test.go
+++ b/libs/fleet/backend/handlers/billing_test.go
@@ -21,6 +21,9 @@ import (
type fakeBillingService struct {
summaryCalls int
summarySubject string
+ attachedCards []billing.SavedCard
+ attachedErr error
+ attachedCalls int
setupSubject string
setupOptions billing.SetupOptions
portalSubject string
@@ -41,7 +44,15 @@ type fakeBillingService struct {
}
func (f *fakeBillingService) AttachedCards(context.Context, string) ([]billing.SavedCard, error) {
- return []billing.SavedCard{}, nil
+ f.attachedCalls++
+ attachedErr := f.attachedErr
+ if attachedErr != nil {
+ return nil, attachedErr
+ }
+ if f.attachedCards == nil {
+ return []billing.SavedCard{}, nil
+ }
+ return f.attachedCards, nil
}
func (f *fakeBillingService) Summary(_ context.Context, subject string) (billing.Summary, error) {
@@ -141,6 +152,71 @@ func TestGetBillingUsageRejectsUnsupportedHistoryWindow(t *testing.T) {
}
}
+func TestBillingSummaryReportsPoolCreateCardRequired(t *testing.T) {
+ postCutoff := time.Date(2026, time.August, 15, 0, 0, 0, 0, time.UTC)
+ preCutoff := time.Date(2026, time.August, 1, 0, 0, 0, 0, time.UTC)
+ nextYear := int64(time.Now().UTC().Year() + 1)
+ cases := []struct {
+ name string
+ cardFlag bool
+ adminSubs string
+ createdAt time.Time
+ cards []billing.SavedCard
+ cardsErr error
+ want bool
+ wantStripeCalls int
+ }{
+ {name: "card flag off", cardFlag: false, createdAt: postCutoff, want: false},
+ {name: "admin exempt", cardFlag: true, adminSubs: `["` + billingAlice.ID + `"]`, createdAt: postCutoff, want: false},
+ {name: "grandfathered user", cardFlag: true, createdAt: preCutoff, want: false},
+ {name: "no card", cardFlag: true, createdAt: postCutoff, want: true, wantStripeCalls: 1},
+ {name: "qualifying card", cardFlag: true, createdAt: postCutoff, cards: []billing.SavedCard{{Brand: "visa", Last4: "4242", ExpYear: nextYear, ExpMonth: 1}}, want: false, wantStripeCalls: 1},
+ {name: "expired card", cardFlag: true, createdAt: postCutoff, cards: []billing.SavedCard{{Brand: "visa", Last4: "4242", ExpYear: 2020, ExpMonth: 1}}, want: true, wantStripeCalls: 1},
+ {name: "stripe outage fails open", cardFlag: true, createdAt: postCutoff, cardsErr: errors.New("stripe unavailable"), want: false, wantStripeCalls: 1},
+ }
+
+ for _, testCase := range cases {
+ t.Run(testCase.name, func(t *testing.T) {
+ cardFlag := "false"
+ if testCase.cardFlag {
+ cardFlag = "true"
+ }
+ adminSubs := testCase.adminSubs
+ if adminSubs == "" {
+ adminSubs = `[]`
+ }
+ t.Setenv("CYCLOPS_CS_REQUIRE_CARD_FOR_CUSTOM_RESOURCE_CREATION", cardFlag)
+ t.Setenv("CYCLOPS_CS_ADMIN_SUBS", adminSubs)
+ t.Setenv("CYCLOPS_CS_CARD_REQUIREMENT_EXEMPT_SUBS", `[]`)
+ setBillingFlag(t, true)
+ auth.InvalidateFeatureFlags()
+ auth.LoadOpa()
+ t.Cleanup(auth.InvalidateFeatureFlags)
+
+ service := &fakeBillingService{attachedCards: testCase.cards, attachedErr: testCase.cardsErr}
+ accounts := &cardEligibilityAccounts{createdAt: testCase.createdAt}
+ h := Handlers{Billing: service, UserAccounts: accounts, Stripe: config.StripeConfiguration{SecretKey: "sk_test"}}
+ w := httptest.NewRecorder()
+
+ h.GetBillingSummary(w, newBillingRequest(http.MethodGet, "/api/billing/summary", "", billingAlice))
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
+ }
+ var summary billing.Summary
+ if err := json.Unmarshal(w.Body.Bytes(), &summary); err != nil {
+ t.Fatalf("decode summary: %v; body = %s", err, w.Body.String())
+ }
+ if summary.PoolCreateCardRequired != testCase.want {
+ t.Fatalf("pool_create_card_required = %v, want %v", summary.PoolCreateCardRequired, testCase.want)
+ }
+ if service.attachedCalls != testCase.wantStripeCalls {
+ t.Fatalf("attached card lookups = %d, want %d", service.attachedCalls, testCase.wantStripeCalls)
+ }
+ })
+ }
+}
+
func TestBillingSummaryReturns503WithoutStripeConfiguration(t *testing.T) {
setBillingFlag(t, true)
service := &fakeBillingService{}
diff --git a/libs/fleet/backend/main_test.go b/libs/fleet/backend/main_test.go
index 45eb314f3e..de282a80f1 100644
--- a/libs/fleet/backend/main_test.go
+++ b/libs/fleet/backend/main_test.go
@@ -486,7 +486,7 @@ func TestBillingSummaryGeneratedContract(t *testing.T) {
t.Fatalf("unmarshal swagger.json: %v", err)
}
summary := document.Definitions["billing.Summary"]
- if !slices.Contains(summary.Required, "payment_method_present") || !slices.Contains(summary.Required, "card") {
+ if !slices.Contains(summary.Required, "payment_method_present") || !slices.Contains(summary.Required, "card") || !slices.Contains(summary.Required, "pool_create_card_required") {
t.Fatalf("billing summary required fields = %#v", summary.Required)
}
var card struct {
diff --git a/libs/fleet/e2e/pools.spec.ts b/libs/fleet/e2e/pools.spec.ts
index c1d658299c..770589a162 100644
--- a/libs/fleet/e2e/pools.spec.ts
+++ b/libs/fleet/e2e/pools.spec.ts
@@ -337,6 +337,100 @@ test.describe("Pool creation", () => {
await dialog.getByRole("button", { name: "Keep editing" }).click()
await expect(name).toHaveValue("new-fleet")
})
+
+ test("create is blocked when the account still needs a payment card", async ({
+ page,
+ }) => {
+ await mockAuth(page, { billing: true })
+ await mockNamespacesApi(page)
+ await mockPoolsApi(page)
+ await page.route("**/api/billing/summary", (route) =>
+ route.fulfill({
+ contentType: "application/json",
+ body: JSON.stringify({
+ payment_method_present: false,
+ card: null,
+ // A missing payment method must block creation even when the
+ // advisory policy result is false (for example, a grandfathered
+ // account or a failed-open policy evaluation).
+ pool_create_card_required: false,
+ }),
+ }),
+ )
+
+ await page.goto("/pools/new")
+
+ await expect(page.getByText("Payment method required")).toBeVisible()
+ // Cloudscape renders reason-carrying disabled buttons with aria-disabled
+ // (kept focusable for the tooltip) rather than the disabled attribute.
+ await expect(page.getByRole("button", { name: "Create" })).toHaveAttribute(
+ "aria-disabled",
+ "true",
+ )
+ await page.getByRole("button", { name: "Create" }).hover()
+ await expect(
+ page
+ .getByRole("tooltip")
+ .getByText("Add a payment method in Settings to create pools."),
+ ).toBeVisible()
+
+ await page.getByRole("button", { name: "Add payment method" }).click()
+ await expect(page).toHaveURL(/\/settings$/)
+ })
+
+ test("create stays enabled once a payment card is on file", async ({
+ page,
+ }) => {
+ await mockAuth(page, { billing: true })
+ await mockNamespacesApi(page)
+ await mockPoolsApi(page)
+ await page.route("**/api/billing/summary", (route) =>
+ route.fulfill({
+ contentType: "application/json",
+ body: JSON.stringify({
+ payment_method_present: true,
+ card: { brand: "visa", last4: "4242", exp_month: 12, exp_year: 2030 },
+ pool_create_card_required: false,
+ }),
+ }),
+ )
+
+ await page.goto("/pools/new")
+
+ await expect(page.getByPlaceholder("my-pool")).toBeVisible()
+ await expect(page.getByText("Payment method required")).toHaveCount(0)
+ await expect(page.getByRole("button", { name: "Create" })).toBeEnabled()
+ })
+
+ test("create failure pipes the backend error into the flash message", async ({
+ page,
+ }) => {
+ await mockAuth(page)
+ await mockNamespacesApi(page)
+ await mockPoolsApi(page)
+ // Registered after mockPoolsApi so it wins: the pool create POST is
+ // denied the way the card-admission policy denies it.
+ const denial =
+ "A payment method is required to create this resource. Add one in Billing and try again."
+ await page.route(
+ "**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/*/osgymsandboxwarmpools",
+ (route) => {
+ if (route.request().method() !== "POST") return route.fallback()
+ return route.fulfill({
+ status: 403,
+ contentType: "application/json",
+ body: JSON.stringify({ error: denial }),
+ })
+ },
+ )
+
+ await page.goto("/pools/new")
+ await page.getByRole("textbox", { name: "Name" }).fill("gated-pool")
+ await page.getByRole("button", { name: "Create" }).click()
+
+ await expect(page.getByText("Create failed")).toBeVisible()
+ await expect(page.getByText(denial)).toBeVisible()
+ })
})
test.describe("Pool duplication", () => {
diff --git a/libs/fleet/package.json b/libs/fleet/package.json
index 7f1491ef14..6a20229e4c 100644
--- a/libs/fleet/package.json
+++ b/libs/fleet/package.json
@@ -15,6 +15,7 @@
"test:e2e": "npm run sdk:browser && playwright test",
"test:e2e:ui": "npm run sdk:browser && playwright test --ui",
"test:auth-contract": "tsx --test tests/auth-redirects.test.ts && node --test tests/auth-first-paint.test.mjs",
+ "test:error-message": "tsx --test tests/error-message.test.ts",
"test:design-boundary": "node --test tests/design-package-boundary.test.mjs",
"test:favicon": "node --test tests/favicon.test.mjs",
"test:sdk-models": "rm -rf target/sdk-model-tests && tsc -p tsconfig.sdk-models.json && node target/sdk-model-tests/e2e/sdk-models.unit.js",
diff --git a/libs/fleet/src/api/billing.ts b/libs/fleet/src/api/billing.ts
index 9eff78d22c..01b669d21e 100644
--- a/libs/fleet/src/api/billing.ts
+++ b/libs/fleet/src/api/billing.ts
@@ -15,6 +15,12 @@ export interface SavedCard {
export interface BillingSummary {
payment_method_present: boolean;
card: SavedCard | null;
+ /**
+ * True when creating a pool (or any custom resource) would be denied by
+ * the backend's card-admission policy until a payment card is added.
+ * Optional so older backends without the field keep parsing.
+ */
+ pool_create_card_required?: boolean;
}
export type UsageRangeMonths = 3 | 6 | 12;
@@ -66,6 +72,7 @@ export const billingApi = {
? Promise.resolve<BillingSummary>({
payment_method_present: true,
card: { brand: "visa", last4: "4242", exp_month: 12, exp_year: 2030 },
+ pool_create_card_required: false,
})
: billingRequest<BillingSummary>("/api/billing/summary", "GET"),
setup: () =>
diff --git a/libs/fleet/src/error-message.ts b/libs/fleet/src/error-message.ts
index ad171e4e3d..75c3f5f785 100644
--- a/libs/fleet/src/error-message.ts
+++ b/libs/fleet/src/error-message.ts
@@ -1,4 +1,51 @@
+// uniffi enum errors (e.g. the fleet SDK's SdkError) stringify as just the
+// variant name — "SdkError.Status" — while the useful details live on the
+// error's `inner` field: Status carries the backend response body verbatim,
+// and most other variants carry a `reason`. The shapes are matched
+// structurally so this module stays independent of the generated bindings.
+interface UniffiErrorLike {
+ tag?: unknown
+ inner?: unknown
+}
+
+// Backend errors arrive as JSON like {"error": "..."} (the auth middleware)
+// or {"message": "..."} (the K8s API); anything else is piped through as-is.
+function backendErrorDetail(body: string): string | undefined {
+ const trimmed = body.trim()
+ if (!trimmed) return undefined
+ try {
+ const parsed = JSON.parse(trimmed) as { error?: unknown; message?: unknown }
+ if (typeof parsed?.error === "string" && parsed.error) return parsed.error
+ if (typeof parsed?.message === "string" && parsed.message) {
+ return parsed.message
+ }
+ } catch {
+ // Not JSON — surface the raw body below.
+ }
+ return trimmed
+}
+
+function uniffiErrorDetail(error: UniffiErrorLike): string | undefined {
+ if (typeof error.tag !== "string") return undefined
+ const inner = error.inner
+ if (!inner || typeof inner !== "object") return undefined
+ const fields = inner as { status?: unknown; body?: unknown; reason?: unknown }
+ // Status, PoolAccessDenied, … — every variant carrying an HTTP response.
+ if (typeof fields.status === "number") {
+ const detail = backendErrorDetail(
+ typeof fields.body === "string" ? fields.body : "",
+ )
+ return detail ?? `Request failed with HTTP status ${fields.status}.`
+ }
+ if (typeof fields.reason === "string" && fields.reason) return fields.reason
+ return undefined
+}
+
export function errorMessage(error: unknown): string {
+ if (error && typeof error === "object") {
+ const detail = uniffiErrorDetail(error as UniffiErrorLike)
+ if (detail) return detail
+ }
if (error instanceof Error && error.message) return error.message
if (typeof error === "string" && error) return error
if (error == null) return "Unknown error"
diff --git a/libs/fleet/src/pages/PoolNew.tsx b/libs/fleet/src/pages/PoolNew.tsx
index b9f3cc2e29..764af3bd8e 100644
--- a/libs/fleet/src/pages/PoolNew.tsx
+++ b/libs/fleet/src/pages/PoolNew.tsx
@@ -1,5 +1,6 @@
-import { useMemo, useRef, useState } from "react"
+import { useEffect, useMemo, useRef, useState } from "react"
import { useBeforeUnload, useLocation, useNavigate } from "react-router-dom"
+import Alert from "@cloudscape-design/components/alert"
import Box from "@cloudscape-design/components/box"
import ColumnLayout from "@cloudscape-design/components/column-layout"
import Container from "@cloudscape-design/components/container"
@@ -11,7 +12,10 @@ import Modal from "@cloudscape-design/components/modal"
import Select from "@cloudscape-design/components/select"
import SpaceBetween from "@cloudscape-design/components/space-between"
import Toggle from "@cloudscape-design/components/toggle"
+import { billingApi } from "../api/billing"
+import { useFeatureFlags } from "../components/FeatureFlagContext"
import { useFlash } from "../components/FlashContext"
+import { errorMessage } from "../error-message"
import { createPool } from "../fleet/pools"
import type { PoolTemplateConfig } from "../fleet/models"
import { CuaButton } from "../components/CuaButton"
@@ -75,6 +79,7 @@ export function PoolNew() {
const navigate = useNavigate()
const location = useLocation()
const flash = useFlash()
+ const { billing: billingEnabled } = useFeatureFlags()
const navState = location.state as PoolNewState | null
const source = navState?.source ?? null
@@ -111,8 +116,32 @@ export function PoolNew() {
const [dirty, setDirty] = useState(false)
const [submitAttempted, setSubmitAttempted] = useState(false)
const [discardOpen, setDiscardOpen] = useState(false)
+ // True once billing confirms there is no saved payment method or the
+ // card-admission policy would deny this user's pool create. Stays false
+ // while loading or when the lookup fails: the backend policy is still the
+ // enforcement point, so the gate fails open on a billing hiccup.
+ const [cardRequired, setCardRequired] = useState(false)
const nameRef = useRef<InputProps.Ref>(null)
+ useEffect(() => {
+ if (!billingEnabled) return
+ let cancelled = false
+ billingApi
+ .summary()
+ .then(summary => {
+ if (!cancelled) {
+ setCardRequired(
+ !summary.payment_method_present ||
+ summary.pool_create_card_required === true,
+ )
+ }
+ })
+ .catch(() => undefined)
+ return () => {
+ cancelled = true
+ }
+ }, [billingEnabled])
+
useBeforeUnload(event => {
if (!dirty || submitting) return
event.preventDefault()
@@ -194,7 +223,7 @@ export function PoolNew() {
flash.push({
type: "error",
header: "Create failed",
- content: String((e as Error).message),
+ content: errorMessage(e),
})
} finally {
setSubmitting(false)
@@ -217,11 +246,32 @@ export function PoolNew() {
}
secondaryActions={<CuaButton onClick={cancel}>Cancel</CuaButton>}
primaryAction={
- <CuaButton tone="primary" loading={submitting} onClick={create}>
+ <CuaButton
+ tone="primary"
+ loading={submitting}
+ disabled={cardRequired}
+ disabledReason="Add a payment method in Settings to create pools."
+ onClick={create}
+ >
Create
</CuaButton>
}
>
+ <SpaceBetween size="l">
+ {cardRequired && (
+ <Alert
+ type="warning"
+ header="Payment method required"
+ action={
+ <CuaButton onClick={() => navigate("/settings")}>
+ Add payment method
+ </CuaButton>
+ }
+ >
+ Pool creation is disabled because this account has no payment method
+ on file. Add a card in Settings, then come back to create your pool.
+ </Alert>
+ )}
<Container header={<Header variant="h2">Configuration</Header>}>
<div onChangeCapture={() => setDirty(true)}>
<Form>
@@ -404,6 +454,7 @@ export function PoolNew() {
</Form>
</div>
</Container>
+ </SpaceBetween>
<Modal
visible={discardOpen}
onDismiss={() => setDiscardOpen(false)}
diff --git a/libs/fleet/tests/error-message.test.ts b/libs/fleet/tests/error-message.test.ts
new file mode 100644
index 0000000000..84477f11a6
--- /dev/null
+++ b/libs/fleet/tests/error-message.test.ts
@@ -0,0 +1,86 @@
+import assert from "node:assert/strict"
+import test from "node:test"
+import { errorMessage } from "../src/error-message.ts"
+
+// Structural stand-ins for uniffi enum errors (e.g. the fleet SDK's
+// SdkError): a real one is an Error whose message is just the variant name
+// ("SdkError.Status") with the details frozen on `inner`.
+function uniffiError(
+ variant: string,
+ inner: Record<string, unknown>,
+): Error & { tag: string; inner: Record<string, unknown> } {
+ return Object.assign(new Error(`SdkError.${variant}`), {
+ tag: variant,
+ inner,
+ })
+}
+
+test("pipes the auth middleware's {error} JSON body through Status errors", () => {
+ const denial =
+ "A payment method is required to create this resource. Add one in Billing and try again."
+ const error = uniffiError("Status", {
+ operation: "createPool",
+ status: 403,
+ body: JSON.stringify({ error: denial }),
+ })
+ assert.equal(errorMessage(error), denial)
+})
+
+test("pipes the K8s API's {message} JSON body", () => {
+ const error = uniffiError("Status", {
+ operation: "createPool",
+ status: 409,
+ body: JSON.stringify({
+ kind: "Status",
+ status: "Failure",
+ message: 'warmpools.osgym.cua.ai "demo" already exists',
+ reason: "AlreadyExists",
+ }),
+ })
+ assert.equal(errorMessage(error), 'warmpools.osgym.cua.ai "demo" already exists')
+})
+
+test("passes a non-JSON body through as-is", () => {
+ const error = uniffiError("Status", {
+ operation: "createPool",
+ status: 502,
+ body: "upstream connect error",
+ })
+ assert.equal(errorMessage(error), "upstream connect error")
+})
+
+test("falls back to the HTTP status when the body is empty", () => {
+ const error = uniffiError("Status", {
+ operation: "createPool",
+ status: 403,
+ body: " ",
+ })
+ assert.equal(errorMessage(error), "Request failed with HTTP status 403.")
+})
+
+test("handles PoolAccessDenied's {status, body} payload like Status", () => {
+ const error = uniffiError("PoolAccessDenied", {
+ operation: "createPool",
+ namespace: "demo",
+ status: 403,
+ body: JSON.stringify({ error: "namespace demo is not yours" }),
+ })
+ assert.equal(errorMessage(error), "namespace demo is not yours")
+})
+
+test("surfaces reason-only variants like Transport", () => {
+ const error = uniffiError("Transport", { reason: "dns lookup failed" })
+ assert.equal(errorMessage(error), "dns lookup failed")
+})
+
+test("keeps a variant with neither status nor reason at its Error message", () => {
+ const error = uniffiError("ClaimTimeout", {})
+ assert.equal(errorMessage(error), "SdkError.ClaimTimeout")
+})
+
+test("leaves plain errors, strings, and nullish values unchanged", () => {
+ assert.equal(errorMessage(new Error("boom")), "boom")
+ assert.equal(errorMessage("plain failure"), "plain failure")
+ assert.equal(errorMessage(null), "Unknown error")
+ assert.equal(errorMessage(undefined), "Unknown error")
+})