Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-5852: 接入 Workspace Stripe 订阅代理 (#6886)

Multica Eve587fbc5559ad
diff --git a/.env.example b/.env.example
index e4b607079c..4061d3f345 100644
--- a/.env.example
+++ b/.env.example
@@ -118,6 +118,10 @@ MULTICA_CODEX_TIMEOUT=20m
# process with the env var set.
MULTICA_FEATURE_FLAGS_FILE=
+# Workspace subscription Checkout/Portal/entitlement proxying is fail-closed;
+# enable it only after multica-cloud billing.subscriptions is configured:
+# FF_BILLING_WORKSPACE_SUBSCRIPTIONS=true
+
# Self-host image channel
# Default stable release channel. Pin to an exact release like v0.2.4 if you
# want to stay on a specific version. If the selected tag has not been
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 3e17c02f0d..c4b85af3f6 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1345,6 +1345,24 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/portal-sessions", h.CreateCloudBillingPortalSession)
})
+ // Workspace subscriptions use the same cloud transport and Stripe
+ // webhook as the existing owner-credit billing surface, but every request
+ // is workspace-scoped. Entitlements are member-readable; Checkout, seat
+ // reconcile, and Portal mutations require owner/admin. The handlers also
+ // enforce billing_workspace_subscriptions so a route refactor cannot
+ // accidentally bypass the rollout flag.
+ r.Route("/api/cloud-subscriptions", func(r chi.Router) {
+ r.Use(handler.RequireHumanActor)
+
+ r.With(middleware.RequireWorkspaceMember(queries)).Get("/entitlements", h.GetCloudWorkspaceEntitlements)
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceRole(queries, "owner", "admin"))
+ r.Post("/checkout-sessions", h.CreateCloudWorkspaceSubscriptionCheckout)
+ r.Post("/seats/reconcile", h.ReconcileCloudWorkspaceSubscriptionSeats)
+ r.Post("/portal-sessions", h.CreateCloudWorkspaceSubscriptionPortal)
+ })
+ })
+
// --- Workspace-scoped routes (all require workspace membership) ---
r.Group(func(r chi.Router) {
r.Use(middleware.RequireWorkspaceMember(queries))
diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.go
index c75fb9e082..c9af98d736 100644
--- a/server/internal/featureflags/keys.go
+++ b/server/internal/featureflags/keys.go
@@ -7,6 +7,11 @@ import (
)
const (
+ // BillingWorkspaceSubscriptions gates the workspace-scoped entitlement,
+ // Stripe Checkout, seat reconcile, and Billing Portal proxy surface. It is
+ // deliberately off by default so the main repository can ship before the
+ // managed cloud enables its matching billing.subscriptions capability.
+ BillingWorkspaceSubscriptions = "billing_workspace_subscriptions"
// ComposioMCPApps gates the Composio app management UI and — together with
// the MUL-3963 permission_mode / invocation_targets access model it depends
// on — the aligned Private / Public-to picker in the agent create flow.
@@ -36,10 +41,15 @@ const (
)
var frontendPublicFlags = []string{
+ BillingWorkspaceSubscriptions,
ComposioMCPApps,
PluginsV1,
}
+func BillingWorkspaceSubscriptionsEnabled(ctx context.Context, flags *featureflag.Service) bool {
+ return flags.IsEnabled(ctx, BillingWorkspaceSubscriptions, false)
+}
+
func ComposioMCPAppsEnabled(ctx context.Context, flags *featureflag.Service) bool {
return flags.IsEnabled(ctx, ComposioMCPApps, false)
}
diff --git a/server/internal/handler/actor_guards.go b/server/internal/handler/actor_guards.go
index 54d7adc99f..ee3bc8586c 100644
--- a/server/internal/handler/actor_guards.go
+++ b/server/internal/handler/actor_guards.go
@@ -18,18 +18,18 @@ import (
// token kind the caller used:
//
// - JWT cookie / mul_ PAT → X-User-ID = the human's user id.
-// X-Actor-Source is left empty.
+// X-Actor-Source is left empty.
// - mat_ task token → X-User-ID = the OWNING human's user id,
-// plus X-Agent-ID, X-Task-ID, and the
-// authoritative server-set header
-// `X-Actor-Source: task_token`.
+// plus X-Agent-ID, X-Task-ID, and the
+// authoritative server-set header
+// `X-Actor-Source: task_token`.
// - mcn_ cloud-node PAT → X-User-ID = the OWNING human's user id,
-// plus `X-Actor-Source: cloud_pat`.
-// The token authenticates a cloud-runtime
-// EC2 node operating on the owner's
-// behalf — same conceptual category as
-// mat_ (machine running owner-scoped
-// code) for authorization purposes.
+// plus `X-Actor-Source: cloud_pat`.
+// The token authenticates a cloud-runtime
+// EC2 node operating on the owner's
+// behalf — same conceptual category as
+// mat_ (machine running owner-scoped
+// code) for authorization purposes.
//
// The mat_ and mcn_ designs (MUL-2600 and the cloud-node PAT story
// respectively) were both deliberately built this way: every request
@@ -95,14 +95,26 @@ import (
// human-equivalent or machine-equivalent.
func RequireHumanActor(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // X-Actor-Source is server-set only. The auth middleware
- // strips any client-supplied value before stamping its own,
- // so a non-empty value here is authoritative.
- switch r.Header.Get("X-Actor-Source") {
- case "task_token", "cloud_pat":
+ if isMachineCredentialActor(r) {
writeError(w, http.StatusForbidden, "this endpoint is only available to human actors")
return
}
next.ServeHTTP(w, r)
})
}
+
+// isMachineCredentialActor centralizes the authoritative actor-source check so
+// sensitive handlers can keep a fail-closed backstop in addition to their
+// router middleware. Unknown actor sources intentionally remain human-equivalent
+// until their authentication branch is explicitly classified here.
+func isMachineCredentialActor(r *http.Request) bool {
+ // X-Actor-Source is server-set only. The auth middleware strips any
+ // client-supplied value before stamping its own, so a recognized value here
+ // is authoritative.
+ switch r.Header.Get("X-Actor-Source") {
+ case "task_token", "cloud_pat":
+ return true
+ default:
+ return false
+ }
+}
diff --git a/server/internal/handler/cloud_billing.go b/server/internal/handler/cloud_billing.go
index a1cb8dc10f..4213eb36b0 100644
--- a/server/internal/handler/cloud_billing.go
+++ b/server/internal/handler/cloud_billing.go
@@ -1,12 +1,16 @@
package handler
import (
+ "encoding/json"
"errors"
"io"
"net/http"
+ "strings"
"github.com/go-chi/chi/v5"
"github.com/multica-ai/multica/server/internal/cloudruntime"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/util"
)
// Cloud billing endpoints proxy to the same multica-cloud HTTP service
@@ -14,9 +18,10 @@ import (
// upstream README). All paths here forward verbatim to /api/v1/billing/*
// on the cloud side, mirroring the cloud-runtime handler shape:
//
-// - User-facing endpoints sit under /api/cloud-billing/* in our router
-// and require the regular Auth middleware. We inject the resolved
-// user_id as `X-User-ID` so the cloud side can scope owner queries.
+// - Owner-credit endpoints sit under /api/cloud-billing/* in our router.
+// Workspace subscription endpoints sit under /api/cloud-subscriptions/*
+// and add membership / role checks plus an authoritative workspace ID.
+// Both require regular Auth and inject the resolved user_id as `X-User-ID`.
//
// - The Stripe webhook is the one outlier: it lives at
// /api/webhooks/stripe (outside the Auth group), takes the raw
@@ -25,8 +30,9 @@ import (
// upstream contract is explicit about this:
// "webhook 使用原始请求体进行签名校验,不要在反向代理里改写 body."
//
-// All proxy paths share `proxyCloudRuntime` for the standard JSON
-// shape and only the webhook needs a custom raw-body forwarder.
+// Owner-credit paths share `proxyCloudRuntime`. Workspace subscriptions use a
+// small stricter wrapper to inject workspace_id and allowlist Idempotency-Key;
+// the webhook remains the only raw-body forwarder.
// maxStripeWebhookBodySize bounds the raw body we'll forward upstream.
// Stripe's documented event payload upper bound is well under this;
@@ -40,6 +46,177 @@ const maxStripeWebhookBodySize = 1 << 20 // 1 MiB
// shared secret and rejects on mismatch.
const stripeSignatureHeader = "Stripe-Signature"
+const idempotencyKeyHeader = "Idempotency-Key"
+const maxCloudSubscriptionIdempotencyKeyLength = 255
+
+type cloudSubscriptionCheckoutRequest struct {
+ Interval string `json:"interval"`
+ IdempotencyKey string `json:"idempotency_key,omitempty"`
+ CustomerEmail string `json:"customer_email,omitempty"`
+}
+
+// This is an intentional allowlist: additive cloud fields are not forwarded
+// until the main repository explicitly reviews and adds them here.
+type cloudSubscriptionCheckoutUpstreamRequest struct {
+ WorkspaceID string `json:"workspace_id"`
+ Interval string `json:"interval"`
+ IdempotencyKey string `json:"idempotency_key,omitempty"`
+ CustomerEmail string `json:"customer_email,omitempty"`
+}
+
+// requireCloudSubscriptionWorkspace is the handler-level backstop behind the
+// router's RequireWorkspaceMember / RequireWorkspaceRole middleware. Keeping
+// the check here makes a future route refactor fail closed instead of exposing
+// a workspace billing write without its tenant/role guard.
+func (h *Handler) requireCloudSubscriptionWorkspace(w http.ResponseWriter, r *http.Request, roles ...string) (string, string, bool) {
+ if isMachineCredentialActor(r) {
+ writeError(w, http.StatusForbidden, "this endpoint is only available to human actors")
+ return "", "", false
+ }
+ if !featureflags.BillingWorkspaceSubscriptionsEnabled(r.Context(), h.FeatureFlags) {
+ writeError(w, http.StatusServiceUnavailable, "workspace subscriptions are not enabled")
+ return "", "", false
+ }
+
+ workspaceID := ctxWorkspaceID(r.Context())
+ workspaceUUID, err := util.ParseUUID(workspaceID)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "workspace_id or workspace_slug is required")
+ return "", "", false
+ }
+ member, ok := ctxMember(r.Context())
+ if !ok {
+ writeError(w, http.StatusForbidden, "workspace membership required")
+ return "", "", false
+ }
+ if len(roles) > 0 && !roleAllowed(member.Role, roles...) {
+ writeError(w, http.StatusForbidden, "insufficient permissions")
+ return "", "", false
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return "", "", false
+ }
+ return util.UUIDToString(workspaceUUID), userID, true
+}
+
+func (h *Handler) proxyCloudSubscription(w http.ResponseWriter, r *http.Request, method, path, userID string, body []byte, headers http.Header) {
+ if h.CloudRuntime == nil || !h.CloudRuntime.Enabled() {
+ writeError(w, http.StatusServiceUnavailable, "cloud runtime is not configured")
+ return
+ }
+ resp, err := h.CloudRuntime.Do(r.Context(), cloudruntime.Request{
+ Method: method,
+ Path: path,
+ Body: body,
+ UserID: userID,
+ RequestID: cloudRuntimeRequestID(r),
+ Op: "billing",
+ Headers: headers,
+ })
+ if err != nil {
+ writeCloudRuntimeError(w, r, err)
+ return
+ }
+ writeCloudRuntimeResponse(w, resp)
+}
+
+func cloudSubscriptionIdempotencyHeaders(r *http.Request) http.Header {
+ key := strings.TrimSpace(r.Header.Get(idempotencyKeyHeader))
+ if key == "" {
+ return nil
+ }
+ return http.Header{idempotencyKeyHeader: []string{key}}
+}
+
+func requireCloudSubscriptionIdempotencyKey(w http.ResponseWriter, r *http.Request, bodyKey string) (string, bool) {
+ key := strings.TrimSpace(bodyKey)
+ if key == "" {
+ key = strings.TrimSpace(r.Header.Get(idempotencyKeyHeader))
+ }
+ if key == "" {
+ writeError(w, http.StatusBadRequest, "Idempotency-Key or idempotency_key is required")
+ return "", false
+ }
+ if len(key) > maxCloudSubscriptionIdempotencyKeyLength {
+ writeError(w, http.StatusBadRequest, "idempotency key must be at most 255 bytes")
+ return "", false
+ }
+ return key, true
+}
+
+// GetCloudWorkspaceEntitlements forwards the active workspace to cloud's
+// resolved entitlement endpoint. Any workspace member may read this snapshot;
+// cloud independently verifies the stamped X-User-ID against its read-only
+// product database.
+func (h *Handler) GetCloudWorkspaceEntitlements(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r)
+ if !ok {
+ return
+ }
+ h.proxyCloudSubscription(w, r, http.MethodGet, "/api/v1/entitlements/"+workspaceID, userID, nil, nil)
+}
+
+// CreateCloudWorkspaceSubscriptionCheckout injects the middleware-resolved
+// workspace into the upstream body. A caller cannot use a valid role in one
+// workspace to smuggle a different workspace_id through JSON.
+func (h *Handler) CreateCloudWorkspaceSubscriptionCheckout(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r, "owner", "admin")
+ if !ok {
+ return
+ }
+ body, ok := readCloudRuntimeJSONBody(w, r)
+ if !ok {
+ return
+ }
+ var in cloudSubscriptionCheckoutRequest
+ if err := json.Unmarshal(body, &in); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if in.Interval != "month" && in.Interval != "year" {
+ writeError(w, http.StatusBadRequest, "interval must be month or year")
+ return
+ }
+ idempotencyKey, ok := requireCloudSubscriptionIdempotencyKey(w, r, in.IdempotencyKey)
+ if !ok {
+ return
+ }
+ upstreamBody, err := json.Marshal(cloudSubscriptionCheckoutUpstreamRequest{
+ WorkspaceID: workspaceID,
+ Interval: in.Interval,
+ IdempotencyKey: idempotencyKey,
+ CustomerEmail: in.CustomerEmail,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to build subscription request")
+ return
+ }
+ h.proxyCloudSubscription(w, r, http.MethodPost, "/api/v1/subscriptions/checkout-sessions", userID, upstreamBody, cloudSubscriptionIdempotencyHeaders(r))
+}
+
+// ReconcileCloudWorkspaceSubscriptionSeats is a hint only: neither this
+// handler nor its caller supplies a seat quantity. Cloud re-counts human
+// members from its least-privilege product-database connection.
+func (h *Handler) ReconcileCloudWorkspaceSubscriptionSeats(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r, "owner", "admin")
+ if !ok {
+ return
+ }
+ h.proxyCloudSubscription(w, r, http.MethodPost, "/api/v1/subscriptions/"+workspaceID+"/seats/reconcile", userID, nil, nil)
+}
+
+func (h *Handler) CreateCloudWorkspaceSubscriptionPortal(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r, "owner", "admin")
+ if !ok {
+ return
+ }
+ if _, ok := requireCloudSubscriptionIdempotencyKey(w, r, ""); !ok {
+ return
+ }
+ h.proxyCloudSubscription(w, r, http.MethodPost, "/api/v1/subscriptions/"+workspaceID+"/portal-sessions", userID, nil, cloudSubscriptionIdempotencyHeaders(r))
+}
+
// GetCloudBillingBalance forwards GET /api/v1/billing/balance.
//
// Returns the caller's wallet balance. Cloud reads `X-User-ID`; we
@@ -282,6 +459,7 @@ func (h *Handler) HandleCloudBillingStripeWebhook(w http.ResponseWriter, r *http
Body: body,
Headers: headers,
RequestID: cloudRuntimeRequestID(r),
+ Op: "billing",
// Intentionally no UserID — webhook is unauthenticated by
// design; injecting an empty header would still be harmless,
// but staying explicit makes the contract obvious to readers.
diff --git a/server/internal/handler/cloud_billing_test.go b/server/internal/handler/cloud_billing_test.go
index 1c6682c598..d3984d4ef3 100644
--- a/server/internal/handler/cloud_billing_test.go
+++ b/server/internal/handler/cloud_billing_test.go
@@ -3,12 +3,16 @@ package handler
import (
"bytes"
"context"
+ "encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/multica-ai/multica/server/internal/cloudruntime"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/middleware"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
// proxyExpectation captures the assertions every standard
@@ -244,6 +248,295 @@ func TestCloudBillingDisabledReturnsUnavailable(t *testing.T) {
}
}
+func withCloudSubscriptionWorkspace(req *http.Request, role string) *http.Request {
+ ctx := middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{Role: role})
+ return req.WithContext(ctx)
+}
+
+func TestCloudWorkspaceSubscriptionsDisabledByDefault(t *testing.T) {
+ proxy := &fakeCloudRuntimeProxy{enabled: true}
+ useCloudRuntimeProxy(t, proxy)
+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, false)
+
+ req := withCloudSubscriptionWorkspace(
+ newRequest(http.MethodGet, "/api/cloud-subscriptions/entitlements", nil),
+ "member",
+ )
+ w := httptest.NewRecorder()
+ testHandler.GetCloudWorkspaceEntitlements(w, req)
+
+ if w.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
+ }
+ if proxy.called {
+ t.Fatal("upstream must not be called while the feature flag is off")
+ }
+}
+
+func TestCloudWorkspaceSubscriptionReadAndWritesUseScopedPaths(t *testing.T) {
+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)
+
+ cases := []struct {
+ name string
+ method string
+ path string
+ role string
+ wantStatus int
+ wantPath string
+ invoke func(http.ResponseWriter, *http.Request)
+ }{
+ {
+ name: "member reads entitlements",
+ method: http.MethodGet,
+ path: "/api/cloud-subscriptions/entitlements",
+ role: "member",
+ wantStatus: http.StatusOK,
+ wantPath: "/api/v1/entitlements/" + testWorkspaceID,
+ invoke: testHandler.GetCloudWorkspaceEntitlements,
+ },
+ {
+ name: "admin reconciles seats",
+ method: http.MethodPost,
+ path: "/api/cloud-subscriptions/seats/reconcile",
+ role: "admin",
+ wantStatus: http.StatusOK,
+ wantPath: "/api/v1/subscriptions/" + testWorkspaceID + "/seats/reconcile",
+ invoke: testHandler.ReconcileCloudWorkspaceSubscriptionSeats,
+ },
+ {
+ name: "owner opens portal",
+ method: http.MethodPost,
+ path: "/api/cloud-subscriptions/portal-sessions",
+ role: "owner",
+ wantStatus: http.StatusOK,
+ wantPath: "/api/v1/subscriptions/" + testWorkspaceID + "/portal-sessions",
+ invoke: testHandler.CreateCloudWorkspaceSubscriptionPortal,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ proxy := &fakeCloudRuntimeProxy{
+ enabled: true,
+ resp: &cloudruntime.Response{
+ StatusCode: tc.wantStatus,
+ Body: []byte(`{"ok":true}`),
+ },
+ }
+ useCloudRuntimeProxy(t, proxy)
+
+ req := withCloudSubscriptionWorkspace(newRequest(tc.method, tc.path, nil), tc.role)
+ if strings.Contains(tc.path, "portal-sessions") {
+ req.Header.Set(idempotencyKeyHeader, "portal-request-1")
+ }
+ w := httptest.NewRecorder()
+ tc.invoke(w, req)
+
+ if w.Code != tc.wantStatus {
+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
+ }
+ if proxy.req.Method != tc.method || proxy.req.Path != tc.wantPath {
+ t.Fatalf("upstream = %s %s, want %s %s", proxy.req.Method, proxy.req.Path, tc.method, tc.wantPath)
+ }
+ if proxy.req.UserID != testUserID {
+ t.Fatalf("upstream user_id = %q, want %q", proxy.req.UserID, testUserID)
+ }
+ if proxy.req.Op != "billing" {
+ t.Fatalf("upstream op = %q, want billing", proxy.req.Op)
+ }
+ if strings.Contains(tc.path, "portal-sessions") && proxy.req.Headers.Get(idempotencyKeyHeader) != "portal-request-1" {
+ t.Fatalf("upstream idempotency key = %q", proxy.req.Headers.Get(idempotencyKeyHeader))
+ }
+ })
+ }
+}
+
+func TestCreateCloudWorkspaceSubscriptionCheckoutInjectsAuthoritativeWorkspace(t *testing.T) {
+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)
+ proxy := &fakeCloudRuntimeProxy{
+ enabled: true,
+ resp: &cloudruntime.Response{
+ StatusCode: http.StatusCreated,
+ Body: []byte(`{"url":"https://checkout.stripe.test/session"}`),
+ },
+ }
+ useCloudRuntimeProxy(t, proxy)
+
+ req := newRequest(http.MethodPost, "/api/cloud-subscriptions/checkout-sessions", map[string]any{
+ "workspace_id": "00000000-0000-0000-0000-000000000001",
+ "interval": "year",
+ "idempotency_key": "checkout-request-1",
+ "customer_email": "[email protected]",
+ })
+ req.Header.Set(idempotencyKeyHeader, "checkout-header-1")
+ req = withCloudSubscriptionWorkspace(req, "owner")
+ w := httptest.NewRecorder()
+ testHandler.CreateCloudWorkspaceSubscriptionCheckout(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
+ }
+ if proxy.req.Path != "/api/v1/subscriptions/checkout-sessions" || proxy.req.Method != http.MethodPost {
+ t.Fatalf("upstream = %s %s", proxy.req.Method, proxy.req.Path)
+ }
+ var body cloudSubscriptionCheckoutUpstreamRequest
+ if err := json.Unmarshal(proxy.req.Body, &body); err != nil {
+ t.Fatalf("decode upstream body: %v", err)
+ }
+ if body.WorkspaceID != testWorkspaceID {
+ t.Fatalf("upstream workspace_id = %q, want middleware workspace %q", body.WorkspaceID, testWorkspaceID)
+ }
+ if body.Interval != "year" || body.IdempotencyKey != "checkout-request-1" || body.CustomerEmail != "[email protected]" {
+ t.Fatalf("upstream body = %+v", body)
+ }
+ if got := proxy.req.Headers.Get(idempotencyKeyHeader); got != "checkout-header-1" {
+ t.Fatalf("upstream idempotency key = %q", got)
+ }
+}
+
+func TestCreateCloudWorkspaceSubscriptionCheckoutAcceptsHeaderIdempotencyKey(t *testing.T) {
+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)
+ proxy := &fakeCloudRuntimeProxy{
+ enabled: true,
+ resp: &cloudruntime.Response{
+ StatusCode: http.StatusCreated,
+ Body: []byte(`{"url":"https://checkout.stripe.test/session"}`),
+ },
+ }
+ useCloudRuntimeProxy(t, proxy)
+
+ req := withCloudSubscriptionWorkspace(
+ newRequest(http.MethodPost, "/api/cloud-subscriptions/checkout-sessions", map[string]any{"interval": "month"}),
+ "admin",
+ )
+ req.Header.Set(idempotencyKeyHeader, "checkout-header-only")
+ w := httptest.NewRecorder()
+ testHandler.CreateCloudWorkspaceSubscriptionCheckout(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
+ }
+ var body cloudSubscriptionCheckoutUpstreamRequest
+ if err := json.Unmarshal(proxy.req.Body, &body); err != nil {
+ t.Fatalf("decode upstream body: %v", err)
+ }
+ if body.IdempotencyKey != "checkout-header-only" {
+ t.Fatalf("upstream body idempotency_key = %q", body.IdempotencyKey)
+ }
+}
+
+func TestCloudWorkspaceSubscriptionWritesRequireManagerRole(t *testing.T) {
+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)
+ proxy := &fakeCloudRuntimeProxy{enabled: true}
+ useCloudRuntimeProxy(t, proxy)
+
+ req := withCloudSubscriptionWorkspace(
+ newRequest(http.MethodPost, "/api/cloud-subscriptions/portal-sessions", nil),
+ "member",
+ )
+ w := httptest.NewRecorder()
+ testHandler.CreateCloudWorkspaceSubscriptionPortal(w, req)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
+ }
+ if proxy.called {
+ t.Fatal("upstream must not be called for a non-manager member")
+ }
+}
+
+func TestCloudWorkspaceSubscriptionsRejectMachineActorsAtHandler(t *testing.T) {
+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)
+
+ for _, actorSource := range []string{"task_token", "cloud_pat"} {
+ t.Run(actorSource, func(t *testing.T) {
+ proxy := &fakeCloudRuntimeProxy{enabled: true}
+ useCloudRuntimeProxy(t, proxy)
+
+ req := withCloudSubscriptionWorkspace(
+ newRequest(http.MethodPost, "/api/cloud-subscriptions/portal-sessions", nil),
+ "owner",
+ )
+ req.Header.Set("X-Actor-Source", actorSource)
+ req.Header.Set(idempotencyKeyHeader, "portal-request-1")
+ w := httptest.NewRecorder()
+ testHandler.CreateCloudWorkspaceSubscriptionPortal(w, req)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
+ }
+ if proxy.called {
+ t.Fatal("upstream must not be called for a machine actor")
+ }
+ })
+ }
+}
+
+func TestCloudWorkspaceSubscriptionMutationsValidateLocally(t *testing.T) {
+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)
+
+ cases := []struct {
+ name string
+ path string
+ body any
+ header string
+ wantError string
+ invoke func(http.ResponseWriter, *http.Request)
+ }{
+ {
+ name: "checkout missing idempotency key",
+ path: "/api/cloud-subscriptions/checkout-sessions",
+ body: map[string]any{"interval": "month"},
+ wantError: "Idempotency-Key or idempotency_key is required",
+ invoke: testHandler.CreateCloudWorkspaceSubscriptionCheckout,
+ },
+ {
+ name: "checkout invalid interval",
+ path: "/api/cloud-subscriptions/checkout-sessions",
+ body: map[string]any{"interval": "weekly", "idempotency_key": "checkout-request-1"},
+ wantError: "interval must be month or year",
+ invoke: testHandler.CreateCloudWorkspaceSubscriptionCheckout,
+ },
+ {
+ name: "portal missing idempotency key",
+ path: "/api/cloud-subscriptions/portal-sessions",
+ wantError: "Idempotency-Key or idempotency_key is required",
+ invoke: testHandler.CreateCloudWorkspaceSubscriptionPortal,
+ },
+ {
+ name: "portal oversized idempotency key",
+ path: "/api/cloud-subscriptions/portal-sessions",
+ header: strings.Repeat("a", maxCloudSubscriptionIdempotencyKeyLength+1),
+ wantError: "idempotency key must be at most 255 bytes",
+ invoke: testHandler.CreateCloudWorkspaceSubscriptionPortal,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ proxy := &fakeCloudRuntimeProxy{enabled: true}
+ useCloudRuntimeProxy(t, proxy)
+
+ req := withCloudSubscriptionWorkspace(newRequest(http.MethodPost, tc.path, tc.body), "owner")
+ if tc.header != "" {
+ req.Header.Set(idempotencyKeyHeader, tc.header)
+ }
+ w := httptest.NewRecorder()
+ tc.invoke(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), tc.wantError) {
+ t.Fatalf("body = %s, want error containing %q", w.Body.String(), tc.wantError)
+ }
+ if proxy.called {
+ t.Fatal("upstream must not be called for a locally invalid request")
+ }
+ })
+ }
+}
+
// --- Stripe webhook ---
// TestStripeWebhookForwardsRawBodyAndSignature is the critical
@@ -302,6 +595,9 @@ func TestStripeWebhookForwardsRawBodyAndSignature(t *testing.T) {
if proxy.req.UserID != "" {
t.Errorf("upstream user_id should be empty for webhook, got %q", proxy.req.UserID)
}
+ if proxy.req.Op != "billing" {
+ t.Errorf("upstream op = %q, want billing", proxy.req.Op)
+ }
}
// TestStripeWebhookMissingSignatureRejectedLocally pins the early
@@ -400,7 +696,6 @@ func TestStripeWebhookDisabledReturnsUnavailable(t *testing.T) {
}
}
-
// TestStripeWebhookRateLimited pins the per-IP rate-limit fast
// path. With a denying limiter installed the handler must 429
// BEFORE consulting upstream. Mirrors HandleAutopilotWebhook's
diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.go
index 29bcb7bbf7..2a7b689994 100644
--- a/server/internal/handler/config_test.go
+++ b/server/internal/handler/config_test.go
@@ -412,6 +412,9 @@ func TestGetConfigExposesFrontendFeatureFlags(t *testing.T) {
if cfg.FeatureFlags["composio_mcp_apps"] {
t.Fatalf("composio_mcp_apps: want false by default, got true")
}
+ if cfg.FeatureFlags["billing_workspace_subscriptions"] {
+ t.Fatalf("billing_workspace_subscriptions: want false by default, got true")
+ }
if cfg.FeatureFlags["plugins_v1"] {
t.Fatalf("plugins_v1: want false by default, got true")
}