From a9eaf558404a2cc6c6efcf0fb8ff51e2e15aa9f7 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 30 Aug 2026 19:48:18 +0200 Subject: [PATCH] fix(crypto): retry outgoing requests and serialize key claims and room encryption --- src/app/crypto/engineCrypto/EngineCrypto.ts | 48 ++++++++++++---- .../engineCrypto/encryptionOrder.test.ts | 57 +++++++++++++++++++ src/app/crypto/engineCrypto/outgoing.ts | 28 ++++++--- .../crypto/engineCrypto/outgoingRetry.test.ts | 43 ++++++++++++++ 4 files changed, 158 insertions(+), 18 deletions(-) create mode 100644 src/app/crypto/engineCrypto/encryptionOrder.test.ts create mode 100644 src/app/crypto/engineCrypto/outgoingRetry.test.ts diff --git a/src/app/crypto/engineCrypto/EngineCrypto.ts b/src/app/crypto/engineCrypto/EngineCrypto.ts index d512ac6b2..0014faaac 100644 --- a/src/app/crypto/engineCrypto/EngineCrypto.ts +++ b/src/app/crypto/engineCrypto/EngineCrypto.ts @@ -331,6 +331,10 @@ export class EngineCrypto readonly #roomsWithTrackedMembers = new Set(); + #claimChain: Promise = Promise.resolve(); + + readonly #encryptionChains = new Map>(); + readonly #backupUpload = createCoalescedRunner( () => this.#uploadRoomKeysToBackup().catch((error: unknown) => { @@ -851,6 +855,8 @@ export class EngineCrypto this.#backupUpload.cancel(); this.#eventsPendingKey.clear(); this.#roomsWithTrackedMembers.clear(); + this.#encryptionChains.clear(); + this.#claimChain = Promise.resolve(); } #trustRequirement(): number { @@ -893,7 +899,30 @@ export class EngineCrypto return settings; } + #serializeForRoom(roomId: string, run: () => Promise): Promise { + const next = (this.#encryptionChains.get(roomId) ?? Promise.resolve()) + .catch(() => undefined) + .then(run); + this.#encryptionChains.set(roomId, next); + return next; + } + + async #ensureSessionsForUsers(users: string[]): Promise { + const next = this.#claimChain + .catch(() => undefined) + .then(async () => { + const claim = (await this.#call('getMissingSessions', { users })) as OutgoingRequest | null; + await this.#sendTracked(claim); + }); + this.#claimChain = next; + await next; + } + async encryptEvent(event: MatrixEvent, room: Room): Promise { + return this.#serializeForRoom(room.roomId, () => this.#encryptEventInner(event, room)); + } + + async #encryptEventInner(event: MatrixEvent, room: Room): Promise { // The megolm session has to reach every device in the room before the event does. const members = await room.getEncryptionTargetMembers(); const users = members.map((member) => member.userId); @@ -906,8 +935,7 @@ export class EngineCrypto this.#roomsWithTrackedMembers.add(room.roomId); } - const claim = (await this.#call('getMissingSessions', { users })) as OutgoingRequest | null; - await this.#sendTracked(claim); + await this.#ensureSessionsForUsers(users); const shared = ((await this.#call('shareRoomKey', { roomId: room.roomId, @@ -1295,15 +1323,13 @@ export class EngineCrypto } prepareToEncrypt(room: Room): void { - void room - .getEncryptionTargetMembers() - .then(async (members) => { - const users = members.map((member) => member.userId); - await this.#trackUsers(users); - await this.#sendTracked(await this.#call('getMissingSessions', { users })); - await this.#flushOutgoingRequests(); - }) - .catch((error: unknown) => engineCryptoLog.warn('general', 'prepareToEncrypt failed', error)); + void this.#serializeForRoom(room.roomId, async () => { + const members = await room.getEncryptionTargetMembers(); + const users = members.map((member) => member.userId); + await this.#trackUsers(users); + await this.#ensureSessionsForUsers(users); + await this.#flushOutgoingRequests(); + }).catch((error: unknown) => engineCryptoLog.warn('general', 'prepareToEncrypt failed', error)); } async forceDiscardSession(roomId: string): Promise { diff --git a/src/app/crypto/engineCrypto/encryptionOrder.test.ts b/src/app/crypto/engineCrypto/encryptionOrder.test.ts new file mode 100644 index 000000000..07d0e3951 --- /dev/null +++ b/src/app/crypto/engineCrypto/encryptionOrder.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { MatrixClient, MatrixEvent, Room } 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 room = (roomId: string) => + ({ + roomId, + getEncryptionTargetMembers: async () => [{ userId: '@me:e.org' }], + getHistoryVisibility: () => 'shared', + getBlacklistUnverifiedDevices: () => false, + currentState: { getStateEvents: () => null }, + }) as unknown as Room; + +const event = () => + ({ + getType: () => 'm.room.message', + getContent: () => ({}), + makeEncrypted: vi.fn(), + getTxnId: () => 't', + }) as unknown as MatrixEvent; + +describe('encryptEvent ordering', () => { + it('never runs two encryptions for a room at the same time', async () => { + const marks: string[] = []; + let inFlight = 0; + + mockInvoke.mockImplementation(async (_identity, method) => { + if (method === 'encryptRoomEvent') { + inFlight += 1; + marks.push(`enter${inFlight}`); + await new Promise((resolve) => { + setTimeout(resolve, 0); + }); + inFlight -= 1; + marks.push('exit'); + return '{}'; + } + if (method === 'identityKeys') return { ed25519: 'e', curve25519: 'c' }; + return null; + }); + + const mx = { http: { authedRequest: vi.fn() } } as unknown as MatrixClient; + const crypto = new EngineCrypto(mx, { userId: '@me:e.org', deviceId: 'D' }); + + await Promise.all([ + crypto.encryptEvent(event(), room('!r:e.org')), + crypto.encryptEvent(event(), room('!r:e.org')), + ]); + + expect(marks).toEqual(['enter1', 'exit', 'enter1', 'exit']); + }); +}); diff --git a/src/app/crypto/engineCrypto/outgoing.ts b/src/app/crypto/engineCrypto/outgoing.ts index d09b8ac34..9ef7431c3 100644 --- a/src/app/crypto/engineCrypto/outgoing.ts +++ b/src/app/crypto/engineCrypto/outgoing.ts @@ -1,4 +1,6 @@ import { Method } from 'matrix-js-sdk/lib/http-api'; +import { calculateRetryBackoff } from 'matrix-js-sdk/lib/http-api/utils'; +import { sleep } from 'matrix-js-sdk/lib/utils'; import type { MatrixClient } from '$types/matrix-sdk'; /** Numeric codes the engine tags outgoing requests with; see wasm_enums.rs. */ @@ -41,13 +43,25 @@ export const sendOutgoingRequest = async ( mx: MatrixClient, request: OutgoingRequest ): Promise => { - const send = (method: Method, url: string, params: Record = {}) => - mx.http.authedRequest(method, url, params, request.body, { - prefix: '', - json: false, - localTimeoutMs: OUTGOING_REQUEST_TIMEOUT_MS, - headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, - }); + const send = async (method: Method, url: string, params: Record = {}) => { + for (let attempts = 0; ;) { + try { + // eslint-disable-next-line no-await-in-loop + return await mx.http.authedRequest(method, url, params, request.body, { + prefix: '', + json: false, + localTimeoutMs: OUTGOING_REQUEST_TIMEOUT_MS, + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + }); + } catch (error) { + attempts += 1; + const backoff = calculateRetryBackoff(error, attempts, true); + if (backoff < 0) throw error; + // eslint-disable-next-line no-await-in-loop + await sleep(backoff); + } + } + }; switch (request.type) { case RequestType.KeysUpload: diff --git a/src/app/crypto/engineCrypto/outgoingRetry.test.ts b/src/app/crypto/engineCrypto/outgoingRetry.test.ts new file mode 100644 index 000000000..370900c2e --- /dev/null +++ b/src/app/crypto/engineCrypto/outgoingRetry.test.ts @@ -0,0 +1,43 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { Method } from 'matrix-js-sdk/lib/http-api'; +import type { MatrixClient } from '$types/matrix-sdk'; +import { RequestType, sendOutgoingRequest } from './outgoing'; + +vi.mock('matrix-js-sdk/lib/utils', async (importOriginal) => ({ + ...(await importOriginal()), + sleep: vi.fn(async () => undefined), +})); + +const rateLimited = () => + Object.assign(new Error('rate limited'), { + httpStatus: 429, + data: { errcode: 'M_LIMIT_EXCEEDED', retry_after_ms: 10 }, + }); + +const request = { id: 'r1', type: RequestType.KeysClaim, body: '{}' }; + +describe('sendOutgoingRequest', () => { + beforeEach(() => vi.clearAllMocks()); + + it('retries a rate-limited request instead of failing the caller', async () => { + const authedRequest = vi + .fn<(...args: never[]) => Promise>() + .mockRejectedValueOnce(rateLimited()) + .mockResolvedValueOnce('{}'); + const mx = { http: { authedRequest } } as unknown as MatrixClient; + + await expect(sendOutgoingRequest(mx, request)).resolves.toBe('{}'); + expect(authedRequest).toHaveBeenCalledTimes(2); + expect(authedRequest.mock.calls[0]?.[0]).toBe(Method.Post); + }); + + it('rethrows an error that is not worth retrying', async () => { + const authedRequest = vi + .fn<(...args: never[]) => Promise>() + .mockRejectedValue(Object.assign(new Error('nope'), { httpStatus: 400, data: {} })); + const mx = { http: { authedRequest } } as unknown as MatrixClient; + + await expect(sendOutgoingRequest(mx, request)).rejects.toThrow('nope'); + expect(authedRequest).toHaveBeenCalledTimes(1); + }); +});