fix(crypto): prevent two clients sharing one crypto store (#1945)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Fixes #

#### Type of change

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).

<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
Erwan Leboucher authored and GitHub committed 2026-08-25 11:42:09 +02:00
commit cdb034fbed
4 files changed
+122 -2

No files matched your search

@@ -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.
+44
View File
@@ -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);
});
});
+63 -2
View File
@@ -61,6 +61,52 @@ const slidingSyncByClient = new WeakMap<MatrixClient, SlidingSyncManager>();
const membershipActionCleanupByClient = new WeakMap<MatrixClient, () => void>();
const presenceSyncByClient = new WeakMap<MatrixClient, PresenceSyncManager>();
// 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<string, MatrixClient>();
const cryptoStoreByClient = new WeakMap<MatrixClient, string>();
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<Sessions>(MATRIX_SESSIONS_KEY, []);
@@ -382,6 +428,7 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
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<MatrixClient> => {
}
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);
+10
View File
@@ -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<string, unknown> | 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;