mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-26 03:46:25 -08:00
test(crypto): port upstream's request, encryption and cross-signing cases
This commit is contained in:
9 files changed
+333
-12
No files matched your search
@@ -330,10 +330,42 @@ pub async fn invoke(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::timeout;
|
||||
use super::{invoke, timeout};
|
||||
use matrix_sdk_crypto::OlmMachine;
|
||||
use serde_json::json;
|
||||
use std::time::Duration;
|
||||
|
||||
async fn machine() -> OlmMachine {
|
||||
let user: &matrix_sdk::ruma::UserId = "@me:example.org".try_into().unwrap();
|
||||
OlmMachine::new(user, "MYDEVICE".into()).await
|
||||
}
|
||||
|
||||
/// Returning success for a device we do not know lets the UI report that a device was
|
||||
/// verified or cross-signed when nothing was signed at all.
|
||||
#[tokio::test]
|
||||
async fn verifying_an_unknown_device_is_an_error() {
|
||||
let machine = machine().await;
|
||||
let args = json!({ "userId": "@me:example.org", "deviceId": "NOSUCHDEVICE" });
|
||||
|
||||
let result = invoke(&machine, "device.verify", &args).await;
|
||||
|
||||
assert!(matches!(result, Some(Err(_))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn trusting_an_unknown_device_is_an_error() {
|
||||
let machine = machine().await;
|
||||
let args = json!({
|
||||
"userId": "@me:example.org",
|
||||
"deviceId": "NOSUCHDEVICE",
|
||||
"trustState": 1,
|
||||
});
|
||||
|
||||
let result = invoke(&machine, "device.setLocalTrust", &args).await;
|
||||
|
||||
assert!(matches!(result, Some(Err(_))));
|
||||
}
|
||||
|
||||
/// `timeoutSecs` arrives verbatim from the webview, and `Duration::from_secs_f64`
|
||||
/// panics on negative, non-finite or overflowing values.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk';
|
||||
import { engineInvoke } from '../olmMachine/engineInvoke';
|
||||
import { EngineCrypto } from './EngineCrypto';
|
||||
|
||||
vi.mock('../olmMachine/engineInvoke', () => ({ engineInvoke: vi.fn() }));
|
||||
|
||||
const mockInvoke = vi.mocked(engineInvoke);
|
||||
|
||||
const room = (roomId: string) =>
|
||||
({
|
||||
roomId,
|
||||
getEncryptionTargetMembers: async () => [{ userId: '@them:e.org' }],
|
||||
getHistoryVisibility: () => 'shared',
|
||||
getBlacklistUnverifiedDevices: () => false,
|
||||
currentState: { getStateEvents: () => null },
|
||||
}) as unknown as Room;
|
||||
|
||||
const event = () =>
|
||||
({
|
||||
getType: () => 'm.room.message',
|
||||
getContent: () => ({}),
|
||||
makeEncrypted: vi.fn(),
|
||||
getTxnId: () => 't',
|
||||
}) as unknown as MatrixEvent;
|
||||
|
||||
const client = () =>
|
||||
({ http: { authedRequest: vi.fn(async () => '{}') } }) as unknown as MatrixClient;
|
||||
|
||||
describe('key claim serialisation', () => {
|
||||
it('never claims keys for two rooms at the same time', async () => {
|
||||
const marks: string[] = [];
|
||||
let inFlight = 0;
|
||||
|
||||
mockInvoke.mockImplementation(async (_identity, method) => {
|
||||
if (method === 'getMissingSessions') {
|
||||
inFlight += 1;
|
||||
marks.push(`enter${inFlight}`);
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, 0);
|
||||
});
|
||||
inFlight -= 1;
|
||||
marks.push('exit');
|
||||
return null;
|
||||
}
|
||||
if (method === 'encryptRoomEvent') return '{}';
|
||||
if (method === 'identityKeys') return { ed25519: 'e', curve25519: 'c' };
|
||||
return null;
|
||||
});
|
||||
|
||||
const crypto = new EngineCrypto(client(), { userId: '@me:e.org', deviceId: 'D' });
|
||||
|
||||
await Promise.all([
|
||||
crypto.encryptEvent(event(), room('!a:e.org')),
|
||||
crypto.encryptEvent(event(), room('!b:e.org')),
|
||||
]);
|
||||
|
||||
expect(marks).toEqual(['enter1', 'exit', 'enter1', 'exit']);
|
||||
});
|
||||
|
||||
it('claims keys for every encryption target member', async () => {
|
||||
mockInvoke.mockImplementation(async (_identity, method) => {
|
||||
if (method === 'encryptRoomEvent') return '{}';
|
||||
if (method === 'identityKeys') return { ed25519: 'e', curve25519: 'c' };
|
||||
return null;
|
||||
});
|
||||
|
||||
const crypto = new EngineCrypto(client(), { userId: '@me:e.org', deviceId: 'D' });
|
||||
await crypto.encryptEvent(event(), room('!a:e.org'));
|
||||
|
||||
const args = mockInvoke.mock.calls.find(([, method]) => method === 'getMissingSessions')?.[2];
|
||||
expect(args).toEqual({ users: ['@them:e.org'] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import { engineInvoke } from '../olmMachine/engineInvoke';
|
||||
import { EngineCrypto } from './EngineCrypto';
|
||||
|
||||
vi.mock('../olmMachine/engineInvoke', () => ({ engineInvoke: vi.fn() }));
|
||||
|
||||
const mockInvoke = vi.mocked(engineInvoke);
|
||||
|
||||
const invoked = (method: string) => mockInvoke.mock.calls.filter(([, called]) => called === method);
|
||||
|
||||
const crypto = () =>
|
||||
new EngineCrypto(
|
||||
{ http: { authedRequest: vi.fn(async () => '{}') } } as unknown as MatrixClient,
|
||||
{
|
||||
userId: '@me:e.org',
|
||||
deviceId: 'D',
|
||||
}
|
||||
);
|
||||
|
||||
describe('userHasCrossSigningKeys', () => {
|
||||
beforeEach(() => mockInvoke.mockReset());
|
||||
|
||||
// Answering false from a stale store makes callers rotate our cross-signing keys and
|
||||
// invalidate every existing verification, so our own identity is always refreshed.
|
||||
it('refreshes keys/query before answering for our own user', async () => {
|
||||
mockInvoke.mockImplementation(async (_identity, method) => {
|
||||
if (method === 'queryKeysForUsers') return { id: 'q1', type: 1, body: '{}' };
|
||||
if (method === 'getIdentity') return { isVerified: false };
|
||||
return null;
|
||||
});
|
||||
|
||||
await expect(crypto().userHasCrossSigningKeys()).resolves.toBe(true);
|
||||
|
||||
const order = mockInvoke.mock.calls.map(([, method]) => method);
|
||||
expect(order.indexOf('queryKeysForUsers')).toBeLessThan(order.indexOf('getIdentity'));
|
||||
expect(invoked('queryKeysForUsers')[0]?.[2]).toMatchObject({ users: ['@me:e.org'] });
|
||||
});
|
||||
|
||||
it('reports no identity for our own user only after a successful refresh', async () => {
|
||||
mockInvoke.mockImplementation(async (_identity, method) => {
|
||||
if (method === 'queryKeysForUsers') return null;
|
||||
if (method === 'getIdentity') return null;
|
||||
return null;
|
||||
});
|
||||
|
||||
await expect(crypto().userHasCrossSigningKeys()).resolves.toBe(false);
|
||||
expect(invoked('queryKeysForUsers')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('does not query for another user unless asked to', async () => {
|
||||
mockInvoke.mockImplementation(async (_identity, method) =>
|
||||
method === 'getIdentity' ? null : null
|
||||
);
|
||||
|
||||
await expect(crypto().userHasCrossSigningKeys('@them:e.org')).resolves.toBe(false);
|
||||
expect(invoked('queryKeysForUsers')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('queries for another user when downloadUncached is set', async () => {
|
||||
mockInvoke.mockImplementation(async (_identity, method) => {
|
||||
if (method === 'queryKeysForUsers') return { id: 'q1', type: 1, body: '{}' };
|
||||
if (method === 'getIdentity') return { isVerified: false };
|
||||
return null;
|
||||
});
|
||||
|
||||
await expect(crypto().userHasCrossSigningKeys('@them:e.org', true)).resolves.toBe(true);
|
||||
expect(invoked('queryKeysForUsers')[0]?.[2]).toMatchObject({ users: ['@them:e.org'] });
|
||||
});
|
||||
});
|
||||
@@ -7,10 +7,13 @@ vi.mock('../olmMachine/engineInvoke', () => ({ engineInvoke: vi.fn() }));
|
||||
|
||||
const mockInvoke = vi.mocked(engineInvoke);
|
||||
|
||||
const room = (roomId: string) =>
|
||||
const room = (roomId: string, onMembers?: () => void) =>
|
||||
({
|
||||
roomId,
|
||||
getEncryptionTargetMembers: async () => [{ userId: '@me:e.org' }],
|
||||
getEncryptionTargetMembers: async () => {
|
||||
onMembers?.();
|
||||
return [{ userId: '@me:e.org' }];
|
||||
},
|
||||
getHistoryVisibility: () => 'shared',
|
||||
getBlacklistUnverifiedDevices: () => false,
|
||||
currentState: { getStateEvents: () => null },
|
||||
@@ -25,6 +28,44 @@ const event = () =>
|
||||
}) as unknown as MatrixEvent;
|
||||
|
||||
describe('encryptEvent ordering', () => {
|
||||
// element-web#26684: an edit must not overtake the message it edits. Looking members up
|
||||
// outside the per-room chain reintroduces that race while keeping mutual exclusion.
|
||||
it('does not look up members for the next event until the previous one is encrypted', async () => {
|
||||
let lookups = 0;
|
||||
let release: (() => void) | undefined;
|
||||
const held = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
|
||||
mockInvoke.mockImplementation(async (_identity, method) => {
|
||||
if (method === 'encryptRoomEvent') {
|
||||
await held;
|
||||
return '{}';
|
||||
}
|
||||
if (method === 'identityKeys') return { ed25519: 'e', curve25519: 'c' };
|
||||
return null;
|
||||
});
|
||||
|
||||
const mx = { http: { authedRequest: vi.fn() } } as unknown as MatrixClient;
|
||||
const crypto = new EngineCrypto(mx, { userId: '@me:e.org', deviceId: 'D' });
|
||||
const target = room('!r:e.org', () => {
|
||||
lookups += 1;
|
||||
});
|
||||
|
||||
const both = Promise.all([
|
||||
crypto.encryptEvent(event(), target),
|
||||
crypto.encryptEvent(event(), target),
|
||||
]);
|
||||
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(lookups).toBe(1);
|
||||
|
||||
release?.();
|
||||
await both;
|
||||
expect(lookups).toBe(2);
|
||||
});
|
||||
|
||||
it('never runs two encryptions for a room at the same time', async () => {
|
||||
const marks: string[] = [];
|
||||
let inFlight = 0;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { Method } from 'matrix-js-sdk/lib/http-api';
|
||||
import { ConnectionError, MatrixError, Method } from 'matrix-js-sdk/lib/http-api';
|
||||
import { sleep } from 'matrix-js-sdk/lib/utils';
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import { RequestType, sendOutgoingRequest } from './outgoing';
|
||||
|
||||
@@ -8,11 +9,14 @@ vi.mock('matrix-js-sdk/lib/utils', async (importOriginal) => ({
|
||||
sleep: vi.fn(async () => undefined),
|
||||
}));
|
||||
|
||||
const rateLimited = () =>
|
||||
Object.assign(new Error('rate limited'), {
|
||||
httpStatus: 429,
|
||||
data: { errcode: 'M_LIMIT_EXCEEDED', retry_after_ms: 10 },
|
||||
});
|
||||
const rateLimited = (retryAfterMs = 10) =>
|
||||
new MatrixError(
|
||||
{ errcode: 'M_LIMIT_EXCEEDED', error: 'Too many requests', retry_after_ms: retryAfterMs },
|
||||
429
|
||||
);
|
||||
|
||||
const clientWith = (authedRequest: unknown) =>
|
||||
({ http: { authedRequest } }) as unknown as MatrixClient;
|
||||
|
||||
const request = { id: 'r1', type: RequestType.KeysClaim, body: '{}' };
|
||||
|
||||
@@ -31,6 +35,54 @@ describe('sendOutgoingRequest', () => {
|
||||
expect(authedRequest.mock.calls[0]?.[0]).toBe(Method.Post);
|
||||
});
|
||||
|
||||
it('waits as long as the server asks after a rate limit', async () => {
|
||||
const authedRequest = vi
|
||||
.fn<(...args: never[]) => Promise<string>>()
|
||||
.mockRejectedValueOnce(rateLimited(5000))
|
||||
.mockResolvedValueOnce('{}');
|
||||
|
||||
await sendOutgoingRequest(clientWith(authedRequest), request);
|
||||
|
||||
expect(vi.mocked(sleep)).toHaveBeenCalledWith(5000);
|
||||
});
|
||||
|
||||
it('gives up after five attempts on a persistent server error', async () => {
|
||||
const authedRequest = vi
|
||||
.fn<(...args: never[]) => Promise<string>>()
|
||||
.mockRejectedValue(new MatrixError({ errcode: 'M_UNKNOWN', error: 'boom' }, 500));
|
||||
|
||||
await expect(sendOutgoingRequest(clientWith(authedRequest), request)).rejects.toThrow();
|
||||
expect(authedRequest).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
|
||||
it('does not retry a request the server says is too large', async () => {
|
||||
const authedRequest = vi
|
||||
.fn<(...args: never[]) => Promise<string>>()
|
||||
.mockRejectedValue(new MatrixError({ errcode: 'M_TOO_LARGE', error: 'too big' }, 502));
|
||||
|
||||
await expect(sendOutgoingRequest(clientWith(authedRequest), request)).rejects.toThrow();
|
||||
expect(authedRequest).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not retry a request we aborted ourselves', async () => {
|
||||
const authedRequest = vi
|
||||
.fn<(...args: never[]) => Promise<string>>()
|
||||
.mockRejectedValue(Object.assign(new Error('aborted'), { name: 'AbortError' }));
|
||||
|
||||
await expect(sendOutgoingRequest(clientWith(authedRequest), request)).rejects.toThrow();
|
||||
expect(authedRequest).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('retries after a connection error', async () => {
|
||||
const authedRequest = vi
|
||||
.fn<(...args: never[]) => Promise<string>>()
|
||||
.mockRejectedValueOnce(new ConnectionError('Failed to fetch'))
|
||||
.mockResolvedValueOnce('{}');
|
||||
|
||||
await expect(sendOutgoingRequest(clientWith(authedRequest), request)).resolves.toBe('{}');
|
||||
expect(authedRequest).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('rethrows an error that is not worth retrying', async () => {
|
||||
const authedRequest = vi
|
||||
.fn<(...args: never[]) => Promise<string>>()
|
||||
|
||||
@@ -30,6 +30,50 @@ const state = (patch: Partial<EngineVerificationState> = {}): EngineVerification
|
||||
});
|
||||
|
||||
describe('EngineVerificationRequest', () => {
|
||||
// Both sides press verify at the same moment; the loser's Sas is replaced by a fresh
|
||||
// one that has not been accepted, and must be re-accepted or the flow hangs.
|
||||
it('re-accepts when our SAS is replaced after losing the start tie-break', async () => {
|
||||
const call = vi.fn<(m: string, a?: Record<string, unknown>) => Promise<unknown>>(
|
||||
async () => null
|
||||
);
|
||||
const started = state({
|
||||
phase: EnginePhase.Transitioned,
|
||||
verification: { className: 'Sas', hasBeenAccepted: true },
|
||||
});
|
||||
const request = new EngineVerificationRequest(call, started);
|
||||
call.mockClear();
|
||||
|
||||
request.apply(
|
||||
state({
|
||||
phase: EnginePhase.Transitioned,
|
||||
verification: { className: 'Sas', hasBeenAccepted: false },
|
||||
})
|
||||
);
|
||||
|
||||
expect(call.mock.calls.filter(([method]) => method === 'sas.accept')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('does not re-accept while the same SAS stays accepted', async () => {
|
||||
const call = vi.fn<(m: string, a?: Record<string, unknown>) => Promise<unknown>>(
|
||||
async () => null
|
||||
);
|
||||
const started = state({
|
||||
phase: EnginePhase.Transitioned,
|
||||
verification: { className: 'Sas', hasBeenAccepted: true },
|
||||
});
|
||||
const request = new EngineVerificationRequest(call, started);
|
||||
call.mockClear();
|
||||
|
||||
request.apply(
|
||||
state({
|
||||
phase: EnginePhase.Transitioned,
|
||||
verification: { className: 'Sas', hasBeenAccepted: true },
|
||||
})
|
||||
);
|
||||
|
||||
expect(call.mock.calls.filter(([method]) => method === 'sas.accept')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('accepts advertising every method we support, not the empty set the engine reports', async () => {
|
||||
const call = vi.fn<(m: string, a?: Record<string, unknown>) => Promise<unknown>>(
|
||||
async (method) =>
|
||||
|
||||
@@ -42,6 +42,8 @@ export class EngineVerificationRequest
|
||||
|
||||
#declining = false;
|
||||
|
||||
#sasAccepted = false;
|
||||
|
||||
constructor(call: EngineCall, state: EngineVerificationState) {
|
||||
super();
|
||||
this.#call = call;
|
||||
@@ -72,7 +74,11 @@ export class EngineVerificationRequest
|
||||
? 'Qr'
|
||||
: undefined;
|
||||
|
||||
if (current !== wanted) {
|
||||
const accepted = (verification as SasState).hasBeenAccepted === true;
|
||||
const lostTieBreak = wanted === 'Sas' && current === 'Sas' && this.#sasAccepted && !accepted;
|
||||
this.#sasAccepted = wanted === 'Sas' ? accepted : false;
|
||||
|
||||
if (current !== wanted || lostTieBreak) {
|
||||
if (wanted === 'Sas') {
|
||||
this.#verifier = new EngineSasVerifier(
|
||||
this.#call,
|
||||
@@ -80,7 +86,7 @@ export class EngineVerificationRequest
|
||||
verification as SasState,
|
||||
this.#state.otherUserId
|
||||
);
|
||||
if (current !== undefined) void this.#reaccept();
|
||||
if (current !== undefined || lostTieBreak) void this.#reaccept();
|
||||
} else if (wanted === 'Qr') {
|
||||
this.#verifier = new EngineQrVerifier(
|
||||
this.#call,
|
||||
|
||||
@@ -47,7 +47,7 @@ export type EngineVerificationState = {
|
||||
theirSupportedMethods?: number[] | null;
|
||||
ourSupportedMethods?: number[] | null;
|
||||
cancelInfo?: EngineCancelInfo | null;
|
||||
verification?: { className?: string; isDone?: boolean } | null;
|
||||
verification?: { className?: string; isDone?: boolean; hasBeenAccepted?: boolean } | null;
|
||||
};
|
||||
|
||||
export const methodFromCode = (code: number): string | undefined => METHOD_BY_CODE[code];
|
||||
|
||||
@@ -13,6 +13,8 @@ export type EngineCall = (method: string, args?: Record<string, unknown>) => Pro
|
||||
|
||||
export type SasState = {
|
||||
className?: string;
|
||||
weStarted?: boolean;
|
||||
hasBeenAccepted?: boolean;
|
||||
canBePresented?: boolean;
|
||||
haveWeConfirmed?: boolean;
|
||||
isDone?: boolean;
|
||||
|
||||
Reference in new issue
Block a user