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.

Show readable SSO save guidance without replaying failed writes

pulse-triage[bot]2f827f1a1e6a
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 2b40dd5a88..465b2ab92f 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -162,6 +162,22 @@ authority.
### SSO editor feedback and exact group names (24 October 2026)
+SSO save failures use the API client's human `message`/legacy `error` field,
+not the JSON envelope, code, timestamp or diagnostic details. Short plain-text
+validation errors remain useful; malformed, markup, control-bearing, oversized
+or unavailable guidance falls back to bounded recovery text. Raw response data
+and thrown network errors are not logged by this save path. A lost response
+must not claim that nothing was saved. Create and edit each make one write per
+explicit submission, including CSRF and rate-limit failures; the form, access
+restrictions and omitted saved secrets survive until deliberate correction or
+retry. The bounded, scrollable feedback area allows the complete ordinary
+initialisation/no-save guidance above the recovery controls on phones.
+`SSOProviderSaveErrors.test.tsx` covers both provider types and create/edit through
+the real state hook and API client. Presentation tests bind unsafe-input fallback;
+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.
+
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/SSOProvidersPanel.tsx b/frontend-modern/src/components/Settings/SSOProvidersPanel.tsx
index 2016479c2e..480af100c0 100644
--- a/frontend-modern/src/components/Settings/SSOProvidersPanel.tsx
+++ b/frontend-modern/src/components/Settings/SSOProvidersPanel.tsx
@@ -797,7 +797,7 @@ export const SSOProvidersPanel: Component<SSOProvidersPanelProps> = (props) => {
<p
role={feedback.tone === 'error' ? 'alert' : 'status'}
tabindex="0"
- class={`max-h-28 overflow-y-auto text-sm [overflow-wrap:anywhere] ${
+ class={`max-h-48 overflow-y-auto text-sm [overflow-wrap:anywhere] ${
feedback.tone === 'error'
? 'text-red-700 dark:text-red-300'
: 'text-base-content'
diff --git a/frontend-modern/src/components/Settings/__tests__/SSOProviderSaveErrors.test.tsx b/frontend-modern/src/components/Settings/__tests__/SSOProviderSaveErrors.test.tsx
index 0db078fcb8..8f64799f06 100644
--- a/frontend-modern/src/components/Settings/__tests__/SSOProviderSaveErrors.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/SSOProviderSaveErrors.test.tsx
@@ -21,12 +21,26 @@ const json = (body: unknown, status = 200) =>
const scenarios = [
{
name: 'structured error envelope',
- response: () => json({ error: guidance, code: 'initialization_error', details: { private: canary }, status_code: 400, timestamp: 1793050000 }, 400),
+ response: () =>
+ json(
+ {
+ error: guidance,
+ code: 'initialization_error',
+ details: { private: canary },
+ status_code: 400,
+ timestamp: 1793050000,
+ },
+ 400,
+ ),
expected: `Unable to save the SSO provider: ${guidance}`,
},
{
name: 'structured message before legacy error',
- response: () => json({ message: 'Check the provider settings.', error: canary, details: { private: canary } }, 400),
+ response: () =>
+ json(
+ { message: 'Check the provider settings.', error: canary, details: { private: canary } },
+ 400,
+ ),
expected: 'Unable to save the SSO provider: Check the provider settings.',
},
{
@@ -51,7 +65,9 @@ const scenarios = [
},
{
name: 'lost network response',
- response: () => { throw new Error(canary); },
+ response: () => {
+ throw new Error(canary);
+ },
expected: fallback,
},
{
@@ -61,7 +77,11 @@ const scenarios = [
},
{
name: 'rate limit without hidden replay',
- response: () => new Response(JSON.stringify({ error: 'Wait before saving again.' }), { status: 429, headers: { 'Content-Type': 'application/json', 'Retry-After': '0.001' } }),
+ response: () =>
+ new Response(JSON.stringify({ error: 'Wait before saving again.' }), {
+ status: 429,
+ headers: { 'Content-Type': 'application/json', 'Retry-After': '0.001' },
+ }),
expected: 'Unable to save the SSO provider: Wait before saving again.',
},
];
@@ -72,39 +92,65 @@ describe.each(['oidc', 'saml'] as const)('SSO %s save error recovery', (type) =>
vi.stubGlobal('fetch', fetchMock);
document.cookie = 'pulse_csrf=synthetic-csrf';
});
- afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
for (const editing of [false, true]) {
it.each(scenarios)(`${editing ? 'edit' : 'create'}: $name`, async ({ response, expected }) => {
const provider = {
- id: 'recovery', name: 'Original provider', type, enabled: true, priority: 0,
- allowedGroups: ['Server Access'], allowedDomains: ['example.test'],
+ id: 'recovery',
+ name: 'Original provider',
+ type,
+ enabled: true,
+ priority: 0,
+ allowedGroups: ['Server Access'],
+ allowedDomains: ['example.test'],
groupRoleMappings: { 'Server Access': 'viewer' },
- oidc: { issuerUrl: 'https://issuer.example.test', clientId: 'pulse', clientSecretSet: true },
+ oidc: {
+ issuerUrl: 'https://issuer.example.test',
+ clientId: 'pulse',
+ clientSecretSet: true,
+ },
saml: { idpEntityId: 'original', idpSsoUrl: 'https://issuer.example.test/sso' },
};
let reject = true;
fetchMock.mockImplementation(async (url: string, options?: RequestInit) => {
- if (options?.method === 'POST' || options?.method === 'PUT') return reject ? response() : json({});
- if (url === '/api/security/status') return json({ publicUrl: 'https://pulse.example.test' });
+ if (options?.method === 'POST' || options?.method === 'PUT')
+ return reject ? response() : json({});
+ if (url === '/api/security/status')
+ return json({ publicUrl: 'https://pulse.example.test' });
if (url.endsWith('/recovery')) return json(provider);
return json({ providers: editing ? [provider] : [] });
});
render(() => <SSOProvidersPanel />);
- fireEvent.click(await screen.findByRole('button', { name: editing ? 'Edit provider' : `Add ${type.toUpperCase()}` }));
+ fireEvent.click(
+ await screen.findByRole('button', {
+ name: editing ? 'Edit provider' : `Add ${type.toUpperCase()}`,
+ }),
+ );
const dialog = within(await screen.findByRole('dialog'));
const name = dialog.getByLabelText('Provider Name') as HTMLInputElement;
fireEvent.input(name, { target: { value: 'Retained draft' } });
if (!editing) {
if (type === 'oidc') {
- fireEvent.input(dialog.getByLabelText('Issuer URL'), { target: { value: 'https://issuer.example.test' } });
+ fireEvent.input(dialog.getByLabelText('Issuer URL'), {
+ target: { value: 'https://issuer.example.test' },
+ });
fireEvent.input(dialog.getByLabelText('Client ID'), { target: { value: 'pulse' } });
} else {
- fireEvent.input(dialog.getByLabelText('IdP Entity ID'), { target: { value: 'attempted' } });
- fireEvent.input(dialog.getByLabelText('IdP SSO URL'), { target: { value: 'https://issuer.example.test/sso' } });
+ fireEvent.input(dialog.getByLabelText('IdP Entity ID'), {
+ target: { value: 'attempted' },
+ });
+ fireEvent.input(dialog.getByLabelText('IdP SSO URL'), {
+ target: { value: 'https://issuer.example.test/sso' },
+ });
}
}
- const save = dialog.getByRole('button', { name: editing ? 'Save Changes' : 'Create Provider' });
+ const save = dialog.getByRole('button', {
+ name: editing ? 'Save Changes' : 'Create Provider',
+ });
const form = save.closest('form')!;
fireEvent.submit(form);
expect(await dialog.findByRole('alert')).toHaveTextContent(expected);
@@ -114,7 +160,8 @@ describe.each(['oidc', 'saml'] as const)('SSO %s save error recovery', (type) =>
expect(save).toBeEnabled();
expect(dialog.getByRole('button', { name: 'Cancel' })).toBeEnabled();
expect(successMock).not.toHaveBeenCalled();
- const writes = () => fetchMock.mock.calls.filter(([, options]) => ['POST', 'PUT'].includes(options?.method));
+ const writes = () =>
+ fetchMock.mock.calls.filter(([, options]) => ['POST', 'PUT'].includes(options?.method));
expect(writes()).toHaveLength(1);
expect(JSON.stringify(loggerErrorMock.mock.calls)).not.toContain(canary);
expect(JSON.stringify(loggerErrorMock.mock.calls)).not.toContain('initialization_error');
diff --git a/frontend-modern/src/components/Settings/useSSOProvidersState.ts b/frontend-modern/src/components/Settings/useSSOProvidersState.ts
index b3aef7cc07..9f7e8ff0ef 100644
--- a/frontend-modern/src/components/Settings/useSSOProvidersState.ts
+++ b/frontend-modern/src/components/Settings/useSSOProvidersState.ts
@@ -133,7 +133,7 @@ export const useSSOProvidersState = (props: SSOProvidersPanelProps) => {
setSaving(true);
try {
- const { apiFetch } = await import('@/utils/apiClient');
+ const { apiFetch, apiErrorFromResponse } = await import('@/utils/apiClient');
const isEdit = Boolean(editingProvider());
const response = await apiFetch(
isEdit
@@ -141,23 +141,29 @@ export const useSSOProvidersState = (props: SSOProvidersPanelProps) => {
: '/api/security/sso/providers',
{
method: isEdit ? 'PUT' : 'POST',
+ // Keep failed configuration writes in this draft until an explicit retry.
+ retry: false,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(buildProviderPayload(form)),
},
);
if (!response.ok) {
- const errorText = await response.text();
- throw new Error(errorText || `Failed to save provider (${response.status})`);
+ const error = await apiErrorFromResponse(response);
+ setEditorFeedback({ tone: 'error', message: getSSOProviderSaveErrorMessage(error) });
+ // Envelope details and upstream bodies can contain private provider data.
+ logger.error('[SSOProvidersPanel] Failed to save provider.', { status: response.status });
+ return;
}
notificationStore.success(getSSOProviderSaveSuccessMessage(isEdit));
setShowModal(false);
await loadProviders();
props.onConfigUpdated?.();
- } catch (error) {
- logger.error('[SSOProvidersPanel] Failed to save provider:', error);
- setEditorFeedback({ tone: 'error', message: getSSOProviderSaveErrorMessage(error) });
+ } catch {
+ // A lost response cannot establish whether the server saved the change.
+ logger.error('[SSOProvidersPanel] Failed to save provider.');
+ setEditorFeedback({ tone: 'error', message: getSSOProviderSaveErrorMessage() });
} finally {
setSaving(false);
}
diff --git a/frontend-modern/src/utils/__tests__/ssoProviderPresentation.branchcov0717.test.ts b/frontend-modern/src/utils/__tests__/ssoProviderPresentation.branchcov0717.test.ts
index 1f8e456e93..65a69bd4b0 100644
--- a/frontend-modern/src/utils/__tests__/ssoProviderPresentation.branchcov0717.test.ts
+++ b/frontend-modern/src/utils/__tests__/ssoProviderPresentation.branchcov0717.test.ts
@@ -36,7 +36,7 @@ import {
// `getSSOProviderModalTitle`, the falsy `oidcIssuerUrl || ''` arm, and both
// falsy arms of the nested `samlIdpEntityId || samlMetadataUrl || ''` chain in
// `getSSOProviderSummary`. It also pins the full concrete return values and
-// `String(error)` coercion behaviour that the sibling suite only spot-checks.
+// bounded save-error presentation that the sibling suite only spot-checks.
describe('ssoProviderPresentation branch coverage (supplemental)', () => {
describe('getSSOProviderTypeLabel', () => {
@@ -122,30 +122,38 @@ describe('ssoProviderPresentation branch coverage (supplemental)', () => {
});
describe('getSSOProviderSaveErrorMessage', () => {
- it('coerces an undefined error to the literal string "undefined" via String()', () => {
- // `String(undefined)` => 'undefined' — documents the runtime behaviour of
- // the optional `error` parameter when callers omit it.
- expect(getSSOProviderSaveErrorMessage()).toBe('Unable to save the SSO provider: undefined');
- });
-
- it('coerces null to "null"', () => {
- expect(getSSOProviderSaveErrorMessage(null)).toBe('Unable to save the SSO provider: null');
- });
-
- it('coerces a plain object to "[object Object]"', () => {
- expect(getSSOProviderSaveErrorMessage({ status: 500 })).toBe(
- 'Unable to save the SSO provider: [object Object]',
+ it('uses an Error message without the JavaScript Error prefix', () => {
+ expect(getSSOProviderSaveErrorMessage(new Error('Check the provider settings.'))).toBe(
+ 'Unable to save the SSO provider: Check the provider settings.',
+ );
+ expect(getSSOProviderSaveErrorMessage(' Invalid role mapping ')).toBe(
+ 'Unable to save the SSO provider: Invalid role mapping',
);
});
- it('coerces an Error instance to "Error: <message>"', () => {
- expect(getSSOProviderSaveErrorMessage(new Error('boom'))).toBe(
- 'Unable to save the SSO provider: Error: boom',
+ it.each([
+ undefined,
+ null,
+ { status: 500 },
+ 42,
+ '',
+ ' ',
+ '{"error":',
+ '[object Object]',
+ '"json string"',
+ '<html>Bad Gateway</html>',
+ 'bad\nmessage',
+ 'x'.repeat(501),
+ ])('uses bounded recovery guidance for unsuitable input %j', (error) => {
+ expect(getSSOProviderSaveErrorMessage(error)).toBe(
+ 'Unable to save the SSO provider. Check the connection and try saving again.',
);
});
- it('coerces a number to its decimal string form', () => {
- expect(getSSOProviderSaveErrorMessage(42)).toBe('Unable to save the SSO provider: 42');
+ it('accepts exactly the bounded human-message length', () => {
+ expect(getSSOProviderSaveErrorMessage('x'.repeat(500))).toBe(
+ `Unable to save the SSO provider: ${'x'.repeat(500)}`,
+ );
});
});
diff --git a/frontend-modern/src/utils/ssoProviderPresentation.ts b/frontend-modern/src/utils/ssoProviderPresentation.ts
index 07a78563db..866719ae1f 100644
--- a/frontend-modern/src/utils/ssoProviderPresentation.ts
+++ b/frontend-modern/src/utils/ssoProviderPresentation.ts
@@ -60,7 +60,20 @@ export function getSSOProviderSaveSuccessMessage(isEdit: boolean): string {
}
export function getSSOProviderSaveErrorMessage(error?: unknown): string {
- return `Unable to save the SSO provider: ${String(error)}`;
+ const message = (
+ error instanceof Error ? error.message : typeof error === 'string' ? error : ''
+ ).trim();
+ // Only short human guidance belongs in the editor, never markup, malformed
+ // envelopes, object coercions or an unbounded upstream response.
+ if (
+ !message ||
+ message.length > 500 ||
+ /^[{["]/.test(message) ||
+ /[<>\u0000-\u001F\u007F]/.test(message) // eslint-disable-line no-control-regex -- intentional sanitization
+ ) {
+ return 'Unable to save the SSO provider. Check the connection and try saving again.';
+ }
+ return `Unable to save the SSO provider: ${message}`;
}
export function getSSOProviderDeleteSuccessMessage(): string {