diff --git a/.changeset/fix-duplicate-crypto-client.md b/.changeset/fix-duplicate-crypto-client.md new file mode 100644 index 000000000..5e22d025c --- /dev/null +++ b/.changeset/fix-duplicate-crypto-client.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Stop a second Matrix client from opening the same crypto store, which could corrupt device keys and leave a device looking unverified to other clients. diff --git a/src/client/initMatrix.test.ts b/src/client/initMatrix.test.ts index 5ed49ef60..d819b0669 100644 --- a/src/client/initMatrix.test.ts +++ b/src/client/initMatrix.test.ts @@ -15,10 +15,13 @@ vi.mock('$utils/platform', async (importOriginal) => ({ })); import { + claimCryptoStore, + getCryptoStoreOwner, installSlidingSyncRequestPatch, newSlidingSyncConnId, ownsActiveMediaSession, recheckKeyBackupAfterInitialSync, + releaseCryptoStore, resolvePollTimeoutMs, supportsSlidingSync, } from './initMatrix'; @@ -340,3 +343,44 @@ describe('recheckKeyBackupAfterInitialSync', () => { expect(checkKeyBackupAndEnable).not.toHaveBeenCalled(); }); }); + +describe('crypto store ownership', () => { + const clientA = { id: 'a' } as unknown as MatrixClient; + const clientB = { id: 'b' } as unknown as MatrixClient; + const storeKey = 'sync@alice:example.org'; + + beforeEach(() => { + releaseCryptoStore(clientA); + releaseCryptoStore(clientB); + }); + + it('reports the client currently holding the store', () => { + claimCryptoStore(clientA, storeKey); + + expect(getCryptoStoreOwner(storeKey)).toBe(clientA); + }); + + it('reports no owner once the holder releases it', () => { + claimCryptoStore(clientA, storeKey); + releaseCryptoStore(clientA); + + expect(getCryptoStoreOwner(storeKey)).toBeUndefined(); + }); + + it('keeps the new owner when a superseded client is released afterwards', () => { + claimCryptoStore(clientA, storeKey); + claimCryptoStore(clientB, storeKey); + + // Otherwise the next init sees a free store and opens a second OlmMachine. + releaseCryptoStore(clientA); + + expect(getCryptoStoreOwner(storeKey)).toBe(clientB); + }); + + it('ignores a release from a client that never claimed a store', () => { + claimCryptoStore(clientA, storeKey); + releaseCryptoStore(clientB); + + expect(getCryptoStoreOwner(storeKey)).toBe(clientA); + }); +}); diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index d1c2f87c0..8979ecb73 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -61,6 +61,52 @@ const slidingSyncByClient = new WeakMap(); const membershipActionCleanupByClient = new WeakMap void>(); const presenceSyncByClient = new WeakMap(); +// Two MatrixClients on one crypto store corrupt it, and initRustCrypto leaves it to the +// application to prevent that, so track which client owns each store. +const liveClientByCryptoStore = new Map(); +const cryptoStoreByClient = new WeakMap(); + +export const getCryptoStoreOwner = (storeKey: string): MatrixClient | undefined => + liveClientByCryptoStore.get(storeKey); + +export const claimCryptoStore = (mx: MatrixClient, storeKey: string): void => { + liveClientByCryptoStore.set(storeKey, mx); + cryptoStoreByClient.set(mx, storeKey); +}; + +export const releaseCryptoStore = (mx: MatrixClient): void => { + const storeKey = cryptoStoreByClient.get(mx); + if (storeKey === undefined) return; + cryptoStoreByClient.delete(mx); + // A superseded client must not evict the entry of whichever client replaced it. + if (liveClientByCryptoStore.get(storeKey) === mx) liveClientByCryptoStore.delete(storeKey); +}; + +const evictPreviousCryptoStoreOwner = (storeKey: string): void => { + const previous = liveClientByCryptoStore.get(storeKey); + if (!previous) return; + + const wasRunning = previous.clientRunning; + const previousSyncState = previous.getSyncState(); + + log.warn('initClient: crypto store already owned by a live client — stopping it first'); + debugLog.warn('sync', 'Duplicate crypto client init — stopping previous owner', { + wasRunning, + previousSyncState, + }); + Sentry.metrics.count('sable.crypto.duplicate_client', 1, { + attributes: { was_running: wasRunning }, + }); + // An Error, not a message, so the stack names what re-entered initClient. + Sentry.captureException(new Error('Duplicate MatrixClient for one crypto store'), { + tags: { area: 'crypto_store_ownership' }, + extra: { was_running: wasRunning, previous_sync_state: previousSyncState }, + }); + + // stopClient releases the store as part of its teardown. + stopClient(previous); +}; + export const ownsActiveMediaSession = (session?: Session): boolean => { if (!session) return true; const sessions = getLocalStorageItem(MATRIX_SESSIONS_KEY, []); @@ -382,6 +428,7 @@ export const initClient = async (session: Session): Promise => { const initStartTime = performance.now(); let initOutcome = 'success'; try { + evictPreviousCryptoStoreOwner(storeName.rustCryptoPrefix); const result = await initializeClient(session, storeName.rustCryptoPrefix); if (!result.ok) { if (!isMismatch(result.error)) { @@ -403,6 +450,10 @@ export const initClient = async (session: Session): Promise => { } result.mx.setMaxListeners(50); + claimCryptoStore(result.mx, storeName.rustCryptoPrefix); + debugLog.info('sync', 'Matrix client initialised, crypto store claimed', { + userId: session.userId, + }); return result.mx; } catch (error) { initOutcome = 'error'; @@ -552,7 +603,11 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig): }); } - debugLog.info('sync', 'Starting Matrix client', { userId: mx.getUserId() }); + debugLog.info('sync', 'Starting Matrix client', { + userId: mx.getUserId(), + transport: useSliding ? 'sliding' : 'classic', + alreadyRunning: mx.clientRunning, + }); let manager: SlidingSyncManager | undefined; @@ -608,7 +663,13 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig): export const stopClient = (mx: MatrixClient): void => { log.log('stopClient', mx.getUserId()); - debugLog.info('sync', 'Stopping client', { userId: mx.getUserId() }); + // stopClient closes the OlmMachine even when the client never ran, so record it. + debugLog.info('sync', 'Stopping client', { + userId: mx.getUserId(), + wasRunning: mx.clientRunning, + syncState: mx.getSyncState(), + }); + releaseCryptoStore(mx); slidingSyncRequestCleanupByClient.get(mx)?.(); disposeSyncStorePersistence(mx); disposeSlidingSync(mx); diff --git a/src/instrument.ts b/src/instrument.ts index f174b874d..f8029284a 100644 --- a/src/instrument.ts +++ b/src/instrument.ts @@ -42,6 +42,9 @@ if (dsn && sentryEnabled) { // Do not send PII (IP addresses, user identifiers) to protect privacy sendDefaultPii: false, + // The default 100 only covered a few seconds of this app's HTTP traffic. + maxBreadcrumbs: 200, + integrations: [ // React Router v6 browser tracing integration Sentry.reactRouterV6BrowserTracingIntegration({ @@ -160,6 +163,13 @@ if (dsn && sentryEnabled) { beforeBreadcrumb(breadcrumb) { // Scrub Matrix paths from HTTP breadcrumb data.url (captures full request URLs) const bData = breadcrumb.data as Record | undefined; + + // Successful requests arrive continuously and evict the breadcrumbs that explain + // a failure. Keep failures and anything without a status. + if (breadcrumb.category === 'fetch' || breadcrumb.category === 'xhr') { + const status = bData?.status_code; + if (typeof status === 'number' && status < 400) return null; + } const rawUrl = typeof bData?.url === 'string' ? bData.url : undefined; const scrubbedUrl = rawUrl ? scrubMatrixUrl(rawUrl) : undefined; const urlChanged = scrubbedUrl !== undefined && scrubbedUrl !== rawUrl;