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.

Keep SAML metadata preview failures private and actionable

pulse-triage[bot]fc11bf88342b
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 568df52dc6..d7edf9fe0a 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -213,6 +213,25 @@ source-bound desktop/narrow browser proof uses captured producer envelopes and
synthetic non-JSON gateway/validation responses. This is not installed sign-in,
issuer compatibility, server persistence or original #3038/#61 recovery proof.
+SAML metadata-preview failures use fixed guidance for recognised validation,
+fetch and parse categories, session/permission refusals and rate limits; unknown,
+legacy, malformed or unavailable replies use bounded connection/URL guidance.
+The editor never stringifies response bodies, error messages, diagnostic details
+or arbitrary callback values into this feedback or the preview logger. It names
+TLS trust on the Pulse server without suggesting a verification bypass. Each
+deliberate Preview makes one request, including CSRF/rate-limit refusals, and
+does not save provider configuration. URL/certificate drafts and access
+restrictions survive failure and retry; a successful parsed/XML preview still
+closes back to the editor and leaves saving explicit. Existing authentication
+expiry handling remains owned by the API client, not replaced by preview copy.
+The normal-suite SSOMetadataPreview.test.tsx exercises create/edit through the
+real state hook and API client, including failure -> explicit retry -> preview ->
+close/cancel, unsafe envelopes/HTML/network errors and disabled blank URLs.
+Presentation tests bind the category-only boundary without object coercion.
+Source-bound desktop/narrow browser proof uses existing public-shaped producer
+responses and adversarial safe fixtures through the production Settings editor.
+This is not a live IdP fetch, provider save, native sign-in or #3038 acceptance.
+
The provider editor scrolls its fields independently of its header and recovery
footer. Save refusals, metadata-preview errors and clipboard outcomes stay in
that active dialog, with live alert/status semantics; connection tests use the
diff --git a/frontend-modern/src/components/Settings/__tests__/SSOMetadataPreview.test.tsx b/frontend-modern/src/components/Settings/__tests__/SSOMetadataPreview.test.tsx
new file mode 100644
index 0000000000..6a4a4b0e59
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/SSOMetadataPreview.test.tsx
@@ -0,0 +1,203 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
+import { SSOProvidersPanel } from '../SSOProvidersPanel';
+
+const fetchMock = vi.fn();
+const loggerErrorMock = vi.fn();
+const notificationErrorMock = vi.fn();
+vi.mock('@/utils/logger', () => ({
+ logger: { error: (...args: unknown[]) => loggerErrorMock(...args), warn: vi.fn() },
+}));
+vi.mock('@/stores/notifications', () => ({
+ notificationStore: {
+ success: vi.fn(),
+ error: (...args: unknown[]) => notificationErrorMock(...args),
+ },
+}));
+
+const canary = 'SYNTHETIC_PRIVATE_METADATA_DETAIL';
+const fallback =
+ 'Unable to preview SAML metadata. Check the connection and metadata URL, then try again. Your draft has not been saved.';
+const fetchGuidance =
+ 'Unable to fetch SAML metadata. Check the URL, provider availability and TLS trust on the Pulse server, then try again. Your draft has not been saved.';
+const json = (body: unknown, status = 200) =>
+ new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+const envelope = (code: unknown) =>
+ json(
+ { error: canary, code, details: { private: canary }, status_code: 400, timestamp: 1793078652 },
+ 400,
+ );
+const preview = {
+ xml: '<EntityDescriptor entityID="https://idp.example.test/entity"/>',
+ parsed: { entityId: 'https://idp.example.test/entity', ssoUrl: 'https://idp.example.test/sso' },
+};
+const cases = [
+ {
+ name: 'structured fetch error',
+ response: () => envelope('fetch_error'),
+ expected: fetchGuidance,
+ },
+ {
+ name: 'structured validation error',
+ response: () => envelope('validation_error'),
+ expected:
+ 'Unable to preview SAML metadata. Check the metadata URL and try again. Your draft has not been saved.',
+ },
+ {
+ name: 'structured parse error',
+ response: () => envelope('parse_error'),
+ expected:
+ 'Unable to parse SAML metadata. Check that the URL returns a SAML metadata document. Your draft has not been saved.',
+ },
+ {
+ name: 'generic private preview error',
+ response: () => envelope('preview_error'),
+ expected: fallback,
+ },
+ { name: 'unknown failure code', response: () => envelope(canary), expected: fallback },
+ {
+ name: 'wrong-type failure code',
+ response: () => envelope({ private: canary }),
+ expected: fallback,
+ },
+ {
+ name: 'legacy gateway page',
+ response: () => new Response(`<html><pre>${canary}</pre></html>`, { status: 502 }),
+ expected: fallback,
+ },
+ {
+ name: 'legacy plain text',
+ response: () => new Response(canary, { status: 400 }),
+ expected: fallback,
+ },
+ {
+ name: 'malformed JSON',
+ response: () => new Response('{"error":', { status: 500 }),
+ expected: fallback,
+ },
+ {
+ name: 'oversized error',
+ response: () => json({ error: canary.repeat(100) }, 400),
+ expected: fallback,
+ },
+ {
+ name: 'lost response',
+ response: () => {
+ throw new Error(canary);
+ },
+ expected: fallback,
+ },
+ {
+ name: 'CSRF refusal without hidden retry',
+ response: () => json({ error: canary }, 403),
+ expected:
+ 'Metadata preview was refused. Check your administrator session and permissions, then try again. Your draft has not been saved.',
+ },
+ {
+ name: 'rate limit without hidden retry',
+ response: () =>
+ new Response(JSON.stringify({ code: 'rate_limited', error: canary }), {
+ status: 429,
+ headers: { 'Retry-After': '0.001' },
+ }),
+ expected:
+ 'Too many metadata previews. Wait a moment and try again. Your draft has not been saved.',
+ },
+];
+
+describe.each([false, true])('SAML metadata preview recovery (editing=%s)', (editing) => {
+ const provider = {
+ id: 'corp-saml',
+ name: 'Corporate SAML',
+ type: 'saml',
+ enabled: true,
+ priority: 0,
+ allowedGroups: ['Server Access'],
+ groupRoleMappings: { 'Server Access': 'viewer' },
+ saml: { idpMetadataUrl: 'https://original.example.test/metadata' },
+ };
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ document.cookie = 'pulse_csrf=synthetic-csrf';
+ });
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ it.each(cases)(
+ '$name preserves drafts and allows an explicit retry',
+ async ({ response, expected }) => {
+ let fail = true;
+ fetchMock.mockImplementation(async (url: string, options?: RequestInit) => {
+ if (url.endsWith('/metadata/preview')) return fail ? response() : json(preview);
+ if (url === '/api/security/status')
+ return json({ publicUrl: 'https://pulse.example.test' });
+ if (url.endsWith('/corp-saml')) return json(provider);
+ return json({ providers: editing ? [provider] : [] });
+ });
+ render(() => <SSOProvidersPanel />);
+ fireEvent.click(
+ await screen.findByRole('button', { name: editing ? 'Edit provider' : 'Add SAML' }),
+ );
+ const editor = await screen.findByRole('dialog');
+ const dialog = within(editor);
+ const url = dialog.getByLabelText('IdP Metadata URL') as HTMLInputElement;
+ const cert = dialog.getByLabelText('IdP Certificate (PEM)') as HTMLTextAreaElement;
+ fireEvent.input(url, { target: { value: 'https://idp.example.test/metadata' } });
+ fireEvent.input(cert, { target: { value: 'synthetic-local-certificate-draft' } });
+ fireEvent.click(dialog.getByRole('button', { name: 'Preview' }));
+ const alert = await dialog.findByRole('alert');
+ expect(alert.textContent).toBe(expected);
+ expect(alert.textContent).not.toContain(canary);
+ expect(url.value).toBe('https://idp.example.test/metadata');
+ expect(cert.value).toBe('synthetic-local-certificate-draft');
+ expect(dialog.getByRole('button', { name: 'Preview' })).toBeEnabled();
+ expect(dialog.getByRole('button', { name: 'Cancel' })).toBeEnabled();
+ expect(notificationErrorMock).not.toHaveBeenCalled();
+ expect(JSON.stringify(loggerErrorMock.mock.calls)).not.toContain(canary);
+ expect(
+ screen.queryByRole('dialog', { name: 'IdP metadata preview' }),
+ ).not.toBeInTheDocument();
+
+ const posts = () => fetchMock.mock.calls.filter(([, options]) => options?.method === 'POST');
+ expect(posts()).toHaveLength(1);
+ expect(JSON.parse(posts()[0][1].body)).toEqual({ type: 'saml', metadataUrl: url.value });
+
+ fail = false;
+ fireEvent.click(dialog.getByRole('button', { name: 'Preview' }));
+ const result = await screen.findByRole('dialog', { name: 'IdP metadata preview' });
+ expect(result).toHaveTextContent(preview.parsed.entityId);
+ expect(result).toHaveTextContent(preview.parsed.ssoUrl);
+ expect(posts()).toHaveLength(2);
+ expect(posts()[1][1].body).toBe(posts()[0][1].body);
+ expect(editor.querySelector('[role="alert"]')).toBeNull();
+ fireEvent.click(within(result).getByRole('button', { name: 'Close metadata preview' }));
+ expect(url.value).toBe('https://idp.example.test/metadata');
+ expect(cert.value).toBe('synthetic-local-certificate-draft');
+ expect(
+ fetchMock.mock.calls.every(
+ ([path, options]) => !options?.method || path.endsWith('/metadata/preview'),
+ ),
+ ).toBe(true);
+ fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ },
+ );
+
+ it('does not dispatch a blank URL or interpret preview as saving', async () => {
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/corp-saml') ? json(provider) : json({ providers: editing ? [provider] : [] }),
+ );
+ render(() => <SSOProvidersPanel />);
+ fireEvent.click(
+ await screen.findByRole('button', { name: editing ? 'Edit provider' : 'Add SAML' }),
+ );
+ const dialog = within(await screen.findByRole('dialog'));
+ fireEvent.input(dialog.getByLabelText('IdP Metadata URL'), { target: { value: ' ' } });
+ expect(dialog.getByRole('button', { name: 'Preview' })).toBeDisabled();
+ expect(dialog.queryByRole('alert')).toBeNull();
+ expect(fetchMock.mock.calls.every(([, options]) => !options?.method)).toBe(true);
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/SSOProvidersPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/SSOProvidersPanel.test.tsx
index 26eb91a9ee..2db5a9f8b5 100644
--- a/frontend-modern/src/components/Settings/__tests__/SSOProvidersPanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/SSOProvidersPanel.test.tsx
@@ -407,7 +407,10 @@ describe('SSOProvidersPanel modal feedback and recovery', () => {
target: { value: 'https://idp.example.com/metadata' },
});
fireEvent.click(dialog.getByRole('button', { name: 'Preview' }));
- expect(await dialog.findByRole('alert')).toHaveTextContent('Metadata unavailable');
+ expect(await dialog.findByRole('alert')).toHaveTextContent(
+ 'Unable to preview SAML metadata. Check the connection and metadata URL, then try again.',
+ );
+ expect(dialog.getByRole('alert')).not.toHaveTextContent('Metadata unavailable');
expect(notificationErrorMock).not.toHaveBeenCalled();
});
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index de3f2682b9..88b38ce665 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -1185,6 +1185,29 @@ describe('settings architecture guardrails', () => {
expect(editor).not.toContain('sticky');
});
+ it('keeps metadata preview recovery on private dialog-owned presentation', () => {
+ const start = ssoProvidersStateSource.indexOf('const fetchMetadataPreview =');
+ const previewLifecycle = ssoProvidersStateSource.slice(
+ start,
+ ssoProvidersStateSource.indexOf('\n return {', start),
+ );
+ expect(previewLifecycle).toContain('apiErrorFromResponse(response)');
+ expect(previewLifecycle).toContain('getSSOMetadataFetchErrorMessage(error)');
+ expect(previewLifecycle).toContain('getSSOMetadataFetchErrorMessage()');
+ expect(previewLifecycle).toContain('setEditorFeedback');
+ expect(previewLifecycle).toContain('retry: false');
+ expect(previewLifecycle).not.toContain('response.text()');
+ expect(previewLifecycle).not.toContain('String(error)');
+ expect(previewLifecycle).not.toContain('notificationStore');
+ expect(previewLifecycle).not.toMatch(/logger\.error\([^;]*,\s*error\)/);
+ const presentation = ssoProviderPresentationSource.slice(
+ ssoProviderPresentationSource.indexOf('export function getSSOMetadataFetchErrorMessage'),
+ ssoProviderPresentationSource.indexOf('export function getSSOProviderSummary'),
+ );
+ expect(presentation).not.toContain('String(error)');
+ expect(presentation).not.toContain('error.message');
+ });
+
it('keeps SAML SSO available without a self-hosted Pro upsell boundary', () => {
expect(ssoProvidersPanelSource).toContain('@/components/shared/Button');
expect(ssoProvidersPanelSource).toContain('ActionIconButton');
diff --git a/frontend-modern/src/components/Settings/useSSOProvidersState.ts b/frontend-modern/src/components/Settings/useSSOProvidersState.ts
index 9f7e8ff0ef..6a3c6345c5 100644
--- a/frontend-modern/src/components/Settings/useSSOProvidersState.ts
+++ b/frontend-modern/src/components/Settings/useSSOProvidersState.ts
@@ -290,6 +290,9 @@ export const useSSOProvidersState = (props: SSOProvidersPanelProps) => {
const canTest = () => canTestProviderForm(form);
const fetchMetadataPreview = async () => {
+ if (!canManage() || loadingPreview()) {
+ return;
+ }
setEditorFeedback(null);
if (!form.samlIdpMetadataUrl.trim()) {
setEditorFeedback({ tone: 'error', message: getSSOMetadataUrlRequiredMessage() });
@@ -300,23 +303,26 @@ export const useSSOProvidersState = (props: SSOProvidersPanelProps) => {
setMetadataPreview(null);
try {
- const { apiFetch } = await import('@/utils/apiClient');
+ const { apiFetch, apiErrorFromResponse } = await import('@/utils/apiClient');
const response = await apiFetch('/api/security/sso/providers/metadata/preview', {
method: 'POST',
+ retry: false,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(buildMetadataPreviewPayload(form)),
});
if (!response.ok) {
- const errorText = await response.text();
- throw new Error(errorText || 'Failed to fetch metadata');
+ const error = await apiErrorFromResponse(response);
+ setEditorFeedback({ tone: 'error', message: getSSOMetadataFetchErrorMessage(error) });
+ logger.error('[SSOProvidersPanel] Metadata preview failed.', { status: response.status });
+ return;
}
setMetadataPreview((await response.json()) as MetadataPreview);
setShowMetadataPreview(true);
- } catch (error) {
- logger.error('[SSOProvidersPanel] Metadata preview error:', error);
- setEditorFeedback({ tone: 'error', message: getSSOMetadataFetchErrorMessage(error) });
+ } catch {
+ logger.error('[SSOProvidersPanel] Metadata preview failed.');
+ setEditorFeedback({ tone: 'error', message: getSSOMetadataFetchErrorMessage() });
} finally {
setLoadingPreview(false);
}
diff --git a/frontend-modern/src/utils/__tests__/ssoProviderPresentation.branchcov0717.test.ts b/frontend-modern/src/utils/__tests__/ssoProviderPresentation.branchcov0717.test.ts
index 65a69bd4b0..cf6ff1526a 100644
--- a/frontend-modern/src/utils/__tests__/ssoProviderPresentation.branchcov0717.test.ts
+++ b/frontend-modern/src/utils/__tests__/ssoProviderPresentation.branchcov0717.test.ts
@@ -206,18 +206,52 @@ describe('ssoProviderPresentation branch coverage (supplemental)', () => {
expect(getSSOMetadataUrlRequiredMessage()).toBe('Enter an IdP metadata URL.');
});
- it('coerces an undefined error to "undefined" via String()', () => {
- expect(getSSOMetadataFetchErrorMessage()).toBe('Unable to fetch metadata: undefined');
+ const fallback =
+ 'Unable to preview SAML metadata. Check the connection and metadata URL, then try again. Your draft has not been saved.';
+
+ it.each([
+ undefined,
+ null,
+ 'timeout',
+ new Error('private upstream text'),
+ { code: 'ECONNRESET' },
+ { code: ['fetch_error'] },
+ ])('keeps unknown error input out of recovery guidance (%s)', (error) =>
+ expect(getSSOMetadataFetchErrorMessage(error)).toBe(fallback),
+ );
+
+ it('does not coerce arbitrary failures into visible text', () => {
+ expect(
+ getSSOMetadataFetchErrorMessage({
+ toString: () => {
+ throw new Error('must not coerce');
+ },
+ }),
+ ).toBe(fallback);
});
- it('coerces null to "null"', () => {
- expect(getSSOMetadataFetchErrorMessage(null)).toBe('Unable to fetch metadata: null');
+ it.each([
+ ['validation_error', 'Check the metadata URL'],
+ ['fetch_error', 'TLS trust on the Pulse server'],
+ ['parse_error', 'URL returns a SAML metadata document'],
+ ['rate_limited', 'Wait a moment'],
+ ])('maps only the recognised %s category to fixed guidance', (code, guidance) => {
+ const message = getSSOMetadataFetchErrorMessage({
+ code,
+ message: 'private upstream text',
+ details: { private: 'private detail' },
+ });
+ expect(message).toContain(guidance);
+ expect(message).toContain('Your draft has not been saved.');
+ expect(message).not.toContain('private');
+ expect(message.length).toBeLessThan(200);
});
- it('coerces a plain object to "[object Object]"', () => {
- expect(getSSOMetadataFetchErrorMessage({ code: 'ECONNRESET' })).toBe(
- 'Unable to fetch metadata: [object Object]',
+ it('uses the HTTP refusal or rate-limit status even without a code', () => {
+ expect(getSSOMetadataFetchErrorMessage({ status: 403, code: 'fetch_error' })).toContain(
+ 'session and permissions',
);
+ expect(getSSOMetadataFetchErrorMessage({ status: 429 })).toContain('Wait a moment');
});
});
diff --git a/frontend-modern/src/utils/__tests__/ssoProviderPresentation.test.ts b/frontend-modern/src/utils/__tests__/ssoProviderPresentation.test.ts
index aed54dc799..4a14a029b6 100644
--- a/frontend-modern/src/utils/__tests__/ssoProviderPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/ssoProviderPresentation.test.ts
@@ -93,7 +93,9 @@ describe('ssoProviderPresentation', () => {
);
expect(getSSOConnectionTestErrorMessage()).toBe('Unable to run the connection test.');
expect(getSSOMetadataUrlRequiredMessage()).toBe('Enter an IdP metadata URL.');
- expect(getSSOMetadataFetchErrorMessage('timeout')).toBe('Unable to fetch metadata: timeout');
+ expect(getSSOMetadataFetchErrorMessage('timeout')).toBe(
+ 'Unable to preview SAML metadata. Check the connection and metadata URL, then try again. Your draft has not been saved.',
+ );
});
it('points admins at the public URL setting when an endpoint URL is unavailable', () => {
diff --git a/frontend-modern/src/utils/ssoProviderPresentation.ts b/frontend-modern/src/utils/ssoProviderPresentation.ts
index 866719ae1f..9ef595f4c0 100644
--- a/frontend-modern/src/utils/ssoProviderPresentation.ts
+++ b/frontend-modern/src/utils/ssoProviderPresentation.ts
@@ -117,7 +117,26 @@ export function getSSOMetadataUrlRequiredMessage(): string {
}
export function getSSOMetadataFetchErrorMessage(error?: unknown): string {
- return `Unable to fetch metadata: ${String(error)}`;
+ // Preview callbacks, proxies and network errors can contain private provider
+ // data. Use recognised categories only, never their message or raw response.
+ const failure =
+ error && typeof error === 'object' ? (error as { code?: unknown; status?: unknown }) : {};
+ if (failure.status === 403) {
+ return 'Metadata preview was refused. Check your administrator session and permissions, then try again. Your draft has not been saved.';
+ }
+ if (failure.status === 429 || failure.code === 'rate_limited') {
+ return 'Too many metadata previews. Wait a moment and try again. Your draft has not been saved.';
+ }
+ switch (failure.code) {
+ case 'validation_error':
+ return 'Unable to preview SAML metadata. Check the metadata URL and try again. Your draft has not been saved.';
+ case 'fetch_error':
+ return 'Unable to fetch SAML metadata. Check the URL, provider availability and TLS trust on the Pulse server, then try again. Your draft has not been saved.';
+ case 'parse_error':
+ return 'Unable to parse SAML metadata. Check that the URL returns a SAML metadata document. Your draft has not been saved.';
+ default:
+ return 'Unable to preview SAML metadata. Check the connection and metadata URL, then try again. Your draft has not been saved.';
+ }
}
export function getSSOProviderSummary(provider: SSOProviderSummaryLike): string {