Skip to content

Add crypto methods for export and import of secrets bundle #4227

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
19 changes: 19 additions & 0 deletions spec/unit/crypto/secrets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -687,4 +687,23 @@ describe("Secrets", function () {
alice.stopClient();
});
});

it("should return false for supportsSecretsForQrLogin", async () => {
const alice = await makeTestClient({ userId: "@alice:example.com", deviceId: "Osborne2" });
expect(alice.getCrypto()?.supportsSecretsForQrLogin()).toBe(false);
});

it("should throw Not Implemented for importSecretsForQRLogin", async () => {
const alice = await makeTestClient({ userId: "@alice:example.com", deviceId: "Osborne2" });
await expect(
alice.getCrypto()?.importSecretsForQrLogin({
cross_signing: { master_key: "", self_signing_key: "", user_signing_key: "" },
}),
).rejects.toThrow("Method not implemented.");
});

it("should throw Not Implemented for exportSecretsForQRLogin", async () => {
const alice = await makeTestClient({ userId: "@alice:example.com", deviceId: "Osborne2" });
await expect(alice.getCrypto()?.exportSecretsForQrLogin()).rejects.toThrow("Method not implemented.");
});
});
42 changes: 42 additions & 0 deletions spec/unit/rust-crypto/rust-crypto.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1515,6 +1515,48 @@ describe("RustCrypto", () => {
expect(await rustCrypto.isDehydrationSupported()).toBe(true);
});
});

describe("exportSecretsForQrLogin", () => {
let rustCrypto: RustCrypto;

beforeEach(async () => {
rustCrypto = await makeTestRustCrypto(
new MatrixHttpApi(new TypedEventEmitter<HttpApiEvent, HttpApiEventHandlerMap>(), {
baseUrl: "http://server/",
prefix: "",
onlyData: true,
}),
testData.TEST_USER_ID,
);
});

it("should return true for supportsSecretsForQrLogin", async () => {
expect(rustCrypto.supportsSecretsForQrLogin()).toBe(true);
});

it("should throw an error if there is nothing to export", async () => {
await expect(rustCrypto.exportSecretsForQrLogin()).rejects.toThrow(
"The store doesn't contain any cross-signing keys",
);
});

it("should return a JSON secrets bundle if there is something to export", async () => {
const bundle = {
cross_signing: {
master_key: "bMnVpkHI4S2wXRxy+IpaKM5PIAUUkl6DE+n0YLIW/qs",
user_signing_key: "8tlgLjUrrb/zGJo4YKGhDTIDCEjtJTAS/Sh2AGNLuIo",
self_signing_key: "pfDknmP5a0fVVRE54zhkUgJfzbNmvKcNfIWEW796bQs",
},
backup: {
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
key: "bYYv3aFLQ49jMNcOjuTtBY9EKDby2x1m3gfX81nIKRQ",
backup_version: "9",
},
};
await rustCrypto.importSecretsForQrLogin(bundle);
await expect(rustCrypto.exportSecretsForQrLogin()).resolves.toEqual(expect.objectContaining(bundle));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we could check the getCrossSigningStatus? and see that the identity is there and trusted?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This causes the test to hang on OlmMachine::getIdentity and I have 0 introspection on the rust side of things to debug this.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, getCrossSigningStatus will want to fire off /keys/query requests and wait for them to complete, so that is more of an integration-test thing.

That said: some integration tests here might be nice?

});
});
});

/** Build a MatrixHttpApi instance */
Expand Down
40 changes: 40 additions & 0 deletions src/@types/matrix-sdk-crypto-wasm.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
Copyright 2024 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import type * as RustSdkCryptoJs from "@matrix-org/matrix-sdk-crypto-wasm";

declare module "@matrix-org/matrix-sdk-crypto-wasm" {
interface OlmMachine {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need this? isn't it already in the index.d.ts of matrix-sdk-crypto-wasm?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes but with return types of any - see matrix-org/matrix-rust-sdk-crypto-wasm#110

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be fixed on the wasm side; matrix-org/matrix-rust-sdk-crypto-wasm#123 does so but it will need a release cycle :/

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, that PR doesn't help with the return type of SecretsBundle.to_json, to be fair. On the other hand: do you actually need to introspect the result of SecretsBundle.to_json outside of tests (where I would be inclined to do some @ts-ignoreing rather than have a separate definition to keep in step)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, that PR doesn't help with the return type of SecretsBundle.to_json, to be fair. On the other hand: do you actually need to introspect the result of SecretsBundle.to_json outside of tests (where I would be inclined to do some @ts-ignoreing rather than have a separate definition to keep in step)?

It should still be a useful type otherwise you'll get junk into the import method. If it isn't meant to be introspectable then it should be a branded type so a round-trip export->import works without needing to rely on any

importSecretsBundle(bundle: RustSdkCryptoJs.SecretsBundle): Promise<void>;
exportSecretsBundle(): Promise<RustSdkCryptoJs.SecretsBundle>;
}

interface SecretsBundle {
// eslint-disable-next-line @typescript-eslint/naming-convention
to_json(): Promise<{
cross_signing: {
master_key: string;
self_signing_key: string;
user_signing_key: string;
};
backup?: {
algorithm: string;
key: string;
backup_version: string;
};
}>;
}
}
22 changes: 22 additions & 0 deletions src/crypto-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import type { SecretsBundle } from "@matrix-org/matrix-sdk-crypto-wasm";
import type { IMegolmSessionData } from "./@types/crypto";
import { Room } from "./models/room";
import { DeviceMap } from "./models/device";
Expand All @@ -24,12 +25,33 @@ import { BackupTrustInfo, KeyBackupCheck, KeyBackupInfo } from "./crypto-api/key
import { ISignatures } from "./@types/signed";
import { MatrixEvent } from "./models/event";

export type QRSecretsBundle = Awaited<ReturnType<SecretsBundle["to_json"]>>;

/**
* Public interface to the cryptography parts of the js-sdk
*
* @remarks Currently, this is a work-in-progress. In time, more methods will be added here.
*/
export interface CryptoApi {
/**
* Boolean check to indicate whether `exportSecretsForQrLogin` and `importSecretsForQrLogin` are supported.
* @experimental - part of MSC4108
*/
supportsSecretsForQrLogin(): boolean;

/**
* Export secrets bundle for transmitting to another device as part of OIDC QR login
* @experimental - part of MSC4108
*/
exportSecretsForQrLogin(): Promise<QRSecretsBundle>;

/**
* Import secrets bundle transmitted from another device as part of OIDC QR login
* @param secrets the secrets bundle received from the other device
* @experimental - part of MSC4108
*/
importSecretsForQrLogin(secrets: QRSecretsBundle): Promise<void>;

/**
* Global override for whether the client should ever send encrypted
* messages to unverified devices. This provides the default for rooms which
Expand Down
13 changes: 13 additions & 0 deletions src/crypto/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ import {
KeyBackupInfo,
OwnDeviceKeys,
VerificationRequest as CryptoApiVerificationRequest,
QRSecretsBundle,
} from "../crypto-api";
import { Device, DeviceMap } from "../models/device";
import { deviceInfoToDevice } from "./device-converter";
Expand Down Expand Up @@ -576,6 +577,18 @@ export class Crypto extends TypedEventEmitter<CryptoEvent, CryptoEventHandlerMap
}
}

public supportsSecretsForQrLogin(): boolean {
return false;
}

public async exportSecretsForQrLogin(): Promise<QRSecretsBundle> {
throw new Error("Method not implemented.");
}

public async importSecretsForQrLogin(secrets: QRSecretsBundle): Promise<void> {
throw new Error("Method not implemented.");
}

/**
* Initialise the crypto module so that it is ready for use
*
Expand Down
17 changes: 17 additions & 0 deletions src/rust-crypto/rust-crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import {
KeyBackupCheck,
KeyBackupInfo,
OwnDeviceKeys,
QRSecretsBundle,
UserVerificationStatus,
VerificationRequest,
} from "../crypto-api";
Expand Down Expand Up @@ -177,6 +178,22 @@ export class RustCrypto extends TypedEventEmitter<RustCryptoEvents, RustCryptoEv
this.checkKeyBackupAndEnable();
}

public supportsSecretsForQrLogin(): boolean {
return true;
}

public async exportSecretsForQrLogin(): Promise<QRSecretsBundle> {
const secretsBundle = await this.getOlmMachineOrThrow().exportSecretsBundle();
const secrets = secretsBundle.to_json();
secretsBundle.free();
return secrets;
}

public async importSecretsForQrLogin(secrets: QRSecretsBundle): Promise<void> {
const secretsBundle = RustSdkCryptoJs.SecretsBundle.from_json(secrets);
await this.getOlmMachineOrThrow().importSecretsBundle(secretsBundle); // this method frees the SecretsBundle
}

/**
* Return the OlmMachine only if {@link RustCrypto#stop} has not been called.
*
Expand Down
Loading