|
| 1 | +import { afterEach, describe, expect, it, vi } from 'vitest'; |
| 2 | +import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; |
| 3 | +import { engineInvoke } from '../olmMachine/engineInvoke'; |
| 4 | +import { EngineCrypto } from './EngineCrypto'; |
| 5 | + |
| 6 | +vi.mock('../olmMachine/engineInvoke', () => ({ |
| 7 | + engineInvoke: vi.fn<(...args: never[]) => Promise<unknown>>(), |
| 8 | +})); |
| 9 | + |
| 10 | +const mockInvoke = vi.mocked(engineInvoke); |
| 11 | + |
| 12 | +const room = (roomId: string) => |
| 13 | + ({ |
| 14 | + roomId, |
| 15 | + getEncryptionTargetMembers: async () => [{ userId: `@${roomId.slice(1, 2)}:e.org` }], |
| 16 | + getHistoryVisibility: () => 'shared', |
| 17 | + getBlacklistUnverifiedDevices: () => false, |
| 18 | + currentState: { getStateEvents: () => null }, |
| 19 | + }) as unknown as Room; |
| 20 | + |
| 21 | +const event = (body: string) => |
| 22 | + ({ |
| 23 | + getType: () => 'm.room.message', |
| 24 | + getContent: () => ({ body }), |
| 25 | + makeEncrypted: vi.fn<() => void>(), |
| 26 | + }) as unknown as MatrixEvent; |
| 27 | + |
| 28 | +const cryptoWith = (authedRequest: ReturnType<typeof vi.fn>) => |
| 29 | + new EngineCrypto({ http: { authedRequest } } as unknown as MatrixClient, { |
| 30 | + userId: '@me:e.org', |
| 31 | + deviceId: 'D', |
| 32 | + }); |
| 33 | + |
| 34 | +describe('encrypted send concurrency', () => { |
| 35 | + afterEach(() => mockInvoke.mockReset()); |
| 36 | + |
| 37 | + it('holds same-room sends behind preparation response and acknowledgement', async () => { |
| 38 | + const queryResponse = Promise.withResolvers<string>(); |
| 39 | + const queryAcknowledged = Promise.withResolvers<void>(); |
| 40 | + const authedRequest = vi.fn<(...args: never[]) => Promise<string>>(async (_method, url) => { |
| 41 | + if (url === '/_matrix/client/v3/keys/query') return queryResponse.promise; |
| 42 | + return '{}'; |
| 43 | + }); |
| 44 | + mockInvoke.mockImplementation(async (_identity, method, args) => { |
| 45 | + if (method === 'queryKeysForUsers') return { id: 'query', type: 1, body: '{}' }; |
| 46 | + if (method === 'markRequestAsSent' && (args as { requestId: string }).requestId === 'query') { |
| 47 | + await queryAcknowledged.promise; |
| 48 | + } |
| 49 | + if (method === 'encryptRoomEvent') return '{}'; |
| 50 | + if (method === 'identityKeys') return { ed25519: 'ed', curve25519: 'curve' }; |
| 51 | + return null; |
| 52 | + }); |
| 53 | + |
| 54 | + const crypto = cryptoWith(authedRequest); |
| 55 | + const target = room('!room:e.org'); |
| 56 | + crypto.prepareToEncrypt(target); |
| 57 | + const sends = [ |
| 58 | + crypto.encryptEvent(event('first'), target), |
| 59 | + crypto.encryptEvent(event('second'), target), |
| 60 | + ]; |
| 61 | + |
| 62 | + try { |
| 63 | + await vi.waitFor(() => expect(authedRequest).toHaveBeenCalledOnce()); |
| 64 | + expect( |
| 65 | + mockInvoke.mock.calls.filter(([, method]) => method === 'getMissingSessions') |
| 66 | + ).toHaveLength(0); |
| 67 | + |
| 68 | + queryResponse.resolve('{}'); |
| 69 | + await vi.waitFor(() => |
| 70 | + expect(mockInvoke.mock.calls).toContainEqual([ |
| 71 | + expect.anything(), |
| 72 | + 'markRequestAsSent', |
| 73 | + expect.objectContaining({ requestId: 'query' }), |
| 74 | + ]) |
| 75 | + ); |
| 76 | + expect( |
| 77 | + mockInvoke.mock.calls.filter(([, method]) => method === 'getMissingSessions') |
| 78 | + ).toHaveLength(0); |
| 79 | + |
| 80 | + queryAcknowledged.resolve(); |
| 81 | + await Promise.all(sends); |
| 82 | + |
| 83 | + expect( |
| 84 | + mockInvoke.mock.calls.filter(([, method]) => method === 'queryKeysForUsers') |
| 85 | + ).toHaveLength(1); |
| 86 | + expect( |
| 87 | + mockInvoke.mock.calls |
| 88 | + .filter(([, method]) => method === 'encryptRoomEvent') |
| 89 | + .map(([, , args]) => JSON.parse((args as { content: string }).content).body) |
| 90 | + ).toEqual(['first', 'second']); |
| 91 | + } finally { |
| 92 | + queryResponse.resolve('{}'); |
| 93 | + queryAcknowledged.resolve(); |
| 94 | + await Promise.allSettled(sends); |
| 95 | + } |
| 96 | + }); |
| 97 | + |
| 98 | + it('keeps claims for separate rooms serialized until their response is acknowledged', async () => { |
| 99 | + const firstClaimResponse = Promise.withResolvers<string>(); |
| 100 | + const firstClaimAcknowledged = Promise.withResolvers<void>(); |
| 101 | + let claimsSent = 0; |
| 102 | + let heldClaimId: string | undefined; |
| 103 | + let queries = 0; |
| 104 | + const authedRequest = vi.fn<(...args: never[]) => Promise<string>>(async (_method, url) => { |
| 105 | + if (url === '/_matrix/client/v3/keys/claim' && claimsSent++ === 0) { |
| 106 | + return firstClaimResponse.promise; |
| 107 | + } |
| 108 | + return '{}'; |
| 109 | + }); |
| 110 | + mockInvoke.mockImplementation(async (_identity, method, args) => { |
| 111 | + if (method === 'queryKeysForUsers') return { id: `query-${queries++}`, type: 1, body: '{}' }; |
| 112 | + if (method === 'getMissingSessions') { |
| 113 | + const user = (args as { users: string[] }).users[0]; |
| 114 | + return { id: `claim-${user}`, type: 2, body: '{}' }; |
| 115 | + } |
| 116 | + if (method === 'markRequestAsSent') { |
| 117 | + const requestId = (args as { requestId: string }).requestId; |
| 118 | + if (requestId.startsWith('claim-') && !heldClaimId) { |
| 119 | + heldClaimId = requestId; |
| 120 | + await firstClaimAcknowledged.promise; |
| 121 | + } |
| 122 | + } |
| 123 | + if (method === 'encryptRoomEvent') return '{}'; |
| 124 | + if (method === 'identityKeys') return { ed25519: 'ed', curve25519: 'curve' }; |
| 125 | + return null; |
| 126 | + }); |
| 127 | + |
| 128 | + const crypto = cryptoWith(authedRequest); |
| 129 | + const sends = [ |
| 130 | + crypto.encryptEvent(event('a'), room('!a:e.org')), |
| 131 | + crypto.encryptEvent(event('b'), room('!b:e.org')), |
| 132 | + ]; |
| 133 | + |
| 134 | + try { |
| 135 | + await vi.waitFor(() => expect(claimsSent).toBe(1)); |
| 136 | + expect( |
| 137 | + mockInvoke.mock.calls.filter(([, method]) => method === 'getMissingSessions') |
| 138 | + ).toHaveLength(1); |
| 139 | + |
| 140 | + firstClaimResponse.resolve('{}'); |
| 141 | + await vi.waitFor(() => expect(heldClaimId).toBeDefined()); |
| 142 | + expect( |
| 143 | + mockInvoke.mock.calls.filter(([, method]) => method === 'getMissingSessions') |
| 144 | + ).toHaveLength(1); |
| 145 | + |
| 146 | + firstClaimAcknowledged.resolve(); |
| 147 | + await Promise.all(sends); |
| 148 | + expect( |
| 149 | + mockInvoke.mock.calls.filter(([, method]) => method === 'getMissingSessions') |
| 150 | + ).toHaveLength(2); |
| 151 | + } finally { |
| 152 | + firstClaimResponse.resolve('{}'); |
| 153 | + firstClaimAcknowledged.resolve(); |
| 154 | + await Promise.allSettled(sends); |
| 155 | + } |
| 156 | + }); |
| 157 | + |
| 158 | + it('lets a queued send retry after preparation query failure', async () => { |
| 159 | + const failedQuery = Promise.withResolvers<string>(); |
| 160 | + let queries = 0; |
| 161 | + const authedRequest = vi.fn<(...args: never[]) => Promise<string>>(async (_method, url) => { |
| 162 | + if (url === '/_matrix/client/v3/keys/query' && queries++ === 0) return failedQuery.promise; |
| 163 | + return '{}'; |
| 164 | + }); |
| 165 | + mockInvoke.mockImplementation(async (_identity, method) => { |
| 166 | + if (method === 'queryKeysForUsers') return { id: 'query', type: 1, body: '{}' }; |
| 167 | + if (method === 'encryptRoomEvent') return '{}'; |
| 168 | + if (method === 'identityKeys') return { ed25519: 'ed', curve25519: 'curve' }; |
| 169 | + return null; |
| 170 | + }); |
| 171 | + |
| 172 | + const crypto = cryptoWith(authedRequest); |
| 173 | + const target = room('!room:e.org'); |
| 174 | + crypto.prepareToEncrypt(target); |
| 175 | + let send: Promise<void> | undefined; |
| 176 | + try { |
| 177 | + await vi.waitFor(() => expect(queries).toBe(1)); |
| 178 | + send = crypto.encryptEvent(event('after failure'), target); |
| 179 | + failedQuery.reject(new Error('query failed')); |
| 180 | + |
| 181 | + await expect(send).resolves.toBeUndefined(); |
| 182 | + expect(queries).toBe(2); |
| 183 | + } finally { |
| 184 | + failedQuery.reject(new Error('query failed')); |
| 185 | + await send?.catch(() => undefined); |
| 186 | + } |
| 187 | + }); |
| 188 | +}); |
0 commit comments