Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cyclops-cs): add stateless Stripe-hosted billing (#5798)
r33drichardsd47798b4103c
diff --git a/libs/fleet/backend/auth/authz.rego b/libs/fleet/backend/auth/authz.regoindex 9fdc20bc2a..7e54899c44 100644--- a/libs/fleet/backend/auth/authz.rego+++ b/libs/fleet/backend/auth/authz.rego@@ -75,6 +75,15 @@ allow {is_interactive_client}+# Stripe-hosted billing browser endpoints. The backend derives the customer+# identity from input.user.sub and never accepts Stripe ownership identifiers.+allow {+ startswith(input.route, "/api/billing/")+ input.route != "/api/billing/webhook"+ input.user.sub != ""+ input.user.azp == "cyclops-cs-spa"+}+# /api/namespaces — namespace management (list, create, delete).# Exact interactive clients may manage their own namespaces.# Capsule enforces per-user scoping at the K8s API level viadiff --git a/libs/fleet/backend/auth/flags_test.go b/libs/fleet/backend/auth/flags_test.goindex 78dfe38368..d09ebe9747 100644--- a/libs/fleet/backend/auth/flags_test.go+++ b/libs/fleet/backend/auth/flags_test.go@@ -116,3 +116,24 @@ func asStrings(v any) []string {}return out}++func TestEvalBillingEnabledDefaultsFalseAndReadsBooleanFlag(t *testing.T) {+ if err := featureflags.SetupProvider(context.Background(), "development", featureflags.AWSCredentials{}); err != nil {+ t.Fatalf("setup dev provider: %v", err)+ }+ LoadOpa()++ t.Setenv("CYCLOPS_CS_BILLING_ENABLED", "false")+ resetFlagsCache()+ enabled, err := EvalBillingEnabled(context.Background(), &User{ID: "user-1", AZP: "cyclops-cs-spa"})+ if err != nil || enabled {+ t.Fatalf("EvalBillingEnabled(false) = %v, %v; want false, nil", enabled, err)+ }++ t.Setenv("CYCLOPS_CS_BILLING_ENABLED", "true")+ resetFlagsCache()+ enabled, err = EvalBillingEnabled(context.Background(), &User{ID: "user-1", AZP: "cyclops-cs-spa"})+ if err != nil || !enabled {+ t.Fatalf("EvalBillingEnabled(true) = %v, %v; want true, nil", enabled, err)+ }+}diff --git a/libs/fleet/backend/auth/middlewares.go b/libs/fleet/backend/auth/middlewares.goindex 2d136842d0..c420b8396e 100644--- a/libs/fleet/backend/auth/middlewares.go+++ b/libs/fleet/backend/auth/middlewares.go@@ -295,6 +295,20 @@ func EvalIsAdmin(ctx context.Context, user *User) (bool, error) {return v, nil}+// EvalBillingEnabled resolves the billing UI flag for the authenticated user.+// The flag defaults off so absent provider configuration never exposes billing.+func EvalBillingEnabled(ctx context.Context, user *User) (bool, error) {+ if user == nil || user.ID == "" {+ return false, nil+ }+ ffClientOnce.Do(func() {+ ffClient = openfeature.NewClient("cyclops-cs-auth")+ })+ callCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ return ffClient.BooleanValue(callCtx, "/feature-flags/cyclops-cs/billing-enabled", false, openfeature.NewEvaluationContext(user.ID, 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.gonew file mode 100644index 0000000000..903d90c313--- /dev/null+++ b/libs/fleet/backend/billing/service.go@@ -0,0 +1,196 @@+package billing++import (+ "context"+ "crypto/rand"+ "crypto/sha256"+ "encoding/hex"+ "errors"+)++const (+ MetadataSubject = "fleet_subject"+ LegacyMetadataSubject = "cyclops_subject"+ CustomerIdempotencyPrefix = "fleet-customer-"+ SetupPurpose = "fleet_default_card"+ MetadataSetupGeneration = "fleet_setup_generation"+)++var (+ ErrCustomerNotFound = errors.New("billing customer not found")+ ErrPaymentMethodNotFound = errors.New("default payment method not found")+)++type Customer struct {+ ID string+ Metadata map[string]string+}++type SavedCard struct {+ Brand string+ Last4 string+ ExpMonth int64+ ExpYear int64+}++type SetupSessionRequest struct {+ CustomerID string+ SuccessURL string+ CancelURL string+ SetupGeneration string+}++type PortalSessionRequest struct {+ CustomerID string+ ReturnURL string+}++type Gateway interface {+ SearchCustomers(ctx context.Context, subject string) ([]Customer, error)+ 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)+ 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)+}++type Service struct {+ gateway Gateway+}++func NewService(gateway Gateway) *Service {+ return &Service{gateway: gateway}+}++func (s *Service) FindCustomer(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] != "" {+ continue+ }+ metadata := map[string]string{MetadataSubject: subject}+ updated, err := s.gateway.UpdateCustomerMetadata(ctx, customer.ID, metadata)+ if err != nil {+ return Customer{}, err+ }+ return updated, nil+ }+ return Customer{}, ErrCustomerNotFound+}++func (s *Service) FindOrCreateCustomer(ctx context.Context, subject string) (Customer, error) {+ customer, err := s.FindCustomer(ctx, subject)+ if err == nil {+ return customer, nil+ }+ if !errors.Is(err, ErrCustomerNotFound) {+ return Customer{}, err+ }+ metadata := map[string]string{MetadataSubject: subject}+ digest := sha256.Sum256([]byte(subject))+ return s.gateway.CreateCustomer(ctx, metadata, CustomerIdempotencyPrefix+hex.EncodeToString(digest[:]))+}++type CardSummary struct {+ Brand string `json:"brand"`+ Last4 string `json:"last4"`+ ExpMonth int64 `json:"exp_month"`+ ExpYear int64 `json:"exp_year"`+}++type Summary struct {+ PaymentMethodPresent bool `json:"payment_method_present" binding:"required"`+ Card *CardSummary `json:"card" binding:"required" extensions:"x-nullable"`+}++func (s *Service) Summary(ctx context.Context, subject string) (Summary, error) {+ customer, err := s.FindCustomer(ctx, subject)+ if errors.Is(err, ErrCustomerNotFound) {+ return Summary{}, nil+ }+ if err != nil {+ return Summary{}, err+ }++ card, err := s.gateway.GetDefaultCard(ctx, customer.ID)+ if errors.Is(err, ErrPaymentMethodNotFound) {+ return Summary{}, nil+ }+ if err != nil {+ return Summary{}, err+ }++ return Summary{+ PaymentMethodPresent: true,+ Card: &CardSummary{+ Brand: card.Brand,+ Last4: card.Last4,+ ExpMonth: card.ExpMonth,+ ExpYear: card.ExpYear,+ },+ }, nil+}++type SetupOptions struct {+ SuccessURL string+ CancelURL string+}++func (s *Service) CreateSetupSession(ctx context.Context, subject string, options SetupOptions) (string, error) {+ customer, err := s.FindOrCreateCustomer(ctx, subject)+ if err != nil {+ return "", err+ }+ generation, err := newSetupGeneration()+ if err != nil {+ return "", err+ }+ url, err := s.gateway.CreateSetupSession(ctx, SetupSessionRequest{+ CustomerID: customer.ID,+ SuccessURL: options.SuccessURL,+ CancelURL: options.CancelURL,+ SetupGeneration: generation,+ })+ if err != nil {+ return "", err+ }+ if _, err := s.gateway.UpdateCustomerMetadata(ctx, customer.ID, map[string]string{MetadataSetupGeneration: generation}); err != nil {+ return "", err+ }+ return url, nil+}++func (s *Service) CreatePortalSession(ctx context.Context, subject, returnURL string) (string, error) {+ customer, err := s.FindCustomer(ctx, subject)+ if err != nil {+ return "", err+ }+ return s.gateway.CreatePortalSession(ctx, PortalSessionRequest{+ CustomerID: customer.ID,+ ReturnURL: returnURL,+ })+}++func newSetupGeneration() (string, error) {+ bytes := make([]byte, 32)+ if _, err := rand.Read(bytes); err != nil {+ return "", err+ }+ return hex.EncodeToString(bytes), nil+}++func (s *Service) SetDefaultPaymentMethodForSetupGeneration(ctx context.Context, customerID, paymentMethodID, generation string) (bool, error) {+ if customerID == "" || paymentMethodID == "" || generation == "" {+ return false, errors.New("customer, payment method, and setup generation are required")+ }+ return s.gateway.SetDefaultPaymentMethodForSetupGeneration(ctx, customerID, paymentMethodID, generation)+}diff --git a/libs/fleet/backend/billing/service_test.go b/libs/fleet/backend/billing/service_test.gonew file mode 100644index 0000000000..94a3cdff3a--- /dev/null+++ b/libs/fleet/backend/billing/service_test.go@@ -0,0 +1,352 @@+package billing++import (+ "context"+ "encoding/json"+ "errors"+ "reflect"+ "strings"+ "testing"+)++type fakeGateway struct {+ searchSubject string+ customers []Customer+ createdMetadata map[string]string+ createIdempotencyKey string+ createdCustomer Customer+ createCalls int+ updatedMetadata map[string]string+ updatedCustomer Customer+ updateErr error+ setupErr error+ operations []string+ defaultCard SavedCard+ defaultCardErr error+ defaultCustomerID string+ defaultPaymentMethodID string+ defaultGeneration string+ defaultApplied bool+ setupRequest SetupSessionRequest+ portalRequest PortalSessionRequest+}++func (f *fakeGateway) SearchCustomers(_ context.Context, subject string) ([]Customer, error) {+ f.searchSubject = subject+ return f.customers, nil+}++func (f *fakeGateway) CreateCustomer(_ context.Context, metadata map[string]string, idempotencyKey string) (Customer, error) {+ f.createCalls+++ f.createdMetadata = metadata+ f.createIdempotencyKey = idempotencyKey+ return f.createdCustomer, nil+}++func (f *fakeGateway) UpdateCustomerMetadata(_ context.Context, customerID string, metadata map[string]string) (Customer, error) {+ f.operations = append(f.operations, "publish")+ f.updatedMetadata = metadata+ if f.updateErr != nil {+ return Customer{}, f.updateErr+ }+ if f.updatedCustomer.ID != "" {+ return f.updatedCustomer, nil+ }+ return Customer{ID: customerID, Metadata: metadata}, nil+}++func (f *fakeGateway) GetDefaultCard(_ context.Context, _ string) (SavedCard, error) {+ return f.defaultCard, f.defaultCardErr+}++func (f *fakeGateway) SetDefaultPaymentMethodForSetupGeneration(_ context.Context, customerID, paymentMethodID, generation string) (bool, error) {+ f.defaultCustomerID = customerID+ f.defaultPaymentMethodID = paymentMethodID+ f.defaultGeneration = generation+ return f.defaultApplied, nil+}++func (f *fakeGateway) CreateSetupSession(_ context.Context, request SetupSessionRequest) (string, error) {+ f.operations = append(f.operations, "create")+ f.setupRequest = request+ if f.setupErr != nil {+ return "", f.setupErr+ }+ return "https://checkout.stripe.test/session", nil+}++func (f *fakeGateway) CreatePortalSession(_ context.Context, request PortalSessionRequest) (string, error) {+ f.portalRequest = request+ return "https://billing.stripe.test/session", nil+}++func TestFindOrCreateCustomerUsesExactControlledMetadata(t *testing.T) {+ gateway := &fakeGateway{+ customers: []Customer{{+ ID: "cus_wrong_subject",+ Metadata: map[string]string{+ MetadataSubject: "subject-12",+ },+ }},+ createdCustomer: Customer{ID: "cus_created"},+ }+ service := NewService(gateway)++ customer, err := service.FindOrCreateCustomer(context.Background(), "subject-123")+ if err != nil {+ t.Fatalf("FindOrCreateCustomer() error = %v", err)+ }+ if customer.ID != "cus_created" {+ t.Fatalf("customer ID = %q, want cus_created", customer.ID)+ }+ if gateway.searchSubject != "subject-123" {+ t.Fatalf("search subject = %q, want exact subject", gateway.searchSubject)+ }+ wantMetadata := map[string]string{+ MetadataSubject: "subject-123",+ }+ if !reflect.DeepEqual(gateway.createdMetadata, wantMetadata) {+ t.Fatalf("created metadata = %#v, want %#v", gateway.createdMetadata, wantMetadata)+ }+}++func TestFindOrCreateCustomerUsesFleetMetadataAndIdempotencyKey(t *testing.T) {+ gateway := &fakeGateway{createdCustomer: Customer{ID: "cus_created"}}+ service := NewService(gateway)++ customer, err := service.FindOrCreateCustomer(context.Background(), "subject-123")+ if err != nil {+ t.Fatalf("FindOrCreateCustomer() error = %v", err)+ }+ if customer.ID != "cus_created" {+ t.Fatalf("customer ID = %q, want cus_created", customer.ID)+ }+ if got := gateway.createdMetadata[MetadataSubject]; got != "subject-123" {+ t.Fatalf("fleet metadata = %q, want subject-123", got)+ }+ if _, exists := gateway.createdMetadata[LegacyMetadataSubject]; exists {+ t.Fatal("new customer must not write legacy cyclops metadata")+ }+ if !strings.HasPrefix(gateway.createIdempotencyKey, CustomerIdempotencyPrefix) {+ t.Fatalf("idempotency key = %q, want fleet prefix", gateway.createIdempotencyKey)+ }+}++func TestFindCustomerMigratesLegacySubjectMetadata(t *testing.T) {+ gateway := &fakeGateway{customers: []Customer{{+ ID: "cus_legacy",+ Metadata: map[string]string{LegacyMetadataSubject: "subject-123"},+ }}}+ service := NewService(gateway)++ customer, err := service.FindCustomer(context.Background(), "subject-123")+ if err != nil {+ t.Fatalf("FindCustomer() error = %v", err)+ }+ if customer.ID != "cus_legacy" {+ t.Fatalf("customer ID = %q, want cus_legacy", customer.ID)+ }+ if got := gateway.updatedMetadata[MetadataSubject]; got != "subject-123" {+ t.Fatalf("updated fleet metadata = %q, want subject-123", got)+ }+ if gateway.createCalls != 0 {+ t.Fatalf("CreateCustomer calls = %d, want 0", gateway.createCalls)+ }+}++func TestFindCustomerSkipsConflictingLegacySubjectMetadata(t *testing.T) {+ gateway := &fakeGateway{customers: []Customer{{+ ID: "cus_other_owner",+ Metadata: map[string]string{+ MetadataSubject: "other",+ LegacyMetadataSubject: "subject-123",+ },+ }}}+ service := NewService(gateway)++ customer, err := service.FindCustomer(context.Background(), "subject-123")+ if !errors.Is(err, ErrCustomerNotFound) {+ t.Fatalf("FindCustomer() customer/error = %#v/%v, want no customer/%v", customer, err, ErrCustomerNotFound)+ }+ if customer.ID != "" {+ t.Fatalf("customer = %#v, want no customer", customer)+ }+ if gateway.updatedMetadata != nil {+ t.Fatalf("updated metadata = %#v, want no update", gateway.updatedMetadata)+ }+}++func TestSummaryReturnsNoPaymentMethodWhenCustomerDoesNotExist(t *testing.T) {+ service := NewService(&fakeGateway{})++ summary, err := service.Summary(context.Background(), "subject-123")+ if err != nil {+ t.Fatalf("Summary() error = %v", err)+ }+ if summary.PaymentMethodPresent || summary.Card != nil {+ t.Fatalf("summary = %#v, want no payment method", summary)+ }+}++func TestSummaryDoesNotTreatCustomerExistenceAsSavedCard(t *testing.T) {+ gateway := &fakeGateway{+ customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}},+ defaultCardErr: ErrPaymentMethodNotFound,+ }+ service := NewService(gateway)++ summary, err := service.Summary(context.Background(), "subject-123")+ if err != nil {+ t.Fatalf("Summary() error = %v", err)+ }+ if summary.PaymentMethodPresent || summary.Card != nil {+ t.Fatalf("summary = %#v, want abandoned setup to remain cardless", summary)+ }+}++func TestSummaryReturnsSanitizedDefaultCard(t *testing.T) {+ gateway := &fakeGateway{+ customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}},+ defaultCard: SavedCard{Brand: "visa", Last4: "4242", ExpMonth: 12, ExpYear: 2030},+ }+ service := NewService(gateway)++ summary, err := service.Summary(context.Background(), "subject-123")+ if err != nil {+ t.Fatalf("Summary() error = %v", err)+ }+ if !summary.PaymentMethodPresent || summary.Card == nil {+ t.Fatalf("summary = %#v, want saved card", summary)+ }+ if *summary.Card != (CardSummary{Brand: "visa", Last4: "4242", ExpMonth: 12, ExpYear: 2030}) {+ t.Fatalf("card = %#v", *summary.Card)+ }+}++func TestSummaryJSONContract(t *testing.T) {+ tests := []struct {+ name string+ summary Summary+ want string+ }{+ {+ name: "cardless",+ summary: Summary{},+ want: `{"payment_method_present":false,"card":null}`,+ },+ {+ name: "saved card",+ summary: Summary{+ 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}}`,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ encoded, err := json.Marshal(test.summary)+ if err != nil {+ t.Fatalf("Marshal() error = %v", err)+ }+ if string(encoded) != test.want {+ t.Fatalf("JSON = %s, want %s", encoded, test.want)+ }+ })+ }+}++func TestCreateSetupSessionUsesServerRequestAndOwnedCustomer(t *testing.T) {+ gateway := &fakeGateway{createdCustomer: Customer{ID: "cus_created"}}+ service := NewService(gateway)++ url, err := service.CreateSetupSession(context.Background(), "subject-123", SetupOptions{+ SuccessURL: "https://run.example.test/billing?checkout=success",+ CancelURL: "https://run.example.test/billing?checkout=cancelled",+ })+ if err != nil {+ t.Fatalf("CreateSetupSession() error = %v", err)+ }+ if url != "https://checkout.stripe.test/session" {+ t.Fatalf("url = %q", url)+ }+ want := SetupSessionRequest{+ CustomerID: "cus_created",+ SuccessURL: "https://run.example.test/billing?checkout=success",+ CancelURL: "https://run.example.test/billing?checkout=cancelled",+ SetupGeneration: gateway.updatedMetadata[MetadataSetupGeneration],+ }+ if want.SetupGeneration == "" || !reflect.DeepEqual(gateway.setupRequest, want) {+ t.Fatalf("setup request = %#v, want %#v", gateway.setupRequest, want)+ }+}++func TestCreatePortalSessionUsesOnlyOwnedExistingCustomer(t *testing.T) {+ gateway := &fakeGateway{customers: []Customer{+ {ID: "cus_attacker", Metadata: map[string]string{MetadataSubject: "other"}},+ {ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}},+ }}+ service := NewService(gateway)++ _, err := service.CreatePortalSession(context.Background(), "subject-123", "https://run.example.test/billing")+ if err != nil {+ t.Fatalf("CreatePortalSession() error = %v", err)+ }+ want := PortalSessionRequest{CustomerID: "cus_owned", ReturnURL: "https://run.example.test/billing"}+ if !reflect.DeepEqual(gateway.portalRequest, want) {+ t.Fatalf("portal request = %#v, want %#v", gateway.portalRequest, want)+ }+}++func TestSetDefaultPaymentMethodForSetupGenerationDelegatesToGateway(t *testing.T) {+ gateway := &fakeGateway{defaultApplied: true}+ service := NewService(gateway)++ applied, err := service.SetDefaultPaymentMethodForSetupGeneration(context.Background(), "cus_owned", "pm_card", "current")+ if err != nil {+ t.Fatalf("SetDefaultPaymentMethodForSetupGeneration() error = %v", err)+ }+ if !applied {+ t.Fatal("default update was not applied")+ }+ if gateway.defaultCustomerID != "cus_owned" || gateway.defaultPaymentMethodID != "pm_card" || gateway.defaultGeneration != "current" {+ t.Fatalf("default update = %q/%q/%q", gateway.defaultCustomerID, gateway.defaultPaymentMethodID, gateway.defaultGeneration)+ }+}++func TestCreateSetupSessionStoresLatestOpaqueGeneration(t *testing.T) {+ gateway := &fakeGateway{createdCustomer: Customer{ID: "cus_owned"}}+ service := NewService(gateway)++ _, err := service.CreateSetupSession(context.Background(), "subject-123", SetupOptions{+ SuccessURL: "https://run.example.test/settings?setup=success",+ CancelURL: "https://run.example.test/settings?setup=cancelled",+ })+ if err != nil {+ t.Fatalf("CreateSetupSession() error = %v", err)+ }+ generation := gateway.updatedMetadata[MetadataSetupGeneration]+ if generation == "" {+ t.Fatal("latest setup generation must be server-generated and stored on the customer")+ }+ if gateway.setupRequest.SetupGeneration != generation {+ t.Fatalf("setup generation = %q, want customer generation", gateway.setupRequest.SetupGeneration)+ }+}++func TestCreateSetupSessionDoesNotPublishGenerationWhenCreationFails(t *testing.T) {+ gateway := &fakeGateway{customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123", MetadataSetupGeneration: "previous"}}}, setupErr: errors.New("stripe unavailable")}+ _, err := NewService(gateway).CreateSetupSession(context.Background(), "subject-123", SetupOptions{})+ if err == nil || gateway.updatedMetadata != nil || !reflect.DeepEqual(gateway.operations, []string{"create"}) {+ t.Fatalf("error/metadata/operations = %v/%#v/%#v", err, gateway.updatedMetadata, gateway.operations)+ }+}++func TestCreateSetupSessionReturnsNoURLWhenGenerationPublishFails(t *testing.T) {+ gateway := &fakeGateway{customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}}, updateErr: errors.New("stripe unavailable")}+ url, err := NewService(gateway).CreateSetupSession(context.Background(), "subject-123", SetupOptions{})+ if err == nil || url != "" || !reflect.DeepEqual(gateway.operations, []string{"create", "publish"}) {+ t.Fatalf("url/error/operations = %q/%v/%#v", url, err, gateway.operations)+ }+}diff --git a/libs/fleet/backend/billing/stripe_gateway.go b/libs/fleet/backend/billing/stripe_gateway.gonew file mode 100644index 0000000000..e20193ceae--- /dev/null+++ b/libs/fleet/backend/billing/stripe_gateway.go@@ -0,0 +1,170 @@+package billing++import (+ "context"+ "fmt"+ "strings"++ "github.com/stripe/stripe-go/v85"+)++type StripeGateway struct {+ client *stripe.Client+}++func NewStripeGateway(secretKey string) *StripeGateway {+ return &StripeGateway{client: stripe.NewClient(secretKey)}+}++func escapeSearchValue(value string) string {+ value = strings.ReplaceAll(value, `\`, `\\`)+ return strings.ReplaceAll(value, `'`, `\'`)+}++func customerSearchQuery(metadataKey, subject string) string {+ return fmt.Sprintf("metadata['%s']:'%s'", metadataKey, escapeSearchValue(subject))+}++func (g *StripeGateway) searchCustomersByMetadata(ctx context.Context, metadataKey, subject string) ([]Customer, error) {+ params := &stripe.CustomerSearchParams{+ SearchParams: stripe.SearchParams{+ Query: customerSearchQuery(metadataKey, subject),+ Limit: stripe.Int64(10),+ },+ }+ customers := make([]Customer, 0)+ for customer, err := range g.client.V1Customers.Search(ctx, params).All(ctx) {+ if err != nil {+ return nil, err+ }+ customers = append(customers, Customer{ID: customer.ID, Metadata: customer.Metadata})+ }+ return customers, nil+}++func (g *StripeGateway) SearchCustomers(ctx context.Context, subject string) ([]Customer, error) {+ byID := map[string]Customer{}+ for _, key := range []string{MetadataSubject, LegacyMetadataSubject} {+ customers, err := g.searchCustomersByMetadata(ctx, key, subject)+ if err != nil {+ return nil, err+ }+ for _, customer := range customers {+ byID[customer.ID] = customer+ }+ }+ customers := make([]Customer, 0, len(byID))+ for _, customer := range byID {+ customers = append(customers, customer)+ }+ return customers, nil+}++func (g *StripeGateway) CreateCustomer(ctx context.Context, metadata map[string]string, idempotencyKey string) (Customer, error) {+ params := &stripe.CustomerCreateParams{Metadata: metadata}+ params.SetIdempotencyKey(idempotencyKey)+ customer, err := g.client.V1Customers.Create(ctx, params)+ if err != nil {+ return Customer{}, err+ }+ return Customer{ID: customer.ID, Metadata: customer.Metadata}, nil+}++func (g *StripeGateway) UpdateCustomerMetadata(ctx context.Context, customerID string, metadata map[string]string) (Customer, error) {+ params := &stripe.CustomerUpdateParams{Metadata: metadata}+ customer, err := g.client.V1Customers.Update(ctx, customerID, params)+ if err != nil {+ return Customer{}, err+ }+ return Customer{ID: customer.ID, Metadata: customer.Metadata}, nil+}++func defaultCardRetrieveParams() *stripe.CustomerRetrieveParams {+ params := &stripe.CustomerRetrieveParams{}+ params.AddExpand("invoice_settings.default_payment_method")+ return params+}++func savedCardFromCustomer(customer *stripe.Customer) (SavedCard, error) {+ if customer == nil ||+ customer.InvoiceSettings == nil ||+ customer.InvoiceSettings.DefaultPaymentMethod == nil ||+ customer.InvoiceSettings.DefaultPaymentMethod.Card == nil {+ return SavedCard{}, ErrPaymentMethodNotFound+ }+ card := customer.InvoiceSettings.DefaultPaymentMethod.Card+ return SavedCard{+ Brand: string(card.Brand),+ Last4: card.Last4,+ ExpMonth: card.ExpMonth,+ ExpYear: card.ExpYear,+ }, nil+}++func (g *StripeGateway) GetDefaultCard(ctx context.Context, customerID string) (SavedCard, error) {+ customer, err := g.client.V1Customers.Retrieve(ctx, customerID, defaultCardRetrieveParams())+ if err != nil {+ return SavedCard{}, err+ }+ return savedCardFromCustomer(customer)+}++func currentSetupGeneration(metadata map[string]string, generation string) bool {+ return generation != "" && metadata[MetadataSetupGeneration] == generation+}++func defaultPaymentMethodUpdateParams(paymentMethodID string) *stripe.CustomerUpdateParams {+ params := &stripe.CustomerUpdateParams{+ InvoiceSettings: &stripe.CustomerUpdateInvoiceSettingsParams{+ DefaultPaymentMethod: stripe.String(paymentMethodID),+ },+ }+ params.AddMetadata(MetadataSetupGeneration, "")+ return params+}++func (g *StripeGateway) SetDefaultPaymentMethodForSetupGeneration(ctx context.Context, customerID, paymentMethodID, generation string) (bool, error) {+ customer, err := g.client.V1Customers.Retrieve(ctx, customerID, nil)+ if err != nil {+ return false, err+ }+ if !currentSetupGeneration(customer.Metadata, generation) {+ return false, nil+ }+ _, err = g.client.V1Customers.Update(ctx, customerID, defaultPaymentMethodUpdateParams(paymentMethodID))+ return err == nil, err+}++// Checkout setup mode creates a reusable off-session SetupIntent by default; stripe-go v85 exposes no usage override here.+func setupSessionParams(request SetupSessionRequest) *stripe.CheckoutSessionCreateParams {+ setupIntentData := &stripe.CheckoutSessionCreateSetupIntentDataParams{}+ setupIntentData.AddMetadata("purpose", SetupPurpose)+ setupIntentData.AddMetadata(MetadataSetupGeneration, request.SetupGeneration)+ return &stripe.CheckoutSessionCreateParams{+ Mode: stripe.String(string(stripe.CheckoutSessionModeSetup)),+ Customer: stripe.String(request.CustomerID),+ SuccessURL: stripe.String(request.SuccessURL),+ CancelURL: stripe.String(request.CancelURL),+ PaymentMethodTypes: []*string{stripe.String("card")},+ SetupIntentData: setupIntentData,+ }+}++func (g *StripeGateway) CreateSetupSession(ctx context.Context, request SetupSessionRequest) (string, error) {+ session, err := g.client.V1CheckoutSessions.Create(ctx, setupSessionParams(request))+ if err != nil {+ return "", err+ }+ return session.URL, nil+}++func (g *StripeGateway) CreatePortalSession(ctx context.Context, request PortalSessionRequest) (string, error) {+ session, err := g.client.V1BillingPortalSessions.Create(ctx, &stripe.BillingPortalSessionCreateParams{+ Customer: stripe.String(request.CustomerID),+ ReturnURL: stripe.String(request.ReturnURL),+ })+ if err != nil {+ return "", err+ }+ return session.URL, nil+}diff --git a/libs/fleet/backend/billing/stripe_gateway_test.go b/libs/fleet/backend/billing/stripe_gateway_test.gonew file mode 100644index 0000000000..67ee0873f7--- /dev/null+++ b/libs/fleet/backend/billing/stripe_gateway_test.go@@ -0,0 +1,164 @@+package billing++import (+ "errors"+ "testing"++ "github.com/stripe/stripe-go/v85"+)++func TestDefaultCardRetrieveParamsExpandsDefaultPaymentMethod(t *testing.T) {+ params := defaultCardRetrieveParams()+ if len(params.Expand) != 1 || params.Expand[0] == nil || *params.Expand[0] != "invoice_settings.default_payment_method" {+ t.Fatalf("Expand = %#v, want invoice_settings.default_payment_method", params.Expand)+ }+}++func TestSavedCardFromCustomer(t *testing.T) {+ tests := []struct {+ name string+ customer *stripe.Customer+ want SavedCard+ wantErr error+ }{+ {+ name: "missing invoice settings",+ customer: &stripe.Customer{},+ wantErr: ErrPaymentMethodNotFound,+ },+ {+ name: "missing default payment method",+ customer: &stripe.Customer{InvoiceSettings: &stripe.CustomerInvoiceSettings{}},+ wantErr: ErrPaymentMethodNotFound,+ },+ {+ name: "non-card default payment method",+ customer: &stripe.Customer{InvoiceSettings: &stripe.CustomerInvoiceSettings{+ DefaultPaymentMethod: &stripe.PaymentMethod{Type: stripe.PaymentMethodTypeUSBankAccount},+ }},+ wantErr: ErrPaymentMethodNotFound,+ },+ {+ name: "sanitized card mapping",+ customer: &stripe.Customer{InvoiceSettings: &stripe.CustomerInvoiceSettings{+ DefaultPaymentMethod: &stripe.PaymentMethod{Card: &stripe.PaymentMethodCard{+ Brand: stripe.PaymentMethodCardBrandVisa,+ Last4: "4242",+ ExpMonth: 12,+ ExpYear: 2030,+ Fingerprint: "must-not-leak",+ }},+ }},+ want: SavedCard{Brand: "visa", Last4: "4242", ExpMonth: 12, ExpYear: 2030},+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ got, err := savedCardFromCustomer(test.customer)+ if !errors.Is(err, test.wantErr) {+ t.Fatalf("error = %v, want %v", err, test.wantErr)+ }+ if got != test.want {+ t.Fatalf("card = %#v, want %#v", got, test.want)+ }+ })+ }+}++func TestCustomerSearchQueryUsesExactEscapedMetadata(t *testing.T) {+ for _, test := range []struct {+ name string+ key string+ want string+ }{+ {name: "fleet", key: MetadataSubject, want: `metadata['fleet_subject']:'subject\'\\123'`},+ {name: "legacy", key: LegacyMetadataSubject, want: `metadata['cyclops_subject']:'subject\'\\123'`},+ } {+ t.Run(test.name, func(t *testing.T) {+ if got := customerSearchQuery(test.key, "subject'\\123"); got != test.want {+ t.Fatalf("query = %q, want %q", got, test.want)+ }+ })+ }+}++func TestSetupSessionParamsUseCardSetupModeAndFleetPurpose(t *testing.T) {+ params := setupSessionParams(SetupSessionRequest{+ CustomerID: "cus_owned",+ SuccessURL: "https://run.example.test/settings?setup=success",+ CancelURL: "https://run.example.test/settings?setup=cancelled",+ })++ if params.Mode == nil || *params.Mode != string(stripe.CheckoutSessionModeSetup) {+ t.Fatalf("Mode = %v, want setup", params.Mode)+ }+ if params.Customer == nil || *params.Customer != "cus_owned" {+ t.Fatalf("Customer = %v, want owned customer", params.Customer)+ }+ if len(params.PaymentMethodTypes) != 1 || params.PaymentMethodTypes[0] == nil || *params.PaymentMethodTypes[0] != "card" {+ t.Fatalf("PaymentMethodTypes = %#v, want card only", params.PaymentMethodTypes)+ }+ if params.SetupIntentData == nil || params.SetupIntentData.Metadata["purpose"] != SetupPurpose {+ t.Fatalf("SetupIntent metadata = %#v, want fleet purpose", params.SetupIntentData)+ }+ if len(params.LineItems) != 0 {+ t.Fatalf("LineItems = %#v, want none", params.LineItems)+ }+}++func TestSetupSessionParamsCopyLatestCustomerGenerationToSetupIntent(t *testing.T) {+ params := setupSessionParams(SetupSessionRequest{+ CustomerID: "cus_owned",+ SuccessURL: "https://run.example.test/settings?setup=success",+ CancelURL: "https://run.example.test/settings?setup=cancelled",+ SetupGeneration: "server-generated-token",+ })++ if got := params.SetupIntentData.Metadata[MetadataSetupGeneration]; got != "server-generated-token" {+ t.Fatalf("setup intent generation = %q, want server-generated-token", got)+ }+}++func TestCurrentSetupGenerationRejectsStaleAndMalformedValues(t *testing.T) {+ tests := []struct {+ name string+ metadata map[string]string+ generation string+ want bool+ }{+ {name: "current", metadata: map[string]string{MetadataSetupGeneration: "current"}, generation: "current", want: true},+ {name: "stale", metadata: map[string]string{MetadataSetupGeneration: "current"}, generation: "older", want: false},+ {name: "missing customer generation", metadata: map[string]string{}, generation: "current", want: false},+ {name: "missing event generation", metadata: map[string]string{MetadataSetupGeneration: "current"}, want: false},+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if got := currentSetupGeneration(test.metadata, test.generation); got != test.want {+ t.Fatalf("currentSetupGeneration() = %t, want %t", got, test.want)+ }+ })+ }+}++func TestDefaultPaymentMethodUpdateParamsConsumeSetupGeneration(t *testing.T) {+ params := defaultPaymentMethodUpdateParams("pm_card")+ if params.InvoiceSettings == nil || params.InvoiceSettings.DefaultPaymentMethod == nil || *params.InvoiceSettings.DefaultPaymentMethod != "pm_card" {+ t.Fatalf("invoice settings = %#v", params.InvoiceSettings)+ }+ if params.Metadata[MetadataSetupGeneration] != "" {+ t.Fatalf("generation metadata = %#v, want supported unset value", params.Metadata)+ }+}++func TestCurrentSetupGenerationIgnoresDuplicateAfterMarkerConsumption(t *testing.T) {+ metadata := map[string]string{MetadataSetupGeneration: "current"}+ if !currentSetupGeneration(metadata, "current") {+ t.Fatal("first delivery must match the current marker")+ }+ metadata[MetadataSetupGeneration] = ""+ if currentSetupGeneration(metadata, "current") {+ t.Fatal("duplicate delivery must not match a consumed marker")+ }+}diff --git a/libs/fleet/backend/billing/webhook.go b/libs/fleet/backend/billing/webhook.gonew file mode 100644index 0000000000..ba41a96f55--- /dev/null+++ b/libs/fleet/backend/billing/webhook.go@@ -0,0 +1,57 @@+package billing++import (+ "encoding/json"++ "github.com/stripe/stripe-go/v85"+ "github.com/stripe/stripe-go/v85/webhook"+)++type WebhookEvent struct {+ ID string+ Type string+ Purpose string+ CustomerID string+ PaymentMethodID string+ SetupGeneration string+}++type StripeWebhookVerifier struct{}++func NewStripeWebhookVerifier() StripeWebhookVerifier {+ return StripeWebhookVerifier{}+}++func (StripeWebhookVerifier) Verify(payload []byte, signature, secret string) (WebhookEvent, error) {+ if err := webhook.ValidatePayload(payload, signature, secret); err != nil {+ return WebhookEvent{}, err+ }+ var envelope struct {+ ID string `json:"id"`+ Type string `json:"type"`+ Data struct {+ Object json.RawMessage `json:"object"`+ } `json:"data"`+ }+ if err := json.Unmarshal(payload, &envelope); err != nil {+ return WebhookEvent{}, nil+ }+ event := WebhookEvent{ID: envelope.ID, Type: envelope.Type}+ if envelope.Type != "setup_intent.succeeded" {+ return event, nil+ }++ var setupIntent stripe.SetupIntent+ if err := json.Unmarshal(envelope.Data.Object, &setupIntent); err != nil {+ return event, nil+ }+ event.Purpose = setupIntent.Metadata["purpose"]+ event.SetupGeneration = setupIntent.Metadata[MetadataSetupGeneration]+ if setupIntent.Customer != nil {+ event.CustomerID = setupIntent.Customer.ID+ }+ if setupIntent.PaymentMethod != nil {+ event.PaymentMethodID = setupIntent.PaymentMethod.ID+ }+ return event, nil+}diff --git a/libs/fleet/backend/billing/webhook_test.go b/libs/fleet/backend/billing/webhook_test.gonew file mode 100644index 0000000000..8e85af7f10--- /dev/null+++ b/libs/fleet/backend/billing/webhook_test.go@@ -0,0 +1,88 @@+package billing++import (+ "crypto/hmac"+ "crypto/sha256"+ "encoding/hex"+ "fmt"+ "testing"+ "time"+)++func billingStripeSignature(payload []byte, secret string, timestamp int64) string {+ mac := hmac.New(sha256.New, []byte(secret))+ _, _ = fmt.Fprintf(mac, "%d.", timestamp)+ _, _ = mac.Write(payload)+ return fmt.Sprintf("t=%d,v1=%s", timestamp, hex.EncodeToString(mac.Sum(nil)))+}++func TestVerifyParsesFleetSetupIntentSucceeded(t *testing.T) {+ secret := "whsec_test"+ payload := []byte(`{+ "id":"evt_setup",+ "type":"setup_intent.succeeded",+ "data":{"object":{+ "id":"seti_123",+ "object":"setup_intent",+ "customer":"cus_owned",+ "payment_method":"pm_card",+ "metadata":{"purpose":"fleet_default_card"}+ }}+ }`)+ signature := billingStripeSignature(payload, secret, time.Now().Unix())++ event, err := NewStripeWebhookVerifier().Verify(payload, signature, secret)+ if err != nil {+ t.Fatalf("Verify() error = %v", err)+ }+ want := WebhookEvent{+ ID: "evt_setup", Type: "setup_intent.succeeded",+ Purpose: SetupPurpose, CustomerID: "cus_owned", PaymentMethodID: "pm_card",+ }+ if event != want {+ t.Fatalf("event = %#v, want %#v", event, want)+ }+}++func TestVerifyLeavesMalformedSetupIntentUnprojected(t *testing.T) {+ secret := "whsec_test"+ payload := []byte(`{"id":"evt_setup","type":"setup_intent.succeeded"}`)+ signature := billingStripeSignature(payload, secret, time.Now().Unix())++ event, err := NewStripeWebhookVerifier().Verify(payload, signature, secret)+ if err != nil {+ t.Fatalf("Verify() error = %v", err)+ }+ want := WebhookEvent{ID: "evt_setup", Type: "setup_intent.succeeded"}+ if event != want {+ t.Fatalf("event = %#v, want %#v", event, want)+ }+}++func TestVerifyIgnoresCorrectlySignedTruncatedEnvelope(t *testing.T) {+ secret := "whsec_test"+ payload := []byte(`{"id":"evt_truncated"`)+ signature := billingStripeSignature(payload, secret, time.Now().Unix())++ event, err := NewStripeWebhookVerifier().Verify(payload, signature, secret)+ if err != nil {+ t.Fatalf("Verify() error = %v", err)+ }+ if event != (WebhookEvent{}) {+ t.Fatalf("event = %#v, want empty event", event)+ }+}++func TestVerifyParsesServerSetupGeneration(t *testing.T) {+ secret := "whsec_test"+ payload := []byte(`{"id":"evt_setup","type":"setup_intent.succeeded","data":{"object":{"id":"seti_123","object":"setup_intent","customer":"cus_owned","payment_method":"pm_card","metadata":{"purpose":"fleet_default_card","fleet_setup_generation":"server-generated-token"}}}}`)+ signature := billingStripeSignature(payload, secret, time.Now().Unix())++ event, err := NewStripeWebhookVerifier().Verify(payload, signature, secret)+ if err != nil {+ t.Fatalf("Verify() error = %v", err)+ }+ if event.SetupGeneration != "server-generated-token" {+ t.Fatalf("setup generation = %q, want server-generated-token", event.SetupGeneration)+ }+}diff --git a/libs/fleet/backend/config/config.go b/libs/fleet/backend/config/config.goindex 1100c8dd8a..4c0b5a4d5b 100644--- a/libs/fleet/backend/config/config.go+++ b/libs/fleet/backend/config/config.go@@ -24,6 +24,7 @@ type Configuration struct {Auth AuthConfigurationKeycloak KeycloakConfigurationGateway GatewayConfiguration+ Stripe StripeConfigurationMetrics MetricsConfigurationTelemetry TelemetryConfiguration}@@ -71,6 +72,13 @@ type GatewayConfiguration struct {ClusterDomain string}+type StripeConfiguration struct {+ SecretKey string+ WebhookSecret string+ CheckoutSuccessURL string+ CheckoutCancelURL string+ PortalReturnURL string+}type MetricsConfiguration struct {Addr string // METRICS_ADDR — Prometheus listen addr@@ -109,6 +117,11 @@ var specs = []flagSpec{{"gateway.scheme", "orch-scheme", "ORCH_SCHEME", "http", "orchestrator scheme"},{"gateway.port", "orch-port", "ORCH_PORT", "80", "orchestrator port"},{"gateway.cluster-domain", "cluster-domain", "CLUSTER_DOMAIN", "svc.cluster.local", "in-cluster DNS domain"},+ {"stripe.secret-key", "stripe-secret-key", "STRIPE_SECRET_KEY", "", "Stripe secret key (server-only)"},+ {"stripe.webhook-secret", "stripe-webhook-secret", "STRIPE_WEBHOOK_SECRET", "", "Stripe webhook signing secret"},+ {"stripe.checkout-success-url", "stripe-checkout-success-url", "STRIPE_CHECKOUT_SUCCESS_URL", "", "Stripe Checkout success redirect URL"},+ {"stripe.checkout-cancel-url", "stripe-checkout-cancel-url", "STRIPE_CHECKOUT_CANCEL_URL", "", "Stripe Checkout cancel redirect URL"},+ {"stripe.portal-return-url", "stripe-portal-return-url", "STRIPE_PORTAL_RETURN_URL", "", "Stripe Billing Portal return URL"},{"metrics.addr", "metrics-addr", "METRICS_ADDR", ":9091", "Prometheus metrics listen address"},{"telemetry.endpoint", "otel-endpoint", "OTEL_EXPORTER_OTLP_ENDPOINT", "https://otel.cua.ai", "OTLP HTTP traces endpoint"},{"telemetry.protocol", "otel-protocol", "OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf", "OTLP exporter protocol"},@@ -140,7 +153,6 @@ func LoadConfig() (*Configuration, error) {issuer = realmPath}-cfg := &Configuration{WebServer: WebServerConfiguration{Addr: viper.GetString("webserver.addr")},Auth: AuthConfiguration{@@ -170,7 +182,14 @@ func LoadConfig() (*Configuration, error) {Port: viper.GetString("gateway.port"),ClusterDomain: viper.GetString("gateway.cluster-domain"),},- Metrics: MetricsConfiguration{Addr: viper.GetString("metrics.addr")},+ Stripe: StripeConfiguration{+ SecretKey: viper.GetString("stripe.secret-key"),+ WebhookSecret: viper.GetString("stripe.webhook-secret"),+ CheckoutSuccessURL: viper.GetString("stripe.checkout-success-url"),+ CheckoutCancelURL: viper.GetString("stripe.checkout-cancel-url"),+ PortalReturnURL: viper.GetString("stripe.portal-return-url"),+ },+ Metrics: MetricsConfiguration{Addr: viper.GetString("metrics.addr")},Telemetry: TelemetryConfiguration{Endpoint: viper.GetString("telemetry.endpoint"),Protocol: viper.GetString("telemetry.protocol"),diff --git a/libs/fleet/backend/config/config_test.go b/libs/fleet/backend/config/config_test.goindex 8474515d28..79b22b6954 100644--- a/libs/fleet/backend/config/config_test.go+++ b/libs/fleet/backend/config/config_test.go@@ -52,3 +52,56 @@ func TestLoadConfig_TelemetryDefaults(t *testing.T) {t.Fatalf("Telemetry.Environment = %q, want %q", got, want)}}++func TestLoadConfig_StripeBillingValues(t *testing.T) {+ t.Setenv("KC_ADMIN_CLIENT_SECRET", "secret")+ t.Setenv("STRIPE_SECRET_KEY", "sk_test_server_only")+ t.Setenv("STRIPE_WEBHOOK_SECRET", "whsec_test")+ t.Setenv("STRIPE_CHECKOUT_SUCCESS_URL", "https://run.example.test/billing?checkout=success")+ t.Setenv("STRIPE_CHECKOUT_CANCEL_URL", "https://run.example.test/billing?checkout=cancelled")+ t.Setenv("STRIPE_PORTAL_RETURN_URL", "https://run.example.test/billing")+ RegisterFlags(pflag.NewFlagSet("stripe-test", pflag.ContinueOnError))++ cfg, err := LoadConfig()+ if err != nil {+ t.Fatalf("LoadConfig() error = %v", err)+ }++ if got, want := cfg.Stripe.SecretKey, "sk_test_server_only"; got != want {+ t.Fatalf("Stripe.SecretKey = %q, want %q", got, want)+ }+ if got, want := cfg.Stripe.WebhookSecret, "whsec_test"; got != want {+ t.Fatalf("Stripe.WebhookSecret = %q, want %q", got, want)+ }+ if got, want := cfg.Stripe.CheckoutSuccessURL, "https://run.example.test/billing?checkout=success"; got != want {+ t.Fatalf("Stripe.CheckoutSuccessURL = %q, want %q", got, want)+ }+ if got, want := cfg.Stripe.CheckoutCancelURL, "https://run.example.test/billing?checkout=cancelled"; got != want {+ t.Fatalf("Stripe.CheckoutCancelURL = %q, want %q", got, want)+ }+ if got, want := cfg.Stripe.PortalReturnURL, "https://run.example.test/billing"; got != want {+ t.Fatalf("Stripe.PortalReturnURL = %q, want %q", got, want)+ }+}++func TestLoadConfig_StripeBillingDefaultsAbsent(t *testing.T) {+ t.Setenv("KC_ADMIN_CLIENT_SECRET", "secret")+ for _, key := range []string{+ "STRIPE_SECRET_KEY",+ "STRIPE_WEBHOOK_SECRET",+ "STRIPE_CHECKOUT_SUCCESS_URL",+ "STRIPE_CHECKOUT_CANCEL_URL",+ "STRIPE_PORTAL_RETURN_URL",+ } {+ t.Setenv(key, "")+ }+ RegisterFlags(pflag.NewFlagSet("stripe-absent-test", pflag.ContinueOnError))++ cfg, err := LoadConfig()+ if err != nil {+ t.Fatalf("LoadConfig() error = %v", err)+ }+ if cfg.Stripe != (StripeConfiguration{}) {+ t.Fatalf("Stripe = %#v, want zero configuration", cfg.Stripe)+ }+}diff --git a/libs/fleet/backend/docs/docs.go b/libs/fleet/backend/docs/docs.goindex bdd0b63bcd..50ee4fa168 100644--- a/libs/fleet/backend/docs/docs.go+++ b/libs/fleet/backend/docs/docs.go@@ -262,6 +262,242 @@ const docTemplate = `{}}},+ "/api/billing/portal-session": {+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Creates a Stripe-hosted Billing Portal Session for the customer owned by the authenticated Cyclops subject.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Create Stripe Billing Portal Session",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.BillingSessionResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "/api/billing/setup-session": {+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Creates a Stripe-hosted Checkout Session in setup mode for reusable off-session card collection.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Create Stripe card setup Session",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.BillingSessionResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "/api/billing/summary": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Returns a sanitized Stripe-backed billing summary for the authenticated Cyclops subject.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Billing summary",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/billing.Summary"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "/api/billing/webhook": {+ "post": {+ "description": "Verifies a Stripe-signed raw webhook body and configures the default payment method for completed fleet setup intents.",+ "consumes": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Receive Stripe webhook",+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "413": {+ "description": "Request Entity Too Large",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },"/api/config": {"get": {"security": [@@ -1119,12 +1355,60 @@ const docTemplate = `{}},"definitions": {+ "billing.CardSummary": {+ "type": "object",+ "properties": {+ "brand": {+ "type": "string"+ },+ "exp_month": {+ "type": "integer"+ },+ "exp_year": {+ "type": "integer"+ },+ "last4": {+ "type": "string"+ }+ }+ },+ "billing.Summary": {+ "type": "object",+ "required": [+ "card",+ "payment_method_present"+ ],+ "properties": {+ "card": {+ "allOf": [+ {+ "$ref": "#/definitions/billing.CardSummary"+ }+ ],+ "x-nullable": true+ },+ "payment_method_present": {+ "type": "boolean"+ }+ }+ },+ "handlers.BillingSessionResponse": {+ "type": "object",+ "properties": {+ "url": {+ "type": "string"+ }+ }+ },"handlers.ConfigResponse": {"type": "object","properties": {"admin": {"description": "Admin is true when the caller is in input.flags.admin_subs (OPA-evaluated).\nNon-admins get the customer view: infra-only nav (Nodes, Operator events)\nis hidden in the SPA and the corresponding kubectl-proxy paths are denied\nserver-side by authz.rego.","type": "boolean"+ },+ "billing": {+ "type": "boolean"}}},diff --git a/libs/fleet/backend/docs/swagger.json b/libs/fleet/backend/docs/swagger.jsonindex d4792431e8..2f1d342f27 100644--- a/libs/fleet/backend/docs/swagger.json+++ b/libs/fleet/backend/docs/swagger.json@@ -255,6 +255,242 @@}}},+ "/api/billing/portal-session": {+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Creates a Stripe-hosted Billing Portal Session for the customer owned by the authenticated Cyclops subject.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Create Stripe Billing Portal Session",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.BillingSessionResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "/api/billing/setup-session": {+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Creates a Stripe-hosted Checkout Session in setup mode for reusable off-session card collection.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Create Stripe card setup Session",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.BillingSessionResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "/api/billing/summary": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Returns a sanitized Stripe-backed billing summary for the authenticated Cyclops subject.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Billing summary",+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/billing.Summary"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "/api/billing/webhook": {+ "post": {+ "description": "Verifies a Stripe-signed raw webhook body and configures the default payment method for completed fleet setup intents.",+ "consumes": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Receive Stripe webhook",+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "413": {+ "description": "Request Entity Too Large",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },"/api/config": {"get": {"security": [@@ -1112,12 +1348,60 @@}},"definitions": {+ "billing.CardSummary": {+ "type": "object",+ "properties": {+ "brand": {+ "type": "string"+ },+ "exp_month": {+ "type": "integer"+ },+ "exp_year": {+ "type": "integer"+ },+ "last4": {+ "type": "string"+ }+ }+ },+ "billing.Summary": {+ "type": "object",+ "required": [+ "card",+ "payment_method_present"+ ],+ "properties": {+ "card": {+ "allOf": [+ {+ "$ref": "#/definitions/billing.CardSummary"+ }+ ],+ "x-nullable": true+ },+ "payment_method_present": {+ "type": "boolean"+ }+ }+ },+ "handlers.BillingSessionResponse": {+ "type": "object",+ "properties": {+ "url": {+ "type": "string"+ }+ }+ },"handlers.ConfigResponse": {"type": "object","properties": {"admin": {"description": "Admin is true when the caller is in input.flags.admin_subs (OPA-evaluated).\nNon-admins get the customer view: infra-only nav (Nodes, Operator events)\nis hidden in the SPA and the corresponding kubectl-proxy paths are denied\nserver-side by authz.rego.","type": "boolean"+ },+ "billing": {+ "type": "boolean"}}},diff --git a/libs/fleet/backend/docs/swagger.yaml b/libs/fleet/backend/docs/swagger.yamlindex c010c6e52a..9a96c798bd 100644--- a/libs/fleet/backend/docs/swagger.yaml+++ b/libs/fleet/backend/docs/swagger.yaml@@ -1,5 +1,33 @@basePath: /definitions:+ billing.CardSummary:+ properties:+ brand:+ type: string+ exp_month:+ type: integer+ exp_year:+ type: integer+ last4:+ type: string+ type: object+ billing.Summary:+ properties:+ card:+ allOf:+ - $ref: '#/definitions/billing.CardSummary'+ x-nullable: true+ payment_method_present:+ type: boolean+ required:+ - card+ - payment_method_present+ type: object+ handlers.BillingSessionResponse:+ properties:+ url:+ type: string+ type: objecthandlers.ConfigResponse:properties:admin:@@ -9,6 +37,8 @@ definitions:is hidden in the SPA and the corresponding kubectl-proxy paths are deniedserver-side by authz.rego.type: boolean+ billing:+ type: booleantype: objecthandlers.CreateKeyRequest:properties:@@ -308,6 +338,162 @@ paths:summary: Deprecated batch submission routetags:- batch+ /api/billing/portal-session:+ post:+ description: Creates a Stripe-hosted Billing Portal Session for the customer+ owned by the authenticated Cyclops subject.+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/handlers.BillingSessionResponse'+ "400":+ description: Bad Request+ schema:+ additionalProperties:+ type: string+ type: object+ "401":+ description: Unauthorized+ schema:+ additionalProperties:+ type: string+ type: object+ "403":+ description: Forbidden+ schema:+ additionalProperties:+ type: string+ type: object+ "404":+ description: Not Found+ schema:+ additionalProperties:+ type: string+ type: object+ "503":+ description: Service Unavailable+ schema:+ additionalProperties:+ type: string+ type: object+ security:+ - BearerAuth: []+ summary: Create Stripe Billing Portal Session+ tags:+ - billing+ /api/billing/setup-session:+ post:+ description: Creates a Stripe-hosted Checkout Session in setup mode for reusable+ off-session card collection.+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/handlers.BillingSessionResponse'+ "400":+ description: Bad Request+ schema:+ additionalProperties:+ type: string+ type: object+ "401":+ description: Unauthorized+ schema:+ additionalProperties:+ type: string+ type: object+ "403":+ description: Forbidden+ schema:+ additionalProperties:+ type: string+ type: object+ "503":+ description: Service Unavailable+ schema:+ additionalProperties:+ type: string+ type: object+ security:+ - BearerAuth: []+ summary: Create Stripe card setup Session+ tags:+ - billing+ /api/billing/summary:+ get:+ description: Returns a sanitized Stripe-backed billing summary for the authenticated+ Cyclops subject.+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/billing.Summary'+ "401":+ description: Unauthorized+ schema:+ additionalProperties:+ type: string+ type: object+ "403":+ description: Forbidden+ schema:+ additionalProperties:+ type: string+ type: object+ "503":+ description: Service Unavailable+ schema:+ additionalProperties:+ type: string+ type: object+ security:+ - BearerAuth: []+ summary: Billing summary+ tags:+ - billing+ /api/billing/webhook:+ post:+ consumes:+ - application/json+ description: Verifies a Stripe-signed raw webhook body and configures the default+ payment method for completed fleet setup intents.+ responses:+ "204":+ description: No Content+ "400":+ description: Bad Request+ schema:+ additionalProperties:+ type: string+ type: object+ "413":+ description: Request Entity Too Large+ schema:+ additionalProperties:+ type: string+ type: object+ "502":+ description: Bad Gateway+ schema:+ additionalProperties:+ type: string+ type: object+ "503":+ description: Service Unavailable+ schema:+ additionalProperties:+ type: string+ type: object+ summary: Receive Stripe webhook+ tags:+ - billing/api/config:get:description: Returns OPA-evaluated feature flags for the authenticated SPA user.diff --git a/libs/fleet/backend/go.mod b/libs/fleet/backend/go.modindex 01c16071ed..b785203403 100644--- a/libs/fleet/backend/go.mod+++ b/libs/fleet/backend/go.mod@@ -16,6 +16,7 @@ require (github.com/spf13/cobra v1.10.2github.com/spf13/pflag v1.0.10github.com/spf13/viper v1.21.0+ github.com/stripe/stripe-go/v85 v85.2.0github.com/swaggo/http-swagger/v2 v2.0.2github.com/swaggo/swag v1.16.6go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0diff --git a/libs/fleet/backend/go.sum b/libs/fleet/backend/go.sumindex 07b321d77a..8aa61d7fa4 100644--- a/libs/fleet/backend/go.sum+++ b/libs/fleet/backend/go.sum@@ -205,6 +205,8 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/stripe/stripe-go/v85 v85.2.0 h1:LomL8ulv13+y+nIKtFP48Cn/pCIZmi4IBz5qjdDn+FY=+github.com/stripe/stripe-go/v85 v85.2.0/go.mod h1:5P+HGFenpWgak27T5Is6JMsmDfUC1yJnjhhmquz7kXw=github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=github.com/swaggo/files/v2 v2.0.0 h1:hmAt8Dkynw7Ssz46F6pn8ok6YmGZqHSVLZ+HQM7i0kw=diff --git a/libs/fleet/backend/handlers/billing.go b/libs/fleet/backend/handlers/billing.gonew file mode 100644index 0000000000..de83d071c8--- /dev/null+++ b/libs/fleet/backend/handlers/billing.go@@ -0,0 +1,171 @@+package handlers++import (+ "context"+ "errors"+ "io"+ "log/slog"+ "net/http"+ "strings"++ "cyclops-cs-backend/auth"+ "cyclops-cs-backend/billing"+)++type BillingService interface {+ 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)+ SetDefaultPaymentMethodForSetupGeneration(ctx context.Context, customerID, paymentMethodID, generation string) (bool, error)+}++type BillingSessionResponse struct {+ URL string `json:"url"`+}++func (h Handlers) billingAvailable(w http.ResponseWriter) bool {+ if h.Billing == nil || h.Stripe.SecretKey == "" {+ writeErr(w, http.StatusServiceUnavailable, "Stripe billing is not configured")+ return false+ }+ return true+}++func requireBillingEnabled(w http.ResponseWriter, r *http.Request) (*auth.User, bool) {+ user := currentUser(r)+ if user == nil || user.ID == "" {+ writeErr(w, http.StatusUnauthorized, "authenticated user is required")+ return nil, false+ }++ enabled, err := auth.EvalBillingEnabled(r.Context(), user)+ if err != nil {+ slog.WarnContext(r.Context(), "billing flag eval failed; denying request", "err", err)+ }+ if !enabled {+ writeErr(w, http.StatusForbidden, "billing is disabled")+ return nil, false+ }+ return user, true+}++func requireEmptyBillingBody(w http.ResponseWriter, r *http.Request) bool {+ if r.Body == nil {+ return true+ }+ r.Body = http.MaxBytesReader(w, r.Body, 1024)+ body, err := io.ReadAll(r.Body)+ if err != nil {+ var maxErr *http.MaxBytesError+ if errors.As(err, &maxErr) {+ writeErr(w, http.StatusRequestEntityTooLarge, "billing request body is too large")+ } else {+ writeErr(w, http.StatusBadRequest, "could not read billing request")+ }+ return false+ }+ if strings.TrimSpace(string(body)) != "" {+ writeErr(w, http.StatusBadRequest, "billing request body must be empty")+ return false+ }+ return true+}++// GetBillingSummary godoc+// @Summary Billing summary+// @Description Returns a sanitized Stripe-backed billing summary for the authenticated Cyclops subject.+// @Tags billing+// @Produce json+// @Success 200 {object} billing.Summary+// @Failure 401 {object} map[string]string+// @Failure 403 {object} map[string]string+// @Failure 503 {object} map[string]string+// @Security BearerAuth+// @Router /api/billing/summary [get]+func (h Handlers) GetBillingSummary(w http.ResponseWriter, r *http.Request) {+ user, ok := requireBillingEnabled(w, r)+ if !ok {+ return+ }+ if !h.billingAvailable(w) {+ return+ }+ summary, err := h.Billing.Summary(r.Context(), user.ID)+ if err != nil {+ writeErr(w, http.StatusBadGateway, "could not load billing summary")+ return+ }+ writeJSON(w, http.StatusOK, summary)+}++// CreateBillingSetupSession godoc+// @Summary Create Stripe card setup Session+// @Description Creates a Stripe-hosted Checkout Session in setup mode for reusable off-session card collection.+// @Tags billing+// @Produce json+// @Success 200 {object} BillingSessionResponse+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Failure 403 {object} map[string]string+// @Failure 503 {object} map[string]string+// @Security BearerAuth+// @Router /api/billing/setup-session [post]+func (h Handlers) CreateBillingSetupSession(w http.ResponseWriter, r *http.Request) {+ user, ok := requireBillingEnabled(w, r)+ if !ok || !requireEmptyBillingBody(w, r) || !h.billingAvailable(w) {+ return+ }+ if h.Stripe.CheckoutSuccessURL == "" || h.Stripe.CheckoutCancelURL == "" {+ writeErr(w, http.StatusServiceUnavailable, "Stripe card setup is not configured; redirect URLs are required")+ return+ }+ url, err := h.Billing.CreateSetupSession(r.Context(), user.ID, billing.SetupOptions{+ SuccessURL: h.Stripe.CheckoutSuccessURL,+ CancelURL: h.Stripe.CheckoutCancelURL,+ })+ if err != nil {+ writeErr(w, http.StatusBadGateway, "could not create Stripe card setup Session")+ return+ }+ writeJSON(w, http.StatusOK, BillingSessionResponse{URL: url})+}++// CreateBillingPortalSession godoc+// @Summary Create Stripe Billing Portal Session+// @Description Creates a Stripe-hosted Billing Portal Session for the customer owned by the authenticated Cyclops subject.+// @Tags billing+// @Produce json+// @Success 200 {object} BillingSessionResponse+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Failure 403 {object} map[string]string+// @Failure 404 {object} map[string]string+// @Failure 503 {object} map[string]string+// @Security BearerAuth+// @Router /api/billing/portal-session [post]+func (h Handlers) CreateBillingPortalSession(w http.ResponseWriter, r *http.Request) {+ user, ok := requireBillingEnabled(w, r)+ if !ok {+ return+ }+ if !requireEmptyBillingBody(w, r) {+ return+ }+ if !h.billingAvailable(w) {+ return+ }+ if h.Stripe.PortalReturnURL == "" {+ writeErr(w, http.StatusServiceUnavailable, "Stripe Billing Portal is not configured; STRIPE_PORTAL_RETURN_URL is required")+ return+ }+ url, err := h.Billing.CreatePortalSession(r.Context(), user.ID, h.Stripe.PortalReturnURL)+ if errors.Is(err, billing.ErrCustomerNotFound) {+ writeErr(w, http.StatusNotFound, "billing customer was not found")+ return+ }+ if err != nil {+ writeErr(w, http.StatusBadGateway, "could not create Stripe Billing Portal Session")+ return+ }+ writeJSON(w, http.StatusOK, BillingSessionResponse{URL: url})+}diff --git a/libs/fleet/backend/handlers/billing_test.go b/libs/fleet/backend/handlers/billing_test.gonew file mode 100644index 0000000000..8f79e03419--- /dev/null+++ b/libs/fleet/backend/handlers/billing_test.go@@ -0,0 +1,266 @@+package handlers++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "cyclops-cs-backend/auth"+ "cyclops-cs-backend/billing"+ "cyclops-cs-backend/config"++ "github.com/trycua/cloud/pkg/featureflags"+)++type fakeBillingService struct {+ summaryCalls int+ summarySubject string+ setupSubject string+ setupOptions billing.SetupOptions+ portalSubject string+ portalReturnURL string+ setupCalls int+ portalCalls int+ defaultCustomerID string+ defaultPaymentMethodID string+ defaultGeneration string+ defaultApplied bool+ defaultCalls int+ defaultErr error+}++func (f *fakeBillingService) Summary(_ context.Context, subject string) (billing.Summary, error) {+ f.summaryCalls+++ f.summarySubject = subject+ return billing.Summary{}, nil+}++func (f *fakeBillingService) SetDefaultPaymentMethodForSetupGeneration(_ context.Context, customerID, paymentMethodID, generation string) (bool, error) {+ f.defaultCalls+++ f.defaultCustomerID = customerID+ f.defaultPaymentMethodID = paymentMethodID+ f.defaultGeneration = generation+ return f.defaultApplied, f.defaultErr+}++func (f *fakeBillingService) CreateSetupSession(_ context.Context, subject string, options billing.SetupOptions) (string, error) {+ f.setupCalls+++ f.setupSubject = subject+ f.setupOptions = options+ return "https://checkout.stripe.test/session", nil+}++func (f *fakeBillingService) CreatePortalSession(_ context.Context, subject, returnURL string) (string, error) {+ f.portalCalls+++ f.portalSubject = subject+ f.portalReturnURL = returnURL+ return "https://billing.stripe.test/session", nil+}++var billingAlice = &auth.User{ID: "user-alice"}++func newBillingRequest(method, target, body string, user *auth.User) *http.Request {+ var request *http.Request+ if body == "" {+ request = httptest.NewRequest(method, target, nil)+ } else {+ request = httptest.NewRequest(method, target, strings.NewReader(body))+ }+ if user != nil {+ request = withUser(request, user)+ }+ return request+}++func setBillingFlag(t *testing.T, enabled bool) {+ t.Helper()+ value := "false"+ if enabled {+ value = "true"+ }+ t.Setenv("CYCLOPS_CS_BILLING_ENABLED", value)+ if err := featureflags.SetupProvider(context.Background(), "development", featureflags.AWSCredentials{}); err != nil {+ t.Fatalf("setup feature flag provider: %v", err)+ }+}++func TestBillingSummaryReturns503WithoutStripeConfiguration(t *testing.T) {+ setBillingFlag(t, true)+ service := &fakeBillingService{}+ h := Handlers{Billing: service}+ w := httptest.NewRecorder()++ h.GetBillingSummary(w, newBillingRequest(http.MethodGet, "/api/billing/summary", "", billingAlice))++ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("status = %d, want 503; body = %s", w.Code, w.Body.String())+ }+ if service.summarySubject != "" {+ t.Fatalf("summary subject = %q, want no service call", service.summarySubject)+ }+}++func TestBillingSummaryDerivesIdentityFromCurrentUser(t *testing.T) {+ setBillingFlag(t, true)+ service := &fakeBillingService{}+ h := Handlers{Billing: service, 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())+ }+ if service.summarySubject != billingAlice.ID {+ t.Fatalf("summary subject = %q, want authenticated subject %q", service.summarySubject, billingAlice.ID)+ }+}++func TestCreateSetupSessionReturns503WithoutRedirectURLs(t *testing.T) {+ setBillingFlag(t, true)+ service := &fakeBillingService{}+ h := Handlers{+ Billing: service,+ Stripe: config.StripeConfiguration{+ SecretKey: "sk_test",+ },+ }+ w := httptest.NewRecorder()++ h.CreateBillingSetupSession(w, newBillingRequest(http.MethodPost, "/api/billing/setup-session", "", billingAlice))++ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("status = %d, want 503; body = %s", w.Code, w.Body.String())+ }+ if service.setupCalls != 0 {+ t.Fatalf("setup calls = %d, want 0", service.setupCalls)+ }+}++func TestCreateSetupSessionUsesAuthenticatedSubjectAndNoClientInput(t *testing.T) {+ setBillingFlag(t, true)+ service := &fakeBillingService{}+ h := Handlers{+ Billing: service,+ Stripe: config.StripeConfiguration{+ SecretKey: "sk_test",+ CheckoutSuccessURL: "https://run.example.test/settings?setup=success",+ CheckoutCancelURL: "https://run.example.test/settings?setup=cancelled",+ },+ }++ attacker := httptest.NewRecorder()+ h.CreateBillingSetupSession(attacker, newBillingRequest(http.MethodPost, "/api/billing/setup-session", `{"customer":"cus_attacker","payment_method":"pm_attacker"}`, billingAlice))+ if attacker.Code != http.StatusBadRequest {+ t.Fatalf("client billing input status = %d, want 400; body = %s", attacker.Code, attacker.Body.String())+ }+ if service.setupCalls != 0 {+ t.Fatalf("setup calls after client input = %d, want 0", service.setupCalls)+ }++ w := httptest.NewRecorder()+ h.CreateBillingSetupSession(w, newBillingRequest(http.MethodPost, "/api/billing/setup-session", "", billingAlice))+ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())+ }+ if service.setupSubject != billingAlice.ID {+ t.Fatalf("setup subject = %q, want %q", service.setupSubject, billingAlice.ID)+ }+ var response BillingSessionResponse+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if response.URL != "https://checkout.stripe.test/session" {+ t.Fatalf("response URL = %q", response.URL)+ }+}++func TestCreatePortalSessionDerivesOwnedCustomerFromCurrentUser(t *testing.T) {+ setBillingFlag(t, true)+ service := &fakeBillingService{}+ h := Handlers{+ Billing: service,+ Stripe: config.StripeConfiguration{SecretKey: "sk_test", PortalReturnURL: "https://run.example.test/billing"},+ }+ w := httptest.NewRecorder()++ h.CreateBillingPortalSession(w, newBillingRequest(http.MethodPost, "/api/billing/portal-session", "", billingAlice))++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())+ }+ if service.portalSubject != billingAlice.ID {+ t.Fatalf("portal subject = %q, want %q", service.portalSubject, billingAlice.ID)+ }+ if service.portalReturnURL != "https://run.example.test/billing" {+ t.Fatalf("portal return URL = %q", service.portalReturnURL)+ }+}++func TestBillingEndpointsRejectWhenFlagDisabled(t *testing.T) {+ setBillingFlag(t, false)++ tests := []struct {+ name string+ handle func(Handlers, http.ResponseWriter, *http.Request)+ method string+ path string+ invoked func(*fakeBillingService) int+ }{+ {+ name: "summary",+ handle: func(h Handlers, w http.ResponseWriter, r *http.Request) { h.GetBillingSummary(w, r) },+ method: http.MethodGet,+ path: "/api/billing/summary",+ invoked: func(service *fakeBillingService) int {+ return service.summaryCalls+ },+ },+ {+ name: "setup",+ handle: func(h Handlers, w http.ResponseWriter, r *http.Request) { h.CreateBillingSetupSession(w, r) },+ method: http.MethodPost,+ path: "/api/billing/setup-session",+ invoked: func(service *fakeBillingService) int {+ return service.setupCalls+ },+ },+ {+ name: "portal",+ handle: func(h Handlers, w http.ResponseWriter, r *http.Request) { h.CreateBillingPortalSession(w, r) },+ method: http.MethodPost,+ path: "/api/billing/portal-session",+ invoked: func(service *fakeBillingService) int {+ return service.portalCalls+ },+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ service := &fakeBillingService{}+ h := Handlers{+ Billing: service,+ Stripe: config.StripeConfiguration{+ SecretKey: "sk_test",+ CheckoutSuccessURL: "https://run.example.test/settings?setup=success",+ CheckoutCancelURL: "https://run.example.test/settings?setup=cancelled",+ PortalReturnURL: "https://run.example.test/billing",+ },+ }+ w := httptest.NewRecorder()++ test.handle(h, w, newBillingRequest(test.method, test.path, "", billingAlice))++ if w.Code != http.StatusForbidden {+ t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())+ }+ if calls := test.invoked(service); calls != 0 {+ t.Fatalf("billing service calls = %d, want 0", calls)+ }+ })+ }+}diff --git a/libs/fleet/backend/handlers/billing_webhook.go b/libs/fleet/backend/handlers/billing_webhook.gonew file mode 100644index 0000000000..feac1b36bd--- /dev/null+++ b/libs/fleet/backend/handlers/billing_webhook.go@@ -0,0 +1,85 @@+package handlers++import (+ "errors"+ "io"+ "net/http"++ "cyclops-cs-backend/billing"+ "cyclops-cs-backend/metrics"+)++const stripeWebhookBodyLimit = 64 << 10++type WebhookVerifier interface {+ Verify(payload []byte, signature, secret string) (billing.WebhookEvent, error)+}++// HandleBillingWebhook godoc+// @Summary Receive Stripe webhook+// @Description Verifies a Stripe-signed raw webhook body and configures the default payment method for completed fleet setup intents.+// @Tags billing+// @Accept json+// @Success 204+// @Failure 400 {object} map[string]string+// @Failure 413 {object} map[string]string+// @Failure 502 {object} map[string]string+// @Failure 503 {object} map[string]string+// @Router /api/billing/webhook [post]+func (h Handlers) HandleBillingWebhook(w http.ResponseWriter, r *http.Request) {+ if h.Stripe.WebhookSecret == "" || h.WebhookVerifier == nil {+ metrics.RecordBillingWebhook("unavailable", "")+ writeErr(w, http.StatusServiceUnavailable, "Stripe webhook verification is not configured")+ return+ }++ r.Body = http.MaxBytesReader(w, r.Body, stripeWebhookBodyLimit)+ payload, err := io.ReadAll(r.Body)+ if err != nil {+ var maxErr *http.MaxBytesError+ if errors.As(err, &maxErr) {+ metrics.RecordBillingWebhook("oversized", "")+ writeErr(w, http.StatusRequestEntityTooLarge, "Stripe webhook body is too large")+ return+ }+ metrics.RecordBillingWebhook("read_error", "")+ writeErr(w, http.StatusBadRequest, "could not read Stripe webhook body")+ return+ }++ event, err := h.WebhookVerifier.Verify(payload, r.Header.Get("Stripe-Signature"), h.Stripe.WebhookSecret)+ if err != nil {+ metrics.RecordBillingWebhook("invalid_signature", "")+ writeErr(w, http.StatusBadRequest, "invalid Stripe webhook signature")+ return+ }++ if event.Type != "setup_intent.succeeded" || event.Purpose != billing.SetupPurpose {+ metrics.RecordBillingWebhook("ignored", event.Type)+ w.WriteHeader(http.StatusNoContent)+ return+ }+ if event.CustomerID == "" || event.PaymentMethodID == "" || event.SetupGeneration == "" {+ metrics.RecordBillingWebhook("malformed", event.Type)+ w.WriteHeader(http.StatusNoContent)+ return+ }+ if h.Billing == nil {+ metrics.RecordBillingWebhook("unavailable", event.Type)+ writeErr(w, http.StatusServiceUnavailable, "Stripe billing is not configured")+ return+ }+ applied, err := h.Billing.SetDefaultPaymentMethodForSetupGeneration(r.Context(), event.CustomerID, event.PaymentMethodID, event.SetupGeneration)+ if err != nil {+ metrics.RecordBillingWebhook("update_failed", event.Type)+ writeErr(w, http.StatusBadGateway, "could not configure default payment method")+ return+ }+ if !applied {+ metrics.RecordBillingWebhook("ignored", event.Type)+ w.WriteHeader(http.StatusNoContent)+ return+ }+ metrics.RecordBillingWebhook("configured", event.Type)+ w.WriteHeader(http.StatusNoContent)+}diff --git a/libs/fleet/backend/handlers/billing_webhook_test.go b/libs/fleet/backend/handlers/billing_webhook_test.gonew file mode 100644index 0000000000..900b419728--- /dev/null+++ b/libs/fleet/backend/handlers/billing_webhook_test.go@@ -0,0 +1,195 @@+package handlers++import (+ "crypto/hmac"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "cyclops-cs-backend/billing"+ "cyclops-cs-backend/config"+)++func stripeTestSignature(payload []byte, secret string, timestamp int64) string {+ mac := hmac.New(sha256.New, []byte(secret))+ _, _ = fmt.Fprintf(mac, "%d.", timestamp)+ _, _ = mac.Write(payload)+ return fmt.Sprintf("t=%d,v1=%s", timestamp, hex.EncodeToString(mac.Sum(nil)))+}++func TestBillingWebhookRejectsInvalidSignature(t *testing.T) {+ h := Handlers{+ Stripe: config.StripeConfiguration{WebhookSecret: "whsec_test"},+ WebhookVerifier: billing.NewStripeWebhookVerifier(),+ }+ r := httptest.NewRequest(http.MethodPost, "/api/billing/webhook", strings.NewReader(`{"id":"evt_bad","type":"invoice.paid"}`))+ r.Header.Set("Stripe-Signature", "t=1,v1=invalid")+ w := httptest.NewRecorder()++ h.HandleBillingWebhook(w, r)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String())+ }+}++func TestBillingWebhookAcceptsValidSignatureOverRawBody(t *testing.T) {+ secret := "whsec_test"+ payload := []byte("{\n \"id\": \"evt_valid\",\n \"type\": \"invoice.paid\",\n \"data\": {\"object\": {}}\n}\n")+ h := Handlers{+ Stripe: config.StripeConfiguration{WebhookSecret: secret},+ WebhookVerifier: billing.NewStripeWebhookVerifier(),+ }+ r := httptest.NewRequest(http.MethodPost, "/api/billing/webhook", strings.NewReader(string(payload)))+ r.Header.Set("Stripe-Signature", stripeTestSignature(payload, secret, time.Now().Unix()))+ w := httptest.NewRecorder()++ h.HandleBillingWebhook(w, r)++ if w.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want 204; body = %s", w.Code, w.Body.String())+ }+}++func TestBillingWebhookRejectsOversizedRawBody(t *testing.T) {+ h := Handlers{+ Stripe: config.StripeConfiguration{WebhookSecret: "whsec_test"},+ WebhookVerifier: billing.NewStripeWebhookVerifier(),+ }+ payload := strings.Repeat("x", stripeWebhookBodyLimit+1)+ r := httptest.NewRequest(http.MethodPost, "/api/billing/webhook", strings.NewReader(payload))+ r.Header.Set("Stripe-Signature", "t=1,v1=invalid")+ w := httptest.NewRecorder()++ h.HandleBillingWebhook(w, r)++ if w.Code != http.StatusRequestEntityTooLarge {+ t.Fatalf("status = %d, want 413; body = %s", w.Code, w.Body.String())+ }+}++type fakeWebhookVerifier struct {+ event billing.WebhookEvent+ err error+}++func (f fakeWebhookVerifier) Verify(_ []byte, _, _ string) (billing.WebhookEvent, error) {+ return f.event, f.err+}++func runBillingWebhook(t *testing.T, service *fakeBillingService, event billing.WebhookEvent) *httptest.ResponseRecorder {+ t.Helper()+ h := Handlers{+ Billing: service,+ Stripe: config.StripeConfiguration{WebhookSecret: "whsec_test"},+ WebhookVerifier: fakeWebhookVerifier{event: event},+ }+ r := httptest.NewRequest(http.MethodPost, "/api/billing/webhook", strings.NewReader("{}"))+ w := httptest.NewRecorder()+ h.HandleBillingWebhook(w, r)+ return w+}++func TestBillingWebhookSetsDefaultPaymentMethodForFleetSetupIntent(t *testing.T) {+ service := &fakeBillingService{defaultApplied: true}+ response := runBillingWebhook(t, service, billing.WebhookEvent{+ Type: "setup_intent.succeeded", Purpose: billing.SetupPurpose,+ CustomerID: "cus_owned", PaymentMethodID: "pm_card", SetupGeneration: "current",+ })+ if response.Code != http.StatusNoContent || service.defaultCalls != 1 || service.defaultCustomerID != "cus_owned" || service.defaultPaymentMethodID != "pm_card" {+ t.Fatalf("default update = calls:%d customer:%q payment:%q", service.defaultCalls, service.defaultCustomerID, service.defaultPaymentMethodID)+ }+}++func TestBillingWebhookIgnoresUnrelatedSetupIntent(t *testing.T) {+ service := &fakeBillingService{}+ response := runBillingWebhook(t, service, billing.WebhookEvent{+ Type: "setup_intent.succeeded", Purpose: "other_product",+ CustomerID: "cus_owned", PaymentMethodID: "pm_card",+ })+ if response.Code != http.StatusNoContent || service.defaultCalls != 0 {+ t.Fatalf("status/calls = %d/%d, want 204/0", response.Code, service.defaultCalls)+ }+}++func TestBillingWebhookIgnoresMalformedSucceededEvent(t *testing.T) {+ service := &fakeBillingService{}+ response := runBillingWebhook(t, service, billing.WebhookEvent{+ Type: "setup_intent.succeeded", Purpose: billing.SetupPurpose,+ })+ if response.Code != http.StatusNoContent || service.defaultCalls != 0 {+ t.Fatalf("status/calls = %d/%d, want 204/0", response.Code, service.defaultCalls)+ }+}++func TestBillingWebhookReturns502WhenDefaultUpdateFails(t *testing.T) {+ service := &fakeBillingService{defaultErr: errors.New("stripe unavailable")}+ response := runBillingWebhook(t, service, billing.WebhookEvent{+ Type: "setup_intent.succeeded", Purpose: billing.SetupPurpose,+ CustomerID: "cus_owned", PaymentMethodID: "pm_card", SetupGeneration: "current",+ })+ if response.Code != http.StatusBadGateway || service.defaultCalls != 1 {+ t.Fatalf("status/calls = %d/%d, want 502/1", response.Code, service.defaultCalls)+ }+}++func TestBillingWebhookDuplicateDeliveryIsSafe(t *testing.T) {+ service := &fakeBillingService{defaultApplied: true}+ event := billing.WebhookEvent{+ Type: "setup_intent.succeeded", Purpose: billing.SetupPurpose,+ CustomerID: "cus_owned", PaymentMethodID: "pm_card", SetupGeneration: "current",+ }+ first := runBillingWebhook(t, service, event)+ second := runBillingWebhook(t, service, event)+ if first.Code != http.StatusNoContent || second.Code != http.StatusNoContent || service.defaultCalls != 2 {+ t.Fatalf("statuses/calls = %d/%d/%d, want 204/204/2", first.Code, second.Code, service.defaultCalls)+ }+}++func TestBillingWebhookIgnoresCorrectlySignedTruncatedEnvelope(t *testing.T) {+ secret := "whsec_test"+ payload := []byte(`{"id":"evt_truncated"`)+ service := &fakeBillingService{}+ h := Handlers{+ Billing: service,+ Stripe: config.StripeConfiguration{WebhookSecret: secret},+ WebhookVerifier: billing.NewStripeWebhookVerifier(),+ }+ r := httptest.NewRequest(http.MethodPost, "/api/billing/webhook", strings.NewReader(string(payload)))+ r.Header.Set("Stripe-Signature", stripeTestSignature(payload, secret, time.Now().Unix()))+ w := httptest.NewRecorder()++ h.HandleBillingWebhook(w, r)++ if w.Code != http.StatusNoContent || service.defaultCalls != 0 {+ t.Fatalf("status/calls = %d/%d, want 204/0", w.Code, service.defaultCalls)+ }+}++func TestBillingWebhookIgnoresStaleSetupGeneration(t *testing.T) {+ service := &fakeBillingService{defaultApplied: false}+ response := runBillingWebhook(t, service, billing.WebhookEvent{+ Type: "setup_intent.succeeded", Purpose: billing.SetupPurpose,+ CustomerID: "cus_owned", PaymentMethodID: "pm_older", SetupGeneration: "older",+ })+ if response.Code != http.StatusNoContent || service.defaultCalls != 1 || service.defaultGeneration != "older" {+ t.Fatalf("status/calls/generation = %d/%d/%q, want 204/1/older", response.Code, service.defaultCalls, service.defaultGeneration)+ }+}++func TestBillingWebhookIgnoresMissingSetupGeneration(t *testing.T) {+ service := &fakeBillingService{defaultApplied: true}+ response := runBillingWebhook(t, service, billing.WebhookEvent{+ Type: "setup_intent.succeeded", Purpose: billing.SetupPurpose,+ CustomerID: "cus_owned", PaymentMethodID: "pm_card",+ })+ if response.Code != http.StatusNoContent || service.defaultCalls != 0 {+ t.Fatalf("status/calls = %d/%d, want 204/0", response.Code, service.defaultCalls)+ }+}diff --git a/libs/fleet/backend/handlers/config.go b/libs/fleet/backend/handlers/config.goindex e4377d164a..a84212672c 100644--- a/libs/fleet/backend/handlers/config.go+++ b/libs/fleet/backend/handlers/config.go@@ -14,7 +14,8 @@ type ConfigResponse struct {// Non-admins get the customer view: infra-only nav (Nodes, Operator events)// is hidden in the SPA and the corresponding kubectl-proxy paths are denied// server-side by authz.rego.- Admin bool `json:"admin"`+ Admin bool `json:"admin"`+ Billing bool `json:"billing"`}// GetConfig returns per-user feature flags evaluated by OPA.@@ -39,5 +40,11 @@ func (h Handlers) GetConfig(w http.ResponseWriter, r *http.Request) {isAdmin = false}- writeJSON(w, http.StatusOK, ConfigResponse{Admin: isAdmin})+ billingEnabled, err := auth.EvalBillingEnabled(ctx, user)+ if err != nil {+ slog.WarnContext(ctx, "billing flag eval failed; defaulting off", "err", err)+ billingEnabled = false+ }++ writeJSON(w, http.StatusOK, ConfigResponse{Admin: isAdmin, Billing: billingEnabled})}diff --git a/libs/fleet/backend/handlers/handlers.go b/libs/fleet/backend/handlers/handlers.goindex a775596f09..8411b965ce 100644--- a/libs/fleet/backend/handlers/handlers.go+++ b/libs/fleet/backend/handlers/handlers.go@@ -18,11 +18,13 @@ import ()type Handlers struct {- Admin *keycloak.Admin- GatewayCfg config.GatewayConfiguration- AuthCfg config.AuthConfiguration- KC config.KeycloakConfiguration-+ Admin *keycloak.Admin+ GatewayCfg config.GatewayConfiguration+ AuthCfg config.AuthConfiguration+ KC config.KeycloakConfiguration+ Stripe config.StripeConfiguration+ Billing BillingService+ WebhookVerifier WebhookVerifier// WorkloadAdmin manages per-tenant clients in the workloads realm so// OSGym pool VMs can obtain a tenant-scoped OIDC token. nil disables@@ -40,6 +42,7 @@ func New(admin *keycloak.Admin, cfg *config.Configuration) Handlers {GatewayCfg: cfg.Gateway,AuthCfg: cfg.Auth,KC: cfg.Keycloak,+ Stripe: cfg.Stripe,}}diff --git a/libs/fleet/backend/main.go b/libs/fleet/backend/main.goindex 51a75f3e42..e1a623784a 100644--- a/libs/fleet/backend/main.go+++ b/libs/fleet/backend/main.go@@ -43,6 +43,7 @@ import ("github.com/spf13/cobra""cyclops-cs-backend/auth"+ "cyclops-cs-backend/billing""cyclops-cs-backend/config"_ "cyclops-cs-backend/docs" // generated by `swag init`"cyclops-cs-backend/handlers"@@ -97,6 +98,17 @@ func setupRouter(c handlers.Handlers) http.Handler {r.Handle("GET /api/config",withMiddlewares("/api/config", nil, c.GetConfig))+ // Stripe-hosted billing. Browser routes require the normal SPA JWT; the+ // webhook uses Stripe signature verification as its authentication boundary.+ r.Handle("GET /api/billing/summary",+ withMiddlewares("/api/billing/summary", nil, c.GetBillingSummary))+ r.Handle("POST /api/billing/setup-session",+ withMiddlewares("/api/billing/setup-session", nil, c.CreateBillingSetupSession))+ r.Handle("POST /api/billing/portal-session",+ withMiddlewares("/api/billing/portal-session", nil, c.CreateBillingPortalSession))+ r.Handle("POST /api/billing/webhook",+ onlyLog("/api/billing/webhook", c.HandleBillingWebhook))+// Swagger UI + JSON. The SPA points its codegen at /api/swagger/doc.json// (see cyclops-cs/scripts/codegen.sh). We don't put the doc behind auth// — the schema is public and the actual endpoints are still gated.@@ -128,7 +140,6 @@ func setupRouter(c handlers.Handlers) http.Handler {r.Handle("DELETE /api/user-keys/{id}",withMiddlewares("/api/user-keys/{id}", []string{"id"}, c.DeleteUserKey))-r.Handle("/api/gateway/{name}",withMiddlewares("/api/gateway/{name}", []string{"name"}, c.Gateway))r.Handle("/api/gateway/{name}/{path...}",@@ -283,6 +294,13 @@ func run() error {}h := handlers.New(admin, cfg)+ if cfg.Stripe.SecretKey != "" {+ h.Billing = billing.NewService(billing.NewStripeGateway(cfg.Stripe.SecretKey))+ slog.Info("stripe billing: hosted flows enabled")+ } else {+ slog.Info("stripe billing: disabled (STRIPE_SECRET_KEY unset)")+ }+ h.WebhookVerifier = billing.NewStripeWebhookVerifier()h.WorkloadAdmin = workloadAdminh.WorkloadAudience = cfg.Keycloak.WorkloadAudienceh.WorkloadTokenURL = cfg.Keycloak.WorkloadTokenURLdiff --git a/libs/fleet/backend/main_test.go b/libs/fleet/backend/main_test.goindex 7f5f44a94c..a3d037692b 100644--- a/libs/fleet/backend/main_test.go+++ b/libs/fleet/backend/main_test.go@@ -1,20 +1,27 @@package mainimport (+ "bytes""context"+ "crypto/hmac""crypto/rand""crypto/rsa"+ "crypto/sha256""encoding/base64"+ "encoding/hex""encoding/json"+ "fmt""io""net/http""net/http/httptest""os"+ "slices""strings""testing""time""cyclops-cs-backend/auth"+ "cyclops-cs-backend/billing""cyclops-cs-backend/config""cyclops-cs-backend/handlers"@@ -26,6 +33,26 @@ import (// returns HTTP 410 Gone with the canonical deprecation message. Each route// is exercised individually so a regression on any single path is immediately// visible rather than hidden behind a representative sample.+func TestSwaggerUsesBillingSetupSessionRoute(t *testing.T) {+ data, err := os.ReadFile("docs/swagger.json")+ if err != nil {+ t.Fatal(err)+ }++ var spec struct {+ Paths map[string]json.RawMessage `json:"paths"`+ }+ if err := json.Unmarshal(data, &spec); err != nil {+ t.Fatalf("unmarshal swagger.json: %v", err)+ }+ if _, ok := spec.Paths["/api/billing/setup-session"]; !ok {+ t.Fatal("swagger.json missing /api/billing/setup-session")+ }+ if _, ok := spec.Paths["/api/billing/checkout-session"]; ok {+ t.Fatal("swagger.json still contains /api/billing/checkout-session")+ }+}+func TestDeprecatedRoutes(t *testing.T) {router := setupRouter(handlers.Handlers{})@@ -182,13 +209,17 @@ func TestMain(m *testing.M) {}func authorizedRequest(t *testing.T, method, path string, body io.Reader) *http.Request {+ return requestWithAZP(t, method, path, body, "cyclops-cs-spa")+}++func requestWithAZP(t *testing.T, method, path string, body io.Reader, azp string) *http.Request {t.Helper()req := httptest.NewRequest(method, path, body)token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{"iss": testIssuer,"sub": "user-123",- "azp": "cyclops-cs-spa",+ "azp": azp,"exp": time.Now().Add(time.Hour).Unix(),"iat": time.Now().Add(-time.Minute).Unix(),})@@ -212,3 +243,118 @@ func bigEndianBytes(v int) []byte {}return out}++type routerBillingService struct{}++func (routerBillingService) Summary(context.Context, string) (billing.Summary, error) {+ return billing.Summary{}, nil+}++func (routerBillingService) CreateSetupSession(context.Context, string, billing.SetupOptions) (string, error) {+ return "https://checkout.stripe.test/session", nil+}++func (routerBillingService) CreatePortalSession(context.Context, string, string) (string, error) {+ return "https://billing.stripe.test/session", nil+}++func (routerBillingService) SetDefaultPaymentMethodForSetupGeneration(context.Context, string, string, string) (bool, error) {+ return true, nil+}++func TestBillingRouterAuthorizationBoundaries(t *testing.T) {+ t.Setenv("CYCLOPS_CS_BILLING_ENABLED", "true")+ const webhookSecret = "whsec_router_test"+ h := handlers.Handlers{+ Billing: routerBillingService{},+ WebhookVerifier: billing.NewStripeWebhookVerifier(),+ Stripe: config.StripeConfiguration{+ SecretKey: "sk_test",+ WebhookSecret: webhookSecret,+ },+ }+ router := setupRouter(h)++ unauthorized := httptest.NewRecorder()+ router.ServeHTTP(unauthorized, httptest.NewRequest(http.MethodGet, "/api/billing/summary", nil))+ if unauthorized.Code != http.StatusUnauthorized {+ t.Fatalf("unauthenticated summary status = %d, want 401; body = %s", unauthorized.Code, unauthorized.Body.String())+ }++ authorized := httptest.NewRecorder()+ router.ServeHTTP(authorized, authorizedRequest(t, http.MethodGet, "/api/billing/summary", nil))+ if authorized.Code != http.StatusOK {+ t.Fatalf("authenticated summary status = %d, want 200; body = %s", authorized.Code, authorized.Body.String())+ }++ for _, tc := range []struct {+ name string+ path string+ }{+ {name: "setup", path: "/api/billing/setup-session"},+ {name: "portal", path: "/api/billing/portal-session"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ unauthenticated := httptest.NewRecorder()+ router.ServeHTTP(unauthenticated, httptest.NewRequest(http.MethodPost, tc.path, nil))+ if unauthenticated.Code != http.StatusUnauthorized {+ t.Fatalf("unauthenticated status = %d, want 401; body = %s", unauthenticated.Code, unauthenticated.Body.String())+ }++ nonSPA := httptest.NewRecorder()+ router.ServeHTTP(nonSPA, requestWithAZP(t, http.MethodPost, tc.path, nil, "some-other-client"))+ if nonSPA.Code != http.StatusForbidden {+ t.Fatalf("non-SPA status = %d, want 403; body = %s", nonSPA.Code, nonSPA.Body.String())+ }+ })+ }++ removedCheckout := httptest.NewRecorder()+ router.ServeHTTP(removedCheckout, authorizedRequest(t, http.MethodPost, "/api/billing/checkout-session", nil))+ if removedCheckout.Code != http.StatusNotFound {+ t.Fatalf("removed checkout-session status = %d, want 404; body = %s", removedCheckout.Code, removedCheckout.Body.String())+ }++ payload := []byte(`{"id":"evt_router","type":"setup_intent.succeeded"}`)+ timestamp := time.Now().Unix()+ mac := hmac.New(sha256.New, []byte(webhookSecret))+ _, _ = fmt.Fprintf(mac, "%d.", timestamp)+ _, _ = mac.Write(payload)+ signature := fmt.Sprintf("t=%d,v1=%s", timestamp, hex.EncodeToString(mac.Sum(nil)))+ webhookRequest := httptest.NewRequest(http.MethodPost, "/api/billing/webhook", bytes.NewReader(payload))+ webhookRequest.Header.Set("Stripe-Signature", signature)+ webhookResponse := httptest.NewRecorder()+ router.ServeHTTP(webhookResponse, webhookRequest)+ if webhookResponse.Code != http.StatusNoContent {+ t.Fatalf("signed webhook status = %d, want 204; body = %s", webhookResponse.Code, webhookResponse.Body.String())+ }+}++func TestBillingSummaryGeneratedContract(t *testing.T) {+ data, err := os.ReadFile("docs/swagger.json")+ if err != nil {+ t.Fatalf("read swagger.json: %v", err)+ }+ var document struct {+ Definitions map[string]struct {+ Required []string `json:"required"`+ Properties map[string]json.RawMessage `json:"properties"`+ } `json:"definitions"`+ }+ if err := json.Unmarshal(data, &document); err != nil {+ 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") {+ t.Fatalf("billing summary required fields = %#v", summary.Required)+ }+ var card struct {+ Nullable bool `json:"x-nullable"`+ }+ if err := json.Unmarshal(summary.Properties["card"], &card); err != nil {+ t.Fatalf("unmarshal card property: %v", err)+ }+ if !card.Nullable {+ t.Fatal("billing summary card must be explicitly nullable")+ }+}diff --git a/libs/fleet/backend/metrics/metrics.go b/libs/fleet/backend/metrics/metrics.goindex 32392f9581..c06f3f4ea1 100644--- a/libs/fleet/backend/metrics/metrics.go+++ b/libs/fleet/backend/metrics/metrics.go@@ -63,6 +63,11 @@ var (Help: "Total requests proxied to upstream services (gateway/orch/k8s).",}, []string{"target", "status_code"})+ BillingWebhookEventsTotal = promauto.NewCounterVec(prometheus.CounterOpts{+ Name: "cyclops_cs_billing_webhook_events_total",+ Help: "Total Stripe billing webhook requests by processing result and event type.",+ }, []string{"result", "event_type"})+UpstreamProxyDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{Name: "cyclops_cs_upstream_proxy_duration_seconds",Help: "Latency of requests proxied to upstream services.",@@ -209,3 +214,7 @@ func StartMetricsServer(addr string) error {srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}return srv.ListenAndServe()}++func RecordBillingWebhook(result, eventType string) {+ BillingWebhookEventsTotal.WithLabelValues(result, eventType).Inc()+}diff --git a/libs/fleet/docs/stripe-billing-mvp-plan.md b/libs/fleet/docs/stripe-billing-mvp-plan.mdnew file mode 100644index 0000000000..596d115987--- /dev/null+++ b/libs/fleet/docs/stripe-billing-mvp-plan.md@@ -0,0 +1,23 @@+# Stripe fleet card setup MVP plan++## Scope++- Stripe-hosted card setup in Checkout `setup` mode.+- Fleet-owned Customer metadata derived from the authenticated Cyclops subject.+- Signed SetupIntent webhook default-card configuration.+- Sanitized saved-card status for the authenticated fleet owner.+- Billing Portal card replacement and removal.++## API shape++- `GET /api/billing/summary` returns the authenticated fleet owner's sanitized saved-card status.+- `POST /api/billing/setup-session` accepts an empty request body and returns a Stripe-hosted card setup URL.+- `POST /api/billing/portal-session` accepts an empty request body and returns the authenticated fleet owner's Billing Portal URL.+- `POST /api/billing/webhook` verifies the bounded raw Stripe body and configures the fleet's default card from signed SetupIntent events.++## Security properties++- The browser never receives a Stripe secret key or submits card details to Cyclops.+- The backend derives fleet ownership from the authenticated request context and controlled Customer metadata.+- Setup and portal sessions use only the Customer owned by the authenticated subject.+- Webhook verification uses the unparsed raw body and rejects missing, invalid, or oversized signatures.diff --git a/libs/fleet/e2e/billing.spec.ts b/libs/fleet/e2e/billing.spec.tsnew file mode 100644index 0000000000..e65db0db71--- /dev/null+++ b/libs/fleet/e2e/billing.spec.ts@@ -0,0 +1,129 @@+import { expect, test, type Page } from "@playwright/test";+import { mockAuth } from "./fixtures/mock-api";++async function setBillingFlag(page: Page, billing: boolean) {+ await page.unroute("**/api/config");+ await page.route("**/api/config", (route) =>+ route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({ admin: false, billing }),+ }),+ );+}++test.beforeEach(async ({ page }) => {+ await mockAuth(page);+});++test("billing has no navigation link even when the flag is on", async ({+ page,+}) => {+ await setBillingFlag(page, true);+ await page.route("**/api/billing/summary", (route) =>+ route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({ payment_method_present: false, card: null }),+ }),+ );+ await page.goto("/pools");+ await expect(page.getByRole("link", { name: "User API keys" })).toBeVisible();+ await expect(page.getByRole("link", { name: "Billing" })).toHaveCount(0);+});++test("the old /billing route redirects to settings", async ({ page }) => {+ await setBillingFlag(page, true);+ await page.route("**/api/billing/summary", (route) =>+ route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({ payment_method_present: false, card: null }),+ }),+ );+ await page.goto("/billing");+ await expect(page.getByRole("heading", { name: "Account" })).toBeVisible();+ await expect(page).toHaveURL(/\/settings$/);+});++test("settings hides billing when the flag is off", async ({ page }) => {+ await setBillingFlag(page, false);+ await page.goto("/settings");+ await expect(page.getByRole("heading", { name: "Account" })).toBeVisible();+ await expect(+ page.getByRole("heading", { name: "Payment method" }),+ ).toHaveCount(0);+ await expect(+ page.getByRole("heading", { name: "Recent invoices" }),+ ).toHaveCount(0);+});++test("settings explains automatic charges before saving a card", async ({+ page,+}) => {+ await setBillingFlag(page, true);+ await page.route("**/api/billing/summary", (route) =>+ route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({ payment_method_present: false, card: null }),+ }),+ );+ await page.route("**/api/billing/setup-session", async (route) => {+ expect(route.request().method()).toBe("POST");+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({ url: "/settings?setup=complete" }),+ });+ });+ await page.goto("/settings");+ await expect(+ page.getByText(+ "By saving this card, you authorize Fleet to charge it automatically for future usage according to the applicable pricing and terms.",+ ),+ ).toBeVisible();+ const redirect = page.waitForURL(/\/settings\?setup=complete$/);+ await page.getByRole("button", { name: "Add payment method" }).click();+ await redirect;+});++test("settings displays the saved default card", async ({ page }) => {+ await setBillingFlag(page, true);+ 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 },+ }),+ }),+ );+ await page.route("**/api/billing/portal-session", async (route) => {+ expect(route.request().method()).toBe("POST");+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({ url: "/settings?portal=complete" }),+ });+ });+ await page.goto("/settings");+ await expect(page.getByText("Visa ending in 4242")).toBeVisible();+ await expect(page.getByText("Expires 12/2030")).toBeVisible();+ const portalRedirect = page.waitForURL(/\/settings\?portal=complete$/);+ await page.getByRole("button", { name: "Manage payment method" }).click();+ await portalRedirect;+ await expect(+ page.getByRole("heading", { name: "Recent invoices" }),+ ).toHaveCount(0);+});++test("settings shows a billing load error", async ({ page }) => {+ await setBillingFlag(page, true);+ await page.route("**/api/billing/summary", (route) =>+ route.fulfill({+ status: 502,+ contentType: "application/json",+ body: '{"error":"unavailable"}',+ }),+ );+ await page.goto("/settings");+ await expect(+ page.getByText("Billing is temporarily unavailable"),+ ).toBeVisible();+ await expect(page.getByRole("heading", { name: "Account" })).toBeVisible();+});diff --git a/libs/fleet/js-sdk/package.json b/libs/fleet/js-sdk/package.jsonindex a3e6032649..83728f1f17 100644--- a/libs/fleet/js-sdk/package.json+++ b/libs/fleet/js-sdk/package.json@@ -28,7 +28,7 @@"generate:check": "node ./scripts/check-generated-client.mjs","build": "npm run clean && tsc -p tsconfig.json","typecheck": "tsc -p tsconfig.json --noEmit",- "test": "npm run build && node --test test/*.test.js",+ "test": "npm run build && node --test test/*.test.js test/*.test.mjs","prepublishOnly": "npm run generate:check && npm run typecheck && npm test && npm run build"},"keywords": [diff --git a/libs/fleet/js-sdk/scripts/patch-generated-client.mjs b/libs/fleet/js-sdk/scripts/patch-generated-client.mjsindex afc5d92bca..c038c16f3b 100644--- a/libs/fleet/js-sdk/scripts/patch-generated-client.mjs+++ b/libs/fleet/js-sdk/scripts/patch-generated-client.mjs@@ -1,6 +1,6 @@import { readFile, writeFile } from "node:fs/promises"-const generatedClientPath = new URL("../src/generated/cyclops-cs-backend.ts", import.meta.url)+const generatedClientPath = process.argv[2] ?? new URL("../src/generated/cyclops-cs-backend.ts", import.meta.url)const original = await readFile(generatedClientPath, "utf8")const oldImplementation = ` private customFetch = (...fetchParams: Parameters<typeof fetch>) =>fetch(...fetchParams);`@@ -18,4 +18,15 @@ if (!original.includes(oldImplementation)) {throw new Error("Generated HttpClient fetch implementation did not match the expected template")}-await writeFile(generatedClientPath, original.replace(oldImplementation, newImplementation))+const oldBillingSummaryCard = " card?: BillingCardSummary | null;";+const newBillingSummaryCard = " card: BillingCardSummary | null;";++if (!original.includes(oldBillingSummaryCard)) {+ throw new Error("Generated BillingSummary card declaration did not match the expected template");+}++const patched = original+ .replace(oldImplementation, newImplementation)+ .replace(oldBillingSummaryCard, newBillingSummaryCard);++await writeFile(generatedClientPath, patched)diff --git a/libs/fleet/js-sdk/src/generated/cyclops-cs-backend.ts b/libs/fleet/js-sdk/src/generated/cyclops-cs-backend.tsindex 2d77f4b465..310eb7a731 100644--- a/libs/fleet/js-sdk/src/generated/cyclops-cs-backend.ts+++ b/libs/fleet/js-sdk/src/generated/cyclops-cs-backend.ts@@ -10,6 +10,22 @@* ---------------------------------------------------------------*/+export interface BillingCardSummary {+ brand?: string;+ exp_month?: number;+ exp_year?: number;+ last4?: string;+}++export interface BillingSummary {+ card: BillingCardSummary | null;+ payment_method_present: boolean;+}++export interface HandlersBillingSessionResponse {+ url?: string;+}+export interface HandlersConfigResponse {/*** Admin is true when the caller is in input.flags.admin_subs (OPA-evaluated).@@ -18,6 +34,7 @@ export interface HandlersConfigResponse {* server-side by authz.rego.*/admin?: boolean;+ billing?: boolean;}export interface HandlersCreateKeyRequest {@@ -105,6 +122,22 @@ export type BatchResultsListError = Record<string, string>;export type BatchStatusListError = Record<string, string>;+export type BillingPortalSessionCreateData = HandlersBillingSessionResponse;++export type BillingPortalSessionCreateError = Record<string, string>;++export type BillingSetupSessionCreateData = HandlersBillingSessionResponse;++export type BillingSetupSessionCreateError = Record<string, string>;++export type BillingSummaryListData = BillingSummary;++export type BillingSummaryListError = Record<string, string>;++export type BillingWebhookCreateData = any;++export type BillingWebhookCreateError = Record<string, string>;+export type ConfigListData = HandlersConfigResponse;export type ConfigListError = HandlersErrorResponse;@@ -561,6 +594,83 @@ export class Api<...params,}),};+ billing = {+ /**+ * @description Creates a Stripe-hosted Billing Portal Session for the customer owned by the authenticated Cyclops subject.+ *+ * @tags billing+ * @name BillingPortalSessionCreate+ * @summary Create Stripe Billing Portal Session+ * @request POST:/api/billing/portal-session+ * @secure+ */+ billingPortalSessionCreate: (params: RequestParams = {}) =>+ this.request<+ BillingPortalSessionCreateData,+ BillingPortalSessionCreateError+ >({+ path: `/api/billing/portal-session`,+ method: "POST",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * @description Creates a Stripe-hosted Checkout Session in setup mode for reusable off-session card collection.+ *+ * @tags billing+ * @name BillingSetupSessionCreate+ * @summary Create Stripe card setup Session+ * @request POST:/api/billing/setup-session+ * @secure+ */+ billingSetupSessionCreate: (params: RequestParams = {}) =>+ this.request<+ BillingSetupSessionCreateData,+ BillingSetupSessionCreateError+ >({+ path: `/api/billing/setup-session`,+ method: "POST",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * @description Returns a sanitized Stripe-backed billing summary for the authenticated Cyclops subject.+ *+ * @tags billing+ * @name BillingSummaryList+ * @summary Billing summary+ * @request GET:/api/billing/summary+ * @secure+ */+ billingSummaryList: (params: RequestParams = {}) =>+ this.request<BillingSummaryListData, BillingSummaryListError>({+ path: `/api/billing/summary`,+ method: "GET",+ secure: true,+ format: "json",+ ...params,+ }),++ /**+ * @description Verifies a Stripe-signed raw webhook body and configures the default payment method for completed fleet setup intents.+ *+ * @tags billing+ * @name BillingWebhookCreate+ * @summary Receive Stripe webhook+ * @request POST:/api/billing/webhook+ */+ billingWebhookCreate: (params: RequestParams = {}) =>+ this.request<BillingWebhookCreateData, BillingWebhookCreateError>({+ path: `/api/billing/webhook`,+ method: "POST",+ type: ContentType.Json,+ ...params,+ }),+ };config = {/*** @description Returns OPA-evaluated feature flags for the authenticated SPA user. `admin` is true when the caller's JWT sub appears in input.flags.admin_subs.diff --git a/libs/fleet/js-sdk/test/patch-generated-client.test.mjs b/libs/fleet/js-sdk/test/patch-generated-client.test.mjsnew file mode 100644index 0000000000..dedcfdb7d9--- /dev/null+++ b/libs/fleet/js-sdk/test/patch-generated-client.test.mjs@@ -0,0 +1,22 @@+import assert from "node:assert/strict";+import { execFile } from "node:child_process";+import { mkdtemp, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { promisify } from "node:util";+import test from "node:test";++const execFileAsync = promisify(execFile);++test("patch guard rejects a malformed BillingSummary declaration", async () => {+ const directory = await mkdtemp(join(tmpdir(), "cyclops-sdk-patch-"));+ const clientPath = join(directory, "cyclops-cs-backend.ts");+ await writeFile(clientPath, ` private customFetch = (...fetchParams: Parameters<typeof fetch>) =>\n fetch(...fetchParams);\n\nexport interface BillingSummary {\n card: BillingCardSummary | null;\n}\n`);++ await assert.rejects(+ execFileAsync(process.execPath, ["scripts/patch-generated-client.mjs", clientPath], {+ cwd: new URL("..", import.meta.url),+ }),+ /BillingSummary card declaration did not match/,+ );+});diff --git a/libs/fleet/nginx.conf b/libs/fleet/nginx.confindex f80b2225ed..318fe0a8d8 100644--- a/libs/fleet/nginx.conf+++ b/libs/fleet/nginx.conf@@ -137,7 +137,18 @@ server {}# All other /api/* backend routes (no oauth2-proxy).- location ~ ^/api/(keys|user-keys|gateway|k8s|orch|swagger|batch|label|namespaces|config)(/|$) {+ # Stripe authenticates this callback with Stripe-Signature. It must bypass+ # browser OAuth while still terminating at the backend verifier.+ location = /api/billing/webhook {+ proxy_pass ${CYCLOPS_CS_BACKEND};+ proxy_http_version 1.1;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ }++ location ~ ^/api/(keys|user-keys|gateway|k8s|orch|swagger|batch|label|namespaces|config|billing)(/|$) {proxy_pass ${CYCLOPS_CS_BACKEND};proxy_http_version 1.1;proxy_set_header Host $host;diff --git a/libs/fleet/src/App.tsx b/libs/fleet/src/App.tsxindex 67f4da3c8b..0ca1904df5 100644--- a/libs/fleet/src/App.tsx+++ b/libs/fleet/src/App.tsx@@ -21,6 +21,7 @@ import { PoolDetail } from "./pages/PoolDetail"import { PoolNew } from "./pages/PoolNew"import { UserApiKeys } from "./pages/UserApiKeys"import { Settings } from "./pages/Settings"+import { FeatureFlagProvider } from "./components/FeatureFlagContext"import { FlashContext, type FlashMsg } from "./components/FlashContext"import { logout, userInfo } from "./auth/keycloak"@@ -180,31 +181,34 @@ function Shell() {export function App() {return (<BrowserRouter>- <Routes>- <Route element={<Shell />}>- <Route index element={<Navigate to="/pools" replace />} />- <Route path="/pools" element={<PoolsList />} />- <Route path="/pools/new" element={<PoolNew />} />- <Route- path="/pools/templates"- element={<Navigate to="/pools" replace />}- />- <Route path="/pools/:namespace/:name" element={<PoolDetail />} />- <Route path="/user-keys" element={<UserApiKeys />} />- <Route path="/settings" element={<Settings />} />- <Route- path="/pools/:namespace/:poolName/claims/:claimName"- element={<ClaimDetail />}- />- <Route path="/modules" element={<Navigate to="/pools" replace />} />- <Route- path="/modules/new"- element={<Navigate to="/pools/new" replace />}- />- <Route path="/modules/:name" element={<RedirectModule />} />- <Route path="/pools/:name" element={<Navigate to="/pools" replace />} />- </Route>- </Routes>+ <FeatureFlagProvider>+ <Routes>+ <Route element={<Shell />}>+ <Route index element={<Navigate to="/pools" replace />} />+ <Route path="/pools" element={<PoolsList />} />+ <Route path="/pools/new" element={<PoolNew />} />+ <Route+ path="/pools/templates"+ element={<Navigate to="/pools" replace />}+ />+ <Route path="/pools/:namespace/:name" element={<PoolDetail />} />+ <Route path="/user-keys" element={<UserApiKeys />} />+ <Route path="/settings" element={<Settings />} />+ <Route path="/billing" element={<Navigate to="/settings" replace />} />+ <Route+ path="/pools/:namespace/:poolName/claims/:claimName"+ element={<ClaimDetail />}+ />+ <Route path="/modules" element={<Navigate to="/pools" replace />} />+ <Route+ path="/modules/new"+ element={<Navigate to="/pools/new" replace />}+ />+ <Route path="/modules/:name" element={<RedirectModule />} />+ <Route path="/pools/:name" element={<Navigate to="/pools" replace />} />+ </Route>+ </Routes>+ </FeatureFlagProvider></BrowserRouter>)}diff --git a/libs/fleet/src/components/FeatureFlagContext.tsx b/libs/fleet/src/components/FeatureFlagContext.tsxnew file mode 100644index 0000000000..0ae95a159c--- /dev/null+++ b/libs/fleet/src/components/FeatureFlagContext.tsx@@ -0,0 +1,47 @@+import { createContext, useContext, useEffect, useState, type ReactNode } from "react"+import { fetchFeatureFlags, type FeatureFlags } from "../sdk/featureFlags"++const DEFAULT_FLAGS: FeatureFlags = { admin: false, billing: false }++interface FeatureFlagContextValue extends FeatureFlags {+ resolved: boolean+}++const FeatureFlagContext = createContext<FeatureFlagContextValue>({+ ...DEFAULT_FLAGS,+ resolved: false,+})++/**+ * Fetches /api/config once at app startup and provides the result via+ * context. All children can call useFeatureFlags() to read flags.+ */+export function FeatureFlagProvider({ children }: { children: ReactNode }) {+ const [value, setValue] = useState<FeatureFlagContextValue>({+ ...DEFAULT_FLAGS,+ resolved: false,+ })++ useEffect(() => {+ fetchFeatureFlags()+ .then(flags => setValue({ ...flags, resolved: true }))+ .catch(() => setValue({ ...DEFAULT_FLAGS, resolved: true }))+ }, [])++ return (+ <FeatureFlagContext.Provider value={value}>+ {children}+ </FeatureFlagContext.Provider>+ )+}++/**+ * Returns the current user's feature flags.+ *+ * @example+ * const { admin } = useFeatureFlags()+ * if (admin) { ... }+ */+export function useFeatureFlags(): FeatureFlagContextValue {+ return useContext(FeatureFlagContext)+}diff --git a/libs/fleet/src/pages/Billing.tsx b/libs/fleet/src/pages/Billing.tsxnew file mode 100644index 0000000000..9653f4af89--- /dev/null+++ b/libs/fleet/src/pages/Billing.tsx@@ -0,0 +1,103 @@+// Billing section rendered inside Settings. Card collection and management+// happen on Stripe-hosted pages; Cyclops never handles card details.++import Alert from "@cloudscape-design/components/alert";+import Box from "@cloudscape-design/components/box";+import Button from "@cloudscape-design/components/button";+import Container from "@cloudscape-design/components/container";+import Header from "@cloudscape-design/components/header";+import SpaceBetween from "@cloudscape-design/components/space-between";+import Spinner from "@cloudscape-design/components/spinner";+import { useEffect, useState } from "react";+import { billingApi, type BillingSummary } from "../sdk/billing";++function cardBrand(brand: string) {+ return brand ? brand[0].toUpperCase() + brand.slice(1) : "Card";+}++export function BillingSettings() {+ const [summary, setSummary] = useState<BillingSummary | null>(null);+ const [error, setError] = useState(false);+ const [redirecting, setRedirecting] = useState(false);++ useEffect(() => {+ billingApi+ .summary()+ .then(setSummary)+ .catch(() => setError(true));+ }, []);++ const redirect = async (kind: "setup" | "portal") => {+ setRedirecting(true);+ setError(false);+ try {+ const { url } =+ kind === "setup" ? await billingApi.setup() : await billingApi.portal();+ window.location.assign(url);+ } catch {+ setError(true);+ setRedirecting(false);+ }+ };++ if (error) {+ return (+ <Alert type="error" header="Billing is temporarily unavailable">+ Try again later. No billing changes were made.+ </Alert>+ );+ }++ return (+ <SpaceBetween size="l">+ <Container+ header={+ <Header+ variant="h2"+ description="Save one card securely with Stripe for future automatic usage charges."+ >+ Payment method+ </Header>+ }+ footer={+ summary && (+ <Button+ variant="primary"+ loading={redirecting}+ onClick={() =>+ redirect(summary.payment_method_present ? "portal" : "setup")+ }+ >+ {summary.payment_method_present+ ? "Manage payment method"+ : "Add payment method"}+ </Button>+ )+ }+ >+ {!summary ? (+ <Spinner />+ ) : summary.payment_method_present && summary.card ? (+ <SpaceBetween size="xs">+ <Box variant="h3">+ {cardBrand(summary.card.brand)} ending in {summary.card.last4}+ </Box>+ <Box color="text-body-secondary">+ Expires {String(summary.card.exp_month).padStart(2, "0")}/+ {summary.card.exp_year}+ </Box>+ </SpaceBetween>+ ) : (+ <SpaceBetween size="s">+ <Box variant="h3">No payment method saved</Box>+ <Box color="text-body-secondary">+ By saving this card, you authorize Fleet to charge it+ automatically for future usage according to the applicable pricing+ and terms.+ </Box>+ </SpaceBetween>+ )}+ </Container>+ </SpaceBetween>+ );+}diff --git a/libs/fleet/src/pages/Settings.tsx b/libs/fleet/src/pages/Settings.tsxindex e49cb2f68e..381492a27d 100644--- a/libs/fleet/src/pages/Settings.tsx+++ b/libs/fleet/src/pages/Settings.tsx@@ -1,5 +1,7 @@// Settings page — shows the signed-in user's identity (username and-// subject) read from the Keycloak token, with copy-to-clipboard for each.+// subject) read from the Keycloak token, with copy-to-clipboard for each,+// plus payment methods and recent invoices when the billing+// feature flag is enabled.import Box from "@cloudscape-design/components/box"import Container from "@cloudscape-design/components/container"@@ -8,9 +10,12 @@ import FormField from "@cloudscape-design/components/form-field"import Header from "@cloudscape-design/components/header"import SpaceBetween from "@cloudscape-design/components/space-between"import { userInfo } from "../auth/keycloak"+import { useFeatureFlags } from "../components/FeatureFlagContext"+import { BillingSettings } from "./Billing"export function Settings() {const { sub, name } = userInfo()+ const { billing } = useFeatureFlags()return (<SpaceBetween size="l">@@ -46,6 +51,7 @@ export function Settings() {</FormField></SpaceBetween></Container>+ {billing && <BillingSettings />}</SpaceBetween>)}diff --git a/libs/fleet/src/sdk/billing.ts b/libs/fleet/src/sdk/billing.tsnew file mode 100644index 0000000000..3ff3c386c6--- /dev/null+++ b/libs/fleet/src/sdk/billing.ts@@ -0,0 +1,35 @@+import { getToken } from "../auth/keycloak";++export interface SavedCard {+ brand: string;+ last4: string;+ exp_month: number;+ exp_year: number;+}++export interface BillingSummary {+ payment_method_present: boolean;+ card: SavedCard | null;+}++async function billingRequest<T>(+ path: string,+ method: "GET" | "POST",+): Promise<T> {+ const token = await getToken();+ const response = await fetch(path, {+ method,+ headers: { Authorization: token ? `Bearer ${token}` : "" },+ });+ if (!response.ok)+ throw new Error(`billing request failed: ${response.status}`);+ return response.json() as Promise<T>;+}++export const billingApi = {+ summary: () => billingRequest<BillingSummary>("/api/billing/summary", "GET"),+ setup: () =>+ billingRequest<{ url: string }>("/api/billing/setup-session", "POST"),+ portal: () =>+ billingRequest<{ url: string }>("/api/billing/portal-session", "POST"),+};diff --git a/libs/fleet/src/sdk/featureFlags.ts b/libs/fleet/src/sdk/featureFlags.tsnew file mode 100644index 0000000000..f46d9abb8a--- /dev/null+++ b/libs/fleet/src/sdk/featureFlags.ts@@ -0,0 +1,58 @@+// Feature flags client — fetches /api/config to get per-user flags.+// The backend derives admin status from the OpenFeature flag+// `/feature-flags/cyclops-cs/admin-subs` (AWS SSM Parameter Store in prod,+// or the CYCLOPS_CS_ADMIN_SUBS env var in dev) — a JSON array of Keycloak+// sub UUIDs. Access to infra-only resources is also enforced server-side by+// the backend's OPA policy, not just by hiding nav here.++import { getToken } from "../auth/keycloak"++export interface FeatureFlags {+ /** Admin users see the full infra UI: Nodes and Operator events. */+ admin: boolean+ /** Billing navigation and page are disabled by default. */+ billing: boolean+}++const DEFAULT_FLAGS: FeatureFlags = {+ admin: false,+ billing: false,+}++let _cache: FeatureFlags | null = null+let _fetchPromise: Promise<FeatureFlags> | null = null++export async function fetchFeatureFlags(): Promise<FeatureFlags> {+ if (_cache) return _cache+ if (_fetchPromise) return _fetchPromise++ _fetchPromise = (async () => {+ try {+ const token = await getToken()+ const res = await fetch("/api/config", {+ headers: {+ Authorization: token ? `Bearer ${token}` : "",+ "Content-Type": "application/json",+ },+ })+ if (!res.ok) return DEFAULT_FLAGS+ const data = (await res.json()) as FeatureFlags+ _cache = {+ admin: data.admin ?? false,+ billing: data.billing ?? false,+ }+ return _cache+ } catch {+ return DEFAULT_FLAGS+ } finally {+ _fetchPromise = null+ }+ })()++ return _fetchPromise+}++/** Invalidate the cache (e.g., after login). */+export function invalidateFeatureFlags(): void {+ _cache = null+}