mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-05 10:03:22 +00:00
Confirm local sign-out before proxy navigation
End the browser session and clear saved state before the configured provider redirect; keep failed or uncertain withdrawal visible and retry deliberate. Preserve normal credential and CSRF transport, independent tokens and administrator recovery. Contract-Neutral: Repair the existing sign-out client sequence and feedback; no API, grant, provider protocol, route, storage/recovery, AI or polling contract delta. Change-source: pulse-maintainer
This commit is contained in:
+7
-4
@@ -128,14 +128,17 @@ Proxy authentication is checked on each request. If the authenticating proxy
|
||||
still supplies a valid identity, Pulse can admit that user again without a
|
||||
local password prompt.
|
||||
|
||||
- **With `PROXY_AUTH_LOGOUT_URL`:** Pulse's **Sign out** action sends the browser
|
||||
directly to that URL, instead of calling Pulse's local `/api/logout` endpoint.
|
||||
- **With `PROXY_AUTH_LOGOUT_URL`:** Pulse's **Sign out** action first calls
|
||||
Pulse's local `/api/logout` endpoint. Only after Pulse confirms success and
|
||||
clears this browser's saved authentication and cached metadata does it send
|
||||
the browser to that URL. A refused request, lost response or browser-cleanup
|
||||
error is shown instead of a redirect; it does not confirm withdrawn access.
|
||||
The destination must perform the required logout in your existing proxy/IdP
|
||||
integration; simply opening a login page or returning to Pulse does not end
|
||||
either upstream session. Some integrations have separate proxy and IdP
|
||||
sessions, so an active IdP session can sign the user straight back in.
|
||||
- **Without that URL:** Pulse uses its local logout endpoint and leaves the
|
||||
proxy/IdP sessions alone. Ending one Pulse browser session does not revoke
|
||||
- **Without that URL:** Pulse uses the same confirmed local logout and browser
|
||||
cleanup, returns to its login page and leaves the proxy/IdP sessions alone. Ending one Pulse browser session does not revoke
|
||||
other browser sessions, API tokens or the shared proxy secret.
|
||||
|
||||
Use the logout route documented for your installed authenticating proxy and its
|
||||
|
||||
@@ -3935,3 +3935,26 @@ Chat)"), not as a Pro capability, so no paid entitlement changes. Paid Patrol
|
||||
capabilities stay as they were: Patrol modes, investigations, governed fixes,
|
||||
and history live on the Patrol and Actions surfaces, and alert Investigate now
|
||||
starts a targeted Patrol run instead of opening a chat.
|
||||
|
||||
### Sign-out confirms local withdrawal before provider navigation
|
||||
|
||||
The existing app runtime sends a single bounded, cookie/CSRF-bearing POST to
|
||||
`/api/logout` before clearing saved authentication and cached metadata, stopping
|
||||
its runtime and following any configured proxy/SSO destination. It requires the
|
||||
endpoint's successful JSON acknowledgement; rejection, a redirect, malformed
|
||||
reply, lost response or timeout stays visibly uncertain and allows deliberate
|
||||
retry. The API client must not turn a logout 401 into a success-looking login
|
||||
redirect. Token-only browsers keep the normal authenticated transport; this
|
||||
ends only the cookie session, not independent API tokens or other sessions.
|
||||
Provider navigation still owns upstream sign-out. A browser cleanup failure
|
||||
remains explicit, does not skip remaining cleanup and does not redirect.
|
||||
|
||||
The actual Layout control is busy/disabled during withdrawal. Disposing its
|
||||
runtime aborts pending transport and prevents late cleanup/navigation. No new
|
||||
route, polling, grant, provider protocol, server invalidation rule or recovery
|
||||
operation is introduced. Registered runtime, API-client auth and AppLayout
|
||||
tests cover order, uncertainty, transport, duplicate attempts, retry, timeout,
|
||||
disposal and storage failure. Desktop/narrow browser proof exercises the actual
|
||||
consumer with synthetic independent sessions and inspected pixels; it is not
|
||||
live IdP or original administrator recovery. The proxy guide and shipped mirror
|
||||
must describe the same sequence without claiming upstream revocation.
|
||||
|
||||
@@ -4654,3 +4654,26 @@ usage and `Dialog.test.tsx` owns modal isolation/focus. Browser proof exercises
|
||||
the consuming TrueNAS table with ordinary keyboard/phone taps, hover parity,
|
||||
updates and dismissal, and natively inspected desktop/narrow pixels. This repairs
|
||||
composition access, not the reporter's missing native ARC or I/O/History source.
|
||||
|
||||
### Sign-out confirms local withdrawal before provider navigation
|
||||
|
||||
The existing app runtime sends a single bounded, cookie/CSRF-bearing POST to
|
||||
`/api/logout` before clearing saved authentication and cached metadata, stopping
|
||||
its runtime and following any configured proxy/SSO destination. It requires the
|
||||
endpoint's successful JSON acknowledgement; rejection, a redirect, malformed
|
||||
reply, lost response or timeout stays visibly uncertain and allows deliberate
|
||||
retry. The API client must not turn a logout 401 into a success-looking login
|
||||
redirect. Token-only browsers keep the normal authenticated transport; this
|
||||
ends only the cookie session, not independent API tokens or other sessions.
|
||||
Provider navigation still owns upstream sign-out. A browser cleanup failure
|
||||
remains explicit, does not skip remaining cleanup and does not redirect.
|
||||
|
||||
The actual Layout control is busy/disabled during withdrawal. Disposing its
|
||||
runtime aborts pending transport and prevents late cleanup/navigation. No new
|
||||
route, polling, grant, provider protocol, server invalidation rule or recovery
|
||||
operation is introduced. Registered runtime, API-client auth and AppLayout
|
||||
tests cover order, uncertainty, transport, duplicate attempts, retry, timeout,
|
||||
disposal and storage failure. Desktop/narrow browser proof exercises the actual
|
||||
consumer with synthetic independent sessions and inspected pixels; it is not
|
||||
live IdP or original administrator recovery. The proxy guide and shipped mirror
|
||||
must describe the same sequence without claiming upstream revocation.
|
||||
|
||||
@@ -128,14 +128,17 @@ Proxy authentication is checked on each request. If the authenticating proxy
|
||||
still supplies a valid identity, Pulse can admit that user again without a
|
||||
local password prompt.
|
||||
|
||||
- **With `PROXY_AUTH_LOGOUT_URL`:** Pulse's **Sign out** action sends the browser
|
||||
directly to that URL, instead of calling Pulse's local `/api/logout` endpoint.
|
||||
- **With `PROXY_AUTH_LOGOUT_URL`:** Pulse's **Sign out** action first calls
|
||||
Pulse's local `/api/logout` endpoint. Only after Pulse confirms success and
|
||||
clears this browser's saved authentication and cached metadata does it send
|
||||
the browser to that URL. A refused request, lost response or browser-cleanup
|
||||
error is shown instead of a redirect; it does not confirm withdrawn access.
|
||||
The destination must perform the required logout in your existing proxy/IdP
|
||||
integration; simply opening a login page or returning to Pulse does not end
|
||||
either upstream session. Some integrations have separate proxy and IdP
|
||||
sessions, so an active IdP session can sign the user straight back in.
|
||||
- **Without that URL:** Pulse uses its local logout endpoint and leaves the
|
||||
proxy/IdP sessions alone. Ending one Pulse browser session does not revoke
|
||||
- **Without that URL:** Pulse uses the same confirmed local logout and browser
|
||||
cleanup, returns to its login page and leaves the proxy/IdP sessions alone. Ending one Pulse browser session does not revoke
|
||||
other browser sessions, API tokens or the shared proxy secret.
|
||||
|
||||
Use the logout route documented for your installed authenticating proxy and its
|
||||
|
||||
@@ -537,6 +537,7 @@ function App() {
|
||||
needsAuth={runtime.needsAuth}
|
||||
proxyAuthInfo={runtime.proxyAuthInfo}
|
||||
handleLogout={runtime.handleLogout}
|
||||
isLoggingOut={runtime.isLoggingOut}
|
||||
state={runtime.state}
|
||||
platformVisibility={platformNavigationVisibility}
|
||||
tokenScopes={() => runtime.securityStatus()?.tokenScopes}
|
||||
|
||||
@@ -143,6 +143,7 @@ export interface AppLayoutProps {
|
||||
needsAuth: () => boolean;
|
||||
proxyAuthInfo: () => { username?: string; logoutURL?: string } | null;
|
||||
handleLogout: () => void;
|
||||
isLoggingOut?: () => boolean;
|
||||
state: () => State;
|
||||
platformVisibility?: () => PlatformNavigationVisibility;
|
||||
tokenScopes: () => string[] | undefined;
|
||||
@@ -804,9 +805,11 @@ export function AppLayout(props: AppLayoutProps) {
|
||||
<button
|
||||
type="button"
|
||||
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"
|
||||
title="Logout"
|
||||
aria-label="Logout"
|
||||
title={props.isLoggingOut?.() ? 'Signing out…' : 'Logout'}
|
||||
aria-label={props.isLoggingOut?.() ? 'Signing out…' : 'Logout'}
|
||||
>
|
||||
<svg
|
||||
class="h-4 w-4 shrink-0"
|
||||
|
||||
@@ -80,6 +80,7 @@ const renderLayout = (
|
||||
detail: 'Backend and live data stream are connected.',
|
||||
tone: 'healthy',
|
||||
}),
|
||||
loggingOut: Accessor<boolean> = () => false,
|
||||
) => {
|
||||
window.history.replaceState({}, '', initialPath);
|
||||
const RouteStateProbe = () => {
|
||||
@@ -109,6 +110,7 @@ const renderLayout = (
|
||||
needsAuth={() => false}
|
||||
proxyAuthInfo={() => null}
|
||||
handleLogout={() => {}}
|
||||
isLoggingOut={loggingOut}
|
||||
state={() =>
|
||||
({
|
||||
activeAlerts: [{ id: 'alert-1', level: 'warning', acknowledged: false }],
|
||||
@@ -651,4 +653,16 @@ describe('AppLayout Issue1650 kiosk scope containment', () => {
|
||||
});
|
||||
expect(window.location.pathname).toBe('/settings/infrastructure');
|
||||
});
|
||||
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);
|
||||
expect(screen.getByRole('button', { name: 'Logout' })).not.toBeDisabled();
|
||||
setLoggingOut(true);
|
||||
const pending = screen.getByRole('button', { name: 'Signing out…' });
|
||||
expect(pending).toBeDisabled();
|
||||
expect(pending).toHaveAttribute('aria-busy', 'true');
|
||||
setLoggingOut(false);
|
||||
expect(screen.getByRole('button', { name: 'Logout' })).not.toBeDisabled();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -193,6 +193,7 @@ describe('useAppRuntimeState', () => {
|
||||
}));
|
||||
|
||||
vi.doMock('@/utils/localStorage', () => ({
|
||||
SESSION_STORAGE_KEYS: { DEMO_AUTO_LOGIN: 'pulse_demo_auto_login' },
|
||||
STORAGE_KEYS: {
|
||||
AUTH: 'auth',
|
||||
AUTH_USER: 'pulse_auth_user',
|
||||
@@ -316,6 +317,8 @@ describe('useAppRuntimeState', () => {
|
||||
for (const dispose of mountedRoots) dispose();
|
||||
mountedRoots.clear();
|
||||
onStoreAcquired = undefined;
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
vi.clearAllMocks();
|
||||
window.localStorage.removeItem('org_id');
|
||||
window.localStorage.removeItem('just_logged_out');
|
||||
@@ -732,6 +735,150 @@ describe('useAppRuntimeState', () => {
|
||||
dispose();
|
||||
});
|
||||
|
||||
const mountLogout = async (mode: 'local' | 'proxy' | 'sso' = 'proxy') => {
|
||||
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 fallback(url);
|
||||
});
|
||||
const mounted = mountHook();
|
||||
await waitFor(() => expect(mounted.hookState.isLoading()).toBe(false));
|
||||
expect(mounted.hookState.needsAuth()).toBe(false);
|
||||
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(['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('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));
|
||||
const pending = hookState.handleLogout();
|
||||
await waitFor(() => expect(finish).toBeDefined());
|
||||
dispose();
|
||||
finish(new Response('{"success":true}'));
|
||||
await pending;
|
||||
expect(clearAuthMock).not.toHaveBeenCalled();
|
||||
expect(showToastMock).not.toHaveBeenCalled();
|
||||
expect(window.location.hash).toBe('');
|
||||
});
|
||||
|
||||
it('logout attempts remaining browser cleanup when one storage operation fails, without hiding the gap', async () => {
|
||||
const { hookState } = await mountLogout();
|
||||
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');
|
||||
remove(key);
|
||||
});
|
||||
const fallback = apiFetchMock.getMockImplementation()!;
|
||||
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'));
|
||||
});
|
||||
|
||||
it('does not start the proxy-auth runtime when protected state rejects the session', async () => {
|
||||
apiFetchMock.mockImplementation(async (url: string) => {
|
||||
if (url === '/api/state/summary') {
|
||||
|
||||
@@ -812,48 +812,87 @@ export const useAppRuntimeState = () => {
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
const [isLoggingOut, setIsLoggingOut] = createSignal(false);
|
||||
let logoutController: AbortController | undefined;
|
||||
let logoutDisposed = false;
|
||||
onCleanup(() => {
|
||||
logoutDisposed = true;
|
||||
logoutController?.abort();
|
||||
});
|
||||
|
||||
const handleLogout = async () => {
|
||||
const proxyAuth = proxyAuthInfo();
|
||||
if (proxyAuth?.logoutURL) {
|
||||
window.location.href = proxyAuth.logoutURL;
|
||||
return;
|
||||
}
|
||||
if (logoutDisposed || isLoggingOut()) return;
|
||||
setIsLoggingOut(true);
|
||||
const destination = proxyAuthInfo()?.logoutURL || '/';
|
||||
const controller = new AbortController();
|
||||
logoutController = controller;
|
||||
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) {
|
||||
logger.error('Logout failed', { status: response.status });
|
||||
if (!response.ok || (await response.json())?.success !== true) {
|
||||
throw new Error('Pulse did not acknowledge sign-out');
|
||||
}
|
||||
controller.signal.throwIfAborted();
|
||||
clearAuth();
|
||||
} catch (error) {
|
||||
logger.error('Logout error', error);
|
||||
}
|
||||
|
||||
const keysToRemove = [
|
||||
STORAGE_KEYS.AUTH,
|
||||
STORAGE_KEYS.GUEST_METADATA,
|
||||
STORAGE_KEYS.DOCKER_METADATA,
|
||||
STORAGE_KEYS.DOCKER_METADATA + '_hosts',
|
||||
];
|
||||
keysToRemove.forEach((key) => localStorage.removeItem(key));
|
||||
sessionStorage.clear();
|
||||
try {
|
||||
sessionStorage.setItem(SESSION_STORAGE_KEYS.DEMO_AUTO_LOGIN, 'suppressed');
|
||||
} catch (_err) {
|
||||
// Storage may be unavailable; the demo login page then simply signs in again.
|
||||
}
|
||||
localStorage.setItem('just_logged_out', 'true');
|
||||
aiAvailabilityStore.setEnabled(false);
|
||||
|
||||
if (wsStore()) {
|
||||
// One blocked storage operation must not prevent the remaining cleanup.
|
||||
let cleanupFailed = false;
|
||||
const clean = (operation: () => void) => {
|
||||
try {
|
||||
operation();
|
||||
} catch {
|
||||
cleanupFailed = true;
|
||||
}
|
||||
};
|
||||
for (const key of [
|
||||
STORAGE_KEYS.AUTH,
|
||||
STORAGE_KEYS.GUEST_METADATA,
|
||||
STORAGE_KEYS.DOCKER_METADATA,
|
||||
STORAGE_KEYS.DOCKER_METADATA + '_hosts',
|
||||
]) {
|
||||
clean(() => localStorage.removeItem(key));
|
||||
}
|
||||
clean(() => sessionStorage.clear());
|
||||
clean(() => sessionStorage.setItem(SESSION_STORAGE_KEYS.DEMO_AUTO_LOGIN, 'suppressed'));
|
||||
clean(() => localStorage.setItem('just_logged_out', 'true'));
|
||||
aiAvailabilityStore.setEnabled(false);
|
||||
setWsStore(null);
|
||||
}
|
||||
setNeedsAuth(true);
|
||||
|
||||
window.location.href = '/';
|
||||
if (cleanupFailed) {
|
||||
showToast(
|
||||
'error',
|
||||
'Browser cleanup incomplete',
|
||||
'Pulse ended this session, but could not clear saved browser data. Close this tab. Your proxy or identity-provider session may still be active.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Provider logout is still required for upstream sessions. Navigate only
|
||||
// after Pulse has acknowledged local withdrawal and browser cleanup.
|
||||
window.location.href = destination;
|
||||
} catch {
|
||||
if (!logoutDisposed) {
|
||||
showToast(
|
||||
'error',
|
||||
'Sign-out not confirmed',
|
||||
'Your session may still be active. Check your connection and try Sign out again.',
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
window.clearTimeout(timeout);
|
||||
logoutController = undefined;
|
||||
if (!logoutDisposed) setIsLoggingOut(false);
|
||||
}
|
||||
};
|
||||
|
||||
const enhancedStore = () => wsStore();
|
||||
@@ -884,6 +923,7 @@ export const useAppRuntimeState = () => {
|
||||
handleOrgSwitch,
|
||||
handleLogin,
|
||||
handleLogout,
|
||||
isLoggingOut,
|
||||
enhancedStore,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -28,4 +28,27 @@ describe('apiClient auth storage integrity', () => {
|
||||
expect(window.sessionStorage.getItem('pulse_api_token')).toBe('legacy-token');
|
||||
expect(window.sessionStorage.getItem('pulse_auth')).toBeNull();
|
||||
});
|
||||
it('returns a rejected logout without clearing the credential or disguising it as a login redirect', async () => {
|
||||
const { apiFetch, getApiToken, setApiToken, setOrgID } = await import('@/utils/apiClient');
|
||||
setApiToken('synthetic-independent-api-token');
|
||||
setOrgID('synthetic-org');
|
||||
document.cookie = 'pulse_csrf=synthetic-csrf; path=/';
|
||||
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' });
|
||||
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(getApiToken()).toBe('synthetic-independent-api-token');
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
document.cookie = 'pulse_csrf=; Max-Age=0; path=/';
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -732,7 +732,9 @@ class ApiClient {
|
||||
'/api/charts/infrastructure',
|
||||
];
|
||||
const shouldSkipRedirect = skipRedirectUrls.some((path) => url.includes(path));
|
||||
if (response.status === 401 && !skipAuth && !shouldSkipRedirect) {
|
||||
// Sign-out owns its result: a rejected or lost withdrawal must remain
|
||||
// visible, not become a login redirect that looks like successful logout.
|
||||
if (response.status === 401 && !skipAuth && !shouldSkipRedirect && url !== '/api/logout') {
|
||||
logger.warn('Authentication expired - redirecting to login');
|
||||
// Clear auth and redirect to login
|
||||
if (typeof window !== 'undefined') {
|
||||
|
||||
@@ -127,7 +127,9 @@ class AuthenticationDiagnosticDocsTest(unittest.TestCase):
|
||||
guide = " ".join(source.split("### Sign out and session boundaries\n", 1)[1]
|
||||
.split("### Verify Headers", 1)[0].split())
|
||||
for boundary in (
|
||||
"instead of calling Pulse's local `/api/logout` endpoint",
|
||||
"first calls Pulse's local `/api/logout` endpoint",
|
||||
"Only after Pulse confirms success",
|
||||
"error is shown instead of a redirect",
|
||||
"leaves the proxy/IdP sessions alone",
|
||||
"other browser sessions, API tokens or the shared proxy secret",
|
||||
"active IdP session can sign the user straight back in",
|
||||
|
||||
Reference in New Issue
Block a user