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
Use stable SSO principals
rcourtman2c9624248738
diff --git a/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md b/docs/release-control/v6/internal/IDENTITY_INVARIANTS.mdindex 0b682bc1b4..836216477e 100644--- a/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md+++ b/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md@@ -48,10 +48,11 @@ principal once a stable user ID exists.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.+ - Email role: access restriction, contact, display, and legacy RBAC+ migration. Self-hosted SSO sessions now use provider-scoped stable+ principals; mutable username/email/display claims may only seed+ compatibility role migration when no authoritative group mapping is+ present.7. API token ID/hash- Shape: token hash plus token metadata in config/auth storage.@@ -76,12 +77,16 @@ principal once a stable user ID exists.They may update billing only after server-owned org/customer linkage exists.5. Legacy email-keyed records may be accepted only at migration boundaries andshould be canonicalized to stable user IDs when the stable ID is known.+6. Self-hosted OIDC and SAML sessions bind to an opaque principal derived from+ provider type, provider ID, and the provider subject (`sub` or `NameID`).+ RBAC may copy a legacy username/email assignment to that principal during+ compatibility migration, but the browser session and tracked active-session+ owner must be the stable SSO principal.## 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.+Self-hosted local password/proxy auth still uses the historical `username`+session field as the local principal. That is a compatibility boundary for+local operators and reverse-proxy deployments. SSO no longer shares that+exception: OIDC and SAML sessions must use provider-scoped stable principals,+with legacy username/email assignments treated only as migration inputs.diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 92350887c4..b99729d734 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -188,7 +188,9 @@ profile and assignment columns, but embedded table framing must route throughThe canonical durable-principal vocabulary for those shared auth routes isrecorded in `docs/release-control/v6/internal/IDENTITY_INVARIANTS.md`; agentlifecycle work may consume that identity but must not define a parallel- email-keyed actor model for fleet operations.+ email-keyed actor model for fleet operations. SSO-authenticated lifecycle+ callers must already arrive with the API-owned provider-scoped principal;+ lifecycle code must not recover authority from SSO email or display claims.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 f53ca29efd..8e13cb5f58 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -975,6 +975,13 @@ local auth handoff. OIDC and SAML success/error handlers must build theirlocal `returnTo` targets through one canonical local-path helper that rejectsabsolute or host-bearing targets before query params are appended, so sharedidentity flows cannot drift back to per-handler open-redirect shaping.+That same runtime SSO contract also owns browser-session principal identity:+`internal/api/oidc_handlers.go`, `internal/api/saml_handlers.go`,+`internal/api/auth_principal_identity.go`, and `internal/api/contract_test.go` must derive+OIDC/SAML session users from provider-scoped stable subjects (`sub`/`NameID`+plus provider ID), not mutable username, email, or display-name claims. Legacy+username/email RBAC assignments may be copied only as compatibility migration+inputs when no authoritative group mapping is present.The SSO entitlement contract is part of that same API boundary. Provideradministration, SAML metadata preview/test, and runtime SAML routes may requirethe core `sso` capability, but they must not gate SAML or multi-providerdiff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex 5ddcd1233a..528bd40f6f 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -116,6 +116,8 @@ controls as normal product settings.must also preserve `docs/release-control/v6/internal/IDENTITY_INVARIANTS.md`:email is contact metadata once a stable principal exists, and browsersessions must bind to the durable principal rather than a delivery address.+ For SSO, the durable principal is the provider-scoped subject, and mutable+ username/email/display claims may not be written as the session owner.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.diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 0def1e907d..8d2c54be5b 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -77,7 +77,9 @@ must 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 storagework may consume accepted org access, but must not mint or widen access from a-delivery email.+delivery email. For SSO-authenticated browser sessions, storage and recovery+consume the API-owned provider-scoped principal only, not raw SAML/OIDC+username, email, or display claims.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/auth_principal_identity.go b/internal/api/auth_principal_identity.gonew file mode 100644index 0000000000..2bbfe00be6--- /dev/null+++ b/internal/api/auth_principal_identity.go@@ -0,0 +1,85 @@+package api++import (+ "crypto/sha256"+ "encoding/base64"+ "fmt"+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++func stableSSOPrincipal(providerType config.SSOProviderType, providerID string, subject string) (string, error) {+ typ := strings.TrimSpace(strings.ToLower(string(providerType)))+ id := strings.TrimSpace(providerID)+ sub := strings.TrimSpace(subject)+ if typ == "" {+ return "", fmt.Errorf("sso provider type is required")+ }+ if id == "" {+ return "", fmt.Errorf("sso provider id is required")+ }+ if sub == "" {+ return "", fmt.Errorf("sso subject is required")+ }++ sum := sha256.Sum256([]byte(typ + "\x00" + id + "\x00" + sub))+ return "sso:" + typ + ":" + id + ":" + base64.RawURLEncoding.EncodeToString(sum[:]), nil+}++func ssoLegacyPrincipalCandidates(values ...string) []string {+ candidates := make([]string, 0, len(values)+2)+ seen := make(map[string]struct{}, len(values)+2)+ for _, value := range values {+ trimmed := strings.TrimSpace(value)+ if trimmed == "" {+ continue+ }+ if _, ok := seen[trimmed]; !ok {+ candidates = append(candidates, trimmed)+ seen[trimmed] = struct{}{}+ }++ if strings.Contains(trimmed, "@") {+ lower := strings.ToLower(trimmed)+ if _, ok := seen[lower]; !ok {+ candidates = append(candidates, lower)+ seen[lower] = struct{}{}+ }+ }+ }+ return candidates+}++func applySSORoleAssignments(manager internalauth.Manager, principal string, legacyCandidates []string, mappedRoles []string, mappingAuthoritative bool, ensureListed bool) error {+ principal = strings.TrimSpace(principal)+ if manager == nil || principal == "" {+ return nil+ }++ if mappingAuthoritative || len(mappedRoles) > 0 {+ return manager.UpdateUserRoles(principal, mappedRoles)+ }++ if assignment, ok := manager.GetUserAssignment(principal); ok && len(assignment.RoleIDs) > 0 {+ return nil+ }++ for _, candidate := range legacyCandidates {+ candidate = strings.TrimSpace(candidate)+ if candidate == "" || candidate == principal {+ continue+ }+ assignment, ok := manager.GetUserAssignment(candidate)+ if !ok || len(assignment.RoleIDs) == 0 {+ continue+ }+ return manager.UpdateUserRoles(principal, assignment.RoleIDs)+ }++ if ensureListed {+ return manager.UpdateUserRoles(principal, nil)+ }+ return nil+}diff --git a/internal/api/auth_principal_identity_test.go b/internal/api/auth_principal_identity_test.gonew file mode 100644index 0000000000..0dc0fc5c8b--- /dev/null+++ b/internal/api/auth_principal_identity_test.go@@ -0,0 +1,110 @@+package api++import (+ "strings"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++type ssoIdentityRBACManager struct {+ auth.Manager+ assignments map[string]auth.UserRoleAssignment+ updatedUser string+ updatedRoles []string+}++func (m *ssoIdentityRBACManager) GetUserAssignment(username string) (auth.UserRoleAssignment, bool) {+ if m.assignments == nil {+ return auth.UserRoleAssignment{}, false+ }+ assignment, ok := m.assignments[username]+ return assignment, ok+}++func (m *ssoIdentityRBACManager) UpdateUserRoles(username string, roleIDs []string) error {+ m.updatedUser = username+ m.updatedRoles = append([]string{}, roleIDs...)+ if m.assignments == nil {+ m.assignments = make(map[string]auth.UserRoleAssignment)+ }+ m.assignments[username] = auth.UserRoleAssignment{Username: username, RoleIDs: append([]string{}, roleIDs...)}+ return nil+}++func TestStableSSOPrincipalUsesProviderScopedOpaqueSubject(t *testing.T) {+ principal, err := stableSSOPrincipal(config.SSOProviderTypeOIDC, "okta", "[email protected]")+ if err != nil {+ t.Fatalf("stableSSOPrincipal error: %v", err)+ }+ again, err := stableSSOPrincipal(config.SSOProviderTypeOIDC, "okta", "[email protected]")+ if err != nil {+ t.Fatalf("stableSSOPrincipal repeat error: %v", err)+ }+ otherProvider, err := stableSSOPrincipal(config.SSOProviderTypeOIDC, "entra", "[email protected]")+ if err != nil {+ t.Fatalf("stableSSOPrincipal other provider error: %v", err)+ }++ if principal != again {+ t.Fatalf("stable principal is not deterministic: %q != %q", principal, again)+ }+ if principal == otherProvider {+ t.Fatal("stable principal must be scoped by provider")+ }+ if !strings.HasPrefix(principal, "sso:oidc:okta:") {+ t.Fatalf("principal %q missing expected provider scope", principal)+ }+ if strings.Contains(principal, "alice") || strings.Contains(principal, "example.com") {+ t.Fatalf("principal %q must not expose the raw email subject", principal)+ }+}++func TestStableSSOPrincipalRequiresSubject(t *testing.T) {+ if _, err := stableSSOPrincipal(config.SSOProviderTypeSAML, "okta", ""); err == nil {+ t.Fatal("expected missing subject to fail")+ }+}++func TestApplySSORoleAssignmentsMigratesLegacyRoles(t *testing.T) {+ manager := &ssoIdentityRBACManager{+ assignments: map[string]auth.UserRoleAssignment{+ "[email protected]": {Username: "[email protected]", RoleIDs: []string{"admin", "viewer"}},+ },+ }+ principal := "sso:oidc:okta:stable"++ err := applySSORoleAssignments(manager, principal, ssoLegacyPrincipalCandidates("[email protected]"), nil, false, true)+ if err != nil {+ t.Fatalf("applySSORoleAssignments error: %v", err)+ }++ if manager.updatedUser != principal {+ t.Fatalf("updated user = %q, want %q", manager.updatedUser, principal)+ }+ if got := strings.Join(manager.updatedRoles, ","); got != "admin,viewer" {+ t.Fatalf("updated roles = %q, want admin,viewer", got)+ }+}++func TestApplySSORoleAssignmentsUsesAuthoritativeMapping(t *testing.T) {+ manager := &ssoIdentityRBACManager{+ assignments: map[string]auth.UserRoleAssignment{+ "[email protected]": {Username: "[email protected]", RoleIDs: []string{"admin"}},+ },+ }+ principal := "sso:saml:okta:stable"++ err := applySSORoleAssignments(manager, principal, []string{"[email protected]"}, []string{"viewer"}, true, true)+ if err != nil {+ t.Fatalf("applySSORoleAssignments error: %v", err)+ }++ if manager.updatedUser != principal {+ t.Fatalf("updated user = %q, want %q", manager.updatedUser, principal)+ }+ if got := strings.Join(manager.updatedRoles, ","); got != "viewer" {+ t.Fatalf("updated roles = %q, want viewer", got)+ }+}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex cbec720bf5..2ca7628b04 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -114,6 +114,52 @@ func TestContract_HostedMagicLinkStablePrincipalProof(t *testing.T) {}}+func TestContract_SSOStablePrincipalProof(t *testing.T) {+ ssoIdentity, err := os.ReadFile(filepath.Clean("auth_principal_identity.go"))+ if err != nil {+ t.Fatalf("read auth_principal_identity.go: %v", err)+ }+ oidcSource, err := os.ReadFile(filepath.Clean("oidc_handlers.go"))+ if err != nil {+ t.Fatalf("read oidc_handlers.go: %v", err)+ }+ samlSource, err := os.ReadFile(filepath.Clean("saml_handlers.go"))+ if err != nil {+ t.Fatalf("read saml_handlers.go: %v", err)+ }++ for file, text := range map[string]string{+ "auth_principal_identity.go": string(ssoIdentity),+ "oidc_handlers.go": string(oidcSource),+ "saml_handlers.go": string(samlSource),+ } {+ for _, required := range []string{+ "stableSSOPrincipal",+ "applySSORoleAssignments",+ } {+ if !strings.Contains(text, required) {+ t.Fatalf("%s must contain %q", file, required)+ }+ }+ }+ for _, forbidden := range []string{+ "establishOIDCSession(w, req, username, oidcTokens)",+ "UpdateUserRoles(username, rolesToAssign)",+ } {+ if strings.Contains(string(oidcSource), forbidden) {+ t.Fatalf("oidc_handlers.go must not contain legacy SSO principal pattern %q", forbidden)+ }+ }+ for _, forbidden := range []string{+ "establishSAMLSession(w, req, username, samlSession)",+ "UpdateUserRoles(result.Username, rolesToAssign)",+ } {+ if strings.Contains(string(samlSource), forbidden) {+ t.Fatalf("saml_handlers.go must not contain legacy SSO principal pattern %q", forbidden)+ }+ }+}+func TestContractAISettingsClampsPaidRuntimeControlsToEntitlements(t *testing.T) {t.Parallel()diff --git a/internal/api/identity_invariant_contract_test.go b/internal/api/identity_invariant_contract_test.goindex 718b411172..78fe346dad 100644--- a/internal/api/identity_invariant_contract_test.go+++ b/internal/api/identity_invariant_contract_test.go@@ -18,12 +18,15 @@ func readIdentityContractFile(t *testing.T, rel string) string {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"),+ "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"),+ "oidc_handlers.go": readIdentityContractFile(t, "oidc_handlers.go"),+ "payments_webhook_handlers.go": readIdentityContractFile(t, "payments_webhook_handlers.go"),+ "saml_handlers.go": readIdentityContractFile(t, "saml_handlers.go"),+ "auth_principal_identity.go": readIdentityContractFile(t, "auth_principal_identity.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"),}@@ -41,6 +44,21 @@ func TestContract_HostedIdentityUsesStablePrincipals(t *testing.T) {"CreateSession(sessionToken, sessionDuration, userAgent, clientIP, authz.UserID)","TrackUserSession(authz.UserID, sessionToken)",},+ "oidc_handlers.go": {+ "stableSSOPrincipal(config.SSOProviderTypeOIDC, providerID, idToken.Subject)",+ "applySSORoleAssignments(authManager, principal",+ "establishOIDCSession(w, req, principal, oidcTokens)",+ },+ "saml_handlers.go": {+ "stableSSOPrincipal(config.SSOProviderTypeSAML, providerID, result.NameID)",+ "applySSORoleAssignments(authManager, principal",+ "establishSAMLSession(w, req, principal, samlSession)",+ },+ "auth_principal_identity.go": {+ "stableSSOPrincipal",+ "ssoLegacyPrincipalCandidates",+ "applySSORoleAssignments",+ },"../cloudcp/stripe/provisioner.go": {"ownerUserID = strings.TrimSpace(user.ID)","org.OwnerEmail = ownerEmail",@@ -56,6 +74,7 @@ func TestContract_HostedIdentityUsesStablePrincipals(t *testing.T) {"Email is contact metadata","Pulse control-plane user ID","SSO provider subject",+ "Self-hosted SSO sessions now use provider-scoped",},}for file, needles := range required {@@ -79,6 +98,14 @@ func TestContract_HostedIdentityUsesStablePrincipals(t *testing.T) {"CreateSession(sessionToken, sessionDuration, userAgent, clientIP, claims.Email)","TrackUserSession(claims.Email, sessionToken)",},+ "oidc_handlers.go": {+ "establishOIDCSession(w, req, username, oidcTokens)",+ "UpdateUserRoles(username, rolesToAssign)",+ },+ "saml_handlers.go": {+ "establishSAMLSession(w, req, username, samlSession)",+ "UpdateUserRoles(result.Username, rolesToAssign)",+ },"payments_webhook_handlers.go": {"sendTo = org.OwnerUserID","sendTo = m.UserID",diff --git a/internal/api/oidc_handlers.go b/internal/api/oidc_handlers.goindex 35d653beb6..ed8602fd6f 100644--- a/internal/api/oidc_handlers.go+++ b/internal/api/oidc_handlers.go@@ -549,6 +549,13 @@ func (r *Router) handleSSOOIDCCallback(w http.ResponseWriter, req *http.Request)if username == "" {username = idToken.Subject}+ principal, err := stableSSOPrincipal(config.SSOProviderTypeOIDC, providerID, idToken.Subject)+ if err != nil {+ log.Error().Err(err).Str("provider_id", providerID).Msg("OIDC subject is not usable as a stable SSO principal")+ LogAuditEventForTenant(GetOrgID(req.Context()), "sso_oidc_login", username, GetClientIP(req), req.URL.Path, false, "Missing stable OIDC subject")+ r.redirectOIDCError(w, req, entry.ReturnTo, "missing_subject")+ return+ }// Apply access restrictions from SSO provider configif len(provider.AllowedEmails) > 0 && !matchesValue(email, provider.AllowedEmails) {@@ -570,7 +577,8 @@ func (r *Router) handleSSOOIDCCallback(w http.ResponseWriter, req *http.Request)}}- // RBAC: Always call UpdateUserRoles so user appears in Users list+ // RBAC: Always call UpdateUserRoles so user appears in Users list, but key+ // SSO users by the provider-scoped subject instead of mutable display claims.if authManager := internalauth.GetManager(); authManager != nil {groups := extractStringSliceClaim(claims, provider.GroupsClaim)var rolesToAssign []string@@ -583,10 +591,11 @@ func (r *Router) handleSSOOIDCCallback(w http.ResponseWriter, req *http.Request)}}}- if err := authManager.UpdateUserRoles(username, rolesToAssign); err != nil {- log.Error().Err(err).Str("user", username).Msg("Failed to update SSO OIDC user roles")+ legacyCandidates := ssoLegacyPrincipalCandidates(username, email, extractStringClaim(claims, "name"))+ if err := applySSORoleAssignments(authManager, principal, legacyCandidates, rolesToAssign, len(provider.GroupRoleMappings) > 0, true); err != nil {+ log.Error().Err(err).Str("user", principal).Str("display_user", username).Msg("Failed to update SSO OIDC user roles")} else if len(rolesToAssign) > 0 {- LogAuditEventForTenant(GetOrgID(req.Context()), "sso_oidc_role_assignment", username, GetClientIP(req), req.URL.Path, true, "Auto-assigned roles: "+strings.Join(rolesToAssign, ", "))+ LogAuditEventForTenant(GetOrgID(req.Context()), "sso_oidc_role_assignment", principal, GetClientIP(req), req.URL.Path, true, "Auto-assigned roles: "+strings.Join(rolesToAssign, ", "))}}@@ -601,13 +610,13 @@ func (r *Router) handleSSOOIDCCallback(w http.ResponseWriter, req *http.Request)}}- if err := r.establishOIDCSession(w, req, username, oidcTokens); err != nil {+ if err := r.establishOIDCSession(w, req, principal, oidcTokens); err != nil {log.Error().Err(err).Msg("Failed to establish session after SSO OIDC login")r.redirectOIDCError(w, req, entry.ReturnTo, "session_failed")return}- LogAuditEventForTenant(GetOrgID(req.Context()), "sso_oidc_login", username, GetClientIP(req), req.URL.Path, true, "SSO OIDC login success via provider: "+providerID)+ LogAuditEventForTenant(GetOrgID(req.Context()), "sso_oidc_login", principal, GetClientIP(req), req.URL.Path, true, "SSO OIDC login success via provider: "+providerID)http.Redirect(w, req, buildLocalRedirectTarget(entry.ReturnTo, map[string]string{"oidc": "success",diff --git a/internal/api/saml_handlers.go b/internal/api/saml_handlers.goindex 57c6e4f464..4007495ccb 100644--- a/internal/api/saml_handlers.go+++ b/internal/api/saml_handlers.go@@ -256,8 +256,18 @@ func (r *Router) handleSAMLACS(w http.ResponseWriter, req *http.Request) {}}- // RBAC Integration: Map SAML groups to Pulse roles- if authManager := internalauth.GetManager(); authManager != nil && len(provider.GroupRoleMappings) > 0 {+ principal, err := stableSSOPrincipal(config.SSOProviderTypeSAML, providerID, result.NameID)+ if err != nil {+ log.Error().Err(err).Str("provider_id", providerID).Msg("SAML NameID is not usable as a stable SSO principal")+ LogAuditEventForTenant(GetOrgID(req.Context()), "saml_login", result.Username, GetClientIP(req), req.URL.Path, false, "Missing stable SAML subject")+ r.redirectSAMLError(w, req, relayState, "missing_subject")+ return+ }++ // RBAC Integration: Map SAML groups to Pulse roles under the stable SSO+ // principal. When mappings are configured they are authoritative, including+ // the case where the current assertion maps to no roles.+ if authManager := internalauth.GetManager(); authManager != nil {var rolesToAssign []stringseenRoles := make(map[string]bool)@@ -270,29 +280,23 @@ func (r *Router) handleSAMLACS(w http.ResponseWriter, req *http.Request) {}}- if len(rolesToAssign) > 0 {+ legacyCandidates := ssoLegacyPrincipalCandidates(result.Username, result.Email, result.NameID)+ roleErr := applySSORoleAssignments(authManager, principal, legacyCandidates, rolesToAssign, len(provider.GroupRoleMappings) > 0, false)+ if roleErr != nil {+ log.Error().Err(roleErr).Str("user", principal).Str("display_user", result.Username).Msg("Failed to update SAML user roles")+ if len(rolesToAssign) > 0 {+ LogAuditEventForTenant(GetOrgID(req.Context()), "saml_role_assignment", principal, GetClientIP(req), req.URL.Path, false, "Failed to auto-assign roles: "+strings.Join(rolesToAssign, ", "))+ }+ } else if len(rolesToAssign) > 0 {log.Info().- Str("user", result.Username).+ Str("user", principal).+ Str("display_user", result.Username).Strs("mapped_roles", rolesToAssign).Msg("Auto-assigning roles based on SAML group mapping")- if err := authManager.UpdateUserRoles(result.Username, rolesToAssign); err != nil {- log.Error().Err(err).Str("user", result.Username).Msg("Failed to auto-assign SAML roles")- LogAuditEventForTenant(GetOrgID(req.Context()), "saml_role_assignment", result.Username, GetClientIP(req), req.URL.Path, false, "Failed to auto-assign roles: "+strings.Join(rolesToAssign, ", "))- } else {- LogAuditEventForTenant(GetOrgID(req.Context()), "saml_role_assignment", result.Username, GetClientIP(req), req.URL.Path, true, "Auto-assigned roles: "+strings.Join(rolesToAssign, ", "))- }+ LogAuditEventForTenant(GetOrgID(req.Context()), "saml_role_assignment", principal, GetClientIP(req), req.URL.Path, true, "Auto-assigned roles: "+strings.Join(rolesToAssign, ", "))}}- // Establish session- username := result.Username- if username == "" {- username = result.Email- }- if username == "" {- username = result.NameID- }-// Store SAML session info for potential SLOsamlSession := &SAMLSessionInfo{ProviderID: providerID,@@ -300,14 +304,14 @@ func (r *Router) handleSAMLACS(w http.ResponseWriter, req *http.Request) {SessionIndex: result.SessionIdx,}- if err := r.establishSAMLSession(w, req, username, samlSession); err != nil {+ if err := r.establishSAMLSession(w, req, principal, samlSession); err != nil {log.Error().Err(err).Msg("Failed to establish session after SAML login")- LogAuditEventForTenant(GetOrgID(req.Context()), "saml_login", username, GetClientIP(req), req.URL.Path, false, "Session creation failed")+ LogAuditEventForTenant(GetOrgID(req.Context()), "saml_login", principal, GetClientIP(req), req.URL.Path, false, "Session creation failed")r.redirectSAMLError(w, req, relayState, "session_failed")return}- LogAuditEventForTenant(GetOrgID(req.Context()), "saml_login", username, GetClientIP(req), req.URL.Path, true, "SAML login success via "+providerID)+ LogAuditEventForTenant(GetOrgID(req.Context()), "saml_login", principal, GetClientIP(req), req.URL.Path, true, "SAML login success via "+providerID)http.Redirect(w, req, buildLocalRedirectTarget(relayState, map[string]string{"saml": "success",