From b9b4f4725aabee459e2d0fdbfd0e817975fd4c4d Mon Sep 17 00:00:00 2001 From: SimonThormeyer Date: Tue, 21 Jan 2025 15:38:39 +0100 Subject: [PATCH 1/5] chore: update iOS/web interop clients to transaction API Also, run `swift-format` on `InteropClientApp.swift`. --- .../InteropClient/InteropClientApp.swift | 294 +++++++++++------- interop/src/clients/corecrypto/web.rs | 57 ++-- 2 files changed, 217 insertions(+), 134 deletions(-) diff --git a/interop/src/clients/InteropClient/InteropClient/InteropClientApp.swift b/interop/src/clients/InteropClient/InteropClient/InteropClientApp.swift index 81020972d9..f3f181a644 100644 --- a/interop/src/clients/InteropClient/InteropClient/InteropClientApp.swift +++ b/interop/src/clients/InteropClient/InteropClient/InteropClientApp.swift @@ -14,40 +14,66 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. -import SwiftUI import Foundation +import SwiftUI import WireCoreCrypto class TransportProvider: MlsTransport { - + func sendCommitBundle( commitBundle: WireCoreCrypto.CommitBundle ) async -> WireCoreCrypto.MlsTransportResponse { .success } - + func sendMessage( mlsMessage: Data ) async -> WireCoreCrypto.MlsTransportResponse { .success } - + +} + +class TransactionExecutor: CoreCryptoCommand { + let block: (_ context: CoreCryptoContext) async throws -> Result + var result: Result? + + init( + _ block: @escaping (_ context: CoreCryptoContext) async throws -> Result + ) { + self.block = block + } + + func execute(context: CoreCryptoContext) async throws { + result = try await block(context) + } +} + +extension CoreCrypto { + func transaction( + _ block: @escaping (_ context: CoreCryptoContext) async throws -> Result + ) async throws -> Result { + let transactionExecutor = TransactionExecutor(block) + try await transaction(command: transactionExecutor) + return transactionExecutor.result! + } } enum InteropError: String, Error { - case notInitialised = "Unable to perform action since core crypto is not initialised" + case notInitialised = + "Unable to perform action since core crypto is not initialised" case encodingError = "Failed to encode result" } @main struct InteropClientApp: App { - + @State var coreCrypto: CoreCrypto? - + init() { print("Ready") } - + var body: some Scene { WindowGroup { ContentView() @@ -56,10 +82,10 @@ struct InteropClientApp: App { try await handleURL(url: url) } }) - + } } - + /// Generates a random keystore path so we'll start with a new keystore on each launch private func generateKeystorePath() -> String { FileManager.default.temporaryDirectory.appending( @@ -67,27 +93,28 @@ struct InteropClientApp: App { directoryHint: .notDirectory ).absoluteString } - + private func handleURL(url: URL) async throws { let response = await executeURL(url: url) - print(String(decoding: try JSONEncoder().encode(response), as: UTF8.self)) + print( + String(decoding: try JSONEncoder().encode(response), as: UTF8.self)) } - - private func executeURL(url: URL) async -> InteropResponse{ + + private func executeURL(url: URL) async -> InteropResponse { guard let action = InteropAction(url: url) else { return .failure(message: "Unknown interop action: \(url)") } - + do { return .success(value: try await executeAction(action)) } catch (let error) { return .failure(message: error.localizedDescription) } } - + private func executeAction(_ action: InteropAction) async throws -> String { switch action { - case .initMLS(clientId: let clientId, ciphersuite: let ciphersuite): + case .initMLS(let clientId, let ciphersuite): self.coreCrypto = try await CoreCrypto.init( path: generateKeystorePath(), key: "secret", @@ -95,150 +122,185 @@ struct InteropClientApp: App { ciphersuites: [ciphersuite], nbKeyPackage: nil ) - - try await self.coreCrypto?.provideTransport(callbacks: TransportProvider()) - + + try await self.coreCrypto?.provideTransport( + callbacks: TransportProvider()) + return "Initialised MLS with ciphersuite: \(ciphersuite)" - - case .getKeyPackage(ciphersuite: let ciphersuite): + + case .getKeyPackage(let ciphersuite): guard let coreCrypto else { throw InteropError.notInitialised } - - let keyPackage = try await coreCrypto.clientKeypackages( - ciphersuite: ciphersuite, - credentialType: .basic, - amountRequested: 1 - ) - - if let encodedKeyPackage = keyPackage.first.map({ $0.base64EncodedString() }) { + + let keyPackage = try await coreCrypto.transaction { + try await $0.clientKeypackages( + ciphersuite: ciphersuite, + credentialType: .basic, + amountRequested: 1) + } + + if let encodedKeyPackage = keyPackage.first.map({ + $0.base64EncodedString() + }) { return encodedKeyPackage } else { throw InteropError.encodingError } - - case .addClient(conversationId: let conversationId, let ciphersuite, keyPackage: let keyPackage): + + case .addClient(let conversationId, let ciphersuite, let keyPackage): guard let coreCrypto else { throw InteropError.notInitialised } - - if try await coreCrypto.conversationExists(conversationId: conversationId) == false { - let customConfiguration = CustomConfiguration(keyRotationSpan: nil, wirePolicy: nil) + + if try await coreCrypto.conversationExists( + conversationId: conversationId) == false + { + let customConfiguration = CustomConfiguration( + keyRotationSpan: nil, wirePolicy: nil) let conversationConfiguration = ConversationConfiguration( ciphersuite: ciphersuite, externalSenders: [], custom: customConfiguration ) - - try await coreCrypto.createConversation( + + try await coreCrypto.transaction { + try await $0.createConversation( + conversationId: conversationId, + creatorCredentialType: .basic, + config: conversationConfiguration) + } + } + + _ = try await coreCrypto.transaction { + try await $0.addClientsToConversation( conversationId: conversationId, - creatorCredentialType: .basic, - config: conversationConfiguration) + keyPackages: [keyPackage] + ) } - - _ = try await coreCrypto.addClientsToConversation( - conversationId: conversationId, - keyPackages: [keyPackage] - ) - + return "added client to conversation" - - case .removeClient(conversationId: let conversationId, clientId: let clientId): + + case .removeClient(let conversationId, let clientId): guard let coreCrypto else { throw InteropError.notInitialised } - - _ = try await coreCrypto.removeClientsFromConversation( - conversationId: conversationId, - clients: [clientId] - ) - + + _ = try await coreCrypto.transaction { + try await $0.removeClientsFromConversation( + conversationId: conversationId, + clients: [clientId] + ) + } + return "removed client from conversation" - - case .processWelcome(welcomePath: let welcomePath): + + case .processWelcome(let welcomePath): guard let coreCrypto else { throw InteropError.notInitialised } - + let welcomeMessage = try Data(contentsOf: welcomePath) - let configuration = CustomConfiguration(keyRotationSpan: nil, wirePolicy: nil) - let bundle = try await coreCrypto.processWelcomeMessage( - welcomeMessage: welcomeMessage, - customConfiguration: configuration - ) - + let configuration = CustomConfiguration( + keyRotationSpan: nil, wirePolicy: nil) + let bundle = try await coreCrypto.transaction { + try await $0.processWelcomeMessage( + welcomeMessage: welcomeMessage, + customConfiguration: configuration + ) + } + return bundle.id.base64EncodedString() - - case .encryptMessage(conversationId: let conversationId, message: let message): + + case .encryptMessage(let conversationId, let message): guard let coreCrypto else { throw InteropError.notInitialised } - - let encryptedMessage = try await coreCrypto.encryptMessage( - conversationId: conversationId, - message: message - ) - + + let encryptedMessage = try await coreCrypto.transaction { + try await $0.encryptMessage( + conversationId: conversationId, + message: message + ) + } + return encryptedMessage.base64EncodedString() - - case .decryptMessage(conversationId: let conversationId, message: let message): + + case .decryptMessage(let conversationId, let message): guard let coreCrypto else { throw InteropError.notInitialised } - - let decryptedMessage = try await coreCrypto.decryptMessage( - conversationId: conversationId, - payload: message - ) - + + let decryptedMessage = try await coreCrypto.transaction { + try await $0.decryptMessage( + conversationId: conversationId, + payload: message + ) + } + if let plaintext = decryptedMessage.message { return plaintext.base64EncodedString() } else { return "decrypted protocol message" } - + case .initProteus: if coreCrypto == nil { self.coreCrypto = try await coreCryptoDeferredInit( path: generateKeystorePath(), key: "secret" ) - - try await self.coreCrypto?.provideTransport(callbacks: TransportProvider()) + + try await self.coreCrypto?.provideTransport( + callbacks: TransportProvider()) } - - try await coreCrypto?.proteusInit() - + + try await coreCrypto?.transaction { try await $0.proteusInit() } + return "Initialised proteus" - + case .getPrekey(let id): - guard let coreCrypto else { throw InteropError.notInitialised } - - let prekey = try await coreCrypto.proteusNewPrekey(prekeyId: id) - + guard let coreCrypto else { throw InteropError.notInitialised } + + let prekey = try await coreCrypto.transaction { + try await $0.proteusNewPrekey(prekeyId: id) + } + return prekey.base64EncodedString() - - case .sessionFromPrekey(sessionId: let sessionId, prekey: let prekey): - guard let coreCrypto else { throw InteropError.notInitialised } - - try await coreCrypto.proteusSessionFromPrekey(sessionId: sessionId, prekey: prekey) - + + case .sessionFromPrekey(let sessionId, let prekey): + guard let coreCrypto else { throw InteropError.notInitialised } + + try await coreCrypto.transaction { + try await $0.proteusSessionFromPrekey( + sessionId: sessionId, prekey: prekey) + } + return "Created session from prekey" - - case .sessionFromMessage(sessionId: let sessionId, message: let message): - guard let coreCrypto else { throw InteropError.notInitialised } - - let decryptedMessage = try await coreCrypto.proteusSessionFromMessage(sessionId: sessionId, envelope: message) - + + case .sessionFromMessage(let sessionId, let message): + guard let coreCrypto else { throw InteropError.notInitialised } + + let decryptedMessage = try await coreCrypto.transaction { + try await $0.proteusSessionFromMessage( + sessionId: sessionId, envelope: message) + } + return decryptedMessage.base64EncodedString() - - case .encryptProteusMessage(sessionId: let sessionId, message: let message): - guard let coreCrypto else { throw InteropError.notInitialised } - - let encryptedMessage = try await coreCrypto.proteusEncrypt(sessionId: sessionId, plaintext: message) - + + case .encryptProteusMessage(let sessionId, let message): + guard let coreCrypto else { throw InteropError.notInitialised } + + let encryptedMessage = try await coreCrypto.transaction { + try await $0.proteusEncrypt( + sessionId: sessionId, plaintext: message) + } + return encryptedMessage.base64EncodedString() - - case .decryptProteusMessage(sessionId: let sessionId, message: let message): - guard let coreCrypto else { throw InteropError.notInitialised } - - let decryptedMessasge = try await coreCrypto.proteusDecrypt(sessionId: sessionId, ciphertext: message) - + + case .decryptProteusMessage(let sessionId, let message): + guard let coreCrypto else { throw InteropError.notInitialised } + + let decryptedMessasge = try await coreCrypto.transaction { + try await $0.proteusDecrypt( + sessionId: sessionId, ciphertext: message) + } + return decryptedMessasge.base64EncodedString() - + case .getFingerprint: guard let coreCrypto else { throw InteropError.notInitialised } - + let fingerprint = try await coreCrypto.proteusFingerprint() - + return fingerprint } } diff --git a/interop/src/clients/corecrypto/web.rs b/interop/src/clients/corecrypto/web.rs index a53b790f8d..2fd56e6c9a 100644 --- a/interop/src/clients/corecrypto/web.rs +++ b/interop/src/clients/corecrypto/web.rs @@ -129,7 +129,9 @@ impl EmulatedMlsClient for CoreCryptoWebClient { .execute_async( r#" const [ciphersuite, callback] = arguments; -window.cc.clientKeypackages(ciphersuite, window.credentialType, 1).then(([kp]) => callback(kp));"#, +window.cc.transaction((ctx) => + ctx.clientKeypackages(ciphersuite, window.credentialType, 1) +).then(([kp]) => callback(kp));"#, vec![serde_json::json!(ciphersuite)], ) .await @@ -156,10 +158,13 @@ const [cId, kp, callback] = arguments; const conversationId = Uint8Array.from(Object.values(cId)); const keyPackage = Uint8Array.from(Object.values(kp)); if (!window.cc.conversationExists(conversationId)) { - await window.cc.createConversation(conversationId); + await window.cc.transaction((ctx) => + ctx.createConversation(conversationId) + ); } -window.cc.addClientsToConversation(conversationId, [{ kp: keyPackage }]) - .then(({ welcome }) => callback(welcome));"#, +window.cc.transaction((ctx) => + ctx.addClientsToConversation(conversationId, [{ kp: keyPackage }])) +.then(({ welcome }) => callback(welcome));"#, vec![conversation_id.into(), kp.into()], ) .await?; @@ -174,8 +179,9 @@ window.cc.addClientsToConversation(conversationId, [{ kp: keyPackage }]) const [cId, clId, callback] = arguments; const conversationId = Uint8Array.from(Object.values(cId)); const clientId = Uint8Array.from(Object.values(clId)); -window.cc.removeClientsFromConversation(conversationId, [clientId]) - .then(({ commit }) => callback(commit));"#, +window.cc.transaction((ctx) => + ctx.removeClientsFromConversation(conversationId, [clientId])) +.then(({ commit }) => callback(commit));"#, vec![conversation_id.into(), client_id.into()], ) .await @@ -189,8 +195,9 @@ window.cc.removeClientsFromConversation(conversationId, [clientId]) r#" const [welcome, callback] = arguments; const welcomeMessage = Uint8Array.from(Object.values(welcome)); -window.cc.processWelcomeMessage(welcomeMessage) - .then(({ id }) => callback(id));"#, +window.cc.transaction((ctx) => + ctx.processWelcomeMessage(welcomeMessage)) +.then(({ id }) => callback(id));"#, vec![welcome.into()], ) .await @@ -205,8 +212,9 @@ window.cc.processWelcomeMessage(welcomeMessage) const [cId, cleartext, callback] = arguments; const conversationId = Uint8Array.from(Object.values(cId)); const message = Uint8Array.from(Object.values(cleartext)); -window.cc.encryptMessage(conversationId, message) - .then(callback);"#, +window.cc.transaction((ctx) => + ctx.encryptMessage(conversationId, message)) +.then(callback);"#, vec![conversation_id.into(), message.into()], ) .await @@ -221,8 +229,9 @@ window.cc.encryptMessage(conversationId, message) const [cId, encMessage, callback] = arguments; const conversationId = Uint8Array.from(Object.values(cId)); const encryptedMessage = Uint8Array.from(Object.values(encMessage)); -window.cc.decryptMessage(conversationId, encryptedMessage) - .then(({ message }) => callback(message));"#, +window.cc.transaction((ctx) => + ctx.decryptMessage(conversationId, encryptedMessage) +).then(({ message }) => callback(message));"#, vec![conversation_id.into(), message.into()], ) .await?; @@ -243,7 +252,9 @@ impl crate::clients::EmulatedProteusClient for CoreCryptoWebClient { .execute_async( r#" const [callback] = arguments; -window.cc.proteusInit().then(callback);"#, +window.cc.transaction((ctx) => + ctx.proteusInit() +).then(callback);"#, vec![], ) .await?; @@ -259,7 +270,9 @@ window.cc.proteusInit().then(callback);"#, .execute_async( r#" const [prekeyId, callback] = arguments; -window.cc.proteusNewPrekey(prekeyId).then(callback);"#, +window.cc.transaction((ctx) => + ctx.proteusNewPrekey(prekeyId) +).then(callback);"#, vec![prekey_last_id.into()], ) .await @@ -274,7 +287,9 @@ window.cc.proteusNewPrekey(prekeyId).then(callback);"#, r#" const [sessionId, prekey, callback] = arguments; const prekeyBuffer = Uint8Array.from(Object.values(prekey)); -window.cc.proteusSessionFromPrekey(sessionId, prekeyBuffer).then(callback);"#, +window.cc.transaction((ctx) => + ctx.proteusSessionFromPrekey(sessionId, prekeyBuffer) +).then(callback);"#, vec![session_id.into(), prekey.into()], ) .await?; @@ -288,7 +303,9 @@ window.cc.proteusSessionFromPrekey(sessionId, prekeyBuffer).then(callback);"#, r#" const [sessionId, message, callback] = arguments; const messageBuffer = Uint8Array.from(Object.values(message)); -window.cc.proteusSessionFromMessage(sessionId, messageBuffer).then(callback);"#, +window.cc.transaction((ctx) => + ctx.proteusSessionFromMessage(sessionId, messageBuffer) +).then(callback);"#, vec![session_id.into(), message.into()], ) .await @@ -303,7 +320,9 @@ window.cc.proteusSessionFromMessage(sessionId, messageBuffer).then(callback);"#, r#" const [sessionId, plaintext, callback] = arguments; const plaintextBuffer = Uint8Array.from(Object.values(plaintext)); -window.cc.proteusEncrypt(sessionId, plaintextBuffer).then(callback);"#, +window.cc.transaction((ctx) => + ctx.proteusEncrypt(sessionId, plaintextBuffer) +).then(callback);"#, vec![session_id.into(), plaintext.into()], ) .await @@ -319,7 +338,9 @@ window.cc.proteusEncrypt(sessionId, plaintextBuffer).then(callback);"#, r#" const [sessionId, ciphertext, callback] = arguments; const ciphertextBuffer = Uint8Array.from(Object.values(ciphertext)); -window.cc.proteusDecrypt(sessionId, ciphertextBuffer).then(callback);"#, +window.cc.transaction((ctx) => + ctx.proteusDecrypt(sessionId, ciphertextBuffer) +).then(callback);"#, vec![session_id.into(), ciphertext.into()], ) .await From 7167a69cc969a7723b0f7edeadb63d6ba2381807 Mon Sep 17 00:00:00 2001 From: SimonThormeyer Date: Mon, 20 Jan 2025 15:04:12 +0100 Subject: [PATCH 2/5] chore: update wrapper tests to transaction API --- crypto-ffi/bindings/js/test/utils.ts | 27 ++++++++++++------- .../com/wire/crypto/ProteusClientTest.kt | 2 +- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/crypto-ffi/bindings/js/test/utils.ts b/crypto-ffi/bindings/js/test/utils.ts index e5714eb25f..46e967c1ac 100644 --- a/crypto-ffi/bindings/js/test/utils.ts +++ b/crypto-ffi/bindings/js/test/utils.ts @@ -149,9 +149,11 @@ export async function createConversation( async (clientName, conversationId) => { const cc = window.ensureCcDefined(clientName); const encoder = new TextEncoder(); - await cc.createConversation( - encoder.encode(conversationId), - window.ccModule.CredentialType.Basic + await cc.transaction((ctx) => + ctx.createConversation( + encoder.encode(conversationId), + window.ccModule.CredentialType.Basic + ) ); }, clientName, @@ -183,18 +185,23 @@ export async function invite( const cc1 = window.ensureCcDefined(client1); const cc2 = window.ensureCcDefined(client2); - const [kp] = await cc2.clientKeypackages( - window.defaultCipherSuite, - window.ccModule.CredentialType.Basic, - 1 + const [kp] = await cc2.transaction((ctx) => + ctx.clientKeypackages( + window.defaultCipherSuite, + window.ccModule.CredentialType.Basic, + 1 + ) ); + const encoder = new TextEncoder(); const conversationIdBytes = encoder.encode(conversationId); - await cc1.addClientsToConversation(conversationIdBytes, [kp]); + await cc1.transaction((ctx) => + ctx.addClientsToConversation(conversationIdBytes, [kp]) + ); const { groupInfo, welcome } = await window.deliveryService.getLatestCommitBundle(); - await cc2.processWelcomeMessage(welcome!); + await cc2.transaction((ctx) => ctx.processWelcomeMessage(welcome!)); return groupInfo; }, @@ -304,7 +311,7 @@ export async function proteusInit(clientName: string): Promise { }; const instance = await window.ccModule.CoreCrypto.deferredInit(clientConfig); - await instance.proteusInit(); + await instance.transaction((ctx) => ctx.proteusInit()); if (window.cc === undefined) { window.cc = {}; diff --git a/crypto-ffi/bindings/jvm/src/test/kotlin/com/wire/crypto/ProteusClientTest.kt b/crypto-ffi/bindings/jvm/src/test/kotlin/com/wire/crypto/ProteusClientTest.kt index 3aec2b8be7..a8885ee077 100644 --- a/crypto-ffi/bindings/jvm/src/test/kotlin/com/wire/crypto/ProteusClientTest.kt +++ b/crypto-ffi/bindings/jvm/src/test/kotlin/com/wire/crypto/ProteusClientTest.kt @@ -36,7 +36,7 @@ internal class ProteusClientTest { val root = Files.createTempDirectory("mls").toFile() val keyStore = root.resolve("keystore-$clientId") val cc = CoreCrypto(keyStore.absolutePath, "secret") - cc.proteusInit() + cc.transaction { it.proteusInit() } cc } From 848ddf574489489db86cd72aeb67ed06ef268ef5 Mon Sep 17 00:00:00 2001 From: SimonThormeyer Date: Mon, 20 Jan 2025 15:27:20 +0100 Subject: [PATCH 3/5] refactor!: stop exposing deprecated functions in Kotlin/TS wrapper [WPB-15292] --- crypto-ffi/bindings/js/src/CoreCrypto.ts | 1 - .../bindings/js/src/CoreCryptoInstance.ts | 716 +----------------- .../main/kotlin/com/wire/crypto/CoreCrypto.kt | 10 - .../kotlin/com/wire/crypto/E2EIEnrollment.kt | 14 - 4 files changed, 2 insertions(+), 739 deletions(-) diff --git a/crypto-ffi/bindings/js/src/CoreCrypto.ts b/crypto-ffi/bindings/js/src/CoreCrypto.ts index 31b32d4427..7bf17c7cf5 100644 --- a/crypto-ffi/bindings/js/src/CoreCrypto.ts +++ b/crypto-ffi/bindings/js/src/CoreCrypto.ts @@ -21,7 +21,6 @@ export { CoreCryptoContext } from "./CoreCryptoContext.js"; export { BuildMetadata, - initLogger, setLogger, CoreCryptoLogLevel, setMaxLogLevel, diff --git a/crypto-ffi/bindings/js/src/CoreCryptoInstance.ts b/crypto-ffi/bindings/js/src/CoreCryptoInstance.ts index 2e66341500..392dd37159 100644 --- a/crypto-ffi/bindings/js/src/CoreCryptoInstance.ts +++ b/crypto-ffi/bindings/js/src/CoreCryptoInstance.ts @@ -24,9 +24,6 @@ import { E2eiDumpedPkiEnv, MlsTransportProvider, WireIdentity, - ConversationConfiguration, - CustomConfiguration, - WelcomeBundle, } from "./core-crypto-ffi.js"; import { CoreCryptoError } from "./CoreCryptoError.js"; @@ -37,21 +34,12 @@ import { ConversationId, ClientId, Ciphersuite, - DecryptedMessage, MlsTransport, } from "./CoreCryptoMLS.js"; import { CoreCryptoContext } from "./CoreCryptoContext.js"; -import { - E2eiConversationState, - E2eiEnrollment, - NewCrlDistributionPoints, - CRLRegistration, - normalizeEnum, -} from "./CoreCryptoE2EI.js"; - -import { ProteusAutoPrekeyBundle } from "./CoreCryptoProteus.js"; +import { E2eiConversationState, normalizeEnum } from "./CoreCryptoE2EI.js"; /** * Params for CoreCrypto deferred initialization @@ -98,26 +86,6 @@ export interface CoreCryptoParams extends CoreCryptoDeferredParams { nbKeyPackage?: number; } -/** - * Initializes the global logger for Core Crypto and registers the callback. - * - * **NOTE:** you must call this after `await CoreCrypto.init(params)` or `await CoreCrypto.deferredInit(params)`. - * - * @deprecated use {@link CoreCrypto.setLogger} instead. - * - * @param logger - the interface to be called when something is going to be logged - * @param level - the max level that should be logged - **/ -export function initLogger( - logger: CoreCryptoLogger, - level: CoreCryptoLogLevel, - ctx: unknown = null -): void { - const wasmLogger = new CoreCryptoWasmLogger(logger.log, ctx); - CoreCrypto.setLogger(wasmLogger); - CoreCrypto.setMaxLogLevel(level); -} - /** * Initializes the global logger for Core Crypto and registers the callback. * @@ -265,7 +233,7 @@ export class CoreCrypto { * Almost identical to {@link CoreCrypto.init} but allows a 2 phase initialization of MLS. * First, calling this will set up the keystore and will allow generating proteus prekeys. * Then, those keys can be traded for a clientId. - * Use this clientId to initialize MLS with {@link CoreCrypto.mlsInit}. + * Use this clientId to initialize MLS with {@link CoreCryptoContext.mlsInit}. * @param params - {@link CoreCryptoDeferredParams} */ static async deferredInit({ @@ -325,58 +293,6 @@ export class CoreCrypto { return result; } - /** - * See {@link CoreCryptoContext.mlsInit}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.mlsInit} instead. - */ - async mlsInit( - clientId: ClientId, - ciphersuites: Ciphersuite[], - nbKeyPackage?: number - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.mlsInit(clientId, ciphersuites, nbKeyPackage) - ); - } - - /** - * See {@link CoreCryptoContext.mlsGenerateKeypair}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.mlsGenerateKeypair} instead. - */ - async mlsGenerateKeypair( - ciphersuites: Ciphersuite[] - ): Promise { - return await this.transaction( - async (ctx) => await ctx.mlsGenerateKeypair(ciphersuites) - ); - } - - /** - * See {@link CoreCryptoContext.mlsInitWithClientId}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.mlsInitWithClientId} instead. - */ - async mlsInitWithClientId( - clientId: ClientId, - signaturePublicKeys: Uint8Array[], - ciphersuites: Ciphersuite[] - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.mlsInitWithClientId( - clientId, - signaturePublicKeys, - ciphersuites - ) - ); - } - /** @hidden */ private constructor(cc: CoreCryptoFfiTypes.CoreCrypto) { this.#cc = cc; @@ -442,22 +358,6 @@ export class CoreCrypto { ); } - /** - * See {@link CoreCryptoContext.markConversationAsChildOf}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.markConversationAsChildOf} instead. - */ - async markConversationAsChildOf( - childId: ConversationId, - parentId: ConversationId - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.markConversationAsChildOf(childId, parentId) - ); - } - /** * See {@link CoreCryptoContext.conversationEpoch}. * @@ -489,85 +389,6 @@ export class CoreCrypto { ); } - /** - * See {@link CoreCryptoContext.wipeConversation}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.wipeConversation} instead. - */ - async wipeConversation(conversationId: ConversationId): Promise { - return await this.transaction( - async (ctx) => await ctx.wipeConversation(conversationId) - ); - } - - /** - * See {@link CoreCryptoContext.createConversation}. - * - * @deprecated Create a transaction with {@link transaction} - * and use {@link CoreCryptoContext.createConversation} instead. - */ - async createConversation( - conversationId: ConversationId, - creatorCredentialType: CredentialType, - configuration: Partial = {} - ) { - return await this.transaction( - async (ctx) => - await ctx.createConversation( - conversationId, - creatorCredentialType, - configuration - ) - ); - } - - /** - * See {@link CoreCryptoContext.decryptMessage}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.decryptMessage} instead. - */ - async decryptMessage( - conversationId: ConversationId, - payload: Uint8Array - ): Promise { - return await this.transaction( - async (ctx) => await ctx.decryptMessage(conversationId, payload) - ); - } - - /** - * See {@link CoreCryptoContext.encryptMessage}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.encryptMessage} instead. - */ - async encryptMessage( - conversationId: ConversationId, - message: Uint8Array - ): Promise { - return await this.transaction( - async (ctx) => await ctx.encryptMessage(conversationId, message) - ); - } - - /** - * See {@link CoreCryptoContext.processWelcomeMessage}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.processWelcomeMessage} instead. - */ - async processWelcomeMessage( - welcomeMessage: Uint8Array, - configuration: Partial = {} - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.processWelcomeMessage(welcomeMessage, configuration) - ); - } - /** * See {@link CoreCryptoContext.clientPublicKey}. * @@ -584,152 +405,6 @@ export class CoreCrypto { ); } - /** - * See {@link CoreCryptoContext.clientValidKeypackagesCount}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.clientValidKeypackagesCount} instead. - */ - async clientValidKeypackagesCount( - ciphersuite: Ciphersuite, - credentialType: CredentialType - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.clientValidKeypackagesCount( - ciphersuite, - credentialType - ) - ); - } - - /** - * See {@link CoreCryptoContext.clientKeypackages}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.clientKeypackages} instead. - */ - async clientKeypackages( - ciphersuite: Ciphersuite, - credentialType: CredentialType, - amountRequested: number - ): Promise> { - return await this.transaction( - async (ctx) => - await ctx.clientKeypackages( - ciphersuite, - credentialType, - amountRequested - ) - ); - } - - /** - * See {@link CoreCryptoContext.deleteKeypackages}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.deleteKeypackages} instead. - */ - async deleteKeypackages(refs: Uint8Array[]): Promise { - return await this.transaction( - async (ctx) => await ctx.deleteKeypackages(refs) - ); - } - - /** - * See {@link CoreCryptoContext.addClientsToConversation}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.addClientsToConversation} instead. - */ - async addClientsToConversation( - conversationId: ConversationId, - keyPackages: Uint8Array[] - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.addClientsToConversation(conversationId, keyPackages) - ); - } - - /** - * See {@link CoreCryptoContext.removeClientsFromConversation}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.removeClientsFromConversation} instead. - */ - async removeClientsFromConversation( - conversationId: ConversationId, - clientIds: ClientId[] - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.removeClientsFromConversation( - conversationId, - clientIds - ) - ); - } - - /** - * See {@link CoreCryptoContext.updateKeyingMaterial}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.updateKeyingMaterial} instead. - */ - async updateKeyingMaterial(conversationId: ConversationId): Promise { - return await this.transaction( - async (ctx) => await ctx.updateKeyingMaterial(conversationId) - ); - } - - /** - * See {@link CoreCryptoContext.e2eiRotate}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.e2eiRotate} instead. - */ - async e2eiRotate(conversationId: ConversationId): Promise { - return await this.transaction( - async (ctx) => await ctx.e2eiRotate(conversationId) - ); - } - - /** - * See {@link CoreCryptoContext.commitPendingProposals}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.commitPendingProposals} instead. - */ - async commitPendingProposals( - conversationId: ConversationId - ): Promise { - return await this.transaction( - async (ctx) => await ctx.commitPendingProposals(conversationId) - ); - } - - /** - * See {@link CoreCryptoContext.joinByExternalCommit}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.joinByExternalCommit} instead. - */ - async joinByExternalCommit( - groupInfo: Uint8Array, - credentialType: CredentialType, - configuration: Partial = {} - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.joinByExternalCommit( - groupInfo, - credentialType, - configuration - ) - ); - } - /** * See {@link CoreCryptoContext.exportSecretKey}. * @@ -802,86 +477,6 @@ export class CoreCrypto { return await CoreCryptoError.asyncMapErr(this.#cc.reseed_rng(seed)); } - /** - * Initializes the proteus client - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusInit} instead. - */ - async proteusInit(): Promise { - return await this.transaction(async (ctx) => await ctx.proteusInit()); - } - - /** - * Create a Proteus session using a prekey - * - * @param sessionId - ID of the Proteus session - * @param prekey - CBOR-encoded Proteus prekey of the other client - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusSessionFromPrekey} instead. - */ - async proteusSessionFromPrekey( - sessionId: string, - prekey: Uint8Array - ): Promise { - return await this.transaction( - async (ctx) => await ctx.proteusSessionFromPrekey(sessionId, prekey) - ); - } - - /** - * Create a Proteus session from a handshake message - * - * @param sessionId - ID of the Proteus session - * @param envelope - CBOR-encoded Proteus message - * - * @returns A `Uint8Array` containing the message that was sent along with the session handshake - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusSessionFromMessage} instead. - */ - async proteusSessionFromMessage( - sessionId: string, - envelope: Uint8Array - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.proteusSessionFromMessage(sessionId, envelope) - ); - } - - /** - * Locally persists a session to the keystore - * - * **Note**: This isn't usually needed as persisting sessions happens automatically when decrypting/encrypting messages and initializing Sessions - * - * @param sessionId - ID of the Proteus session - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusSessionSave} instead. - */ - async proteusSessionSave(sessionId: string): Promise { - return await this.transaction( - async (ctx) => await ctx.proteusSessionSave(sessionId) - ); - } - - /** - * Deletes a session - * Note: this also deletes the persisted data within the keystore - * - * @param sessionId - ID of the Proteus session - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusSessionDelete} instead. - */ - async proteusSessionDelete(sessionId: string): Promise { - return await this.transaction( - async (ctx) => await ctx.proteusSessionDelete(sessionId) - ); - } - /** * Checks if a session exists * @@ -895,106 +490,6 @@ export class CoreCrypto { ); } - /** - * Decrypt an incoming message for an existing Proteus session - * - * @param sessionId - ID of the Proteus session - * @param ciphertext - CBOR encoded, encrypted proteus message - * @returns The decrypted payload contained within the message - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusDecrypt} instead. - */ - async proteusDecrypt( - sessionId: string, - ciphertext: Uint8Array - ): Promise { - return await this.transaction( - async (ctx) => await ctx.proteusDecrypt(sessionId, ciphertext) - ); - } - - /** - * Encrypt a message for a given Proteus session - * - * @param sessionId - ID of the Proteus session - * @param plaintext - payload to encrypt - * @returns The CBOR-serialized encrypted message - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusEncrypt} instead. - */ - async proteusEncrypt( - sessionId: string, - plaintext: Uint8Array - ): Promise { - return await this.transaction( - async (ctx) => await ctx.proteusEncrypt(sessionId, plaintext) - ); - } - - /** - * Batch encryption for proteus messages - * This is used to minimize FFI roundtrips when used in the context of a multi-client session (i.e. conversation) - * - * @param sessions - List of Proteus session IDs to encrypt the message for - * @param plaintext - payload to encrypt - * @returns A map indexed by each session ID and the corresponding CBOR-serialized encrypted message for this session - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusEncryptBatched} instead. - */ - async proteusEncryptBatched( - sessions: string[], - plaintext: Uint8Array - ): Promise> { - return await this.transaction( - async (ctx) => await ctx.proteusEncryptBatched(sessions, plaintext) - ); - } - - /** - * Creates a new prekey with the requested ID. - * - * @param prekeyId - ID of the PreKey to generate. This cannot be bigger than a u16 - * @returns: A CBOR-serialized version of the PreKeyBundle corresponding to the newly generated and stored PreKey - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusNewPrekey} instead. - */ - async proteusNewPrekey(prekeyId: number): Promise { - return await this.transaction( - async (ctx) => await ctx.proteusNewPrekey(prekeyId) - ); - } - - /** - * Creates a new prekey with an automatically generated ID.. - * - * @returns A CBOR-serialized version of the PreKeyBundle corresponding to the newly generated and stored PreKey accompanied by its ID - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusNewPrekeyAuto} instead. - */ - async proteusNewPrekeyAuto(): Promise { - return await this.transaction( - async (ctx) => await ctx.proteusNewPrekeyAuto() - ); - } - - /** - * Proteus last resort prekey stuff - * - * @returns A CBOR-serialize version of the PreKeyBundle associated with the last resort PreKey (holding the last resort prekey id) - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusLastResortPrekey} instead. - */ - async proteusLastResortPrekey(): Promise { - return await this.transaction( - async (ctx) => await ctx.proteusLastResortPrekey() - ); - } - /** * @returns The last resort PreKey id */ @@ -1052,118 +547,6 @@ export class CoreCrypto { } } - /** - * Imports all the data stored by Cryptobox into the CoreCrypto keystore - * - * @param storeName - The name of the IndexedDB store where the data is stored - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.proteusCryptoboxMigrate} instead. - */ - async proteusCryptoboxMigrate(storeName: string): Promise { - return await this.transaction( - async (ctx) => await ctx.proteusCryptoboxMigrate(storeName) - ); - } - - /** - * See {@link CoreCryptoContext.e2eiNewEnrollment}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.e2eiNewEnrollment} instead. - */ - async e2eiNewEnrollment( - clientId: string, - displayName: string, - handle: string, - expirySec: number, - ciphersuite: Ciphersuite, - team?: string - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.e2eiNewEnrollment( - clientId, - displayName, - handle, - expirySec, - ciphersuite, - team - ) - ); - } - - /** - * See {@link CoreCryptoContext.e2eiNewActivationEnrollment}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.e2eiNewActivationEnrollment} instead. - */ - async e2eiNewActivationEnrollment( - displayName: string, - handle: string, - expirySec: number, - ciphersuite: Ciphersuite, - team?: string - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.e2eiNewActivationEnrollment( - displayName, - handle, - expirySec, - ciphersuite, - team - ) - ); - } - - /** - * See {@link CoreCryptoContext.e2eiNewRotateEnrollment}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.e2eiNewRotateEnrollment} instead. - */ - async e2eiNewRotateEnrollment( - expirySec: number, - ciphersuite: Ciphersuite, - displayName?: string, - handle?: string, - team?: string - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.e2eiNewRotateEnrollment( - expirySec, - ciphersuite, - displayName, - handle, - team - ) - ); - } - - /** - * See {@link CoreCryptoContext.e2eiMlsInitOnly}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.e2eiMlsInitOnly} instead. - */ - async e2eiMlsInitOnly( - enrollment: E2eiEnrollment, - certificateChain: string, - nbKeyPackage?: number - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.e2eiMlsInitOnly( - enrollment, - certificateChain, - nbKeyPackage - ) - ); - } - /** * See {@link CoreCryptoContext.e2eiDumpPKIEnv}. * @@ -1181,101 +564,6 @@ export class CoreCrypto { return await this.#cc.e2ei_is_pki_env_setup(); } - /** - * See {@link CoreCryptoContext.e2eiRegisterAcmeCA}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.e2eiRegisterAcmeCA} instead. - */ - async e2eiRegisterAcmeCA(trustAnchorPEM: string): Promise { - return await this.transaction( - async (ctx) => await ctx.e2eiRegisterAcmeCA(trustAnchorPEM) - ); - } - - /** - * See {@link CoreCryptoContext.e2eiRegisterIntermediateCA}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.e2eiRegisterIntermediateCA} instead. - */ - async e2eiRegisterIntermediateCA( - certPEM: string - ): Promise { - return await this.transaction( - async (ctx) => await ctx.e2eiRegisterIntermediateCA(certPEM) - ); - } - - /** - * See {@link CoreCryptoContext.e2eiRegisterCRL}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.e2eiRegisterCRL} instead. - */ - async e2eiRegisterCRL( - crlDP: string, - crlDER: Uint8Array - ): Promise { - return await this.transaction( - async (ctx) => await ctx.e2eiRegisterCRL(crlDP, crlDER) - ); - } - - /** - * See {@link CoreCryptoContext.saveX509Credential}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.saveX509Credential} instead. - */ - async saveX509Credential( - enrollment: E2eiEnrollment, - certificateChain: string - ): Promise { - return await this.transaction( - async (ctx) => - await ctx.saveX509Credential(enrollment, certificateChain) - ); - } - - /** - * See {@link CoreCryptoContext.e2eiEnrollmentStash}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.e2eiEnrollmentStash} instead. - */ - async e2eiEnrollmentStash(enrollment: E2eiEnrollment): Promise { - return await this.transaction( - async (ctx) => await ctx.e2eiEnrollmentStash(enrollment) - ); - } - - /** - * See {@link CoreCryptoContext.e2eiEnrollmentStashPop}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.e2eiEnrollmentStashPop} instead. - */ - async e2eiEnrollmentStashPop(handle: Uint8Array): Promise { - return await this.transaction( - async (ctx) => await ctx.e2eiEnrollmentStashPop(handle) - ); - } - - /** - * See {@link CoreCryptoContext.e2eiConversationState}. - * - * @deprecated Create a transaction with {@link CoreCrypto.transaction} - * and use {@link CoreCryptoContext.e2eiConversationState} instead. - */ - async e2eiConversationState( - conversationId: ConversationId - ): Promise { - return await this.transaction( - async (ctx) => await ctx.e2eiConversationState(conversationId) - ); - } - /** * See {@link CoreCryptoContext.e2eiIsEnabled}. * diff --git a/crypto-ffi/bindings/jvm/src/main/kotlin/com/wire/crypto/CoreCrypto.kt b/crypto-ffi/bindings/jvm/src/main/kotlin/com/wire/crypto/CoreCrypto.kt index e625f35870..021527c37c 100644 --- a/crypto-ffi/bindings/jvm/src/main/kotlin/com/wire/crypto/CoreCrypto.kt +++ b/crypto-ffi/bindings/jvm/src/main/kotlin/com/wire/crypto/CoreCrypto.kt @@ -106,16 +106,6 @@ class CoreCrypto(private val cc: com.wire.crypto.uniffi.CoreCrypto) { return result as R } - /** - * Initialise [CoreCrypto] to be used with proteus. - * - * All proteus related methods will fail until this function is called. - */ - @Deprecated("Use the method inside a transaction on the CoreCryptoContext object.") - suspend fun proteusInit() { - this.transaction { ctx -> ctx.proteusInit() } - } - suspend fun provideTransport(transport: MlsTransport) { cc.provideTransport(transport) } diff --git a/crypto-ffi/bindings/jvm/src/main/kotlin/com/wire/crypto/E2EIEnrollment.kt b/crypto-ffi/bindings/jvm/src/main/kotlin/com/wire/crypto/E2EIEnrollment.kt index d4b678cd5b..efa0e325b3 100644 --- a/crypto-ffi/bindings/jvm/src/main/kotlin/com/wire/crypto/E2EIEnrollment.kt +++ b/crypto-ffi/bindings/jvm/src/main/kotlin/com/wire/crypto/E2EIEnrollment.kt @@ -229,20 +229,6 @@ class E2EIEnrollment(private val delegate: com.wire.crypto.uniffi.E2eiEnrollment previousNonce: String, ) = delegate.newOidcChallengeRequest(idToken, refreshToken, previousNonce) - /** - * Parses the response from `POST /acme/{provisioner-name}/challenge/{challenge-id}` for OIDC - * challenge. - * - * @param cc CoreCrypto instance - * @param challenge HTTP response body - * @see https://www.rfc-editor.org/rfc/rfc8555.html#section-7.5.1 - */ - @Deprecated( - "Use contextOidcChallengeResponse() with the CoreCryptoContext object created from a CoreCryptoCentral.transaction call" - ) - suspend fun oidcChallengeResponse(cc: CoreCrypto, challenge: JsonRawData) = - delegate.newOidcChallengeResponse(cc.lower(), challenge) - /** * Parses the response from `POST /acme/{provisioner-name}/challenge/{challenge-id}` for OIDC * challenge within a CoreCryptoContext. From 21a8d74cda21b855dccc0530c960328b541100d3 Mon Sep 17 00:00:00 2001 From: SimonThormeyer Date: Mon, 20 Jan 2025 17:43:23 +0100 Subject: [PATCH 4/5] refactor!: stop exposing data-mutating functions on uniffi core crypto type [WPB-15292] These were deprecated for some time now. They created a transaction internally. Now, an explicit transaction created on the core crypto transaction context must be used. --- crypto-ffi/src/generic/context/mod.rs | 22 - crypto-ffi/src/generic/mod.rs | 743 +------------------------- 2 files changed, 7 insertions(+), 758 deletions(-) diff --git a/crypto-ffi/src/generic/context/mod.rs b/crypto-ffi/src/generic/context/mod.rs index c0aa460c0a..e1731537ec 100644 --- a/crypto-ffi/src/generic/context/mod.rs +++ b/crypto-ffi/src/generic/context/mod.rs @@ -188,28 +188,6 @@ impl CoreCrypto { } } } -impl CoreCrypto { - /// For internal use in deprecated functions. - pub(crate) async fn deprecated_transaction(&self, callback: F) -> CoreCryptoResult - where - F: FnOnce(CentralContext) -> Fut, - Fut: Future>, - E: Into, - { - let context = self.central.new_transaction().await?; - let result = callback(context.clone()).await; - match result { - Ok(result) => { - context.finish().await?; - Ok(result) - } - Err(err) => { - context.abort().await?; - Err(>::into(err).into()) - } - } - } -} #[uniffi::export] impl CoreCryptoContext { diff --git a/crypto-ffi/src/generic/mod.rs b/crypto-ffi/src/generic/mod.rs index fd954dfd0a..a0ecee6cac 100644 --- a/crypto-ffi/src/generic/mod.rs +++ b/crypto-ffi/src/generic/mod.rs @@ -1,4 +1,3 @@ -#![allow(deprecated)] // Wire // Copyright (C) 2022 Wire Swiss GmbH @@ -17,7 +16,7 @@ use std::{ collections::{BTreeMap, HashMap}, - ops::{Deref, DerefMut}, + ops::Deref, sync::{Arc, LazyLock, Once}, }; @@ -26,16 +25,15 @@ use log::{ Level, LevelFilter, Metadata, Record, }; use log_reload::ReloadLog; -use tls_codec::{Deserialize, Serialize}; +use tls_codec::Deserialize; use self::context::CoreCryptoContext; use crate::{proteus_impl, UniffiCustomTypeConverter}; pub use core_crypto::prelude::ConversationId; use core_crypto::{ prelude::{ - ClientIdentifier, EntropySeed, KeyPackageIn, KeyPackageRef, MlsBufferedConversationDecryptMessage, MlsCentral, - MlsCentralConfiguration, MlsCiphersuite, MlsCommitBundle, MlsConversationConfiguration, - MlsConversationDecryptMessage, MlsCustomConfiguration, MlsGroupInfoBundle, MlsProposalBundle, + EntropySeed, MlsBufferedConversationDecryptMessage, MlsCentral, MlsCentralConfiguration, MlsCiphersuite, + MlsCommitBundle, MlsConversationDecryptMessage, MlsCustomConfiguration, MlsGroupInfoBundle, MlsProposalBundle, VerifiableGroupInfo, }, InnermostErrorMessage, RecursiveError, @@ -961,8 +959,8 @@ impl core_crypto::prelude::MlsTransport for MlsTransportWrapper { } } -/// This is needed instead of the original trait ([core_crypto::CoreCryptoTransport]) to use types -/// that we export via uniffi. +/// Used by core crypto to send commits or application messages to the delivery service. +/// This trait must be implemented before calling any functions that produce commits. #[uniffi::export(with_foreign)] #[async_trait::async_trait] pub trait MlsTransport: std::fmt::Debug + Send + Sync { @@ -1126,7 +1124,7 @@ pub async fn core_crypto_new( #[uniffi::export] /// Similar to [core_crypto_new] but defers MLS initialization. It can be initialized later -/// with [CoreCrypto::mls_init]. +/// with [CoreCryptoContext::mls_init]. pub async fn core_crypto_deferred_init(path: String, key: String) -> CoreCryptoResult { CoreCrypto::new(path, key, None, None, None).await } @@ -1161,78 +1159,6 @@ impl CoreCrypto { Ok(CoreCrypto { central }) } - /// See [core_crypto::context::CentralContext::mls_init] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn mls_init( - &self, - client_id: ClientId, - ciphersuites: Ciphersuites, - nb_key_package: Option, - ) -> CoreCryptoResult<()> { - self.deprecated_transaction(|context| async move { - let nb_key_package = nb_key_package - .map(usize::try_from) - .transpose() - .expect("we never run corecrypto on systems with architectures narrower than 32 bits"); - context - .mls_init( - ClientIdentifier::Basic(client_id.0), - (&ciphersuites).into(), - nb_key_package, - ) - .await - .map_err(RecursiveError::mls("doing mls init")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::mls_generate_keypairs] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn mls_generate_keypairs(&self, ciphersuites: Ciphersuites) -> CoreCryptoResult> { - self.deprecated_transaction(|context| async move { - context - .mls_generate_keypairs((&ciphersuites).into()) - .await - .map(|cids| cids.into_iter().map(ClientId).collect()) - .map_err(RecursiveError::mls("generating mls keypairs")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::mls_init_with_client_id] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn mls_init_with_client_id( - &self, - client_id: ClientId, - tmp_client_ids: Vec, - ciphersuites: Ciphersuites, - ) -> CoreCryptoResult<()> { - self.deprecated_transaction(|context| async move { - context - .mls_init_with_client_id( - client_id.0, - tmp_client_ids.into_iter().map(|cid| cid.0).collect(), - (&ciphersuites).into(), - ) - .await - .map_err(RecursiveError::mls("initing mls with client id")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::proteus_reload_sessions] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn restore_from_disk(&self) -> CoreCryptoResult<()> { - cfg_if::cfg_if! { - if #[cfg(feature = "proteus")] { - self.deprecated_transaction(|context| async move { - context.proteus_reload_sessions().await - }).await? - } - } - Ok(()) - } - /// See [core_crypto::mls::MlsCentral::provide_transport] pub async fn provide_transport(&self, callbacks: Arc) -> CoreCryptoResult<()> { self.central @@ -1253,92 +1179,6 @@ impl CoreCrypto { .await?) } - /// See [core_crypto::context::CentralContext::get_or_create_client_keypackages] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn client_keypackages( - &self, - ciphersuite: Ciphersuite, - credential_type: MlsCredentialType, - amount_requested: u32, - ) -> CoreCryptoResult>> { - self.deprecated_transaction(|context| async move { - let kps = context - .get_or_create_client_keypackages(ciphersuite.into(), credential_type.into(), amount_requested as usize) - .await - .map_err(RecursiveError::mls_client("getting or creating client keypackages"))?; - kps.into_iter() - .map(|kp| { - kp.tls_serialize_detached() - .map_err(core_crypto::mls::conversation::Error::tls_serialize("keypackage")) - .map_err(RecursiveError::mls_conversation("serializing keypackage")) - .map_err(Into::into) - }) - .collect::>>>() - }) - .await - } - - /// See [core_crypto::context::CentralContext::client_valid_key_packages_count] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn client_valid_keypackages_count( - &self, - ciphersuite: Ciphersuite, - credential_type: MlsCredentialType, - ) -> CoreCryptoResult { - self.deprecated_transaction(|context| async move { - context - .client_valid_key_packages_count(ciphersuite.into(), credential_type.into()) - .await - .map(|count| count.try_into().unwrap_or(0)) - .map_err(RecursiveError::mls_client("counting valid key packages")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::delete_keypackages] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn delete_keypackages(&self, refs: Vec>) -> CoreCryptoResult<()> { - let refs = refs - .into_iter() - .map(|r| KeyPackageRef::from_slice(&r)) - .collect::>(); - - self.deprecated_transaction(|context| async move { - context - .delete_keypackages(&refs[..]) - .await - .map_err(RecursiveError::mls_client("deleting keypackages")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::new_conversation] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn create_conversation( - &self, - conversation_id: Vec, - creator_credential_type: MlsCredentialType, - config: ConversationConfiguration, - ) -> CoreCryptoResult<()> { - let mut lower_cfg = MlsConversationConfiguration { - custom: config.custom.into(), - ciphersuite: config.ciphersuite.into(), - ..Default::default() - }; - - self.deprecated_transaction(|context| async move { - context - .set_raw_external_senders(&mut lower_cfg, config.external_senders) - .await - .map_err(RecursiveError::mls_conversation("setting raw external senders"))?; - context - .new_conversation(&conversation_id, creator_credential_type.into(), lower_cfg) - .await - .map_err(RecursiveError::mls("creating new conversation")) - }) - .await - } - /// See [core_crypto::mls::MlsCentral::conversation_epoch] pub async fn conversation_epoch(&self, conversation_id: Vec) -> CoreCryptoResult { Ok(self.central.conversation_epoch(&conversation_id).await?) @@ -1350,196 +1190,11 @@ impl CoreCrypto { Ok(Ciphersuite::from(core_crypto::prelude::CiphersuiteName::from(cs))) } - /// See [core_crypto::context::CentralContext::process_raw_welcome_message] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn process_welcome_message( - &self, - welcome_message: Vec, - custom_configuration: CustomConfiguration, - ) -> CoreCryptoResult { - self.deprecated_transaction(|context| async move { - context - .process_raw_welcome_message(welcome_message, custom_configuration.into()) - .await - .map(Into::into) - .map_err(RecursiveError::mls_conversation("processing welcome message")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::add_members_to_conversation] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn add_clients_to_conversation( - &self, - conversation_id: Vec, - key_packages: Vec>, - ) -> CoreCryptoResult { - let key_packages = key_packages - .into_iter() - .map(|kp| KeyPackageIn::tls_deserialize(&mut kp.as_slice()).map_err(CoreCryptoError::generic())) - .collect::>>()?; - - Ok(self - .deprecated_transaction(|context| async move { - context - .add_members_to_conversation(&conversation_id, key_packages) - .await - .map_err(RecursiveError::mls_conversation("adding members to conversation")) - }) - .await - .map(|new_crl_distribution_point| -> Option> { new_crl_distribution_point.into() })? - .into()) - } - - /// See [core_crypto::context::CentralContext::remove_members_from_conversation] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn remove_clients_from_conversation( - &self, - conversation_id: Vec, - clients: Vec, - ) -> CoreCryptoResult<()> { - let clients: Vec = clients.into_iter().map(|c| c.0).collect(); - self.deprecated_transaction(|context| async move { - context - .remove_members_from_conversation(&conversation_id, &clients) - .await - .map_err(RecursiveError::mls_conversation("removing members from conversation")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::mark_conversation_as_child_of] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn mark_conversation_as_child_of(&self, child_id: Vec, parent_id: Vec) -> CoreCryptoResult<()> { - self.deprecated_transaction(|context| async move { - context - .mark_conversation_as_child_of(&child_id, &parent_id) - .await - .map_err(RecursiveError::mls_conversation("marking conversation as child")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::update_keying_material] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn update_keying_material(&self, conversation_id: Vec) -> CoreCryptoResult<()> { - self.deprecated_transaction(|context| async move { - context - .update_keying_material(&conversation_id) - .await - .map_err(RecursiveError::mls_conversation("updating keying material")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::commit_pending_proposals] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn commit_pending_proposals(&self, conversation_id: Vec) -> CoreCryptoResult<()> { - self.deprecated_transaction(|context| async move { - context - .commit_pending_proposals(&conversation_id) - .await - .map_err(RecursiveError::mls_conversation("commiting pending proposals")) - }) - .await - } - - /// see [core_crypto::context::CentralContext::wipe_conversation] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn wipe_conversation(&self, conversation_id: Vec) -> CoreCryptoResult<()> { - self.deprecated_transaction(|context| async move { - context - .wipe_conversation(&conversation_id) - .await - .map_err(RecursiveError::mls_conversation("wiping conversation")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::decrypt_message] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn decrypt_message( - &self, - conversation_id: Vec, - payload: Vec, - ) -> CoreCryptoResult { - self.deprecated_transaction(|context| async move { - context - .decrypt_message(&conversation_id, payload) - .await - .map_err(RecursiveError::mls_conversation("decrypting message")) - }) - .await? - .try_into() - } - - /// See [core_crypto::context::CentralContext::encrypt_message] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn encrypt_message(&self, conversation_id: Vec, message: Vec) -> CoreCryptoResult> { - self.deprecated_transaction(|context| async move { - context - .encrypt_message(&conversation_id, message) - .await - .map_err(RecursiveError::mls_conversation("encrypting message")) - }) - .await - } - /// See [core_crypto::mls::MlsCentral::conversation_exists] pub async fn conversation_exists(&self, conversation_id: Vec) -> CoreCryptoResult { Ok(self.central.conversation_exists(&conversation_id).await?) } - /// See [core_crypto::context::CentralContext::new_external_add_proposal] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn new_external_add_proposal( - &self, - conversation_id: Vec, - epoch: u64, - ciphersuite: Ciphersuite, - credential_type: MlsCredentialType, - ) -> CoreCryptoResult> { - self.deprecated_transaction(|context| async move { - context - .new_external_add_proposal( - conversation_id, - epoch.into(), - ciphersuite.into(), - credential_type.into(), - ) - .await - .map_err(RecursiveError::mls("creating new external add proposal"))? - .to_bytes() - .map_err(core_crypto::MlsError::wrap( - "converting new external add proposal to bytes", - )) - .map_err(core_crypto::Error::from) - }) - .await - } - - /// See [core_crypto::context::CentralContext::join_by_external_commit] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn join_by_external_commit( - &self, - group_info: Vec, - custom_configuration: CustomConfiguration, - credential_type: MlsCredentialType, - ) -> CoreCryptoResult { - let group_info = VerifiableGroupInfo::tls_deserialize(&mut group_info.as_slice()) - .map_err(core_crypto::MlsError::wrap("deserializing group info")) - .map_err(core_crypto::Error::from)?; - Ok(self - .deprecated_transaction(|context| async move { - context - .join_by_external_commit(group_info, custom_configuration.into(), credential_type.into()) - .await - .map_err(RecursiveError::mls("joining by external commit")) - }) - .await? - .into()) - } - /// See [core_crypto::mls::MlsCentral::random_bytes] pub async fn random_bytes(&self, len: u32) -> CoreCryptoResult> { Ok(self @@ -1602,138 +1257,11 @@ impl From for E2eiConversationState #[cfg_attr(not(feature = "proteus"), allow(unused_variables))] #[uniffi::export] impl CoreCrypto { - /// See [core_crypto::proteus::ProteusCentral::try_new] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_init(&self) -> CoreCryptoResult<()> { - proteus_impl!({ - self.deprecated_transaction(|context| async move { context.proteus_init().await }) - .await - }) - } - - /// See [core_crypto::proteus::ProteusCentral::session_from_prekey] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_session_from_prekey(&self, session_id: String, prekey: Vec) -> CoreCryptoResult<()> { - proteus_impl!({ - self.deprecated_transaction(|context| async move { - context - .proteus_session_from_prekey(&session_id, &prekey) - .await - .map(|_| ()) - }) - .await - }) - } - - /// See [core_crypto::proteus::ProteusCentral::session_from_message] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_session_from_message( - &self, - session_id: String, - envelope: Vec, - ) -> CoreCryptoResult> { - proteus_impl!({ - self.deprecated_transaction(|context| async move { - context - .proteus_session_from_message(&session_id, &envelope) - .await - .map(|(_, payload)| payload) - }) - .await - }) - } - - /// See [core_crypto::proteus::ProteusCentral::session_save] - /// **Note**: This isn't usually needed as persisting sessions happens automatically when decrypting/encrypting messages and initializing Sessions - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_session_save(&self, session_id: String) -> CoreCryptoResult<()> { - proteus_impl!({ - self.deprecated_transaction(|context| async move { context.proteus_session_save(&session_id).await }) - .await - }) - } - - /// See [core_crypto::proteus::ProteusCentral::session_delete] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_session_delete(&self, session_id: String) -> CoreCryptoResult<()> { - proteus_impl!({ - self.deprecated_transaction(|context| async move { context.proteus_session_delete(&session_id).await }) - .await - }) - } - /// See [core_crypto::proteus::ProteusCentral::session_exists] pub async fn proteus_session_exists(&self, session_id: String) -> CoreCryptoResult { proteus_impl!({ Ok(self.central.proteus_session_exists(&session_id).await?) }) } - /// See [core_crypto::proteus::ProteusCentral::decrypt] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_decrypt(&self, session_id: String, ciphertext: Vec) -> CoreCryptoResult> { - proteus_impl!({ - self.deprecated_transaction( - |context| async move { context.proteus_decrypt(&session_id, &ciphertext).await }, - ) - .await - }) - } - - /// See [core_crypto::proteus::ProteusCentral::encrypt] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_encrypt(&self, session_id: String, plaintext: Vec) -> CoreCryptoResult> { - proteus_impl!({ - self.deprecated_transaction(|context| async move { context.proteus_encrypt(&session_id, &plaintext).await }) - .await - }) - } - - /// See [core_crypto::proteus::ProteusCentral::encrypt_batched] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_encrypt_batched( - &self, - sessions: Vec, - plaintext: Vec, - ) -> CoreCryptoResult>> { - proteus_impl!({ - self.deprecated_transaction(|context| async move { - context.proteus_encrypt_batched(&sessions, &plaintext).await - }) - .await - }) - } - - /// See [core_crypto::proteus::ProteusCentral::new_prekey] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_new_prekey(&self, prekey_id: u16) -> CoreCryptoResult> { - proteus_impl!({ - self.deprecated_transaction(|context| async move { context.proteus_new_prekey(prekey_id).await }) - .await - }) - } - - /// See [core_crypto::proteus::ProteusCentral::new_prekey_auto] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_new_prekey_auto(&self) -> CoreCryptoResult { - proteus_impl!({ - self.deprecated_transaction(|context| async move { - context - .proteus_new_prekey_auto() - .await - .map(|(id, pkb)| ProteusAutoPrekeyBundle { id, pkb }) - }) - .await - }) - } - - /// See [core_crypto::proteus::ProteusCentral::last_resort_prekey] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_last_resort_prekey(&self) -> CoreCryptoResult> { - proteus_impl!({ - self.deprecated_transaction(|context| async move { context.proteus_last_resort_prekey().await }) - .await - }) - } - /// See [core_crypto::proteus::ProteusCentral::last_resort_prekey_id] pub fn proteus_last_resort_prekey_id(&self) -> CoreCryptoResult { proteus_impl!({ Ok(core_crypto::CoreCrypto::proteus_last_resort_prekey_id()) }) @@ -1759,95 +1287,12 @@ impl CoreCrypto { pub fn proteus_fingerprint_prekeybundle(&self, prekey: Vec) -> CoreCryptoResult { proteus_impl!({ Ok(core_crypto::proteus::ProteusCentral::fingerprint_prekeybundle(&prekey)?) }) } - - /// See [core_crypto::proteus::ProteusCentral::cryptobox_migrate] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn proteus_cryptobox_migrate(&self, path: String) -> CoreCryptoResult<()> { - proteus_impl!({ - self.deprecated_transaction(|context| async move { context.proteus_cryptobox_migrate(&path).await }) - .await - }) - } } // End-to-end identity methods #[allow(dead_code, unused_variables)] #[uniffi::export] impl CoreCrypto { - /// See [core_crypto::context::CentralContext::e2ei_new_enrollment] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn e2ei_new_enrollment( - &self, - client_id: String, - display_name: String, - handle: String, - team: Option, - expiry_sec: u32, - ciphersuite: Ciphersuite, - ) -> CoreCryptoResult { - self.deprecated_transaction(|context| async move { - context - .e2ei_new_enrollment( - client_id.into_bytes().into(), - display_name, - handle, - team, - expiry_sec, - ciphersuite.into(), - ) - .await - .map(async_lock::RwLock::new) - .map(std::sync::Arc::new) - .map(E2eiEnrollment) - .map_err(RecursiveError::e2e_identity("creating new e2ei enrollment")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::e2ei_new_activation_enrollment] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn e2ei_new_activation_enrollment( - &self, - display_name: String, - handle: String, - team: Option, - expiry_sec: u32, - ciphersuite: Ciphersuite, - ) -> CoreCryptoResult { - self.deprecated_transaction(|context| async move { - context - .e2ei_new_activation_enrollment(display_name, handle, team, expiry_sec, ciphersuite.into()) - .await - .map(async_lock::RwLock::new) - .map(std::sync::Arc::new) - .map(E2eiEnrollment) - .map_err(RecursiveError::e2e_identity("creating new e2ei activation enrollment")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::e2ei_new_rotate_enrollment] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn e2ei_new_rotate_enrollment( - &self, - display_name: Option, - handle: Option, - team: Option, - expiry_sec: u32, - ciphersuite: Ciphersuite, - ) -> CoreCryptoResult { - self.deprecated_transaction(|context| async move { - context - .e2ei_new_rotate_enrollment(display_name, handle, team, expiry_sec, ciphersuite.into()) - .await - .map(async_lock::RwLock::new) - .map(std::sync::Arc::new) - .map(E2eiEnrollment) - .map_err(RecursiveError::e2e_identity("creating new rotate enrollment")) - }) - .await - } - pub async fn e2ei_dump_pki_env(&self) -> CoreCryptoResult> { Ok(self.central.e2ei_dump_pki_env().await?.map(Into::into)) } @@ -1857,156 +1302,6 @@ impl CoreCrypto { self.central.e2ei_is_pki_env_setup().await } - /// See [core_crypto::context::CentralContext::e2ei_register_acme_ca] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn e2ei_register_acme_ca(&self, trust_anchor_pem: String) -> CoreCryptoResult<()> { - self.deprecated_transaction(|context| async move { - context - .e2ei_register_acme_ca(trust_anchor_pem) - .await - .map_err(RecursiveError::e2e_identity("registering acme ca")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::e2ei_register_intermediate_ca_pem] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn e2ei_register_intermediate_ca(&self, cert_pem: String) -> CoreCryptoResult { - self.deprecated_transaction(|context| async move { - context - .e2ei_register_intermediate_ca_pem(cert_pem) - .await - .map(|new_crl_distribution_point| -> Option> { new_crl_distribution_point.into() }) - .map(Into::into) - .map_err(RecursiveError::e2e_identity("registering intermediate ca")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::e2ei_register_crl] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn e2ei_register_crl(&self, crl_dp: String, crl_der: Vec) -> CoreCryptoResult { - self.deprecated_transaction(|context| async move { - context - .e2ei_register_crl(crl_dp, crl_der) - .await - .map(Into::into) - .map_err(RecursiveError::e2e_identity("registering crl")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::e2ei_mls_init_only] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn e2ei_mls_init_only( - &self, - enrollment: std::sync::Arc, - certificate_chain: String, - nb_key_package: Option, - ) -> CoreCryptoResult { - let nb_key_package = nb_key_package - .map(usize::try_from) - .transpose() - .expect("we never run corecrypto on systems with architectures narrower than 32 bits"); - - self.deprecated_transaction(|context| async move { - context - .e2ei_mls_init_only( - enrollment.0.write().await.deref_mut(), - certificate_chain, - nb_key_package, - ) - .await - .map(|new_crl_distribution_point| -> Option> { new_crl_distribution_point.into() }) - .map(Into::into) - .map_err(RecursiveError::e2e_identity("doing mls init only")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::e2ei_rotate] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn e2ei_rotate(&self, conversation_id: Vec) -> CoreCryptoResult<()> { - self.deprecated_transaction(|context| async move { - context - .e2ei_rotate(&conversation_id, None) - .await - .map_err(RecursiveError::e2e_identity("rotating")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::save_x509_credential] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn save_x509_credential( - &self, - enrollment: Arc, - certificate_chain: String, - ) -> CoreCryptoResult { - self.deprecated_transaction(|context| async move { - context - .save_x509_credential(enrollment.0.write().await.deref_mut(), certificate_chain) - .await - .map(|new_crl_distribution_point| -> Option> { new_crl_distribution_point.into() }) - .map(Into::into) - .map_err(RecursiveError::e2e_identity("rotating all")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::e2ei_enrollment_stash] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn e2ei_enrollment_stash(&self, enrollment: std::sync::Arc) -> CoreCryptoResult> { - let enrollment = std::sync::Arc::into_inner(enrollment).ok_or_else(|| { - CoreCryptoError::Other( - "enrollmemnt had more than one strong pointer and could not be removed from arc".into(), - ) - })?; - let enrollment = std::sync::Arc::into_inner(enrollment.0) - .ok_or_else(|| { - CoreCryptoError::Other( - "enrollmemnt.0 had more than one strong pointer and could not be removed from arc".into(), - ) - })? - .into_inner(); - - self.deprecated_transaction(|context| async move { - context - .e2ei_enrollment_stash(enrollment) - .await - .map_err(RecursiveError::e2e_identity("stashing enrollment")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::e2ei_enrollment_stash_pop] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn e2ei_enrollment_stash_pop(&self, handle: Vec) -> CoreCryptoResult { - self.deprecated_transaction(|context| async move { - context - .e2ei_enrollment_stash_pop(handle) - .await - .map(async_lock::RwLock::new) - .map(std::sync::Arc::new) - .map(E2eiEnrollment) - .map_err(RecursiveError::e2e_identity("popping enrollment stash")) - }) - .await - } - - /// See [core_crypto::context::CentralContext::e2ei_conversation_state] - #[deprecated = "Please create a transaction in Core Crypto and call this method from it."] - pub async fn e2ei_conversation_state(&self, conversation_id: Vec) -> CoreCryptoResult { - self.deprecated_transaction(|context| async move { - context - .e2ei_conversation_state(&conversation_id) - .await - .map(Into::into) - .map_err(RecursiveError::e2e_identity("getting conversation state")) - }) - .await - } - /// See [core_crypto::mls::MlsCentral::e2ei_is_enabled] pub async fn e2ei_is_enabled(&self, ciphersuite: Ciphersuite) -> CoreCryptoResult { let sc = core_crypto::prelude::MlsCiphersuite::from(core_crypto::prelude::CiphersuiteName::from(ciphersuite)) @@ -2149,30 +1444,6 @@ impl E2eiEnrollment { .new_oidc_challenge_request(id_token, refresh_token, previous_nonce)?) } - /// See [core_crypto::e2e_identity::E2eiEnrollment::new_oidc_challenge_response] - #[deprecated = "Please create a transaction in Core Crypto and call Self::context_newoidc_challenge_response."] - pub async fn new_oidc_challenge_response( - &self, - cc: std::sync::Arc, - challenge: Vec, - ) -> CoreCryptoResult<()> { - cc.deprecated_transaction(|context| async move { - self.0 - .write() - .await - .new_oidc_challenge_response( - &context - .mls_provider() - .await - .map_err(RecursiveError::root("getting mls provider"))?, - challenge, - ) - .await - .map_err(RecursiveError::e2e_identity("creating new oidc challenge response")) - }) - .await - } - /// See [core_crypto::e2e_identity::E2eiEnrollment::new_oidc_challenge_response] pub async fn context_new_oidc_challenge_response( &self, From 1fd0f46dd7800e590fae583394faf710ca960261 Mon Sep 17 00:00:00 2001 From: SimonThormeyer Date: Mon, 20 Jan 2025 17:43:31 +0100 Subject: [PATCH 5/5] docs: some minor docs cleanup Addresses some warnings that are emitted by `cargo doc --all --no-deps`. --- crypto/src/mls/external_commit.rs | 5 +--- crypto/src/proteus.rs | 42 +++++++++++++++---------------- 2 files changed, 22 insertions(+), 25 deletions(-) diff --git a/crypto/src/mls/external_commit.rs b/crypto/src/mls/external_commit.rs index 3a9583fa7a..252e761a02 100644 --- a/crypto/src/mls/external_commit.rs +++ b/crypto/src/mls/external_commit.rs @@ -45,10 +45,7 @@ impl CentralContext { /// /// If the Delivery Service accepts the external commit, you have to [CentralContext::merge_pending_group_from_external_commit] /// in order to get back a functional MLS group. On the opposite, if it rejects it, you can either - /// retry by just calling again [CentralContext::join_by_external_commit], no need to [CentralContext::clear_pending_group_from_external_commit]. - /// If you want to abort the operation (too many retries or the user decided to abort), you can use - /// [CentralContext::clear_pending_group_from_external_commit] in order not to bloat the user's storage but nothing - /// bad can happen if you forget to except some storage space wasted. + /// retry by just calling again [CentralContext::join_by_external_commit]. /// /// # Arguments /// * `group_info` - a GroupInfo wrapped in a MLS message. it can be obtained by deserializing a TLS serialized `GroupInfo` object diff --git a/crypto/src/proteus.rs b/crypto/src/proteus.rs index d93f95777b..ee76478272 100644 --- a/crypto/src/proteus.rs +++ b/crypto/src/proteus.rs @@ -84,7 +84,7 @@ impl ProteusConversationSession { impl CoreCrypto { /// Proteus session accessor /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_session( &self, session_id: &str, @@ -97,7 +97,7 @@ impl CoreCrypto { /// Proteus session exists /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_session_exists(&self, session_id: &str) -> Result { let mut mutex = self.proteus.lock().await; let proteus = mutex.as_mut().ok_or(Error::ProteusNotInitialized)?; @@ -112,7 +112,7 @@ impl CoreCrypto { /// Returns the proteus identity's public key fingerprint /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_fingerprint(&self) -> Result { let mutex = self.proteus.lock().await; let proteus = mutex.as_ref().ok_or(Error::ProteusNotInitialized)?; @@ -121,7 +121,7 @@ impl CoreCrypto { /// Returns the proteus identity's public key fingerprint /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_fingerprint_local(&self, session_id: &str) -> Result { let mut mutex = self.proteus.lock().await; let proteus = mutex.as_mut().ok_or(Error::ProteusNotInitialized)?; @@ -131,7 +131,7 @@ impl CoreCrypto { /// Returns the proteus identity's public key fingerprint /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_fingerprint_remote(&self, session_id: &str) -> Result { let mut mutex = self.proteus.lock().await; let proteus = mutex.as_mut().ok_or(Error::ProteusNotInitialized)?; @@ -157,7 +157,7 @@ impl CentralContext { /// Reloads the sessions from the key store /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or it will do nothing + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or it will do nothing pub async fn proteus_reload_sessions(&self) -> Result<()> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -168,7 +168,7 @@ impl CentralContext { /// Creates a proteus session from a prekey /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_session_from_prekey( &self, session_id: &str, @@ -186,7 +186,7 @@ impl CentralContext { /// Creates a proteus session from a Proteus message envelope /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_session_from_message( &self, session_id: &str, @@ -206,7 +206,7 @@ impl CentralContext { /// Saves a proteus session in the keystore /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_session_save(&self, session_id: &str) -> Result<()> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -217,7 +217,7 @@ impl CentralContext { /// Deletes a proteus session from the keystore /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_session_delete(&self, session_id: &str) -> Result<()> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -228,7 +228,7 @@ impl CentralContext { /// Proteus session accessor /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_session( &self, session_id: &str, @@ -242,7 +242,7 @@ impl CentralContext { /// Proteus session exists /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_session_exists(&self, session_id: &str) -> Result { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -253,7 +253,7 @@ impl CentralContext { /// Decrypts a proteus message envelope /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_decrypt(&self, session_id: &str, ciphertext: &[u8]) -> Result> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -264,7 +264,7 @@ impl CentralContext { /// Encrypts proteus message for a given session ID /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_encrypt(&self, session_id: &str, plaintext: &[u8]) -> Result> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -276,7 +276,7 @@ impl CentralContext { /// Encrypts a proteus message for several sessions ID. This is more efficient than other methods as the calls are batched. /// This also reduces the rountrips when crossing over the FFI /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_encrypt_batched( &self, sessions: &[impl AsRef], @@ -291,7 +291,7 @@ impl CentralContext { /// Creates a new Proteus prekey and returns the CBOR-serialized version of the prekey bundle /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_new_prekey(&self, prekey_id: u16) -> Result> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -302,7 +302,7 @@ impl CentralContext { /// Creates a new Proteus prekey with an automatically incremented ID and returns the CBOR-serialized version of the prekey bundle /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_new_prekey_auto(&self) -> Result<(u16, Vec)> { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -328,7 +328,7 @@ impl CentralContext { /// Returns the proteus identity's public key fingerprint /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_fingerprint(&self) -> Result { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -338,7 +338,7 @@ impl CentralContext { /// Returns the proteus identity's public key fingerprint /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_fingerprint_local(&self, session_id: &str) -> Result { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -349,7 +349,7 @@ impl CentralContext { /// Returns the proteus identity's public key fingerprint /// - /// Warning: The Proteus client **MUST** be initialized with [CoreCrypto::proteus_init] first or an error will be returned + /// Warning: The Proteus client **MUST** be initialized with [CentralContext::proteus_init] first or an error will be returned pub async fn proteus_fingerprint_remote(&self, session_id: &str) -> Result { let arc = self.proteus_central().await?; let mut mutex = arc.lock().await; @@ -360,7 +360,7 @@ impl CentralContext { /// Migrates an existing Cryptobox data store (whether a folder or an IndexedDB database) located at `path` to the keystore. /// - ///The client can then be initialized with [CoreCrypto::proteus_init] + ///The client can then be initialized with [CentralContext::proteus_init] pub async fn proteus_cryptobox_migrate(&self, path: &str) -> Result<()> { let keystore = self.keystore().await?; ProteusCentral::cryptobox_migrate(&keystore, path).await