fix(crypto): validate the stored backup key and settle a cancelled SAS flow

This commit is contained in:
Erwan Leboucher committed 2026-08-30 19:53:54 +02:00
1 parent a9eaf55840
commit f1b531a112
6 files changed
+130 -8

No files matched your search

+1 -1
View File
@@ -173,7 +173,7 @@ function SasVerification({ verifier, onCancel }: SasVerificationProps) {
useVerifierCancel(verifier, onCancel);
useEffect(() => {
verifier.verify();
verifier.verify().catch(() => undefined);
}, [verifier]);
if (sasData) {
+24 -1
View File
@@ -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<string | null> {
return (await this.#call('backupVersion')) as string | null;
}
@@ -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);
});
});
+5 -1
View File
@@ -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;
}
@@ -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<unknown>>(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<unknown>>(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<unknown>>(async () => null);
+12 -5
View File
@@ -107,8 +107,17 @@ abstract class EngineVerifier<TState>
abstract verify(): Promise<void>;
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<string, unknown>, 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<SasState> {
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'));
},
};
}