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 failed sign-in discovery distinct from first-run setup

pulse-triage[bot]552e5d502493
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 63b27aec8a..000f291974 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -10718,3 +10718,27 @@ settings mutation or a paid SSO gate. `SSOProvidersPanel.test.tsx` verifies
exact OIDC/SAML clipboard values, read-only/disabled-provider controls and
clipboard rejection. Actual consuming desktop and narrow-browser geometry,
keyboard/touch and inspected pixels establish responsive fit beyond JSDOM.
+
+
+### Failed login discovery is not first-run setup
+
+`Login.tsx` uses a complete bootstrap observation or reads `/api/security/status`
+before selecting setup or sign-in options. A boolean `hasAuth` hint alone cannot
+supply SSO/local-login policy. A failed read or missing/non-boolean
+`hasAuthentication` remains unknown; it never becomes `false`. Only an explicit
+server `false` enters the existing bootstrap-token-protected setup wizard.
+
+The failed-read surface offers sign-in help and one explicit, read-only retry.
+While pending, its live status and retry control remain mounted, duplicate
+requests are ignored, and a successful retry hands owned focus to the access
+region without stealing focus the user moved elsewhere. Disposal aborts the
+read and ignores late results. Supplied valid discovery still avoids a redundant
+read; existing SSO hiding, local-login override, lockouts, demo sign-in and
+remembered username behaviour remain unchanged. No authentication, entitlement,
+credential, server setup or session-validation rule changes.
+
+Normal-suite `components/__tests__/Login.test.tsx` covers failed and malformed
+reads, recovery to SSO/local login or confirmed setup, single-flight/cancellation,
+focus ownership and the established sign-in behaviours. Browser proof exercises
+the actual Login/API client/CSS with safe HTTP fixtures at desktop and narrow
+widths; it is not installed SSO or original private/access recovery.
diff --git a/frontend-modern/src/components/Login.tsx b/frontend-modern/src/components/Login.tsx
index 1d9e14e6c7..689b889daa 100644
--- a/frontend-modern/src/components/Login.tsx
+++ b/frontend-modern/src/components/Login.tsx
@@ -5,6 +5,7 @@ import {
Show,
For,
onMount,
+ onCleanup,
lazy,
Suspense,
} from 'solid-js';
@@ -21,7 +22,7 @@ const SetupWizard = lazy(() => import('./SetupWizard').then((m) => ({ default: m
interface LoginProps {
onLogin: () => void;
- hasAuth?: boolean; // If true, auth is configured (passed from App.tsx to skip redundant check)
+ hasAuth?: boolean; // Compatibility hint; full discovery still decides setup and sign-in options.
securityStatus?: SecurityStatus; // Full security status from App.tsx to avoid redundant API call
}
@@ -70,14 +71,62 @@ export const Login: Component<LoginProps> = (props) => {
const [rememberMe, setRememberMe] = createSignal(false);
const [error, setError] = createSignal('');
const [loading, setLoading] = createSignal(false);
- const [authStatus, setAuthStatus] = createSignal<SecurityStatus | null>(
- props.securityStatus ?? null,
- );
- // If hasAuth is passed from App.tsx, we already know auth status - skip the loading state
- // Also skip if securityStatus is provided
- const [loadingAuth, setLoadingAuth] = createSignal(
- props.hasAuth === undefined && !props.securityStatus,
- );
+ // Only an explicit server observation can select setup. A boolean hint from
+ // bootstrap cannot supply the SSO/local-login policy or turn a failed read
+ // into an unconfigured server.
+ const hasAuthDiscovery = (value: unknown): value is SecurityStatus =>
+ value !== null &&
+ typeof value === 'object' &&
+ typeof (value as SecurityStatus).hasAuthentication === 'boolean';
+ const initialStatus = hasAuthDiscovery(props.securityStatus) ? props.securityStatus : null;
+ const [authStatus, setAuthStatus] = createSignal<SecurityStatus | null>(initialStatus);
+ const [loadingAuth, setLoadingAuth] = createSignal(!initialStatus);
+ const [authReadFailed, setAuthReadFailed] = createSignal(false);
+ let authController: AbortController | undefined;
+ let active = true;
+ let accessEntry: HTMLDivElement | undefined;
+ let authReadNotice: HTMLDivElement | undefined;
+
+ onCleanup(() => {
+ active = false;
+ authController?.abort();
+ });
+
+ const readAuthStatus = async () => {
+ if (!active || authController) return;
+ const returnFocus = authReadNotice?.contains(document.activeElement);
+ const controller = new AbortController();
+ authController = controller;
+ setLoadingAuth(true);
+ let accepted = false;
+ try {
+ const data = await apiFetchJSON<unknown>('/api/security/status', {
+ signal: controller.signal,
+ retry: false,
+ });
+ if (!active) return;
+ if (!hasAuthDiscovery(data)) throw new Error('Authentication discovery is incomplete');
+ setAuthStatus(data);
+ setAuthReadFailed(false);
+ accepted = true;
+ } catch {
+ if (!active) return;
+ // Never expose proxy content, raw response errors or guessed auth state.
+ setAuthReadFailed(true);
+ } finally {
+ if (active) {
+ authController = undefined;
+ setLoadingAuth(false);
+ if (accepted && returnFocus) {
+ queueMicrotask(() => {
+ // Recovery removes Retry. Hand off its focus, not focus the user
+ // moved elsewhere while waiting, and never after unmount.
+ if (active && document.activeElement === document.body) accessEntry?.focus();
+ });
+ }
+ }
+ }
+ };
const [oidcLoading] = createSignal(false);
const [oidcError, setOidcError] = createSignal('');
const [oidcMessage, setOidcMessage] = createSignal('');
@@ -167,42 +216,9 @@ export const Login: Component<LoginProps> = (props) => {
window.history.replaceState({}, document.title, newUrl);
}
- // If securityStatus was passed from App.tsx, use it directly without making another API call
- // This eliminates the flicker between "Checking authentication..." and the login form
- // AND ensures hideLocalLogin and SSO settings are properly respected
- if (props.securityStatus) {
- logger.debug(
- '[Login] Using securityStatus from App.tsx, skipping redundant auth check',
- props.securityStatus,
- );
- setAuthStatus(props.securityStatus);
- setLoadingAuth(false);
- return;
- }
-
- // Compatibility fallback: if only hasAuth was passed (without full securityStatus)
- if (props.hasAuth !== undefined && !props.securityStatus) {
- logger.debug('[Login] Using hasAuth from App.tsx fallback, fetching full security status');
- // Still need to fetch full status to get hideLocalLogin and SSO settings.
- }
-
- logger.debug('[Login] Starting auth check...');
- try {
- const data = await apiFetchJSON<SecurityStatus>('/api/security/status');
- logger.debug('[Login] Auth status data', data);
- setAuthStatus(data);
- } catch (err: any) {
- // Check for 429
- // apiFetchJSON throws error with status attached? No, simple Error map.
- // But if needed we can parse error message if it contains "Too Many Requests"
-
- // Just assume no auth on error, matching previous logic mostly.
- logger.error('[Login] Failed to check auth status:', err);
- setAuthStatus({ hasAuthentication: false } as SecurityStatus);
- } finally {
- logger.debug('[Login] Auth check complete, setting loading to false');
- setLoadingAuth(false);
- }
+ // The full bootstrap observation avoids a redundant read. Failed or
+ // incomplete bootstrap discovery takes the same guarded read path here.
+ if (!initialStatus) await readAuthStatus();
});
// Auto-redirect to OIDC is intentionally disabled to prevent redirect loops
@@ -310,7 +326,7 @@ export const Login: Component<LoginProps> = (props) => {
// this page anyway, so sign the visitor in instead of making them type
// demo/demo. Once per browser tab, and never straight after a sign-out.
createEffect(() => {
- if (loadingAuth() || !demoModeEnabled() || showFirstRunSetup()) return;
+ if (loadingAuth() || authReadFailed() || !demoModeEnabled() || showFirstRunSetup()) return;
const params = new URLSearchParams(window.location.search);
if (params.has('oidc') || params.has('saml')) return;
const storage = getBrowserStorage('sessionStorage');
@@ -341,61 +357,100 @@ export const Login: Component<LoginProps> = (props) => {
};
return (
- <Show
- when={!loadingAuth()}
- fallback={
- <div class="min-h-screen flex items-center justify-center">
- <div class="text-center">
- <LoadingSpinner size="lg" tone="info" label="Checking authentication" class="mb-4" />
- <p class="text-muted">Checking authentication...</p>
- </div>
- </div>
- }
- >
+ <div ref={accessEntry} role="region" aria-label="Pulse access" tabIndex={-1}>
<Show
- when={showFirstRunSetup()}
+ when={!loadingAuth() || authReadFailed()}
fallback={
- <LoginForm
- {...{
- username,
- setUsername,
- password,
- setPassword,
- rememberMe,
- setRememberMe,
- error,
- loading,
- handleSubmit,
- oidcLoading,
- oidcError,
- oidcMessage,
- demoModeEnabled: demoModeEnabled(),
- demoAutoLogin,
- showLocalLogin: shouldShowLocalLogin(),
- ssoProviders: ssoProviders(),
- }}
- />
+ <div class="min-h-screen flex items-center justify-center">
+ <div class="text-center">
+ <LoadingSpinner size="lg" tone="info" label="Checking authentication" class="mb-4" />
+ <p class="text-muted">Checking authentication...</p>
+ </div>
+ </div>
}
>
- <Suspense
+ <Show
+ when={!authReadFailed()}
fallback={
- <div class="min-h-screen flex items-center justify-center">
- <div class="text-center">
- <LoadingSpinner size="lg" tone="info" label="Loading setup" class="mb-4" />
- <p class="text-muted">Loading setup...</p>
+ <div class="min-h-screen flex items-center justify-center px-4 py-8 text-base-content">
+ <div
+ ref={authReadNotice}
+ class="w-full max-w-md rounded-md border border-border bg-surface p-6 shadow-xs sm:p-8"
+ >
+ <h1 class="text-lg font-semibold">Could not check sign-in options</h1>
+ <p role="status" aria-live="polite" class="mt-3 text-sm leading-6 text-muted">
+ {loadingAuth()
+ ? 'Checking authentication again…'
+ : 'Pulse could not read its authentication status. This does not mean authentication is unconfigured.'}
+ </p>
+ <p class="mt-3 text-sm leading-6 text-muted">
+ Retry the check before changing authentication settings. This check does not
+ change your settings or start setup.
+ </p>
+ <button
+ type="button"
+ aria-disabled={loadingAuth()}
+ onClick={() => void readAuthStatus()}
+ class="mt-5 min-h-11 w-full rounded-md bg-blue-600 px-4 py-3 text-sm font-medium text-white hover:bg-blue-700 focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500 aria-disabled:opacity-50"
+ >
+ Retry sign-in check
+ </button>
+ <a
+ href={TROUBLESHOOTING_DOC_URL}
+ class="mt-3 inline-flex min-h-11 items-center rounded-sm px-1 text-sm font-medium text-blue-700 hover:underline focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500 dark:text-blue-300"
+ >
+ Can’t sign in?
+ </a>
</div>
</div>
}
>
- <SetupWizard
- onComplete={(nextPath) => {
- const target = nextPath || window.location.pathname;
- window.location.assign(target);
- }}
- />
- </Suspense>
+ <Show
+ when={showFirstRunSetup()}
+ fallback={
+ <LoginForm
+ {...{
+ username,
+ setUsername,
+ password,
+ setPassword,
+ rememberMe,
+ setRememberMe,
+ error,
+ loading,
+ handleSubmit,
+ oidcLoading,
+ oidcError,
+ oidcMessage,
+ demoModeEnabled: demoModeEnabled(),
+ demoAutoLogin,
+ showLocalLogin: shouldShowLocalLogin(),
+ ssoProviders: ssoProviders(),
+ }}
+ />
+ }
+ >
+ <Suspense
+ fallback={
+ <div class="min-h-screen flex items-center justify-center">
+ <div class="text-center">
+ <LoadingSpinner size="lg" tone="info" label="Loading setup" class="mb-4" />
+ <p class="text-muted">Loading setup...</p>
+ </div>
+ </div>
+ }
+ >
+ <SetupWizard
+ onComplete={(nextPath) => {
+ const target = nextPath || window.location.pathname;
+ window.location.assign(target);
+ }}
+ />
+ </Suspense>
+ </Show>
+ </Show>
</Show>
- </Show>
+ </div>
);
};
diff --git a/frontend-modern/src/components/__tests__/Login.test.tsx b/frontend-modern/src/components/__tests__/Login.test.tsx
index 8ec2e7d482..aff20b97a5 100644
--- a/frontend-modern/src/components/__tests__/Login.test.tsx
+++ b/frontend-modern/src/components/__tests__/Login.test.tsx
@@ -393,6 +393,215 @@ describe('Login', () => {
);
});
+ describe('authentication discovery recovery', () => {
+ const discoveryResponse = (data: unknown) =>
+ new Response(JSON.stringify(data), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ const expectNoGuessedAccess = () => {
+ expect(screen.queryByRole('main', { name: 'Pulse Setup Wizard' })).not.toBeInTheDocument();
+ expect(screen.queryByPlaceholderText('Username')).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /sign in to pulse/i })).not.toBeInTheDocument();
+ };
+
+ it.each([401, 403, 429, 503])(
+ 'keeps a failed HTTP %s read unknown and never starts setup or retries automatically',
+ async (status) => {
+ const onLogin = vi.fn();
+ mockFetch.mockResolvedValueOnce(
+ new Response(JSON.stringify({ error: 'SYNTHETIC_PRIVATE_RESPONSE' }), { status }),
+ );
+ render(() => <Login onLogin={onLogin} hasAuth={false} />);
+
+ expect(
+ await screen.findByRole('heading', { name: 'Could not check sign-in options' }),
+ ).toBeVisible();
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'does not mean authentication is unconfigured',
+ );
+ expectNoGuessedAccess();
+ expect(screen.queryByText(/SYNTHETIC_PRIVATE_RESPONSE/)).not.toBeInTheDocument();
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ expect(mockFetch.mock.calls[0][0]).toBe('/api/security/status');
+ expect(onLogin).not.toHaveBeenCalled();
+ expect(screen.getByRole('link', { name: 'Can’t sign in?' })).toHaveAttribute(
+ 'href',
+ '/docs/TROUBLESHOOTING',
+ );
+ },
+ );
+
+ it('keeps a network failure unknown without exposing its raw text', async () => {
+ mockFetch.mockRejectedValueOnce(new Error('SYNTHETIC_PRIVATE_TRANSPORT'));
+ render(() => <Login onLogin={vi.fn()} />);
+ expect(await screen.findByRole('button', { name: 'Retry sign-in check' })).toBeVisible();
+ expectNoGuessedAccess();
+ expect(document.body).not.toHaveTextContent('SYNTHETIC_PRIVATE_TRANSPORT');
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ null,
+ [],
+ {},
+ { hasAuthentication: null },
+ { hasAuthentication: 0 },
+ { hasAuthentication: 'false' },
+ ])('keeps incomplete or malformed discovery %j unknown', async (data) => {
+ mockFetch.mockResolvedValueOnce(discoveryResponse(data));
+ render(() => <Login onLogin={vi.fn()} />);
+ expect(await screen.findByRole('button', { name: 'Retry sign-in check' })).toBeVisible();
+ expectNoGuessedAccess();
+ });
+
+ it('keeps invalid JSON unknown instead of entering setup', async () => {
+ mockFetch.mockResolvedValueOnce(new Response('not-json', { status: 200 }));
+ render(() => <Login onLogin={vi.fn()} />);
+ expect(await screen.findByRole('button', { name: 'Retry sign-in check' })).toBeVisible();
+ expectNoGuessedAccess();
+ });
+
+ it.each([true, false])(
+ 'waits for full discovery despite a hasAuth=%s bootstrap hint',
+ async (hasAuth) => {
+ mockFetch.mockReturnValueOnce(new Promise(() => {}));
+ const view = render(() => <Login onLogin={vi.fn()} hasAuth={hasAuth} />);
+ expect(screen.getByText('Checking authentication...')).toBeVisible();
+ expectNoGuessedAccess();
+ const signal = mockFetch.mock.calls[0][1].signal as AbortSignal;
+ expect(signal.aborted).toBe(false);
+ view.unmount();
+ expect(signal.aborted).toBe(true);
+ },
+ );
+
+ it('reads again when bootstrap supplied no explicit authentication observation', async () => {
+ mockFetch.mockResolvedValueOnce(discoveryResponse({ hasAuthentication: true }));
+ render(() => <Login onLogin={vi.fn()} securityStatus={{} as any} />);
+ expect(await screen.findByPlaceholderText('Username')).toBeVisible();
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries one read, retains pending focus and restores SSO policy without local login', async () => {
+ mockFetch.mockResolvedValueOnce(new Response('{}', { status: 503 }));
+ let finish!: (response: Response) => void;
+ mockFetch.mockReturnValueOnce(
+ new Promise<Response>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const onLogin = vi.fn();
+ render(() => <Login onLogin={onLogin} hasAuth={true} />);
+ const retry = await screen.findByRole('button', { name: 'Retry sign-in check' });
+ retry.focus();
+ fireEvent.click(retry);
+ fireEvent.click(retry);
+ expect(screen.getByRole('button', { name: 'Retry sign-in check' })).toBe(retry);
+ expect(retry).toHaveAttribute('aria-disabled', 'true');
+ expect(retry).toHaveFocus();
+ expect(screen.getByRole('status')).toHaveTextContent('Checking authentication again');
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ expectNoGuessedAccess();
+ finish(
+ discoveryResponse({
+ hasAuthentication: true,
+ hideLocalLogin: true,
+ ssoProviders: [
+ {
+ id: 'lab',
+ name: 'Lab SSO',
+ displayName: 'Lab SSO',
+ type: 'oidc',
+ loginUrl: '/api/oidc/lab/login',
+ },
+ ],
+ }),
+ );
+ expect(await screen.findByRole('button', { name: 'Continue with Lab SSO' })).toBeVisible();
+ expect(screen.queryByPlaceholderText('Username')).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Retry sign-in check' })).not.toBeInTheDocument();
+ await waitFor(() =>
+ expect(screen.getByRole('region', { name: 'Pulse access' })).toHaveFocus(),
+ );
+ expect(
+ mockFetch.mock.calls.every(
+ ([url, options]) =>
+ url === '/api/security/status' && (!options.method || options.method === 'GET'),
+ ),
+ ).toBe(true);
+ expect(onLogin).not.toHaveBeenCalled();
+ });
+
+ it('retains the same retry control and focus after another failed read', async () => {
+ mockFetch.mockResolvedValueOnce(new Response('{}', { status: 503 }));
+ mockFetch.mockResolvedValueOnce(new Response('{}', { status: 503 }));
+ render(() => <Login onLogin={vi.fn()} />);
+ const retry = await screen.findByRole('button', { name: 'Retry sign-in check' });
+ retry.focus();
+ fireEvent.click(retry);
+ await waitFor(() => expect(retry).toHaveAttribute('aria-disabled', 'false'));
+ expect(screen.getByRole('button', { name: 'Retry sign-in check' })).toBe(retry);
+ expect(retry).toHaveFocus();
+ expectNoGuessedAccess();
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not steal focus moved outside the failed-read notice while a retry is pending', async () => {
+ mockFetch.mockResolvedValueOnce(new Response('{}', { status: 503 }));
+ let finish!: (response: Response) => void;
+ mockFetch.mockReturnValueOnce(
+ new Promise<Response>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ render(() => (
+ <>
+ <button type="button">Independent control</button>
+ <Login onLogin={vi.fn()} />
+ </>
+ ));
+ const retry = await screen.findByRole('button', { name: 'Retry sign-in check' });
+ retry.focus();
+ fireEvent.click(retry);
+ const independent = screen.getByRole('button', { name: 'Independent control' });
+ independent.focus();
+ finish(discoveryResponse({ hasAuthentication: true }));
+ expect(await screen.findByPlaceholderText('Username')).toBeVisible();
+ expect(independent).toHaveFocus();
+ });
+
+ it('ignores late discovery after disposal and aborts its transport', async () => {
+ let finish!: (response: Response) => void;
+ mockFetch.mockReturnValueOnce(
+ new Promise<Response>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const onLogin = vi.fn();
+ const view = render(() => <Login onLogin={onLogin} />);
+ const signal = mockFetch.mock.calls[0][1].signal as AbortSignal;
+ view.unmount();
+ expect(signal.aborted).toBe(true);
+ finish(discoveryResponse({ hasAuthentication: false }));
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(screen.queryByRole('region', { name: 'Pulse access' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('main', { name: 'Pulse Setup Wizard' })).not.toBeInTheDocument();
+ expect(onLogin).not.toHaveBeenCalled();
+ });
+
+ it('enters the existing protected setup only after retry explicitly observes unconfigured authentication', async () => {
+ mockFetch.mockResolvedValueOnce(new Response('{}', { status: 503 }));
+ mockFetch.mockResolvedValueOnce(discoveryResponse({ hasAuthentication: false }));
+ render(() => <Login onLogin={vi.fn()} hasAuth={false} />);
+ fireEvent.click(await screen.findByRole('button', { name: 'Retry sign-in check' }));
+ expect(await screen.findByRole('main', { name: 'Pulse Setup Wizard' })).toBeVisible();
+ expect(screen.queryByPlaceholderText('Username')).not.toBeInTheDocument();
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ });
+ });
+
it('routes login loading indicators through the shared LoadingSpinner primitive', () => {
expect(loginSource).toContain("from '@/components/shared/LoadingSpinner'");
expect(loginSource).toContain('<LoadingSpinner size="lg" tone="info"');