Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(billing): make Cloud seat enforcement automatic (#7542)
LinYushenbaf1bbf3401b
diff --git a/.env.example b/.env.exampleindex d9dcacfb64..4bbf6719f3 100644--- a/.env.example+++ b/.env.example@@ -214,14 +214,23 @@ MULTICA_ENTITLEMENT_STALE_GRACE=15m# all gates off without contacting Cloud; it cannot enable a policy.MULTICA_ENTITLEMENT_EMERGENCY_DISABLED=false-# Managed pre-purchased member-seat executor. Cloud remains the commercial-# authority; the product only records and retries idempotent capacity intents.-# Keep disabled for self-hosting. The token must match Cloud's+# Managed multica-cloud connection. Leave the URL empty for self-hosting. When+# connected, Fleet, Billing, and strict pre-purchased seat capacity use this+# same service; capacity cannot be disabled independently. Entitlement policy+# keeps its dedicated configuration above.+MULTICA_CLOUD_URL=+MULTICA_CLOUD_TIMEOUT=35s+# The machine token must match Cloud's# billing.subscriptions.service_token_env secret.-MULTICA_SUBSCRIPTION_CAPACITY_ENABLED=false-MULTICA_SUBSCRIPTION_CAPACITY_URL=MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN=MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT=3s+# Retired Cloud/Fleet/capacity variables are intentionally unsupported. The+# server refuses to start when any retired variable has a non-empty value so a+# rollout cannot silently lose PAT/runtime connectivity or seat enforcement.+# Replace MULTICA_FLEET_URL / MULTICA_CLOUD_FLEET_URL and the retired capacity+# URL/switch variables with the settings above before deploying this version.+# Delete/unset the old switches completely: a literal value such as+# MULTICA_SUBSCRIPTION_CAPACITY_ENABLED=false is still non-empty and blocks boot.# Self-host image channel# Default stable release channel. Pin to an exact release like v0.2.4 if youdiff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yamlindex 8e93c7da5a..34124fd6bb 100644--- a/deploy/helm/multica/templates/configmap.yaml+++ b/deploy/helm/multica/templates/configmap.yaml@@ -25,9 +25,9 @@ data:MULTICA_ENTITLEMENT_POLICY_TIMEOUT: {{ .Values.backend.config.entitlementPolicy.timeout | quote }}MULTICA_ENTITLEMENT_STALE_GRACE: {{ .Values.backend.config.entitlementPolicy.staleGrace | quote }}MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: {{ .Values.backend.config.entitlementPolicy.emergencyDisabled | quote }}- MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: {{ .Values.backend.config.subscriptionCapacity.enabled | quote }}- MULTICA_SUBSCRIPTION_CAPACITY_URL: {{ .Values.backend.config.subscriptionCapacity.url | quote }}- MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: {{ .Values.backend.config.subscriptionCapacity.timeout | quote }}+ MULTICA_CLOUD_URL: {{ .Values.backend.config.cloud.url | quote }}+ MULTICA_CLOUD_TIMEOUT: {{ .Values.backend.config.cloud.timeout | quote }}+ MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: {{ .Values.backend.config.cloud.capacityTimeout | quote }}GOOGLE_CLIENT_ID: {{ .Values.backend.config.googleClientId | quote }}GOOGLE_REDIRECT_URI: {{ .Values.backend.config.googleRedirectUri | quote }}S3_BUCKET: {{ .Values.backend.config.s3Bucket | quote }}diff --git a/deploy/helm/multica/templates/prometheusrule.yaml b/deploy/helm/multica/templates/prometheusrule.yamlindex 4180a77ba6..802ec1b382 100644--- a/deploy/helm/multica/templates/prometheusrule.yaml+++ b/deploy/helm/multica/templates/prometheusrule.yaml@@ -58,5 +58,5 @@ spec:severity: {{ .Values.monitoring.prometheusRule.severity | quote }}annotations:summary: "Seat capacity outbox is stalled"- description: "The oldest {{ "{{ $labels.action }}" }} seat capacity intent has remained unsettled beyond the configured age threshold."+ description: "The oldest {{ "{{ $labels.action }}" }} seat capacity intent has remained unsettled beyond the configured age threshold. Repeated Cloud or proxy 429 deferrals intentionally remain pending and surface here instead of in the dead-letter alert."{{- end }}diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yamlindex 6288d060e7..2b643111b3 100644--- a/deploy/helm/multica/values.yaml+++ b/deploy/helm/multica/values.yaml@@ -150,12 +150,13 @@ backend:staleGrace: 15m# Local down switch applied by the next chart rollout; it only forces off.emergencyDisabled: false- # Managed Cloud seat-capacity executor. Keep off for self-hosting. When- # enabled, put the matching service token in existingSecret.- subscriptionCapacity:- enabled: false+ # Managed multica-cloud connection. Empty keeps self-hosting independent.+ # When set, Fleet, Billing and strict seat capacity share this URL; put the+ # matching seat-capacity service token in existingSecret.+ cloud:url: ""- timeout: 3s+ timeout: 35s+ capacityTimeout: 3sgoogleClientId: ""googleRedirectUri: http://multica.dev.lan/auth/callbacks3Bucket: ""diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex acf78fe5b3..0a4d06ab7e 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -114,9 +114,9 @@ services:MULTICA_ENTITLEMENT_POLICY_TIMEOUT: ${MULTICA_ENTITLEMENT_POLICY_TIMEOUT:-3s}MULTICA_ENTITLEMENT_STALE_GRACE: ${MULTICA_ENTITLEMENT_STALE_GRACE:-15m}MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: ${MULTICA_ENTITLEMENT_EMERGENCY_DISABLED:-false}- # Managed seat capacity is also opt-in and stays off for self-hosting.- MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: ${MULTICA_SUBSCRIPTION_CAPACITY_ENABLED:-false}- MULTICA_SUBSCRIPTION_CAPACITY_URL: ${MULTICA_SUBSCRIPTION_CAPACITY_URL:-}+ # Managed Cloud stays off for self-hosting; seat capacity follows this URL.+ MULTICA_CLOUD_URL: ${MULTICA_CLOUD_URL:-}+ MULTICA_CLOUD_TIMEOUT: ${MULTICA_CLOUD_TIMEOUT:-35s}MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN: ${MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN:-}MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: ${MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT:-3s}GITHUB_APP_SLUG: ${GITHUB_APP_SLUG:-}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 4312af6997..eeb7fa178e 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -1158,6 +1158,7 @@"toast_invitation_sent": "Invitation sent","toast_invitation_failed": "Failed to send invitation","toast_seat_capacity_unavailable": "Member capacity could not be verified. Please try again.",+ "toast_seat_capacity_rate_limited": "Seat capacity is busy. Try again shortly.","seat_purchase_title": "Add a seat to send this invitation?","seat_purchase_description": "No purchased seat is available for {{email}}. Review Stripe's estimate, then approve the purchase and invitation together.","purchase_seat_and_invite": "Buy 1 seat and invite",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 51dd22bf3b..1fced4f59d 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -1155,6 +1155,7 @@"toast_invitation_sent": "招待を送信しました","toast_invitation_failed": "招待を送信できませんでした","toast_seat_capacity_unavailable": "メンバー席を確認できませんでした。もう一度お試しください。",+ "toast_seat_capacity_rate_limited": "席数のリクエストが集中しています。しばらくしてからもう一度お試しください。","seat_purchase_title": "席を追加して招待を送信しますか?","seat_purchase_description": "{{email}} に使用できる購入済みの席がありません。Stripe の見積もりを確認し、席の購入と招待をまとめて承認してください。","purchase_seat_and_invite": "1 席を購入して招待",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 4d989409a6..d37591e790 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -893,6 +893,7 @@"toast_invitation_sent": "초대를 보냈습니다","toast_invitation_failed": "초대를 보내지 못했습니다","toast_seat_capacity_unavailable": "멤버 좌석을 확인할 수 없습니다. 다시 시도해 주세요.",+ "toast_seat_capacity_rate_limited": "좌석 요청이 많습니다. 잠시 후 다시 시도해 주세요.","seat_purchase_title": "좌석을 추가하고 초대를 보내시겠어요?","seat_purchase_description": "{{email}}에 사용할 구매 좌석이 없습니다. Stripe 견적을 확인한 뒤 좌석 구매와 초대를 함께 승인하세요.","purchase_seat_and_invite": "좌석 1개 구매 후 초대",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 1a31b15d4c..136aefa27e 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -1155,6 +1155,7 @@"toast_invitation_sent": "已发送邀请","toast_invitation_failed": "发送邀请失败","toast_seat_capacity_unavailable": "暂时无法核验成员席位,请稍后重试。",+ "toast_seat_capacity_rate_limited": "席位请求过于频繁,请稍后重试。","seat_purchase_title": "增加一个席位并发送邀请?","seat_purchase_description": "当前没有可供 {{email}} 使用的已购席位。请核对 Stripe 报价,然后一次确认补购和邀请。","purchase_seat_and_invite": "购买 1 个席位并邀请",diff --git a/packages/views/settings/components/members-tab.tsx b/packages/views/settings/components/members-tab.tsxindex 7cffa8835c..234d61b090 100644--- a/packages/views/settings/components/members-tab.tsx+++ b/packages/views/settings/components/members-tab.tsx@@ -80,6 +80,8 @@ import { formatStripeMinorAmount } from "./billing-format";import {isSingleSeatInvitePreview,purchasedSeatIsReadyForInvitation,+ seatInvitationCanRetryAfterPurchase,+ seatInvitationCapacityFailure,seatPurchaseCanRetryWithSameQuote,seatPurchaseMatchesPreview,} from "./seat-invite-purchase";@@ -433,6 +435,7 @@ export function MembersTab() {await sendInvitation(email, role);} catch (e) {const code = errorCode(e);+ const capacityFailure = seatInvitationCapacityFailure(code);if (code === "seat_capacity_overcommitted") {try {const summary = await qc.fetchQuery({@@ -467,7 +470,7 @@ export function MembersTab() {}return;}- if (code === "seat_capacity_full") {+ if (capacityFailure === "full") {try {const preview = await previewSeatPurchase.mutateAsync({additionalSeats: 1,@@ -496,10 +499,14 @@ export function MembersTab() {}return;}- if (code === "seat_capacity_unavailable") {+ if (capacityFailure === "unavailable") {toast.error(t(($) => $.members.toast_seat_capacity_unavailable));return;}+ if (capacityFailure === "rate_limited") {+ toast.error(t(($) => $.members.toast_seat_capacity_rate_limited));+ return;+ }toast.error(e instanceof Error ? e.message : t(($) => $.members.toast_invitation_failed));} finally {setInviteLoading(false);@@ -519,6 +526,10 @@ export function MembersTab() {setInviteSeatPurchase(null);return;}+ // A transient failure may happen after the purchase succeeded and the+ // first invitation dispatch ran. Reusing the same idempotency key is safe,+ // but the dispatch guard must be reopened for the retried invitation.+ dispatchedInvitePurchaseKey.current = null;setInviteSeatPurchase({...current,phase: "purchasing",@@ -605,18 +616,29 @@ export function MembersTab() {.then(() => setInviteSeatPurchase(null)).catch((error) => {const code = errorCode(error);+ const capacityFailure = seatInvitationCapacityFailure(code);+ let message: string;+ switch (capacityFailure) {+ case "full":+ message = t(($) => $.members.seat_purchase_capacity_taken);+ break;+ case "unavailable":+ message = t(($) => $.members.toast_seat_capacity_unavailable);+ break;+ case "rate_limited":+ message = t(($) => $.members.toast_seat_capacity_rate_limited);+ break;+ default:+ message =+ error instanceof Error+ ? error.message+ : t(($) => $.members.toast_invitation_failed);+ }setInviteSeatPurchase({...purchase,phase: "error",- retryable: false,- error:- code === "seat_capacity_full"- ? t(($) => $.members.seat_purchase_capacity_taken)- : code === "seat_capacity_unavailable"- ? t(($) => $.members.toast_seat_capacity_unavailable)- : error instanceof Error- ? error.message- : t(($) => $.members.toast_invitation_failed),+ retryable: seatInvitationCanRetryAfterPurchase(code),+ error: message,});});}, [diff --git a/packages/views/settings/components/seat-invite-purchase.test.ts b/packages/views/settings/components/seat-invite-purchase.test.tsindex 69ece536a4..fcd337d414 100644--- a/packages/views/settings/components/seat-invite-purchase.test.ts+++ b/packages/views/settings/components/seat-invite-purchase.test.ts@@ -6,6 +6,8 @@ import type {import {isSingleSeatInvitePreview,purchasedSeatIsReadyForInvitation,+ seatInvitationCanRetryAfterPurchase,+ seatInvitationCapacityFailure,seatPurchaseCanRetryWithSameQuote,seatPurchaseMatchesPreview,} from "./seat-invite-purchase";@@ -100,4 +102,29 @@ describe("invite seat purchase validation", () => {expect(purchasedSeatIsReadyForInvitation(summary(4, 0), preview, 100, 101)).toBe(false);expect(purchasedSeatIsReadyForInvitation(summary(5, 0), preview, 100, 101)).toBe(false);});++ it("classifies capacity toast branches without confusing purchase limits", () => {+ expect(seatInvitationCapacityFailure("seat_capacity_full")).toBe("full");+ expect(seatInvitationCapacityFailure("seat_capacity_unavailable")).toBe(+ "unavailable",+ );+ expect(seatInvitationCapacityFailure("seat_capacity_rate_limited")).toBe(+ "rate_limited",+ );+ expect(+ seatInvitationCapacityFailure("seat_purchase_rate_limited"),+ ).toBeUndefined();+ });++ it("allows transient post-purchase invitation failures to retry idempotently", () => {+ expect(+ seatInvitationCanRetryAfterPurchase("seat_capacity_rate_limited"),+ ).toBe(true);+ expect(+ seatInvitationCanRetryAfterPurchase("seat_capacity_unavailable"),+ ).toBe(true);+ expect(seatInvitationCanRetryAfterPurchase("seat_capacity_full")).toBe(+ false,+ );+ });});diff --git a/packages/views/settings/components/seat-invite-purchase.ts b/packages/views/settings/components/seat-invite-purchase.tsindex 11fd457c14..93ddf97f4b 100644--- a/packages/views/settings/components/seat-invite-purchase.ts+++ b/packages/views/settings/components/seat-invite-purchase.ts@@ -4,6 +4,33 @@ import type {WorkspaceSubscriptionSummary,} from "@multica/core/types";+export type SeatInvitationCapacityFailure =+ | "full"+ | "unavailable"+ | "rate_limited";++export function seatInvitationCapacityFailure(+ errorCode: string | undefined,+): SeatInvitationCapacityFailure | undefined {+ switch (errorCode) {+ case "seat_capacity_full":+ return "full";+ case "seat_capacity_unavailable":+ return "unavailable";+ case "seat_capacity_rate_limited":+ return "rate_limited";+ default:+ return undefined;+ }+}++export function seatInvitationCanRetryAfterPurchase(+ errorCode: string | undefined,+): boolean {+ const failure = seatInvitationCapacityFailure(errorCode);+ return failure === "unavailable" || failure === "rate_limited";+}+export function isSingleSeatInvitePreview(preview: WorkspaceSeatPurchasePreview | null | undefined,): preview is WorkspaceSeatPurchasePreview {diff --git a/scripts/helm-config.test.sh b/scripts/helm-config.test.shindex 5277a32592..d48c314030 100644--- a/scripts/helm-config.test.sh+++ b/scripts/helm-config.test.sh@@ -35,8 +35,9 @@ default_config="$(require_rendered_value "$default_config" 'MULTICA_VCS_INTEGRATION_ENABLED: "true"'require_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_POLICY_ENABLED: "false"'require_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_POLICY_URL: ""'-require_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: "false"'-require_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_URL: ""'+reject_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_ENABLED'+reject_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_URL'+require_rendered_value "$default_config" 'MULTICA_CLOUD_URL: ""'require_rendered_value "$default_config" 'MULTICA_TASK_QUEUED_TTL: "2h"'require_rendered_value "$default_config" 'MULTICA_DATABASE_STARTUP_TIMEOUT: "3m"'require_rendered_value "$default_config" 'MULTICA_DATABASE_CONNECT_TIMEOUT: "5s"'@@ -85,13 +86,13 @@ reject_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_SERVICE_TOKEN'capacity_config="$(helm template multica "$CHART_DIR" \--show-only templates/configmap.yaml \- --set backend.config.subscriptionCapacity.enabled=true \- --set-string backend.config.subscriptionCapacity.url=https://multica-cloud.internal \- --set-string backend.config.subscriptionCapacity.timeout=2s+ --set-string backend.config.cloud.url=https://multica-cloud.internal \+ --set-string backend.config.cloud.capacityTimeout=2s)"-require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: "true"'-require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_URL: "https://multica-cloud.internal"'+require_rendered_value "$capacity_config" 'MULTICA_CLOUD_URL: "https://multica-cloud.internal"'require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: "2s"'+reject_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_ENABLED'+reject_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_URL'reject_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN'capacity_alerts="$(diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex ade3007571..f298a04ed9 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -269,8 +269,37 @@ func jwtSecretBootError(jwtSecret, appEnv string) error {return auth.ValidateJWTSecret(jwtSecret)}+var retiredCloudEnvironmentVariables = []string{+ "MULTICA_FLEET_URL",+ "MULTICA_CLOUD_FLEET_URL",+ "MULTICA_CLOUD_FLEET_TIMEOUT",+ "MULTICA_SUBSCRIPTION_CAPACITY_ENABLED",+ "MULTICA_SUBSCRIPTION_CAPACITY_URL",+ "MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED",+}++func retiredCloudEnvironmentError(lookupEnv func(string) (string, bool)) error {+ var configured []string+ for _, name := range retiredCloudEnvironmentVariables {+ if value, exists := lookupEnv(name); exists && strings.TrimSpace(value) != "" {+ configured = append(configured, name)+ }+ }+ if len(configured) == 0 {+ return nil+ }+ return fmt.Errorf(+ "retired Cloud environment variables are still configured: %s; use MULTICA_CLOUD_URL and the current capacity token/timeout settings",+ strings.Join(configured, ", "),+ )+}+func main() {logger.Init()+ if err := retiredCloudEnvironmentError(os.LookupEnv); err != nil {+ slog.Error("refusing to start with retired Cloud configuration", "error", err)+ os.Exit(1)+ }// Warn about missing configurationif err := jwtSecretBootError(os.Getenv("JWT_SECRET"), os.Getenv("APP_ENV")); err != nil {diff --git a/server/cmd/server/main_test.go b/server/cmd/server/main_test.goindex a4fe4b5747..8a8f8c13e1 100644--- a/server/cmd/server/main_test.go+++ b/server/cmd/server/main_test.go@@ -513,3 +513,27 @@ func TestJWTSecretBootError(t *testing.T) {})}}++func TestRetiredCloudEnvironmentError(t *testing.T) {+ tests := []struct {+ name string+ env map[string]string+ want bool+ }{+ {name: "current configuration", env: map[string]string{"MULTICA_CLOUD_URL": "https://cloud.internal"}},+ {name: "empty retired variable", env: map[string]string{"MULTICA_FLEET_URL": ""}},+ {name: "retired fleet URL", env: map[string]string{"MULTICA_FLEET_URL": "https://fleet.internal"}, want: true},+ {name: "retired capacity switch", env: map[string]string{"MULTICA_SUBSCRIPTION_CAPACITY_ENABLED": "false"}, want: true},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := retiredCloudEnvironmentError(func(name string) (string, bool) {+ value, ok := tt.env[name]+ return value, ok+ })+ if (err != nil) != tt.want {+ t.Fatalf("retiredCloudEnvironmentError() = %v, want error %v", err, tt.want)+ }+ })+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex c18b5a6466..4635c8df5d 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -342,6 +342,24 @@ func strictPositiveDurationEnv(name string, fallback time.Duration) (time.Duratireturn value, nil}+func seatCapacityExecutorFromEnv(cloudURL string) seatcapacity.Executor {+ executor, err := seatcapacity.New(seatcapacity.Config{+ BaseURL: cloudURL,+ ServiceToken: os.Getenv("MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN"),+ Timeout: envDuration("MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT", 3*time.Second),+ })+ if err == nil {+ return executor+ }+ // A Cloud-connected deployment with malformed credentials must not+ // silently restore unlimited membership. The fail-closed executor returns+ // 503 until the operator repairs the machine credential; it is deliberately+ // ineligible for recovery-worker startup so queued intents keep their retry+ // budget while configuration is broken.+ slog.Error("subscription seat capacity executor unavailable", "error", err)+ return seatcapacity.NewUnavailable(err)+}+// NewRouterWithOptions builds the fully-configured Chi router and// returns the *handler.Handler it was constructed from. Callers that// need to drive background lifecycle on services attached to the@@ -381,8 +399,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusPublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")), "/"),AppURL: appURLFromEnv(),TrustedProxies: parseTrustedProxies(os.Getenv("MULTICA_TRUSTED_PROXIES")),- CloudRuntimeFleetURL: cloudRuntimeFleetURLFromEnv(),- CloudRuntimeFleetTimeout: envDuration("MULTICA_CLOUD_FLEET_TIMEOUT", 35*time.Second),+ CloudURL: strings.TrimSpace(os.Getenv("MULTICA_CLOUD_URL")),+ CloudTimeout: envDuration("MULTICA_CLOUD_TIMEOUT", 35*time.Second),AttachmentDownloadMode: os.Getenv("ATTACHMENT_DOWNLOAD_MODE"),AttachmentDownloadURLTTL: envDuration("ATTACHMENT_DOWNLOAD_URL_TTL", 30*time.Minute),AttachmentFrameAncestors: origins,@@ -421,27 +439,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush.AutopilotService.Entitlements = entitlementClienth.AutopilotService.QuotaMetrics = opts.BusinessMetrics}- // This is deployment wiring, not a business mode: when connected, admission- // and settlement both follow Cloud's single strict prepaid-seat policy.- capacityEnabled := envBool("MULTICA_SUBSCRIPTION_CAPACITY_ENABLED", false)- capacityClient, capacityErr := seatcapacity.New(seatcapacity.Config{- Enabled: capacityEnabled,- BaseURL: strings.TrimSpace(os.Getenv("MULTICA_SUBSCRIPTION_CAPACITY_URL")),- ServiceToken: os.Getenv("MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN"),- Timeout: envDuration("MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT", 3*time.Second),- })- if capacityErr != nil {- // Explicit enablement with malformed config must not silently restore- // unlimited membership. The fail-closed executor returns 503 until the- // operator repairs the service URL or credential.- slog.Error("subscription seat capacity executor unavailable", "error", capacityErr)- h.SeatCapacity = seatcapacity.NewUnavailable(capacityErr)- } else {- h.SeatCapacity = capacityClient- }+ // Cloud Runtime and strict seat capacity are one managed deployment. Reuse+ // the same base URL so Billing cannot be readable while invitation writes+ // silently skip Cloud's authoritative seat policy.+ h.SeatCapacity = seatCapacityExecutorFromEnv(signupConfig.CloudURL)capacityLocker := seatcapacity.NewWorkspaceLocker(pool)h.SeatCapacityLocker = capacityLocker- if capacityEnabled && h.SeatCapacity.Enabled() {+ if seatcapacity.CanRunWorker(h.SeatCapacity) {h.SeatCapacityWorker = seatcapacity.NewWorker(queries, h.SeatCapacity, capacityLocker, seatcapacity.WorkerConfig{Metrics: opts.SeatCapacityMetrics,})@@ -1193,13 +1197,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush.MembershipCache = auth.NewMembershipCache(rdb)// Cloud PAT verifier: validates mcn_ tokens against Multica Cloud- // Fleet. Returns nil when no Fleet URL is configured — the Auth /+ // Fleet. Returns nil when no Cloud URL is configured — the Auth /// DaemonAuth middlewares treat nil as "mcn_ not supported" and// reject with 401, instead of falling through to mul_/JWT paths.- // Reuses MULTICA_CLOUD_FLEET_URL (the same URL the cloud-runtime- // proxy uses) so a deployment doesn't need a second config knob.+ // Reuses MULTICA_CLOUD_URL (the same URL the cloud-runtime proxy uses) so a+ // deployment has one authoritative multica-cloud connection.cloudPATVerifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{- FleetBaseURL: signupConfig.CloudRuntimeFleetURL,+ FleetBaseURL: signupConfig.CloudURL,Redis: rdb,})@@ -2399,13 +2403,6 @@ func splitAndTrim(s string) []string {return res}-func cloudRuntimeFleetURLFromEnv() string {- if url := strings.TrimSpace(os.Getenv("MULTICA_CLOUD_FLEET_URL")); url != "" {- return url- }- return strings.TrimSpace(os.Getenv("MULTICA_FLEET_URL"))-}-// composioStateSecret resolves the HMAC key for the connect-state. Prefers an// explicit COMPOSIO_STATE_SECRET; otherwise derives a composio-specific key// from JWT_SECRET via SHA-256 so the two signing domains never share andiff --git a/server/cmd/server/router_seat_capacity_test.go b/server/cmd/server/router_seat_capacity_test.gonew file mode 100644index 0000000000..693eb98bf9--- /dev/null+++ b/server/cmd/server/router_seat_capacity_test.go@@ -0,0 +1,28 @@+package main++import (+ "context"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/seatcapacity"+)++func TestSeatCapacityAssemblyFailsClosedWithoutServiceToken(t *testing.T) {+ t.Setenv("MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN", "")+ t.Setenv("MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT", "3s")++ executor := seatCapacityExecutorFromEnv("https://cloud.internal")+ if executor == nil {+ t.Fatal("Cloud-connected router assembled a nil capacity executor")+ }+ if seatcapacity.CanRunWorker(executor) {+ t.Fatal("unavailable capacity executor was eligible for worker startup")+ }+ if _, err := executor.ReserveInvitation(+ context.Background(), uuid.New(), uuid.New(), time.Now().Add(time.Hour),+ ); err == nil {+ t.Fatal("Cloud-connected admission succeeded without a capacity service token")+ }+}diff --git a/server/internal/auth/cloud_pat.go b/server/internal/auth/cloud_pat.goindex e61022f85a..596b73dad9 100644--- a/server/internal/auth/cloud_pat.go+++ b/server/internal/auth/cloud_pat.go@@ -163,7 +163,7 @@ type OwnerLookupFunc func(ctx context.Context, ownerID string) (bool, error)// A nil *CloudPATVerifier is safe — Verify returns// ErrCloudPATNotConfigured. The Auth/DaemonAuth middlewares treat// "verifier nil" the same as "fleet URL empty", so a server with no-// MULTICA_CLOUD_FLEET_URL configured simply rejects mcn_ tokens at+// MULTICA_CLOUD_URL configured simply rejects mcn_ tokens at// the prefix branch instead of nil-derefing.type CloudPATVerifier struct {baseURL stringdiff --git a/server/internal/auth/cloud_pat_test.go b/server/internal/auth/cloud_pat_test.goindex ff1048b65e..f902347042 100644--- a/server/internal/auth/cloud_pat_test.go+++ b/server/internal/auth/cloud_pat_test.go@@ -69,7 +69,7 @@ func newFleetServer(t *testing.T, opts fleetServerOpts) *httptest.Server {}// TestCloudPATVerifier_NilSafe pins the nil-receiver contract: a server-// without MULTICA_CLOUD_FLEET_URL configured constructs nil here, and+// without MULTICA_CLOUD_URL configured constructs nil here, and// the middleware nil-checks before calling. Verify must still return a// classifiable error so the middleware emits a deterministic 401 instead// of a nil-deref panic.diff --git a/server/internal/cloudruntime/client.go b/server/internal/cloudruntime/client.goindex 11423d29d6..23042c6a9c 100644--- a/server/internal/cloudruntime/client.go+++ b/server/internal/cloudruntime/client.go@@ -18,8 +18,8 @@ const ()var (- ErrDisabled = errors.New("cloud runtime fleet URL is not configured")- ErrInvalidBaseURL = errors.New("cloud runtime fleet URL is invalid")+ ErrDisabled = errors.New("multica-cloud URL is not configured")+ ErrInvalidBaseURL = errors.New("multica-cloud URL is invalid"))// RequestRecorder is the small interface the client uses to instrument everydiff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 0fd7a252ac..4cf31b692c 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -108,11 +108,11 @@ type Config struct {// webhook limiter from being bypassed by a spoofed XFF on deployments// without a header-stripping reverse proxy in front.TrustedProxies []netip.Prefix- // CloudRuntimeFleetURL enables the SaaS-only remote Fleet adapter when set.- // Empty keeps self-hosted deployments explicit: cloud runtime endpoints- // return 503 instead of attempting to dial a hard-coded private service.- CloudRuntimeFleetURL string- CloudRuntimeFleetTimeout time.Duration+ // CloudURL enables the SaaS-only multica-cloud connection when set. Empty+ // keeps self-hosted deployments explicit: Cloud endpoints return 503 instead+ // of attempting to dial a hard-coded private service.+ CloudURL string+ CloudTimeout time.DurationAttachmentDownloadMode stringAttachmentDownloadURLTTL time.Duration// AttachmentFrameAncestors are trusted browser origins allowed to embed@@ -474,8 +474,8 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventWebhookAbsoluteIPRateLimiter: NewMemoryWebhookAbsoluteIPRateLimiter(DefaultWebhookAbsoluteIPRateLimit()),InvitationRateLimiters: NewMemoryInvitationRateLimiters(DefaultInvitationRateLimits()),CloudRuntime: cloudruntime.NewClient(cloudruntime.Config{- BaseURL: cfg.CloudRuntimeFleetURL,- Timeout: cfg.CloudRuntimeFleetTimeout,+ BaseURL: cfg.CloudURL,+ Timeout: cfg.CloudTimeout,}),LLM: llmClient,cfg: cfg,diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.goindex 088e683a99..64d9d876c9 100644--- a/server/internal/handler/invitation.go+++ b/server/internal/handler/invitation.go@@ -134,28 +134,36 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {if existingUser.ID.Valid {inviteeUserID = existingUser.ID}+ admission, ok := h.checkInvitationAdmission(+ w,+ r,+ uuidToString(requester.UserID),+ uuidToString(requester.WorkspaceID),+ email,+ )+ if !ok {+ return+ }invitationID := uuid.New()expiresAt := time.Now().Add(7 * 24 * time.Hour)if err := h.reserveInvitationCapacity(r.Context(), uuid.UUID(requester.WorkspaceID.Bytes), invitationID, expiresAt); err != nil {+ if isPersistentSeatCapacityAdmissionRejection(err) {+ // Full and overcommitted workspaces cannot admit another member until+ // their durable capacity facts change. Charge repeated attempts to the+ // actor budget so this endpoint cannot hammer the capacity service,+ // while preserving workspace and recipient budgets for a later valid+ // invitation.+ h.consumeInvitationActorAdmission(r, admission)+ }writeSeatCapacityError(w, err)return}- // Consume rate-limit budgets only after capacity is secured. A request that- // must purchase a seat can then retry without spending the same invitation- // budgets twice. If admission rejects, the durable capacity intent releases- // the hold immediately or through the recovery worker.- if !h.admitInvitation(- w,- r,- uuidToString(requester.UserID),- uuidToString(requester.WorkspaceID),- email,- ) {- h.compensateCapacityIntent(r.Context(), invitationID)- return- }+ // The non-consuming abuse checks run before Cloud. Spend all budgets only+ // after Cloud has secured capacity. Persistent capacity rejections spend the+ // actor budget only in the branch above; transient failures spend none.+ h.consumeInvitationAdmission(r, admission)createParams := db.CreateInvitationParams{ID: uuidToPG(invitationID), WorkspaceID: requester.WorkspaceID, InviterID: requester.UserID,diff --git a/server/internal/handler/invitation_rate_limiter.go b/server/internal/handler/invitation_rate_limiter.goindex bfaddaa083..91bc5b317a 100644--- a/server/internal/handler/invitation_rate_limiter.go+++ b/server/internal/handler/invitation_rate_limiter.go@@ -42,6 +42,14 @@ type InvitationRateLimiters struct {Recipient SlidingWindowRateLimiter}+type invitationRateLimitDimension string++const (+ invitationRateLimitActor invitationRateLimitDimension = "actor"+ invitationRateLimitWorkspace invitationRateLimitDimension = "workspace"+ invitationRateLimitRecipient invitationRateLimitDimension = "recipient"+)+// NewMemoryInvitationRateLimiters builds single-process gates for local and// Redis-less deployments.func NewMemoryInvitationRateLimiters(limits InvitationRateLimits) InvitationRateLimiters {@@ -63,9 +71,13 @@ func NewRedisInvitationRateLimiters(rdb *redis.Client, limits InvitationRateLimi}type invitationRateLimitGate struct {- name string- key string- limiter SlidingWindowRateLimiter+ dimension invitationRateLimitDimension+ key string+ limiter SlidingWindowRateLimiter+}++type invitationAdmission struct {+ gates []invitationRateLimitGate}func invitationRecipientKey(email string) string {@@ -74,11 +86,11 @@ func invitationRecipientKey(email string) string {return hex.EncodeToString(digest[:])}-func (h *Handler) admitInvitation(w http.ResponseWriter, r *http.Request, actorID, workspaceID, email string) bool {+func (h *Handler) checkInvitationAdmission(w http.ResponseWriter, r *http.Request, actorID, workspaceID, email string) (*invitationAdmission, bool) {gates := []invitationRateLimitGate{- {name: "actor", key: actorID, limiter: h.InvitationRateLimiters.Actor},- {name: "workspace", key: workspaceID, limiter: h.InvitationRateLimiters.Workspace},- {name: "recipient", key: invitationRecipientKey(email), limiter: h.InvitationRateLimiters.Recipient},+ {dimension: invitationRateLimitActor, key: actorID, limiter: h.InvitationRateLimiters.Actor},+ {dimension: invitationRateLimitWorkspace, key: workspaceID, limiter: h.InvitationRateLimiters.Workspace},+ {dimension: invitationRateLimitRecipient, key: invitationRecipientKey(email), limiter: h.InvitationRateLimiters.Recipient},}var checkErr error@@ -91,7 +103,7 @@ func (h *Handler) admitInvitation(w http.ResponseWriter, r *http.Request, actorIif checkErr == nil {checkErr = err}- checkErrorGates = append(checkErrorGates, gate.name)+ checkErrorGates = append(checkErrorGates, string(gate.dimension))continue}if allowed {@@ -107,16 +119,40 @@ func (h *Handler) admitInvitation(w http.ResponseWriter, r *http.Request, actorIif checkErr != nil {slog.Error("invitation rate limiter unavailable", append(logger.RequestAttrs(r), "gates", strings.Join(checkErrorGates, ","), "error", checkErr)...)writeInvitationLimiterUnavailable(w)- return false+ return nil, false}if len(deniedGates) > 0 {for _, gate := range deniedGates {- h.Metrics.RecordEmailRateLimited("workspace_invitation", gate.name)+ h.Metrics.RecordEmailRateLimited("workspace_invitation", string(gate.dimension))}writeInvitationRateLimited(w, retryAfter)- return false+ return nil, false}+ return &invitationAdmission{gates: gates}, true+}++func (h *Handler) consumeInvitationAdmission(r *http.Request, admission *invitationAdmission) {+ if admission == nil {+ return+ }+ h.consumeInvitationGates(r, admission.gates)+}++// consumeInvitationActorAdmission charges persistent capacity rejections to+// the caller without spending the shared workspace or recipient email budgets.+func (h *Handler) consumeInvitationActorAdmission(r *http.Request, admission *invitationAdmission) {+ if admission == nil {+ return+ }+ for _, gate := range admission.gates {+ if gate.dimension == invitationRateLimitActor {+ h.consumeInvitationGates(r, []invitationRateLimitGate{gate})+ return+ }+ }+}+func (h *Handler) consumeInvitationGates(r *http.Request, gates []invitationRateLimitGate) {for _, gate := range gates {allowed, err := slidingWindowLimiterAllow(r.Context(), gate.limiter, gate.key)if err != nil {@@ -124,7 +160,7 @@ func (h *Handler) admitInvitation(w http.ResponseWriter, r *http.Request, actorI// the narrow Check-to-Allow window. Admit this in-flight request rather// than return an error after an earlier gate may have consumed. A// sustained backend failure is caught by Phase 1 on later requests.- slog.Warn("invitation rate limiter consume failed after successful checks; allowing bounded overshoot", append(logger.RequestAttrs(r), "gate", gate.name, "error", err)...)+ slog.Warn("invitation rate limiter consume failed after successful checks; allowing bounded overshoot", append(logger.RequestAttrs(r), "gate", string(gate.dimension), "error", err)...)continue}if !allowed {@@ -134,7 +170,6 @@ func (h *Handler) admitInvitation(w http.ResponseWriter, r *http.Request, actorIcontinue}}- return true}func writeInvitationLimiterUnavailable(w http.ResponseWriter) {diff --git a/server/internal/handler/invitation_test.go b/server/internal/handler/invitation_test.goindex ddecf3bd34..0643c87467 100644--- a/server/internal/handler/invitation_test.go+++ b/server/internal/handler/invitation_test.go@@ -33,7 +33,8 @@ type stubSeatCapacity struct {consumeErr error}-func (s *stubSeatCapacity) Enabled() bool { return true }+func (*stubSeatCapacity) RecoveryAvailable() bool { return true }+func (s *stubSeatCapacity) ReserveInvitation(context.Context, uuid.UUID, uuid.UUID, time.Time) (seatcapacity.Decision, error) {s.reserveCalls++return s.reserveDecision, s.reserveErr@@ -212,6 +213,10 @@ func TestCreateInvitation_BlocksWhenPurchasedCapacityIsFull(t *testing.T) {Managed: true, Allowed: false, Reason: "capacity_full",}}useSeatCapacity(t, capacity)+ actor := &stubInvitationRateLimiter{allowed: true}+ workspace := &stubInvitationRateLimiter{allowed: true}+ recipient := &stubInvitationRateLimiter{allowed: true}+ useInvitationRateLimiters(t, InvitationRateLimiters{Actor: actor, Workspace: workspace, Recipient: recipient})req := newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members", CreateMemberRequest{Email: "[email protected]", Role: "member",@@ -235,6 +240,23 @@ func TestCreateInvitation_BlocksWhenPurchasedCapacityIsFull(t *testing.T) {if capacity.reserveCalls != 1 {t.Fatalf("reserve calls = %d, want 1", capacity.reserveCalls)}+ for name, calls := range map[string]int{+ "actor checks": len(actor.checkKeys), "workspace checks": len(workspace.checkKeys), "recipient checks": len(recipient.checkKeys),+ } {+ if calls != 1 {+ t.Errorf("%s = %d, want 1", name, calls)+ }+ }+ if calls := len(actor.allowKeys); calls != 1 {+ t.Errorf("actor allows = %d, want 1 when persistent capacity_full is rejected", calls)+ }+ for name, calls := range map[string]int{+ "workspace allows": len(workspace.allowKeys), "recipient allows": len(recipient.allowKeys),+ } {+ if calls != 0 {+ t.Errorf("%s = %d, want 0 so a later purchased-seat invitation keeps shared budget", name, calls)+ }+ }var invitationCount, outboxCount intif err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM workspace_invitation WHERE workspace_id = $1 AND invitee_email = $2`, parseUUID(testWorkspaceID), "[email protected]").Scan(&invitationCount); err != nil {t.Fatal(err)@@ -254,6 +276,10 @@ func TestCreateInvitation_BlocksOvercommittedCapacityWithoutOfferingSingleSeatSeCode: "capacity_overcommitted",}}useSeatCapacity(t, capacity)+ actor := &stubInvitationRateLimiter{allowed: true}+ workspace := &stubInvitationRateLimiter{allowed: true}+ recipient := &stubInvitationRateLimiter{allowed: true}+ useInvitationRateLimiters(t, InvitationRateLimiters{Actor: actor, Workspace: workspace, Recipient: recipient})req := newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members", CreateMemberRequest{Email: "[email protected]", Role: "member",@@ -277,6 +303,68 @@ func TestCreateInvitation_BlocksOvercommittedCapacityWithoutOfferingSingleSeatSeif capacity.reserveCalls != 1 {t.Fatalf("reserve calls = %d, want 1", capacity.reserveCalls)}+ if calls := len(actor.allowKeys); calls != 1 {+ t.Errorf("actor allows = %d, want 1 when persistent capacity_overcommitted is rejected", calls)+ }+ for name, calls := range map[string]int{+ "workspace allows": len(workspace.allowKeys), "recipient allows": len(recipient.allowKeys),+ } {+ if calls != 0 {+ t.Errorf("%s = %d, want 0 while capacity remains overcommitted", name, calls)+ }+ }+}++func TestCreateInvitation_MapsCloudCapacityRateLimitWithoutConsumingInvitationBudget(t *testing.T) {+ clearInvitationsForTestWorkspace(t)+ if _, err := testPool.Exec(context.Background(), `DELETE FROM seat_capacity_outbox WHERE workspace_id = $1`, parseUUID(testWorkspaceID)); err != nil {+ t.Fatalf("clear capacity outbox: %v", err)+ }+ capacity := &stubSeatCapacity{reserveErr: &seatcapacity.HTTPError{+ StatusCode: http.StatusTooManyRequests,+ RetryAfter: 3 * time.Second,+ }}+ useSeatCapacity(t, capacity)+ actor := &stubInvitationRateLimiter{allowed: true}+ workspace := &stubInvitationRateLimiter{allowed: true}+ recipient := &stubInvitationRateLimiter{allowed: true}+ useInvitationRateLimiters(t, InvitationRateLimiters{Actor: actor, Workspace: workspace, Recipient: recipient})++ req := newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members", CreateMemberRequest{+ Email: "[email protected]", Role: "member",+ })+ req = withURLParam(req, "id", testWorkspaceID)+ rec := httptest.NewRecorder()+ testHandler.CreateInvitation(rec, req)++ if rec.Code != http.StatusTooManyRequests {+ t.Fatalf("status = %d, want 429: %s", rec.Code, rec.Body.String())+ }+ if rec.Header().Get("Retry-After") != "3" || rec.Header().Get("Cache-Control") != "no-store" {+ t.Fatalf("unexpected retry/cache headers: %v", rec.Header())+ }+ var body struct {+ Code string `json:"code"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {+ t.Fatal(err)+ }+ if body.Code != "seat_capacity_rate_limited" {+ t.Fatalf("code = %q, want seat_capacity_rate_limited", body.Code)+ }+ if capacity.reserveCalls != 1 || capacity.releaseCalls != 0 {+ t.Fatalf("capacity calls reserve=%d release=%d, want 1/0", capacity.reserveCalls, capacity.releaseCalls)+ }+ for name, calls := range map[string]int{+ "actor allows": len(actor.allowKeys), "workspace allows": len(workspace.allowKeys), "recipient allows": len(recipient.allowKeys),+ } {+ if calls != 0 {+ t.Errorf("%s = %d, want 0 after Cloud rate limit", name, calls)+ }+ }+ if intents := dbfx.Count(t, `SELECT count(*) FROM seat_capacity_outbox WHERE workspace_id = $1`, parseUUID(testWorkspaceID)); intents != 0 {+ t.Fatalf("capacity intents = %d, want 0 after Cloud rate limit", intents)+ }}func TestCreateInvitation_CompensatesCapacityWhenCommitRollsBack(t *testing.T) {@@ -379,7 +467,7 @@ func TestCreateInvitation_AllowsAfterExpiry(t *testing.T) {}}-func TestCreateInvitation_RateLimitChecksEveryGateAfterCapacityReservation(t *testing.T) {+func TestCreateInvitation_RateLimitChecksEveryGateBeforeCapacityReservation(t *testing.T) {clearInvitationsForTestWorkspace(t)if _, err := testPool.Exec(context.Background(), `DELETE FROM seat_capacity_outbox WHERE workspace_id = $1`, parseUUID(testWorkspaceID)); err != nil {t.Fatalf("clear capacity outbox: %v", err)@@ -460,8 +548,8 @@ func TestCreateInvitation_RateLimitChecksEveryGateAfterCapacityReservation(t *teif pendingCount != 0 {t.Fatalf("pending invitation count = %d, want 0 after rate limit rejection", pendingCount)}- if capacity.reserveCalls != 1 || capacity.releaseCalls != 1 {- t.Fatalf("capacity calls reserve=%d release=%d, want 1/1", capacity.reserveCalls, capacity.releaseCalls)+ if capacity.reserveCalls != 0 || capacity.releaseCalls != 0 {+ t.Fatalf("capacity calls reserve=%d release=%d, want 0/0", capacity.reserveCalls, capacity.releaseCalls)}if intents := dbfx.Count(t, `SELECT count(*) FROM seat_capacity_outbox WHERE workspace_id = $1`, parseUUID(testWorkspaceID)); intents != 0 {t.Fatalf("capacity intents = %d, want 0 after compensated rate-limit rejection", intents)@@ -533,7 +621,7 @@ func TestCreateInvitation_RateLimiterFailureReturnsServiceUnavailable(t *testing}}-func TestAdmitInvitation_RejectedActorDoesNotConsumeWorkspaceBudget(t *testing.T) {+func TestInvitationAdmission_RejectedActorDoesNotConsumeWorkspaceBudget(t *testing.T) {limits := InvitationRateLimits{Actor: SlidingWindowRateLimit{Limit: 1, Window: time.Hour},Workspace: SlidingWindowRateLimit{Limit: 2, Window: time.Hour},@@ -544,7 +632,11 @@ func TestAdmitInvitation_RejectedActorDoesNotConsumeWorkspaceBudget(t *testing.Tadmit := func(actorID, email string) bool {req := httptest.NewRequest(http.MethodPost, "/api/workspaces/workspace-a/members", nil)- return h.admitInvitation(httptest.NewRecorder(), req, actorID, "workspace-a", email)+ admission, ok := h.checkInvitationAdmission(httptest.NewRecorder(), req, actorID, "workspace-a", email)+ if ok {+ h.consumeInvitationAdmission(req, admission)+ }+ return ok}if !admit("actor-a", "[email protected]") {@@ -560,7 +652,7 @@ func TestAdmitInvitation_RejectedActorDoesNotConsumeWorkspaceBudget(t *testing.T}}-func TestAdmitInvitation_RejectedActorDoesNotConsumeRecipientBudget(t *testing.T) {+func TestInvitationAdmission_RejectedActorDoesNotConsumeRecipientBudget(t *testing.T) {limits := InvitationRateLimits{Actor: SlidingWindowRateLimit{Limit: 1, Window: time.Hour},Workspace: SlidingWindowRateLimit{Limit: 10, Window: time.Hour},@@ -571,7 +663,11 @@ func TestAdmitInvitation_RejectedActorDoesNotConsumeRecipientBudget(t *testing.Tadmit := func(actorID, workspaceID string) bool {req := httptest.NewRequest(http.MethodPost, "/api/workspaces/"+workspaceID+"/members", nil)- return h.admitInvitation(httptest.NewRecorder(), req, actorID, workspaceID, "[email protected]")+ admission, ok := h.checkInvitationAdmission(httptest.NewRecorder(), req, actorID, workspaceID, "[email protected]")+ if ok {+ h.consumeInvitationAdmission(req, admission)+ }+ return ok}if !admit("actor-a", "workspace-a") {@@ -585,7 +681,7 @@ func TestAdmitInvitation_RejectedActorDoesNotConsumeRecipientBudget(t *testing.T}}-func TestAdmitInvitation_AllowsBoundedOvershootWhenGateFillsAfterCheck(t *testing.T) {+func TestInvitationAdmission_AllowsBoundedOvershootWhenGateFillsAfterCheck(t *testing.T) {allowDenied := falseactor := &stubInvitationRateLimiter{allowed: true, allowResult: &allowDenied}workspace := &stubInvitationRateLimiter{allowed: true}@@ -594,9 +690,11 @@ func TestAdmitInvitation_AllowsBoundedOvershootWhenGateFillsAfterCheck(t *testinh.InvitationRateLimiters = InvitationRateLimiters{Actor: actor, Workspace: workspace, Recipient: recipient}req := httptest.NewRequest(http.MethodPost, "/api/workspaces/workspace-a/members", nil)- if !h.admitInvitation(httptest.NewRecorder(), req, "actor-a", "workspace-a", "[email protected]") {- t.Fatal("concurrent fill rejected after a different gate may already have consumed")+ admission, ok := h.checkInvitationAdmission(httptest.NewRecorder(), req, "actor-a", "workspace-a", "[email protected]")+ if !ok {+ t.Fatal("invitation was rejected during the non-consuming check")}+ h.consumeInvitationAdmission(req, admission)for name, calls := range map[string]int{"actor checks": len(actor.checkKeys), "workspace checks": len(workspace.checkKeys), "recipient checks": len(recipient.checkKeys),"actor allows": len(actor.allowKeys), "workspace allows": len(workspace.allowKeys), "recipient allows": len(recipient.allowKeys),@@ -607,7 +705,7 @@ func TestAdmitInvitation_AllowsBoundedOvershootWhenGateFillsAfterCheck(t *testin}}-func TestAdmitInvitation_AllowsBoundedOvershootWhenBackendFailsAfterChecks(t *testing.T) {+func TestInvitationAdmission_AllowsBoundedOvershootWhenBackendFailsAfterChecks(t *testing.T) {actor := &stubInvitationRateLimiter{allowed: true}workspace := &stubInvitationRateLimiter{allowed: true, allowErr: errors.New("redis unavailable")}recipient := &stubInvitationRateLimiter{allowed: true}@@ -616,9 +714,11 @@ func TestAdmitInvitation_AllowsBoundedOvershootWhenBackendFailsAfterChecks(t *tereq := httptest.NewRequest(http.MethodPost, "/api/workspaces/workspace-a/members", nil)rec := httptest.NewRecorder()- if !h.admitInvitation(rec, req, "actor-a", "workspace-a", "[email protected]") {- t.Fatalf("backend failed after successful checks: request was rejected with %d: %s", rec.Code, rec.Body.String())+ admission, ok := h.checkInvitationAdmission(rec, req, "actor-a", "workspace-a", "[email protected]")+ if !ok {+ t.Fatalf("invitation was rejected during successful checks with %d: %s", rec.Code, rec.Body.String())}+ h.consumeInvitationAdmission(req, admission)if rec.Body.Len() != 0 || rec.Header().Get("Retry-After") != "" {t.Fatalf("backend failure after checks wrote an error response: headers=%v body=%s", rec.Header(), rec.Body.String())}diff --git a/server/internal/handler/seat_capacity.go b/server/internal/handler/seat_capacity.goindex 5b2e043cd2..a6100fb7f5 100644--- a/server/internal/handler/seat_capacity.go+++ b/server/internal/handler/seat_capacity.go@@ -20,10 +20,14 @@ var (errSeatCapacityUnavailable = errors.New("seat capacity service is unavailable"))+func isPersistentSeatCapacityAdmissionRejection(err error) bool {+ return errors.Is(err, errSeatCapacityFull) || errors.Is(err, errSeatCapacityOvercommitted)+}+const seatCapacityWorkspaceLockWait = 2 * time.Secondfunc (h *Handler) seatCapacityEnabled() bool {- return h != nil && h.SeatCapacity != nil && h.SeatCapacity.Enabled()+ return h != nil && h.SeatCapacity != nil}func (h *Handler) lockSeatCapacityWorkspace(ctx context.Context, workspaceID uuid.UUID) (*db.Queries, func(), error) {@@ -69,6 +73,12 @@ func (h *Handler) reserveInvitationCapacity(ctx context.Context, workspaceID, in}decision, err := h.SeatCapacity.ReserveInvitation(ctx, workspaceID, invitationID, expiresAt)if err != nil {+ if seatcapacity.IsRateLimited(err) {+ if deleteErr := deleteCapacityIntentForAction(ctx, q, invitationID, seatcapacity.ActionReserveInvitation); deleteErr != nil {+ return fmt.Errorf("discard rate-limited invitation capacity intent: %w", deleteErr)+ }+ return fmt.Errorf("reserve invitation capacity: %w", err)+ }if seatcapacity.IsCapacityOvercommitted(err) {if deleteErr := deleteCapacityIntentForAction(ctx, q, invitationID, seatcapacity.ActionReserveInvitation); deleteErr != nil {return fmt.Errorf("discard overcommitted invitation capacity intent: %w", deleteErr)@@ -117,6 +127,9 @@ func (h *Handler) beginCapacityConsume(ctx context.Context, workspaceID, token,}decision, err := h.SeatCapacity.Consume(ctx, workspaceID, token)if err != nil {+ if seatcapacity.IsRateLimited(err) {+ return false, fmt.Errorf("consume invitation capacity: %w", err)+ }return false, fmt.Errorf("%w: %v", errSeatCapacityUnavailable, err)}if !decision.Managed {@@ -157,6 +170,12 @@ func (h *Handler) beginShareJoinCapacity(ctx context.Context, workspaceID, sharetoken := uuid.UUID(intent.OperationToken.Bytes)decision, err := h.SeatCapacity.ClaimShareJoin(ctx, workspaceID, token)if err != nil {+ if seatcapacity.IsRateLimited(err) {+ if deleteErr := deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionClaimShareJoin); deleteErr != nil {+ return uuid.Nil, fmt.Errorf("discard rate-limited share-join capacity intent: %w", deleteErr)+ }+ return uuid.Nil, fmt.Errorf("claim share-join capacity: %w", err)+ }if seatcapacity.IsCapacityOvercommitted(err) {if deleteErr := deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionClaimShareJoin); deleteErr != nil {return uuid.Nil, fmt.Errorf("discard overcommitted share-join capacity intent: %w", deleteErr)@@ -332,6 +351,15 @@ func recordCapacityFailure(ctx context.Context, q *db.Queries, token uuid.UUID,func writeSeatCapacityError(w http.ResponseWriter, err error) {switch {+ case seatcapacity.IsRateLimited(err):+ retryAfter := seatcapacity.RateLimitRetryAfter(err)+ if retryAfter < time.Second {+ retryAfter = time.Second+ }+ retryAfterSeconds := int64((retryAfter + time.Second - 1) / time.Second)+ w.Header().Set("Cache-Control", "no-store")+ w.Header().Set("Retry-After", fmt.Sprintf("%d", retryAfterSeconds))+ writeErrorCode(w, http.StatusTooManyRequests, "seat_capacity_rate_limited", "Member capacity is busy. Please retry shortly.")case errors.Is(err, errSeatCapacityOvercommitted):writeErrorCode(w, http.StatusConflict, "seat_capacity_overcommitted", "Workspace members exceed purchased seats. Add enough seats or remove members before adding another member.")case errors.Is(err, errSeatCapacityFull):diff --git a/server/internal/handler/share_link_test.go b/server/internal/handler/share_link_test.goindex 65e7560199..50661f5a17 100644--- a/server/internal/handler/share_link_test.go+++ b/server/internal/handler/share_link_test.go@@ -27,7 +27,8 @@ type shareJoinCapacityStub struct {claimGate *sync.WaitGroup}-func (s *shareJoinCapacityStub) Enabled() bool { return true }+func (*shareJoinCapacityStub) RecoveryAvailable() bool { return true }+func (s *shareJoinCapacityStub) ReserveInvitation(context.Context, uuid.UUID, uuid.UUID, time.Time) (seatcapacity.Decision, error) {return seatcapacity.Decision{Managed: true, Allowed: true}, nil}diff --git a/server/internal/middleware/auth.go b/server/internal/middleware/auth.goindex d447a50a59..ac028ffeb6 100644--- a/server/internal/middleware/auth.go+++ b/server/internal/middleware/auth.go@@ -121,7 +121,7 @@ func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATV// personal_access_tokens table for this prefix; an mcn_// string is not a valid mul_ value, so falling through// would just be a redundant DB miss. When the verifier- // is unconfigured (no MULTICA_CLOUD_FLEET_URL) we reject+ // is unconfigured (no MULTICA_CLOUD_URL) we reject// at this branch rather than treating the token as a// JWT/PAT — failing closed avoids a misconfigured prod// silently downgrading auth.diff --git a/server/internal/middleware/auth_test.go b/server/internal/middleware/auth_test.goindex 1c6575956c..b6f474d70e 100644--- a/server/internal/middleware/auth_test.go+++ b/server/internal/middleware/auth_test.go@@ -343,7 +343,7 @@ func TestAuth_PATCacheHit(t *testing.T) {}// TestAuth_MCN_NoVerifierConfigured pins the same fail-closed branch-// as the daemon side: with no MULTICA_CLOUD_FLEET_URL configured, an+// as the daemon side: with no MULTICA_CLOUD_URL configured, an// mcn_ bearer token must be rejected with 401 at the prefix branch.// We don't fall through — an mcn_ string can't be a valid mul_ PAT or// JWT, so any fall-through would be wasted work.diff --git a/server/internal/middleware/daemon_auth_test.go b/server/internal/middleware/daemon_auth_test.goindex cd4b8573d2..3c7657c8b9 100644--- a/server/internal/middleware/daemon_auth_test.go+++ b/server/internal/middleware/daemon_auth_test.go@@ -165,7 +165,7 @@ func TestDaemonAuth_InvalidMDT_NilQueries(t *testing.T) {}// TestDaemonAuth_MCN_NoVerifierConfigured pins the fail-closed-// behaviour when MULTICA_CLOUD_FLEET_URL is empty: an mcn_ token MUST+// behaviour when MULTICA_CLOUD_URL is empty: an mcn_ token MUST// be rejected at the prefix branch with 401, not silently fall// through to the mul_/JWT paths (an mcn_ string would never match a// valid PAT or JWT, but failing closed makes the contract explicit).diff --git a/server/internal/seatcapacity/client.go b/server/internal/seatcapacity/client.goindex 176aec4a29..a980010a13 100644--- a/server/internal/seatcapacity/client.go+++ b/server/internal/seatcapacity/client.go@@ -11,6 +11,7 @@ import ("io""net/http""net/url"+ "strconv""strings""time"@@ -18,16 +19,19 @@ import ()const (- defaultTimeout = 3 * time.Second- maxTimeout = 5 * time.Second- maxResponseBodySize = 64 << 10- minServiceTokenSize = 32+ defaultTimeout = 3 * time.Second+ maxTimeout = 5 * time.Second+ maxResponseBodySize = 64 << 10+ minServiceTokenSize = 32+ rateLimitScopeHeader = "X-Multica-RateLimit-Scope"++ RateLimitScopeGlobal = "global"+ RateLimitScopeWorkspace = "workspace")var ErrInvalidConfig = errors.New("seat capacity: invalid configuration")type Config struct {- Enabled boolBaseURL stringServiceToken stringTimeout time.Duration@@ -59,7 +63,11 @@ type Decision struct {}type Executor interface {- Enabled() bool+ // RecoveryAvailable reports whether this executor may settle durable+ // product-side intents. Implementations and decorators must forward this+ // capability explicitly, so an unavailable executor cannot be hidden by a+ // wrapper and accidentally start the recovery worker.+ RecoveryAvailable() boolReserveInvitation(context.Context, uuid.UUID, uuid.UUID, time.Time) (Decision, error)ClaimShareJoin(context.Context, uuid.UUID, uuid.UUID) (Decision, error)Consume(context.Context, uuid.UUID, uuid.UUID) (Decision, error)@@ -71,11 +79,17 @@ type Executor interface {type unavailableExecutor struct{ err error }-// NewUnavailable preserves fail-closed behavior when an operator explicitly-// enabled managed capacity with invalid configuration.+// NewUnavailable preserves fail-closed behavior when a Cloud-connected+// deployment has invalid capacity credentials.func NewUnavailable(err error) Executor { return &unavailableExecutor{err: err} }-func (u *unavailableExecutor) Enabled() bool { return true }+// CanRunWorker reports whether executor can safely settle durable intents.+func CanRunWorker(executor Executor) bool {+ return executor != nil && executor.RecoveryAvailable()+}++func (*unavailableExecutor) RecoveryAvailable() bool { return false }+func (u *unavailableExecutor) fail() (Decision, error) {return Decision{}, fmt.Errorf("seat capacity executor unavailable: %w", u.err)}@@ -102,7 +116,6 @@ func (u *unavailableExecutor) GetOperation(context.Context, uuid.UUID, uuid.UUID}type Client struct {- enabled boolbaseURL *url.URLserviceToken stringtimeout time.Duration@@ -111,11 +124,16 @@ type Client struct {var _ Executor = (*Client)(nil)-func New(cfg Config) (*Client, error) {- if !cfg.Enabled {- return &Client{}, nil- }+func (*Client) RecoveryAvailable() bool { return true }++func New(cfg Config) (Executor, error) {rawURL := strings.TrimRight(strings.TrimSpace(cfg.BaseURL), "/")+ if rawURL == "" && cfg.ServiceToken == "" {+ return nil, nil+ }+ if rawURL == "" {+ return nil, fmt.Errorf("%w: base URL is required when a service token is configured", ErrInvalidConfig)+ }baseURL, err := url.Parse(rawURL)if err != nil || (baseURL.Scheme != "http" && baseURL.Scheme != "https") || baseURL.Host == "" ||baseURL.User != nil || baseURL.RawQuery != "" || baseURL.Fragment != "" {@@ -139,7 +157,6 @@ func New(cfg Config) (*Client, error) {// The machine credential must never cross an HTTP redirect boundary.httpClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }return &Client{- enabled: true,baseURL: baseURL,serviceToken: cfg.ServiceToken,timeout: timeout,@@ -147,8 +164,6 @@ func New(cfg Config) (*Client, error) {}, nil}-func (c *Client) Enabled() bool { return c != nil && c.enabled }-func (c *Client) ReserveInvitation(ctx context.Context, workspaceID, invitationID uuid.UUID, expiresAt time.Time) (Decision, error) {return c.post(ctx, workspaceID, "reserve", map[string]any{"token": invitationID, "kind": "invitation", "subject_id": invitationID, "expires_at": expiresAt,@@ -190,9 +205,6 @@ func (c *Client) post(ctx context.Context, workspaceID uuid.UUID, action string,}func (c *Client) do(ctx context.Context, method string, workspaceID uuid.UUID, suffix string, body []byte) (Decision, error) {- if !c.Enabled() {- return Decision{Allowed: true}, nil- }if workspaceID == uuid.Nil {return Decision{}, fmt.Errorf("seat capacity: workspace ID is required")}@@ -232,7 +244,13 @@ func (c *Client) do(ctx context.Context, method string, workspaceID uuid.UUID, sCode string `json:"code"`}_ = json.Unmarshal(payload, &remote)- return Decision{}, &HTTPError{StatusCode: resp.StatusCode, Code: remote.Code, Message: remote.Error}+ return Decision{}, &HTTPError{+ StatusCode: resp.StatusCode,+ Code: remote.Code,+ Message: remote.Error,+ RetryAfter: retryAfterDuration(resp.Header.Get("Retry-After")),+ RateLimitScope: normalizedRateLimitScope(resp.Header.Get(rateLimitScopeHeader)),+ }}var out Decisionif err := json.Unmarshal(payload, &out); err != nil {@@ -242,9 +260,11 @@ func (c *Client) do(ctx context.Context, method string, workspaceID uuid.UUID, s}type HTTPError struct {- StatusCode int- Code string- Message string+ StatusCode int+ Code string+ Message string+ RetryAfter time.Duration+ RateLimitScope string}func (e *HTTPError) Error() string {@@ -263,3 +283,64 @@ func IsCapacityOvercommitted(err error) bool {var remote *HTTPErrorreturn errors.As(err, &remote) && remote.StatusCode == http.StatusConflict && remote.Code == "capacity_overcommitted"}++func IsRateLimited(err error) bool {+ var remote *HTTPError+ // A proxy, ingress, or WAF may generate the 429 before the request reaches+ // Cloud and therefore cannot attach Cloud's JSON error code. HTTP 429 is+ // sufficient to preserve the retryable semantics and Retry-After value.+ return errors.As(err, &remote) && remote.StatusCode == http.StatusTooManyRequests+}++func RateLimitRetryAfter(err error) time.Duration {+ var remote *HTTPError+ if !errors.As(err, &remote) || !IsRateLimited(remote) {+ return 0+ }+ return remote.RetryAfter+}++// RateLimitScopeOf returns a trusted Cloud scope hint. Proxy-generated 429s+// normally have no scope and remain conservatively global to the caller.+func RateLimitScopeOf(err error) string {+ var remote *HTTPError+ if !errors.As(err, &remote) || !IsRateLimited(remote) {+ return ""+ }+ return normalizedRateLimitScope(remote.RateLimitScope)+}++func normalizedRateLimitScope(value string) string {+ switch strings.ToLower(strings.TrimSpace(value)) {+ case RateLimitScopeGlobal:+ return RateLimitScopeGlobal+ case RateLimitScopeWorkspace:+ return RateLimitScopeWorkspace+ default:+ return ""+ }+}++func retryAfterDuration(value string) time.Duration {+ return retryAfterDurationAt(value, time.Now())+}++func retryAfterDurationAt(value string, now time.Time) time.Duration {+ value = strings.TrimSpace(value)+ seconds, err := strconv.ParseInt(value, 10, 64)+ if err == nil {+ if seconds < 1 {+ return 0+ }+ return time.Duration(seconds) * time.Second+ }+ retryAt, err := http.ParseTime(value)+ if err != nil {+ return 0+ }+ delay := retryAt.Sub(now)+ if delay <= 0 {+ return 0+ }+ return delay+}diff --git a/server/internal/seatcapacity/client_test.go b/server/internal/seatcapacity/client_test.goindex bceb0c05b9..bb146f554d 100644--- a/server/internal/seatcapacity/client_test.go+++ b/server/internal/seatcapacity/client_test.go@@ -26,7 +26,7 @@ func TestClientReserveInvitation(t *testing.T) {}))defer server.Close()- client, err := New(Config{Enabled: true, BaseURL: server.URL + "/base", ServiceToken: strings.Repeat("s", 32)})+ client, err := New(Config{BaseURL: server.URL + "/base", ServiceToken: strings.Repeat("s", 32)})if err != nil {t.Fatal(err)}@@ -50,7 +50,7 @@ func TestClientRejectsRedirectAndDoesNotForwardCredential(t *testing.T) {}))defer source.Close()- client, err := New(Config{Enabled: true, BaseURL: source.URL, ServiceToken: strings.Repeat("s", 32)})+ client, err := New(Config{BaseURL: source.URL, ServiceToken: strings.Repeat("s", 32)})if err != nil {t.Fatal(err)}@@ -74,27 +74,78 @@ func TestIsCapacityOvercommittedRequiresCloudConflictCode(t *testing.T) {}}-func TestDisabledClientPreservesLegacyBehavior(t *testing.T) {+func TestClientPreservesCapacityRateLimit(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Retry-After", "3")+ w.WriteHeader(http.StatusTooManyRequests)+ // Simulate a proxy-generated response with no Cloud JSON error code.+ _, _ = w.Write([]byte(`rate limited by ingress`))+ }))+ defer server.Close()++ client, err := New(Config{BaseURL: server.URL, ServiceToken: strings.Repeat("s", 32)})+ if err != nil {+ t.Fatal(err)+ }+ _, err = client.ReserveInvitation(context.Background(), uuid.New(), uuid.New(), time.Now().Add(time.Hour))+ if !IsRateLimited(err) {+ t.Fatalf("error = %v, want capacity rate limit", err)+ }+ if retry := RateLimitRetryAfter(err); retry != 3*time.Second {+ t.Fatalf("retry after = %s, want 3s", retry)+ }+ if scope := RateLimitScopeOf(err); scope != "" {+ t.Fatalf("proxy rate-limit scope = %q, want unknown", scope)+ }+}++func TestClientPreservesCloudWorkspaceRateLimitScope(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Retry-After", "1")+ w.Header().Set(rateLimitScopeHeader, RateLimitScopeWorkspace)+ w.WriteHeader(http.StatusTooManyRequests)+ }))+ defer server.Close()++ client, err := New(Config{BaseURL: server.URL, ServiceToken: strings.Repeat("s", 32)})+ if err != nil {+ t.Fatal(err)+ }+ _, err = client.ReserveInvitation(context.Background(), uuid.New(), uuid.New(), time.Now().Add(time.Hour))+ if scope := RateLimitScopeOf(err); scope != RateLimitScopeWorkspace {+ t.Fatalf("rate-limit scope = %q, want %q", scope, RateLimitScopeWorkspace)+ }+}++func TestRetryAfterDurationAcceptsHTTPDate(t *testing.T) {+ now := time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC)+ retryAt := now.Add(7 * time.Second)+ if got := retryAfterDurationAt(retryAt.Format(http.TimeFormat), now); got != 7*time.Second {+ t.Fatalf("retry after = %s, want 7s", got)+ }+}++func TestClientIsDisabledOnlyWhenCloudURLAndTokenAreAbsent(t *testing.T) {client, err := New(Config{})if err != nil {t.Fatal(err)}- decision, err := client.ClaimShareJoin(context.Background(), uuid.New(), uuid.New())- if err != nil || !decision.Allowed || decision.Managed {- t.Fatalf("decision=%+v err=%v", decision, err)+ if client != nil {+ t.Fatalf("client = %#v, want nil for self-host", client)}}-func TestEnabledClientRejectsUnsafeConfiguration(t *testing.T) {+func TestCloudConnectedClientRejectsUnsafeConfiguration(t *testing.T) {tests := []struct {name stringcfg Config}{- {name: "missing URL", cfg: Config{Enabled: true, ServiceToken: strings.Repeat("s", 32)}},- {name: "URL credentials", cfg: Config{Enabled: true, BaseURL: "https://user:[email protected]", ServiceToken: strings.Repeat("s", 32)}},- {name: "short token", cfg: Config{Enabled: true, BaseURL: "https://example.com", ServiceToken: "short"}},- {name: "token whitespace", cfg: Config{Enabled: true, BaseURL: "https://example.com", ServiceToken: strings.Repeat("s", 31) + "\n"}},- {name: "excessive timeout", cfg: Config{Enabled: true, BaseURL: "https://example.com", ServiceToken: strings.Repeat("s", 32), Timeout: 6 * time.Second}},+ {name: "missing URL", cfg: Config{ServiceToken: strings.Repeat("s", 32)}},+ {name: "missing token", cfg: Config{BaseURL: "https://example.com"}},+ {name: "URL credentials", cfg: Config{BaseURL: "https://user:[email protected]", ServiceToken: strings.Repeat("s", 32)}},+ {name: "short token", cfg: Config{BaseURL: "https://example.com", ServiceToken: "short"}},+ {name: "token whitespace", cfg: Config{BaseURL: "https://example.com", ServiceToken: strings.Repeat("s", 31) + "\n"}},+ {name: "excessive timeout", cfg: Config{BaseURL: "https://example.com", ServiceToken: strings.Repeat("s", 32), Timeout: 6 * time.Second}},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {diff --git a/server/internal/seatcapacity/worker.go b/server/internal/seatcapacity/worker.goindex 1672408fe1..52df8f7a54 100644--- a/server/internal/seatcapacity/worker.go+++ b/server/internal/seatcapacity/worker.go@@ -38,6 +38,7 @@ type WorkerConfig struct {type workerQueries interface {ClaimNextDueSeatCapacityIntent(context.Context, pgtype.Timestamptz) (db.SeatCapacityOutbox, error)+ DeferClaimedSeatCapacityIntent(context.Context, db.DeferClaimedSeatCapacityIntentParams) (int64, error)DeleteClaimedSeatCapacityIntent(context.Context, db.DeleteClaimedSeatCapacityIntentParams) (int64, error)ExpireInvitationForCapacityRecovery(context.Context, pgtype.UUID) errorGetClaimedSeatCapacityIntent(context.Context, db.GetClaimedSeatCapacityIntentParams) (db.SeatCapacityOutbox, error)@@ -98,7 +99,7 @@ func newWorker(queries workerQueries, executor Executor, cfg WorkerConfig) *Work}func (w *Worker) Enabled() bool {- return w != nil && w.queries != nil && w.executor != nil && w.executor.Enabled()+ return w != nil && w.queries != nil && CanRunWorker(w.executor)}func (w *Worker) Run(ctx context.Context) {@@ -123,6 +124,7 @@ func (w *Worker) ReconcileOnce(ctx context.Context) error {if !w.Enabled() {return nil}+ workspaceDeferrals := make(map[uuid.UUID]rateLimitDeferral)for i := int32(0); i < w.batchSize; i++ {intent, err := w.queries.ClaimNextDueSeatCapacityIntent(ctx, pgtype.Timestamptz{Time: w.now().Add(defaultClaimLease), Valid: true,@@ -133,14 +135,59 @@ func (w *Worker) ReconcileOnce(ctx context.Context) error {if err != nil {return err}+ workspaceID := uuidFromPG(intent.WorkspaceID)+ if deferral, ok := workspaceDeferrals[workspaceID]; ok && deferral.until.After(w.now()) {+ if err := w.deferClaimedUntil(ctx, intent, deferral.reason, deferral.until); err != nil {+ return err+ }+ continue+ }settleErr := w.settleWithWorkspaceLimit(ctx, intent)if settleErr != nil {+ if IsRateLimited(settleErr) {+ deferredUntil, err := w.deferRateLimited(ctx, intent, settleErr)+ if err != nil {+ return errors.Join(settleErr, err)+ }+ if RateLimitScopeOf(settleErr) == RateLimitScopeWorkspace {+ workspaceDeferrals[workspaceID] = rateLimitDeferral{+ until: deferredUntil, reason: settleErr.Error(),+ }+ continue+ }+ // A global Cloud 429, or an unscoped 429 generated by an ingress or+ // proxy, may affect every tenant. Stop this batch rather than amplify+ // saturation; explicitly workspace-scoped 429s continue above.+ break+ }w.recordFailure(ctx, intent, settleErr)}}return w.refreshMetrics(ctx)}+type rateLimitDeferral struct {+ until time.Time+ reason string+}++func (w *Worker) deferRateLimited(ctx context.Context, intent db.SeatCapacityOutbox, settleErr error) (time.Time, error) {+ delay := RateLimitRetryAfter(settleErr)+ if delay <= 0 {+ delay = time.Second+ }+ deferredUntil := w.now().Add(delay)+ return deferredUntil, w.deferClaimedUntil(ctx, intent, settleErr.Error(), deferredUntil)+}++func (w *Worker) deferClaimedUntil(ctx context.Context, intent db.SeatCapacityOutbox, reason string, deferredUntil time.Time) error {+ _, err := w.queries.DeferClaimedSeatCapacityIntent(ctx, db.DeferClaimedSeatCapacityIntentParams{+ LastError: reason, NextAttemptAt: pgtype.Timestamptz{Time: deferredUntil, Valid: true},+ OperationToken: intent.OperationToken, Action: intent.Action, LeaseToken: intent.LeaseToken,+ })+ return err+}+func (w *Worker) settleWithWorkspaceLimit(ctx context.Context, intent db.SeatCapacityOutbox) error {if w.workspaceLocker == nil {return w.settle(ctx, intent)diff --git a/server/internal/seatcapacity/worker_test.go b/server/internal/seatcapacity/worker_test.goindex f1f1609de2..555137c10d 100644--- a/server/internal/seatcapacity/worker_test.go+++ b/server/internal/seatcapacity/worker_test.go@@ -15,11 +15,14 @@ import ()type workerTestExecutor struct {- decision Decision- err error- confirms int+ decision Decision+ err error+ errorsByWorkspace map[uuid.UUID]error+ confirmWorkspaces []uuid.UUID}+func (*workerTestExecutor) RecoveryAvailable() bool { return true }+type workerTestLocker struct {locks intunlocks int@@ -30,7 +33,6 @@ func (l *workerTestLocker) Lock(context.Context, uuid.UUID) (db.DBTX, func(), erreturn nil, func() { l.unlocks++ }, nil}-func (e *workerTestExecutor) Enabled() bool { return true }func (e *workerTestExecutor) ReserveInvitation(context.Context, uuid.UUID, uuid.UUID, time.Time) (Decision, error) {return Decision{}, nil}@@ -40,8 +42,12 @@ func (e *workerTestExecutor) ClaimShareJoin(context.Context, uuid.UUID, uuid.UUIfunc (e *workerTestExecutor) Consume(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {return Decision{}, nil}-func (e *workerTestExecutor) Confirm(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (Decision, error) {- e.confirms++++func (e *workerTestExecutor) Confirm(_ context.Context, workspaceID, _, _ uuid.UUID) (Decision, error) {+ e.confirmWorkspaces = append(e.confirmWorkspaces, workspaceID)+ if err := e.errorsByWorkspace[workspaceID]; err != nil {+ return Decision{}, err+ }return e.decision, e.err}func (e *workerTestExecutor) Release(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {@@ -58,21 +64,37 @@ type workerTestQueries struct {mu sync.Mutexintent db.SeatCapacityOutbox+ intents []db.SeatCapacityOutbox+ nextIntent intclaimAvailable boolinvitation db.WorkspaceInvitationinvitationError errorstats []db.SeatCapacityOutboxStatsRow+ deferredUntil pgtype.Timestamptz+ deferredUntils []pgtype.Timestamptz+ claimCalls inttransitions intdeletes intexpires intfailures intdeadLetters int+ deferrals int}func (q *workerTestQueries) ClaimNextDueSeatCapacityIntent(context.Context, pgtype.Timestamptz) (db.SeatCapacityOutbox, error) {q.mu.Lock()defer q.mu.Unlock()+ q.claimCalls+++ if len(q.intents) > 0 {+ if q.nextIntent >= len(q.intents) {+ return db.SeatCapacityOutbox{}, pgx.ErrNoRows+ }+ q.intent = q.intents[q.nextIntent]+ q.nextIntent+++ q.intent.LeaseToken = uuidToTestPG(uuid.New())+ return q.intent, nil+ }if !q.claimAvailable {return db.SeatCapacityOutbox{}, pgx.ErrNoRows}@@ -81,6 +103,19 @@ func (q *workerTestQueries) ClaimNextDueSeatCapacityIntent(context.Context, pgtyreturn q.intent, nil}+func (q *workerTestQueries) DeferClaimedSeatCapacityIntent(_ context.Context, arg db.DeferClaimedSeatCapacityIntentParams) (int64, error) {+ q.mu.Lock()+ defer q.mu.Unlock()+ if q.intent.OperationToken != arg.OperationToken || q.intent.Action != arg.Action || q.intent.LeaseToken != arg.LeaseToken {+ return 0, nil+ }+ q.deferrals+++ q.deferredUntil = arg.NextAttemptAt+ q.deferredUntils = append(q.deferredUntils, arg.NextAttemptAt)+ q.intent.LeaseToken = pgtype.UUID{}+ return 1, nil+}+func (q *workerTestQueries) DeleteClaimedSeatCapacityIntent(_ context.Context, arg db.DeleteClaimedSeatCapacityIntentParams) (int64, error) {q.mu.Lock()defer q.mu.Unlock()@@ -155,6 +190,12 @@ func (q *workerTestQueries) counts() (transitions, deletes, expires, failures, dreturn q.transitions, q.deletes, q.expires, q.failures, q.deadLetters}+func (q *workerTestQueries) rateLimitState() (claimCalls, deferrals int, attemptCount int32, deferredUntil time.Time) {+ q.mu.Lock()+ defer q.mu.Unlock()+ return q.claimCalls, q.deferrals, q.intent.AttemptCount, q.deferredUntil.Time+}+func workerTestIntent(action string) db.SeatCapacityOutbox {return db.SeatCapacityOutbox{WorkspaceID: uuidToTestPG(uuid.New()), OperationToken: uuidToTestPG(uuid.New()),@@ -293,6 +334,93 @@ func TestWorkerDeadLettersAfterMaximumAttempts(t *testing.T) {}}+func TestWorkerDefersCloudRateLimitWithoutSpendingRetryBudget(t *testing.T) {+ now := time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC)+ intent := workerTestIntent(ActionConfirm)+ intent.AttemptCount = 9+ queries := &workerTestQueries{intent: intent, claimAvailable: true}+ worker := newWorker(queries, &workerTestExecutor{err: &HTTPError{+ StatusCode: http.StatusTooManyRequests,+ Code: "capacity_rate_limited",+ RetryAfter: 3 * time.Second,+ }}, WorkerConfig{MaxAttempts: 10})+ worker.now = func() time.Time { return now }++ if err := worker.ReconcileOnce(context.Background()); err != nil {+ t.Fatal(err)+ }+ claimCalls, deferrals, attemptCount, deferredUntil := queries.rateLimitState()+ _, _, _, failures, deadLetters := queries.counts()+ if claimCalls != 1 {+ t.Fatalf("claim calls=%d, want 1 so the rate-limited batch stops immediately", claimCalls)+ }+ if deferrals != 1 || failures != 0 || deadLetters != 0 {+ t.Fatalf("deferrals=%d failures=%d deadLetters=%d, want 1/0/0", deferrals, failures, deadLetters)+ }+ if attemptCount != 9 {+ t.Fatalf("attempt count=%d, want unchanged value 9", attemptCount)+ }+ if want := now.Add(3 * time.Second); !deferredUntil.Equal(want) {+ t.Fatalf("deferred until=%s, want %s", deferredUntil, want)+ }+}++func TestWorkerWorkspaceRateLimitDoesNotStopOtherTenants(t *testing.T) {+ now := time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC)+ limitedWorkspace, healthyWorkspace := uuid.New(), uuid.New()+ limitedA := workerTestIntent(ActionConfirm)+ limitedA.WorkspaceID = uuidToTestPG(limitedWorkspace)+ limitedB := workerTestIntent(ActionConfirm)+ limitedB.WorkspaceID = uuidToTestPG(limitedWorkspace)+ healthy := workerTestIntent(ActionConfirm)+ healthy.WorkspaceID = uuidToTestPG(healthyWorkspace)+ queries := &workerTestQueries{intents: []db.SeatCapacityOutbox{limitedA, limitedB, healthy}}+ executor := &workerTestExecutor{+ decision: Decision{Managed: true, Allowed: true},+ errorsByWorkspace: map[uuid.UUID]error{+ limitedWorkspace: &HTTPError{+ StatusCode: http.StatusTooManyRequests,+ RetryAfter: 2 * time.Second,+ RateLimitScope: RateLimitScopeWorkspace,+ },+ },+ }+ worker := newWorker(queries, executor, WorkerConfig{BatchSize: 10})+ worker.now = func() time.Time { return now }++ if err := worker.ReconcileOnce(context.Background()); err != nil {+ t.Fatal(err)+ }+ if got := executor.confirmWorkspaces; len(got) != 2 || got[0] != limitedWorkspace || got[1] != healthyWorkspace {+ t.Fatalf("Cloud confirm workspaces = %v, want one limited call followed by healthy tenant", got)+ }+ if queries.deferrals != 2 || queries.deletes != 1 {+ t.Fatalf("deferrals=%d deletes=%d, want 2/1", queries.deferrals, queries.deletes)+ }+ if queries.claimCalls != 4 {+ t.Fatalf("claim calls=%d, want three intents plus end-of-queue check", queries.claimCalls)+ }+ for _, deferred := range queries.deferredUntils {+ if want := now.Add(2 * time.Second); !deferred.Time.Equal(want) {+ t.Fatalf("deferred until=%s, want %s", deferred.Time, want)+ }+ }+}++func TestUnavailableExecutorDisablesWorkerRecovery(t *testing.T) {+ unavailable := NewUnavailable(errors.New("invalid capacity credentials"))+ if CanRunWorker(unavailable) {+ t.Fatal("unavailable executor can run recovery worker")+ }+ worker := newWorker(&workerTestQueries{}, unavailable, WorkerConfig{})+ if worker.Enabled() {+ t.Fatal("worker is enabled with unavailable executor")+ }+ if !CanRunWorker(&workerTestExecutor{}) {+ t.Fatal("configured executor cannot run recovery worker")+ }+}+func TestWorkerUsesWorkspaceSerializationBeforeCloudCall(t *testing.T) {intent := workerTestIntent(ActionConfirm)queries := &workerTestQueries{intent: intent}@@ -319,8 +447,8 @@ func TestWorkerSkipsCloudCallWhenClaimWasReactivatedBeforeWorkspaceLock(t *testiif err := worker.settleWithWorkspaceLimit(context.Background(), intent); err != nil {t.Fatal(err)}- if executor.confirms != 0 {- t.Fatalf("stale worker made %d Cloud confirm calls, want 0", executor.confirms)+ if len(executor.confirmWorkspaces) != 0 {+ t.Fatalf("stale worker made %d Cloud confirm calls, want 0", len(executor.confirmWorkspaces))}}diff --git a/server/pkg/db/generated/seat_capacity.sql.go b/server/pkg/db/generated/seat_capacity.sql.goindex 6f59e5d915..bf1e1b5102 100644--- a/server/pkg/db/generated/seat_capacity.sql.go+++ b/server/pkg/db/generated/seat_capacity.sql.go@@ -122,6 +122,40 @@ func (q *Queries) CreateOrReactivateShareJoinCapacityIntent(ctx context.Context,return i, err}+const deferClaimedSeatCapacityIntent = `-- name: DeferClaimedSeatCapacityIntent :execrows+UPDATE seat_capacity_outbox+SET last_error = left($1, 1000),+ next_attempt_at = $2,+ lease_token = NULL,+ updated_at = now()+WHERE operation_token = $3+ AND action = $4+ AND lease_token = $5+ AND dead_lettered_at IS NULL+`++type DeferClaimedSeatCapacityIntentParams struct {+ LastError string `json:"last_error"`+ NextAttemptAt pgtype.Timestamptz `json:"next_attempt_at"`+ OperationToken pgtype.UUID `json:"operation_token"`+ Action string `json:"action"`+ LeaseToken pgtype.UUID `json:"lease_token"`+}++func (q *Queries) DeferClaimedSeatCapacityIntent(ctx context.Context, arg DeferClaimedSeatCapacityIntentParams) (int64, error) {+ result, err := q.db.Exec(ctx, deferClaimedSeatCapacityIntent,+ arg.LastError,+ arg.NextAttemptAt,+ arg.OperationToken,+ arg.Action,+ arg.LeaseToken,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const deleteClaimedSeatCapacityIntent = `-- name: DeleteClaimedSeatCapacityIntent :execrowsDELETE FROM seat_capacity_outboxWHERE operation_token = $1diff --git a/server/pkg/db/queries/seat_capacity.sql b/server/pkg/db/queries/seat_capacity.sqlindex ab80fa1e2b..c32e432301 100644--- a/server/pkg/db/queries/seat_capacity.sql+++ b/server/pkg/db/queries/seat_capacity.sql@@ -267,6 +267,17 @@ WHERE operation_token = sqlc.arg('operation_token')AND action = sqlc.arg('action')AND lease_token = sqlc.arg('lease_token');+-- name: DeferClaimedSeatCapacityIntent :execrows+UPDATE seat_capacity_outbox+SET last_error = left(sqlc.arg('last_error'), 1000),+ next_attempt_at = sqlc.arg('next_attempt_at'),+ lease_token = NULL,+ updated_at = now()+WHERE operation_token = sqlc.arg('operation_token')+ AND action = sqlc.arg('action')+ AND lease_token = sqlc.arg('lease_token')+ AND dead_lettered_at IS NULL;+-- name: DeleteSeatCapacityIntentForAction :execDELETE FROM seat_capacity_outboxWHERE operation_token = $1 AND action = $2;