diff --git a/src/app/components/DeviceVerification.tsx b/src/app/components/DeviceVerification.tsx index f44c640a4..42a4d085e 100644 --- a/src/app/components/DeviceVerification.tsx +++ b/src/app/components/DeviceVerification.tsx @@ -92,13 +92,23 @@ type VerificationStartProps = { onStart: () => Promise; }; function AutoVerificationStart({ onStart }: VerificationStartProps) { + const [error, setError] = useState(); + useEffect(() => { - onStart().catch(() => undefined); + onStart().catch((reason: unknown) => { + const failure = reason instanceof Error ? reason : new Error(String(reason)); + Sentry.captureException(failure, { tags: { flow: 'device-verification-start' } }); + setError(failure); + }); }, [onStart]); return ( - + {error ? ( + {error.message} + ) : ( + + )} ); } diff --git a/src/app/crypto/engineCrypto/EngineCrypto.ts b/src/app/crypto/engineCrypto/EngineCrypto.ts index f5e4c86ae..610bf9d8c 100644 --- a/src/app/crypto/engineCrypto/EngineCrypto.ts +++ b/src/app/crypto/engineCrypto/EngineCrypto.ts @@ -719,21 +719,34 @@ export class EngineCrypto }); } - async onIncomingKeyVerificationRequest(sender: string, transactionId: string): Promise { + async onIncomingKeyVerificationRequest(sender: string, transactionId: string): Promise { const state = (await this.#call('getVerificationRequest', { userId: sender, flowId: transactionId, })) as EngineVerificationState | null; - if (!state) return; + if (!state) return false; const existing = this.#verificationRequests.get(transactionId); if (existing) { existing.apply(state); - return; + return true; } const request = new EngineVerificationRequest(this.#engineCall, state); this.#verificationRequests.set(transactionId, request); this.emit(CryptoEvent.VerificationRequestReceived, request); + return true; + } + + async #retryVerificationRequestWithKeys( + sender: string, + transactionId: string, + event: IToDeviceEvent + ): Promise { + await this.#trackUsers([sender]); + await this.#sendTracked(await this.#call('queryKeysForUsers', { users: [sender] })); + await this.#flushOutgoingRequests(); + await this.#receiveSyncChanges({ toDeviceEvents: [event] }); + await this.onIncomingKeyVerificationRequest(sender, transactionId); } #flushOutgoingRequests(): Promise { @@ -805,11 +818,20 @@ export class EngineCrypto if (transactionId && message.sender) { if (message.type === EventType.KeyVerificationRequest) { // eslint-disable-next-line no-await-in-loop - await this.onIncomingKeyVerificationRequest(message.sender, transactionId); + const handled = await this.onIncomingKeyVerificationRequest( + message.sender, + transactionId + ); + if (!handled) { + // eslint-disable-next-line no-await-in-loop + await this.#retryVerificationRequestWithKeys(message.sender, transactionId, message); + } } else if (message.type === EventType.KeyVerificationDone) { // Rust removes completed requests while consuming the event, so no state snapshot // exists to refresh. Keep the JS request alive long enough to expose Done. this.#verificationRequests.get(transactionId)?.markDone(); + // eslint-disable-next-line no-await-in-loop + await this.#queryOwnKeys(); } else { // Without this the verifier never learns the SAS digits arrived. // eslint-disable-next-line no-await-in-loop @@ -1562,6 +1584,22 @@ export class EngineCrypto await this.#flushOutgoingRequests(); } + async #signOwnDeviceIfNeeded(): Promise { + const status = await this.getDeviceVerificationStatus( + this.#identity.userId, + this.#identity.deviceId + ); + if (status?.crossSigningVerified) return; + + const request = (await this.#call('device.verify', { + userId: this.#identity.userId, + deviceId: this.#identity.deviceId, + })) as OutgoingRequest | null; + if (!request) return; + await sendOutgoingRequest(this.#mx, request); + await this.#queryOwnKeys(); + } + async crossSignDevice(deviceId: string): Promise { await this.#sendTracked( await this.#call('device.verify', { userId: this.#identity.userId, deviceId }) @@ -1602,6 +1640,7 @@ export class EngineCrypto if (!stored && (await this.#mx.secretStorage.hasKey())) { await this.#exportCrossSigningKeysToStorage(); } + await this.#signOwnDeviceIfNeeded(); return; } diff --git a/src/app/crypto/engineCrypto/incomingVerificationRequest.test.ts b/src/app/crypto/engineCrypto/incomingVerificationRequest.test.ts new file mode 100644 index 000000000..6d4152abe --- /dev/null +++ b/src/app/crypto/engineCrypto/incomingVerificationRequest.test.ts @@ -0,0 +1,85 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { CryptoEvent, EventType, type MatrixClient } from '$types/matrix-sdk'; +import { engineInvoke } from '../olmMachine/engineInvoke'; +import { EngineCrypto } from './EngineCrypto'; + +vi.mock('../olmMachine/engineInvoke', () => ({ + engineInvoke: vi.fn<(...args: never[]) => Promise>(), +})); + +const mockInvoke = vi.mocked(engineInvoke); + +const clientSpy = () => { + const authedRequest = vi.fn<(...args: never[]) => Promise>(async () => '{}'); + return { mx: { http: { authedRequest } } as unknown as MatrixClient, authedRequest }; +}; + +const REQUEST_EVENT = { + type: EventType.KeyVerificationRequest, + sender: '@me:e.org', + content: { transaction_id: '$f', from_device: 'OTHER' }, +}; + +const requestState = { + flowId: '$f', + otherUserId: '@me:e.org', + phase: 1, + isSelfVerification: true, +}; + +describe('incoming verification request', () => { + beforeEach(() => mockInvoke.mockReset()); + + it('fetches the sender keys and replays the event when the device is unknown', async () => { + const { mx } = clientSpy(); + let senderKnown = false; + const invoked: string[] = []; + + mockInvoke.mockImplementation(async (_identity, method) => { + invoked.push(method as string); + if (method === 'receiveSyncChanges') { + return [{ type: 3, rawEvent: JSON.stringify(REQUEST_EVENT) }]; + } + if (method === 'queryKeysForUsers') { + senderKnown = true; + return { id: 'q1', type: 1, className: 'KeysQueryRequest', body: '{}' }; + } + if (method === 'getVerificationRequest') return senderKnown ? requestState : null; + return []; + }); + + const crypto = new EngineCrypto(mx, { userId: '@me:e.org', deviceId: 'D' }); + const received = vi.fn(); + crypto.on(CryptoEvent.VerificationRequestReceived, received); + + await crypto.preprocessToDeviceMessages([REQUEST_EVENT as never]); + + expect(invoked.filter((m) => m === 'queryKeysForUsers')).toHaveLength(1); + expect(invoked.filter((m) => m === 'receiveSyncChanges')).toHaveLength(2); + expect(received).toHaveBeenCalledOnce(); + }); + + it('does not replay when the engine already knows the request', async () => { + const { mx } = clientSpy(); + const invoked: string[] = []; + + mockInvoke.mockImplementation(async (_identity, method) => { + invoked.push(method as string); + if (method === 'receiveSyncChanges') { + return [{ type: 3, rawEvent: JSON.stringify(REQUEST_EVENT) }]; + } + if (method === 'getVerificationRequest') return requestState; + return []; + }); + + const crypto = new EngineCrypto(mx, { userId: '@me:e.org', deviceId: 'D' }); + const received = vi.fn(); + crypto.on(CryptoEvent.VerificationRequestReceived, received); + + await crypto.preprocessToDeviceMessages([REQUEST_EVENT as never]); + + expect(invoked).not.toContain('queryKeysForUsers'); + expect(invoked.filter((m) => m === 'receiveSyncChanges')).toHaveLength(1); + expect(received).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/app/crypto/verification/request.ts b/src/app/crypto/verification/request.ts index 70eb65d81..13210664e 100644 --- a/src/app/crypto/verification/request.ts +++ b/src/app/crypto/verification/request.ts @@ -44,6 +44,8 @@ export class EngineVerificationRequest #sasAccepted = false; + #sasWeStarted = false; + constructor(call: EngineCall, state: EngineVerificationState) { super(); this.#call = call; @@ -75,8 +77,14 @@ export class EngineVerificationRequest : undefined; const accepted = (verification as SasState).hasBeenAccepted === true; - const lostTieBreak = wanted === 'Sas' && current === 'Sas' && this.#sasAccepted && !accepted; + const weStarted = (verification as SasState).weStarted === true; + const replaced = + wanted === 'Sas' && + current === 'Sas' && + ((this.#sasAccepted && !accepted) || (this.#sasWeStarted && !weStarted)); + const lostTieBreak = replaced; this.#sasAccepted = wanted === 'Sas' ? accepted : false; + this.#sasWeStarted = wanted === 'Sas' ? weStarted : false; if (current !== wanted || lostTieBreak) { if (wanted === 'Sas') { @@ -118,7 +126,15 @@ export class EngineVerificationRequest 'verificationRequest.state', this.#flow )) as EngineVerificationState | null; - if (!next) return; + if (!next) { + if (this.#state.phase === EnginePhase.Done || this.#state.phase === EnginePhase.Cancelled) { + return; + } + this.#state = { ...this.#state, phase: EnginePhase.Cancelled, isCancelled: true }; + this.#syncVerifier(); + this.emit(VerificationRequestEvent.Change); + return; + } this.#state = next; this.#syncVerifier(); diff --git a/src/app/features/settings/devices/Devices.tsx b/src/app/features/settings/devices/Devices.tsx index 128636784..cbb09bd84 100644 --- a/src/app/features/settings/devices/Devices.tsx +++ b/src/app/features/settings/devices/Devices.tsx @@ -6,6 +6,7 @@ import { useDeviceIds, useDeviceList, useSplitCurrentDevice } from '$hooks/useDe import { useMatrixClient } from '$hooks/useMatrixClient'; import { useDeviceVerificationStatus, + useVerifiedDeviceCount, useUnverifiedDeviceCount, VerificationStatus, } from '$hooks/useDeviceVerificationStatus'; @@ -49,6 +50,7 @@ export function Devices({ requestBack, requestClose }: DevicesProps) { ); const otherDevicesId = useDeviceIds(otherDevices); + const verifiedDeviceCount = useVerifiedDeviceCount(crypto, mx.getSafeUserId(), otherDevicesId); const unverifiedDeviceCount = useUnverifiedDeviceCount( crypto, mx.getSafeUserId(), @@ -111,15 +113,13 @@ export function Devices({ requestBack, requestClose }: DevicesProps) { > {crypto && } - {crossSigningActive && - verificationStatus === VerificationStatus.Unverified && - defaultSecretStorageKeyId && - defaultSecretStorageKeyContent && ( - - )} + {crossSigningActive && verificationStatus === VerificationStatus.Unverified && ( + 0} + /> + )} {crypto && verificationStatus === VerificationStatus.Verified && ( )} diff --git a/src/app/features/settings/devices/Verification.test.tsx b/src/app/features/settings/devices/Verification.test.tsx index afe82c033..34b7c800b 100644 --- a/src/app/features/settings/devices/Verification.test.tsx +++ b/src/app/features/settings/devices/Verification.test.tsx @@ -20,10 +20,15 @@ vi.mock('$components/DeviceVerification', () => ({ const KEY_ID = 'key-id'; const KEY_CONTENT = { algorithm: 'm.secret_storage.v1.aes-hmac-sha2' } as SecretStorageKeyContent; -const renderTile = () => +const renderTile = (props: Record = {}) => render( - + ); @@ -42,6 +47,34 @@ describe('VerifyCurrentDeviceTile', () => { expect(await screen.findByText('device verification dialog')).toBeInTheDocument(); }); + it('offers the device flow when there is no recovery key to fall back on', async () => { + renderTile({ secretStorageKeyId: undefined, secretStorageKeyContent: undefined }); + + expect(screen.getByRole('button', { name: /Verify with Device/i })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Verify Manually/i })).toBeNull(); + expect(screen.getByText(/Verify with another device\./)).toBeInTheDocument(); + }); + + it('does not offer a request nobody can answer when no other device is verified', async () => { + renderTile({ hasVerifiedOtherDevice: false }); + + expect(screen.queryByRole('button', { name: /Verify with Device/i })).toBeNull(); + expect(screen.getByRole('button', { name: /Verify Manually/i })).toBeInTheDocument(); + expect(screen.getByText(/recovery key/i)).toBeInTheDocument(); + }); + + it('says to reset when there is neither a verified device nor a recovery key', async () => { + renderTile({ + hasVerifiedOtherDevice: false, + secretStorageKeyId: undefined, + secretStorageKeyContent: undefined, + }); + + expect(screen.queryByRole('button', { name: /Verify with Device/i })).toBeNull(); + expect(screen.queryByRole('button', { name: /Verify Manually/i })).toBeNull(); + expect(screen.getByText(/reset device verification/i)).toBeInTheDocument(); + }); + it('reports why the request failed instead of silently doing nothing', async () => { requestOwnUserVerification.mockRejectedValue(new Error('no cross-signing identity')); renderTile(); diff --git a/src/app/features/settings/devices/Verification.tsx b/src/app/features/settings/devices/Verification.tsx index fa5722668..c33f4079d 100644 --- a/src/app/features/settings/devices/Verification.tsx +++ b/src/app/features/settings/devices/Verification.tsx @@ -61,7 +61,20 @@ export function VerificationStatusBadge({ ); } -function LearnStartVerificationFromOtherDevice() { +const describeOptions = (canVerifyWithDevice: boolean, canVerifyManually: boolean): string => { + if (canVerifyWithDevice && canVerifyManually) { + return 'Verify with another device or verify manually.'; + } + if (canVerifyWithDevice) return 'Verify with another device.'; + if (canVerifyManually) return 'Verify manually with your recovery key.'; + return 'No verified device and no recovery key: reset device verification to start over.'; +}; + +function LearnStartVerificationFromOtherDevice({ + canVerifyManually, +}: { + canVerifyManually: boolean; +}) { return ( Steps to verify from other device. @@ -77,20 +90,25 @@ function LearnStartVerificationFromOtherDevice() {
  • Initiate verification.
  • - - If you do not have any verified device press the "Verify Manually" button. - + {canVerifyManually && ( + + If you do not have any verified device press the "Verify Manually"{' '} + button. + + )}
    ); } type VerifyCurrentDeviceTileProps = { - secretStorageKeyId: string; - secretStorageKeyContent: SecretStorageKeyContent; + secretStorageKeyId?: string; + secretStorageKeyContent?: SecretStorageKeyContent; + hasVerifiedOtherDevice?: boolean; }; export function VerifyCurrentDeviceTile({ secretStorageKeyId, secretStorageKeyContent, + hasVerifiedOtherDevice = false, }: VerifyCurrentDeviceTileProps) { const mx = useMatrixClient(); const [learnMore, setLearnMore] = useState(false); @@ -113,6 +131,8 @@ export function VerifyCurrentDeviceTile({ setRequestState({ status: AsyncStatus.Idle }); }, []); const requesting = requestState.status === AsyncStatus.Loading; + const canVerifyManually = Boolean(secretStorageKeyId && secretStorageKeyContent); + const canVerifyWithDevice = hasVerifiedOtherDevice; return ( <> @@ -121,44 +141,50 @@ export function VerifyCurrentDeviceTile({ title="Unverified" description={ <> - Verify with another device or verify manually.{' '} + {describeOptions(canVerifyWithDevice, canVerifyManually)}{' '} setLearnMore(!learnMore)}> {learnMore ? 'View Less' : 'Learn More'} } after={ - !manualVerification && ( + !(manualVerification && canVerifyManually) && ( - - + {canVerifyWithDevice && ( + + )} + {canVerifyManually && ( + + )} ) } > - {learnMore && } + {learnMore && ( + + )} {requestState.status === AsyncStatus.Error && ( {requestState.error.message} )} @@ -166,7 +192,7 @@ export function VerifyCurrentDeviceTile({ )} - {manualVerification && ( + {manualVerification && secretStorageKeyId && secretStorageKeyContent && ( { + useInvalidateDeviceVerification(crypto); + + return useQueries({ + queries: devices.map((deviceId) => deviceVerificationQuery(crypto, userId, deviceId)), + combine: (results) => { + if (!crypto) return 0; + if (results.some((result) => result.isPending)) return undefined; + return results.filter((result) => result.data === true).length; + }, + }); +}; + export const useUnverifiedDeviceCount = ( crypto: CryptoApi | undefined, userId: string, diff --git a/tests/e2e/device-verification-entry.spec.ts b/tests/e2e/device-verification-entry.spec.ts new file mode 100644 index 000000000..a4af6227b --- /dev/null +++ b/tests/e2e/device-verification-entry.spec.ts @@ -0,0 +1,87 @@ +import type { Page } from '@playwright/test'; +import { test, expect } from './fixtures/test'; +import { homeserverBaseUrl, PASSWORD, type InjectedSession } from './fixtures/session'; +import { + loginUser, + registerUser, + setAccountData, + type RegisteredUser, +} from './fixtures/continuwuity'; + +const injectSession = async (page: Page, baseUrl: string, user: RegisteredUser): Promise => { + const session: InjectedSession = { + baseUrl, + userId: user.userId, + deviceId: user.deviceId, + accessToken: user.accessToken, + slidingSyncOptIn: false, + }; + await page.addInitScript((injected: InjectedSession) => { + localStorage.setItem('matrixSessions', JSON.stringify([injected])); + localStorage.setItem('matrixActiveSession', JSON.stringify(injected.userId)); + localStorage.setItem('dismissNotice', 'true'); + }, session); +}; + +test.describe('device verification entry points', () => { + test('an unverified session can still start verification with another session', async ({ + browser, + }, testInfo) => { + test.setTimeout(300_000); + const storageStatePath = testInfo.project.use.storageState as string; + const hsBaseUrl = await homeserverBaseUrl(storageStatePath); + const username = `two-device-${testInfo.project.name}-${process.pid}`; + + const first = await registerUser(hsBaseUrl, username, PASSWORD); + await setAccountData(hsBaseUrl, first, 'm.cross_signing.master', { encrypted: {} }); + const second = await loginUser(hsBaseUrl, username, PASSWORD); + + const firstContext = await browser.newContext({ storageState: undefined }); + const firstPage = await firstContext.newPage(); + await injectSession(firstPage, hsBaseUrl, first); + await firstPage.goto('/settings/devices'); + await expect(firstPage.getByText(first.deviceId).first()).toBeVisible({ timeout: 120_000 }); + await expect + .poll( + async () => { + const response = await fetch(`${hsBaseUrl}/_matrix/client/v3/keys/query`, { + method: 'POST', + headers: { Authorization: `Bearer ${first.accessToken}` }, + body: JSON.stringify({ device_keys: { [first.userId]: [] } }), + }); + const body = (await response.json()) as { + device_keys?: Record>; + }; + return Object.keys(body.device_keys?.[first.userId] ?? {}).length; + }, + { timeout: 120_000, intervals: [2_000] } + ) + .toBeGreaterThanOrEqual(1); + + const context = await browser.newContext({ storageState: undefined }); + const page = await context.newPage(); + await injectSession(page, hsBaseUrl, second); + + await page.goto('/settings/devices'); + await expect(page.getByText('Others')).toBeVisible({ timeout: 120_000 }); + await expect(page.getByText(first.deviceId).first()).toBeVisible({ timeout: 120_000 }); + + const otherDeviceTile = page.getByText( + 'Verify device identity and grant access to encrypted messages.', + { exact: true } + ); + await expect(otherDeviceTile).toBeVisible({ timeout: 120_000 }); + + await page + .getByRole('button', { name: 'Verify', exact: true }) + .last() + .click({ timeout: 60_000 }); + + await expect( + firstPage.getByText('Click accept to start the verification process.') + ).toBeVisible({ timeout: 120_000 }); + + await context.close(); + await firstContext.close(); + }); +}); diff --git a/tests/e2e/fixtures/continuwuity.ts b/tests/e2e/fixtures/continuwuity.ts index 45bcdbe5e..08139b2a7 100644 --- a/tests/e2e/fixtures/continuwuity.ts +++ b/tests/e2e/fixtures/continuwuity.ts @@ -88,6 +88,49 @@ export async function registerUser( return { userId: body.user_id, accessToken: body.access_token, deviceId: body.device_id }; } +export async function loginUser( + baseUrl: string, + username: string, + password: string +): Promise { + const response = await fetch(`${baseUrl}/_matrix/client/v3/login`, { + method: 'POST', + body: JSON.stringify({ + type: 'm.login.password', + identifier: { type: 'm.id.user', user: username }, + password, + }), + }); + if (!response.ok) { + throw new Error(`login failed: ${response.status} ${await response.text()}`); + } + const body = (await response.json()) as { + user_id: string; + access_token: string; + device_id: string; + }; + return { userId: body.user_id, accessToken: body.access_token, deviceId: body.device_id }; +} + +export async function setAccountData( + baseUrl: string, + user: RegisteredUser, + type: string, + content: Record +): Promise { + const response = await fetch( + `${baseUrl}/_matrix/client/v3/user/${encodeURIComponent(user.userId)}/account_data/${type}`, + { + method: 'PUT', + headers: { Authorization: `Bearer ${user.accessToken}` }, + body: JSON.stringify(content), + } + ); + if (!response.ok) { + throw new Error(`account data ${type} failed: ${response.status} ${await response.text()}`); + } +} + export async function createRoom( baseUrl: string, token: string,