fix: add crypto verification diagnostics (#1899)

<!-- 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

- [x] 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-21 08:38:07 +02:00
commit cbb7dcfa84
4 files changed
+150 -5

No files matched your search

@@ -11,7 +11,7 @@ import {
VerificationStatus,
} from './useDeviceVerificationStatus';
const { mockMx, getListenerCount } = vi.hoisted(() => {
const { mockMx, getListenerCount, sentry } = vi.hoisted(() => {
const listeners = new Map<string, Set<(...args: never[]) => void>>();
const mx = {
on(event: string, cb: (...args: never[]) => void) {
@@ -30,14 +30,23 @@ const { mockMx, getListenerCount } = vi.hoisted(() => {
getListenerCount(event: string) {
return listeners.get(event)?.size ?? 0;
},
getSafeUserId() {
return '@me:example.org';
},
};
return {
mockMx: mx,
getListenerCount: (event: string) => mx.getListenerCount(event),
sentry: { addBreadcrumb: vi.fn<() => void>(), metrics: { count: vi.fn<() => void>() } },
};
return { mockMx: mx, getListenerCount: (event: string) => mx.getListenerCount(event) };
});
vi.mock('$hooks/useMatrixClient', () => ({
useMatrixClient: () => mockMx,
}));
vi.mock('@sentry/react', () => sentry);
const USER_ID = '@me:example.org';
const DEVICE_ID = 'DEVICEONE';
@@ -58,6 +67,8 @@ describe('useDeviceVerificationStatus', () => {
beforeEach(() => {
getDeviceVerificationStatus.mockReset();
getDeviceVerificationStatus.mockResolvedValue({ crossSigningVerified: true });
sentry.addBreadcrumb.mockClear();
sentry.metrics.count.mockClear();
});
it('reports the cross-signing verification status', async () => {
@@ -171,6 +182,24 @@ describe('useDeviceVerificationStatus', () => {
expect(getDeviceVerificationStatus).toHaveBeenCalledTimes(2);
});
it('records a current-device trust loss after a crypto refresh', async () => {
const { result } = renderHook(() => useDeviceVerificationStatus(crypto, USER_ID, DEVICE_ID), {
wrapper: createWrapper(),
});
await waitFor(() => expect(result.current).toBe(VerificationStatus.Verified));
getDeviceVerificationStatus.mockResolvedValue({ crossSigningVerified: false });
await act(async () => {
mockMx.emit(CryptoEvent.KeysChanged, ...([{}] as never[]));
});
await waitFor(() => expect(result.current).toBe(VerificationStatus.Unverified));
expect(sentry.metrics.count).toHaveBeenCalledWith('sable.crypto.device_verification_lost', 1, {
attributes: { own_device: true },
});
});
it('ignores device updates for a different user', async () => {
const { result } = renderHook(() => useDeviceVerificationStatus(crypto, USER_ID, DEVICE_ID), {
wrapper: createWrapper(),
+50 -1
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect } from 'react';
import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
import * as Sentry from '@sentry/react';
import { type CryptoApi, type CryptoEventHandlerMap, CryptoEvent } from '$types/matrix-sdk';
import { verifiedDevice } from '$utils/matrix-crypto';
import { useMatrixClient } from './useMatrixClient';
@@ -41,6 +42,7 @@ const DEVICE_VERIFICATION_QUERY_KEY = 'device-verification';
const cryptoIds = new WeakMap<CryptoApi, string>();
let cryptoIdCounter = 0;
const verificationStatuses = new WeakMap<CryptoApi, Map<string, VerificationStatus>>();
const getCryptoId = (crypto: CryptoApi | undefined): string => {
if (!crypto) return 'none';
@@ -89,16 +91,38 @@ const useInvalidateDeviceVerification = (crypto: CryptoApi | undefined): void =>
let sub = clientSubscriptions.get(mx);
if (!sub) {
const onDevicesUpdated: CryptoEventHandlerMap[CryptoEvent.DevicesUpdated] = (userIds) => {
if (userIds.includes(mx.getSafeUserId())) {
Sentry.addBreadcrumb({
category: 'crypto',
message: 'Device verification refreshed',
level: 'info',
data: { trigger: 'devices_updated' },
});
}
for (const uid of userIds) {
queryClient.invalidateQueries({ queryKey: [DEVICE_VERIFICATION_QUERY_KEY, uid] });
}
};
const onKeysChanged: CryptoEventHandlerMap[CryptoEvent.KeysChanged] = () => {
Sentry.addBreadcrumb({
category: 'crypto',
message: 'Device verification refreshed',
level: 'info',
data: { trigger: 'keys_changed' },
});
queryClient.invalidateQueries({ queryKey: [DEVICE_VERIFICATION_QUERY_KEY] });
};
const onUserTrustStatusChanged: CryptoEventHandlerMap[CryptoEvent.UserTrustStatusChanged] = (
changedUserId
) => {
if (changedUserId === mx.getSafeUserId()) {
Sentry.addBreadcrumb({
category: 'crypto',
message: 'Device verification refreshed',
level: 'info',
data: { trigger: 'user_trust_changed' },
});
}
queryClient.invalidateQueries({
queryKey: [DEVICE_VERIFICATION_QUERY_KEY, changedUserId],
});
@@ -152,11 +176,36 @@ export const useDeviceVerificationStatus = (
userId: string,
deviceId: string | undefined
): VerificationStatus => {
const mx = useMatrixClient();
useInvalidateDeviceVerification(crypto);
const { data } = useQuery(deviceVerificationQuery(crypto, userId, deviceId));
return toVerificationStatus(data);
const status = toVerificationStatus(data);
useEffect(() => {
if (!crypto || !deviceId) return;
const deviceKey = `${userId}\x00${deviceId}`;
const statuses = verificationStatuses.get(crypto) ?? new Map<string, VerificationStatus>();
const previous = statuses.get(deviceKey);
statuses.set(deviceKey, status);
verificationStatuses.set(crypto, statuses);
if (previous === VerificationStatus.Verified && status === VerificationStatus.Unverified) {
Sentry.addBreadcrumb({
category: 'crypto',
message: 'Device verification changed to unverified',
level: 'warning',
data: { own_device: userId === mx.getSafeUserId() },
});
Sentry.metrics.count('sable.crypto.device_verification_lost', 1, {
attributes: { own_device: userId === mx.getSafeUserId() },
});
}
}, [crypto, deviceId, mx, status, userId]);
return status;
};
export const useUnverifiedDeviceCount = (
+42
View File
@@ -5,6 +5,13 @@ import type { CryptoApi } from '$types/matrix-sdk';
import { CryptoEvent } from '$types/matrix-sdk';
import { useSessionBackupKeyUsable } from './useKeyBackup';
const sentry = vi.hoisted(() => ({
addBreadcrumb: vi.fn<() => void>(),
metrics: { count: vi.fn<() => void>() },
}));
vi.mock('@sentry/react', () => sentry);
const emitter = new TypedEventEmitter<string, Record<string, (...args: never[]) => void>>();
vi.mock('$hooks/useMatrixClient', () => ({
@@ -28,6 +35,8 @@ const createCrypto = ({ key, version }: CryptoParts) =>
describe('useSessionBackupKeyUsable', () => {
beforeEach(() => {
emitter.removeAllListeners();
sentry.addBreadcrumb.mockClear();
sentry.metrics.count.mockClear();
});
it('reports true when both the key and the backup version are in the store', async () => {
@@ -86,4 +95,37 @@ describe('useSessionBackupKeyUsable', () => {
await waitFor(() => expect(result.current).toBe(true));
});
it('records when an available session backup key is lost', async () => {
const key = vi
.fn<CryptoApi['getSessionBackupPrivateKey']>()
.mockResolvedValueOnce(new Uint8Array([1]))
.mockResolvedValue(null);
const crypto = createCrypto({ key });
const { result } = renderHook(() => useSessionBackupKeyUsable(crypto));
await waitFor(() => expect(result.current).toBe(true));
emitter.emit(CryptoEvent.KeyBackupDecryptionKeyCached as never);
await waitFor(() => expect(result.current).toBe(false));
expect(sentry.metrics.count).toHaveBeenCalledWith('sable.crypto.session_backup_key_lost', 1);
});
it('records when a lookup fails after the backup key was available', async () => {
const key = vi
.fn<CryptoApi['getSessionBackupPrivateKey']>()
.mockResolvedValueOnce(new Uint8Array([1]))
.mockRejectedValue(new Error('store closed'));
const crypto = createCrypto({ key });
const { result } = renderHook(() => useSessionBackupKeyUsable(crypto));
await waitFor(() => expect(result.current).toBe(true));
emitter.emit(CryptoEvent.KeyBackupDecryptionKeyCached as never);
await waitFor(() => expect(result.current).toBeUndefined());
expect(sentry.metrics.count).toHaveBeenCalledWith(
'sable.crypto.session_backup_key_lookup_failed',
1
);
});
});
+27 -2
View File
@@ -74,10 +74,35 @@ export const useSessionBackupKeyUsable = (crypto: CryptoApi): boolean | undefine
Promise.all([crypto.getSessionBackupPrivateKey(), crypto.getActiveSessionBackupVersion()])
.then(([key, version]) => {
// A later lookup already answered; this one is stale.
if (alive() && request === requestRef.current) setUsable(key !== null && version !== null);
if (alive() && request === requestRef.current) {
const nextUsable = key !== null && version !== null;
setUsable((current) => {
if (current === true && !nextUsable) {
Sentry.addBreadcrumb({
category: 'crypto',
message: 'Session backup key became unavailable',
level: 'warning',
});
Sentry.metrics.count('sable.crypto.session_backup_key_lost', 1);
}
return nextUsable;
});
}
})
.catch(() => {
if (alive() && request === requestRef.current) setUsable(undefined);
if (alive() && request === requestRef.current) {
setUsable((current) => {
if (current === true) {
Sentry.addBreadcrumb({
category: 'crypto',
message: 'Session backup key lookup failed',
level: 'warning',
});
Sentry.metrics.count('sable.crypto.session_backup_key_lookup_failed', 1);
}
return undefined;
});
}
});
}, [crypto, alive]);