|
| 1 | +/* |
| 2 | +Copyright 2024 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 fetchMock from "fetch-mock-jest"; |
| 19 | + |
| 20 | +import { createClient, ClientEvent, MatrixClient, MatrixEvent } from "../../../src"; |
| 21 | +import { RustCrypto } from "../../../src/rust-crypto/rust-crypto"; |
| 22 | +import { AddSecretStorageKeyOpts } from "../../../src/secret-storage"; |
| 23 | +import { E2EKeyReceiver } from "../../test-utils/E2EKeyReceiver"; |
| 24 | +import { E2EKeyResponder } from "../../test-utils/E2EKeyResponder"; |
| 25 | + |
| 26 | +describe("Device dehydration", () => { |
| 27 | + it("should rehydrate and dehydrate a device", async () => { |
| 28 | + jest.useFakeTimers({ doNotFake: ["queueMicrotask"] }); |
| 29 | + |
| 30 | + const matrixClient = createClient({ |
| 31 | + baseUrl: "http://test.server", |
| 32 | + userId: "@alice:localhost", |
| 33 | + deviceId: "aliceDevice", |
| 34 | + cryptoCallbacks: { |
| 35 | + getSecretStorageKey: async (keys: any, name: string) => { |
| 36 | + return [[...Object.keys(keys.keys)][0], new Uint8Array(32)]; |
| 37 | + }, |
| 38 | + }, |
| 39 | + }); |
| 40 | + |
| 41 | + await initializeSecretStorage(matrixClient, "@alice:localhost", "http://test.server"); |
| 42 | + |
| 43 | + // count the number of times the dehydration key gets set |
| 44 | + let setDehydrationCount = 0; |
| 45 | + matrixClient.on(ClientEvent.AccountData, (event: MatrixEvent) => { |
| 46 | + if (event.getType() === "org.matrix.msc3814") { |
| 47 | + setDehydrationCount++; |
| 48 | + } |
| 49 | + }); |
| 50 | + |
| 51 | + const crypto = matrixClient.getCrypto()!; |
| 52 | + fetchMock.config.overwriteRoutes = true; |
| 53 | + |
| 54 | + // start dehydration -- we start with no dehydrated device, and we |
| 55 | + // store the dehydrated device that we create |
| 56 | + fetchMock.get("path:/_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device", { |
| 57 | + status: 404, |
| 58 | + body: { |
| 59 | + errcode: "M_NOT_FOUND", |
| 60 | + error: "Not found", |
| 61 | + }, |
| 62 | + }); |
| 63 | + let dehydratedDeviceBody: any; |
| 64 | + let dehydrationCount = 0; |
| 65 | + let resolveDehydrationPromise: () => void; |
| 66 | + fetchMock.put("path:/_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device", (_, opts) => { |
| 67 | + dehydratedDeviceBody = JSON.parse(opts.body as string); |
| 68 | + dehydrationCount++; |
| 69 | + if (resolveDehydrationPromise) { |
| 70 | + resolveDehydrationPromise(); |
| 71 | + } |
| 72 | + return {}; |
| 73 | + }); |
| 74 | + await crypto.startDehydration(); |
| 75 | + |
| 76 | + expect(dehydrationCount).toEqual(1); |
| 77 | + |
| 78 | + // a week later, we should have created another dehydrated device |
| 79 | + const dehydrationPromise = new Promise<void>((resolve, reject) => { |
| 80 | + resolveDehydrationPromise = resolve; |
| 81 | + }); |
| 82 | + jest.advanceTimersByTime(7 * 24 * 60 * 60 * 1000); |
| 83 | + await dehydrationPromise; |
| 84 | + expect(dehydrationCount).toEqual(2); |
| 85 | + |
| 86 | + // restart dehydration -- rehydrate the device that we created above, |
| 87 | + // and create a new dehydrated device. We also set `createNewKey`, so |
| 88 | + // a new dehydration key will be set |
| 89 | + fetchMock.get("path:/_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device", { |
| 90 | + device_id: dehydratedDeviceBody.device_id, |
| 91 | + device_data: dehydratedDeviceBody.device_data, |
| 92 | + }); |
| 93 | + const eventsResponse = jest.fn((url, opts) => { |
| 94 | + // rehydrating should make two calls to the /events endpoint. |
| 95 | + // The first time will return a single event, and the second |
| 96 | + // time will return no events (which will signal to the |
| 97 | + // rehydration function that it can stop) |
| 98 | + const body = JSON.parse(opts.body as string); |
| 99 | + const nextBatch = body.next_batch ?? "0"; |
| 100 | + const events = nextBatch === "0" ? [{ sender: "@alice:localhost", type: "m.dummy", content: {} }] : []; |
| 101 | + return { |
| 102 | + events, |
| 103 | + next_batch: nextBatch + "1", |
| 104 | + }; |
| 105 | + }); |
| 106 | + fetchMock.post( |
| 107 | + `path:/_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device/${encodeURIComponent(dehydratedDeviceBody.device_id)}/events`, |
| 108 | + eventsResponse, |
| 109 | + ); |
| 110 | + await crypto.startDehydration(true); |
| 111 | + expect(dehydrationCount).toEqual(3); |
| 112 | + |
| 113 | + expect(setDehydrationCount).toEqual(2); |
| 114 | + expect(eventsResponse.mock.calls).toHaveLength(2); |
| 115 | + |
| 116 | + matrixClient.stopClient(); |
| 117 | + }); |
| 118 | +}); |
| 119 | + |
| 120 | +/** create a new secret storage and cross-signing keys */ |
| 121 | +async function initializeSecretStorage( |
| 122 | + matrixClient: MatrixClient, |
| 123 | + userId: string, |
| 124 | + homeserverUrl: string, |
| 125 | +): Promise<void> { |
| 126 | + fetchMock.get("path:/_matrix/client/v3/room_keys/version", { |
| 127 | + status: 404, |
| 128 | + body: { |
| 129 | + errcode: "M_NOT_FOUND", |
| 130 | + error: "Not found", |
| 131 | + }, |
| 132 | + }); |
| 133 | + const e2eKeyReceiver = new E2EKeyReceiver(homeserverUrl); |
| 134 | + const e2eKeyResponder = new E2EKeyResponder(homeserverUrl); |
| 135 | + e2eKeyResponder.addKeyReceiver(userId, e2eKeyReceiver); |
| 136 | + fetchMock.post("path:/_matrix/client/v3/keys/device_signing/upload", {}); |
| 137 | + fetchMock.post("path:/_matrix/client/v3/keys/signatures/upload", {}); |
| 138 | + const accountData: Map<string, object> = new Map(); |
| 139 | + fetchMock.get("glob:http://*/_matrix/client/v3/user/*/account_data/*", (url, opts) => { |
| 140 | + const name = url.split("/").pop()!; |
| 141 | + const value = accountData.get(name); |
| 142 | + if (value) { |
| 143 | + return value; |
| 144 | + } else { |
| 145 | + return { |
| 146 | + status: 404, |
| 147 | + body: { |
| 148 | + errcode: "M_NOT_FOUND", |
| 149 | + error: "Not found", |
| 150 | + }, |
| 151 | + }; |
| 152 | + } |
| 153 | + }); |
| 154 | + fetchMock.put("glob:http://*/_matrix/client/v3/user/*/account_data/*", (url, opts) => { |
| 155 | + const name = url.split("/").pop()!; |
| 156 | + const value = JSON.parse(opts.body as string); |
| 157 | + accountData.set(name, value); |
| 158 | + matrixClient.emit(ClientEvent.AccountData, new MatrixEvent({ type: name, content: value })); |
| 159 | + return {}; |
| 160 | + }); |
| 161 | + |
| 162 | + await matrixClient.initRustCrypto(); |
| 163 | + const crypto = matrixClient.getCrypto()! as RustCrypto; |
| 164 | + // we need to process a sync so that the OlmMachine will upload keys |
| 165 | + await crypto.preprocessToDeviceMessages([]); |
| 166 | + await crypto.onSyncCompleted({}); |
| 167 | + |
| 168 | + // create initial secret storage |
| 169 | + async function createSecretStorageKey() { |
| 170 | + return { |
| 171 | + keyInfo: {} as AddSecretStorageKeyOpts, |
| 172 | + privateKey: new Uint8Array(32), |
| 173 | + }; |
| 174 | + } |
| 175 | + await matrixClient.bootstrapCrossSigning({ setupNewCrossSigning: true }); |
| 176 | + await matrixClient.bootstrapSecretStorage({ |
| 177 | + createSecretStorageKey, |
| 178 | + setupNewSecretStorage: true, |
| 179 | + setupNewKeyBackup: false, |
| 180 | + }); |
| 181 | +} |
0 commit comments