mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 00:51:17 -08:00
fix(crypto): stop device verification from silently reverting (#2115)
<!-- 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: - [x] Created without the usage of AI - [ ] 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. You MUST explain what modifications you have made in order to ensure that the result is compatible with THE LICENSE By deleting this section or comment, in code or in body, the PR should be rejected and closed. -->
This commit is contained in:
12 files changed
+388
-17
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix devices repeatedly reverting to unverified.
|
||||
@@ -12,7 +12,9 @@ export default {
|
||||
'src-tauri/ios-project.yml',
|
||||
// Copied verbatim from the Firebase console; formatting it would drift.
|
||||
'src-tauri/gen/android/app/google-services.json',
|
||||
// knope rewrites these on every release; reformatting them breaks the next fmt:check.
|
||||
'package.json',
|
||||
'src-tauri/tauri.conf.json',
|
||||
'pnpm-lock.yaml',
|
||||
'LICENSE',
|
||||
'README.md',
|
||||
|
||||
@@ -23,6 +23,25 @@
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:136631010081:android:4cfbdacbecff60c00b7460",
|
||||
"android_client_info": {
|
||||
"package_name": "moe.sable.client.nightly"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyC-0JTo2XFXGqKda6iaUyUGoCI-NIqhMFA"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
|
||||
@@ -7,6 +7,9 @@ import type { SecretStorageKeyContent } from '$types/matrix/accountData';
|
||||
import { BackupRestoreTile } from './BackupRestore';
|
||||
|
||||
const decodeRecoveryKey = vi.hoisted(() => vi.fn<(key: string) => Uint8Array>());
|
||||
const appFetch = vi.hoisted(() => vi.fn<() => Promise<unknown>>());
|
||||
|
||||
vi.mock('$utils/fetch', () => ({ fetch: appFetch }));
|
||||
const emitter = new TypedEventEmitter<string, Record<string, (...args: never[]) => void>>();
|
||||
const mockClient = Object.assign(emitter, {
|
||||
secretStorage: {
|
||||
@@ -15,6 +18,8 @@ const mockClient = Object.assign(emitter, {
|
||||
},
|
||||
getSafeUserId: () => '@me:example.org',
|
||||
getDeviceId: () => 'DEVICE',
|
||||
baseUrl: 'https://example.org',
|
||||
getAccessToken: () => 'access-token',
|
||||
});
|
||||
|
||||
vi.mock('$hooks/useMatrixClient', () => ({
|
||||
@@ -61,6 +66,17 @@ const createCrypto = ({ backupInfo = BACKUP_INFO, backupKey = null }: CryptoOver
|
||||
loadSessionBackupPrivateKeyFromSecretStorage: vi
|
||||
.fn<CryptoApi['loadSessionBackupPrivateKeyFromSecretStorage']>()
|
||||
.mockResolvedValue(undefined),
|
||||
getDeviceVerificationStatus: vi
|
||||
.fn<CryptoApi['getDeviceVerificationStatus']>()
|
||||
.mockResolvedValue({ crossSigningVerified: true } as Awaited<
|
||||
ReturnType<CryptoApi['getDeviceVerificationStatus']>
|
||||
>),
|
||||
getOwnDeviceKeys: vi
|
||||
.fn<CryptoApi['getOwnDeviceKeys']>()
|
||||
.mockResolvedValue({ ed25519: 'own-ed25519', curve25519: 'own-curve25519' }),
|
||||
getCrossSigningKeyId: vi
|
||||
.fn<CryptoApi['getCrossSigningKeyId']>()
|
||||
.mockResolvedValue('own-master'),
|
||||
}) as unknown as CryptoBackend;
|
||||
|
||||
const recoveryPrompt = () => screen.queryByText(/does not hold the backup decryption key/i);
|
||||
@@ -77,6 +93,14 @@ describe('BackupRestoreTile', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
decodeRecoveryKey.mockReturnValue(new Uint8Array([1, 2, 3]));
|
||||
appFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
device_keys: {
|
||||
'@me:example.org': { DEVICE: { keys: { 'ed25519:DEVICE': 'own-ed25519' } } },
|
||||
},
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it('offers recovery when a backup exists but its key is not in the crypto store', async () => {
|
||||
|
||||
@@ -13,6 +13,14 @@ const processDeviceLists = vi.hoisted(() => vi.fn<() => Promise<void>>());
|
||||
const bootstrapCrossSigning = vi.hoisted(() => vi.fn<() => Promise<void>>());
|
||||
const bootstrapSecretStorage = vi.hoisted(() => vi.fn<() => Promise<void>>());
|
||||
const loadSessionBackupPrivateKeyFromSecretStorage = vi.hoisted(() => vi.fn<() => Promise<void>>());
|
||||
const getDeviceVerificationStatus = vi.hoisted(() =>
|
||||
vi.fn<() => Promise<{ crossSigningVerified: boolean } | null>>()
|
||||
);
|
||||
const getOwnDeviceKeys = vi.hoisted(() => vi.fn<() => Promise<{ ed25519: string }>>());
|
||||
const getCrossSigningKeyId = vi.hoisted(() => vi.fn<() => Promise<string | null>>());
|
||||
const appFetch = vi.hoisted(() => vi.fn<() => Promise<unknown>>());
|
||||
|
||||
vi.mock('$utils/fetch', () => ({ fetch: appFetch }));
|
||||
|
||||
vi.mock('$types/matrix-sdk', () => ({ decodeRecoveryKey }));
|
||||
vi.mock('$client/secretStorageKeys', () => ({ storePrivateKey }));
|
||||
@@ -20,6 +28,8 @@ vi.mock('$hooks/useMatrixClient', () => ({
|
||||
useMatrixClient: () => ({
|
||||
getSafeUserId: () => '@me:example.org',
|
||||
getDeviceId: () => 'DEVICE',
|
||||
baseUrl: 'https://example.org',
|
||||
getAccessToken: () => 'access-token',
|
||||
secretStorage: { checkKey, get: getSecret },
|
||||
getCrypto: () =>
|
||||
({
|
||||
@@ -27,10 +37,21 @@ vi.mock('$hooks/useMatrixClient', () => ({
|
||||
bootstrapCrossSigning,
|
||||
bootstrapSecretStorage,
|
||||
loadSessionBackupPrivateKeyFromSecretStorage,
|
||||
getDeviceVerificationStatus,
|
||||
getOwnDeviceKeys,
|
||||
getCrossSigningKeyId,
|
||||
}) as unknown as CryptoApi,
|
||||
}),
|
||||
}));
|
||||
|
||||
const publishedKeysResponse = (ed25519: string, masterKey = 'own-master') => ({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
device_keys: { '@me:example.org': { DEVICE: { keys: { 'ed25519:DEVICE': ed25519 } } } },
|
||||
master_keys: { '@me:example.org': { keys: { [`ed25519:${masterKey}`]: masterKey } } },
|
||||
}),
|
||||
});
|
||||
|
||||
const KEY_ID = 'key-id';
|
||||
const KEY_CONTENT = { algorithm: 'm.secret_storage.v1.aes-hmac-sha2' } as SecretStorageKeyContent;
|
||||
const recoveryKey = new Uint8Array([1, 2, 3]);
|
||||
@@ -60,6 +81,10 @@ describe('ManualVerificationTile', () => {
|
||||
bootstrapCrossSigning.mockResolvedValue(undefined);
|
||||
bootstrapSecretStorage.mockResolvedValue(undefined);
|
||||
loadSessionBackupPrivateKeyFromSecretStorage.mockResolvedValue(undefined);
|
||||
getDeviceVerificationStatus.mockResolvedValue({ crossSigningVerified: true });
|
||||
getOwnDeviceKeys.mockResolvedValue({ ed25519: 'own-ed25519' });
|
||||
getCrossSigningKeyId.mockResolvedValue('own-master');
|
||||
appFetch.mockResolvedValue(publishedKeysResponse('own-ed25519'));
|
||||
});
|
||||
|
||||
it('refreshes cross-signing public keys before importing the recovery key', async () => {
|
||||
@@ -87,6 +112,44 @@ describe('ManualVerificationTile', () => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['device-verification'] });
|
||||
});
|
||||
|
||||
it('reports failure when the device is still not cross-signed after bootstrapping', async () => {
|
||||
getDeviceVerificationStatus.mockResolvedValue({ crossSigningVerified: false });
|
||||
renderTile(new QueryClient());
|
||||
|
||||
submitRecoveryKey('valid-key');
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByText(/could not be signed by your cross-signing identity/)
|
||||
).toBeInTheDocument()
|
||||
);
|
||||
expect(screen.queryByText('Device verified!')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('reports failure when the server publishes different keys for this device', async () => {
|
||||
appFetch.mockResolvedValue(publishedKeysResponse('stale-ed25519'));
|
||||
renderTile(new QueryClient());
|
||||
|
||||
submitRecoveryKey('valid-key');
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText(/no longer matches the encryption keys/)).toBeInTheDocument()
|
||||
);
|
||||
expect(screen.queryByText('Device verified!')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('reports failure when the recovery key unlocks a superseded identity', async () => {
|
||||
appFetch.mockResolvedValue(publishedKeysResponse('own-ed25519', 'rotated-master'));
|
||||
renderTile(new QueryClient());
|
||||
|
||||
submitRecoveryKey('valid-key');
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText(/previous verification identity/)).toBeInTheDocument()
|
||||
);
|
||||
expect(screen.queryByText('Device verified!')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not bootstrap when the cross-signing keys are missing from secret storage', async () => {
|
||||
getSecret.mockResolvedValue(undefined);
|
||||
renderTile(new QueryClient());
|
||||
|
||||
@@ -55,6 +55,10 @@ const debugLog = createDebugLogger('BackgroundNotifications');
|
||||
|
||||
const BACKGROUND_STAGGER_DELAY_MS = 5_000;
|
||||
|
||||
// These sync the account's own device without crypto, so they ack and discard its to-device
|
||||
// traffic. Giving them a second store for the same deviceId strands the device instead.
|
||||
const BACKGROUND_SYNC_CLIENTS_ENABLED = false;
|
||||
|
||||
let desktopNotificationSeq = 1;
|
||||
const nextDesktopNotificationId = (): number => {
|
||||
const id = desktopNotificationSeq;
|
||||
@@ -180,7 +184,7 @@ export function BackgroundNotifications() {
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldRunBackgroundNotifications) {
|
||||
if (!shouldRunBackgroundNotifications || !BACKGROUND_SYNC_CLIENTS_ENABLED) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
clearLoginData,
|
||||
discardSessionStores,
|
||||
initClient,
|
||||
isStrandedCryptoStoreError,
|
||||
logoutClient,
|
||||
startClient,
|
||||
} from '$client/initMatrix';
|
||||
@@ -403,7 +404,12 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
);
|
||||
|
||||
const isError = loadState.status === AsyncStatus.Error || startState.status === AsyncStatus.Error;
|
||||
const nativeCryptoRecoveryRequired = nativeCryptoError !== undefined;
|
||||
const strandedCryptoStore =
|
||||
loadState.status === AsyncStatus.Error && isStrandedCryptoStoreError(loadState.error)
|
||||
? loadState.error
|
||||
: undefined;
|
||||
const cryptoRecoveryRequired =
|
||||
nativeCryptoError !== undefined || strandedCryptoStore !== undefined;
|
||||
|
||||
// Set matrix client context: homeserver and sync type (not PII)
|
||||
useEffect(() => {
|
||||
@@ -444,7 +450,11 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
// Capture fatal client failures — useAsyncCallback swallows these into state so
|
||||
// they never reach the React ErrorBoundary; explicit capture is required.
|
||||
useEffect(() => {
|
||||
if (loadState.status === AsyncStatus.Error && !isNativeCryptoStoreError(loadState.error)) {
|
||||
if (
|
||||
loadState.status === AsyncStatus.Error &&
|
||||
!isNativeCryptoStoreError(loadState.error) &&
|
||||
!isStrandedCryptoStoreError(loadState.error)
|
||||
) {
|
||||
Sentry.captureException(loadState.error, { tags: { phase: 'load' } });
|
||||
}
|
||||
}, [loadState]);
|
||||
@@ -496,14 +506,20 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
<Dialog>
|
||||
<Box direction="Column" gap="400" style={{ padding: config.space.S400 }}>
|
||||
{loadState.status === AsyncStatus.Error &&
|
||||
(nativeCryptoRecoveryRequired ? (
|
||||
(cryptoRecoveryRequired ? (
|
||||
<>
|
||||
<Text>Sign in again to continue using encrypted chats.</Text>
|
||||
<Text>
|
||||
Export your message keys first, or restore them from backup after signing
|
||||
in.
|
||||
{strandedCryptoStore?.message ??
|
||||
'Sign in again to continue using encrypted chats.'}
|
||||
</Text>
|
||||
<LegacyKeyExport exporter={nativeCryptoError.exportRoomKeys} />
|
||||
<Text>
|
||||
{nativeCryptoError
|
||||
? 'Export your message keys first, or restore them from backup after signing in.'
|
||||
: 'Restore your messages from key backup after signing in.'}
|
||||
</Text>
|
||||
{nativeCryptoError && (
|
||||
<LegacyKeyExport exporter={nativeCryptoError.exportRoomKeys} />
|
||||
)}
|
||||
<AsyncError state={recoveryState} prefix="Failed to sign out" size="T300" />
|
||||
<Button
|
||||
variant="Critical"
|
||||
@@ -521,7 +537,7 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
{startState.status === AsyncStatus.Error && (
|
||||
<Text>{`Failed to start. ${errorMessage(startState.error)}`}</Text>
|
||||
)}
|
||||
{!nativeCryptoRecoveryRequired && (
|
||||
{!cryptoRecoveryRequired && (
|
||||
<Button variant="Critical" onClick={mx ? () => startMatrix(mx) : loadMatrix}>
|
||||
<Text as="span" size="B400">
|
||||
Retry
|
||||
|
||||
@@ -147,6 +147,13 @@ export type SessionsAction =
|
||||
session: Session;
|
||||
};
|
||||
|
||||
// A PUT carries a session rebuilt from a login response, and `fallbackSdkStores` picks the
|
||||
// IndexedDB stores, so losing it on the same device points at an empty crypto store.
|
||||
const preserveStoreLocation = (existing: Session, next: Session): Session =>
|
||||
existing.fallbackSdkStores && existing.deviceId === next.deviceId
|
||||
? { ...next, fallbackSdkStores: true }
|
||||
: next;
|
||||
|
||||
export const sessionsAtom = atom<Sessions, [SessionsAction], void>(
|
||||
(get) => get(baseSessionsAtom),
|
||||
(get, set, action) => {
|
||||
@@ -160,7 +167,11 @@ export const sessionsAtom = atom<Sessions, [SessionsAction], void>(
|
||||
sessions.push(action.session);
|
||||
} else {
|
||||
log.log('PUT update session', action.session.userId);
|
||||
sessions.splice(sessionIndex, 1, action.session);
|
||||
sessions.splice(
|
||||
sessionIndex,
|
||||
1,
|
||||
preserveStoreLocation(sessions[sessionIndex]!, action.session)
|
||||
);
|
||||
}
|
||||
set(baseSessionsAtom, sessions);
|
||||
return;
|
||||
|
||||
@@ -83,3 +83,62 @@ describe("sessionsAtom 'UPDATE' action", () => {
|
||||
expect(session?.slidingSyncOptIn).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sessionsAtom 'PUT' action", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('keeps the fallback store flag when the same device signs in again', () => {
|
||||
const store = createStore();
|
||||
store.set(sessionsAtom, {
|
||||
type: 'PUT',
|
||||
session: { ...baseSession, fallbackSdkStores: true },
|
||||
});
|
||||
|
||||
store.set(sessionsAtom, {
|
||||
type: 'PUT',
|
||||
session: { ...baseSession, accessToken: 'fresh-access' },
|
||||
});
|
||||
|
||||
const [alice] = store.get(sessionsAtom);
|
||||
expect(alice!.fallbackSdkStores).toBe(true);
|
||||
expect(alice!.accessToken).toBe('fresh-access');
|
||||
});
|
||||
|
||||
it('drops the fallback store flag when the session moves to a new device', () => {
|
||||
const store = createStore();
|
||||
store.set(sessionsAtom, {
|
||||
type: 'PUT',
|
||||
session: { ...baseSession, fallbackSdkStores: true },
|
||||
});
|
||||
|
||||
store.set(sessionsAtom, {
|
||||
type: 'PUT',
|
||||
session: { ...baseSession, deviceId: 'DEV2', accessToken: 'fresh-access' },
|
||||
});
|
||||
|
||||
const [alice] = store.get(sessionsAtom);
|
||||
expect(alice!.fallbackSdkStores).toBeUndefined();
|
||||
expect(alice!.deviceId).toBe('DEV2');
|
||||
});
|
||||
|
||||
it('does not resurrect fields a re-login cleared', () => {
|
||||
const store = createStore();
|
||||
store.set(sessionsAtom, { type: 'PUT', session: baseSession });
|
||||
|
||||
store.set(sessionsAtom, {
|
||||
type: 'PUT',
|
||||
session: {
|
||||
baseUrl: baseSession.baseUrl,
|
||||
userId: baseSession.userId,
|
||||
deviceId: baseSession.deviceId,
|
||||
accessToken: 'password-login-access',
|
||||
},
|
||||
});
|
||||
|
||||
const [alice] = store.get(sessionsAtom);
|
||||
expect(alice!.refreshToken).toBeUndefined();
|
||||
expect(alice!.oidc).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { CryptoApi, MatrixClient } from '$types/matrix-sdk';
|
||||
import { fetch } from '$utils/fetch';
|
||||
|
||||
export const verifiedDevice = async (
|
||||
api: CryptoApi,
|
||||
@@ -12,6 +13,85 @@ export const verifiedDevice = async (
|
||||
return status.crossSigningVerified;
|
||||
};
|
||||
|
||||
type KeysQueryResponse = {
|
||||
device_keys?: Record<string, Record<string, { keys?: Record<string, string> }>>;
|
||||
master_keys?: Record<string, { keys?: Record<string, string> }>;
|
||||
};
|
||||
|
||||
/** What the homeserver currently publishes for our own user; undefined where it has nothing. */
|
||||
export type PublishedIdentity = {
|
||||
deviceKey: string | undefined;
|
||||
masterKeyId: string | undefined;
|
||||
};
|
||||
|
||||
export const fetchPublishedIdentity = async (
|
||||
baseUrl: string,
|
||||
accessToken: string,
|
||||
userId: string,
|
||||
deviceId: string
|
||||
): Promise<PublishedIdentity> => {
|
||||
const response = await fetch(`${baseUrl}/_matrix/client/v3/keys/query`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
body: JSON.stringify({ device_keys: { [userId]: [deviceId] } }),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Failed to read published device keys (${response.status})`);
|
||||
|
||||
const body = (await response.json()) as KeysQueryResponse;
|
||||
const masterKeys = body.master_keys?.[userId]?.keys;
|
||||
return {
|
||||
deviceKey: body.device_keys?.[userId]?.[deviceId]?.keys?.[`ed25519:${deviceId}`],
|
||||
masterKeyId: masterKeys ? Object.values(masterKeys)[0] : undefined,
|
||||
};
|
||||
};
|
||||
|
||||
export const fetchPublishedDeviceKey = async (
|
||||
baseUrl: string,
|
||||
accessToken: string,
|
||||
userId: string,
|
||||
deviceId: string
|
||||
): Promise<string | undefined> =>
|
||||
(await fetchPublishedIdentity(baseUrl, accessToken, userId, deviceId)).deviceKey;
|
||||
|
||||
// `/keys/signatures/upload` answers 200 with a `failures` map, so a rejected self-signature never
|
||||
// throws and the device keeps reporting itself as verified until the next device list refresh.
|
||||
const assertDeviceSignedItself = async (mx: MatrixClient, crypto: CryptoApi): Promise<void> => {
|
||||
const userId = mx.getSafeUserId();
|
||||
const deviceId = mx.getDeviceId();
|
||||
if (!deviceId) throw new Error('Unexpected Error! This session has no device id.');
|
||||
|
||||
if ((await verifiedDevice(crypto, userId, deviceId)) !== true) {
|
||||
throw new Error('This device could not be signed by your cross-signing identity.');
|
||||
}
|
||||
|
||||
// The local machine signs its own keys, so only the server's view says whether it can stick.
|
||||
const [ownKeys, localMasterKeyId, published] = await Promise.all([
|
||||
crypto.getOwnDeviceKeys(),
|
||||
crypto.getCrossSigningKeyId(),
|
||||
fetchPublishedIdentity(mx.baseUrl, mx.getAccessToken() ?? '', userId, deviceId),
|
||||
]);
|
||||
|
||||
if (published.deviceKey !== undefined && published.deviceKey !== ownKeys.ed25519) {
|
||||
throw new Error(
|
||||
'This device no longer matches the encryption keys your account published for it, so it cannot be verified. Sign out and sign in again to continue using encrypted chats.'
|
||||
);
|
||||
}
|
||||
|
||||
// Recovery keys outlive their identity; signing with a superseded one is discarded server-side.
|
||||
if (
|
||||
published.masterKeyId !== undefined &&
|
||||
localMasterKeyId !== null &&
|
||||
published.masterKeyId !== localMasterKeyId
|
||||
) {
|
||||
throw new Error(
|
||||
'Your recovery key unlocks a previous verification identity, not the one your account uses now. Verify with another signed-in device, or reset verification from Settings to start a new identity.'
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const CROSS_SIGNING_SECRETS = [
|
||||
'm.cross_signing.master',
|
||||
'm.cross_signing.self_signing',
|
||||
@@ -39,4 +119,6 @@ export const restoreCrossSigningFromSecretStorage = async (
|
||||
throw new Error('Refusing to replace your cross-signing identity to verify this device.');
|
||||
},
|
||||
});
|
||||
|
||||
await assertDeviceSignedItself(mx, crypto);
|
||||
};
|
||||
@@ -4,12 +4,17 @@ import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import type { Session } from '$state/sessions';
|
||||
import { getSessionStoreName } from '$state/sessions';
|
||||
import type * as MatrixSdkModule from 'matrix-js-sdk/lib/matrix';
|
||||
import type * as MatrixCryptoModule from '$utils/matrix-crypto';
|
||||
|
||||
const { isTauri, invoke, initRustCrypto } = vi.hoisted(() => ({
|
||||
isTauri: vi.fn<() => boolean>(() => false),
|
||||
invoke: vi.fn<(command: string, args?: unknown) => Promise<unknown>>(),
|
||||
initRustCrypto: vi.fn<(...args: unknown[]) => Promise<void>>(),
|
||||
}));
|
||||
const { isTauri, invoke, initRustCrypto, storeStartup, fetchPublishedDeviceKey } = vi.hoisted(
|
||||
() => ({
|
||||
isTauri: vi.fn<() => boolean>(() => false),
|
||||
invoke: vi.fn<(command: string, args?: unknown) => Promise<unknown>>(),
|
||||
initRustCrypto: vi.fn<(...args: unknown[]) => Promise<void>>(),
|
||||
storeStartup: vi.fn<() => Promise<void>>(),
|
||||
fetchPublishedDeviceKey: vi.fn<() => Promise<string | undefined>>(),
|
||||
})
|
||||
);
|
||||
|
||||
vi.mock('@tauri-apps/api/core', () => ({
|
||||
invoke,
|
||||
@@ -23,13 +28,18 @@ vi.mock('matrix-js-sdk/lib/matrix', async (importOriginal) => {
|
||||
createClient: (options: Parameters<typeof actual.createClient>[0]) => {
|
||||
const mx = actual.createClient(options);
|
||||
mx.initRustCrypto = initRustCrypto as MatrixClient['initRustCrypto'];
|
||||
mx.store.startup = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
|
||||
mx.store.startup = storeStartup as MatrixClient['store']['startup'];
|
||||
mx.store.destroy = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
|
||||
return mx;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('$utils/matrix-crypto', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof MatrixCryptoModule>()),
|
||||
fetchPublishedDeviceKey,
|
||||
}));
|
||||
|
||||
vi.mock('./versionsCache', () => ({
|
||||
primeVersionsFromCache: vi.fn<() => Promise<boolean>>().mockResolvedValue(false),
|
||||
revalidateVersionsCache: vi.fn<() => void>(),
|
||||
@@ -98,6 +108,8 @@ describe('initClient SDK crypto initialization', () => {
|
||||
isTauri.mockReturnValue(false);
|
||||
invoke.mockResolvedValue(undefined);
|
||||
initRustCrypto.mockResolvedValue(undefined);
|
||||
storeStartup.mockResolvedValue(undefined);
|
||||
fetchPublishedDeviceKey.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it.each([false, true])('initializes SDK crypto in %s runtime', async (tauri) => {
|
||||
@@ -199,6 +211,35 @@ describe('initClient SDK crypto initialization', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses to rebuild the crypto store for a device the server already holds keys for', async () => {
|
||||
const strandedSession = session('@stranded:example.org');
|
||||
initRustCrypto.mockRejectedValueOnce(new Error("account in the store doesn't match"));
|
||||
fetchPublishedDeviceKey.mockResolvedValue('published-ed25519-key');
|
||||
|
||||
await expect(initClient(strandedSession)).rejects.toMatchObject({
|
||||
name: 'StrandedCryptoStoreError',
|
||||
});
|
||||
expect(initRustCrypto).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps the crypto store when the published device key cannot be read', async () => {
|
||||
const offlineSession = session('@offline-check:example.org');
|
||||
initRustCrypto.mockRejectedValueOnce(new Error("account in the store doesn't match"));
|
||||
fetchPublishedDeviceKey.mockRejectedValue(new Error('offline'));
|
||||
|
||||
await expect(initClient(offlineSession)).rejects.toThrow("account in the store doesn't match");
|
||||
expect(initRustCrypto).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not rebuild the crypto store when the sync store reports a mismatch', async () => {
|
||||
const syncFailure = session('@sync-mismatch:example.org');
|
||||
storeStartup.mockRejectedValue(new Error('sync store version does not match'));
|
||||
|
||||
await expect(initClient(syncFailure)).rejects.toThrow('does not match');
|
||||
expect(fetchPublishedDeviceKey).not.toHaveBeenCalled();
|
||||
expect(initRustCrypto).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('allows a retry after an initialization failure', async () => {
|
||||
const failedSession = session('@retry-after-failure:example.org');
|
||||
initRustCrypto.mockRejectedValueOnce(new Error('SDK startup failed'));
|
||||
|
||||
@@ -36,6 +36,7 @@ import { assertAuthMetadataIssuer, createSessionTokenRefresher } from './oidcTok
|
||||
import { revokeOAuthToken } from './oauthTokenRevocation';
|
||||
import { clearSecretStorageKeys, cryptoCallbacks } from './secretStorageKeys';
|
||||
import { ensureSdkCryptoCanStart } from '$app/crypto/install';
|
||||
import { fetchPublishedDeviceKey } from '$utils/matrix-crypto';
|
||||
import type { SlidingSyncDiagnostics } from './slidingSync';
|
||||
import {
|
||||
prepareSlidingSyncTimelines,
|
||||
@@ -385,6 +386,20 @@ const isMismatch = (err: unknown): boolean => {
|
||||
);
|
||||
};
|
||||
|
||||
// A rebuilt store mints a new olm identity, but the server keeps the device keys it already
|
||||
// published for this device id, so the device can never be signed or decrypted to again.
|
||||
export class StrandedCryptoStoreError extends Error {
|
||||
constructor() {
|
||||
super(
|
||||
'This device can no longer use its encryption keys. Sign out and sign in again to continue using encrypted chats.'
|
||||
);
|
||||
this.name = 'StrandedCryptoStoreError';
|
||||
}
|
||||
}
|
||||
|
||||
export const isStrandedCryptoStoreError = (error: unknown): error is StrandedCryptoStoreError =>
|
||||
error instanceof StrandedCryptoStoreError;
|
||||
|
||||
const getSessionInitializationIdentity = (session: Session): string =>
|
||||
JSON.stringify({
|
||||
baseUrl: session.baseUrl,
|
||||
@@ -542,7 +557,8 @@ const initializeSession = async (session: Session): Promise<MatrixClient> => {
|
||||
evictPreviousCryptoStoreOwner(storeName.rustCryptoPrefix);
|
||||
const result = await initializeClient(session, storeName.rustCryptoPrefix);
|
||||
if (!result.ok) {
|
||||
if (!isMismatch(result.error)) {
|
||||
// Only the crypto phase says anything about the crypto store.
|
||||
if (result.phase !== 'rust_crypto' || !isMismatch(result.error)) {
|
||||
debugLog.error('sync', 'Failed to initialize client', {
|
||||
phase: result.phase,
|
||||
error: result.error,
|
||||
@@ -550,6 +566,35 @@ const initializeSession = async (session: Session): Promise<MatrixClient> => {
|
||||
throw result.error;
|
||||
}
|
||||
|
||||
let publishedDeviceKey: string | undefined;
|
||||
try {
|
||||
publishedDeviceKey = await fetchPublishedDeviceKey(
|
||||
session.baseUrl,
|
||||
session.accessToken,
|
||||
session.userId,
|
||||
session.deviceId
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(
|
||||
'initClient: could not read published device keys; refusing to rebuild the crypto store',
|
||||
error
|
||||
);
|
||||
throw result.error;
|
||||
}
|
||||
|
||||
if (publishedDeviceKey !== undefined) {
|
||||
debugLog.error(
|
||||
'sync',
|
||||
'Crypto store mismatch on a device the server already holds keys for',
|
||||
{
|
||||
phase: result.phase,
|
||||
error: result.error,
|
||||
}
|
||||
);
|
||||
Sentry.captureException(result.error, { tags: { area: 'crypto_store_stranded' } });
|
||||
throw new StrandedCryptoStoreError();
|
||||
}
|
||||
|
||||
log.warn(
|
||||
`initClient: mismatch during ${result.phase}; retrying on a device scoped crypto store`,
|
||||
result.error
|
||||
|
||||
Reference in new issue
Block a user