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
Derive SSO callback URLs from the request when no public URL is set
[email protected]a92825b9db31
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex c0e1cec7ac..4fb18c6b22 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -5401,3 +5401,17 @@ split. `internal/hostagent/proxmox_setup_test.go`,`internal/api/issue1644_host_install_token_proxmox_test.go` prove the recurringhealth, first-install, type/host binding, one-time consumption, rejection,host-token bootstrap, and concurrent-completion contracts.++### Shared internal/api request-origin helpers are read-only URL derivation++The shared `internal/api` boundary this subsystem consumes gained+`requestOriginBaseURL`, `requestForwardedScheme` and `requestForwardedHost` in+`internal/api/router.go`, factored out of the existing SSO OIDC callback URL+builder so SSO provider responses can derive endpoint URLs from the inbound+request instead of guessing `http://localhost:7655`. The helpers only read the+request; they honor forwarded headers under the same trusted-proxy gate the+callback builder already applied, and they neither mutate nor persist+`config.PublicURL`. No agent registration, token issuance, command admission,+update targeting, or fleet-lifecycle authority is touched, and the+extension-point expectations on `internal/api/` and `internal/api/router.go`+are otherwise unchanged.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 957fa75bc5..ddf254a693 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -8572,3 +8572,32 @@ checks, and lifecycle counts are additive.`internal/api/resources_pool_health_contract_test.go` and the frontendtype-check are the focused wire compatibility proofs.++### SSO provider endpoint URLs derive from the request, never from localhost++`providerToResponse` / `providerToDetailResponse` in+`internal/api/identity_sso_handlers.go` build `oidcLoginUrl`,+`oidcCallbackUrl`, `samlSpEntityId`, `samlMetadataUrl` and `samlAcsUrl` from a+base URL that is now resolved in this order: the configured public URL when set+(still authoritative, trailing slash trimmed), otherwise the scheme and host of+the inbound request. The previous `http://localhost:7655` fallback is gone. The+SSO settings panel presents these values as the URLs to register with the+Identity Provider, so a localhost guess was copied straight into an IdP where+it fails with no diagnosable cause; the admin's own request, by contrast,+necessarily arrived over an address that reaches Pulse.++The request-derived base URL uses the shared+`requestOriginBaseURL` / `requestForwardedScheme` / `requestForwardedHost`+helpers in `internal/api/router.go`, which honor `X-Forwarded-Proto`,+`X-Forwarded-Scheme` and `X-Forwarded-Host` only when the immediate peer is a+trusted proxy (`PULSE_TRUSTED_PROXY_CIDRS`). `buildSSOOIDCCallbackURL` in+`internal/api/oidc_handlers.go` now shares those helpers; its output is+unchanged.++All five fields are `omitempty` and are now omitted entirely when neither+source resolves a host, rather than carrying a wrong absolute URL. Clients must+treat an absent value as "no registerable URL available" and tell the operator+to configure a public URL. `TestContract_SSOProviderResponseBaseURLNeverGuessesLocalhost`+in `internal/api/contract_test.go` pins the precedence, the request fallback,+the trusted-proxy gate on forwarded headers, and the empty-rather-than-wrong+behavior.diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 8548b4e88f..301e25f2c6 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -5418,3 +5418,24 @@ andare the focused presentation proofs. The governed browser proof must open theshared resource detail surface and verify the same evidence labels in renderedUI.++### SSO endpoint URLs are presented as copyable only when the server supplied one++`frontend-modern/src/components/Settings/SSOProvidersPanel.tsx` renders the+OIDC Callback / Redirect URL and the SAML SP metadata and ACS URLs as+`CopyValueButton` chips that admins are told to register with their Identity+Provider. The backend may now legitimately omit those values when it cannot+resolve a public URL for the deployment, so each block falls back to guidance+text from `getSSOEndpointUnavailableHint` in+`frontend-modern/src/utils/ssoProviderPresentation.ts` instead of rendering a+copy affordance around an empty or wrong value. The panel must never embed a+`localhost` endpoint URL of its own.++The OIDC edit modal distinguishes the two reasons the URL can be missing: for a+provider being created it explains the URL is generated on save and copied from+the provider card afterwards (the modal closes on save, so it cannot show the+URL itself), and for an existing provider it shows the same public-URL guidance+as the card. `settingsArchitecture.test.ts` pins the guidance owner, the absent+localhost literal, and the corrected post-save copy; the rendered fallbacks and+copy affordances are covered by+`frontend-modern/src/components/Settings/__tests__/SSOProvidersPanel.test.tsx`.diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 732dd82841..a4c475969a 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -2069,3 +2069,12 @@ The public agent-version reconciliation path on `internal/api/router.go`remains an O(1) target projection. Cache-prevention headers and theagent-supplied non-secret cache key add no inventory scan, persistence read,metrics fan-out, or background work to `GET /api/agent/version`.++### Request-origin URL helpers on internal/api/router.go stay O(1)++The `requestForwardedScheme`, `requestForwardedHost` and `requestOriginBaseURL`+helpers added to `internal/api/router.go` perform only header reads and string+manipulation on the request already in hand. They add no inventory scan,+persistence read, lock acquisition, metrics fan-out, or background work, and+their cost is constant per SSO provider entry rendered in the admin settings+response.diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex fcf6abfc3b..08a7117628 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -1716,3 +1716,18 @@ runtime tokens remain in protected request headers and redirects remainrejected. The target-version query on `/download/pulse-agent` is cache identity,not trust evidence: checksum, embedded-key signature, self-test, and atomicreplacement validation remain mandatory and fail closed.++### Request-derived SSO endpoint URLs keep the trusted-proxy gate++`internal/api/router.go` gained `requestForwardedScheme`,+`requestForwardedHost` and `requestOriginBaseURL`, extracted verbatim from the+SSO OIDC callback URL builder so SSO provider responses can derive endpoint+URLs from the inbound request instead of returning a hardcoded+`http://localhost:7655`. The trust boundary is unchanged and fail-closed:+`X-Forwarded-Proto`, `X-Forwarded-Scheme` and `X-Forwarded-Host` are honored+only when the immediate peer matches `PULSE_TRUSTED_PROXY_CIDRS`, which is+empty by default, so an untrusted client cannot steer a returned URL to a host+or scheme of its choosing — it can only reach the same `Host` header handling+the request already depends on. The derived value is returned in an+admin-authenticated settings response and is never persisted, never used as a+redirect target, and never used to make an authorization decision.diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 5dfdf50f17..f487613cbd 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -4742,3 +4742,17 @@ fields and nullable mode/kind metadata before presenting canonical item labels,while storage detail drawers and filter controls must route summary series IDs,source tones, and disk metrics through the shared storage helpers instead ofreconstructing them from local table state.++### Shared internal/api request-origin helpers persist nothing++The shared `internal/api` boundary this subsystem consumes gained+`requestOriginBaseURL`, `requestForwardedScheme` and `requestForwardedHost` in+`internal/api/router.go`, used by `internal/api/identity_sso_handlers.go` to+derive SSO endpoint URLs from the inbound request when no public URL is+configured. The derivation is per-response and read-only: nothing is written to+`system.json`, the SSO config, or any other persisted artifact, and the+separate `capturePublicURLFromRequest` detection path that does persist a+detected public URL is unchanged. Tenant workspace preservation, recovery flows+that copy `system.json` forward, and backup or restore attribution are+unaffected, and the extension-point expectations on `internal/api/` and+`internal/api/router.go` are otherwise unchanged.diff --git a/frontend-modern/src/components/Settings/SSOProvidersPanel.tsx b/frontend-modern/src/components/Settings/SSOProvidersPanel.tsxindex 0f97d82985..969f449bf5 100644--- a/frontend-modern/src/components/Settings/SSOProvidersPanel.tsx+++ b/frontend-modern/src/components/Settings/SSOProvidersPanel.tsx@@ -19,6 +19,7 @@ import { SSOProviderTypeIcon } from './SSOProviderTypeIcon';import {getSSOProviderAddButtonLabel,getSSOCertificatePresentation,+ getSSOEndpointUnavailableHint,getSSOProviderCardClass,getSSOProviderEmptyStateDescription,getSSOProviderEmptyStateTitle,@@ -189,57 +190,75 @@ export const SSOProvidersPanel: Component<SSOProvidersPanelProps> = (props) => {</div>{/* OIDC callback info */}- <Show when={provider.type === 'oidc' && provider.oidcCallbackUrl}>+ <Show when={provider.type === 'oidc'}><div class="mt-3 pt-3 border-t border-border-subtle">- <div class="flex flex-wrap gap-4 text-xs">- <div class="flex items-center gap-1">- <span class="text-slate-500">Callback / Redirect URL:</span>- <CopyValueButton- value={provider.oidcCallbackUrl}- onCopyValue={(value) => copyToClipboard(value, 'Callback URL')}- label="Copy callback / redirect URL"- variant="accent"- size="chip"- class="max-w-[18rem] text-xs"- >- <span class="min-w-0 truncate">{provider.oidcCallbackUrl}</span>- </CopyValueButton>+ <Show+ when={provider.oidcCallbackUrl}+ fallback={+ <p class="text-xs text-muted">+ {getSSOEndpointUnavailableHint('Callback / Redirect URL')}+ </p>+ }+ >+ <div class="flex flex-wrap gap-4 text-xs">+ <div class="flex items-center gap-1">+ <span class="text-slate-500">Callback / Redirect URL:</span>+ <CopyValueButton+ value={provider.oidcCallbackUrl}+ onCopyValue={(value) => copyToClipboard(value, 'Callback URL')}+ label="Copy callback / redirect URL"+ variant="accent"+ size="chip"+ class="max-w-[18rem] text-xs"+ >+ <span class="min-w-0 truncate">{provider.oidcCallbackUrl}</span>+ </CopyValueButton>+ </div></div>- </div>+ </Show></div></Show>{/* SAML metadata info */}<Show when={provider.type === 'saml' && provider.enabled}><div class="mt-3 pt-3 border-t border-border-subtle">- <div class="flex flex-wrap gap-4 text-xs">- <div class="flex items-center gap-1">- <span class="text-slate-500">SP Metadata:</span>- <CopyValueButton- value={provider.samlMetadataUrl}- onCopyValue={(value) => copyToClipboard(value, 'Metadata URL')}- label="Copy SP metadata URL"- variant="accent"- size="chip"- class="max-w-[18rem] text-xs"- >- <span class="min-w-0 truncate">{provider.samlMetadataUrl}</span>- </CopyValueButton>- </div>- <div class="flex items-center gap-1">- <span class="text-slate-500">ACS URL:</span>- <CopyValueButton- value={provider.samlAcsUrl}- onCopyValue={(value) => copyToClipboard(value, 'ACS URL')}- label="Copy ACS URL"- variant="accent"- size="chip"- class="max-w-[18rem] text-xs"- >- <span class="min-w-0 truncate">{provider.samlAcsUrl}</span>- </CopyValueButton>+ <Show+ when={provider.samlMetadataUrl && provider.samlAcsUrl}+ fallback={+ <p class="text-xs text-muted">+ {getSSOEndpointUnavailableHint('SP metadata and ACS URLs')}+ </p>+ }+ >+ <div class="flex flex-wrap gap-4 text-xs">+ <div class="flex items-center gap-1">+ <span class="text-slate-500">SP Metadata:</span>+ <CopyValueButton+ value={provider.samlMetadataUrl}+ onCopyValue={(value) => copyToClipboard(value, 'Metadata URL')}+ label="Copy SP metadata URL"+ variant="accent"+ size="chip"+ class="max-w-[18rem] text-xs"+ >+ <span class="min-w-0 truncate">{provider.samlMetadataUrl}</span>+ </CopyValueButton>+ </div>+ <div class="flex items-center gap-1">+ <span class="text-slate-500">ACS URL:</span>+ <CopyValueButton+ value={provider.samlAcsUrl}+ onCopyValue={(value) => copyToClipboard(value, 'ACS URL')}+ label="Copy ACS URL"+ variant="accent"+ size="chip"+ class="max-w-[18rem] text-xs"+ >+ <span class="min-w-0 truncate">{provider.samlAcsUrl}</span>+ </CopyValueButton>+ </div></div>- </div>+ </Show></div></Show></div>@@ -304,8 +323,9 @@ export const SSOProvidersPanel: Component<SSOProvidersPanelProps> = (props) => {when={editingProvider()?.oidcCallbackUrl}fallback={<p class="mt-2 text-xs text-muted">- The Callback / Redirect URL is generated when the provider is saved and- shown here and on the provider card.+ {editingProvider()+ ? getSSOEndpointUnavailableHint('Callback / Redirect URL')+ : 'The Callback / Redirect URL is generated when the provider is saved. Save this provider, then copy it from the provider card.'}</p>}>@@ -411,7 +431,14 @@ export const SSOProvidersPanel: Component<SSOProvidersPanelProps> = (props) => {configure SSO URL + Certificate manually. Use the SP Metadata URL below toconfigure your Identity Provider.</p>- <Show when={publicUrl()}>+ <Show+ when={publicUrl()}+ fallback={+ <p class="mt-2 text-xs text-muted">+ {getSSOEndpointUnavailableHint('SP metadata URL')}+ </p>+ }+ ><div class="mt-2 flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2"><span class="text-xs text-muted">SP Metadata:</span><code class="inline-block max-w-full break-all rounded bg-surface-hover px-2 py-0.5 text-xs">diff --git a/frontend-modern/src/components/Settings/__tests__/SSOProvidersPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/SSOProvidersPanel.test.tsxindex be45f97aca..d61cc44a50 100644--- a/frontend-modern/src/components/Settings/__tests__/SSOProvidersPanel.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/SSOProvidersPanel.test.tsx@@ -136,3 +136,81 @@ describe('SSOProvidersPanel OIDC scopes', () => {});});});++describe('SSOProvidersPanel IdP endpoint URLs', () => {+ beforeEach(() => {+ fetchMock.mockReset();+ notificationSuccessMock.mockReset();+ notificationErrorMock.mockReset();+ loggerErrorMock.mockReset();+ loggerWarnMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ document.cookie = 'pulse_csrf=test-csrf-token';+ });++ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it('offers the server-supplied callback URL for copying', async () => {+ setupFetch([+ { ...corpProvider, oidcCallbackUrl: 'https://pulse.example.com/api/oidc/corp-oidc/callback' },+ ]);+ render(() => <SSOProvidersPanel />);++ expect(+ await screen.findByText('https://pulse.example.com/api/oidc/corp-oidc/callback'),+ ).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Copy callback / redirect URL' })).toBeTruthy();+ });++ it('guides the admin to set a public URL instead of offering a copyable OIDC URL', async () => {+ setupFetch([{ ...corpProvider, oidcCallbackUrl: '' }]);+ render(() => <SSOProvidersPanel />);++ expect(+ await screen.findByText(+ 'Set the public URL in Settings > System to generate the correct Callback / Redirect URL.',+ ),+ ).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Copy callback / redirect URL' })).toBeNull();+ });++ it('guides the admin to set a public URL instead of offering copyable SAML URLs', async () => {+ setupFetch([+ {+ id: 'corp-saml',+ name: 'Corporate SAML',+ type: 'saml' as const,+ enabled: true,+ priority: 0,+ samlMetadataUrl: '',+ samlAcsUrl: '',+ },+ ]);+ render(() => <SSOProvidersPanel />);++ expect(+ await screen.findByText(+ 'Set the public URL in Settings > System to generate the correct SP metadata and ACS URLs.',+ ),+ ).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Copy SP metadata URL' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Copy ACS URL' })).toBeNull();+ });++ it('tells a new OIDC provider where the callback URL appears after saving', async () => {+ setupFetch([]);+ render(() => <SSOProvidersPanel />);++ const addButton = await screen.findByRole('button', { name: /Add OIDC/i });+ fireEvent.click(addButton);++ expect(+ screen.getByText(+ 'The Callback / Redirect URL is generated when the provider is saved. Save this provider, then copy it from the provider card.',+ ),+ ).toBeTruthy();+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.tsindex b6a1ca22fb..a4ec77c7b4 100644--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts@@ -97,6 +97,7 @@ import useInfrastructureInstallStateSource from '../useInfrastructureInstallStatimport infrastructureOnboardingPresentationSource from '../../../utils/infrastructureOnboardingPresentation.ts?raw';import selfHostedBillingPresentationSource from '../selfHostedBillingPresentation.ts?raw';import systemSettingsPresentationSource from '../../../utils/systemSettingsPresentation.ts?raw';+import ssoProviderPresentationSource from '../../../utils/ssoProviderPresentation.ts?raw';import aiSettingsPresentationSource from '../../../utils/aiSettingsPresentation.ts?raw';import auditLogPresentationSource from '../../../utils/auditLogPresentation.ts?raw';import statusIndicatorBadgeSource from '../../shared/StatusIndicatorBadge.tsx?raw';@@ -981,6 +982,23 @@ describe('settings architecture guardrails', () => {expect(ssoProvidersStateSource).not.toContain('loadRuntimeCapabilities');});+ it('never offers a localhost SSO endpoint URL as if it were registerable with an IdP', () => {+ // The panel tells admins to register these URLs with their IdP, so a+ // hardcoded localhost guess would be copied out and fail at the IdP. The+ // backend derives them from the configured public URL or the request; when+ // neither resolves, the panel must guide instead of offering a copy button.+ expect(ssoProvidersPanelSource).not.toContain('localhost:7655');+ expect(ssoProvidersPanelSource).toContain('getSSOEndpointUnavailableHint');+ expect(ssoProviderPresentationSource).toContain('getSSOEndpointUnavailableHint');+ expect(ssoProviderPresentationSource).toContain(+ 'Set the public URL in Settings > System to generate the correct',+ );+ // The add-provider modal closes on save, so it must not promise the URL+ // will appear in the modal itself.+ expect(ssoProvidersPanelSource).not.toContain('shown here and on the provider card');+ expect(ssoProvidersPanelSource).toContain('then copy it from the provider card');+ });+it('keeps Docker and Podman update-action copy on the system settings presentation owner', () => {expect(dockerRuntimeSettingsCardSource).toContain('getDockerUpdateActionsPresentation');expect(dockerRuntimeSettingsCardSource).toContain('DOCKER_UPDATE_ACTIONS_ENV_VAR');diff --git a/frontend-modern/src/utils/__tests__/ssoProviderPresentation.test.ts b/frontend-modern/src/utils/__tests__/ssoProviderPresentation.test.tsindex d698b4f17a..a13b1bb0f5 100644--- a/frontend-modern/src/utils/__tests__/ssoProviderPresentation.test.ts+++ b/frontend-modern/src/utils/__tests__/ssoProviderPresentation.test.ts@@ -6,6 +6,7 @@ import {getSSOConnectionTestErrorMessage,getSSOConnectionTestFailureMessage,getSSOConnectionTestSuccessMessage,+ getSSOEndpointUnavailableHint,getSSOProviderCardClass,getSSOProviderDeleteErrorMessage,getSSOProviderDeleteSuccessMessage,@@ -93,6 +94,15 @@ describe('ssoProviderPresentation', () => {expect(getSSOMetadataFetchErrorMessage('timeout')).toBe('Unable to fetch metadata: timeout');});+ it('points admins at the public URL setting when an endpoint URL is unavailable', () => {+ expect(getSSOEndpointUnavailableHint('Callback / Redirect URL')).toBe(+ 'Set the public URL in Settings > System to generate the correct Callback / Redirect URL.',+ );+ expect(getSSOEndpointUnavailableHint('SP metadata and ACS URLs')).toBe(+ 'Set the public URL in Settings > System to generate the correct SP metadata and ACS URLs.',+ );+ });+it('formats certificate tone and expired label canonically', () => {expect(getSSOCertificatePresentation(true).containerClass).toContain('bg-red-100');expect(getSSOCertificatePresentation(false).containerClass).toContain('bg-surface-hover');diff --git a/frontend-modern/src/utils/ssoProviderPresentation.ts b/frontend-modern/src/utils/ssoProviderPresentation.tsindex e115ba7c28..1f1da4042e 100644--- a/frontend-modern/src/utils/ssoProviderPresentation.ts+++ b/frontend-modern/src/utils/ssoProviderPresentation.ts@@ -141,6 +141,14 @@ export function getSSOTestResultPresentation(success: boolean) {};}+// getSSOEndpointUnavailableHint explains why a server-generated SSO endpoint URL+// is missing. The backend derives these URLs from the configured public URL, or+// from the request when none is set, so an empty value means neither source+// resolved a host and the admin has to configure one explicitly.+export function getSSOEndpointUnavailableHint(endpointLabel: string): string {+ return `Set the public URL in Settings > System to generate the correct ${endpointLabel}.`;+}+export function getSSOCertificatePresentation(isExpired: boolean) {return {containerClass: isExpireddiff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex fd777aebc7..6368d267fe 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -22013,3 +22013,107 @@ func TestContract_AutoRegisteredInstallTokenTakesCleanExecFirstBind(t *testing.Tt.Fatalf("an already-versioned binding was replayed as a first use: %+v", bound)}}++// TestContract_SSOProviderResponseBaseURLNeverGuessesLocalhost pins the base URL+// used for the OIDC callback/login and SAML metadata/ACS URLs that the SSO+// settings panel tells admins to register with their IdP. A configured public+// URL stays authoritative. When none is set the URL is derived from the inbound+// request, which by construction reached Pulse — a hardcoded localhost guess+// would be copied into the IdP and fail there with no hint why. Forwarded+// headers only count when the peer is a trusted proxy.+func TestContract_SSOProviderResponseBaseURLNeverGuessesLocalhost(t *testing.T) {+ oidcProvider := &config.SSOProvider{+ ID: "corp-oidc",+ Name: "Corporate OIDC",+ Type: config.SSOProviderTypeOIDC,+ Enabled: true,+ OIDC: &config.OIDCProviderConfig{IssuerURL: "https://idp.example.com", ClientID: "pulse"},+ }+ samlProvider := &config.SSOProvider{+ ID: "corp-saml",+ Name: "Corporate SAML",+ Type: config.SSOProviderTypeSAML,+ Enabled: true,+ SAML: &config.SAMLProviderConfig{IDPSSOURL: "https://idp.example.com/sso"},+ }++ t.Run("configured public url stays authoritative", func(t *testing.T) {+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")+ resetTrustedProxyCIDRsForTests()++ req := httptest.NewRequest(http.MethodGet, "http://pulse.local:7655/api/security/sso/providers", nil)+ resp := providerToResponse(oidcProvider, "https://pulse.example.com/", req)++ if got, want := resp.OIDCCallbackURL, "https://pulse.example.com/api/oidc/corp-oidc/callback"; got != want {+ t.Fatalf("OIDCCallbackURL = %q, want %q", got, want)+ }+ if got, want := resp.OIDCLoginURL, "https://pulse.example.com/api/oidc/corp-oidc/login"; got != want {+ t.Fatalf("OIDCLoginURL = %q, want %q", got, want)+ }+ })++ t.Run("falls back to the request host instead of localhost", func(t *testing.T) {+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")+ resetTrustedProxyCIDRsForTests()++ req := httptest.NewRequest(http.MethodGet, "http://pulse.lan:7655/api/security/sso/providers", nil)+ resp := providerToResponse(oidcProvider, "", req)++ if got, want := resp.OIDCCallbackURL, "http://pulse.lan:7655/api/oidc/corp-oidc/callback"; got != want {+ t.Fatalf("OIDCCallbackURL = %q, want %q", got, want)+ }+ if strings.Contains(resp.OIDCCallbackURL, "localhost:7655") {+ t.Fatalf("OIDCCallbackURL fell back to a hardcoded localhost guess: %q", resp.OIDCCallbackURL)+ }++ samlResp := providerToResponse(samlProvider, "", req)+ if got, want := samlResp.SAMLMetadataURL, "http://pulse.lan:7655/api/saml/corp-saml/metadata"; got != want {+ t.Fatalf("SAMLMetadataURL = %q, want %q", got, want)+ }+ if got, want := samlResp.SAMLACSURL, "http://pulse.lan:7655/api/saml/corp-saml/acs"; got != want {+ t.Fatalf("SAMLACSURL = %q, want %q", got, want)+ }+ if got, want := samlResp.SAMLSPEntityID, "http://pulse.lan:7655/saml/corp-saml"; got != want {+ t.Fatalf("SAMLSPEntityID = %q, want %q", got, want)+ }+ })++ t.Run("honors forwarded headers only from a trusted proxy", func(t *testing.T) {+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "192.0.2.1/32")+ resetTrustedProxyCIDRsForTests()++ trusted := httptest.NewRequest(http.MethodGet, "http://pulse.lan:7655/api/security/sso/providers", nil)+ trusted.RemoteAddr = "192.0.2.1:5555"+ trusted.Header.Set("X-Forwarded-Proto", "https")+ trusted.Header.Set("X-Forwarded-Host", "sso.example.com")++ if got, want := providerToResponse(oidcProvider, "", trusted).OIDCCallbackURL, "https://sso.example.com/api/oidc/corp-oidc/callback"; got != want {+ t.Fatalf("trusted proxy OIDCCallbackURL = %q, want %q", got, want)+ }++ untrusted := httptest.NewRequest(http.MethodGet, "http://pulse.lan:7655/api/security/sso/providers", nil)+ untrusted.RemoteAddr = "198.51.100.7:5555"+ untrusted.Header.Set("X-Forwarded-Proto", "https")+ untrusted.Header.Set("X-Forwarded-Host", "attacker.example.com")++ if got, want := providerToResponse(oidcProvider, "", untrusted).OIDCCallbackURL, "http://pulse.lan:7655/api/oidc/corp-oidc/callback"; got != want {+ t.Fatalf("untrusted forwarded headers were honored: %q, want %q", got, want)+ }+ })++ t.Run("emits no url when neither source resolves a host", func(t *testing.T) {+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")+ resetTrustedProxyCIDRsForTests()++ resp := providerToResponse(oidcProvider, "", nil)+ if resp.OIDCCallbackURL != "" || resp.OIDCLoginURL != "" {+ t.Fatalf("expected empty OIDC URLs, got callback=%q login=%q", resp.OIDCCallbackURL, resp.OIDCLoginURL)+ }++ samlResp := providerToResponse(samlProvider, "", nil)+ if samlResp.SAMLMetadataURL != "" || samlResp.SAMLACSURL != "" || samlResp.SAMLSPEntityID != "" {+ t.Fatalf("expected empty SAML URLs, got metadata=%q acs=%q spEntityID=%q",+ samlResp.SAMLMetadataURL, samlResp.SAMLACSURL, samlResp.SAMLSPEntityID)+ }+ })+}diff --git a/internal/api/identity_sso_handlers.go b/internal/api/identity_sso_handlers.goindex 01ce29fb95..3282d9ca12 100644--- a/internal/api/identity_sso_handlers.go+++ b/internal/api/identity_sso_handlers.go@@ -268,7 +268,7 @@ func (r *Router) handleListSSOProviders(w http.ResponseWriter, req *http.Requestresponse.AllowMultipleProviders = r.ssoConfig.AllowMultipleProvidersfor _, p := range r.ssoConfig.Providers {- response.Providers = append(response.Providers, providerToResponse(&p, r.config.PublicURL))+ response.Providers = append(response.Providers, providerToResponse(&p, r.config.PublicURL, req))}w.Header().Set("Content-Type", "application/json")@@ -285,7 +285,7 @@ func (r *Router) handleGetSSOProvider(w http.ResponseWriter, req *http.Request,}w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(providerToDetailResponse(provider, r.config.PublicURL).NormalizeCollections())+ json.NewEncoder(w).Encode(providerToDetailResponse(provider, r.config.PublicURL, req).NormalizeCollections())}func (r *Router) handleCreateSSOProvider(w http.ResponseWriter, req *http.Request) {@@ -418,7 +418,7 @@ func (r *Router) handleCreateSSOProvider(w http.ResponseWriter, req *http.Requesw.Header().Set("Content-Type", "application/json")w.WriteHeader(http.StatusCreated)- json.NewEncoder(w).Encode(providerToResponse(&provider, r.config.PublicURL))+ json.NewEncoder(w).Encode(providerToResponse(&provider, r.config.PublicURL, req))}func (r *Router) handleUpdateSSOProvider(w http.ResponseWriter, req *http.Request, providerID string) {@@ -571,7 +571,7 @@ func (r *Router) handleUpdateSSOProvider(w http.ResponseWriter, req *http.RequesLogAuditEventForTenant(GetOrgID(req.Context()), "sso_provider_updated", "", GetClientIP(req), req.URL.Path, true, "Updated provider: "+updated.Name)w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(providerToResponse(&updated, r.config.PublicURL))+ json.NewEncoder(w).Encode(providerToResponse(&updated, r.config.PublicURL, req))}func (r *Router) handleDeleteSSOProvider(w http.ResponseWriter, req *http.Request, providerID string) {@@ -631,7 +631,20 @@ func (r *Router) saveSSOConfig() error {return nil}-func providerToResponse(p *config.SSOProvider, publicURL string) SSOProviderResponse {+// ssoResponseBaseURL resolves the base URL used to build the callback, login,+// metadata and ACS URLs handed to administrators for registration with their+// IdP. A configured public URL stays authoritative; otherwise the URL is+// derived from the inbound request, which by definition arrived over an address+// that reaches Pulse. Returns "" when neither source yields a host, so callers+// emit no URL at all rather than a localhost guess that fails at the IdP.+func ssoResponseBaseURL(publicURL string, req *http.Request) string {+ if configured := strings.TrimRight(strings.TrimSpace(publicURL), "/"); configured != "" {+ return configured+ }+ return requestOriginBaseURL(req)+}++func providerToResponse(p *config.SSOProvider, publicURL string, req *http.Request) SSOProviderResponse {resp := EmptySSOProviderResponse()resp.ID = p.IDresp.Name = p.Name@@ -650,17 +663,16 @@ func providerToResponse(p *config.SSOProvider, publicURL string) SSOProviderRespresp.DisplayName = p.Name}- baseURL := publicURL- if baseURL == "" {- baseURL = "http://localhost:7655"- }+ baseURL := ssoResponseBaseURL(publicURL, req)if p.Type == config.SSOProviderTypeOIDC && p.OIDC != nil {resp.OIDCIssuerURL = p.OIDC.IssuerURLresp.OIDCClientID = p.OIDC.ClientIDresp.OIDCClientSecretSet = p.OIDC.ClientSecretSet || p.OIDC.ClientSecret != ""- resp.OIDCLoginURL = baseURL + "/api/oidc/" + p.ID + "/login"- resp.OIDCCallbackURL = baseURL + "/api/oidc/" + p.ID + "/callback"+ if baseURL != "" {+ resp.OIDCLoginURL = baseURL + "/api/oidc/" + p.ID + "/login"+ resp.OIDCCallbackURL = baseURL + "/api/oidc/" + p.ID + "/callback"+ }}if p.Type == config.SSOProviderTypeSAML && p.SAML != nil {@@ -669,18 +681,20 @@ func providerToResponse(p *config.SSOProvider, publicURL string) SSOProviderRespresp.SAMLIDPEntityID = p.SAML.IDPIssuer}resp.SAMLSPEntityID = p.SAML.SPEntityID- if resp.SAMLSPEntityID == "" {+ if resp.SAMLSPEntityID == "" && baseURL != "" {resp.SAMLSPEntityID = baseURL + "/saml/" + p.ID}- resp.SAMLMetadataURL = baseURL + "/api/saml/" + p.ID + "/metadata"- resp.SAMLACSURL = baseURL + "/api/saml/" + p.ID + "/acs"+ if baseURL != "" {+ resp.SAMLMetadataURL = baseURL + "/api/saml/" + p.ID + "/metadata"+ resp.SAMLACSURL = baseURL + "/api/saml/" + p.ID + "/acs"+ }}return resp.NormalizeCollections()}-func providerToDetailResponse(p *config.SSOProvider, publicURL string) SSOProviderResponse {- resp := providerToResponse(p, publicURL)+func providerToDetailResponse(p *config.SSOProvider, publicURL string, req *http.Request) SSOProviderResponse {+ resp := providerToResponse(p, publicURL, req)if p.Type == config.SSOProviderTypeOIDC && p.OIDC != nil {resp.OIDC = &SSOProviderOIDCResponse{diff --git a/internal/api/oidc_handlers.go b/internal/api/oidc_handlers.goindex f2a88ad5b0..f5c4fe89b8 100644--- a/internal/api/oidc_handlers.go+++ b/internal/api/oidc_handlers.go@@ -310,45 +310,7 @@ func buildSSOOIDCCallbackURL(req *http.Request, providerID string, configuredURLreturn configured}- scheme := "http"- if req.TLS != nil {- scheme = "https"- }-- peerIP := extractRemoteIP(req.RemoteAddr)- trustedProxy := isTrustedProxyIP(peerIP)-- if trustedProxy {- if proto := firstForwardedValue(req.Header.Get("X-Forwarded-Proto")); proto != "" {- scheme = proto- } else if proto := firstForwardedValue(req.Header.Get("X-Forwarded-Scheme")); proto != "" {- scheme = proto- }- }- scheme = strings.ToLower(strings.TrimSpace(scheme))- switch scheme {- case "https", "http":- default:- if req.TLS != nil {- scheme = "https"- } else {- scheme = "http"- }- }-- rawHost := ""- if trustedProxy {- rawHost = firstForwardedValue(req.Header.Get("X-Forwarded-Host"))- }- if rawHost == "" {- rawHost = req.Host- }- host, _ := sanitizeForwardedHost(rawHost)- if host == "" {- host = req.Host- }-- return fmt.Sprintf("%s://%s/api/oidc/%s/callback", scheme, host, providerID)+ return fmt.Sprintf("%s://%s/api/oidc/%s/callback", requestForwardedScheme(req), requestForwardedHost(req), providerID)}// handleSSOOIDCLogin handles login for a multi-provider SSO OIDC provider.diff --git a/internal/api/router.go b/internal/api/router.goindex dd3cde4ec7..c0c3782720 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -4713,6 +4713,74 @@ func firstForwardedValue(header string) string {return strings.TrimSpace(parts[0])}+// requestForwardedScheme resolves the scheme the client used to reach Pulse.+// X-Forwarded-Proto / X-Forwarded-Scheme are only honored when the immediate+// peer is a trusted proxy, so untrusted clients cannot spoof "https".+func requestForwardedScheme(req *http.Request) string {+ scheme := "http"+ if req == nil {+ return scheme+ }+ if req.TLS != nil {+ scheme = "https"+ }++ if isTrustedProxyIP(extractRemoteIP(req.RemoteAddr)) {+ if proto := firstForwardedValue(req.Header.Get("X-Forwarded-Proto")); proto != "" {+ scheme = proto+ } else if proto := firstForwardedValue(req.Header.Get("X-Forwarded-Scheme")); proto != "" {+ scheme = proto+ }+ }++ scheme = strings.ToLower(strings.TrimSpace(scheme))+ switch scheme {+ case "http", "https":+ return scheme+ default:+ if req.TLS != nil {+ return "https"+ }+ return "http"+ }+}++// requestForwardedHost resolves the host:port the client used to reach Pulse.+// X-Forwarded-Host is only honored when the immediate peer is a trusted proxy.+// Returns "" when no host can be resolved.+func requestForwardedHost(req *http.Request) string {+ if req == nil {+ return ""+ }++ rawHost := ""+ if isTrustedProxyIP(extractRemoteIP(req.RemoteAddr)) {+ rawHost = firstForwardedValue(req.Header.Get("X-Forwarded-Host"))+ }+ if rawHost == "" {+ rawHost = req.Host+ }++ host, _ := sanitizeForwardedHost(rawHost)+ if host == "" {+ host = strings.TrimSpace(req.Host)+ }+ return host+}++// requestOriginBaseURL derives the scheme://host base URL the admin's browser+// used to reach Pulse. It is the fallback for building absolute URLs (OIDC+// callbacks, SAML metadata/ACS) when no public URL has been configured — the+// request necessarily arrived over a reachable address, unlike a hardcoded+// localhost guess. Returns "" when the host cannot be resolved.+func requestOriginBaseURL(req *http.Request) string {+ host := requestForwardedHost(req)+ if host == "" {+ return ""+ }+ return requestForwardedScheme(req) + "://" + host+}+func sanitizeForwardedHost(raw string) (string, string) {host := strings.TrimSpace(raw)if host == "" {