Skip to content
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

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

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

describe("exportSecretsForQrLogin", () => {
describe("import & export secrets bundle", () => {
let rustCrypto: RustCrypto;

beforeEach(async () => {
Expand All @@ -1530,17 +1530,13 @@ describe("RustCrypto", () => {
);
});

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(
await expect(rustCrypto.exportsSecretsBundle()).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 () => {
it("should correctly import & export a secrets bundle", async () => {
const bundle = {
cross_signing: {
master_key: "bMnVpkHI4S2wXRxy+IpaKM5PIAUUkl6DE+n0YLIW/qs",
Expand All @@ -1553,8 +1549,8 @@ describe("RustCrypto", () => {
backup_version: "9",
},
};
await rustCrypto.importSecretsForQrLogin(bundle);
await expect(rustCrypto.exportSecretsForQrLogin()).resolves.toEqual(expect.objectContaining(bundle));
await rustCrypto.importSecretsBundle(bundle);
await expect(rustCrypto.exportsSecretsBundle()).resolves.toEqual(expect.objectContaining(bundle));
});
});
});
Expand Down
38 changes: 17 additions & 21 deletions src/crypto-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,33 +25,12 @@ 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 Expand Up @@ -554,6 +533,23 @@ export interface CryptoApi {
* to false.
*/
startDehydration(createNewKey?: boolean): Promise<void>;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Import/export of secret keys
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
* Export secrets bundle for transmitting to another device as part of OIDC QR login
*/
exportSecretsBundle?(): Promise<Awaited<ReturnType<SecretsBundle["to_json"]>>>;

/**
* Import secrets bundle transmitted from another device.
* @param secrets - The secrets bundle received from the other device
*/
importSecretsBundle?(secrets: Awaited<ReturnType<SecretsBundle["to_json"]>>): Promise<void>;
}

/** A reason code for a failure to decrypt an event. */
Expand Down
13 changes: 0 additions & 13 deletions src/crypto/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ 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 @@ -577,18 +576,6 @@ 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
38 changes: 21 additions & 17 deletions src/rust-crypto/rust-crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
CrossSigningKey,
CrossSigningKeyInfo,
CrossSigningStatus,
CryptoApi,
CryptoCallbacks,
Curve25519AuthData,
DecryptionFailureCode,
Expand All @@ -50,7 +51,6 @@ import {
KeyBackupCheck,
KeyBackupInfo,
OwnDeviceKeys,
QRSecretsBundle,
UserVerificationStatus,
VerificationRequest,
} from "../crypto-api";
Expand Down Expand Up @@ -178,22 +178,6 @@ 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 Expand Up @@ -1182,6 +1166,26 @@ export class RustCrypto extends TypedEventEmitter<RustCryptoEvents, RustCryptoEv
this.checkKeyBackupAndEnable();
}

/**
* Implementation of {@link CryptoApi#importSecretsBundle}.
*/
public async importSecretsBundle(
secrets: Parameters<NonNullable<CryptoApi["importSecretsBundle"]>>[0],
Copy link
Member

@richvdh richvdh Jun 5, 2024

Choose a reason for hiding this comment

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

I still think there's way too much type magic going on here. As a caller of this function, how am I meant to build one of these things?

... I'm not going to block the PR further on it, though.

Copy link
Member Author

Choose a reason for hiding this comment

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

As a caller of this function, how am I meant to build one of these things?

you shouldn't construct manually, only ever exported by the matching export function

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

/**
* Implementation of {@link CryptoApi#exportSecretsBundle}.
*/
public async exportsSecretsBundle(): ReturnType<NonNullable<CryptoApi["exportSecretsBundle"]>> {
const secretsBundle = await this.getOlmMachineOrThrow().exportSecretsBundle();
const secrets = secretsBundle.to_json();
secretsBundle.free();
return secrets;
}

/**
* Signs the given object with the current device and current identity (if available).
* As defined in {@link https://spec.matrix.org/v1.8/appendices/#signing-json | Signing JSON}.
Expand Down
Loading