mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-28 04:46:28 -08:00
fix: prevent metadata failures from signing users out (#2053)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description <!-- Please include a summary of the change. Please also include relevant motivation and context. List any dependencies that are required for this change. --> Fixes # #### Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ### Checklist: - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings ### AI disclosure: - [ ] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [ ] Fully AI generated (explain what all the generated code does in moderate detail). <!-- Write any explanation required here, but do not generate the explanation using AI!! You must prove you understand what the code in this PR does. -->
This commit is contained in:
7 files changed
+232
-38
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix unexpected sign-outs and preserve saved accounts when signing in again.
|
||||
@@ -0,0 +1,59 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { beforeEach, expect, it, vi } from 'vitest';
|
||||
import { createClient, HttpApiEvent, MatrixError } from '$types/matrix-sdk';
|
||||
import { MATRIX_SESSIONS_KEY } from '$state/sessions';
|
||||
import { stopClient } from '$client/initMatrix';
|
||||
import { useSessionLogout } from './useSessionLogout';
|
||||
|
||||
vi.mock('$client/initMatrix', () => ({ stopClient: vi.fn<() => void>() }));
|
||||
vi.mock('@sentry/react', () => ({
|
||||
addBreadcrumb: vi.fn<() => void>(),
|
||||
metrics: { count: vi.fn<() => void>() },
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
'preserves all accounts and stores on logout with soft_logout=%s',
|
||||
(softLogout) => {
|
||||
const mx = createClient({ baseUrl: 'https://hs.example' });
|
||||
const clearStores = vi.spyOn(mx, 'clearStores');
|
||||
const accounts = JSON.stringify([
|
||||
{ userId: '@alice:hs.example' },
|
||||
{ userId: '@bob:hs.example' },
|
||||
]);
|
||||
localStorage.setItem(MATRIX_SESSIONS_KEY, accounts);
|
||||
localStorage.setItem('settings', 'saved-settings');
|
||||
const { result, unmount } = renderHook(() => useSessionLogout(mx));
|
||||
expect(result.current).toBe(false);
|
||||
const error = new MatrixError({ errcode: 'M_UNKNOWN_TOKEN', soft_logout: softLogout }, 401);
|
||||
act(() => {
|
||||
mx.emit(HttpApiEvent.SessionLoggedOut, error);
|
||||
mx.emit(HttpApiEvent.SessionLoggedOut, error);
|
||||
});
|
||||
expect(result.current).toBe(true);
|
||||
expect(stopClient).toHaveBeenCalledExactlyOnceWith(mx);
|
||||
expect(clearStores).not.toHaveBeenCalled();
|
||||
expect(localStorage.getItem(MATRIX_SESSIONS_KEY)).toBe(accounts);
|
||||
expect(localStorage.getItem('settings')).toBe('saved-settings');
|
||||
unmount();
|
||||
expect(stopClient).toHaveBeenCalledTimes(1);
|
||||
expect(mx.listenerCount(HttpApiEvent.SessionLoggedOut)).toBe(0);
|
||||
}
|
||||
);
|
||||
|
||||
it('does not carry the expired state to another client', () => {
|
||||
const first = createClient({ baseUrl: 'https://hs.example' });
|
||||
const second = createClient({ baseUrl: 'https://hs.example' });
|
||||
const { result, rerender } = renderHook(({ mx }) => useSessionLogout(mx), {
|
||||
initialProps: { mx: first },
|
||||
});
|
||||
act(() =>
|
||||
first.emit(HttpApiEvent.SessionLoggedOut, new MatrixError({ errcode: 'M_UNKNOWN_TOKEN' }, 401))
|
||||
);
|
||||
rerender({ mx: second });
|
||||
expect(result.current).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { HttpApiEvent, type MatrixClient } from '$types/matrix-sdk';
|
||||
import { stopClient } from '$client/initMatrix';
|
||||
import { useMatrixEvent } from './useMatrixEvent';
|
||||
|
||||
export const useSessionLogout = (mx?: MatrixClient): boolean => {
|
||||
const [expiredClient, setExpiredClient] = useState<MatrixClient>();
|
||||
const handledClient = useRef<MatrixClient | undefined>(undefined);
|
||||
const handleLogout = useCallback(() => {
|
||||
if (!mx || handledClient.current === mx) return;
|
||||
handledClient.current = mx;
|
||||
Sentry.addBreadcrumb({
|
||||
category: 'auth',
|
||||
message: 'Session requires reauthentication',
|
||||
level: 'warning',
|
||||
});
|
||||
Sentry.metrics.count('sable.auth.forced_logout', 1);
|
||||
stopClient(mx);
|
||||
setExpiredClient(mx);
|
||||
}, [mx]);
|
||||
|
||||
useMatrixEvent(mx, HttpApiEvent.SessionLoggedOut, handleLogout);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (mx && handledClient.current !== mx) stopClient(mx);
|
||||
},
|
||||
[mx]
|
||||
);
|
||||
return mx !== undefined && expiredClient === mx;
|
||||
};
|
||||
@@ -2,12 +2,11 @@ import type { RectCords } from 'folds';
|
||||
import { Box, Button, config, Dialog, IconButton, Menu, MenuItem, Spinner, Text } from 'folds';
|
||||
import { PopOut } from '$components/overlay-stack';
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import { HttpApiEvent } from '$types/matrix-sdk';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import type { MouseEventHandler, ReactNode } from 'react';
|
||||
import { useRef, useCallback, useEffect, useLayoutEffect, useState } from 'react';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { matchPath, useLocation, useNavigate } from 'react-router';
|
||||
import { Link, matchPath, useLocation, useNavigate } from 'react-router';
|
||||
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
|
||||
import {
|
||||
clearCacheAndReload,
|
||||
@@ -29,13 +28,12 @@ import { MatrixClientProvider } from '$hooks/useMatrixClient';
|
||||
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import { useSyncState } from '$hooks/useSyncState';
|
||||
import { useCrossSigningResetDetect } from '$hooks/useCrossSigningResetDetect';
|
||||
import { useMatrixEvent } from '$hooks/useMatrixEvent';
|
||||
import { useSessionLogout } from '$hooks/useSessionLogout';
|
||||
import { stopPropagation } from '$utils/keyboard';
|
||||
import { AuthMetadataProvider, getSessionAuthMetadata } from '$hooks/useAuthMetadata';
|
||||
import {
|
||||
sessionsAtom,
|
||||
activeSessionIdAtom,
|
||||
getSessionStoreName,
|
||||
type Session,
|
||||
type SessionsAction,
|
||||
} from '$state/sessions';
|
||||
@@ -47,7 +45,7 @@ import { useLoopbackMediaRecovery } from '$hooks/useLoopbackMediaRecovery';
|
||||
import { useSyncOrchestrator } from '$hooks/useSyncOrchestrator';
|
||||
import { usePushDiagnosticsReport } from '$hooks/usePushDiagnosticsReport';
|
||||
import { composerIcon, DotsThreeOutlineVerticalIcon } from '$components/icons/phosphor';
|
||||
import { getHomePath } from '$pages/pathUtils';
|
||||
import { getHomePath, getLoginPath, withSearchParam } from '$pages/pathUtils';
|
||||
import { DIRECT_ROOM_PATH, HOME_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths';
|
||||
import { getCanonicalAliasRoomId, isRoomAlias, isRoomId } from '$utils/matrix';
|
||||
import { pushPersistedSessionToSW, pushSessionToSW } from '../../../sw-session';
|
||||
@@ -225,25 +223,6 @@ function ClientRootOptions({ mx, onLogout }: ClientRootOptionsProps) {
|
||||
);
|
||||
}
|
||||
|
||||
const useLogoutListener = (mx?: MatrixClient, session?: Session) => {
|
||||
const handleLogout = useCallback(async () => {
|
||||
Sentry.addBreadcrumb({
|
||||
category: 'auth',
|
||||
message: 'Session forcibly logged out by server',
|
||||
level: 'warning',
|
||||
});
|
||||
Sentry.metrics.count('sable.auth.forced_logout', 1);
|
||||
if (mx) stopClient(mx);
|
||||
await mx?.clearStores(
|
||||
session ? { cryptoDatabasePrefix: getSessionStoreName(session).rustCryptoPrefix } : undefined
|
||||
);
|
||||
window.localStorage.clear();
|
||||
window.location.reload();
|
||||
}, [mx, session]);
|
||||
|
||||
useMatrixEvent(mx, HttpApiEvent.SessionLoggedOut, handleLogout);
|
||||
};
|
||||
|
||||
type ClientRootProps = {
|
||||
children: ReactNode;
|
||||
};
|
||||
@@ -289,7 +268,9 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
}, [activeSession, activeSessionId, setActiveSessionId])
|
||||
);
|
||||
|
||||
const mx = loadState.status === AsyncStatus.Success ? loadState.data : undefined;
|
||||
const loadedClient = loadState.status === AsyncStatus.Success ? loadState.data : undefined;
|
||||
const sessionExpired = useSessionLogout(loadedClient);
|
||||
const mx = sessionExpired ? undefined : loadedClient;
|
||||
|
||||
const legacyCryptoError =
|
||||
loadState.status === AsyncStatus.Error && isLegacyWasmCryptoStoreError(loadState.error)
|
||||
@@ -371,7 +352,6 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
);
|
||||
|
||||
useSyncNicknames(mx);
|
||||
useLogoutListener(mx, activeSession);
|
||||
useAppVisibility(mx);
|
||||
useNetworkRecovery(mx);
|
||||
useSyncOrchestrator(startState.status === AsyncStatus.Success ? mx : undefined);
|
||||
@@ -379,16 +359,6 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
useLoopbackMediaRecovery();
|
||||
useCrossSigningResetDetect(mx);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (mx) {
|
||||
log.log('ClientRoot unmounting — stopping client', mx.getUserId());
|
||||
stopClient(mx);
|
||||
}
|
||||
},
|
||||
[mx]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (loadState.status === AsyncStatus.Idle) {
|
||||
loadMatrix();
|
||||
@@ -488,6 +458,37 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
}
|
||||
}, [startState]);
|
||||
|
||||
if (sessionExpired && activeSession) {
|
||||
return (
|
||||
<SplashScreen>
|
||||
<Box direction="Column" grow="Yes" alignItems="Center" justifyContent="Center" gap="400">
|
||||
<Text>Sign in again as {activeSession.userId}.</Text>
|
||||
<Button
|
||||
as={Link}
|
||||
reloadDocument
|
||||
to={withSearchParam(getLoginPath(activeSession.baseUrl), {
|
||||
addAccount: '1',
|
||||
username: activeSession.userId,
|
||||
})}
|
||||
>
|
||||
<Text as="span" size="B400">
|
||||
Sign in again
|
||||
</Text>
|
||||
</Button>
|
||||
{sessions
|
||||
.filter((session) => session.userId !== activeSession.userId)
|
||||
.map((session) => (
|
||||
<Button key={session.userId} onClick={() => setActiveSessionId(session.userId)}>
|
||||
<Text as="span" size="B400">
|
||||
Switch to {session.userId}
|
||||
</Text>
|
||||
</Button>
|
||||
))}
|
||||
</Box>
|
||||
</SplashScreen>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AutoDiscovery userId={userId ?? ''} baseUrl={baseUrl ?? ''}>
|
||||
{mx && <SyncStatus mx={mx} />}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { expect, it, vi } from 'vitest';
|
||||
import {
|
||||
createClient,
|
||||
HttpApiEvent,
|
||||
MatrixError,
|
||||
Method,
|
||||
TokenRefreshError,
|
||||
TokenRefreshLogoutError,
|
||||
} from '$types/matrix-sdk';
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import { MATRIX_SESSIONS_KEY, type Session } from '$state/sessions';
|
||||
import { createSessionTokenRefresher } from './oidcTokenRefresher';
|
||||
|
||||
vi.mock('../sw-session', () => ({
|
||||
pushSessionToSW: vi.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
it.each([401, 429, 503])(
|
||||
'does not log out when authentication metadata returns %s',
|
||||
async (status) => {
|
||||
const session: Session = {
|
||||
baseUrl: 'https://hs.example',
|
||||
userId: '@alice:hs.example',
|
||||
deviceId: 'DEVICE',
|
||||
accessToken: 'expired-access',
|
||||
refreshToken: 'valid-refresh',
|
||||
oidc: { issuer: 'https://issuer.example', clientId: 'client' },
|
||||
};
|
||||
localStorage.setItem(MATRIX_SESSIONS_KEY, JSON.stringify([session]));
|
||||
const metadataClient = {
|
||||
getAuthMetadata: vi
|
||||
.fn<MatrixClient['getAuthMetadata']>()
|
||||
.mockRejectedValue(new MatrixError({ errcode: 'M_UNKNOWN', error: 'unavailable' }, status)),
|
||||
} as unknown as MatrixClient;
|
||||
const refresher = createSessionTokenRefresher(session, metadataClient)!;
|
||||
const mx = createClient({
|
||||
baseUrl: session.baseUrl,
|
||||
userId: session.userId,
|
||||
deviceId: session.deviceId,
|
||||
accessToken: session.accessToken,
|
||||
refreshToken: session.refreshToken,
|
||||
tokenRefreshFunction: refresher.tokenRefreshFunction,
|
||||
fetchFn: vi.fn<typeof fetch>().mockImplementation(
|
||||
async () =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
errcode: 'M_UNKNOWN_TOKEN',
|
||||
error: 'expired',
|
||||
soft_logout: true,
|
||||
}),
|
||||
{ status: 401, headers: { 'Content-Type': 'application/json' } }
|
||||
)
|
||||
),
|
||||
});
|
||||
const logout = vi.fn<() => void>();
|
||||
mx.on(HttpApiEvent.SessionLoggedOut, logout);
|
||||
await expect(mx.http.authedRequest(Method.Get, '/account/whoami')).rejects.toBeInstanceOf(
|
||||
TokenRefreshError
|
||||
);
|
||||
expect(logout).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('still requests reauthentication when the refresh token is rejected', async () => {
|
||||
const mx = createClient({
|
||||
baseUrl: 'https://hs.example',
|
||||
accessToken: 'expired-access',
|
||||
refreshToken: 'revoked-refresh',
|
||||
tokenRefreshFunction: async () => {
|
||||
throw new TokenRefreshLogoutError(new Error('invalid_grant'));
|
||||
},
|
||||
fetchFn: async () =>
|
||||
new Response(JSON.stringify({ errcode: 'M_UNKNOWN_TOKEN' }), {
|
||||
status: 401,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
});
|
||||
const logout = vi.fn<() => void>();
|
||||
mx.on(HttpApiEvent.SessionLoggedOut, logout);
|
||||
await expect(mx.http.authedRequest(Method.Get, '/account/whoami')).rejects.toBeInstanceOf(
|
||||
MatrixError
|
||||
);
|
||||
expect(logout).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
@@ -102,6 +102,19 @@ describe('createSessionTokenRefresher', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('retries metadata discovery after a temporary failure', async () => {
|
||||
getAuthMetadata.mockRejectedValueOnce(new Error('unavailable'));
|
||||
mocks.refresh.mockResolvedValue({ accessToken: 'new-access', refreshToken: 'new-refresh' });
|
||||
const refresher = createSessionTokenRefresher(session, mx)!;
|
||||
await expect(refresher.tokenRefreshFunction('old-refresh')).rejects.toThrow(
|
||||
'Unable to load authentication metadata'
|
||||
);
|
||||
await expect(refresher.tokenRefreshFunction('old-refresh')).resolves.toMatchObject({
|
||||
accessToken: 'new-access',
|
||||
});
|
||||
expect(getAuthMetadata).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('uses the current stored token after waiting for the cross-tab refresh lock', async () => {
|
||||
const request = vi.fn<(name: string, callback: () => Promise<unknown>) => Promise<unknown>>(
|
||||
async (_name, callback) => {
|
||||
@@ -127,5 +140,6 @@ describe('createSessionTokenRefresher', () => {
|
||||
});
|
||||
expect(request).toHaveBeenCalledWith('sable-oidc-refresh', expect.any(Function));
|
||||
expect(mocks.refresh).not.toHaveBeenCalled();
|
||||
expect(getAuthMetadata).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -95,7 +95,7 @@ export const createSessionTokenRefresher = (
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
tokenRefresherPromise = undefined;
|
||||
throw error;
|
||||
throw new Error('Unable to load authentication metadata', { cause: error });
|
||||
});
|
||||
}
|
||||
return tokenRefresherPromise;
|
||||
@@ -104,7 +104,6 @@ export const createSessionTokenRefresher = (
|
||||
return {
|
||||
tokenRefreshFunction: async (refreshToken) => {
|
||||
const refresh = withRefreshQueue(session.userId, async () => {
|
||||
const tokenRefresher = await getTokenRefresher();
|
||||
const refreshWithCurrentState = async () => {
|
||||
// Another tab may have rotated the token; reusing a consumed one revokes the session.
|
||||
const storedSession = getStoredSession(session.userId);
|
||||
@@ -118,6 +117,7 @@ export const createSessionTokenRefresher = (
|
||||
refreshToken: latestRefreshToken,
|
||||
};
|
||||
}
|
||||
const tokenRefresher = await getTokenRefresher();
|
||||
const tokens = await tokenRefresher.tokenRefreshFunction(latestRefreshToken);
|
||||
return {
|
||||
...tokens,
|
||||
|
||||
Reference in new issue
Block a user