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.

Bound sign-out preparation and response waits

pulse-triage[bot]8953faefc727
diff --git a/frontend-modern/src/AppLayout.tsx b/frontend-modern/src/AppLayout.tsx
index b9567a2604..3f8af6574a 100644
--- a/frontend-modern/src/AppLayout.tsx
+++ b/frontend-modern/src/AppLayout.tsx
@@ -2,6 +2,7 @@ import { For, Show, Suspense, createEffect, createMemo, createSignal, onCleanup
import type { JSX } from 'solid-js';
import { A, useLocation, useNavigate } from '@solidjs/router';
import BellIcon from 'lucide-solid/icons/bell';
+import LoaderCircleIcon from 'lucide-solid/icons/loader-circle';
import ListChecksIcon from 'lucide-solid/icons/list-checks';
import SettingsIcon from 'lucide-solid/icons/settings';
import Maximize2Icon from 'lucide-solid/icons/maximize-2';
@@ -807,24 +808,31 @@ export function AppLayout(props: AppLayoutProps) {
onClick={props.handleLogout}
disabled={props.isLoggingOut?.()}
aria-busy={props.isLoggingOut?.() || undefined}
- class="group relative flex h-9 w-9 items-center justify-center rounded-full bg-surface-hover text-xs text-base-content transition hover:bg-border focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500 sm:h-10 sm:w-10"
+ class="group relative flex h-9 w-9 items-center justify-center rounded-full bg-surface-hover text-xs text-base-content transition hover:bg-border focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500 disabled:cursor-wait disabled:opacity-60 sm:h-10 sm:w-10"
title={props.isLoggingOut?.() ? 'Signing out…' : 'Logout'}
aria-label={props.isLoggingOut?.() ? 'Signing out…' : 'Logout'}
>
- <svg
- class="h-4 w-4 shrink-0"
- fill="none"
- viewBox="0 0 24 24"
- stroke="currentColor"
- stroke-width="2"
- aria-hidden="true"
+ <Show
+ when={props.isLoggingOut?.()}
+ fallback={
+ <svg
+ class="h-4 w-4 shrink-0"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ stroke-width="2"
+ aria-hidden="true"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
+ />
+ </svg>
+ }
>
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
- />
- </svg>
+ <LoaderCircleIcon class="h-4 w-4 animate-spin" aria-hidden="true" />
+ </Show>
</button>
</div>
</Show>
diff --git a/frontend-modern/src/__tests__/AppLayout.test.tsx b/frontend-modern/src/__tests__/AppLayout.test.tsx
index b20bb29049..b164c9dbc7 100644
--- a/frontend-modern/src/__tests__/AppLayout.test.tsx
+++ b/frontend-modern/src/__tests__/AppLayout.test.tsx
@@ -655,7 +655,14 @@ describe('AppLayout Issue1650 kiosk scope containment', () => {
});
it('names and disables the actual sign-out control while withdrawal is pending, and restores retry', async () => {
const [loggingOut, setLoggingOut] = createSignal(false);
- renderLayout([], '/settings/infrastructure', undefined, ['settings:read'], undefined, loggingOut);
+ renderLayout(
+ [],
+ '/settings/infrastructure',
+ undefined,
+ ['settings:read'],
+ undefined,
+ loggingOut,
+ );
expect(screen.getByRole('button', { name: 'Logout' })).not.toBeDisabled();
setLoggingOut(true);
const pending = screen.getByRole('button', { name: 'Signing out…' });
@@ -664,5 +671,4 @@ describe('AppLayout Issue1650 kiosk scope containment', () => {
setLoggingOut(false);
expect(screen.getByRole('button', { name: 'Logout' })).not.toBeDisabled();
});
-
});
diff --git a/frontend-modern/src/__tests__/useAppRuntimeState.test.ts b/frontend-modern/src/__tests__/useAppRuntimeState.test.ts
index b5bfd82134..2ab7fd5c62 100644
--- a/frontend-modern/src/__tests__/useAppRuntimeState.test.ts
+++ b/frontend-modern/src/__tests__/useAppRuntimeState.test.ts
@@ -322,6 +322,9 @@ describe('useAppRuntimeState', () => {
vi.clearAllMocks();
window.localStorage.removeItem('org_id');
window.localStorage.removeItem('just_logged_out');
+ for (const key of ['auth', 'guest_metadata', 'docker_metadata', 'docker_metadata_hosts']) {
+ window.localStorage.removeItem(key);
+ }
const policyModule = await import('@/stores/sessionPresentationPolicy');
policyModule.syncSessionPresentationPolicy(null);
vi.resetModules();
@@ -635,7 +638,7 @@ describe('useAppRuntimeState', () => {
ssoEnabled: true,
ssoSessionUsername: principal,
ssoSessionDisplayName: '[email protected]',
- ssoLogoutURL: '/api/oidc/test-oidc/logout',
+ ssoLogoutURL: 'https://idp.example.test/logout',
}),
{ status: 200 },
);
@@ -660,7 +663,7 @@ describe('useAppRuntimeState', () => {
await waitFor(() => {
expect(hookState.proxyAuthInfo()).toEqual({
username: '[email protected]',
- logoutURL: '/api/oidc/test-oidc/logout',
+ logoutURL: 'https://idp.example.test/logout',
});
expect(hookState.platformAdmission()).not.toBeNull();
});
@@ -739,14 +742,25 @@ describe('useAppRuntimeState', () => {
const fallback = apiFetchMock.getMockImplementation()!;
apiFetchMock.mockImplementation(async (url: string) => {
if (url === '/api/security/status') {
- return new Response(JSON.stringify({
- hasAuthentication: true,
- ...(mode === 'proxy' ? {
- hasProxyAuth: true, proxyAuthUsername: 'synthetic-proxy', proxyAuthLogoutURL: '/#proxy-logout',
- } : mode === 'sso' ? {
- ssoEnabled: true, ssoSessionUsername: 'synthetic-sso', ssoLogoutURL: '/#sso-logout',
- } : {}),
- }), { status: 200 });
+ return new Response(
+ JSON.stringify({
+ hasAuthentication: true,
+ ...(mode === 'proxy'
+ ? {
+ hasProxyAuth: true,
+ proxyAuthUsername: 'synthetic-proxy',
+ proxyAuthLogoutURL: '/#proxy-logout',
+ }
+ : mode === 'sso'
+ ? {
+ ssoEnabled: true,
+ ssoSessionUsername: 'synthetic-sso',
+ ssoLogoutURL: '/#sso-logout',
+ }
+ : {}),
+ }),
+ { status: 200 },
+ );
}
return fallback(url);
});
@@ -756,99 +770,139 @@ describe('useAppRuntimeState', () => {
return mounted;
};
- it.each(['local', 'proxy', 'sso'] as const)('logout acknowledges the local session before %s navigation and cleanup', async (mode) => {
- const { hookState } = await mountLogout(mode);
- for (const key of ['auth', 'guest_metadata', 'docker_metadata', 'docker_metadata_hosts']) {
- localStorage.setItem(key, 'synthetic-cache');
- }
- sessionStorage.setItem('auth', 'synthetic-browser-token');
- sessionStorage.setItem('pulse_auth_user', 'synthetic-user');
- let finish!: (value: Response) => void;
- const fallback = apiFetchMock.getMockImplementation()!;
- apiFetchMock.mockImplementation((url: string) => url === '/api/logout'
- ? new Promise<Response>((resolve) => { finish = resolve; }) : fallback(url));
- const pending = hookState.handleLogout();
- await waitFor(() => expect(finish).toBeDefined());
- expect(hookState.isLoggingOut()).toBe(true);
- expect(clearAuthMock).not.toHaveBeenCalled();
- expect(localStorage.getItem('auth')).toBe('synthetic-cache');
- expect(window.location.hash).toBe('');
- await hookState.handleLogout();
- expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/logout')).toHaveLength(1);
- expect(apiFetchMock).toHaveBeenCalledWith('/api/logout', expect.objectContaining({
- method: 'POST', retry: false, skipOrgContext: true, redirect: 'error', signal: expect.any(AbortSignal),
- }));
- finish(new Response('{"success":true}', { status: 200 }));
- await pending;
- expect(clearAuthMock).toHaveBeenCalledOnce();
- for (const key of ['auth', 'guest_metadata', 'docker_metadata', 'docker_metadata_hosts']) {
- expect(localStorage.getItem(key)).toBeNull();
- }
- expect(sessionStorage.getItem('auth')).toBeNull();
- expect(sessionStorage.getItem('pulse_auth_user')).toBeNull();
- expect(sessionStorage.getItem('pulse_demo_auto_login')).toBe('suppressed');
- expect(localStorage.getItem('just_logged_out')).toBe('true');
- expect(hookState.enhancedStore()).toBeNull();
- expect(hookState.needsAuth()).toBe(true);
- expect(aiAvailabilitySetEnabledMock).toHaveBeenLastCalledWith(false);
- expect(hookState.isLoggingOut()).toBe(false);
- expect(showToastMock).not.toHaveBeenCalled();
- if (mode !== 'local') expect(window.location.hash).toBe(`#${mode}-logout`);
- });
+ it.each(['local', 'proxy', 'sso'] as const)(
+ 'logout acknowledges the local session before %s navigation and cleanup',
+ async (mode) => {
+ const { hookState } = await mountLogout(mode);
+ for (const key of ['auth', 'guest_metadata', 'docker_metadata', 'docker_metadata_hosts']) {
+ localStorage.setItem(key, 'synthetic-cache');
+ }
+ sessionStorage.setItem('auth', 'synthetic-browser-token');
+ sessionStorage.setItem('pulse_auth_user', 'synthetic-user');
+ let finish!: (value: Response) => void;
+ const fallback = apiFetchMock.getMockImplementation()!;
+ apiFetchMock.mockImplementation((url: string) =>
+ url === '/api/logout'
+ ? new Promise<Response>((resolve) => {
+ finish = resolve;
+ })
+ : fallback(url),
+ );
+ const pending = hookState.handleLogout();
+ await waitFor(() => expect(finish).toBeDefined());
+ expect(hookState.isLoggingOut()).toBe(true);
+ expect(clearAuthMock).not.toHaveBeenCalled();
+ expect(localStorage.getItem('auth')).toBe('synthetic-cache');
+ expect(window.location.hash).toBe('');
+ await hookState.handleLogout();
+ expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/logout')).toHaveLength(1);
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ '/api/logout',
+ expect.objectContaining({
+ method: 'POST',
+ retry: false,
+ skipOrgContext: true,
+ redirect: 'error',
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ finish(new Response('{"success":true}', { status: 200 }));
+ await pending;
+ expect(clearAuthMock).toHaveBeenCalledOnce();
+ for (const key of ['auth', 'guest_metadata', 'docker_metadata', 'docker_metadata_hosts']) {
+ expect(localStorage.getItem(key)).toBeNull();
+ }
+ expect(sessionStorage.getItem('auth')).toBeNull();
+ expect(sessionStorage.getItem('pulse_auth_user')).toBeNull();
+ expect(sessionStorage.getItem('pulse_demo_auto_login')).toBe('suppressed');
+ expect(localStorage.getItem('just_logged_out')).toBe('true');
+ expect(hookState.enhancedStore()).toBeNull();
+ expect(hookState.needsAuth()).toBe(true);
+ expect(aiAvailabilitySetEnabledMock).toHaveBeenLastCalledWith(false);
+ expect(hookState.isLoggingOut()).toBe(false);
+ expect(showToastMock).not.toHaveBeenCalled();
+ if (mode !== 'local') expect(window.location.hash).toBe(`#${mode}-logout`);
+ },
+ );
- it.each(['401', '403', '503', 'network', 'html', 'null', 'false', 'redirect'])('logout keeps uncertain %s visible without clearing or redirecting, and permits deliberate retry', async (failure) => {
- const { hookState } = await mountLogout();
- sessionStorage.setItem('auth', 'saved-browser-credential');
- const fallback = apiFetchMock.getMockImplementation()!;
- let attempts = 0;
- apiFetchMock.mockImplementation(async (url: string) => {
- if (url !== '/api/logout') return fallback(url);
- attempts++;
- if (attempts > 1) return new Response('{"success":true}');
- if (failure === 'network') throw new TypeError('Synthetic lost response');
- if (/^\d+$/.test(failure)) return new Response('refused', { status: Number(failure) });
- const bodies: Record<string, string> = { html: '<html>proxy login</html>', null: 'null', false: '{"success":false}', redirect: '' };
- return new Response(bodies[failure], { status: failure === 'redirect' ? 302 : 200 });
- });
- await hookState.handleLogout();
- expect(attempts).toBe(1);
- expect(hookState.isLoggingOut()).toBe(false);
- expect(hookState.needsAuth()).toBe(false);
- expect(clearAuthMock).not.toHaveBeenCalled();
- expect(sessionStorage.getItem('auth')).toBe('saved-browser-credential');
- expect(localStorage.getItem('just_logged_out')).toBeNull();
- expect(window.location.hash).toBe('');
- expect(showToastMock).toHaveBeenCalledWith('error', 'Sign-out not confirmed', expect.stringContaining('may still be active'));
- await hookState.handleLogout();
- expect(attempts).toBe(2);
- expect(clearAuthMock).toHaveBeenCalledOnce();
- expect(window.location.hash).toBe('#proxy-logout');
- });
+ it.each(['401', '403', '503', 'network', 'html', 'null', 'false', 'redirect'])(
+ 'logout keeps uncertain %s visible without clearing or redirecting, and permits deliberate retry',
+ async (failure) => {
+ const { hookState } = await mountLogout();
+ sessionStorage.setItem('auth', 'saved-browser-credential');
+ const fallback = apiFetchMock.getMockImplementation()!;
+ let attempts = 0;
+ apiFetchMock.mockImplementation(async (url: string) => {
+ if (url !== '/api/logout') return fallback(url);
+ attempts++;
+ if (attempts > 1) return new Response('{"success":true}');
+ if (failure === 'network') throw new TypeError('Synthetic lost response');
+ if (/^\d+$/.test(failure)) return new Response('refused', { status: Number(failure) });
+ const bodies: Record<string, string> = {
+ html: '<html>proxy login</html>',
+ null: 'null',
+ false: '{"success":false}',
+ redirect: '',
+ };
+ return new Response(bodies[failure], { status: failure === 'redirect' ? 302 : 200 });
+ });
+ await hookState.handleLogout();
+ expect(attempts).toBe(1);
+ expect(hookState.isLoggingOut()).toBe(false);
+ expect(hookState.needsAuth()).toBe(false);
+ expect(clearAuthMock).not.toHaveBeenCalled();
+ expect(sessionStorage.getItem('auth')).toBe('saved-browser-credential');
+ expect(localStorage.getItem('just_logged_out')).toBeNull();
+ expect(window.location.hash).toBe('');
+ expect(showToastMock).toHaveBeenCalledWith(
+ 'error',
+ 'Sign-out not confirmed',
+ expect.stringContaining('may still be active'),
+ );
+ await hookState.handleLogout();
+ expect(attempts).toBe(2);
+ expect(clearAuthMock).toHaveBeenCalledOnce();
+ expect(window.location.hash).toBe('#proxy-logout');
+ },
+ );
- it('logout aborts an unanswered request after a bounded wait without claiming withdrawal', async () => {
- const { hookState } = await mountLogout();
- const fallback = apiFetchMock.getMockImplementation()!;
- apiFetchMock.mockImplementation(((url: string, options?: RequestInit) => {
- if (url !== '/api/logout') return fallback(url);
- return new Promise<Response>((_resolve, reject) => options!.signal!.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError'))));
- }) as typeof fallback);
- vi.useFakeTimers();
- const pending = hookState.handleLogout();
- await flushAsync();
- await vi.advanceTimersByTimeAsync(15_000);
- await pending;
- expect(clearAuthMock).not.toHaveBeenCalled();
- expect(hookState.isLoggingOut()).toBe(false);
- expect(window.location.hash).toBe('');
- expect(showToastMock).toHaveBeenCalledWith('error', 'Sign-out not confirmed', expect.any(String));
- });
+ it.each(['transport', 'body'])(
+ 'logout bounds an unanswered %s even when it ignores abort',
+ async (phase) => {
+ const { hookState } = await mountLogout();
+ const fallback = apiFetchMock.getMockImplementation()!;
+ apiFetchMock.mockImplementation((url: string) => {
+ if (url !== '/api/logout') return fallback(url);
+ if (phase === 'body') return Promise.resolve(new Response(new ReadableStream()));
+ return new Promise<Response>(() => {});
+ });
+ vi.useFakeTimers();
+ const pending = hookState.handleLogout();
+ await flushAsync();
+ await vi.advanceTimersByTimeAsync(15_000);
+ await pending;
+ expect(clearAuthMock).not.toHaveBeenCalled();
+ expect(hookState.isLoggingOut()).toBe(false);
+ expect(window.location.hash).toBe('');
+ expect(showToastMock).toHaveBeenCalledWith(
+ 'error',
+ 'Sign-out not confirmed',
+ expect.any(String),
+ );
+ },
+ );
it('logout cannot clear or navigate a disposed runtime after its response arrives', async () => {
const { hookState, dispose } = await mountLogout();
const fallback = apiFetchMock.getMockImplementation()!;
let finish!: (value: Response) => void;
- apiFetchMock.mockImplementation((url: string) => url === '/api/logout'
- ? new Promise<Response>((resolve) => { finish = resolve; }) : fallback(url));
+ apiFetchMock.mockImplementation((url: string) =>
+ url === '/api/logout'
+ ? new Promise<Response>((resolve) => {
+ finish = resolve;
+ })
+ : fallback(url),
+ );
const pending = hookState.handleLogout();
await waitFor(() => expect(finish).toBeDefined());
dispose();
@@ -864,19 +918,25 @@ describe('useAppRuntimeState', () => {
localStorage.setItem('docker_metadata', 'synthetic-cache');
const remove = localStorage.removeItem.bind(localStorage);
vi.spyOn(localStorage, 'removeItem').mockImplementation((key: string) => {
- if (key === 'guest_metadata') throw new DOMException('Synthetic storage refusal', 'SecurityError');
+ if (key === 'guest_metadata')
+ throw new DOMException('Synthetic storage refusal', 'SecurityError');
remove(key);
});
const fallback = apiFetchMock.getMockImplementation()!;
- apiFetchMock.mockImplementation(async (url: string) => url === '/api/logout'
- ? new Response('{"success":true}') : fallback(url));
+ apiFetchMock.mockImplementation(async (url: string) =>
+ url === '/api/logout' ? new Response('{"success":true}') : fallback(url),
+ );
await hookState.handleLogout();
expect(clearAuthMock).toHaveBeenCalledOnce();
expect(localStorage.getItem('docker_metadata')).toBeNull();
expect(hookState.needsAuth()).toBe(true);
expect(hookState.enhancedStore()).toBeNull();
expect(window.location.hash).toBe('');
- expect(showToastMock).toHaveBeenCalledWith('error', 'Browser cleanup incomplete', expect.stringContaining('proxy or identity-provider session may still be active'));
+ expect(showToastMock).toHaveBeenCalledWith(
+ 'error',
+ 'Browser cleanup incomplete',
+ expect.stringContaining('proxy or identity-provider session may still be active'),
+ );
});
it('does not start the proxy-auth runtime when protected state rejects the session', async () => {
diff --git a/frontend-modern/src/useAppRuntimeState.ts b/frontend-modern/src/useAppRuntimeState.ts
index 4332c7060e..eb76c34048 100644
--- a/frontend-modern/src/useAppRuntimeState.ts
+++ b/frontend-modern/src/useAppRuntimeState.ts
@@ -826,20 +826,33 @@ export const useAppRuntimeState = () => {
const destination = proxyAuthInfo()?.logoutURL || '/';
const controller = new AbortController();
logoutController = controller;
+ const aborted = new Promise<never>((_resolve, reject) => {
+ controller.signal.addEventListener('abort', () => reject(new Error('Sign-out aborted')), {
+ once: true,
+ });
+ });
const timeout = window.setTimeout(() => controller.abort(), 15_000);
try {
- const { apiFetch: runtimeApiFetch, clearAuth } = await import('@/utils/apiClient');
- const response = await runtimeApiFetch('/api/logout', {
- method: 'POST',
- // Keep normal credentials and CSRF, including token-only browsers.
- // The endpoint ends only the cookie session; it does not revoke tokens.
- skipOrgContext: true,
- retry: false,
- redirect: 'error',
- signal: controller.signal,
- });
- if (!response.ok || (await response.json())?.success !== true) {
+ const { apiFetch: runtimeApiFetch, clearAuth } = await Promise.race([
+ import('@/utils/apiClient'),
+ aborted,
+ ]);
+ const response = await Promise.race([
+ runtimeApiFetch('/api/logout', {
+ method: 'POST',
+ // Keep normal credentials and CSRF, including token-only browsers.
+ // The endpoint ends only the cookie session; it does not revoke tokens.
+ skipOrgContext: true,
+ // Also stops a late CSRF preparation from dispatching after abort.
+ retry: false,
+ redirect: 'error',
+ signal: controller.signal,
+ }),
+ aborted,
+ ]);
+ const acknowledgement = response.ok ? await Promise.race([response.json(), aborted]) : null;
+ if (acknowledgement?.success !== true) {
throw new Error('Pulse did not acknowledge sign-out');
}
controller.signal.throwIfAborted();
diff --git a/frontend-modern/src/utils/__tests__/apiClient.auth.test.ts b/frontend-modern/src/utils/__tests__/apiClient.auth.test.ts
index e65be823d5..d0b3bce9f8 100644
--- a/frontend-modern/src/utils/__tests__/apiClient.auth.test.ts
+++ b/frontend-modern/src/utils/__tests__/apiClient.auth.test.ts
@@ -36,19 +36,31 @@ describe('apiClient auth storage integrity', () => {
const fetchMock = vi.fn().mockResolvedValue(new Response('{}', { status: 401 }));
vi.stubGlobal('fetch', fetchMock);
try {
- const response = await apiFetch('/api/logout', { method: 'POST', retry: false, skipOrgContext: true, redirect: 'error' });
+ const response = await apiFetch('/api/logout', {
+ method: 'POST',
+ retry: false,
+ skipOrgContext: true,
+ redirect: 'error',
+ });
expect(response.status).toBe(401);
expect(fetchMock).toHaveBeenCalledOnce();
- expect(fetchMock).toHaveBeenCalledWith('/api/logout', expect.objectContaining({
- method: 'POST', credentials: 'include', redirect: 'error', headers: expect.objectContaining({
- 'X-API-Token': 'synthetic-independent-api-token', 'X-CSRF-Token': 'synthetic-csrf', 'X-Pulse-Org-ID': 'default',
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/logout',
+ expect.objectContaining({
+ method: 'POST',
+ credentials: 'include',
+ redirect: 'error',
+ headers: expect.objectContaining({
+ 'X-API-Token': 'synthetic-independent-api-token',
+ 'X-CSRF-Token': 'synthetic-csrf',
+ 'X-Pulse-Org-ID': 'default',
+ }),
}),
- }));
+ );
expect(getApiToken()).toBe('synthetic-independent-api-token');
} finally {
vi.unstubAllGlobals();
document.cookie = 'pulse_csrf=; Max-Age=0; path=/';
}
});
-
});