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 hosted tenant identity keys
rcourtman3e497ecb7040
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex d1ba1d56cb..a8b2215963 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -173,6 +173,11 @@ profile and assignment columns, but embedded table framing must route throughthe one-time `authToken` only and must not also send the long-lived`X-API-Token` header. The header-backed `agent:report` fallback exists onlyfor update-only re-registration when setup-token fetch is unavailable.+ Shared `internal/api/` session and auth changes consumed by lifecycle+ routes must preserve durable principal IDs as the authorization key. Agent+ lifecycle surfaces may display contact email when supplied by the shared+ auth boundary, but they must not reinterpret SSO or Stripe email as the+ canonical user identifier for setup, install, or fleet-management actions.That same lifecycle-owned setup path also owns script teardown behavior:rerunning the governed setup script in remove mode must call canonical`/api/auto-unregister` with `source:"script"` before local credentials arediff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 7cbcd0396c..314f4ab0b0 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -344,6 +344,11 @@ the canonical monitored-system blocked payload.repair org metadata, or upgrade roles on arrival. Handoff may mint a browser session only when the tenant orgalready contains the account as the owner or a member with a valid stored role, and tenant orgs with a blank`OwnerUserID` must fail closed instead of being claimed by the first owner-shaped handoff token.+ Hosted handoff session identity must bind to the signed stable user subject+ (`sub`/`UserID`) rather than the contact email. Email may participate only+ as legacy membership lookup and delivery metadata, and any canonicalization+ of email-keyed tenant membership must preserve the stored role instead of+ creating or elevating membership from the token.19. Keep tenant settings-scope authorization aligned with org management: `internal/api/security_setup_fix.go`, `internal/api/contract_test.go`, and settings-bound hosted callers must allow the current non-default org owner/admin membership to exercise privileged tenant routes, rather than requiring a separate configured local admin identity after hosted handoff.Hosted handoff must not be treated as an org-management side effect for that same privilege boundary. Onlycanonical invitation, membership-management, or explicit owner-transfer flows may create tenant membership ordiff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 472de490a3..e5b2a555c0 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -225,6 +225,12 @@ runtime gating as separate unlinked claims.portal-targeted magic link carrying tenant identity so the firstauthenticated landing is Pulse Account rather than a tenant-runtime-onlyredirect.+ Hosted tenant identity created from checkout, Pulse Account, or handoff+ must use the control-plane registry's stable `User.ID` as the tenant org+ owner/member principal. Stripe customer email and SSO email are contact and+ delivery metadata only; they may be used for idempotent lookup or legacy+ fallback, but they must not become the primary hosted tenant user key when a+ stable account user ID exists.That same portal boundary also owns the signed-in shell shape: hostedarrivals default to `Workspaces`, self-hosted-only arrivals default to`Billing`, and the shell destinations are limited to `Workspaces`,@@ -275,6 +281,10 @@ runtime gating as separate unlinked claims.signup. Repeated signup requests for the same owner email must resolve tothe existing tenant record instead of creating parallel orgs for oneaccount identity.+ The idempotency key remains the contact email only at the provisioning+ edge. Once a stable control-plane user exists, hosted org `OwnerUserID` and+ member `UserID` values must carry that durable user ID while owner/member+ email fields preserve delivery and display contact metadata.13. Add or change hosted billing-admin presentation through `frontend-modern/src/components/Settings/BillingAdminPanel.tsx`, `frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx`, and `frontend-modern/src/components/Settings/useBillingAdminPanelState.ts`14. Add or change shared commercial plan/usage presentation through `frontend-modern/src/components/Settings/CommercialBillingSections.tsx` and `frontend-modern/src/utils/commercialBillingModel.ts`15. Add or change organization billing and usage presentation through `frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx`, `frontend-modern/src/components/Settings/OrganizationBillingLoadingState.tsx`, and `frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts`diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.mdindex b386027503..367594f31e 100644--- a/docs/release-control/v6/internal/subsystems/organization-settings.md+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md@@ -164,6 +164,12 @@ settings surfaces. The organization settings panels now also normalize orgscope through `frontend-modern/src/utils/orgScope.ts` instead of carryingtheir own `getOrgID() || 'default'` fallbacks, so access, overview, andsharing views stay aligned with the shared multi-tenant org context contract.+That same membership model separates durable identity from contact metadata:+`OwnerUserID` and member `UserID` are the canonical principal keys when stable+control-plane user IDs exist, while `OwnerEmail` and member `Email` carry+delivery/display email. Email-shaped owner/member IDs remain only as legacy+fallback and migration input, and hosted handoff may canonicalize those records+to stable user IDs without changing the stored role.That same org-control surface also treats owner transfer as a re-auth-boundoperation. Existing membership remains a prerequisite for the target user, andthe acting owner must present a fresh browser session minted through thediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 692f0686ee..12067e7e4a 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -70,6 +70,10 @@ Storage/recovery auth-adjacent changes may consume SSO-authenticated sessions,but they must not reinterpret SAML or multi-provider SSO availability as astorage/recovery entitlement; that provider-route and license truth belongs tothe shared API/security boundary.+Storage/recovery may also consume org-scoped session identity from the shared+API boundary, but durable user IDs remain the authorization principal. Contact+email may support display or legacy lookup only; storage and recovery surfaces+must not create their own email-keyed membership or entitlement interpretation.1. Add or change recovery-point persistence, rollups, or series derivation through `internal/recovery/`2. Add or change recovery page UX through `frontend-modern/src/components/Recovery/` and keep canonical route/query/filter state ownership in `frontend-modern/src/features/recovery/useRecoverySurfaceState.ts`diff --git a/internal/api/cloud_handoff.go b/internal/api/cloud_handoff.goindex 243a8c00f4..311d77b796 100644--- a/internal/api/cloud_handoff.go+++ b/internal/api/cloud_handoff.go@@ -51,18 +51,24 @@ func HandleCloudHandoff(dataPath string) http.HandlerFunc {return}email := normalizeHandoffEmail(claims.Email)+ userID := strings.TrimSpace(claims.UserID)tenantID := strings.TrimSpace(claims.TenantID)- if email == "" || !isValidOrganizationID(tenantID) {+ if userID == "" {+ userID = email+ }+ if email == "" || userID == "" || !isValidOrganizationID(tenantID) {log.Warn().Str("tenant_id", tenantID).Msg("Cloud handoff token rejected due to invalid tenant ID")http.Redirect(w, r, "/login?error=handoff_invalid", http.StatusTemporaryRedirect)return}- if _, err := authorizeHandoffOrganizationMembership(dataPath, tenantID, email, claims.Role); err != nil {+ authz, err := authorizeHandoffOrganizationMembership(dataPath, tenantID, userID, email, claims.Role)+ if err != nil {if errors.Is(err, errHandoffAuthorizationDenied) {log.Warn().Err(err).Str("tenant_id", tenantID).Str("email", email).+ Str("user_id", userID).Msg("Cloud handoff authorization denied")http.Redirect(w, r, "/login?error=handoff_invalid", http.StatusTemporaryRedirect)return@@ -71,6 +77,7 @@ func HandleCloudHandoff(dataPath string) http.HandlerFunc {Err(err).Str("tenant_id", tenantID).Str("email", email).+ Str("user_id", userID).Msg("Cloud handoff authorization lookup failed")http.Error(w, "Internal server error", http.StatusInternalServerError)return@@ -102,8 +109,8 @@ func HandleCloudHandoff(dataPath string) http.HandlerFunc {userAgent := r.Header.Get("User-Agent")clientIP := GetClientIP(r)sessionDuration := 24 * time.Hour- GetSessionStore().CreateSession(sessionToken, sessionDuration, userAgent, clientIP, email)- TrackUserSession(email, sessionToken)+ GetSessionStore().CreateSession(sessionToken, sessionDuration, userAgent, clientIP, authz.UserID)+ TrackUserSession(authz.UserID, sessionToken)csrfToken := generateCSRFToken(sessionToken)isSecure, sameSitePolicy := getCookieSettings(r)@@ -137,6 +144,7 @@ func HandleCloudHandoff(dataPath string) http.HandlerFunc {log.Info().Str("email", email).+ Str("user_id", authz.UserID).Msg("Cloud handoff completed, session created")http.Redirect(w, r, "/", http.StatusTemporaryRedirect)diff --git a/internal/api/cloud_handoff_handlers.go b/internal/api/cloud_handoff_handlers.goindex b863d52283..d7678be915 100644--- a/internal/api/cloud_handoff_handlers.go+++ b/internal/api/cloud_handoff_handlers.go@@ -36,6 +36,12 @@ type cloudHandoffClaims struct {jwt.RegisteredClaims}+type handoffAuthorization struct {+ UserID string+ Email string+ Role models.OrganizationRole+}+type jtiReplayStore struct {once sync.Oncedb *sql.DB@@ -344,7 +350,8 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {return}claims.Email = normalizeHandoffEmail(claims.Email)- if strings.TrimSpace(claims.ID) == "" || strings.TrimSpace(claims.Subject) == "" || claims.Email == "" {+ subject := strings.TrimSpace(claims.Subject)+ if strings.TrimSpace(claims.ID) == "" || subject == "" || claims.Email == "" {http.Error(w, "invalid token", http.StatusUnauthorized)return}@@ -359,7 +366,7 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {return}- effectiveRole, err := authorizeHandoffOrganizationMembership(configDir, tenantID, claims.Email, claims.Role)+ authz, err := authorizeHandoffOrganizationMembership(configDir, tenantID, subject, claims.Email, claims.Role)if err != nil {if errors.Is(err, errHandoffAuthorizationDenied) {http.Error(w, "forbidden", http.StatusForbidden)@@ -381,8 +388,8 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {userAgent := r.Header.Get("User-Agent")clientIP := GetClientIP(r)sessionDuration := 24 * time.Hour- GetSessionStore().CreateSession(sessionToken, sessionDuration, userAgent, clientIP, claims.Email)- TrackUserSession(claims.Email, sessionToken)+ GetSessionStore().CreateSession(sessionToken, sessionDuration, userAgent, clientIP, authz.UserID)+ TrackUserSession(authz.UserID, sessionToken)csrfToken := generateCSRFToken(sessionToken)isSecure, sameSitePolicy := getCookieSettings(r)@@ -419,9 +426,9 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {"ok": true,"tenant_id": tenantID,"account_id": claims.AccountID,- "user_id": claims.Subject,- "email": claims.Email,- "role": string(effectiveRole),+ "user_id": authz.UserID,+ "email": authz.Email,+ "role": string(authz.Role),"jti": claims.ID,"exp": claims.ExpiresAt.Time.UTC().Format(time.RFC3339),}@@ -435,54 +442,58 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {}}-func authorizeHandoffOrganizationMembership(configDir, tenantID, email, role string) (models.OrganizationRole, error) {+func authorizeHandoffOrganizationMembership(configDir, tenantID, userID, email, role string) (*handoffAuthorization, error) {mtp := config.NewMultiTenantPersistence(configDir)org, err := mtp.LoadOrganization(tenantID)if err != nil {- return "", fmt.Errorf("load tenant organization %s: %w", tenantID, err)+ return nil, fmt.Errorf("load tenant organization %s: %w", tenantID, err)}if org == nil {- return "", fmt.Errorf("%w: tenant organization %s is missing", errHandoffAuthorizationDenied, tenantID)+ return nil, fmt.Errorf("%w: tenant organization %s is missing", errHandoffAuthorizationDenied, tenantID)}+ userID = strings.TrimSpace(userID)email = normalizeHandoffEmail(email)- if email == "" {- return "", fmt.Errorf("%w: handoff email is empty", errHandoffAuthorizationDenied)+ if userID == "" {+ userID = email}-- effectiveRole := models.OrganizationRole("")- if strings.EqualFold(strings.TrimSpace(org.OwnerUserID), email) {- effectiveRole = models.OrgRoleOwner- } else {- for i := range org.Members {- if !strings.EqualFold(strings.TrimSpace(org.Members[i].UserID), email) {- continue- }- effectiveRole = models.NormalizeOrganizationRole(org.Members[i].Role)- break- }+ if email == "" && strings.Contains(userID, "@") {+ email = normalizeHandoffEmail(userID)+ }+ if userID == "" {+ return nil, fmt.Errorf("%w: handoff user id is empty", errHandoffAuthorizationDenied)}+ effectiveRole := org.GetMemberRoleForPrincipal(userID, email)if effectiveRole == "" {- return "", fmt.Errorf("%w: no pre-existing membership for %s", errHandoffAuthorizationDenied, email)+ return nil, fmt.Errorf("%w: no pre-existing membership for %s", errHandoffAuthorizationDenied, userID)}if !models.IsValidOrganizationRole(effectiveRole) {- return "", fmt.Errorf("%w: stored role %q for %s is invalid", errHandoffAuthorizationDenied, effectiveRole, email)+ return nil, fmt.Errorf("%w: stored role %q for %s is invalid", errHandoffAuthorizationDenied, effectiveRole, userID)+ }+ if changed := org.CanonicalizePrincipalIdentity(userID, email); changed {+ if err := mtp.SaveOrganization(org); err != nil {+ return nil, fmt.Errorf("save canonicalized handoff identity for %s: %w", tenantID, err)+ }}if effectiveRole == models.OrgRoleOwner && strings.TrimSpace(org.OwnerUserID) == "" {- return "", fmt.Errorf("%w: tenant organization %s has blank owner", errHandoffAuthorizationDenied, tenantID)+ return nil, fmt.Errorf("%w: tenant organization %s has blank owner", errHandoffAuthorizationDenied, tenantID)}desiredRole := models.OrganizationRoleFromAccountRole(role)if !models.OrganizationRoleAtLeast(effectiveRole, desiredRole) {- return "", fmt.Errorf(+ return nil, fmt.Errorf("%w: requested role %q exceeds stored role %q for %s",errHandoffAuthorizationDenied,desiredRole,effectiveRole,- email,+ userID,)}- return effectiveRole, nil+ return &handoffAuthorization{+ UserID: userID,+ Email: email,+ Role: effectiveRole,+ }, nil}diff --git a/internal/api/cloud_handoff_handlers_test.go b/internal/api/cloud_handoff_handlers_test.goindex 728e4361cb..5f380c7263 100644--- a/internal/api/cloud_handoff_handlers_test.go+++ b/internal/api/cloud_handoff_handlers_test.go@@ -458,8 +458,8 @@ func TestHandleHandoffExchange(t *testing.T) {if session == nil {t.Fatal("expected session to exist")}- if session.Username != "[email protected]" {- t.Fatalf("session username = %q, want %q", session.Username, "[email protected]")+ if session.Username != "user-123" {+ t.Fatalf("session username = %q, want stable subject %q", session.Username, "user-123")}})}diff --git a/internal/api/cloud_handoff_test.go b/internal/api/cloud_handoff_test.goindex 36297f593f..bde5ad92a6 100644--- a/internal/api/cloud_handoff_test.go+++ b/internal/api/cloud_handoff_test.go@@ -184,10 +184,10 @@ func TestHandleCloudHandoffLowercasesSessionEmailIdentity(t *testing.T) {}sessionsMu.RLock()- tracked := append([]string(nil), allSessions["[email protected]"]...)+ tracked := append([]string(nil), allSessions["user-mixed-email"]...)sessionsMu.RUnlock()if len(tracked) == 0 {- t.Fatal("expected normalized user session to be tracked")+ t.Fatal("expected stable user session to be tracked")}var session *SessionData@@ -200,8 +200,8 @@ func TestHandleCloudHandoffLowercasesSessionEmailIdentity(t *testing.T) {if session == nil {t.Fatal("expected tracked session to exist in the session store")}- if session.Username != "[email protected]" {- t.Fatalf("session username = %q, want %q", session.Username, "[email protected]")+ if session.Username != "user-mixed-email" {+ t.Fatalf("session username = %q, want stable user id %q", session.Username, "user-mixed-email")}}@@ -258,9 +258,12 @@ func TestHandleCloudHandoffUsesExistingTenantOrganizationMembership(t *testing.Tif org.OwnerUserID != "[email protected]" {t.Fatalf("ownerUserID = %q, want %q", org.OwnerUserID, "[email protected]")}- if got := org.GetMemberRole("[email protected]"); got != models.OrgRoleOwner {+ if got := org.GetMemberRole("user-claims-membership"); got != models.OrgRoleOwner {t.Fatalf("member role = %q, want %q", got, models.OrgRoleOwner)}+ if got := org.Members[1].Email; got != "[email protected]" {+ t.Fatalf("canonicalized member email = %q, want %q", got, "[email protected]")+ }}func TestHandleCloudHandoffRejectsMissingTenantOrganizationMembership(t *testing.T) {diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex bb40322216..d9439ac44c 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -7059,8 +7059,11 @@ func TestContract_HostedCloudHandoffUsesExistingTenantOrganizationMembership(t *if org.OwnerUserID != "[email protected]" {t.Fatalf("ownerUserID=%q, want %q", org.OwnerUserID, "[email protected]")}- if got := org.GetMemberRole("[email protected]"); got != models.OrgRoleOwner {- t.Fatalf("member role=%q, want %q", got, models.OrgRoleOwner)+ if got := org.GetMemberRole("user-contract-membership"); got != models.OrgRoleOwner {+ t.Fatalf("stable member role=%q, want %q", got, models.OrgRoleOwner)+ }+ if got := org.Members[1].Email; got != "[email protected]" {+ t.Fatalf("canonicalized member email=%q, want %q", got, "[email protected]")}}@@ -7116,8 +7119,11 @@ func TestContract_HostedDirectCloudHandoffUsesExistingTenantMembership(t *testinif org.OwnerUserID != "[email protected]" {t.Fatalf("ownerUserID=%q, want %q", org.OwnerUserID, "[email protected]")}- if got := org.GetMemberRole("[email protected]"); got != models.OrgRoleOwner {- t.Fatalf("member role=%q, want %q", got, models.OrgRoleOwner)+ if got := org.GetMemberRole("user-direct-contract"); got != models.OrgRoleOwner {+ t.Fatalf("stable member role=%q, want %q", got, models.OrgRoleOwner)+ }+ if got := org.Members[1].Email; got != "[email protected]" {+ t.Fatalf("canonicalized member email=%q, want %q", got, "[email protected]")}}diff --git a/internal/api/magic_link_handlers.go b/internal/api/magic_link_handlers.goindex c6dedb8931..bb5321b4d0 100644--- a/internal/api/magic_link_handlers.go+++ b/internal/api/magic_link_handlers.go@@ -232,7 +232,7 @@ func (h *MagicLinkHandlers) findOrgForEmail(email string) (string, bool, error)if org == nil {continue}- if strings.EqualFold(org.OwnerUserID, email) {+ if strings.EqualFold(org.OwnerEmail, email) || strings.EqualFold(org.OwnerUserID, email) {return org.ID, true, nil}}@@ -241,7 +241,7 @@ func (h *MagicLinkHandlers) findOrgForEmail(email string) (string, bool, error)continue}for _, m := range org.Members {- if strings.EqualFold(m.UserID, email) {+ if strings.EqualFold(m.Email, email) || strings.EqualFold(m.UserID, email) {return org.ID, true, nil}}diff --git a/internal/api/payments_webhook_handlers.go b/internal/api/payments_webhook_handlers.goindex fa59bc147b..919206ac08 100644--- a/internal/api/payments_webhook_handlers.go+++ b/internal/api/payments_webhook_handlers.go@@ -313,12 +313,12 @@ func (h *StripeWebhookHandlers) handleCheckoutSessionCompleted(ctx context.Conteif h.magicLinks != nil && email != "" {// Only send a link to an existing org member/owner. Stripe customer email is user-controlled.sendTo := ""- if strings.EqualFold(org.OwnerUserID, email) {- sendTo = org.OwnerUserID+ if strings.EqualFold(org.OwnerEmail, email) || strings.EqualFold(org.OwnerUserID, email) {+ sendTo = email} else {for _, m := range org.Members {- if strings.EqualFold(m.UserID, email) {- sendTo = m.UserID+ if strings.EqualFold(m.Email, email) || strings.EqualFold(m.UserID, email) {+ sendTo = emailbreak}}diff --git a/internal/api/stripe_webhook_handlers_test.go b/internal/api/stripe_webhook_handlers_test.goindex 2d57fd573a..b3630b1356 100644--- a/internal/api/stripe_webhook_handlers_test.go+++ b/internal/api/stripe_webhook_handlers_test.go@@ -40,6 +40,15 @@ func (e *captureEmailer) Count() int {return len(e.calls)}+func (e *captureEmailer) LastTo() string {+ e.mu.Lock()+ defer e.mu.Unlock()+ if len(e.calls) == 0 {+ return ""+ }+ return e.calls[len(e.calls)-1].to+}+func createTestOrg(t *testing.T, persistence *config.MultiTenantPersistence, orgID, ownerEmail string) {t.Helper()@@ -434,6 +443,86 @@ func TestStripeWebhook_CheckoutCompleted_RetriesUntilLinkedOrgExists(t *testing.}}+func TestStripeWebhook_CheckoutCompleted_UsesContactEmailForStableOwnerIdentity(t *testing.T) {+ t.Setenv("STRIPE_WEBHOOK_SECRET", "whsec_test_stable_owner_contact")++ tmp := t.TempDir()+ persistence := config.NewMultiTenantPersistence(tmp)+ rbacProvider := NewTenantRBACProvider(tmp)+ billingStore := config.NewFileBillingStore(tmp)++ emailer := &captureEmailer{}+ magicLinks := NewMagicLinkServiceWithKey([]byte("01234567890123456789012345678901"), nil, emailer, nil)+ t.Cleanup(magicLinks.Stop)++ publicURL := func(_ *http.Request) string { return "https://pulse.example.test" }+ h := NewStripeWebhookHandlers(billingStore, persistence, rbacProvider, magicLinks, publicURL, true, tmp)++ orgID := "org_stable_owner_contact"+ if _, err := persistence.GetPersistence(orgID); err != nil {+ t.Fatalf("GetPersistence(%s): %v", orgID, err)+ }+ now := time.Now().UTC()+ if err := persistence.SaveOrganization(&models.Organization{+ ID: orgID,+ DisplayName: "Stable Owner Contact",+ CreatedAt: now,+ OwnerUserID: "u_owner_stable",+ OwnerEmail: "[email protected]",+ Members: []models.OrganizationMember{+ {+ UserID: "u_owner_stable",+ Email: "[email protected]",+ Role: models.OrgRoleOwner,+ AddedAt: now,+ AddedBy: "u_owner_stable",+ },+ },+ }); err != nil {+ t.Fatalf("SaveOrganization(%s): %v", orgID, err)+ }++ event := map[string]any{+ "id": "evt_checkout_stable_owner_contact",+ "type": "checkout.session.completed",+ "data": map[string]any{+ "object": map[string]any{+ "id": "cs_stable_owner_contact",+ "mode": "subscription",+ "customer": "cus_stable_owner_contact",+ "customer_email": "[email protected]",+ "subscription": "sub_stable_owner_contact",+ "metadata": map[string]any{+ "org_id": orgID,+ "org_name": "Stable Owner Contact",+ "plan_version": "cloud-v1",+ },+ },+ },+ }+ payload, err := json.Marshal(event)+ if err != nil {+ t.Fatalf("marshal event: %v", err)+ }+ signed := webhook.GenerateTestSignedPayload(&webhook.UnsignedPayload{+ Payload: payload,+ Secret: "whsec_test_stable_owner_contact",+ Timestamp: time.Now(),+ Scheme: "v1",+ })++ req := httptest.NewRequest(http.MethodPost, "/api/webhooks/stripe", bytes.NewReader(payload))+ req.Header.Set("Stripe-Signature", signed.Header)+ rr := httptest.NewRecorder()+ h.HandleStripeWebhook(rr, req)+ if rr.Code != http.StatusOK {+ t.Fatalf("status=%d, want %d: %s", rr.Code, http.StatusOK, rr.Body.String())+ }+ if got := emailer.LastTo(); got != "[email protected]" {+ t.Fatalf("magic link recipient=%q, want owner contact email", got)+ }+}+func TestStripeWebhook_DoesNotSendMagicLinkWithoutPublicURL(t *testing.T) {t.Setenv("STRIPE_WEBHOOK_SECRET", "whsec_test_no_url")diff --git a/internal/cloudcp/stripe/cloud_lifecycle_integration_test.go b/internal/cloudcp/stripe/cloud_lifecycle_integration_test.goindex 64919c8784..5a24185378 100644--- a/internal/cloudcp/stripe/cloud_lifecycle_integration_test.go+++ b/internal/cloudcp/stripe/cloud_lifecycle_integration_test.go@@ -125,8 +125,18 @@ func TestCloudLifecycle_CheckoutToBillingToMonitoredSystemLimits(t *testing.T) {if org.DisplayName != tenant.ID {t.Fatalf("org.DisplayName = %q, want %q", org.DisplayName, tenant.ID)}- if org.OwnerUserID != session.CustomerEmail {- t.Fatalf("org.OwnerUserID = %q, want %q", org.OwnerUserID, session.CustomerEmail)+ ownerUser, err := reg.GetUserByEmail(strings.ToLower(session.CustomerEmail))+ if err != nil {+ t.Fatalf("GetUserByEmail(%s): %v", session.CustomerEmail, err)+ }+ if ownerUser == nil {+ t.Fatalf("expected owner user for %s", session.CustomerEmail)+ }+ if org.OwnerUserID != ownerUser.ID {+ t.Fatalf("org.OwnerUserID = %q, want stable user id %q", org.OwnerUserID, ownerUser.ID)+ }+ if org.OwnerEmail != session.CustomerEmail {+ t.Fatalf("org.OwnerEmail = %q, want %q", org.OwnerEmail, session.CustomerEmail)}if org.GetMemberRole(session.CustomerEmail) != models.OrgRoleOwner {t.Fatalf("org role for %q = %q, want %q", session.CustomerEmail, org.GetMemberRole(session.CustomerEmail), models.OrgRoleOwner)diff --git a/internal/cloudcp/stripe/provisioner.go b/internal/cloudcp/stripe/provisioner.goindex 45de71de92..0b09f8a3ce 100644--- a/internal/cloudcp/stripe/provisioner.go+++ b/internal/cloudcp/stripe/provisioner.go@@ -197,16 +197,19 @@ func (p *Provisioner) buildSeededTenantOrganization(accountID, tenantID, display}type memberSeed struct {- email string- role models.OrganizationRole+ userID string+ email string+ role models.OrganizationRole}type ownerCandidate struct {+ userID stringemail stringcreatedAt time.Time}memberSeeds := map[string]memberSeed{}ownerEmail := strings.ToLower(strings.TrimSpace(fallbackOwnerEmail))+ ownerUserID := ""var fallbackOwner *ownerCandidateif p.registry != nil && strings.TrimSpace(accountID) != "" {@@ -229,18 +232,26 @@ func (p *Provisioner) buildSeededTenantOrganization(accountID, tenantID, displayif email == "" {return nil, fmt.Errorf("account member %s has empty email", membership.UserID)}+ userID := strings.TrimSpace(user.ID)+ if userID == "" {+ return nil, fmt.Errorf("account member %s has empty stable user id", membership.UserID)+ }role := models.OrganizationRoleFromAccountRole(string(membership.Role))- if existing, ok := memberSeeds[email]; !ok || models.OrganizationRoleAtLeast(role, existing.role) {- memberSeeds[email] = memberSeed{email: email, role: role}+ if existing, ok := memberSeeds[userID]; !ok || models.OrganizationRoleAtLeast(role, existing.role) {+ memberSeeds[userID] = memberSeed{userID: userID, email: email, role: role}+ }+ if ownerEmail != "" && ownerEmail == email {+ ownerUserID = userID}if membership.Role == registry.MemberRoleOwner {candidate := ownerCandidate{+ userID: userID,email: email,createdAt: membership.CreatedAt.UTC(),}if fallbackOwner == nil ||candidate.createdAt.Before(fallbackOwner.createdAt) ||- (candidate.createdAt.Equal(fallbackOwner.createdAt) && candidate.email < fallbackOwner.email) {+ (candidate.createdAt.Equal(fallbackOwner.createdAt) && candidate.userID < fallbackOwner.userID) {fallbackOwner = &candidate}}@@ -248,28 +259,48 @@ func (p *Provisioner) buildSeededTenantOrganization(accountID, tenantID, display}if ownerEmail == "" && fallbackOwner != nil {ownerEmail = fallbackOwner.email+ ownerUserID = fallbackOwner.userID}if ownerEmail != "" {- memberSeeds[ownerEmail] = memberSeed{email: ownerEmail, role: models.OrgRoleOwner}- org.OwnerUserID = ownerEmail+ if ownerUserID == "" && p.registry != nil {+ if user, err := p.registry.GetUserByEmail(ownerEmail); err != nil {+ return nil, fmt.Errorf("lookup owner user by email: %w", err)+ } else if user != nil {+ ownerUserID = strings.TrimSpace(user.ID)+ }+ }+ if ownerUserID == "" {+ ownerUserID = ownerEmail+ }+ memberSeeds[ownerUserID] = memberSeed{userID: ownerUserID, email: ownerEmail, role: models.OrgRoleOwner}+ org.OwnerUserID = ownerUserID+ org.OwnerEmail = ownerEmail}- memberEmails := make([]string, 0, len(memberSeeds))- for email := range memberSeeds {- memberEmails = append(memberEmails, email)+ memberIDs := make([]string, 0, len(memberSeeds))+ for userID := range memberSeeds {+ memberIDs = append(memberIDs, userID)}- sort.Strings(memberEmails)+ sort.Slice(memberIDs, func(i, j int) bool {+ left := memberSeeds[memberIDs[i]]+ right := memberSeeds[memberIDs[j]]+ if left.email != right.email {+ return left.email < right.email+ }+ return left.userID < right.userID+ })- members := make([]models.OrganizationMember, 0, len(memberEmails))- for _, email := range memberEmails {- seed := memberSeeds[email]+ members := make([]models.OrganizationMember, 0, len(memberIDs))+ for _, userID := range memberIDs {+ seed := memberSeeds[userID]addedBy := org.OwnerUserIDif addedBy == "" {- addedBy = seed.email+ addedBy = seed.userID}members = append(members, models.OrganizationMember{- UserID: seed.email,+ UserID: seed.userID,+ Email: seed.email,Role: seed.role,AddedAt: now,AddedBy: addedBy,diff --git a/internal/cloudcp/stripe/provisioner_rollback_test.go b/internal/cloudcp/stripe/provisioner_rollback_test.goindex 8773da8a4f..c05f3cf32a 100644--- a/internal/cloudcp/stripe/provisioner_rollback_test.go+++ b/internal/cloudcp/stripe/provisioner_rollback_test.go@@ -350,7 +350,7 @@ func TestBuildSeededTenantOrganization_UsesDeterministicOldestOwnerFallback(t *tt.Fatalf("CreateAccount: %v", err)}- createOwner := func(email string, createdAt int64) {+ createOwner := func(email string, createdAt int64) string {t.Helper()userID, err := registry.GenerateUserID()if err != nil {@@ -367,17 +367,21 @@ func TestBuildSeededTenantOrganization_UsesDeterministicOldestOwnerFallback(t *t}); err != nil {t.Fatalf("CreateMembership(%s): %v", email, err)}+ return userID}createOwner("[email protected]", 200)- createOwner("[email protected]", 100)+ oldOwnerID := createOwner("[email protected]", 100)org, err := p.buildSeededTenantOrganization(accountID, "t-example", "Example", "")if err != nil {t.Fatalf("buildSeededTenantOrganization: %v", err)}- if org.OwnerUserID != "[email protected]" {- t.Fatalf("org.OwnerUserID = %q, want %q", org.OwnerUserID, "[email protected]")+ if org.OwnerUserID != oldOwnerID {+ t.Fatalf("org.OwnerUserID = %q, want stable user id %q", org.OwnerUserID, oldOwnerID)+ }+ if org.OwnerEmail != "[email protected]" {+ t.Fatalf("org.OwnerEmail = %q, want %q", org.OwnerEmail, "[email protected]")}}@@ -398,7 +402,7 @@ func TestBuildSeededTenantOrganization_PrefersExplicitFallbackOwner(t *testing.Tt.Fatalf("CreateAccount: %v", err)}- createMember := func(email string, role registry.MemberRole, createdAt int64) {+ createMember := func(email string, role registry.MemberRole, createdAt int64) string {t.Helper()userID, err := registry.GenerateUserID()if err != nil {@@ -415,17 +419,21 @@ func TestBuildSeededTenantOrganization_PrefersExplicitFallbackOwner(t *testing.T}); err != nil {t.Fatalf("CreateMembership(%s): %v", email, err)}+ return userID}createMember("[email protected]", registry.MemberRoleOwner, 100)- createMember("[email protected]", registry.MemberRoleAdmin, 200)+ operatorID := createMember("[email protected]", registry.MemberRoleAdmin, 200)org, err := p.buildSeededTenantOrganization(accountID, "t-example", "Example", "[email protected]")if err != nil {t.Fatalf("buildSeededTenantOrganization: %v", err)}- if org.OwnerUserID != "[email protected]" {- t.Fatalf("org.OwnerUserID = %q, want %q", org.OwnerUserID, "[email protected]")+ if org.OwnerUserID != operatorID {+ t.Fatalf("org.OwnerUserID = %q, want stable user id %q", org.OwnerUserID, operatorID)+ }+ if org.OwnerEmail != "[email protected]" {+ t.Fatalf("org.OwnerEmail = %q, want %q", org.OwnerEmail, "[email protected]")}if org.GetMemberRole("[email protected]") != models.OrgRoleOwner {t.Fatalf("org role for [email protected] = %q, want %q", org.GetMemberRole("[email protected]"), models.OrgRoleOwner)@@ -457,12 +465,14 @@ func TestProvisionWorkspaceSeedsOrganizationMembershipsFromAccountMembers(t *test.Fatalf("CreateStripeAccount: %v", err)}+ userIDsByEmail := map[string]string{}createMember := func(email string, role registry.MemberRole) {t.Helper()userID, err := registry.GenerateUserID()if err != nil {t.Fatalf("GenerateUserID: %v", err)}+ userIDsByEmail[email] = userIDif err := reg.CreateUser(®istry.User{ID: userID, Email: email}); err != nil {t.Fatalf("CreateUser(%s): %v", email, err)}@@ -491,8 +501,11 @@ func TestProvisionWorkspaceSeedsOrganizationMembershipsFromAccountMembers(t *tesif err != nil {t.Fatalf("LoadOrganizationStrict(%s): %v", tenant.ID, err)}- if org.OwnerUserID != "[email protected]" {- t.Fatalf("org.OwnerUserID = %q, want %q", org.OwnerUserID, "[email protected]")+ if org.OwnerUserID != userIDsByEmail["[email protected]"] {+ t.Fatalf("org.OwnerUserID = %q, want stable user id %q", org.OwnerUserID, userIDsByEmail["[email protected]"])+ }+ if org.OwnerEmail != "[email protected]" {+ t.Fatalf("org.OwnerEmail = %q, want %q", org.OwnerEmail, "[email protected]")}wantRoles := map[string]models.OrganizationRole{@@ -508,6 +521,9 @@ func TestProvisionWorkspaceSeedsOrganizationMembershipsFromAccountMembers(t *tesif got := org.GetMemberRole(email); got != wantRole {t.Fatalf("org role for %q = %q, want %q", email, got, wantRole)}+ if got := org.GetMemberRole(userIDsByEmail[email]); got != wantRole {+ t.Fatalf("org role for stable user %q = %q, want %q", userIDsByEmail[email], got, wantRole)+ }}}diff --git a/internal/hosted/provisioner.go b/internal/hosted/provisioner.goindex 796faa9a5b..8a939f1bde 100644--- a/internal/hosted/provisioner.go+++ b/internal/hosted/provisioner.go@@ -172,7 +172,7 @@ func (p *Provisioner) findExistingOrganizationByOwnerEmail(email string) (*Proviif org == nil {continue}- if strings.EqualFold(strings.TrimSpace(org.OwnerUserID), email) {+ if strings.EqualFold(strings.TrimSpace(org.OwnerEmail), email) || strings.EqualFold(strings.TrimSpace(org.OwnerUserID), email) {return &ProvisionResult{OrgID: org.ID,UserID: strings.TrimSpace(org.OwnerUserID),@@ -246,9 +246,11 @@ func (p *Provisioner) createOrganization(ctx context.Context, orgID, userID, orgDisplayName: orgName,CreatedAt: now,OwnerUserID: userID,+ OwnerEmail: contactEmailForLegacyUserID(userID),Members: []models.OrganizationMember{{UserID: userID,+ Email: contactEmailForLegacyUserID(userID),Role: models.OrgRoleOwner,AddedAt: now,AddedBy: userID,@@ -285,6 +287,14 @@ func (p *Provisioner) createOrganization(ctx context.Context, orgID, userID, org}, nil}+func contactEmailForLegacyUserID(userID string) string {+ userID = strings.ToLower(strings.TrimSpace(userID))+ if strings.Contains(userID, "@") {+ return userID+ }+ return ""+}+func (p *Provisioner) cleanupOrgDirectory(orgID, dataDir string) {log.Warn().Str("org_id", orgID).diff --git a/internal/models/organization.go b/internal/models/organization.goindex 5c693843fa..53d3d3aa59 100644--- a/internal/models/organization.go+++ b/internal/models/organization.go@@ -134,6 +134,10 @@ type OrganizationMember struct {// UserID is the unique identifier of the member.UserID string `json:"userId"`+ // Email is the member's contact/display email. It is not the durable+ // identity key; legacy records may still have email-shaped UserID values.+ Email string `json:"email,omitempty"`+// Role is the member's role within the organization.Role OrganizationRole `json:"role"`@@ -216,6 +220,10 @@ type Organization struct {// The owner has full administrative rights and cannot be removed.OwnerUserID string `json:"ownerUserId,omitempty"`+ // OwnerEmail is the owner's contact/display email. It is not the durable+ // identity key; legacy records may still have email-shaped OwnerUserID values.+ OwnerEmail string `json:"ownerEmail,omitempty"`+// Members is the list of users who have access to this organization.// This includes the owner (with OrgRoleOwner) and any additional members.Members []OrganizationMember `json:"members,omitempty"`@@ -244,10 +252,69 @@ type Organization struct {EncryptionKeyID string `json:"encryptionKeyId,omitempty"`}+func normalizeOrganizationIdentityValue(value string) string {+ return strings.TrimSpace(value)+}++func normalizeOrganizationEmail(value string) string {+ return strings.ToLower(strings.TrimSpace(value))+}++func identityLooksLikeEmail(value string) bool {+ return strings.Contains(strings.TrimSpace(value), "@")+}++func memberEmail(member OrganizationMember) string {+ email := normalizeOrganizationEmail(member.Email)+ if email != "" {+ return email+ }+ if identityLooksLikeEmail(member.UserID) {+ return normalizeOrganizationEmail(member.UserID)+ }+ return ""+}++func memberMatchesUserID(member OrganizationMember, userID string) bool {+ userID = normalizeOrganizationIdentityValue(userID)+ return userID != "" && normalizeOrganizationIdentityValue(member.UserID) == userID+}++func memberMatchesEmail(member OrganizationMember, email string) bool {+ email = normalizeOrganizationEmail(email)+ return email != "" && memberEmail(member) == email+}++func ownerMatchesUserID(org *Organization, userID string) bool {+ if org == nil {+ return false+ }+ userID = normalizeOrganizationIdentityValue(userID)+ return userID != "" && normalizeOrganizationIdentityValue(org.OwnerUserID) == userID+}++func ownerMatchesEmail(org *Organization, email string) bool {+ if org == nil {+ return false+ }+ email = normalizeOrganizationEmail(email)+ if email == "" {+ return false+ }+ ownerEmail := normalizeOrganizationEmail(org.OwnerEmail)+ if ownerEmail != "" {+ return ownerEmail == email+ }+ if identityLooksLikeEmail(org.OwnerUserID) {+ return normalizeOrganizationEmail(org.OwnerUserID) == email+ }+ return false+}+// HasMember checks if a user is a member of the organization.func (o *Organization) HasMember(userID string) bool {for _, member := range o.Members {- if member.UserID == userID {+ if memberMatchesUserID(member, userID) || memberMatchesEmail(member, userID) {return true}}@@ -258,7 +325,7 @@ func (o *Organization) HasMember(userID string) bool {// Returns empty string if the user is not a member.func (o *Organization) GetMemberRole(userID string) OrganizationRole {for _, member := range o.Members {- if member.UserID == userID {+ if memberMatchesUserID(member, userID) || memberMatchesEmail(member, userID) {return NormalizeOrganizationRole(member.Role)}}@@ -267,12 +334,12 @@ func (o *Organization) GetMemberRole(userID string) OrganizationRole {// IsOwner checks if a user is the owner of the organization.func (o *Organization) IsOwner(userID string) bool {- return o.OwnerUserID == userID+ return ownerMatchesUserID(o, userID) || ownerMatchesEmail(o, userID)}// CanUserAccess checks if a user has any level of access to the organization.func (o *Organization) CanUserAccess(userID string) bool {- if o.OwnerUserID == userID {+ if o.IsOwner(userID) {return true}return o.HasMember(userID)@@ -280,8 +347,74 @@ func (o *Organization) CanUserAccess(userID string) bool {// CanUserManage checks if a user can manage the organization (owner or admin).func (o *Organization) CanUserManage(userID string) bool {- if o.OwnerUserID == userID {+ if o.IsOwner(userID) {return true}return OrganizationRoleAtLeast(o.GetMemberRole(userID), OrgRoleAdmin)}++// GetMemberRoleForPrincipal resolves a role using the durable user ID first,+// then email only as a legacy/contact fallback.+func (o *Organization) GetMemberRoleForPrincipal(userID, email string) OrganizationRole {+ if o == nil {+ return ""+ }+ if ownerMatchesUserID(o, userID) || ownerMatchesEmail(o, email) {+ return OrgRoleOwner+ }+ userID = normalizeOrganizationIdentityValue(userID)+ email = normalizeOrganizationEmail(email)+ for _, member := range o.Members {+ if memberMatchesUserID(member, userID) || memberMatchesEmail(member, email) {+ return NormalizeOrganizationRole(member.Role)+ }+ }+ return ""+}++// CanonicalizePrincipalIdentity upgrades legacy email-keyed membership records+// to a stable user ID while preserving email as contact metadata.+func (o *Organization) CanonicalizePrincipalIdentity(userID, email string) bool {+ if o == nil {+ return false+ }+ userID = normalizeOrganizationIdentityValue(userID)+ email = normalizeOrganizationEmail(email)+ if userID == "" || email == "" {+ return false+ }++ changed := false+ if ownerMatchesUserID(o, userID) || ownerMatchesEmail(o, email) {+ if normalizeOrganizationIdentityValue(o.OwnerUserID) != userID {+ o.OwnerUserID = userID+ changed = true+ }+ if normalizeOrganizationEmail(o.OwnerEmail) != email {+ o.OwnerEmail = email+ changed = true+ }+ }++ for i := range o.Members {+ member := o.Members[i]+ if !memberMatchesUserID(member, userID) && !memberMatchesEmail(member, email) {+ continue+ }+ oldUserID := normalizeOrganizationIdentityValue(member.UserID)+ if oldUserID != userID {+ o.Members[i].UserID = userID+ changed = true+ }+ if normalizeOrganizationEmail(member.Email) != email {+ o.Members[i].Email = email+ changed = true+ }+ if addedBy := normalizeOrganizationIdentityValue(member.AddedBy); addedBy != "" && (addedBy == oldUserID || normalizeOrganizationEmail(addedBy) == email) && addedBy != userID {+ o.Members[i].AddedBy = userID+ changed = true+ }+ }++ return changed+}diff --git a/internal/models/organization_additional_test.go b/internal/models/organization_additional_test.goindex 4e3f014250..0fa10e995d 100644--- a/internal/models/organization_additional_test.go+++ b/internal/models/organization_additional_test.go@@ -32,6 +32,36 @@ func TestOrganizationAccessors(t *testing.T) {}}+func TestOrganizationPrincipalIdentityCanonicalization(t *testing.T) {+ org := &Organization{+ ID: "org-1",+ OwnerUserID: "[email protected]",+ Members: []OrganizationMember{+ {UserID: "[email protected]", Role: OrgRoleOwner, AddedBy: "[email protected]"},+ {UserID: "[email protected]", Role: OrgRoleAdmin, AddedBy: "[email protected]"},+ },+ }++ if role := org.GetMemberRoleForPrincipal("u_owner", "[email protected]"); role != OrgRoleOwner {+ t.Fatalf("owner role = %q, want %q", role, OrgRoleOwner)+ }+ if !org.CanonicalizePrincipalIdentity("u_owner", "[email protected]") {+ t.Fatal("expected owner identity to be canonicalized")+ }+ if org.OwnerUserID != "u_owner" || org.OwnerEmail != "[email protected]" {+ t.Fatalf("owner identity = (%q, %q), want stable id + email", org.OwnerUserID, org.OwnerEmail)+ }+ if got := org.GetMemberRole("u_owner"); got != OrgRoleOwner {+ t.Fatalf("stable owner role = %q, want %q", got, OrgRoleOwner)+ }+ if got := org.GetMemberRole("[email protected]"); got != OrgRoleOwner {+ t.Fatalf("legacy email owner role = %q, want %q", got, OrgRoleOwner)+ }+ if got := org.Members[0].Email; got != "[email protected]" {+ t.Fatalf("member email = %q, want %q", got, "[email protected]")+ }+}+func TestOrganizationRoleNormalization(t *testing.T) {if got := NormalizeOrganizationRole("member"); got != OrganizationRole("member") {t.Fatalf("expected member to remain unchanged, got %q", got)