diff --git a/src/app/hooks/useDeviceVerificationStatus.test.tsx b/src/app/hooks/useDeviceVerificationStatus.test.tsx index 09324b242..3460d1442 100644 --- a/src/app/hooks/useDeviceVerificationStatus.test.tsx +++ b/src/app/hooks/useDeviceVerificationStatus.test.tsx @@ -11,7 +11,7 @@ import { VerificationStatus, } from './useDeviceVerificationStatus'; -const { mockMx, getListenerCount } = vi.hoisted(() => { +const { mockMx, getListenerCount, sentry } = vi.hoisted(() => { const listeners = new Map 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(), diff --git a/src/app/hooks/useDeviceVerificationStatus.ts b/src/app/hooks/useDeviceVerificationStatus.ts index 95db011e9..d14effca0 100644 --- a/src/app/hooks/useDeviceVerificationStatus.ts +++ b/src/app/hooks/useDeviceVerificationStatus.ts @@ -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(); let cryptoIdCounter = 0; +const verificationStatuses = new WeakMap>(); 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(); + 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 = ( diff --git a/src/app/hooks/useKeyBackup.test.tsx b/src/app/hooks/useKeyBackup.test.tsx index 361bf4a6e..9fe397dc0 100644 --- a/src/app/hooks/useKeyBackup.test.tsx +++ b/src/app/hooks/useKeyBackup.test.tsx @@ -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 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() + .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() + .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 + ); + }); }); diff --git a/src/app/hooks/useKeyBackup.ts b/src/app/hooks/useKeyBackup.ts index cd2fedfa9..b8ab47c67 100644 --- a/src/app/hooks/useKeyBackup.ts +++ b/src/app/hooks/useKeyBackup.ts @@ -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]);