fix(crypto): repair SAS emoji timing and in-room verification

This commit is contained in:
Erwan Leboucher committed 2026-08-28 17:51:27 +02:00
1 parent ec5c324656
commit c983a143d7
7 files changed
+495 -11

No files matched your search

+177
View File
@@ -591,4 +591,181 @@ mod tests {
assert_eq!(method_from_code(3), Some(VerificationMethod::ReciprocateV1));
assert_eq!(method_from_code(4), None);
}
mod sas_flow {
use std::collections::BTreeMap;
use matrix_sdk::ruma::api::client::keys::get_keys;
use matrix_sdk::ruma::api::client::sync::sync_events::DeviceLists;
use matrix_sdk::ruma::api::client::to_device::send_event_to_device;
use matrix_sdk::ruma::encryption::DeviceKeys;
use matrix_sdk::ruma::events::AnyToDeviceEvent;
use matrix_sdk::ruma::serde::Raw;
use matrix_sdk_crypto::types::requests::{
AnyIncomingResponse, AnyOutgoingRequest, ToDeviceRequest,
};
use matrix_sdk_crypto::{DecryptionSettings, EncryptionSyncChanges, TrustRequirement};
use super::*;
const USER: &str = "@sable:example.org";
async fn machine(device: &str) -> OlmMachine {
let user = UserId::parse(USER).unwrap();
OlmMachine::new(&user, device.into()).await
}
async fn device_keys(of: &OlmMachine) -> Raw<DeviceKeys> {
for request in of.outgoing_requests().await.unwrap() {
if let AnyOutgoingRequest::KeysUpload(upload) = request.request() {
if let Some(keys) = upload.device_keys.clone() {
return keys;
}
}
}
panic!("machine issued no keys upload");
}
async fn learn_device(learner: &OlmMachine, about: &OlmMachine) {
let user = UserId::parse(USER).unwrap();
let keys = device_keys(about).await;
learner.update_tracked_users([user.as_ref()]).await.unwrap();
let mut response = get_keys::v3::Response::new();
response.device_keys.insert(
user.clone(),
BTreeMap::from([(about.device_id().to_owned(), keys)]),
);
for request in learner.outgoing_requests().await.unwrap() {
if matches!(request.request(), AnyOutgoingRequest::KeysQuery(_)) {
learner
.mark_request_as_sent(
request.request_id(),
AnyIncomingResponse::KeysQuery(&response),
)
.await
.unwrap();
return;
}
}
panic!("machine issued no keys query");
}
fn as_events(sender: &UserId, request: &ToDeviceRequest) -> Vec<Raw<AnyToDeviceEvent>> {
let mut events = Vec::new();
for devices in request.messages.values() {
for content in devices.values() {
let event = json!({
"sender": sender,
"type": request.event_type.to_string(),
"content": content,
});
events.push(Raw::new(&event).unwrap().cast_unchecked());
}
}
events
}
async fn deliver(to: &OlmMachine, events: Vec<Raw<AnyToDeviceEvent>>) {
let device_lists = DeviceLists::new();
let counts = BTreeMap::new();
let settings = DecryptionSettings {
sender_device_trust_requirement: TrustRequirement::Untrusted,
};
to.receive_sync_changes(
EncryptionSyncChanges {
to_device_events: events,
changed_devices: &device_lists,
one_time_keys_counts: &counts,
unused_fallback_keys: None,
next_batch_token: None,
},
&settings,
)
.await
.unwrap();
}
async fn send_one(
from: &OlmMachine,
to: &OlmMachine,
request: OutgoingVerificationRequest,
) {
match request {
OutgoingVerificationRequest::ToDevice(request) => {
deliver(to, as_events(from.user_id(), &request)).await;
}
OutgoingVerificationRequest::InRoom(_) => panic!("expected a to-device request"),
}
}
async fn pump(from: &OlmMachine, to: &OlmMachine) {
for request in from.outgoing_requests().await.unwrap() {
if let AnyOutgoingRequest::ToDeviceRequest(to_device) = request.request() {
deliver(to, as_events(from.user_id(), to_device)).await;
from.mark_request_as_sent(
request.request_id(),
AnyIncomingResponse::ToDevice(&send_event_to_device::v3::Response::new()),
)
.await
.unwrap();
}
}
}
fn emoji_of(machine: &OlmMachine, flow_id: &str) -> Value {
let user = UserId::parse(USER).unwrap();
let request = machine.get_verification_request(&user, flow_id).unwrap();
request_state(&request)["verification"]["emoji"].clone()
}
#[tokio::test]
async fn emoji_appear_only_once_our_own_key_is_acked() {
let alice = machine("DEVICEA").await;
let bob = machine("DEVICEB").await;
learn_device(&alice, &bob).await;
learn_device(&bob, &alice).await;
let user = UserId::parse(USER).unwrap();
let bob_device = alice
.get_device(&user, "DEVICEB".into(), None)
.await
.unwrap()
.expect("alice should know bob's device");
let (alice_request, outgoing) = bob_device.request_verification();
send_one(&alice, &bob, outgoing).await;
let flow_id = alice_request.flow_id().as_str().to_owned();
let bob_request = bob.get_verification_request(&user, &flow_id).unwrap();
send_one(&bob, &alice, bob_request.accept().unwrap()).await;
let (_, start) = alice_request.start_sas().await.unwrap().unwrap();
send_one(&alice, &bob, start).await;
let bob_sas = bob
.get_verification(&user, &flow_id)
.unwrap()
.sas_v1()
.unwrap();
send_one(&bob, &alice, bob_sas.accept().unwrap()).await;
pump(&alice, &bob).await;
assert!(
emoji_of(&bob, &flow_id).is_null(),
"the peer's key alone must not expose emoji"
);
pump(&bob, &alice).await;
assert!(
!emoji_of(&bob, &flow_id).is_null(),
"responder must have emoji once its own key is acked"
);
assert!(
!emoji_of(&alice, &flow_id).is_null(),
"initiator must have emoji once the responder's key arrives"
);
}
}
}
+146 -7
View File
@@ -7,9 +7,13 @@ import {
encodeRecoveryKey,
EventType,
ImportRoomKeyStage,
KnownMembership,
MatrixEventEvent,
MsgType,
UserVerificationStatus,
VerificationMethod,
} from '$types/matrix-sdk';
import { isVerificationEvent } from 'matrix-js-sdk/lib/rust-crypto/verification';
import { Device, DeviceVerification } from 'matrix-js-sdk/lib/models/device';
import { getHttpUriForMxc } from 'matrix-js-sdk/lib/content-repo';
import * as RustSdkCryptoJs from '@matrix-org/matrix-sdk-crypto-wasm';
@@ -65,6 +69,7 @@ import type {
MatrixEvent,
OwnDeviceKeys,
Room,
RoomMember,
SecretStorageStatus,
StartDehydrationOpts,
VerificationRequest,
@@ -72,6 +77,8 @@ import type {
const engineCryptoLog = createDebugLogger('engine-crypto');
const DECRYPTION_WAIT_MS = 5 * 60 * 1000;
/** js-sdk keeps this union private to its own rust-crypto module; derived the same way. */
type CryptoEvents = (typeof CryptoEvent)[keyof typeof CryptoEvent];
@@ -244,6 +251,8 @@ export class EngineCrypto
/** Live requests, keyed by flow id, so the synchronous CryptoApi getters can answer. */
readonly #verificationRequests = new Map<string, EngineVerificationRequest>();
#flushing: Promise<void> = Promise.resolve();
constructor(mx: MatrixClient, identity: EngineIdentity) {
super();
this.#mx = mx;
@@ -349,6 +358,100 @@ export class EngineCrypto
return request;
}
async onLiveEventFromSync(event: MatrixEvent): Promise<void> {
if (event.isState() || event.getUnsigned().transaction_id) return;
const handle = async (candidate: MatrixEvent): Promise<void> => {
if (isVerificationEvent(candidate)) await this.onKeyVerificationEvent(candidate);
};
if (event.isDecryptionFailure() || event.isEncrypted()) {
let timeoutId: ReturnType<typeof setTimeout>;
const onDecrypted = (decrypted: MatrixEvent, error?: Error) => {
if (error) return;
clearTimeout(timeoutId);
event.off(MatrixEventEvent.Decrypted, onDecrypted);
void handle(decrypted);
};
timeoutId = setTimeout(() => {
event.off(MatrixEventEvent.Decrypted, onDecrypted);
}, DECRYPTION_WAIT_MS);
event.on(MatrixEventEvent.Decrypted, onDecrypted);
return;
}
await handle(event);
}
async onKeyVerificationEvent(event: MatrixEvent): Promise<void> {
const roomId = event.getRoomId();
const senderId = event.getSender();
const eventId = event.getId();
if (!roomId || !senderId || !eventId) return;
const content = event.getContent();
const isRequest =
event.getType() === EventType.RoomMessage &&
content.msgtype === MsgType.KeyVerificationRequest;
if (isRequest) {
await this.#sendTracked(await this.#call('queryKeysForUsers', { users: [senderId] }));
}
await this.#call('receiveVerificationEvent', {
roomId,
event: JSON.stringify({
event_id: eventId,
type: event.getType(),
sender: senderId,
state_key: event.getStateKey(),
content,
origin_server_ts: event.getTs(),
}),
});
if (isRequest) {
await this.onIncomingKeyVerificationRequest(senderId, eventId);
} else {
const flowId = (content['m.relates_to'] as { event_id?: string } | undefined)?.event_id;
if (flowId) await this.#verificationRequests.get(flowId)?.refresh();
}
await this.#flushOutgoingRequests();
}
onRoomStateEvent(event: MatrixEvent): void {
if (event.getType() !== EventType.RoomMember) return;
if (
event.getStateKey() !== this.#identity.userId &&
event.getContent().membership !== KnownMembership.Join
) {
void this.forceDiscardSession(event.getRoomId() ?? '');
}
}
onRoomMembership(event: MatrixEvent, member: RoomMember, oldMembership?: string): void {
const roomId = event.getRoomId();
if (!roomId) return;
if (
oldMembership === KnownMembership.Join &&
member.membership !== KnownMembership.Join &&
member.userId === this.#identity.userId
) {
void this.#call('clearRoomPendingKeyBundle', { roomId });
}
}
async #sendTracked(request: unknown): Promise<void> {
if (!isOutgoingRequest(request)) return;
const response = await sendOutgoingRequest(this.#mx, request);
await this.#call('markRequestAsSent', {
requestId: request.id,
requestType: request.type,
response,
});
}
async onIncomingKeyVerificationRequest(sender: string, transactionId: string): Promise<void> {
const state = (await this.#call('getVerificationRequest', {
userId: sender,
@@ -366,9 +469,14 @@ export class EngineCrypto
this.emit(CryptoEvent.VerificationRequestReceived, request);
}
#flushOutgoingRequests(): Promise<void> {
this.#flushing = this.#flushing.then(() => this.#drainOutgoingRequests());
return this.#flushing;
}
/** matrix-sdk-crypto only clears a request once told it was sent, so a failure here
* leaves it queued for the next drain rather than losing it. */
async #flushOutgoingRequests(): Promise<void> {
async #drainOutgoingRequests(): Promise<void> {
if (this.#stopped) return;
const requests = ((await this.#call('outgoingRequests')) ?? []) as OutgoingRequest[];
@@ -396,15 +504,30 @@ export class EngineCrypto
const processed = await this.#receiveSyncChanges({ toDeviceEvents: events });
const received: ReceivedToDeviceMessage[] = [];
for (const event of processed) {
const message = JSON.parse(event.rawEvent) as IToDeviceEvent;
const messages = processed.map(
(event) => [event, JSON.parse(event.rawEvent) as IToDeviceEvent] as const
);
if (
messages.some(
([, message]) =>
typeof message.type === 'string' && message.type.startsWith('m.key.verification.')
)
) {
await this.#flushOutgoingRequests();
}
for (const [event, message] of messages) {
if (typeof message.type === 'string' && message.type.startsWith('m.key.verification.')) {
const transactionId = (message.content as { transaction_id?: string })?.transaction_id;
if (transactionId && message.sender) {
if (message.type === EventType.KeyVerificationRequest) {
// eslint-disable-next-line no-await-in-loop
await this.onIncomingKeyVerificationRequest(message.sender, transactionId);
} 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();
} else {
// Without this the verifier never learns the SAS digits arrived.
// eslint-disable-next-line no-await-in-loop
@@ -444,9 +567,22 @@ export class EngineCrypto
}
async onCryptoEvent(room: Room, event: MatrixEvent): Promise<void> {
engineCryptoLog.debug('general', 'Room encryption configured', {
const config = event.getContent();
if (config.algorithm !== 'm.megolm.v1.aes-sha2') {
engineCryptoLog.warn('general', 'Ignoring encryption event with invalid algorithm', {
roomId: room.roomId,
algorithm: config.algorithm,
});
return;
}
await this.#call('setRoomSettings', {
roomId: room.roomId,
algorithm: event.getContent().algorithm,
settings: {
algorithm: config.algorithm,
sessionRotationPeriodMs: config.rotation_period_ms,
sessionRotationPeriodMessages: config.rotation_period_msgs,
},
});
}
@@ -1032,7 +1168,7 @@ export class EngineCrypto
const started = (await this.#call('userIdentity.requestVerificationDm', {
userId,
roomId,
eventId,
requestEventId: eventId,
methods: SUPPORTED_VERIFICATION_METHOD_CODES,
})) as { request: EngineVerificationState; outgoingRequest?: unknown };
@@ -1040,7 +1176,10 @@ export class EngineCrypto
await sendOutgoingRequest(this.#mx, started.outgoingRequest);
}
await this.#flushOutgoingRequests();
return new EngineVerificationRequest(this.#engineCall, started.request);
const request = new EngineVerificationRequest(this.#engineCall, started.request);
this.#verificationRequests.set(started.request.flowId, request);
return request;
}
async requestOwnUserVerification(): Promise<VerificationRequest> {
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { MatrixClient } from '$types/matrix-sdk';
import { VerificationPhase, EventType, type MatrixClient } from '$types/matrix-sdk';
import { engineInvoke } from '../olmMachine/engineInvoke';
import { EngineCrypto } from './EngineCrypto';
@@ -100,4 +100,122 @@ describe('verification outgoing requests', () => {
);
expect(verificationCalls).toEqual([]);
});
it('completes a request when the engine consumes the final done event', async () => {
const { mx } = clientSpy();
mockInvoke.mockImplementation(async (_identity, method) => {
if (method === 'device.requestVerification') {
return {
request: {
flowId: '$f',
otherUserId: '@them:e.org',
phase: 3,
verification: { className: 'Sas' },
},
};
}
if (method === 'receiveSyncChanges') {
return [
{
type: 3,
rawEvent: JSON.stringify({
type: EventType.KeyVerificationDone,
sender: '@them:e.org',
content: { transaction_id: '$f' },
}),
},
];
}
if (method === 'verificationRequest.state') {
throw new Error('verificationRequest.state: no verification request');
}
return [];
});
const crypto = new EngineCrypto(mx, { userId: '@me:e.org', deviceId: 'D' });
const request = await crypto.requestDeviceVerification('@them:e.org', 'THEIRS');
await expect(
crypto.preprocessToDeviceMessages([
{
type: EventType.KeyVerificationDone,
sender: '@them:e.org',
content: { transaction_id: '$f' },
} as never,
])
).resolves.toEqual([]);
expect(request.phase).toBe(VerificationPhase.Done);
});
it('drains the outgoing queue before re-reading the SAS snapshot', async () => {
const authedRequest = vi.fn<(...args: never[]) => Promise<string>>(
async () =>
new Promise((resolve) => {
setTimeout(() => resolve('{}'), 5);
})
);
const mx = { http: { authedRequest } } as unknown as MatrixClient;
let peerKeyReceived = false;
let ourKeyAcked = false;
mockInvoke.mockImplementation(async (_identity, method) => {
if (method === 'device.requestVerification') {
return {
request: {
flowId: '$f',
otherUserId: '@them:e.org',
phase: 3,
verification: { className: 'Sas' },
},
};
}
if (method === 'receiveSyncChanges') {
peerKeyReceived = true;
return [
{
type: 3,
rawEvent: JSON.stringify({
type: 'm.key.verification.key',
sender: '@them:e.org',
content: { transaction_id: '$f' },
}),
},
];
}
if (method === 'outgoingRequests') {
return peerKeyReceived
? [{ id: 'k', type: 3, body: '{}', event_type: 'm.key.verification.key', txn_id: 'k' }]
: [];
}
if (method === 'markRequestAsSent') {
ourKeyAcked = true;
return null;
}
if (method === 'verificationRequest.state') {
return {
flowId: '$f',
otherUserId: '@them:e.org',
phase: 3,
verification: {
className: 'Sas',
emoji: ourKeyAcked ? [{ symbol: '🌏', description: 'Globe' }] : null,
},
};
}
return [];
});
const crypto = new EngineCrypto(mx, { userId: '@me:e.org', deviceId: 'D' });
const request = await crypto.requestDeviceVerification('@them:e.org', 'THEIRS');
await crypto.preprocessToDeviceMessages([
{
type: 'm.key.verification.key',
sender: '@them:e.org',
content: { transaction_id: '$f' },
} as never,
]);
expect(request.verifier?.getShowSasCallbacks()?.sas.emoji).toEqual([['🌏', 'Globe']]);
});
});
+26 -1
View File
@@ -1,7 +1,8 @@
import { CryptoEvent } from 'matrix-js-sdk/lib/crypto-api';
import { ReEmitter } from 'matrix-js-sdk/lib/ReEmitter';
import { isTauri } from '@tauri-apps/api/core';
import type { MatrixClient } from '$types/matrix-sdk';
import { ClientEvent, RoomMemberEvent, RoomStateEvent } from '$types/matrix-sdk';
import type { MatrixClient, MatrixEvent, RoomMember } from '$types/matrix-sdk';
import { createDebugLogger } from '$utils/debugLogger';
import { engineOpen } from '$generated/tauri/commands';
import * as RustSdkCryptoJs from '@matrix-org/matrix-sdk-crypto-wasm';
@@ -72,6 +73,28 @@ export const reEmitCryptoEvents = (mx: MatrixClient, crypto: EngineCrypto): (()
return () => reEmitter.stopReEmitting(crypto, REEMITTED_CRYPTO_EVENTS);
};
export const wireCryptoClientEvents = (mx: MatrixClient, crypto: EngineCrypto): (() => void) => {
const onLiveEvent = (event: MatrixEvent) => {
void crypto.onLiveEventFromSync(event);
};
const onMembership = (event: MatrixEvent, member: RoomMember, oldMembership?: string) => {
crypto.onRoomMembership(event, member, oldMembership);
};
const onStateEvent = (event: MatrixEvent) => {
crypto.onRoomStateEvent(event);
};
mx.on(ClientEvent.Event, onLiveEvent);
mx.on(RoomMemberEvent.Membership, onMembership);
mx.on(RoomStateEvent.Events, onStateEvent);
return () => {
mx.removeListener(ClientEvent.Event, onLiveEvent);
mx.removeListener(RoomMemberEvent.Membership, onMembership);
mx.removeListener(RoomStateEvent.Events, onStateEvent);
};
};
export const installRustCrypto = async (
mx: MatrixClient,
options: { storeDir?: string; passphrase?: string } = {}
@@ -98,11 +121,13 @@ export const installRustCrypto = async (
// `MatrixClient.initRustCrypto` normally wires these events to the client. The native
// engine is installed independently, so reproduce that SDK initialization step here.
const stopReEmittingCryptoEvents = reEmitCryptoEvents(mx, engineCrypto);
const stopClientEvents = wireCryptoClientEvents(mx, engineCrypto);
const stopEventBridge = await startCryptoEventBridge(engineCrypto, identity);
const stopEngineCrypto = engineCrypto.stop.bind(engineCrypto);
engineCrypto.stop = () => {
stopReEmittingCryptoEvents();
stopClientEvents();
stopEventBridge();
stopEngineCrypto();
};
+17 -1
View File
@@ -57,7 +57,8 @@ export class EngineVerificationRequest
#syncVerifier(): void {
const verification = this.#state.verification;
if (!verification) {
this.#verifier = undefined;
if (this.#state.phase === EnginePhase.Done) this.#verifier?.settle(true);
else if (this.#state.phase === EnginePhase.Cancelled) this.#verifier?.settle(false);
return;
}
@@ -105,6 +106,19 @@ export class EngineVerificationRequest
this.emit(VerificationRequestEvent.Change);
}
markDone(): void {
this.#state = {
...this.#state,
phase: EnginePhase.Done,
isDone: true,
verification: this.#state.verification
? { ...this.#state.verification, isDone: true }
: this.#state.verification,
};
this.#syncVerifier();
this.emit(VerificationRequestEvent.Change);
}
get transactionId(): string | undefined {
return this.#state.flowId;
}
@@ -191,6 +205,7 @@ export class EngineVerificationRequest
} finally {
this.#accepting = false;
}
this.emit(VerificationRequestEvent.Change);
}
async cancel(params?: { reason?: string; code?: string }): Promise<void> {
@@ -201,6 +216,7 @@ export class EngineVerificationRequest
} finally {
this.#declining = false;
}
this.emit(VerificationRequestEvent.Change);
}
async startVerification(method: string): Promise<Verifier> {
+1 -1
View File
@@ -47,7 +47,7 @@ export type EngineVerificationState = {
theirSupportedMethods?: number[] | null;
ourSupportedMethods?: number[] | null;
cancelInfo?: EngineCancelInfo | null;
verification?: { className?: string } | null;
verification?: { className?: string; isDone?: boolean } | null;
};
export const methodFromCode = (code: number): string | undefined => METHOD_BY_CODE[code];
+9
View File
@@ -91,6 +91,15 @@ abstract class EngineVerifier<TState>
this.#cancelled = true;
}
settle(done: boolean): void {
if (done) {
this.completion.resolve();
return;
}
this.markCancelled();
this.completion.reject(new Error('Verification cancelled'));
}
abstract onChange(state: TState): void;
abstract get verificationPhase(): VerificationPhase;