Skip to content
This repository has been archived by the owner on Oct 22, 2024. It is now read-only.

First batch: remove deprecated calls on MatrixClient #154

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/SecurityManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ async function getSecretStorageKey({
keys: Record<string, SecretStorage.SecretStorageKeyDescription>;
}): Promise<[string, Uint8Array]> {
const cli = MatrixClientPeg.safeGet();
let keyId = await cli.getDefaultSecretStorageKeyId();
let keyId = await cli.secretStorage.getDefaultKeyId();
let keyInfo!: SecretStorage.SecretStorageKeyDescription;
if (keyId) {
// use the default SSSS key if set
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export default class CreateKeyBackupDialog extends React.PureComponent<IProps, I
const cli = MatrixClientPeg.safeGet();
try {
// Check if 4S already set up
const secretStorageAlreadySetup = await cli.hasSecretStorageKey();
const secretStorageAlreadySetup = await cli.secretStorage.hasKey();

if (!secretStorageAlreadySetup) {
// bootstrap secret storage; that will also create a backup version
Expand Down
5 changes: 3 additions & 2 deletions src/components/structures/MatrixChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1707,9 +1707,10 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}
}

if (cli.getCrypto()) {
const crypto = cli.getCrypto();
if (crypto) {
const blacklistEnabled = SettingsStore.getValueAt(SettingLevel.DEVICE, "blacklistUnverifiedDevices");
cli.setGlobalBlacklistUnverifiedDevices(blacklistEnabled);
crypto.globalBlacklistUnverifiedDevices = blacklistEnabled;

// With cross-signing enabled, we send to unknown devices
// without prompting. Any bad-device status the user should
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ export default class AccessSecretStorageDialog extends React.PureComponent<IProp
await accessSecretStorage(async (): Promise<void> => {
// Now reset cross-signing so everything Just Works™ again.
const cli = MatrixClientPeg.safeGet();
await cli.bootstrapCrossSigning({
await cli.getCrypto()?.bootstrapCrossSigning({
authUploadDeviceSigningKeys: async (makeRequest): Promise<void> => {
const { finished } = Modal.createDialog(InteractiveAuthDialog, {
title: _t("encryption|bootstrap_title"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ export default class CreateCrossSigningDialog extends React.PureComponent<IProps

try {
const cli = MatrixClientPeg.safeGet();
await cli.bootstrapCrossSigning({
await cli.getCrypto()?.bootstrapCrossSigning({
authUploadDeviceSigningKeys: this.doBootstrapUIAuth,
});
this.props.onFinished(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent<IProps,
try {
const cli = MatrixClientPeg.safeGet();
const backupInfo = await cli.getKeyBackupVersion();
const has4S = await cli.hasSecretStorageKey();
const has4S = await cli.secretStorage.hasKey();
const backupKeyStored = has4S ? await cli.isKeyBackupKeyStored() : null;
this.setState({
backupInfo,
Expand Down
3 changes: 2 additions & 1 deletion src/components/views/settings/CryptographyPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ export default class CryptographyPanel extends React.Component<IProps, IState> {
};

private updateBlacklistDevicesFlag = (checked: boolean): void => {
MatrixClientPeg.safeGet().setGlobalBlacklistUnverifiedDevices(checked);
const crypto = MatrixClientPeg.safeGet().getCrypto();
if (crypto) crypto.globalBlacklistUnverifiedDevices = checked;
};
}
49 changes: 0 additions & 49 deletions src/stores/widgets/StopGapWidgetDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,55 +414,6 @@ export class StopGapWidgetDriver extends WidgetDriver {
await client._unstable_updateDelayedEvent(delayId, action);
}

public async sendToDevice(
eventType: string,
encrypted: boolean,
contentMap: { [userId: string]: { [deviceId: string]: object } },
): Promise<void> {
const client = MatrixClientPeg.safeGet();

if (encrypted) {
const deviceInfoMap = await client.crypto!.deviceList.downloadKeys(Object.keys(contentMap), false);

await Promise.all(
Object.entries(contentMap).flatMap(([userId, userContentMap]) =>
Object.entries(userContentMap).map(async ([deviceId, content]): Promise<void> => {
const devices = deviceInfoMap.get(userId);
if (!devices) return;

if (deviceId === "*") {
// Send the message to all devices we have keys for
await client.encryptAndSendToDevices(
Array.from(devices.values()).map((deviceInfo) => ({
userId,
deviceInfo,
})),
content,
);
} else if (devices.has(deviceId)) {
// Send the message to a specific device
await client.encryptAndSendToDevices(
[{ userId, deviceInfo: devices.get(deviceId)! }],
content,
);
}
}),
),
);
} else {
await client.queueToDevice({
eventType,
batch: Object.entries(contentMap).flatMap(([userId, userContentMap]) =>
Object.entries(userContentMap).map(([deviceId, content]) => ({
userId,
deviceId,
payload: content,
})),
),
});
}
}

private pickRooms(roomIds?: (string | Symbols.AnyRoom)[]): Room[] {
const client = MatrixClientPeg.get();
if (!client) throw new Error("Not attached to a client");
Expand Down
15 changes: 5 additions & 10 deletions src/verification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ Please see LICENSE files in the repository root for full details.
*/

import { User, MatrixClient, RoomMember } from "matrix-js-sdk/src/matrix";
import { VerificationMethod } from "matrix-js-sdk/src/types";
import { CrossSigningKey, VerificationRequest } from "matrix-js-sdk/src/crypto-api";

import dis from "./dispatcher/dispatcher";
Expand Down Expand Up @@ -39,7 +38,7 @@ export async function verifyDevice(matrixClient: MatrixClient, user: User, devic
return;
}
// if cross-signing is not explicitly disabled, check if it should be enabled first.
if (matrixClient.getCryptoTrustCrossSignedDevices()) {
if (matrixClient.getCrypto()?.getTrustCrossSignedDevices()) {
if (!(await enable4SIfNeeded(matrixClient))) {
return;
}
Expand All @@ -50,11 +49,9 @@ export async function verifyDevice(matrixClient: MatrixClient, user: User, devic
device,
onFinished: async (action): Promise<void> => {
if (action === "sas") {
const verificationRequestPromise = matrixClient.legacyDeviceVerification(
user.userId,
device.deviceId,
VerificationMethod.Sas,
);
const verificationRequestPromise = matrixClient
.getCrypto()
?.requestDeviceVerification(user.userId, device.deviceId);
setRightPanel({ member: user, verificationRequestPromise });
} else if (action === "legacy") {
Modal.createDialog(ManualDeviceKeyVerificationDialog, {
Expand All @@ -72,13 +69,11 @@ export async function legacyVerifyUser(matrixClient: MatrixClient, user: User):
return;
}
// if cross-signing is not explicitly disabled, check if it should be enabled first.
if (matrixClient.getCryptoTrustCrossSignedDevices()) {
if (matrixClient.getCrypto()?.getTrustCrossSignedDevices()) {
if (!(await enable4SIfNeeded(matrixClient))) {
return;
}
}
const verificationRequestPromise = matrixClient.requestVerification(user.userId);
setRightPanel({ member: user, verificationRequestPromise });
}

export async function verifyUser(matrixClient: MatrixClient, user: User): Promise<void> {
Expand Down
2 changes: 0 additions & 2 deletions test/MatrixClientPeg-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,10 @@ describe("MatrixClientPeg", () => {
it("should initialise the rust crypto library by default", async () => {
const mockSetValue = jest.spyOn(SettingsStore, "setValue").mockResolvedValue(undefined);

const mockInitCrypto = jest.spyOn(testPeg.safeGet(), "initCrypto").mockResolvedValue(undefined);
const mockInitRustCrypto = jest.spyOn(testPeg.safeGet(), "initRustCrypto").mockResolvedValue(undefined);

const cryptoStoreKey = new Uint8Array([1, 2, 3, 4]);
await testPeg.start({ rustCryptoStoreKey: cryptoStoreKey });
expect(mockInitCrypto).not.toHaveBeenCalled();
expect(mockInitRustCrypto).toHaveBeenCalledWith({ storageKey: cryptoStoreKey });

// we should have stashed the setting in the settings store
Expand Down
8 changes: 5 additions & 3 deletions test/components/structures/MatrixChat-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,6 @@ describe("<MatrixChat />", () => {
}),
getVisibleRooms: jest.fn().mockReturnValue([]),
getRooms: jest.fn().mockReturnValue([]),
setGlobalBlacklistUnverifiedDevices: jest.fn(),
setGlobalErrorOnUnknownDevices: jest.fn(),
getCrypto: jest.fn().mockReturnValue({
getVerificationRequestsToDeviceInProgress: jest.fn().mockReturnValue([]),
Expand All @@ -135,9 +134,10 @@ describe("<MatrixChat />", () => {
getVersion: jest.fn().mockReturnValue("1"),
setDeviceIsolationMode: jest.fn(),
userHasCrossSigningKeys: jest.fn(),
globalBlacklistUnverifiedDevices: false,
// This needs to not finish immediately because we need to test the screen appears
bootstrapCrossSigning: jest.fn().mockImplementation(() => bootstrapDeferred.promise),
}),
// This needs to not finish immediately because we need to test the screen appears
bootstrapCrossSigning: jest.fn().mockImplementation(() => bootstrapDeferred.promise),
secretStorage: {
isStored: jest.fn().mockReturnValue(null),
},
Expand Down Expand Up @@ -1010,6 +1010,8 @@ describe("<MatrixChat />", () => {
.mockResolvedValue(new UserVerificationStatus(false, false, false)),
setDeviceIsolationMode: jest.fn(),
userHasCrossSigningKeys: jest.fn().mockResolvedValue(false),
// This needs to not finish immediately because we need to test the screen appears
bootstrapCrossSigning: jest.fn().mockImplementation(() => bootstrapDeferred.promise),
};
loginClient.getCrypto.mockReturnValue(mockCrypto as any);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ describe("CreateKeyBackupDialog", () => {

it("should display an error message when backup creation failed", async () => {
const matrixClient = createTestClient();
mocked(matrixClient.hasSecretStorageKey).mockResolvedValue(true);
jest.spyOn(matrixClient.secretStorage, "hasKey").mockResolvedValue(true);
mocked(matrixClient.getCrypto()!.resetKeyBackup).mockImplementation(() => {
throw new Error("failed");
});
Expand All @@ -49,7 +49,7 @@ describe("CreateKeyBackupDialog", () => {

it("should display an error message when there is no Crypto available", async () => {
const matrixClient = createTestClient();
mocked(matrixClient.hasSecretStorageKey).mockResolvedValue(true);
jest.spyOn(matrixClient.secretStorage, "hasKey").mockResolvedValue(true);
mocked(matrixClient.getCrypto).mockReturnValue(undefined);
MatrixClientPeg.safeGet = MatrixClientPeg.get = () => matrixClient;

Expand Down
1 change: 0 additions & 1 deletion test/components/views/right_panel/UserInfo-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,6 @@ beforeEach(() => {
getRoom: jest.fn(),
credentials: {},
setPowerLevel: jest.fn(),
downloadKeys: jest.fn(),
getCrypto: jest.fn().mockReturnValue(mockCrypto),
} as unknown as MatrixClient);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ describe("<CrossSigningPanel />", () => {
});

mockClient.doesServerSupportUnstableFeature.mockResolvedValue(true);
mockClient.isCrossSigningReady.mockResolvedValue(false);
});

afterEach(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import {
waitForElementToBeRemoved,
within,
} from "jest-matrix-react";
import { DeviceInfo } from "matrix-js-sdk/src/crypto/deviceinfo";
import { logger } from "matrix-js-sdk/src/logger";
import { CryptoApi, DeviceVerificationStatus, VerificationRequest } from "matrix-js-sdk/src/crypto-api";
import { defer, sleep } from "matrix-js-sdk/src/utils";
Expand Down Expand Up @@ -202,7 +201,6 @@ describe("<SessionManagerTab />", () => {
...mockClientMethodsServer(),
getCrypto: jest.fn().mockReturnValue(mockCrypto),
getDevices: jest.fn(),
getStoredDevice: jest.fn(),
getDeviceId: jest.fn().mockReturnValue(deviceId),
deleteMultipleDevices: jest.fn(),
generateClientSecret: jest.fn(),
Expand All @@ -217,10 +215,6 @@ describe("<SessionManagerTab />", () => {
});
jest.clearAllMocks();
jest.spyOn(logger, "error").mockRestore();
mockClient.getStoredDevice.mockImplementation((_userId, id) => {
const device = [alicesDevice, alicesMobileDevice].find((device) => device.device_id === id);
return device ? new DeviceInfo(device.device_id) : null;
});
mockCrypto.getDeviceVerificationStatus.mockReset().mockResolvedValue(new DeviceVerificationStatus({}));

mockClient.getDevices.mockReset().mockResolvedValue({ devices: [alicesDevice, alicesMobileDevice] });
Expand Down Expand Up @@ -289,7 +283,6 @@ describe("<SessionManagerTab />", () => {
mockClient.getDevices.mockResolvedValue({
devices: [alicesDevice, alicesMobileDevice, alicesOlderMobileDevice],
});
mockClient.getStoredDevice.mockImplementation((_userId, deviceId) => new DeviceInfo(deviceId));
mockCrypto.getDeviceVerificationStatus.mockImplementation(async (_userId, deviceId) => {
// alices device is trusted
if (deviceId === alicesDevice.device_id) {
Expand Down Expand Up @@ -461,7 +454,6 @@ describe("<SessionManagerTab />", () => {
mockClient.getDevices.mockResolvedValue({
devices: [alicesDevice, alicesMobileDevice],
});
mockClient.getStoredDevice.mockImplementation(() => new DeviceInfo(alicesDevice.device_id));
mockCrypto.getDeviceVerificationStatus.mockResolvedValue(
new DeviceVerificationStatus({ crossSigningVerified: true, localVerified: true }),
);
Expand Down Expand Up @@ -565,7 +557,6 @@ describe("<SessionManagerTab />", () => {
mockClient.getDevices.mockResolvedValue({
devices: [alicesDevice, alicesMobileDevice],
});
mockClient.getStoredDevice.mockImplementation((_userId, deviceId) => new DeviceInfo(deviceId));
mockCrypto.getDeviceVerificationStatus.mockImplementation(async (_userId, deviceId) => {
if (deviceId === alicesDevice.device_id) {
return new DeviceVerificationStatus({ crossSigningVerified: true, localVerified: true });
Expand All @@ -592,7 +583,6 @@ describe("<SessionManagerTab />", () => {
mockClient.getDevices.mockResolvedValue({
devices: [alicesDevice, alicesMobileDevice],
});
mockClient.getStoredDevice.mockImplementation((_userId, deviceId) => new DeviceInfo(deviceId));
mockCrypto.getDeviceVerificationStatus.mockImplementation(async (_userId, deviceId) => {
// current session verified = able to verify other sessions
if (deviceId === alicesDevice.device_id) {
Expand Down Expand Up @@ -626,7 +616,6 @@ describe("<SessionManagerTab />", () => {
mockClient.getDevices.mockResolvedValue({
devices: [alicesDevice, alicesMobileDevice],
});
mockClient.getStoredDevice.mockImplementation((_userId, deviceId) => new DeviceInfo(deviceId));
mockCrypto.getDeviceVerificationStatus.mockImplementation(async (_userId, deviceId) => {
if (deviceId === alicesDevice.device_id) {
return new DeviceVerificationStatus({ crossSigningVerified: true, localVerified: true });
Expand Down Expand Up @@ -664,7 +653,6 @@ describe("<SessionManagerTab />", () => {
mockClient.getDevices.mockResolvedValue({
devices: [alicesDevice, alicesMobileDevice, alicesDehydratedDevice],
});
mockClient.getStoredDevice.mockImplementation((_userId, deviceId) => new DeviceInfo(deviceId));

const devicesMap = new Map<string, Device>([
[alicesDeviceObj.deviceId, alicesDeviceObj],
Expand Down Expand Up @@ -705,7 +693,6 @@ describe("<SessionManagerTab />", () => {
mockClient.getDevices.mockResolvedValue({
devices: [alicesDevice, alicesMobileDevice, alicesDehydratedDevice],
});
mockClient.getStoredDevice.mockImplementation((_userId, deviceId) => new DeviceInfo(deviceId));

const devicesMap = new Map<string, Device>([
[alicesDeviceObj.deviceId, alicesDeviceObj],
Expand Down Expand Up @@ -746,7 +733,6 @@ describe("<SessionManagerTab />", () => {
mockClient.getDevices.mockResolvedValue({
devices: [alicesDevice, alicesMobileDevice, alicesDehydratedDevice, alicesOtherDehydratedDevice],
});
mockClient.getStoredDevice.mockImplementation((_userId, deviceId) => new DeviceInfo(deviceId));

const devicesMap = new Map<string, Device>([
[alicesDeviceObj.deviceId, alicesDeviceObj],
Expand Down
Loading
Loading