Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Port v5 SAML public URL rebinding

rcourtmana33983175b40
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 441de4a7bc..b5fb9a5079 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -195,6 +195,7 @@ an add-only capacity posture.
4. Keep shared `internal/api/` helper edits isolated from agent lifecycle semantics: Patrol-specific status transport or alert-trigger wiring changes in shared handlers must not bleed into auto-register, installer, or fleet-control behavior unless this contract moves in the same slice.
The same isolation rule applies to AI settings payload work in `internal/api/ai_handlers.go`: provider auth fields, masked-secret echoes, and provider-test model selection remain AI/runtime plus API-contract ownership and must not be reinterpreted as lifecycle setup or registration semantics just because they share backend helper layers.
The same shared-helper rule now covers SSO outbound discovery and metadata fetches plus credential-file loads in `internal/api/sso_outbound.go`, `internal/api/saml_service.go`, and `internal/api/oidc_service.go`: lifecycle-adjacent setup or auth work may depend on that shared trust boundary, but it must not fork a second HTTP client, redirect policy, or file-read rule inside lifecycle-local flows.
+ That same shared helper boundary also owns SAML service-provider public URL rebinding: lifecycle-adjacent setup and login flows may depend on shared `internal/api/saml_handlers.go` plus `internal/api/router.go` to rebind initialized SAML providers to the canonical configured `PublicURL`, but they must not snapshot, concatenate, or locally cache alternate SP base URLs inside install or registration surfaces.
4. Keep legacy Unified Agent compatibility names explicitly secondary when touching shared `internal/api/` runtime helpers: the legacy host-route family and `host-agent:*` scope names may remain as ingress or migration aliases, but they must not retake primary ownership in router state, live runtime scope checks, handler commentary, or operator-facing guidance.
5. Add or change installer flags, persisted service arguments, or upgrade-safe re-entry behavior through `scripts/install.sh` and `scripts/install.ps1`.
6. Add or change profile management, the extracted agent profiles runtime owner, the pure unified-agent inventory/install model, the API-backed platform connections workspace shell, route model, reporting summary owner, shared install/inventory/dialog section owners, the split infrastructure install/reporting state owners, the split direct-node/discovery infrastructure settings owners plus their shared model, shared frontend install-command assembly, Proxmox setup/install API transport, TrueNAS platform-connection management, VMware platform-connection management, the shared monitored-system admission preview shell for those platform connections, setup-completion install handoff transport, deploy-fallback manual install transport, and fleet-control presentation through `frontend-modern/src/api/agentProfiles.ts`, `frontend-modern/src/api/nodes.ts`, `frontend-modern/src/components/Settings/AgentProfilesPanel.tsx`, `frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`, `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx`, `frontend-modern/src/components/Settings/InfrastructureReportingPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInventorySection.tsx`, `frontend-modern/src/components/Settings/InfrastructureActiveRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureIgnoredRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureStopMonitoringDialog.tsx`, `frontend-modern/src/components/Settings/InfrastructurePlatformConnectionsSummaryCard.tsx`, `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx`, `frontend-modern/src/components/Settings/infrastructureWorkspaceModel.ts`, `frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx`, `frontend-modern/src/components/Settings/PlatformConnectionsWorkspace.tsx`, `frontend-modern/src/components/Settings/platformConnectionsModel.ts`, `frontend-modern/src/components/Settings/TrueNASSettingsPanel.tsx`, `frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts`, `frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx`, `frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts`, `frontend-modern/src/components/Settings/ProxmoxSettingsPanel.tsx`, `frontend-modern/src/components/Settings/proxmoxSettingsModel.ts`, `frontend-modern/src/components/Settings/ProxmoxDirectWorkspace.tsx`, `frontend-modern/src/components/Settings/ProxmoxConfiguredNodesTable.tsx`, `frontend-modern/src/components/Settings/ProxmoxDirectConnectionsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDiscoveryResultsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDeleteNodeDialog.tsx`, `frontend-modern/src/components/Settings/ProxmoxNodeModalStack.tsx`, `frontend-modern/src/components/Settings/ConfiguredNodeTables.tsx`, `frontend-modern/src/components/Settings/SettingsSectionNav.tsx`, `frontend-modern/src/components/Settings/infrastructureSettingsModel.ts`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts`, `frontend-modern/src/components/Settings/useProxmoxDirectWorkspaceState.ts`, `frontend-modern/src/components/Settings/NodeModal.tsx`, `frontend-modern/src/components/Settings/nodeModalModel.ts`, `frontend-modern/src/components/Settings/useNodeModalState.ts`, `frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx`, and `frontend-modern/src/utils/agentInstallCommand.ts`.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 300ccfd035..72b1ae421a 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -612,6 +612,13 @@ manual logout URL drift out of the request model or bypass the governed URL
normalization path.
That same runtime SSO contract also owns the Pulse-side public URL that feeds
SAML service-provider metadata and auth requests. `internal/api/saml_handlers.go`,
+`internal/api/saml_service.go`, and `internal/api/contract_test.go` must rebind
+previously initialized SAML providers to the current configured `PublicURL`
+before metadata or browser login flows emit SP entity, ACS, or metadata URLs,
+so a stale startup-time blank/relative base URL cannot leak back into runtime
+metadata or auth request generation once the canonical external URL is known.
+That same runtime SSO contract also owns the Pulse-side public URL that feeds
+SAML service-provider metadata and auth requests. `internal/api/saml_handlers.go`,
`internal/api/saml_service.go`, and the SAML regression tests must rebind
previously initialized SAML providers to the current configured `PublicURL`
before metadata or browser login flows emit SP entity, ACS, or metadata URLs,
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 477b698c6b..9fb8e42e0e 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -204,6 +204,11 @@ regression protection.
performance work must not add filesystem reads, GitHub release lookups, or
other per-request version discovery on activation, legacy exchange, or
grant-refresh traffic just to stamp authenticated install metadata.
+ That same shared router boundary must keep SAML public URL synchronization
+ change-driven rather than request-driven: `internal/api/router.go` may rebind
+ shared SAML service providers when the canonical `PublicURL` changes, but it
+ must not rebuild that auth state on every dashboard, summary, or chart read
+ that passes through the protected router hot path.
30. Keep dashboard summary-chart fetches scope-owned rather than page-churn-owned: `frontend-modern/src/hooks/useDashboardTrends.ts` must hydrate infrastructure and storage summaries once per org/range scope from the canonical summary caches and recompute card presentation locally as the compact dashboard overview changes, rather than refetching the infrastructure-summary transport in `frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts`, the dashboard storage-summary trend transport in `frontend-modern/src/utils/storageSummaryTrendCache.ts`, or the storage-page summary transport in `frontend-modern/src/utils/storageSummaryCache.ts` for every top-resource or card reshuffle on the same dashboard load. That dashboard infrastructure path must also request only the metrics it renders through the canonical infrastructure-summary route owned by `internal/api/router_routes_monitoring.go` and `internal/api/router.go`; the dashboard may not pay for disk or network summary series when it only renders CPU and memory. App-shell prewarm in `frontend-modern/src/useAppRuntimeState.ts` must not front-run that dashboard-specific route while the operator is already on the root dashboard route owned by `frontend-modern/src/App.tsx`.
The same hot path must keep mock/demo chart identity on the canonical
unified snapshot too: when mock mode is enabled, `internal/api/router.go`
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index c4ab49a121..5f5903b635 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -120,6 +120,7 @@ querying, and the operator-facing storage health presentation layer.
6. Preserve API-owned node identity continuity in shared `internal/api/` helpers so storage and recovery transport attachments do not fork by hostname-versus-IP drift across the same runtime.
7. Preserve fail-closed API assignment and lookup behavior in shared `internal/api/` helpers so storage and recovery surfaces do not inherit orphaned profile or resource references from unrelated transport mutations.
8. Preserve canonical configured public endpoint selection in shared `internal/api/` helpers so recovery and storage links do not inherit loopback-local scheme drift from admin-originated setup/install flows.
+ That same shared endpoint-selection rule also covers SAML service-provider rebinding in `internal/api/saml_handlers.go`, `internal/api/saml_service.go`, and `internal/api/router.go`: storage- and recovery-adjacent flows may depend on the canonical configured `PublicURL`, but they must not fork alternate SP metadata/login base URLs when they share the backend auth helper layer.
9. Preserve trailing-slash normalization in those shared install-command helpers so recovery-adjacent transport and link surfaces do not inherit double-slash installer paths or slash-suffixed public endpoint drift from canonical backend install payloads.
10. Preserve canonical /api/auto-register token-action truth in shared `internal/api/` helpers so adjacent setup and recovery-adjacent transport flows stay on caller-supplied credential completion instead of reviving deleted alternate completion modes.
11. Preserve the canonical setup-script `source="script"` marker through those same shared auto-register helpers, and reject non-canonical source labels there, so later canonical reruns can keep treating script-confirmed tokens differently from agent-created tokens without reviving arbitrary caller-label compatibility.
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index ae9b1d2267..b3407e1728 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -2025,6 +2025,74 @@ func TestContract_SSOTestRejectsCrossOriginSAMLMetadataRedirect(t *testing.T) {
}
}
+func TestContract_SAMLRuntimePublicURLRefreshKeepsMetadataAndAuthRequestsAbsolute(t *testing.T) {
+ provider := config.SSOProvider{
+ ID: "okta",
+ Name: "Okta",
+ Type: config.SSOProviderTypeSAML,
+ Enabled: true,
+ SAML: &config.SAMLProviderConfig{
+ IDPSSOURL: "https://idp.example.com/sso",
+ IDPEntityID: "https://idp.example.com/metadata",
+ },
+ }
+
+ router := &Router{
+ config: &config.Config{PublicURL: "https://pulse.example.com"},
+ samlManager: NewSAMLServiceManager(""),
+ ssoConfig: &config.SSOConfig{
+ Providers: []config.SSOProvider{provider},
+ },
+ }
+
+ if err := router.samlManager.InitializeProvider(context.Background(), provider.ID, provider.SAML); err != nil {
+ t.Fatalf("initialize provider: %v", err)
+ }
+ service := router.samlManager.GetService(provider.ID)
+ if service == nil {
+ t.Fatal("expected initialized SAML service")
+ }
+ if got := service.GetSPEntityID(); got != "/saml/okta" {
+ t.Fatalf("expected relative entity ID before sync, got %q", got)
+ }
+
+ metadataReq := httptest.NewRequest(http.MethodGet, "/api/saml/okta/metadata", nil)
+ metadataRec := httptest.NewRecorder()
+ router.handleSAMLMetadata(metadataRec, metadataReq)
+ if metadataRec.Code != http.StatusOK {
+ t.Fatalf("metadata status=%d want %d: %s", metadataRec.Code, http.StatusOK, metadataRec.Body.String())
+ }
+ metadataBody := metadataRec.Body.String()
+ if !strings.Contains(metadataBody, `entityID="https://pulse.example.com/saml/okta"`) {
+ t.Fatalf("expected absolute entity ID in metadata, got %q", metadataBody)
+ }
+ if !strings.Contains(metadataBody, `Location="https://pulse.example.com/api/saml/okta/acs"`) {
+ t.Fatalf("expected absolute ACS URL in metadata, got %q", metadataBody)
+ }
+
+ router.samlManager = NewSAMLServiceManager("")
+ if err := router.samlManager.InitializeProvider(context.Background(), provider.ID, provider.SAML); err != nil {
+ t.Fatalf("reinitialize provider: %v", err)
+ }
+ service = router.samlManager.GetService(provider.ID)
+ if service == nil {
+ t.Fatal("expected initialized SAML service after reset")
+ }
+
+ loginReq := httptest.NewRequest(http.MethodGet, "/api/saml/okta/login", nil)
+ loginRec := httptest.NewRecorder()
+ router.handleSAMLLogin(loginRec, loginReq)
+ if loginRec.Code != http.StatusFound {
+ t.Fatalf("login status=%d want %d", loginRec.Code, http.StatusFound)
+ }
+ if got := service.GetSPEntityID(); got != "https://pulse.example.com/saml/okta" {
+ t.Fatalf("expected absolute entity ID after login sync, got %q", got)
+ }
+ if got := service.sp.AcsURL.String(); got != "https://pulse.example.com/api/saml/okta/acs" {
+ t.Fatalf("expected absolute ACS URL after login sync, got %q", got)
+ }
+}
+
func TestContract_SSOTestRejectsCrossOriginOIDCDiscoveryRedirect(t *testing.T) {
targetCalled := make(chan struct{}, 1)
var targetURL string
diff --git a/internal/api/identity_sso_handlers.go b/internal/api/identity_sso_handlers.go
index c4b6df2731..b789879cf1 100644
--- a/internal/api/identity_sso_handlers.go
+++ b/internal/api/identity_sso_handlers.go
@@ -365,6 +365,9 @@ func (r *Router) handleCreateSSOProvider(w http.ResponseWriter, req *http.Reques
// Initialize SAML provider if applicable
if provider.Type == config.SSOProviderTypeSAML && provider.Enabled && provider.SAML != nil {
+ if err := r.syncSAMLPublicURL(); err != nil {
+ log.Warn().Err(err).Str("provider_id", provider.ID).Msg("Failed to synchronize SAML public URL before provider init")
+ }
if err := r.samlManager.InitializeProvider(req.Context(), provider.ID, provider.SAML); err != nil {
log.Warn().Err(err).Str("provider_id", provider.ID).Msg("Failed to initialize SAML provider (will retry on first use)")
}
@@ -522,6 +525,9 @@ func (r *Router) handleUpdateSSOProvider(w http.ResponseWriter, req *http.Reques
// Re-initialize SAML provider if applicable
if updated.Type == config.SSOProviderTypeSAML && updated.SAML != nil {
if updated.Enabled {
+ if err := r.syncSAMLPublicURL(); err != nil {
+ log.Warn().Err(err).Str("provider_id", updated.ID).Msg("Failed to synchronize SAML public URL before provider re-init")
+ }
if err := r.samlManager.InitializeProvider(req.Context(), updated.ID, updated.SAML); err != nil {
log.Warn().Err(err).Str("provider_id", updated.ID).Msg("Failed to re-initialize SAML provider")
}
diff --git a/internal/api/router.go b/internal/api/router.go
index 363e27229d..96674815e8 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -269,6 +269,9 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monit
// Initialize SSO service managers
r.oidcManager = NewOIDCServiceManager()
r.samlManager = NewSAMLServiceManager("")
+ if err := r.syncSAMLPublicURL(); err != nil {
+ log.Error().Err(err).Msg("Failed to initialize SAML public URL")
+ }
r.initializeBootstrapToken()
@@ -3822,6 +3825,9 @@ func (r *Router) capturePublicURLFromRequest(req *http.Request) {
mgr.SetPublicURL(normalizedCandidate)
}
}
+ if err := r.syncSAMLPublicURL(); err != nil {
+ log.Error().Err(err).Str("publicURL", normalizedCandidate).Msg("Failed to synchronize SAML public URL from request")
+ }
}
func firstForwardedValue(header string) string {
diff --git a/internal/api/saml_handlers.go b/internal/api/saml_handlers.go
index 0ce4aece1d..e707bde5bf 100644
--- a/internal/api/saml_handlers.go
+++ b/internal/api/saml_handlers.go
@@ -29,6 +29,35 @@ func NewSAMLServiceManager(baseURL string) *SAMLServiceManager {
}
}
+func (m *SAMLServiceManager) GetPublicURL() string {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.baseURL
+}
+
+func (m *SAMLServiceManager) SetPublicURL(baseURL string) error {
+ normalizedBaseURL, err := normalizeSAMLBaseURL(baseURL)
+ if err != nil {
+ return fmt.Errorf("normalize SAML public URL: %w", err)
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ if normalizedBaseURL == m.baseURL {
+ return nil
+ }
+
+ for providerID, service := range m.services {
+ if err := service.SetBaseURL(normalizedBaseURL); err != nil {
+ return fmt.Errorf("rebind SAML provider %q public URL: %w", providerID, err)
+ }
+ }
+
+ m.baseURL = normalizedBaseURL
+ return nil
+}
+
// GetService returns a SAML service for the given provider ID
func (m *SAMLServiceManager) GetService(providerID string) *SAMLService {
m.mu.RLock()
@@ -38,7 +67,11 @@ func (m *SAMLServiceManager) GetService(providerID string) *SAMLService {
// InitializeProvider creates or updates a SAML service for a provider
func (m *SAMLServiceManager) InitializeProvider(ctx context.Context, providerID string, cfg *config.SAMLProviderConfig) error {
- service, err := NewSAMLService(ctx, providerID, cfg, m.baseURL)
+ m.mu.RLock()
+ baseURL := m.baseURL
+ m.mu.RUnlock()
+
+ service, err := NewSAMLService(ctx, providerID, cfg, baseURL)
if err != nil {
return fmt.Errorf("initialize SAML provider %q: %w", providerID, err)
}
@@ -61,6 +94,13 @@ func (m *SAMLServiceManager) RemoveProvider(providerID string) {
delete(m.services, providerID)
}
+func (r *Router) syncSAMLPublicURL() error {
+ if r == nil || r.samlManager == nil || r.config == nil {
+ return nil
+ }
+ return r.samlManager.SetPublicURL(r.config.PublicURL)
+}
+
// handleSAMLLogin initiates a SAML authentication flow
func (r *Router) handleSAMLLogin(w http.ResponseWriter, req *http.Request) {
providerID := extractSAMLProviderID(req.URL.Path, "login")
@@ -81,6 +121,12 @@ func (r *Router) handleSAMLLogin(w http.ResponseWriter, req *http.Request) {
return
}
+ if err := r.syncSAMLPublicURL(); err != nil {
+ log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to synchronize SAML public URL")
+ writeErrorResponse(w, http.StatusInternalServerError, "saml_init_failed", "Failed to synchronize SAML provider", nil)
+ return
+ }
+
service := r.samlManager.GetService(providerID)
if service == nil {
// Try to initialize the provider
@@ -288,6 +334,12 @@ func (r *Router) handleSAMLMetadata(w http.ResponseWriter, req *http.Request) {
return
}
+ if err := r.syncSAMLPublicURL(); err != nil {
+ log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to synchronize SAML public URL for metadata")
+ writeErrorResponse(w, http.StatusInternalServerError, "saml_init_failed", "Failed to synchronize SAML provider", nil)
+ return
+ }
+
service := r.samlManager.GetService(providerID)
if service == nil {
// Try to initialize the provider
@@ -529,6 +581,9 @@ func (r *Router) InitializeSAMLProviders(ctx context.Context) error {
if r.ssoConfig == nil {
return nil
}
+ if err := r.syncSAMLPublicURL(); err != nil {
+ return fmt.Errorf("sync saml public url: %w", err)
+ }
for _, provider := range r.ssoConfig.Providers {
if provider.Type == config.SSOProviderTypeSAML && provider.Enabled && provider.SAML != nil {
@@ -547,6 +602,9 @@ func (r *Router) InitializeSAMLProviders(ctx context.Context) error {
// RefreshSAMLProvider refreshes a SAML provider's IdP metadata
func (r *Router) RefreshSAMLProvider(ctx context.Context, providerID string) error {
+ if err := r.syncSAMLPublicURL(); err != nil {
+ return fmt.Errorf("sync saml public url: %w", err)
+ }
service := r.samlManager.GetService(providerID)
if service == nil {
return nil
diff --git a/internal/api/saml_handlers_additional_test.go b/internal/api/saml_handlers_additional_test.go
index 863aa26c4e..0e9eb6dc27 100644
--- a/internal/api/saml_handlers_additional_test.go
+++ b/internal/api/saml_handlers_additional_test.go
@@ -145,14 +145,17 @@ func TestInitializeSAMLProviders(t *testing.T) {
}
router := newSAMLRouter(t, provider)
- if router.samlManager == nil {
- router.samlManager = NewSAMLServiceManager("https://pulse.example.com")
- }
+ router.samlManager = NewSAMLServiceManager("")
if err := router.InitializeSAMLProviders(reqContext(t)); err != nil {
t.Fatalf("InitializeSAMLProviders error: %v", err)
}
+ if actual := router.samlManager.GetPublicURL(); actual != "https://pulse.example.com" {
+ t.Fatalf("expected synchronized public URL, got %q", actual)
+ }
if svc := router.samlManager.GetService("okta"); svc == nil {
t.Fatalf("expected SAML service to be initialized")
+ } else if svc.GetSPEntityID() != "https://pulse.example.com/saml/okta" {
+ t.Fatalf("expected absolute entity ID after init, got %q", svc.GetSPEntityID())
}
}
diff --git a/internal/api/saml_handlers_success_test.go b/internal/api/saml_handlers_success_test.go
index d4ebd076a2..7a70051de9 100644
--- a/internal/api/saml_handlers_success_test.go
+++ b/internal/api/saml_handlers_success_test.go
@@ -54,6 +54,121 @@ func TestHandleSAMLMetadata_Success(t *testing.T) {
}
}
+func TestHandleSAMLMetadata_SynchronizesConfiguredPublicURL(t *testing.T) {
+ router := &Router{
+ config: &config.Config{PublicURL: "https://pulse.example.com"},
+ samlManager: NewSAMLServiceManager(""),
+ ssoConfig: &config.SSOConfig{
+ Providers: []config.SSOProvider{testSAMLProvider("okta", true)},
+ },
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/api/saml/okta/metadata", nil)
+ rr := httptest.NewRecorder()
+
+ router.handleSAMLMetadata(rr, req)
+
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d", http.StatusOK, rr.Code)
+ }
+ body := rr.Body.String()
+ if !strings.Contains(body, `entityID="https://pulse.example.com/saml/okta"`) {
+ t.Fatalf("expected absolute entityID in metadata, got %q", body)
+ }
+ if !strings.Contains(body, `Location="https://pulse.example.com/api/saml/okta/acs"`) {
+ t.Fatalf("expected absolute ACS URL in metadata, got %q", body)
+ }
+}
+
+func TestHandleSAMLMetadata_RebuildsPreviouslyInitializedRelativeMetadata(t *testing.T) {
+ provider := testSAMLProvider("okta", true)
+ router := &Router{
+ config: &config.Config{PublicURL: "https://pulse.example.com"},
+ samlManager: NewSAMLServiceManager(""),
+ ssoConfig: &config.SSOConfig{
+ Providers: []config.SSOProvider{provider},
+ },
+ }
+
+ if err := router.samlManager.InitializeProvider(context.Background(), provider.ID, provider.SAML); err != nil {
+ t.Fatalf("InitializeProvider: %v", err)
+ }
+
+ service := router.samlManager.GetService(provider.ID)
+ if service == nil {
+ t.Fatal("expected initialized SAML service")
+ }
+
+ staleMetadata, err := service.GetMetadata()
+ if err != nil {
+ t.Fatalf("GetMetadata before sync: %v", err)
+ }
+ staleBody := string(staleMetadata)
+ if !strings.Contains(staleBody, `entityID="/saml/okta"`) {
+ t.Fatalf("expected pre-sync relative entityID, got %q", staleBody)
+ }
+ if !strings.Contains(staleBody, `Location="/api/saml/okta/acs"`) {
+ t.Fatalf("expected pre-sync relative ACS URL, got %q", staleBody)
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/api/saml/okta/metadata", nil)
+ rr := httptest.NewRecorder()
+
+ router.handleSAMLMetadata(rr, req)
+
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d", http.StatusOK, rr.Code)
+ }
+ body := rr.Body.String()
+ if !strings.Contains(body, `entityID="https://pulse.example.com/saml/okta"`) {
+ t.Fatalf("expected absolute entityID after sync, got %q", body)
+ }
+ if !strings.Contains(body, `Location="https://pulse.example.com/api/saml/okta/acs"`) {
+ t.Fatalf("expected absolute ACS URL after sync, got %q", body)
+ }
+}
+
+func TestHandleSAMLLogin_RebuildsPreviouslyInitializedRelativeServiceProvider(t *testing.T) {
+ provider := testSAMLProvider("okta", true)
+ router := &Router{
+ config: &config.Config{PublicURL: "https://pulse.example.com"},
+ samlManager: NewSAMLServiceManager(""),
+ ssoConfig: &config.SSOConfig{
+ Providers: []config.SSOProvider{provider},
+ },
+ }
+
+ if err := router.samlManager.InitializeProvider(context.Background(), provider.ID, provider.SAML); err != nil {
+ t.Fatalf("InitializeProvider: %v", err)
+ }
+
+ service := router.samlManager.GetService(provider.ID)
+ if service == nil {
+ t.Fatal("expected initialized SAML service")
+ }
+ if got := service.GetSPEntityID(); got != "/saml/okta" {
+ t.Fatalf("expected relative entity ID before login sync, got %q", got)
+ }
+ if got := service.sp.AcsURL.String(); got != "/api/saml/okta/acs" {
+ t.Fatalf("expected relative ACS URL before login sync, got %q", got)
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/api/saml/okta/login", nil)
+ rr := httptest.NewRecorder()
+
+ router.handleSAMLLogin(rr, req)
+
+ if rr.Code != http.StatusFound {
+ t.Fatalf("expected status %d, got %d", http.StatusFound, rr.Code)
+ }
+ if got := service.GetSPEntityID(); got != "https://pulse.example.com/saml/okta" {
+ t.Fatalf("expected absolute entity ID after login sync, got %q", got)
+ }
+ if got := service.sp.AcsURL.String(); got != "https://pulse.example.com/api/saml/okta/acs" {
+ t.Fatalf("expected absolute ACS URL after login sync, got %q", got)
+ }
+}
+
func TestHandleSAMLLogin_SuccessGetAndPost(t *testing.T) {
router := newSAMLRouter(t, testSAMLProvider("okta", true))
diff --git a/internal/api/saml_service.go b/internal/api/saml_service.go
index 1585904d31..f6e1eb53ac 100644
--- a/internal/api/saml_service.go
+++ b/internal/api/saml_service.go
@@ -33,6 +33,18 @@ type SAMLService struct {
lastRefresh time.Time
}
+func normalizeSAMLBaseURL(baseURL string) (string, error) {
+ normalized := strings.TrimRight(strings.TrimSpace(baseURL), "/")
+ if normalized == "" {
+ return "", nil
+ }
+ parsed, err := securityutil.NormalizeAbsoluteHTTPURL(normalized)
+ if err != nil {
+ return "", err
+ }
+ return strings.TrimRight(parsed.String(), "/"), nil
+}
+
// SAMLAuthResult contains the result of a successful SAML authentication
type SAMLAuthResult struct {
Username string
@@ -51,10 +63,15 @@ func NewSAMLService(ctx context.Context, providerID string, cfg *config.SAMLProv
return nil, errors.New("saml configuration is nil")
}
+ normalizedBaseURL, err := normalizeSAMLBaseURL(baseURL)
+ if err != nil {
+ return nil, fmt.Errorf("invalid saml base url: %w", err)
+ }
+
service := &SAMLService{
providerID: providerID,
config: cfg,
- baseURL: strings.TrimRight(baseURL, "/"),
+ baseURL: normalizedBaseURL,
httpClient: newSAMLHTTPClient(),
}
@@ -265,6 +282,12 @@ func (s *SAMLService) addIDPCertificate(metadata *saml.EntityDescriptor) error {
}
func (s *SAMLService) initServiceProvider() error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.initServiceProviderLocked()
+}
+
+func (s *SAMLService) initServiceProviderLocked() error {
// Build SP Entity ID
spEntityID := s.config.SPEntityID
if spEntityID == "" {
@@ -333,6 +356,32 @@ func (s *SAMLService) initServiceProvider() error {
return nil
}
+func (s *SAMLService) SetBaseURL(baseURL string) error {
+ normalizedBaseURL, err := normalizeSAMLBaseURL(baseURL)
+ if err != nil {
+ return fmt.Errorf("invalid saml base url: %w", err)
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if normalizedBaseURL == s.baseURL {
+ return nil
+ }
+
+ previousBaseURL := s.baseURL
+ previousSP := s.sp
+
+ s.baseURL = normalizedBaseURL
+ if err := s.initServiceProviderLocked(); err != nil {
+ s.baseURL = previousBaseURL
+ s.sp = previousSP
+ return err
+ }
+
+ return nil
+}
+
func (s *SAMLService) loadSPCredentials() (*x509.Certificate, *rsa.PrivateKey, error) {
var certData, keyData []byte
var err error