Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Harden multi-tenant GA readiness
rcourtman0622169be845
diff --git a/docs/release-control/v6/internal/records/multi-tenant-ga-readiness-revalidation-2026-04-23.md b/docs/release-control/v6/internal/records/multi-tenant-ga-readiness-revalidation-2026-04-23.mdnew file mode 100644index 0000000000..abf05d00d9--- /dev/null+++ b/docs/release-control/v6/internal/records/multi-tenant-ga-readiness-revalidation-2026-04-23.md@@ -0,0 +1,48 @@+# Multi-Tenant GA Readiness Revalidation++- Date: `2026-04-23`+- Gates:+ - `multi-tenant-runtime-isolation-and-coherence`+ - `msp-provider-tenant-management`+ - `organization-user-scope-and-rbac`+- Evidence tier: `local-rehearsal`+- Scope: Current checkout revalidation after the multi-tenant GA audit found red proof in org ownership transfer, MSP account invite lifecycle, portal bundle sync, workspace-limit HA safety, and non-default tenant fallback drift.++## Changes Revalidated++1. Organization ownership transfer now validates the target-member prerequisite before requiring a fresh browser session, so invalid transfers return the canonical `owner_transfer_requires_member` contract instead of a reauth response.+2. MSP account invite lifecycle proof now matches the canonical pending-invitation model for unknown account emails: `202 Accepted` with `state=pending`, not an immediate active membership.+3. Pulse Account embedded portal bundle was rebuilt from the current frontend source and the bundle sync test now passes.+4. Workspace creation now has a registry-backed transactional workspace-limit check in addition to the per-process account lock, so multiple control-plane instances share the same final limit source of truth.+5. Non-default tenant monitor/config helper paths now fail closed instead of falling back to default-org state when tenant monitor resolution is unavailable.++## Proof Commands++- `go test ./internal/api -run 'Test(.*Tenant|.*Org|.*RBAC|.*BillingState|.*WebSocketIsolation|.*ResourceHandlers_NonDefaultOrg|.*SetMultiTenantMonitor_WiresHandlers|.*MultiTenantStateProvider|.*Hosted|.*Token.*Org|.*Isolation|.*RateLimit)' -count=1`+- `go test ./internal/cloudcp ./internal/cloudcp/account ./internal/cloudcp/auth ./internal/cloudcp/handoff ./internal/cloudcp/portal ./internal/cloudcp/registry ./internal/cloudcp/stripe -run 'Test(.*Account|.*Tenant|.*Workspace|.*Portal|.*Session|.*Magic|.*Membership|.*MSP|.*Billing|.*Handoff|.*Route|.*Registry|.*Stripe|.*Grace|.*Provision|.*Lifecycle|.*Entitlement|.*Signup|.*Public)' -count=1`+- `go test ./internal/monitoring -run 'TestMultiTenantMonitor|TestMonitorBroadcastStateUsesTenantChannel|TestMonitorBroadcastStateUsesGlobalChannel|TestMonitorSetOrgID|TestMonitoredSystemUsage|TestRecoveryRollups' -count=1`+- `go test ./pkg/audit ./pkg/cloudauth ./pkg/auth ./pkg/licensing -run 'Test(.*Tenant|.*Org|.*RBAC|.*Session|.*Handoff|.*Billing|.*Plan|.*Workspace|.*Limit|.*Entitlement|.*Grant|.*Scope|.*User|.*Audit|.*Cardinality)' -count=1`+- `npm --prefix frontend-modern test -- src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx src/components/Settings/__tests__/RBACPaywallPanels.test.tsx src/components/Settings/__tests__/OrganizationAccessPanel.test.tsx src/components/Settings/__tests__/OrganizationOverviewPanel.test.tsx src/utils/__tests__/organizationRolePresentation.test.ts src/utils/__tests__/organizationSettingsPresentation.test.ts src/utils/__tests__/rbacPermissions.test.ts src/utils/__tests__/rbacPresentation.test.ts`+- `npm --prefix internal/cloudcp/portal/frontend test`+- `npm --prefix internal/cloudcp/portal/frontend run typecheck`++All commands passed.++## Browser Rehearsal++- Started the local Pulse Account preview server with `npm --prefix internal/cloudcp/portal/frontend run dev`.+- Opened `http://127.0.0.1:8765/?scenario=managed&reset=1` in the in-app browser.+- Verified the managed MSP account shell rendered Workspaces, Access, Invite people, and Billing without console warnings or errors.+- Opened `http://127.0.0.1:8765/?scenario=selfhosted&reset=1&portal_handoff_id=cph_preview&feature=self_hosted_plan`.+- Verified the self-hosted plan-upgrade billing shell rendered the updated Plans-page checkout copy and plan cards without console warnings or errors.++## Outcome++- The previously red local proof surfaces are green.+- The shipped Pulse Account bundle is synchronized with the current source.+- The workspace-limit path has a database-backed final enforcement point for multi-instance control-plane deployments.+- Non-default tenant state resolution no longer has the audited default-org fallback drift in the router/config helper paths.++## Remaining Promotion Note++This record is a local GA-readiness revalidation. The older `real-external-e2e` MSP production evidence remains the external proof floor for `msp-provider-tenant-management`; a fresh production promotion rehearsal should still be run as part of the release-day publication workflow.diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.jsonindex ec1d483a1e..1c4ee6ddb1 100644--- a/docs/release-control/v6/internal/status.json+++ b/docs/release-control/v6/internal/status.json@@ -3653,6 +3653,12 @@"path": "docs/release-control/v6/internal/records/msp-provider-tenant-management-production-followup-2026-03-13.md","kind": "file","evidence_tier": "real-external-e2e"+ },+ {+ "repo": "pulse",+ "path": "docs/release-control/v6/internal/records/multi-tenant-ga-readiness-revalidation-2026-04-23.md",+ "kind": "file",+ "evidence_tier": "local-rehearsal"}]},@@ -3671,6 +3677,12 @@"L17"],"evidence": [+ {+ "repo": "pulse",+ "path": "docs/release-control/v6/internal/records/multi-tenant-ga-readiness-revalidation-2026-04-23.md",+ "kind": "file",+ "evidence_tier": "local-rehearsal"+ },{"repo": "pulse","path": "docs/release-control/v6/internal/records/multi-tenant-runtime-isolation-and-coherence-2026-03-13.md",@@ -3695,6 +3707,12 @@"L17"],"evidence": [+ {+ "repo": "pulse",+ "path": "docs/release-control/v6/internal/records/multi-tenant-ga-readiness-revalidation-2026-04-23.md",+ "kind": "file",+ "evidence_tier": "local-rehearsal"+ },{"repo": "pulse","path": "docs/release-control/v6/internal/records/organization-user-scope-and-rbac-2026-03-12.md",diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.goindex 7a45c9053f..434df2cc44 100644--- a/internal/api/config_handlers.go+++ b/internal/api/config_handlers.go@@ -333,8 +333,14 @@ func (h *ConfigHandlers) getContextState(ctx context.Context) (*config.Config, *p, _ = mtPersistence.GetPersistence(orgID)}return cfg, p, m- } else if err != nil {- log.Warn().Str("orgID", orgID).Err(err).Msg("Falling back to default-org config after tenant monitor lookup failure")+ } else {+ if orgID != "default" {+ log.Warn().Str("orgID", orgID).Err(err).Msg("Tenant config resolution failed for non-default org")+ return nil, nil, nil+ }+ if err != nil {+ log.Warn().Str("orgID", orgID).Err(err).Msg("Falling back to default-org config after default tenant monitor lookup failure")+ }}}diff --git a/internal/api/multi_tenant_setters_additional_test.go b/internal/api/multi_tenant_setters_additional_test.goindex 6469e7b777..19d1fa0d27 100644--- a/internal/api/multi_tenant_setters_additional_test.go+++ b/internal/api/multi_tenant_setters_additional_test.go@@ -77,6 +77,27 @@ func TestRouterSetMultiTenantMonitorRefreshesConfigHandlerMonitorSource(t *testi}}+func TestConfigHandlersNonDefaultMissingTenantMonitorFailsClosed(t *testing.T) {+ defaultConfig := &config.Config{DataPath: t.TempDir(), ConfigPath: t.TempDir()}+ defaultMonitor, _, _ := newTestMonitor(t)+ mtp := config.NewMultiTenantPersistence(t.TempDir())+ mtm := monitoring.NewMultiTenantMonitor(defaultConfig, mtp, nil)+ defer mtm.Stop()++ handler := &ConfigHandlers{+ defaultConfig: defaultConfig,+ defaultPersistence: config.NewConfigPersistence(defaultConfig.ConfigPath),+ defaultMonitor: defaultMonitor,+ }+ handler.SetMultiTenantMonitor(mtm)++ ctx := context.WithValue(context.Background(), OrgIDContextKey, "tenant-missing")+ cfg, persistence, monitor := handler.getContextState(ctx)+ if cfg != nil || persistence != nil || monitor != nil {+ t.Fatalf("expected missing non-default tenant state to fail closed, got cfg=%#v persistence=%#v monitor=%#v", cfg, persistence, monitor)+ }+}+func TestNewRouterWiresTenantResourceStateProvider(t *testing.T) {cfg := &config.Config{DataPath: t.TempDir(),diff --git a/internal/api/org_handlers.go b/internal/api/org_handlers.goindex f60bf2679f..ae24deade4 100644--- a/internal/api/org_handlers.go+++ b/internal/api/org_handlers.go@@ -481,14 +481,14 @@ func (h *OrgHandlers) HandleInviteMember(w http.ResponseWriter, r *http.Request)// Ownership transfer: demote old owner to admin and promote target user to owner.if req.Role == models.OrgRoleOwner && req.UserID != org.OwnerUserID {- if authErr := validateFreshBrowserSession(r, username, "transfer ownership", privilegedBrowserSessionMaxAge); authErr != nil {- writeErrorResponse(w, authErr.Status, authErr.Code, authErr.Message, nil)- return- }if memberIndex < 0 {writeErrorResponse(w, http.StatusBadRequest, "owner_transfer_requires_member", "Ownership can only be transferred to an existing member", nil)return}+ if authErr := validateFreshBrowserSession(r, username, "transfer ownership", privilegedBrowserSessionMaxAge); authErr != nil {+ writeErrorResponse(w, authErr.Status, authErr.Code, authErr.Message, nil)+ return+ }for i := range org.Members {if org.Members[i].UserID == org.OwnerUserID {org.Members[i].Role = models.OrgRoleAdmindiff --git a/internal/api/router_helpers.go b/internal/api/router_helpers.goindex a62dc48578..28a6440329 100644--- a/internal/api/router_helpers.go+++ b/internal/api/router_helpers.go@@ -1,6 +1,7 @@package apiimport (+ "errors""net/http""time"@@ -9,18 +10,19 @@ import ("github.com/rs/zerolog/log")+var errTenantMonitorUnavailable = errors.New("tenant monitor unavailable")+// getMonitor returns the tenant-specific monitor instance for the request.// It uses the OrgID from the context (injected by TenantMiddleware).-// If no tenant monitor is found, or if not in multi-tenant mode, it returns the default monitor.+// Non-default orgs fail closed when tenant monitor resolution is unavailable.func (r *Router) getMonitor(req *http.Request) (*monitoring.Monitor, error) {- if r.mtMonitor == nil {- return r.monitor, nil- }-orgID := GetOrgID(req.Context())- if orgID == "" {+ if orgID == "" || orgID == "default" {return r.monitor, nil}+ if r.mtMonitor == nil {+ return nil, errTenantMonitorUnavailable+ }return r.mtMonitor.GetMonitor(orgID)}diff --git a/internal/api/router_helpers_more_test.go b/internal/api/router_helpers_more_test.goindex d6d58eeb1a..0ef9845ecd 100644--- a/internal/api/router_helpers_more_test.go+++ b/internal/api/router_helpers_more_test.go@@ -52,6 +52,22 @@ func TestRouterGetMonitor_WithTenant(t *testing.T) {}}+func TestRouterGetMonitor_NonDefaultWithoutTenantMonitorFailsClosed(t *testing.T) {+ defaultMonitor, _, _ := newTestMonitor(t)+ router := &Router{monitor: defaultMonitor}++ req := httptest.NewRequest(http.MethodGet, "/", nil)+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "tenant-1"))++ monitor, err := router.getMonitor(req)+ if err == nil {+ t.Fatal("expected non-default org without tenant monitor to fail closed")+ }+ if monitor != nil {+ t.Fatalf("monitor = %#v, want nil", monitor)+ }+}+func TestMultiTenantStateProvider_UnifiedReadStateForTenant(t *testing.T) {defaultMonitor, defaultState, _ := newTestMonitor(t)defaultState.Hosts = []models.Host{{ID: "host-default", Hostname: "default-host", Status: "online"}}diff --git a/internal/cloudcp/account/tenant_handlers.go b/internal/cloudcp/account/tenant_handlers.goindex 3be9186ad2..e1cd9492ec 100644--- a/internal/cloudcp/account/tenant_handlers.go+++ b/internal/cloudcp/account/tenant_handlers.go@@ -12,10 +12,9 @@ import ()// workspaceCreateLocks provides per-account serialization for workspace-// creation to prevent check-then-create race conditions. Each account gets-// its own mutex so that slow provisioning for one account does not block-// other accounts. For multi-instance deployments, this should be replaced-// with a DB-level constraint.+// creation inside one control-plane process. The registry still enforces the+// final workspace limit in the tenant-create transaction, so multi-instance+// deployments share the same source of truth.var workspaceCreateLocks sync.Map // map[string]*sync.Mutexfunc accountCreateLock(accountID string) *sync.Mutex {@@ -173,6 +172,22 @@ func HandleCreateTenant(reg *registry.TenantRegistry, provisioner WorkspaceProvireturn}if provisionErr != nil {+ if limitErr, ok := registry.WorkspaceLimitExceeded(provisionErr); ok {+ auditEvent(r, "cp_tenant_create", "failure").+ Err(provisionErr).+ Str("account_id", accountID).+ Str("display_name", displayName).+ Str("reason", "workspace_limit_reached").+ Int("current_count", limitErr.Current).+ Int("limit", limitErr.Limit).+ Msg("Tenant creation blocked by registry workspace limit")+ http.Error(+ w,+ fmt.Sprintf("workspace limit reached: %d of %d allowed", limitErr.Current, limitErr.Limit),+ http.StatusForbidden,+ )+ return+ }auditEvent(r, "cp_tenant_create", "failure").Err(provisionErr).Str("account_id", accountID).diff --git a/internal/cloudcp/account/tenant_handlers_test.go b/internal/cloudcp/account/tenant_handlers_test.goindex d5d08f9d96..8ae3eb01d0 100644--- a/internal/cloudcp/account/tenant_handlers_test.go+++ b/internal/cloudcp/account/tenant_handlers_test.go@@ -365,7 +365,13 @@ func TestCreateWorkspace_MSPStarterLimitEnforced(t *testing.T) {}}- // The 11th should be blocked.+ if _, err := provisioner.ProvisionWorkspace(context.Background(), accountID, "Client 11 direct"); err == nil {+ t.Fatal("expected registry-backed workspace limit to block direct provisioning")+ } else if _, ok := registry.WorkspaceLimitExceeded(err); !ok {+ t.Fatalf("direct provision error = %v, want workspace limit", err)+ }++ // The handler should also return the product-level limit response.body := `{"display_name":"Client 11"}`req := httptest.NewRequest(http.MethodPost, "/api/accounts/"+accountID+"/tenants", bytes.NewBufferString(body))rec := doRequest(t, mux, req)diff --git a/internal/cloudcp/portal/dist/build_manifest.json b/internal/cloudcp/portal/dist/build_manifest.jsonindex 10661025bb..c7fc87a648 100644--- a/internal/cloudcp/portal/dist/build_manifest.json+++ b/internal/cloudcp/portal/dist/build_manifest.json@@ -1,5 +1,5 @@{- "source_hash": "c5558e1c54558cd9722d83db8479de508085548b0cd6a6658b8eafb99805a14c",+ "source_hash": "089714382660bd7a2b789d096dbb88b1382be8ef7b0d35ade5fbd1479c3753fd","build_inputs": ["package.json","tsconfig.json",diff --git a/internal/cloudcp/portal/dist/portal_app.js b/internal/cloudcp/portal/dist/portal_app.jsindex 8223702068..82980f21e0 100644--- a/internal/cloudcp/portal/dist/portal_app.js+++ b/internal/cloudcp/portal/dist/portal_app.js@@ -1460,19 +1460,19 @@}if (!portalHandoffID) {summaryItems.push(- '<div class="billing-status visible error">Open this upgrade from Pulse Pro billing so Pulse Account can verify the secure upgrade handoff before checkout.</div>'+ '<div class="billing-status visible error">Open this upgrade from the Plans page in Pulse so Pulse Account can verify the secure plan upgrade handoff before checkout.</div>');} else if (handoffState.status === "loading") {- summaryItems.push('<div class="billing-status visible">Verifying the secure Pulse Pro upgrade handoff...</div>');+ summaryItems.push('<div class="billing-status visible">Verifying the secure plan upgrade handoff...</div>');} else if (handoffState.status === "error") {- summaryItems.push('<div class="billing-status visible error">' + escapeText(handoffState.error || "Failed to verify the secure Pulse Pro upgrade handoff.") + "</div>");+ summaryItems.push('<div class="billing-status visible error">' + escapeText(handoffState.error || "Failed to verify the secure plan upgrade handoff.") + "</div>");} else if (handoffState.status === "ready") {if (handoffLifecycle === "completed") {- summaryItems.push('<div class="billing-status visible success">This secure upgrade handoff already completed. Return to Pulse Pro billing to review the live plan state.</div>');+ summaryItems.push('<div class="billing-status visible success">This secure upgrade handoff already completed. Return to the Plans page in Pulse to review the live plan state.</div>');} else if (handoffLifecycle === "checkout_started") {summaryItems.push('<div class="billing-status visible">Secure checkout is already prepared for this upgrade. Continue below if you still need to reopen it.</div>');} else {- summaryItems.push('<div class="billing-status visible success">Pulse Account will return completed checkout directly to Pulse Pro billing.</div>');+ summaryItems.push('<div class="billing-status visible success">Pulse Account will return completed checkout directly to the Plans page in Pulse.</div>');}}if (pricingState.status === "loading" && !pricingState.data) {@@ -1486,7 +1486,7 @@if (explainer) {summaryItems.push('<div class="helper-text">' + explainer + "</div>");}- root.innerHTML = '<div class="billing-upgrade-root">' + summaryItems.join("") + renderUpgradePlansHTML(billingState) + (pricingState.status === "ready" && pricingState.data && pricingState.data.description ? '<div class="helper-text">' + escapeText(pricingState.data.description) + "</div>" : "") + '<div class="helper-text">' + (featureKey === "self_hosted_plan" || featureKey === "max_monitored_systems" ? "Pulse Account keeps checkout tied to the Pulse instance that opened it, so completed Relay or Pro purchases return to the right billing surface automatically." : "Pulse Account compares self-hosted tiers and sends completed checkout straight back to Pulse Pro billing.") + "</div></div>";+ root.innerHTML = '<div class="billing-upgrade-root">' + summaryItems.join("") + renderUpgradePlansHTML(billingState) + (pricingState.status === "ready" && pricingState.data && pricingState.data.description ? '<div class="helper-text">' + escapeText(pricingState.data.description) + "</div>" : "") + '<div class="helper-text">' + (featureKey === "self_hosted_plan" || featureKey === "max_monitored_systems" ? "Pulse Account keeps checkout tied to the Pulse instance that opened it, so completed Relay or Pro purchases return to the right Plans page automatically." : "Pulse Account compares self-hosted tiers and sends completed checkout straight back to the Plans page in Pulse.") + "</div></div>";}function renderButton(id, disabled, label) {if (!id || !label) return;@@ -1819,7 +1819,7 @@failQueryState(nextBillingState.upgradePortalHandoff,null,- err instanceof Error ? err.message : "Failed to verify the secure Pulse Pro upgrade handoff."+ err instanceof Error ? err.message : "Failed to verify the secure plan upgrade handoff.");});}@@ -1835,7 +1835,7 @@updateBillingState(function(nextBillingState) {failMutationState(nextBillingState.upgradeCheckout,- "Pulse Account could not verify the secure upgrade handoff. Reopen the upgrade flow from Pulse Pro billing."+ "Pulse Account could not verify the secure upgrade handoff. Reopen the upgrade flow from the Plans page in Pulse.");});return;@@ -1844,7 +1844,7 @@updateBillingState(function(nextBillingState) {failMutationState(nextBillingState.upgradeCheckout,- "This secure upgrade handoff already completed. Return to Pulse Pro billing to review the live plan state."+ "This secure upgrade handoff already completed. Return to the Plans page in Pulse to review the live plan state.");});return;@@ -2275,7 +2275,7 @@return isSelfHostedPlanUpgrade(featureKey) ? "Compare self-hosted plans as monitor, reach, or operate instead of by monitored-system volume." : "Compare self-hosted plans and continue into the commercial checkout path.";}function selfHostedUpgradeActionHighlights(featureKey) {- return isSelfHostedPlanUpgrade(featureKey) ? ["Plan comparison", "Pulse Pro checkout"] : ["Plan comparison", "Checkout handoff"];+ return isSelfHostedPlanUpgrade(featureKey) ? ["Plan comparison", "Plan checkout"] : ["Plan comparison", "Checkout handoff"];}function renderSelfHostedUpgradeActionRow(context) {var featureKey = normalizeUpgradeFeatureKey(context.billingState.upgradeFeatureKey);@@ -2291,10 +2291,10 @@}function renderSelfHostedUpgradeBillingPanel(context) {var featureKey = normalizeUpgradeFeatureKey(context.billingState.upgradeFeatureKey);- var helperCopy = isSelfHostedPlanUpgrade(featureKey) ? "Choose the self-hosted tier that fits how you run Pulse: Community monitors, Relay reaches anywhere, and Pro investigates and helps fix issues. Pulse Account will send completed checkout directly back to Pulse Pro billing." : "Choose the self-hosted tier that fits this upgrade. Pulse Account will send completed checkout directly back to Pulse Pro billing.";+ var helperCopy = isSelfHostedPlanUpgrade(featureKey) ? "Choose the self-hosted tier that fits how you run Pulse: Community monitors, Relay reaches anywhere, and Pro investigates and helps fix issues. Pulse Account will send completed checkout directly back to the Plans page in Pulse." : "Choose the self-hosted tier that fits this upgrade. Pulse Account will send completed checkout directly back to the Plans page in Pulse.";return renderBillingTaskPanel(selfHostedUpgradeActionTitle(featureKey),- "Pulse Account owns self-hosted plan selection and checkout for Pulse Pro upgrades.",+ "Pulse Account owns self-hosted plan selection and checkout for self-hosted upgrades.","upgrade-billing-panel",'<div id="upgrade-billing-root"></div><div class="helper-text">' + escapeHTML(helperCopy) + "</div>");diff --git a/internal/cloudcp/registry/registry.go b/internal/cloudcp/registry/registry.goindex f6aee1f511..25def93f67 100644--- a/internal/cloudcp/registry/registry.go+++ b/internal/cloudcp/registry/registry.go@@ -1,8 +1,10 @@package registryimport (+ "context""database/sql""database/sql/driver"+ "errors""fmt""net/url""os"@@ -30,6 +32,31 @@ func canonicalizeRegistryPlanVersion(planVersion string) string {return pkglicensing.CanonicalizePlanVersion(strings.TrimSpace(planVersion))}+// WorkspaceLimitExceededError is returned when an account has already reached+// its allowed active workspace count.+type WorkspaceLimitExceededError struct {+ AccountID string+ Current int+ Limit int+}++func (e *WorkspaceLimitExceededError) Error() string {+ if e == nil {+ return "workspace limit exceeded"+ }+ return fmt.Sprintf("workspace limit reached for account %q: %d of %d allowed", e.AccountID, e.Current, e.Limit)+}++// WorkspaceLimitExceeded unwraps wrapped errors that represent a workspace+// limit violation.+func WorkspaceLimitExceeded(err error) (*WorkspaceLimitExceededError, bool) {+ var limitErr *WorkspaceLimitExceededError+ if errors.As(err, &limitErr) {+ return limitErr, true+ }+ return nil, false+}+// NewTenantRegistry opens (or creates) the tenant registry database in dir.func NewTenantRegistry(dir string) (*TenantRegistry, error) {if err := os.MkdirAll(dir, 0o755); err != nil {@@ -515,14 +542,89 @@ func (r *TenantRegistry) Create(t *Tenant) error {if t == nil {return fmt.Errorf("tenant is nil")}+ prepareTenantForCreate(t)++ if err := insertTenant(context.Background(), r.db, t); err != nil {+ return fmt.Errorf("create tenant: %w", err)+ }+ return nil+}++// CreateWithAccountWorkspaceLimit inserts a tenant only if the account remains+// below its active workspace limit. The check and insert happen under a SQLite+// write transaction so multiple control-plane instances share the same final+// source of truth instead of relying on per-process locks.+func (r *TenantRegistry) CreateWithAccountWorkspaceLimit(t *Tenant, limit int) error {+ if t == nil {+ return fmt.Errorf("tenant is nil")+ }+ if strings.TrimSpace(t.AccountID) == "" {+ return fmt.Errorf("account id is required")+ }+ if limit < 1 {+ limit = 1+ }+ prepareTenantForCreate(t)++ ctx := context.Background()+ conn, err := r.db.Conn(ctx)+ if err != nil {+ return fmt.Errorf("open tenant registry connection: %w", err)+ }+ defer conn.Close()++ if _, err := conn.ExecContext(ctx, "BEGIN IMMEDIATE"); err != nil {+ return fmt.Errorf("begin tenant create transaction: %w", err)+ }+ committed := false+ defer func() {+ if !committed {+ _, _ = conn.ExecContext(ctx, "ROLLBACK")+ }+ }()++ var current int+ if err := conn.QueryRowContext(ctx, `+ SELECT COUNT(*) FROM tenants+ WHERE account_id = ?+ AND state NOT IN ('deleting', 'deleted', 'canceled')`,+ t.AccountID,+ ).Scan(¤t); err != nil {+ return fmt.Errorf("count active tenants for account %q: %w", t.AccountID, err)+ }+ if current >= limit {+ return &WorkspaceLimitExceededError{+ AccountID: t.AccountID,+ Current: current,+ Limit: limit,+ }+ }++ if err := insertTenant(ctx, conn, t); err != nil {+ return fmt.Errorf("create tenant: %w", err)+ }+ if _, err := conn.ExecContext(ctx, "COMMIT"); err != nil {+ return fmt.Errorf("commit tenant create transaction: %w", err)+ }+ committed = true+ return nil+}++type tenantInsertExecer interface {+ ExecContext(context.Context, string, ...any) (sql.Result, error)+}++func prepareTenantForCreate(t *Tenant) {now := time.Now().UTC()if t.CreatedAt.IsZero() {t.CreatedAt = now}t.PlanVersion = canonicalizeRegistryPlanVersion(t.PlanVersion)t.UpdatedAt = now+}- _, err := r.db.Exec(`+func insertTenant(ctx context.Context, execer tenantInsertExecer, t *Tenant) error {+ _, err := execer.ExecContext(ctx, `INSERT INTO tenants (id, account_id, email, display_name, state,stripe_customer_id, stripe_subscription_id, stripe_price_id,@@ -535,7 +637,7 @@ func (r *TenantRegistry) Create(t *Tenant) error {t.CreatedAt.Unix(), t.UpdatedAt.Unix(), nullableTimeUnix(t.LastHealthCheck), boolToInt(t.HealthCheckOK),)if err != nil {- return fmt.Errorf("create tenant: %w", err)+ return err}return nil}diff --git a/internal/cloudcp/registry/registry_test.go b/internal/cloudcp/registry/registry_test.goindex 8f98df14a8..55b3c97e44 100644--- a/internal/cloudcp/registry/registry_test.go+++ b/internal/cloudcp/registry/registry_test.go@@ -2,6 +2,7 @@ package registryimport ("database/sql"+ "errors""os""path/filepath""strings"@@ -808,6 +809,42 @@ func TestListByAccountID(t *testing.T) {}}+func TestCreateWithAccountWorkspaceLimitEnforcesActiveCount(t *testing.T) {+ reg := newTestRegistry(t)++ accountID, err := GenerateAccountID()+ if err != nil {+ t.Fatal(err)+ }+ if err := reg.CreateAccount(&Account{ID: accountID, Kind: AccountKindMSP, DisplayName: "Account"}); err != nil {+ t.Fatal(err)+ }+ if err := reg.CreateWithAccountWorkspaceLimit(&Tenant{ID: "t-LIMIT001", AccountID: accountID, State: TenantStateActive}, 1); err != nil {+ t.Fatalf("first create: %v", err)+ }++ err = reg.CreateWithAccountWorkspaceLimit(&Tenant{ID: "t-LIMIT002", AccountID: accountID, State: TenantStateProvisioning}, 1)+ var limitErr *WorkspaceLimitExceededError+ if !errors.As(err, &limitErr) {+ t.Fatalf("second create error = %v, want WorkspaceLimitExceededError", err)+ }+ if limitErr.Current != 1 || limitErr.Limit != 1 {+ t.Fatalf("limit error = %+v, want current=1 limit=1", limitErr)+ }++ first, err := reg.Get("t-LIMIT001")+ if err != nil {+ t.Fatalf("load first tenant: %v", err)+ }+ first.State = TenantStateDeleted+ if err := reg.Update(first); err != nil {+ t.Fatalf("mark first tenant deleted: %v", err)+ }+ if err := reg.CreateWithAccountWorkspaceLimit(&Tenant{ID: "t-LIMIT003", AccountID: accountID, State: TenantStateProvisioning}, 1); err != nil {+ t.Fatalf("deleted tenant should free an active workspace slot: %v", err)+ }+}+func TestCountByState(t *testing.T) {reg := newTestRegistry(t)diff --git a/internal/cloudcp/stripe/msp_lifecycle_integration_test.go b/internal/cloudcp/stripe/msp_lifecycle_integration_test.goindex 29b9c62e80..cf5481226d 100644--- a/internal/cloudcp/stripe/msp_lifecycle_integration_test.go+++ b/internal/cloudcp/stripe/msp_lifecycle_integration_test.go@@ -250,11 +250,11 @@ func TestMSPLifecycle_AccountToPortal(t *testing.T) {inviteRec := httptest.NewRecorder()memberMux.ServeHTTP(inviteRec, inviteReq)- if inviteRec.Code != http.StatusCreated {- t.Fatalf("invite member: status = %d, want %d (body=%q)", inviteRec.Code, http.StatusCreated, inviteRec.Body.String())+ if inviteRec.Code != http.StatusAccepted {+ t.Fatalf("invite member: status = %d, want %d (body=%q)", inviteRec.Code, http.StatusAccepted, inviteRec.Body.String())}- // Verify member list includes both users.+ // Verify the access list includes the active owner and the pending tech invite.listReq := httptest.NewRequest(http.MethodGet, "/api/accounts/"+accountID+"/members", nil)listReq.Header.Set("X-Admin-Key", "secret-key")listRec := httptest.NewRecorder()@@ -265,22 +265,23 @@ func TestMSPLifecycle_AccountToPortal(t *testing.T) {}var members []struct {- Email string `json:"email"`- Role registry.MemberRole `json:"role"`+ Email string `json:"email"`+ Role registry.MemberRole `json:"role"`+ State registry.AccountAccessState `json:"state"`}if err := json.Unmarshal(listRec.Body.Bytes(), &members); err != nil {t.Fatalf("decode members: %v", err)}if len(members) != 2 {- t.Fatalf("expected 2 members, got %d (%+v)", len(members), members)+ t.Fatalf("expected 2 access subjects, got %d (%+v)", len(members), members)}sort.Slice(members, func(i, j int) bool { return members[i].Email < members[j].Email })- if members[0].Email != "[email protected]" || members[0].Role != registry.MemberRoleOwner {- t.Fatalf("member[0] = %+v, want [email protected]/owner", members[0])+ if members[0].Email != "[email protected]" || members[0].Role != registry.MemberRoleOwner || members[0].State != registry.AccountAccessStateActive {+ t.Fatalf("member[0] = %+v, want [email protected]/owner/active", members[0])}- if members[1].Email != "[email protected]" || members[1].Role != registry.MemberRoleTech {- t.Fatalf("member[1] = %+v, want [email protected]/tech", members[1])+ if members[1].Email != "[email protected]" || members[1].Role != registry.MemberRoleTech || members[1].State != registry.AccountAccessStatePending {+ t.Fatalf("member[1] = %+v, want [email protected]/tech/pending", members[1])}// ── Phase 4: Portal dashboard ──────────────────────────────────────diff --git a/internal/cloudcp/stripe/provisioner.go b/internal/cloudcp/stripe/provisioner.goindex c86c2f14d4..c4ab7489f7 100644--- a/internal/cloudcp/stripe/provisioner.go+++ b/internal/cloudcp/stripe/provisioner.go@@ -897,7 +897,11 @@ func (p *Provisioner) ProvisionWorkspaceForOwner(ctx context.Context, accountID,State: registry.TenantStateProvisioning,PlanVersion: planVersion,}- if err := p.registry.Create(tenant); err != nil {+ workspaceLimit, knownWorkspaceLimit := pkglicensing.WorkspaceLimitForPlan(planVersion)+ if !knownWorkspaceLimit {+ workspaceLimit = pkglicensing.UnknownPlanDefaultWorkspaceLimit+ }+ if err := p.registry.CreateWithAccountWorkspaceLimit(tenant, workspaceLimit); err != nil {return nil, fmt.Errorf("create tenant record: %w", err)}cleanup.tenantID = tenantID