From f1b531a1124e744e3d3b9f0a2cf5d150ebffd34b Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 30 Aug 2026 19:53:54 +0200 Subject: [PATCH] fix(crypto): validate the stored backup key and settle a cancelled SAS flow --- src/app/components/DeviceVerification.tsx | 2 +- src/app/crypto/engineCrypto/EngineCrypto.ts | 25 +++++++++- .../engineCrypto/backupKeyFrom4S.test.ts | 50 +++++++++++++++++++ src/app/crypto/verification/request.ts | 6 ++- src/app/crypto/verification/verifier.test.ts | 38 ++++++++++++++ src/app/crypto/verification/verifier.ts | 17 +++++-- 6 files changed, 130 insertions(+), 8 deletions(-) create mode 100644 src/app/crypto/engineCrypto/backupKeyFrom4S.test.ts diff --git a/src/app/components/DeviceVerification.tsx b/src/app/components/DeviceVerification.tsx index f2c582566..f44c640a4 100644 --- a/src/app/components/DeviceVerification.tsx +++ b/src/app/components/DeviceVerification.tsx @@ -173,7 +173,7 @@ function SasVerification({ verifier, onCancel }: SasVerificationProps) { useVerifierCancel(verifier, onCancel); useEffect(() => { - verifier.verify(); + verifier.verify().catch(() => undefined); }, [verifier]); if (sasData) { diff --git a/src/app/crypto/engineCrypto/EngineCrypto.ts b/src/app/crypto/engineCrypto/EngineCrypto.ts index 0014faaac..699c8c6af 100644 --- a/src/app/crypto/engineCrypto/EngineCrypto.ts +++ b/src/app/crypto/engineCrypto/EngineCrypto.ts @@ -28,7 +28,10 @@ import type { RoomMessageEventContent } from 'matrix-js-sdk/lib/types'; import { encodeUri } from 'matrix-js-sdk/lib/utils'; import { TypedEventEmitter } from 'matrix-js-sdk/lib/models/typed-event-emitter'; import { CryptoEvent, DeviceIsolationModeKind } from 'matrix-js-sdk/lib/crypto-api'; -import { DecryptionFailureCode } from 'matrix-js-sdk/lib/crypto-api'; +import { + DecryptionFailureCode, + DecryptionKeyDoesNotMatchError, +} from 'matrix-js-sdk/lib/crypto-api'; import { DecryptionError } from 'matrix-js-sdk/lib/common-crypto/CryptoBackend'; import type { CryptoEventHandlerMap } from 'matrix-js-sdk/lib/crypto-api/CryptoEventHandlerMap'; import { createDebugLogger } from '$utils/debugLogger'; @@ -1894,9 +1897,29 @@ export class EngineCrypto const backupInfo = await this.#requestKeyBackupVersion(); if (!backupInfo?.version) throw new Error('No key backup version to attach the key to'); + if (!EngineCrypto.#keyMatchesBackup(encoded, backupInfo)) { + throw new DecryptionKeyDoesNotMatchError( + 'loadSessionBackupPrivateKeyFromSecretStorage: decryption key does not match backup info' + ); + } + await this.storeSessionBackupPrivateKey(decodeBase64(encoded), backupInfo.version); } + static #keyMatchesBackup(encoded: string, backupInfo: KeyBackupInfo): boolean { + const publicKey = (backupInfo.auth_data as { public_key?: string } | undefined)?.public_key; + try { + const key = RustSdkCryptoJs.BackupDecryptionKey.fromBase64(encoded); + try { + return key.megolmV1PublicKey.publicKeyBase64 === publicKey; + } finally { + key.free(); + } + } catch { + return false; + } + } + async getActiveSessionBackupVersion(): Promise { return (await this.#call('backupVersion')) as string | null; } diff --git a/src/app/crypto/engineCrypto/backupKeyFrom4S.test.ts b/src/app/crypto/engineCrypto/backupKeyFrom4S.test.ts new file mode 100644 index 000000000..35853b72c --- /dev/null +++ b/src/app/crypto/engineCrypto/backupKeyFrom4S.test.ts @@ -0,0 +1,50 @@ +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as RustSdkCryptoJs from '@matrix-org/matrix-sdk-crypto-wasm'; +import { DecryptionKeyDoesNotMatchError } from 'matrix-js-sdk/lib/crypto-api'; +import type { MatrixClient } from '$types/matrix-sdk'; +import { engineInvoke } from '../olmMachine/engineInvoke'; +import { EngineCrypto } from './EngineCrypto'; + +vi.mock('../olmMachine/engineInvoke', () => ({ engineInvoke: vi.fn() })); + +const mockInvoke = vi.mocked(engineInvoke); + +const clientWith = (encoded: string, publicKey: string) => + ({ + secretStorage: { get: async () => encoded }, + http: { + authedRequest: vi.fn(async () => ({ + version: '3', + algorithm: 'm.megolm_backup.v1.curve25519-aes-sha2', + auth_data: { public_key: publicKey }, + })), + }, + }) as unknown as MatrixClient; + +describe('loadSessionBackupPrivateKeyFromSecretStorage', () => { + beforeAll(() => RustSdkCryptoJs.initAsync()); + beforeEach(() => mockInvoke.mockReset().mockResolvedValue(null)); + + it('rejects a stored key that does not match the server backup', async () => { + const stored = RustSdkCryptoJs.BackupDecryptionKey.createRandomKey(); + const other = RustSdkCryptoJs.BackupDecryptionKey.createRandomKey(); + const mx = clientWith(stored.toBase64(), other.megolmV1PublicKey.publicKeyBase64); + + const crypto = new EngineCrypto(mx, { userId: '@me:e.org', deviceId: 'D' }); + + await expect(crypto.loadSessionBackupPrivateKeyFromSecretStorage()).rejects.toBeInstanceOf( + DecryptionKeyDoesNotMatchError + ); + expect(mockInvoke.mock.calls.some(([, m]) => m === 'saveBackupDecryptionKey')).toBe(false); + }); + + it('accepts a stored key that matches the server backup', async () => { + const stored = RustSdkCryptoJs.BackupDecryptionKey.createRandomKey(); + const mx = clientWith(stored.toBase64(), stored.megolmV1PublicKey.publicKeyBase64); + + const crypto = new EngineCrypto(mx, { userId: '@me:e.org', deviceId: 'D' }); + + await expect(crypto.loadSessionBackupPrivateKeyFromSecretStorage()).resolves.toBeUndefined(); + expect(mockInvoke.mock.calls.some(([, m]) => m === 'saveBackupDecryptionKey')).toBe(true); + }); +}); diff --git a/src/app/crypto/verification/request.ts b/src/app/crypto/verification/request.ts index b8a071adb..cd4521790 100644 --- a/src/app/crypto/verification/request.ts +++ b/src/app/crypto/verification/request.ts @@ -247,7 +247,11 @@ export class EngineVerificationRequest await this.#call('verificationRequest.startSas', this.#flow); await this.refresh(); - if (!this.#verifier) throw new Error(`Starting ${method} produced no verifier`); + if (!this.#verifier) { + throw new Error( + `Could not start ${method}: the other device is no longer available for verification` + ); + } return this.#verifier; } diff --git a/src/app/crypto/verification/verifier.test.ts b/src/app/crypto/verification/verifier.test.ts index 6d1e0abe3..486e8ad72 100644 --- a/src/app/crypto/verification/verifier.test.ts +++ b/src/app/crypto/verification/verifier.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'; import { VerificationPhase, VerifierEvent, + type MatrixEvent, type ShowQrCodeCallbacks, type ShowSasCallbacks, } from '$types/matrix-sdk'; @@ -10,6 +11,43 @@ import { EngineQrVerifier, EngineSasVerifier } from './verifier'; const flow = { userId: '@them:e.org', flowId: '$f' }; describe('EngineSasVerifier', () => { + it('settles the flow when the user says the codes do not match', async () => { + const call = vi.fn<(method: string, args: unknown) => Promise>(async () => null); + const verifier = new EngineSasVerifier(call, flow, {}, '@them:e.org'); + const cancelled = vi.fn<(error: Error | MatrixEvent) => void>(); + verifier.on(VerifierEvent.Cancel, cancelled); + const completion = verifier.verify(); + + verifier.onChange({ + emoji: [{ symbol: '🐶', description: 'Dog' }], + decimals: [1, 2, 3], + }); + verifier.getShowSasCallbacks()?.mismatch(); + + await expect(completion).rejects.toThrow('The codes did not match'); + expect(cancelled).toHaveBeenCalledOnce(); + expect(call).toHaveBeenCalledWith( + 'sas.cancel', + expect.objectContaining({ code: 'm.mismatched_sas' }) + ); + }); + + it('does not send a second cancel when the user double taps', async () => { + const call = vi.fn<(method: string, args: unknown) => Promise>(async () => null); + const verifier = new EngineSasVerifier(call, flow, {}, '@them:e.org'); + verifier.verify().catch(() => undefined); + + verifier.onChange({ + emoji: [{ symbol: '🐶', description: 'Dog' }], + decimals: [1, 2, 3], + }); + const callbacks = verifier.getShowSasCallbacks(); + callbacks?.cancel(); + callbacks?.cancel(); + + expect(call.mock.calls.filter(([method]) => method === 'sas.cancel')).toHaveLength(1); + }); + // Reading the digits straight after accepting yields nothing: they arrive later. it('emits ShowSas when the digits arrive, not when accept is sent', async () => { const call = vi.fn<() => Promise>(async () => null); diff --git a/src/app/crypto/verification/verifier.ts b/src/app/crypto/verification/verifier.ts index fecdbb603..84763e7fc 100644 --- a/src/app/crypto/verification/verifier.ts +++ b/src/app/crypto/verification/verifier.ts @@ -107,8 +107,17 @@ abstract class EngineVerifier abstract verify(): Promise; cancel(error: Error): void { + this.finishCancelled(this.flow, error); + } + + protected cancelWithCode(code: string, error: Error): void { + this.finishCancelled({ ...this.flow, code }, error); + } + + private finishCancelled(flow: Record, error: Error): void { + if (this.hasBeenCancelled) return; this.markCancelled(); - void this.call(this.cancelMethod, this.flow); + void this.call(this.cancelMethod, flow); this.completion.reject(error); this.emit(VerifierEvent.Cancel, error); } @@ -169,12 +178,10 @@ export class EngineSasVerifier extends EngineVerifier { await this.call('sas.confirm', this.flow); }, mismatch: () => { - this.markCancelled(); - void this.call('sas.cancel', { ...this.flow, code: 'm.mismatched_sas' }); + this.cancelWithCode('m.mismatched_sas', new Error('The codes did not match')); }, cancel: () => { - this.markCancelled(); - void this.call('sas.cancel', { ...this.flow, code: 'm.user' }); + this.cancelWithCode('m.user', new Error('Verification cancelled')); }, }; }