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
Pin hosted identity invariants
rcourtman7829c3e6edd9
diff --git a/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md b/docs/release-control/v6/internal/IDENTITY_INVARIANTS.mdnew file mode 100644index 0000000000..0b682bc1b4--- /dev/null+++ b/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md@@ -0,0 +1,87 @@+# Pulse Identity Invariants++This file captures the stable identity contract for v6 runtime and agent-ready+work. It is deliberately stricter than display naming: anything that can grant+access, bind billing, own an organization, or authorize an action needs a+durable key that is not silently replaced by email.++## Core Rule++Email is contact metadata. It may be used for delivery, display, lookup,+rate-limiting, and legacy migration boundaries, but it must not be the durable+principal once a stable user ID exists.++## Canonical Identifiers++1. Pulse control-plane user ID+ - Shape: `u_...` from `internal/cloudcp/registry`.+ - Owns: Pulse Account user identity and hosted tenant membership principal.+ - Email role: contact/display/delivery metadata through registry user email,+ organization `OwnerEmail`, and member `Email`.++2. Pulse account ID+ - Shape: `a_...` from `internal/cloudcp/registry`.+ - Owns: commercial account/workspace grouping, MSP/customer account scope,+ invitations, and account membership.+ - Must not be inferred from email.++3. Hosted tenant ID+ - Shape: `t_...` from `internal/cloudcp/registry`.+ - Owns: hosted workspace runtime, tenant data directory, handoff audience,+ and tenant organization scope.+ - Must not be inferred from Stripe email or SSO email.++4. Organization ID+ - Shape: org-safe identifier validated by the API/config boundary.+ - Owns: local organization metadata, RBAC/share scope, org cookie scope, and+ tenant org metadata.+ - Organization owner/member principals should be stable user IDs when the+ control plane has one; email-shaped user IDs are legacy fallback only.++5. Stripe customer and subscription IDs+ - Shape: Stripe IDs such as `cus_...` and `sub_...`.+ - Owns: billing linkage and subscription lifecycle only.+ - Stripe `customer_email` is delivery/contact evidence, not identity+ authority. It may send a magic link only when it matches existing stored+ owner/member contact metadata or a legacy email-keyed member.++6. SSO provider subject+ - Shape: provider-scoped OIDC `sub` or SAML `NameID`, paired with provider ID.+ - Owns: external identity continuity for SSO.+ - Email role: access restriction, contact, display, and legacy username+ fallback. A future SSO migration must move self-hosted RBAC from unscoped+ username/email keys to provider-scoped subject keys with a compatibility+ migration, not by changing session names silently.++7. API token ID/hash+ - Shape: token hash plus token metadata in config/auth storage.+ - Owns: API credential identity, scope, and revocation.+ - `owner_user_id` metadata must carry the authenticated principal, not an+ arbitrary email copied from a browser payload.++8. Mobile/relay device identity+ - Shape: relay/mobile device registration IDs and platform device tokens.+ - Owns: device trust, push routing, and pairing state.+ - Email must not be used as a device key.++## Runtime Requirements++1. Handoff sessions bind to the signed stable subject or `UserID`, then verify+ that subject against existing server-side organization membership.+2. Magic-link sessions bind to the stored organization principal resolved from+ contact email at verification time, not to the email embedded in the token.+3. Hosted checkout and tenant provisioning seed organization membership from+ registry user IDs. Contact email is copied separately.+4. Webhook payloads must never create organizations or memberships from email.+ They may update billing only after server-owned org/customer linkage exists.+5. Legacy email-keyed records may be accepted only at migration boundaries and+ should be canonicalized to stable user IDs when the stable ID is known.++## Current Explicit Exception++Self-hosted local auth and SSO RBAC still use the historical `username` session+field as the local principal. That is a compatibility boundary, not the desired+long-term model for SSO. Any future SSO hardening must introduce a provider-+scoped stable principal and migration path for existing RBAC assignments,+audit records, and active sessions instead of substituting email with another+display claim in-place.diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 2de1dcadf7..92350887c4 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -185,6 +185,10 @@ profile and assignment columns, but embedded table framing must route throughlifecycle surfaces may display contact email when supplied by the sharedauth boundary, but they must not reinterpret SSO or Stripe email as thecanonical user identifier for setup, install, or fleet-management actions.+ The canonical durable-principal vocabulary for those shared auth routes is+ recorded in `docs/release-control/v6/internal/IDENTITY_INVARIANTS.md`; agent+ lifecycle work may consume that identity but must not define a parallel+ email-keyed actor model for fleet operations.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 44ff8767fc..5bf27e8451 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -359,6 +359,10 @@ the canonical monitored-system blocked payload.as legacy membership lookup and delivery metadata, and any canonicalizationof email-keyed tenant membership must preserve the stored role instead ofcreating or elevating membership from the token.+ Hosted magic-link verification follows the same API/session identity rule:+ the token may carry contact email for delivery, but `/api/public/magic-link/verify`+ must resolve that email against current server-side organization metadata+ and create the browser session for the stored owner/member principal.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 e5b2a555c0..d6115b88a2 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -231,6 +231,10 @@ runtime gating as separate unlinked claims.delivery metadata only; they may be used for idempotent lookup or legacyfallback, but they must not become the primary hosted tenant user key when astable account user ID exists.+ Hosted magic links are a delivery mechanism inside that same boundary:+ verification must re-read the tenant organization and session as the stored+ stable owner/member principal, so an old token cannot keep email as the+ runtime identity or survive removal from tenant membership.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`,diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.mdindex 367594f31e..59482f9af3 100644--- a/docs/release-control/v6/internal/subsystems/organization-settings.md+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md@@ -170,6 +170,11 @@ control-plane user IDs exist, while `OwnerEmail` and member `Email` carrydelivery/display email. Email-shaped owner/member IDs remain only as legacyfallback and migration input, and hosted handoff may canonicalize those recordsto stable user IDs without changing the stored role.+Email-delivery flows that need to mint sessions, including hosted magic links,+must resolve contact email back through this organization model before+authorizing. `internal/models/organization.go` owns the email-to-principal+helper so handlers do not duplicate membership lookup or accidentally bind+sessions to email.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/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex c6992ded08..5ddcd1233a 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -112,6 +112,10 @@ controls as normal product settings.receive distinct bounded replacement tokens for one session, but explicitsession deletion, password-change invalidation, and logout must invalidateevery retained CSRF hash for that session.+ Auth and session changes that involve hosted, SSO, or commercial identity+ must also preserve `docs/release-control/v6/internal/IDENTITY_INVARIANTS.md`:+ email is contact metadata once a stable principal exists, and browser+ sessions must bind to the durable principal rather than a delivery address.5. Change security/privacy settings presentation through the shared `frontend-modern/src/components/Settings/APIAccessPanel.tsx`, `frontend-modern/src/components/Settings/GeneralSettingsPanel.tsx`, `frontend-modern/src/components/Settings/SecurityAuthPanel.tsx`, `frontend-modern/src/components/Settings/SecurityOverviewPanel.tsx`, `frontend-modern/src/components/Settings/QuickSecuritySetup.tsx`, `frontend-modern/src/components/Settings/SecurityPostureSummary.tsx`, `frontend-modern/src/components/Settings/SSOProviderTypeIcon.tsx`, `frontend-modern/src/constants/apiScopes.ts`, `frontend-modern/src/utils/apiTokenPresentation.ts`, `frontend-modern/src/utils/securityAuthPresentation.ts`, `frontend-modern/src/utils/securityScorePresentation.ts`, `frontend-modern/src/utils/auditLogPresentation.ts`, and `frontend-modern/src/utils/auditWebhookPresentation.ts` boundary.6. Change operator-facing telemetry/adoption reporting through `scripts/telemetry_adoption_report.py` together with the privacy disclosure whenever release-identity interpretation changes.7. Change data-at-rest encryption-key or control-plane magic-link HMAC key and storage-root hardening semantics through `internal/crypto/crypto.go`, `internal/cloudcp/auth/magiclink.go`, `internal/cloudcp/auth/magiclink_store.go`, and `internal/securityutil/secure_storage_dir.go` together so writable-but-not-owned runtime storage mounts stay supported without weakening file-level secrecy.@@ -151,6 +155,11 @@ controls as normal product settings.quickstart/trial transport as absent from normal self-hosted v6 GA docs.Both disclosures must state that governed resource details useresource-policy redaction before non-local model transport.+11. Keep durable identity and email-contact semantics aligned with the+ canonical identity invariant record. Hosted and commercial auth paths must+ use stable Pulse user/account/tenant IDs where they exist; SSO subject+ migration must be explicit and compatible rather than silently substituting+ email or display claims as durable principals.## Current Statediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 28779a0af2..0def1e907d 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -74,6 +74,10 @@ Storage/recovery may also consume org-scoped session identity from the sharedAPI boundary, but durable user IDs remain the authorization principal. Contactemail may support display or legacy lookup only; storage and recovery surfacesmust not create their own email-keyed membership or entitlement interpretation.+The canonical actor vocabulary for those shared sessions is+`docs/release-control/v6/internal/IDENTITY_INVARIANTS.md`; recovery and storage+work may consume accepted org access, but must not mint or widen access from a+delivery email.Storage/recovery remediation or restore-adjacent workflows may consume`POST /api/actions/plan` only as the API-owned resource capability planningcontract. This subsystem must not create a storage-local approval policy,diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex d3f7cc5f53..cbec720bf5 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -104,6 +104,14 @@ func TestContract_HostedMagicLinkStablePrincipalProof(t *testing.T) {if !strings.Contains(string(invariantDoc), "Email is contact metadata") {t.Fatal("identity invariant contract must define email as contact metadata")}++ modelSource, err := os.ReadFile(filepath.Clean("../models/organization.go"))+ if err != nil {+ t.Fatalf("read organization model: %v", err)+ }+ if !strings.Contains(string(modelSource), "ResolvePrincipalByEmail") {+ t.Fatal("organization model must expose email-to-stable-principal resolution")+ }}func TestContractAISettingsClampsPaidRuntimeControlsToEntitlements(t *testing.T) {diff --git a/internal/api/identity_invariant_contract_test.go b/internal/api/identity_invariant_contract_test.gonew file mode 100644index 0000000000..718b411172--- /dev/null+++ b/internal/api/identity_invariant_contract_test.go@@ -0,0 +1,99 @@+package api++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func readIdentityContractFile(t *testing.T, rel string) string {+ t.Helper()+ body, err := os.ReadFile(filepath.Clean(rel))+ if err != nil {+ t.Fatalf("read %s: %v", rel, err)+ }+ return string(body)+}++func TestContract_HostedIdentityUsesStablePrincipals(t *testing.T) {+ files := map[string]string{+ "magic_link_handlers.go": readIdentityContractFile(t, "magic_link_handlers.go"),+ "cloud_handoff.go": readIdentityContractFile(t, "cloud_handoff.go"),+ "cloud_handoff_handlers.go": readIdentityContractFile(t, "cloud_handoff_handlers.go"),+ "payments_webhook_handlers.go": readIdentityContractFile(t, "payments_webhook_handlers.go"),+ "../cloudcp/stripe/provisioner.go": readIdentityContractFile(t, "../cloudcp/stripe/provisioner.go"),+ "../models/organization.go": readIdentityContractFile(t, "../models/organization.go"),+ "../../docs/release-control/v6/internal/IDENTITY_INVARIANTS.md": readIdentityContractFile(t, "../../docs/release-control/v6/internal/IDENTITY_INVARIANTS.md"),+ }++ required := map[string][]string{+ "magic_link_handlers.go": {+ "resolveMagicLinkPrincipal",+ "CreateSession(sessionToken, sessionDuration, userAgent, clientIP, principal.UserID)",+ "TrackUserSession(principal.UserID, sessionToken)",+ },+ "cloud_handoff.go": {+ "CreateSession(sessionToken, sessionDuration, userAgent, clientIP, authz.UserID)",+ "TrackUserSession(authz.UserID, sessionToken)",+ },+ "cloud_handoff_handlers.go": {+ "CreateSession(sessionToken, sessionDuration, userAgent, clientIP, authz.UserID)",+ "TrackUserSession(authz.UserID, sessionToken)",+ },+ "../cloudcp/stripe/provisioner.go": {+ "ownerUserID = strings.TrimSpace(user.ID)",+ "org.OwnerEmail = ownerEmail",+ "UserID: seed.userID",+ "Email: seed.email",+ },+ "../models/organization.go": {+ "OwnerEmail string",+ "ResolvePrincipalByEmail",+ "CanonicalizePrincipalIdentity",+ },+ "../../docs/release-control/v6/internal/IDENTITY_INVARIANTS.md": {+ "Email is contact metadata",+ "Pulse control-plane user ID",+ "SSO provider subject",+ },+ }+ for file, needles := range required {+ for _, needle := range needles {+ if !strings.Contains(files[file], needle) {+ t.Fatalf("%s must contain %q", file, needle)+ }+ }+ }++ forbidden := map[string][]string{+ "magic_link_handlers.go": {+ "CreateSession(sessionToken, sessionDuration, userAgent, clientIP, token.Email)",+ "TrackUserSession(token.Email, sessionToken)",+ },+ "cloud_handoff.go": {+ "CreateSession(sessionToken, sessionDuration, userAgent, clientIP, email)",+ "TrackUserSession(email, sessionToken)",+ },+ "cloud_handoff_handlers.go": {+ "CreateSession(sessionToken, sessionDuration, userAgent, clientIP, claims.Email)",+ "TrackUserSession(claims.Email, sessionToken)",+ },+ "payments_webhook_handlers.go": {+ "sendTo = org.OwnerUserID",+ "sendTo = m.UserID",+ },+ "../cloudcp/stripe/provisioner.go": {+ "org.OwnerUserID = ownerEmail",+ "UserID: seed.email",+ "memberSeeds[ownerEmail]",+ },+ }+ for file, needles := range forbidden {+ for _, needle := range needles {+ if strings.Contains(files[file], needle) {+ t.Fatalf("%s must not contain legacy email-principal pattern %q", file, needle)+ }+ }+ }+}diff --git a/internal/api/magic_link_handlers.go b/internal/api/magic_link_handlers.goindex bb5321b4d0..bf407c199e 100644--- a/internal/api/magic_link_handlers.go+++ b/internal/api/magic_link_handlers.go@@ -2,11 +2,13 @@ package apiimport ("encoding/json"+ "fmt""net/http""strings""time""github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rs/zerolog/log")@@ -33,6 +35,12 @@ func NewMagicLinkHandlers(}}+type magicLinkPrincipal struct {+ UserID string+ Email string+ Role models.OrganizationRole+}+func (h *MagicLinkHandlers) HandlePublicMagicLinkRequest(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)@@ -156,6 +164,16 @@ func (h *MagicLinkHandlers) HandlePublicMagicLinkVerify(w http.ResponseWriter, rwriteErrorResponse(w, http.StatusBadRequest, "invalid_magic_link", "Invalid or expired magic link", nil)return}+ principal, err := h.resolveMagicLinkPrincipal(token.OrgID, token.Email)+ if err != nil {+ log.Warn().Err(err).Str("org_id", token.OrgID).Str("email", token.Email).Msg("Magic link verify: failed to resolve stable principal")+ if !strings.Contains(r.Header.Get("Accept"), "application/json") {+ http.Redirect(w, r, "/login?error=magic_link_invalid", http.StatusTemporaryRedirect)+ return+ }+ writeErrorResponse(w, http.StatusBadRequest, "invalid_magic_link", "Invalid or expired magic link", nil)+ return+ }// Invalidate any pre-existing session to prevent session fixation attacks.InvalidateOldSessionFromRequest(r)@@ -170,8 +188,8 @@ func (h *MagicLinkHandlers) HandlePublicMagicLinkVerify(w http.ResponseWriter, ruserAgent := r.Header.Get("User-Agent")clientIP := GetClientIP(r)sessionDuration := 24 * time.Hour- GetSessionStore().CreateSession(sessionToken, sessionDuration, userAgent, clientIP, token.Email)- TrackUserSession(token.Email, sessionToken)+ GetSessionStore().CreateSession(sessionToken, sessionDuration, userAgent, clientIP, principal.UserID)+ TrackUserSession(principal.UserID, sessionToken)csrfToken := generateCSRFToken(sessionToken)isSecure, sameSitePolicy := getCookieSettings(r)@@ -209,7 +227,8 @@ func (h *MagicLinkHandlers) HandlePublicMagicLinkVerify(w http.ResponseWriter, rwriteJSON(w, http.StatusOK, map[string]interface{}{"success": true,"org_id": token.OrgID,- "user_id": token.Email,+ "user_id": principal.UserID,+ "email": principal.Email,})return}@@ -248,3 +267,31 @@ func (h *MagicLinkHandlers) findOrgForEmail(email string) (string, bool, error)}return "", false, nil}++func (h *MagicLinkHandlers) resolveMagicLinkPrincipal(orgID, email string) (*magicLinkPrincipal, error) {+ if h == nil || h.persistence == nil {+ return nil, fmt.Errorf("organization persistence is not configured")+ }+ orgID = strings.TrimSpace(orgID)+ email = strings.ToLower(strings.TrimSpace(email))+ if !isValidOrganizationID(orgID) || email == "" {+ return nil, fmt.Errorf("invalid magic link principal input")+ }++ org, err := h.persistence.LoadOrganizationStrict(orgID)+ if err != nil {+ return nil, fmt.Errorf("load organization %s: %w", orgID, err)+ }+ userID, role, ok := org.ResolvePrincipalByEmail(email)+ if !ok {+ return nil, fmt.Errorf("no organization principal for magic link email")+ }+ if userID == "" || !models.IsValidOrganizationRole(role) {+ return nil, fmt.Errorf("invalid organization principal for magic link email")+ }+ return &magicLinkPrincipal{+ UserID: userID,+ Email: email,+ Role: role,+ }, nil+}diff --git a/internal/api/magic_link_handlers_test.go b/internal/api/magic_link_handlers_test.goindex c90a77e015..5439dccb98 100644--- a/internal/api/magic_link_handlers_test.go+++ b/internal/api/magic_link_handlers_test.go@@ -1,10 +1,14 @@package apiimport (+ "encoding/json""net/http""net/http/httptest""testing""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models")func TestHandlePublicMagicLinkVerifyRejectsInvalidOrgIDInToken(t *testing.T) {@@ -41,3 +45,157 @@ func TestHandlePublicMagicLinkVerifyRejectsInvalidOrgIDInToken(t *testing.T) {}}}++func TestHandlePublicMagicLinkVerifyUsesStableOrganizationPrincipal(t *testing.T) {+ resetPersistentAuthStoresForTests()+ t.Cleanup(resetPersistentAuthStoresForTests)+ sessionsMu.Lock()+ allSessions = make(map[string][]string)+ sessionsMu.Unlock()++ dataDir := t.TempDir()+ InitSessionStore(dataDir)+ InitCSRFStore(dataDir)+ persistence := config.NewMultiTenantPersistence(dataDir)++ now := time.Now().UTC()+ org := &models.Organization{+ ID: "org_magic_stable",+ DisplayName: "Magic Stable",+ CreatedAt: now,+ OwnerUserID: "u_owner_magic",+ OwnerEmail: "[email protected]",+ Members: []models.OrganizationMember{+ {+ UserID: "u_owner_magic",+ Email: "[email protected]",+ Role: models.OrgRoleOwner,+ AddedAt: now,+ AddedBy: "u_owner_magic",+ },+ },+ }+ if err := persistence.SaveOrganization(org); err != nil {+ t.Fatalf("SaveOrganization: %v", err)+ }++ key := []byte("0123456789abcdef0123456789abcdef")+ store := NewInMemoryMagicLinkStore()+ svc := NewMagicLinkServiceWithKey(key, store, nil, nil)+ t.Cleanup(func() { svc.Stop() })+ token, err := svc.GenerateToken("[email protected]", org.ID)+ if err != nil {+ t.Fatalf("GenerateToken: %v", err)+ }++ h := NewMagicLinkHandlers(persistence, svc, true, nil)+ req := httptest.NewRequest(http.MethodGet, "/api/public/magic-link/verify?format=json&token="+token, nil)+ req.Header.Set("Accept", "application/json")+ rec := httptest.NewRecorder()+ h.HandlePublicMagicLinkVerify(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String())+ }+ var payload struct {+ Success bool `json:"success"`+ OrgID string `json:"org_id"`+ UserID string `json:"user_id"`+ Email string `json:"email"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if !payload.Success || payload.OrgID != org.ID || payload.UserID != "u_owner_magic" || payload.Email != "[email protected]" {+ t.Fatalf("payload = %+v, want stable user id and contact email", payload)+ }++ var sessionToken string+ for _, cookie := range rec.Result().Cookies() {+ if cookie.Name == cookieNameSession {+ sessionToken = cookie.Value+ break+ }+ }+ if sessionToken == "" {+ t.Fatal("expected session cookie")+ }+ session := GetSessionStore().GetSession(sessionToken)+ if session == nil {+ t.Fatal("expected stored session")+ }+ if session.Username != "u_owner_magic" {+ t.Fatalf("session username = %q, want stable user id", session.Username)+ }+ sessionsMu.RLock()+ tracked := append([]string(nil), allSessions["u_owner_magic"]...)+ emailTracked := append([]string(nil), allSessions["[email protected]"]...)+ sessionsMu.RUnlock()+ if len(tracked) != 1 || tracked[0] != sessionToken {+ t.Fatalf("tracked stable sessions = %v, want [%s]", tracked, sessionToken)+ }+ if len(emailTracked) != 0 {+ t.Fatalf("email-keyed sessions = %v, want none", emailTracked)+ }+}++func TestHandlePublicMagicLinkVerifyRejectsRemovedOrganizationMember(t *testing.T) {+ resetPersistentAuthStoresForTests()+ t.Cleanup(resetPersistentAuthStoresForTests)++ dataDir := t.TempDir()+ InitSessionStore(dataDir)+ InitCSRFStore(dataDir)+ persistence := config.NewMultiTenantPersistence(dataDir)++ now := time.Now().UTC()+ if err := persistence.SaveOrganization(&models.Organization{+ ID: "org_magic_removed",+ DisplayName: "Magic Removed",+ CreatedAt: now,+ OwnerUserID: "u_owner_magic",+ OwnerEmail: "[email protected]",+ Members: []models.OrganizationMember{+ {UserID: "u_owner_magic", Email: "[email protected]", Role: models.OrgRoleOwner, AddedAt: now},+ },+ }); err != nil {+ t.Fatalf("SaveOrganization initial: %v", err)+ }++ key := []byte("0123456789abcdef0123456789abcdef")+ store := NewInMemoryMagicLinkStore()+ svc := NewMagicLinkServiceWithKey(key, store, nil, nil)+ t.Cleanup(func() { svc.Stop() })+ token, err := svc.GenerateToken("[email protected]", "org_magic_removed")+ if err != nil {+ t.Fatalf("GenerateToken: %v", err)+ }++ if err := persistence.SaveOrganization(&models.Organization{+ ID: "org_magic_removed",+ DisplayName: "Magic Removed",+ CreatedAt: now,+ OwnerUserID: "u_other_owner",+ OwnerEmail: "[email protected]",+ Members: []models.OrganizationMember{+ {UserID: "u_other_owner", Email: "[email protected]", Role: models.OrgRoleOwner, AddedAt: now},+ },+ }); err != nil {+ t.Fatalf("SaveOrganization removed: %v", err)+ }++ h := NewMagicLinkHandlers(persistence, svc, true, nil)+ req := httptest.NewRequest(http.MethodGet, "/api/public/magic-link/verify?format=json&token="+token, nil)+ req.Header.Set("Accept", "application/json")+ rec := httptest.NewRecorder()+ h.HandlePublicMagicLinkVerify(rec, req)++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400: %s", rec.Code, rec.Body.String())+ }+ for _, cookie := range rec.Result().Cookies() {+ if cookie.Name == cookieNameSession {+ t.Fatalf("did not expect session cookie for removed member")+ }+ }+}diff --git a/internal/models/organization.go b/internal/models/organization.goindex 53d3d3aa59..977e555493 100644--- a/internal/models/organization.go+++ b/internal/models/organization.go@@ -372,6 +372,37 @@ func (o *Organization) GetMemberRoleForPrincipal(userID, email string) Organizatreturn ""}+// ResolvePrincipalByEmail returns the durable principal for a contact email.+// It is intended for email-delivery flows such as magic links where the email+// proves delivery but the session should still bind to the stored user ID.+func (o *Organization) ResolvePrincipalByEmail(email string) (string, OrganizationRole, bool) {+ if o == nil {+ return "", "", false+ }+ email = normalizeOrganizationEmail(email)+ if email == "" {+ return "", "", false+ }+ if ownerMatchesEmail(o, email) {+ userID := normalizeOrganizationIdentityValue(o.OwnerUserID)+ if userID == "" {+ userID = email+ }+ return userID, OrgRoleOwner, true+ }+ for _, member := range o.Members {+ if !memberMatchesEmail(member, email) {+ continue+ }+ userID := normalizeOrganizationIdentityValue(member.UserID)+ if userID == "" {+ userID = email+ }+ return userID, NormalizeOrganizationRole(member.Role), true+ }+ return "", "", false+}+// 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 {diff --git a/internal/models/organization_additional_test.go b/internal/models/organization_additional_test.goindex 0fa10e995d..c27d25c8fd 100644--- a/internal/models/organization_additional_test.go+++ b/internal/models/organization_additional_test.go@@ -62,6 +62,34 @@ func TestOrganizationPrincipalIdentityCanonicalization(t *testing.T) {}}+func TestOrganizationResolvePrincipalByEmail(t *testing.T) {+ org := &Organization{+ ID: "org-1",+ OwnerUserID: "u_owner",+ OwnerEmail: "[email protected]",+ Members: []OrganizationMember{+ {UserID: "u_owner", Email: "[email protected]", Role: OrgRoleOwner},+ {UserID: "u_admin", Email: "[email protected]", Role: OrgRoleAdmin},+ {UserID: "[email protected]", Role: OrgRoleViewer},+ },+ }++ userID, role, ok := org.ResolvePrincipalByEmail("[email protected]")+ if !ok || userID != "u_owner" || role != OrgRoleOwner {+ t.Fatalf("owner principal = (%q, %q, %v), want stable owner", userID, role, ok)+ }++ userID, role, ok = org.ResolvePrincipalByEmail("[email protected]")+ if !ok || userID != "u_admin" || role != OrgRoleAdmin {+ t.Fatalf("member principal = (%q, %q, %v), want stable admin", userID, role, ok)+ }++ userID, role, ok = org.ResolvePrincipalByEmail("[email protected]")+ if !ok || userID != "[email protected]" || role != OrgRoleViewer {+ t.Fatalf("legacy principal = (%q, %q, %v), want legacy email fallback", userID, role, ok)+ }+}+func TestOrganizationRoleNormalization(t *testing.T) {if got := NormalizeOrganizationRole("member"); got != OrganizationRole("member") {t.Fatalf("expected member to remain unchanged, got %q", got)