Skip to content

Commit 15ef8fa

Browse files
authored
Introduce a mechanism for using the rust-crypto-sdk (#2969)
This PR introduces MatrixClient.initRustCrypto, which is similar to initCrypto, except that it will use the Rust crypto SDK instead of the old libolm-based implementation. This is very much not something you want to use in production code right now, because the integration with the rust sdk is extremely skeletal and almost everything crypto-related will raise an exception rather than doing anything useful. It is, however, enough to demonstrate the loading of the wasmified rust sdk in element web, and a react sdk with light modifications can successfully log in and out. Part of element-hq/element-web#21972.
1 parent df42014 commit 15ef8fa

File tree

7 files changed

+291
-0
lines changed

7 files changed

+291
-0
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
],
5555
"dependencies": {
5656
"@babel/runtime": "^7.12.5",
57+
"@matrix-org/matrix-sdk-crypto-js": "^0.1.0-alpha.2",
5758
"another-json": "^0.2.0",
5859
"bs58": "^5.0.0",
5960
"content-type": "^1.0.4",

spec/integ/rust-crypto.spec.ts

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import "fake-indexeddb/auto";
18+
import { IDBFactory } from "fake-indexeddb";
19+
20+
import { createClient } from "../../src";
21+
22+
afterEach(() => {
23+
// reset fake-indexeddb after each test, to make sure we don't leak connections
24+
// cf https://github.com/dumbmatter/fakeIndexedDB#wipingresetting-the-indexeddb-for-a-fresh-state
25+
// eslint-disable-next-line no-global-assign
26+
indexedDB = new IDBFactory();
27+
});
28+
29+
describe("MatrixClient.initRustCrypto", () => {
30+
it("should raise if userId or deviceId is unknown", async () => {
31+
const unknownUserClient = createClient({
32+
baseUrl: "http://test.server",
33+
deviceId: "aliceDevice",
34+
});
35+
await expect(() => unknownUserClient.initRustCrypto()).rejects.toThrow("unknown userId");
36+
37+
const unknownDeviceClient = createClient({
38+
baseUrl: "http://test.server",
39+
userId: "@alice:test",
40+
});
41+
await expect(() => unknownDeviceClient.initRustCrypto()).rejects.toThrow("unknown deviceId");
42+
});
43+
44+
it("should create the indexed dbs", async () => {
45+
const matrixClient = createClient({
46+
baseUrl: "http://test.server",
47+
userId: "@alice:localhost",
48+
deviceId: "aliceDevice",
49+
});
50+
51+
// No databases.
52+
expect(await indexedDB.databases()).toHaveLength(0);
53+
54+
await matrixClient.initRustCrypto();
55+
56+
// should have two dbs now
57+
const databaseNames = (await indexedDB.databases()).map((db) => db.name);
58+
expect(databaseNames).toEqual(
59+
expect.arrayContaining(["matrix-js-sdk::matrix-sdk-crypto", "matrix-js-sdk::matrix-sdk-crypto-meta"]),
60+
);
61+
});
62+
63+
it("should ignore a second call", async () => {
64+
const matrixClient = createClient({
65+
baseUrl: "http://test.server",
66+
userId: "@alice:localhost",
67+
deviceId: "aliceDevice",
68+
});
69+
70+
await matrixClient.initRustCrypto();
71+
await matrixClient.initRustCrypto();
72+
});
73+
});
74+
75+
describe("MatrixClient.clearStores", () => {
76+
it("should clear the indexeddbs", async () => {
77+
const matrixClient = createClient({
78+
baseUrl: "http://test.server",
79+
userId: "@alice:localhost",
80+
deviceId: "aliceDevice",
81+
});
82+
83+
await matrixClient.initRustCrypto();
84+
expect(await indexedDB.databases()).toHaveLength(2);
85+
await matrixClient.stopClient();
86+
87+
await matrixClient.clearStores();
88+
expect(await indexedDB.databases()).toHaveLength(0);
89+
});
90+
});

src/client.ts

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,7 @@ import { LocalNotificationSettings } from "./@types/local_notifications";
211211
import { UNREAD_THREAD_NOTIFICATIONS } from "./@types/sync";
212212
import { buildFeatureSupportMap, Feature, ServerSupport } from "./feature";
213213
import { CryptoBackend } from "./common-crypto/CryptoBackend";
214+
import { RUST_SDK_STORE_PREFIX } from "./rust-crypto/constants";
214215

215216
export type Store = IStore;
216217

@@ -1657,6 +1658,41 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
16571658
if (this.cryptoStore) {
16581659
promises.push(this.cryptoStore.deleteAllData());
16591660
}
1661+
1662+
// delete the stores used by the rust matrix-sdk-crypto, in case they were used
1663+
const deleteRustSdkStore = async (): Promise<void> => {
1664+
let indexedDB: IDBFactory;
1665+
try {
1666+
indexedDB = global.indexedDB;
1667+
} catch (e) {
1668+
// No indexeddb support
1669+
return;
1670+
}
1671+
for (const dbname of [
1672+
`${RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto`,
1673+
`${RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto-meta`,
1674+
]) {
1675+
const prom = new Promise((resolve, reject) => {
1676+
logger.info(`Removing IndexedDB instance ${dbname}`);
1677+
const req = indexedDB.deleteDatabase(dbname);
1678+
req.onsuccess = (_): void => {
1679+
logger.info(`Removed IndexedDB instance ${dbname}`);
1680+
resolve(0);
1681+
};
1682+
req.onerror = (e): void => {
1683+
logger.error(`Failed to remove IndexedDB instance ${dbname}: ${e}`);
1684+
reject(new Error(`Error clearing storage: ${e}`));
1685+
};
1686+
req.onblocked = (e): void => {
1687+
logger.info(`cannot yet remove IndexedDB instance ${dbname}`);
1688+
//reject(new Error(`Error clearing storage: ${e}`));
1689+
};
1690+
});
1691+
await prom;
1692+
}
1693+
};
1694+
promises.push(deleteRustSdkStore());
1695+
16601696
return Promise.all(promises).then(); // .then to fix types
16611697
}
16621698

@@ -2065,6 +2101,46 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
20652101
});
20662102
}
20672103

2104+
/**
2105+
* Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto.
2106+
*
2107+
* An alternative to {@link initCrypto}.
2108+
*
2109+
* *WARNING*: this API is very experimental, should not be used in production, and may change without notice!
2110+
* Eventually it will be deprecated and `initCrypto` will do the same thing.
2111+
*
2112+
* @experimental
2113+
*
2114+
* @returns a Promise which will resolve when the crypto layer has been
2115+
* successfully initialised.
2116+
*/
2117+
public async initRustCrypto(): Promise<void> {
2118+
if (this.cryptoBackend) {
2119+
logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");
2120+
return;
2121+
}
2122+
2123+
const userId = this.getUserId();
2124+
if (userId === null) {
2125+
throw new Error(
2126+
`Cannot enable encryption on MatrixClient with unknown userId: ` +
2127+
`ensure userId is passed in createClient().`,
2128+
);
2129+
}
2130+
const deviceId = this.getDeviceId();
2131+
if (deviceId === null) {
2132+
throw new Error(
2133+
`Cannot enable encryption on MatrixClient with unknown deviceId: ` +
2134+
`ensure deviceId is passed in createClient().`,
2135+
);
2136+
}
2137+
2138+
// importing rust-crypto will download the webassembly, so we delay it until we know it will be
2139+
// needed.
2140+
const RustCrypto = await import("./rust-crypto");
2141+
this.cryptoBackend = await RustCrypto.initRustCrypto(userId, deviceId);
2142+
}
2143+
20682144
/**
20692145
* Is end-to-end crypto enabled for this client.
20702146
* @returns True if end-to-end is enabled.

src/rust-crypto/constants.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
/** The prefix used on indexeddbs created by rust-crypto */
18+
export const RUST_SDK_STORE_PREFIX = "matrix-js-sdk";

src/rust-crypto/index.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import * as RustSdkCryptoJs from "@matrix-org/matrix-sdk-crypto-js";
18+
19+
import { RustCrypto } from "./rust-crypto";
20+
import { logger } from "../logger";
21+
import { CryptoBackend } from "../common-crypto/CryptoBackend";
22+
import { RUST_SDK_STORE_PREFIX } from "./constants";
23+
24+
export async function initRustCrypto(userId: string, deviceId: string): Promise<CryptoBackend> {
25+
// initialise the rust matrix-sdk-crypto-js, if it hasn't already been done
26+
await RustSdkCryptoJs.initAsync();
27+
28+
// enable tracing in the rust-sdk
29+
new RustSdkCryptoJs.Tracing(RustSdkCryptoJs.LoggerLevel.Debug).turnOn();
30+
31+
const u = new RustSdkCryptoJs.UserId(userId);
32+
const d = new RustSdkCryptoJs.DeviceId(deviceId);
33+
logger.info("Init OlmMachine");
34+
35+
// TODO: use the pickle key for the passphrase
36+
const olmMachine = await RustSdkCryptoJs.OlmMachine.initialize(u, d, RUST_SDK_STORE_PREFIX, "test pass");
37+
const rustCrypto = new RustCrypto(olmMachine, userId, deviceId);
38+
39+
logger.info("Completed rust crypto-sdk setup");
40+
return rustCrypto;
41+
}

src/rust-crypto/rust-crypto.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import * as RustSdkCryptoJs from "@matrix-org/matrix-sdk-crypto-js";
18+
19+
import { IEventDecryptionResult } from "../@types/crypto";
20+
import { MatrixEvent } from "../models/event";
21+
import { CryptoBackend } from "../common-crypto/CryptoBackend";
22+
23+
// import { logger } from "../logger";
24+
25+
/**
26+
* An implementation of {@link CryptoBackend} using the Rust matrix-sdk-crypto.
27+
*/
28+
export class RustCrypto implements CryptoBackend {
29+
public globalBlacklistUnverifiedDevices = false;
30+
public globalErrorOnUnknownDevices = false;
31+
32+
/** whether stop() has been called */
33+
private stopped = false;
34+
35+
public constructor(private readonly olmMachine: RustSdkCryptoJs.OlmMachine, _userId: string, _deviceId: string) {}
36+
37+
public stop(): void {
38+
// stop() may be called multiple times, but attempting to close() the OlmMachine twice
39+
// will cause an error.
40+
if (this.stopped) {
41+
return;
42+
}
43+
this.stopped = true;
44+
45+
// make sure we close() the OlmMachine; doing so means that all the Rust objects will be
46+
// cleaned up; in particular, the indexeddb connections will be closed, which means they
47+
// can then be deleted.
48+
this.olmMachine.close();
49+
}
50+
51+
public async decryptEvent(event: MatrixEvent): Promise<IEventDecryptionResult> {
52+
await this.olmMachine.decryptRoomEvent("event", new RustSdkCryptoJs.RoomId("room"));
53+
throw new Error("not implemented");
54+
}
55+
56+
public async userHasCrossSigningKeys(): Promise<boolean> {
57+
// TODO
58+
return false;
59+
}
60+
}

yarn.lock

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1432,6 +1432,11 @@
14321432
dependencies:
14331433
lodash "^4.17.21"
14341434

1435+
"@matrix-org/matrix-sdk-crypto-js@^0.1.0-alpha.2":
1436+
version "0.1.0-alpha.2"
1437+
resolved "https://registry.yarnpkg.com/@matrix-org/matrix-sdk-crypto-js/-/matrix-sdk-crypto-js-0.1.0-alpha.2.tgz#a09d0fea858e817da971a3c9f904632ef7b49eb6"
1438+
integrity sha512-oVkBCh9YP7H9i4gAoQbZzswniczfo/aIptNa4dxRi4Ff9lSvUCFv6Hvzi7C+90c0/PWZLXjIDTIAWZYmwyd2fA==
1439+
14351440
"@matrix-org/olm@https://gitlab.matrix.org/api/v4/projects/27/packages/npm/@matrix-org/olm/-/@matrix-org/olm-3.2.14.tgz":
14361441
version "3.2.14"
14371442
resolved "https://gitlab.matrix.org/api/v4/projects/27/packages/npm/@matrix-org/olm/-/@matrix-org/olm-3.2.14.tgz#acd96c00a881d0f462e1f97a56c73742c8dbc984"

0 commit comments

Comments
 (0)