diff --git a/.github/actions/make/android/package/action.yml b/.github/actions/make/android/package/action.yml index 35f5644ee2..aaa6f340b1 100644 --- a/.github/actions/make/android/package/action.yml +++ b/.github/actions/make/android/package/action.yml @@ -6,7 +6,6 @@ inputs: runs: using: composite steps: - - uses: actions/checkout@v5 - name: download armv7-linux-androideabi binaries uses: ./.github/actions/make/android/lib with: diff --git a/.github/workflows/interop.yml b/.github/workflows/interop.yml index 76715601c3..a1b4820b43 100644 --- a/.github/workflows/interop.yml +++ b/.github/workflows/interop.yml @@ -13,6 +13,9 @@ jobs: if: github.event_name == 'pull_request' runs-on: self-hosted + env: + ANDROID_NDK_VERSION: 28.1.13356709 + steps: - uses: actions/checkout@v6 - name: Setup rust macOS @@ -20,6 +23,18 @@ jobs: with: rustflags: '' cache-key-prefix: e2e-interop-test + - uses: actions/checkout@v6 + - name: set up jdk 17 + uses: actions/setup-java@v5 + with: + java-version: "17" + distribution: "adopt" + - name: gradle setup + uses: gradle/actions/setup-gradle@v5 + - name: validate gradle wrapper + uses: gradle/actions/wrapper-validation@v5 + - name: Setup Android SDK + uses: android-actions/setup-android@v3 - name: setup Xcode uses: maxim-lobanov/setup-xcode@v1 with: @@ -57,25 +72,40 @@ jobs: with: gh-token: ${{ secrets.GITHUB_TOKEN }} + - name: download android package + uses: ./.github/actions/make/android/package + with: + gh-token: ${{ secrets.GITHUB_TOKEN }} + - name: download interop test binary uses: ./.github/actions/make/interop-build with: gh-token: ${{ secrets.GITHUB_TOKEN }} - - name: create simulator + - name: create iOS simulator run: | echo "SIMULATOR=$(./scripts/create-ios-sim-device.sh "iPhone 16 e2e-interop-test")" >> $GITHUB_ENV + - name: build & install iOS Interop client run: | cd interop/src/clients/InteropClient xcodebuild -scheme InteropClient -sdk iphonesimulator -configuration Release \ -destination 'platform=iOS Simulator,name=iPhone 16 e2e-interop-test' clean build install DSTROOT=./Products ./install-interop-client.sh ${{ env.SIMULATOR }} - - name: run e2e interop test + + - name: build android interop client & run e2e interop test env: RUST_LOG: interop=info - # We're not building the interop binary in release mode, so it's in `target/debug`. - run: ./target/debug/interop + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: 32 + arch: arm64-v8a + working-directory: . + # We're not building the interop binary in release mode, so it's in `target/debug`. + script: | + (cd interop/src/clients && ./gradlew android-interop:installRelease) + ./target/debug/interop + # we separate shutdown from deletion to make sure the device is always removed, even when shutdown failed - name: delete simulator if: always() diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 463f6978f0..f25daedb09 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -203,6 +203,7 @@ jobs: - build-ios - bindings-swift - bindings-ts + - package-android - build-interop uses: ./.github/workflows/interop.yml diff --git a/Makefile b/Makefile index 02860cd22a..f155d8df25 100644 --- a/Makefile +++ b/Makefile @@ -311,7 +311,7 @@ android-env: @ndk_version=$$(perl -ne 's/Pkg\.Revision = // and print' $(ANDROID_NDK_HOME)/source.properties) && \ echo "Using Android NDK $${ndk_version} at $(ANDROID_NDK_HOME)"; \ -ANDROID_ARMv7 := target/armv7-linux-androideabi/$(RELEASE_MODE)/libcore_crypto_ffi.$(LIBRARY_EXTENSION) +ANDROID_ARMv7 := target/armv7-linux-androideabi/$(RELEASE_MODE)/libcore_crypto_ffi.so android-armv7-deps := $(RUST_SOURCES) $(ANDROID_ARMv7): $(android-armv7-deps) | android-env cargo rustc --locked \ @@ -323,7 +323,7 @@ $(ANDROID_ARMv7): $(android-armv7-deps) | android-env .PHONY: android-armv7 android-armv7: $(ANDROID_ARMv7) ## Build core-crypto-ffi for armv7-linux-androideabi -ANDROID_ARMv8 := target/aarch64-linux-android/$(RELEASE_MODE)/libcore_crypto_ffi.$(LIBRARY_EXTENSION) +ANDROID_ARMv8 := target/aarch64-linux-android/$(RELEASE_MODE)/libcore_crypto_ffi.so android-armv8-deps := $(RUST_SOURCES) $(ANDROID_ARMv8): $(android-armv8-deps) | android-env cargo rustc --locked \ @@ -335,7 +335,7 @@ $(ANDROID_ARMv8): $(android-armv8-deps) | android-env .PHONY: android-armv8 android-armv8: $(ANDROID_ARMv8) ## Build core-crypto-ffi for aarch64-linux-android -ANDROID_X86 := target/x86_64-linux-android/$(RELEASE_MODE)/libcore_crypto_ffi.$(LIBRARY_EXTENSION) +ANDROID_X86 := target/x86_64-linux-android/$(RELEASE_MODE)/libcore_crypto_ffi.so android-x86-deps := $(RUST_SOURCES) $(ANDROID_X86): $(android-x86-deps) | android-env # Link clang_rt.builtins statically for x86_64 Android @@ -653,17 +653,18 @@ swift-check: $(STAMPS)/swift-check ## Lint Swift files via swift-format and swif KT_WRAPPER = ./crypto-ffi/bindings/jvm/src/main/kotlin KT_TESTS = ./crypto-ffi/bindings/jvm/src/test -KT_FILES := $(shell find $(KT_WRAPPER) $(KT_TESTS) -type f -name '*.kt') +KT_INTEROP = ./interop/src/clients/android-interop/src/main/java +KT_FILES := $(shell find $(KT_WRAPPER) $(KT_TESTS) $(KT_INTEROP) -type f -name '*.kt') $(STAMPS)/kotlin-fmt: $(KT_FILES) - ktlint --format $(KT_WRAPPER) $(KT_TESTS) + ktlint --format $(KT_WRAPPER) $(KT_TESTS) $(KT_INTEROP) $(TOUCH_STAMP) .PHONY: kotlin-fmt kotlin-fmt: $(STAMPS)/kotlin-fmt ## Format Kotlin files via ktlint $(STAMPS)/kotlin-check: $(KT_FILES) - ktlint $(KT_WRAPPER) $(KT_TESTS) + ktlint $(KT_WRAPPER) $(KT_TESTS) $(KT_INTEROP) $(TOUCH_STAMP) .PHONY: kotlin-check diff --git a/crypto-ffi/bindings/android/build.gradle.kts b/crypto-ffi/bindings/android/build.gradle.kts index d99a1e6777..f359a2d125 100644 --- a/crypto-ffi/bindings/android/build.gradle.kts +++ b/crypto-ffi/bindings/android/build.gradle.kts @@ -1,7 +1,7 @@ import org.gradle.api.tasks.bundling.Jar plugins { - id("com.android.library") + alias(libs.plugins.android.library) kotlin("android") id("com.vanniktech.maven.publish.base") } diff --git a/crypto-ffi/bindings/build.gradle.kts b/crypto-ffi/bindings/build.gradle.kts index 1848b9ed9b..4af52beb12 100644 --- a/crypto-ffi/bindings/build.gradle.kts +++ b/crypto-ffi/bindings/build.gradle.kts @@ -12,7 +12,9 @@ buildscript { } } +// Top-level build file where you can add configuration options common to all sub-projects/modules. plugins { + alias(libs.plugins.android.library) apply false id(libs.plugins.vanniktech.publish.get().pluginId) version libs.versions.vanniktech.publish id(libs.plugins.dokka.get().pluginId) version libs.versions.dokka } diff --git a/crypto-ffi/bindings/gradle/libs.versions.toml b/crypto-ffi/bindings/gradle/libs.versions.toml index c55795c9ec..4e34270a17 100644 --- a/crypto-ffi/bindings/gradle/libs.versions.toml +++ b/crypto-ffi/bindings/gradle/libs.versions.toml @@ -1,5 +1,5 @@ [versions] -kotlin = "1.9.25" +kotlin = "2.0.21" coroutines = "1.7.3" kotlinx-datetime = "0.6.1" jna = "5.17.0" @@ -14,8 +14,10 @@ vanniktech-publish = "0.34.0" kotlin-gradle = "1.9.21" dokka = "2.0.0" detekt = "1.23.8" +agp = "8.12.3" [plugins] +android-library = { id = "com.android.library", version.ref = "agp" } vanniktech-publish = { id = "com.vanniktech.maven.publish", version.ref = "vanniktech-publish" } dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "detekt" } diff --git a/crypto-ffi/bindings/settings.gradle.kts b/crypto-ffi/bindings/settings.gradle.kts index 0d5cfd834c..45d9cfc660 100644 --- a/crypto-ffi/bindings/settings.gradle.kts +++ b/crypto-ffi/bindings/settings.gradle.kts @@ -7,4 +7,4 @@ pluginManagement { } } -include("jvm", "android") +include(":jvm", ":android") diff --git a/interop/src/clients/android-interop/.gitignore b/interop/src/clients/android-interop/.gitignore new file mode 100644 index 0000000000..a7747886cf --- /dev/null +++ b/interop/src/clients/android-interop/.gitignore @@ -0,0 +1,2 @@ +/build + diff --git a/interop/src/clients/android-interop/build.gradle.kts b/interop/src/clients/android-interop/build.gradle.kts new file mode 100644 index 0000000000..0f65b6c884 --- /dev/null +++ b/interop/src/clients/android-interop/build.gradle.kts @@ -0,0 +1,40 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.serialisation) +} + +android { + namespace = "com.wire.androidinterop" + compileSdk = 36 + + defaultConfig { + applicationId = "com.wire.androidinterop" + minSdk = 30 + targetSdk = 36 + versionCode = 1 + versionName = "1.0" + } + + buildTypes { + release { + isMinifyEnabled = false + signingConfig = signingConfigs.getByName("debug") + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlin { + jvmToolchain(17) + } +} + +dependencies { + implementation("core-crypto-kotlin:android") + implementation(libs.ktxSerialization) + implementation(libs.androidx.activity) +} diff --git a/interop/src/clients/android-interop/src/main/AndroidManifest.xml b/interop/src/clients/android-interop/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..11c0a3dd3a --- /dev/null +++ b/interop/src/clients/android-interop/src/main/AndroidManifest.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + diff --git a/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/InteropAction.kt b/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/InteropAction.kt new file mode 100644 index 0000000000..406583c66f --- /dev/null +++ b/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/InteropAction.kt @@ -0,0 +1,139 @@ +package com.wire.androidinterop + +import android.content.Intent +import kotlinx.serialization.Serializable +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi + +@Serializable +sealed class InteropAction { + sealed class MLS : InteropAction() { + class InitMLS(val clientId: ByteArray, val ciphersuite: Int) : MLS() + + class GetKeyPackage(val ciphersuite: Int) : MLS() + + class AddClient(val conversationId: ByteArray, val keyPackage: ByteArray) : MLS() + + class RemoveClient(val conversationId: ByteArray, val clientId: ByteArray) : MLS() + + class ProcessWelcome(val welcome: ByteArray) : MLS() + + class EncryptMessage(val conversationId: ByteArray, val message: ByteArray) : MLS() + + class DecryptMessage(val conversationId: ByteArray, val message: ByteArray) : MLS() + } + + sealed class Proteus : InteropAction() { + class InitProteus : Proteus() + + class GetPrekey(val id: UShort) : Proteus() + + class SessionFromPrekey(val sessionId: String, val prekey: ByteArray) : Proteus() + + class SessionFromMessage(val sessionId: String, val message: ByteArray) : Proteus() + + class EncryptProteusMessage(val sessionId: String, val message: ByteArray) : Proteus() + + class DecryptProteusMessage(val sessionId: String, val message: ByteArray) : Proteus() + + class GetProteusFingerprint() : Proteus() + } + + companion object { + @OptIn(ExperimentalEncodingApi::class) + fun fromIntent(intent: Intent): InteropAction { + return when (intent.getStringExtra("action")) { + "init-mls" -> { + val clientId = intent.getStringExtra("client_id") ?: throw IllegalArgumentException("client_id is missing") + val ciphersuite = intent.getIntExtra("ciphersuite", 0) + + MLS.InitMLS(clientId = Base64.Default.decode(clientId), ciphersuite = ciphersuite) + } + + "get-key-package" -> { + val ciphersuite = intent.getIntExtra("ciphersuite", 0) + MLS.GetKeyPackage(ciphersuite = ciphersuite) + } + + "add-client" -> { + val conversationId = intent.getStringExtra("cid") ?: throw IllegalArgumentException("conversation_id is missing") + val keyPackage = intent.getStringExtra("kp") ?: throw IllegalArgumentException("key_package is missing") + + MLS.AddClient(conversationId = Base64.Default.decode(conversationId), keyPackage = Base64.Default.decode(keyPackage)) + } + + "remove-client" -> { + val conversationId = intent.getStringExtra("cid") ?: throw IllegalArgumentException("conversation_id is missing") + val clientId = intent.getStringExtra("client_id") ?: throw IllegalArgumentException("client_id is missing") + + MLS.RemoveClient(conversationId = Base64.Default.decode(conversationId), clientId = Base64.Default.decode(clientId)) + } + + "process-welcome" -> { + val welcome = intent.getStringExtra("welcome") ?: throw IllegalArgumentException("welcome is missing") + + MLS.ProcessWelcome(Base64.Default.decode(welcome)) + } + + "encrypt-message" -> { + val conversationId = intent.getStringExtra("cid") ?: throw IllegalArgumentException("conversation_id is missing") + val message = intent.getStringExtra("message") ?: throw IllegalArgumentException("message is missing") + + MLS.EncryptMessage(Base64.Default.decode(conversationId), Base64.Default.decode(message)) + } + + "decrypt-message" -> { + val conversationId = intent.getStringExtra("cid") ?: throw IllegalArgumentException("conversation_id is missing") + val message = intent.getStringExtra("message") ?: throw IllegalArgumentException("message is missing") + + MLS.DecryptMessage(Base64.Default.decode(conversationId), Base64.Default.decode(message)) + } + + "init-proteus" -> { + Proteus.InitProteus() + } + + "get-prekey" -> { + val id = intent.getIntExtra("id", 0).toUShort() + Proteus.GetPrekey(id) + } + + "session-from-prekey" -> { + val sessionId = intent.getStringExtra("session_id") ?: throw IllegalArgumentException("session_id is missing") + val prekey = intent.getStringExtra("prekey") ?: throw IllegalArgumentException("prekey is missing") + + Proteus.SessionFromPrekey(sessionId = sessionId, prekey = Base64.Default.decode(prekey)) + } + + "session-from-message" -> { + val sessionId = intent.getStringExtra("session_id") ?: throw IllegalArgumentException("session_id is missing") + val message = intent.getStringExtra("message") ?: throw IllegalArgumentException("message is missing") + + Proteus.SessionFromMessage(sessionId = sessionId, message = Base64.Default.decode(message)) + } + + "encrypt-proteus" -> { + val sessionId = intent.getStringExtra("session_id") ?: throw IllegalArgumentException("session_id is missing") + val message = intent.getStringExtra("message") ?: throw IllegalArgumentException("message is missing") + + Proteus.EncryptProteusMessage(sessionId = sessionId, message = Base64.Default.decode(message)) + } + + "decrypt-proteus" -> { + val sessionId = intent.getStringExtra("session_id") ?: throw IllegalArgumentException("session_id is missing") + val message = intent.getStringExtra("message") ?: throw IllegalArgumentException("message is missing") + + Proteus.DecryptProteusMessage(sessionId = sessionId, message = Base64.Default.decode(message)) + } + + "get-fingerprint" -> { + Proteus.GetProteusFingerprint() + } + + else -> { + throw IllegalArgumentException("Unknown action: ${intent.getStringExtra("action")}") + } + } + } + } +} diff --git a/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/InteropActionHandler.kt b/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/InteropActionHandler.kt new file mode 100644 index 0000000000..f59cb51fca --- /dev/null +++ b/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/InteropActionHandler.kt @@ -0,0 +1,193 @@ +package com.wire.androidinterop + +import com.wire.crypto.ClientId +import com.wire.crypto.ConversationId +import com.wire.crypto.CoreCrypto +import com.wire.crypto.DatabaseKey +import com.wire.crypto.Keypackage +import com.wire.crypto.Welcome +import com.wire.crypto.ciphersuiteFromU16 +import com.wire.crypto.credentialBasic +import com.wire.crypto.openDatabase +import java.nio.file.Files +import java.security.SecureRandom +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi +import kotlin.random.Random + +class InteropActionHandler(val coreCrypto: CoreCrypto) { + @OptIn(ExperimentalEncodingApi::class) + suspend fun handleAction(action: InteropAction): Result { + return when (action) { + is InteropAction.MLS.InitMLS -> { + coreCrypto.transaction({ context -> + context.mlsInit( + clientId = ClientId(action.clientId), + ciphersuites = listOf(ciphersuiteFromU16(action.ciphersuite.toUShort())) + ) + + context.addCredential( + credentialBasic( + clientId = ClientId(action.clientId), + ciphersuite = ciphersuiteFromU16(action.ciphersuite.toUShort()) + ) + ) + }) + + return Result.success("MLS initialized") + } + + is InteropAction.MLS.AddClient -> { + coreCrypto.transaction { context -> + context.addClientsToConversation( + ConversationId(action.conversationId), + keyPackages = listOf( + Keypackage(action.keyPackage) + ) + ) + } + + return Result.success("Client added") + } + + is InteropAction.MLS.RemoveClient -> { + coreCrypto.transaction { context -> + context.removeClientsFromConversation(ConversationId(action.conversationId), listOf(ClientId(action.clientId))) + } + + return Result.success("Client removed") + } + + is InteropAction.MLS.DecryptMessage -> { + coreCrypto.transaction { context -> + context.decryptMessage(ConversationId(bytes = action.conversationId), action.message) + }.message?.let { + return Result.success(Base64.Default.encode(it)) + } + Result.success("decrypted protocol message") + } + + is InteropAction.MLS.EncryptMessage -> { + coreCrypto.transaction { context -> + context.encryptMessage(ConversationId(action.conversationId), action.message) + }.let { + Result.success(Base64.Default.encode(it)) + } + } + + is InteropAction.MLS.GetKeyPackage -> { + coreCrypto.transaction { context -> + val credential = context.findCredentials( + ciphersuite = ciphersuiteFromU16(action.ciphersuite.toUShort()), + clientId = null, + publicKey = null, + credentialType = null, + earliestValidity = null + ).first() + context.generateKeypackage(credential, null) + }.let { + Result.success(Base64.Default.encode(it.serialize())) + } + } + + is InteropAction.MLS.ProcessWelcome -> { + coreCrypto.transaction { context -> + context.processWelcomeMessage(Welcome(action.welcome)) + }.let { + Result.success(Base64.Default.encode(it.id.copyBytes())) + } + } + + is InteropAction.Proteus.InitProteus -> { + coreCrypto.transaction({ context -> + context.proteusInit() + }) + + return Result.success("Proteus initialized") + } + + is InteropAction.Proteus.GetPrekey -> { + coreCrypto.transaction({ context -> + context.proteusNewPrekey(action.id) + }).let { + Result.success(Base64.Default.encode(it)) + } + } + + is InteropAction.Proteus.SessionFromPrekey -> { + coreCrypto.transaction { context -> + context.proteusSessionFromPrekey( + sessionId = action.sessionId, + prekey = action.prekey + ) + } + Result.success("Session created") + } + + is InteropAction.Proteus.SessionFromMessage -> { + coreCrypto.transaction { context -> + context.proteusSessionFromMessage( + sessionId = action.sessionId, + envelope = action.message + ) + }.let { + Result.success(Base64.Default.encode(it)) + } + } + + is InteropAction.Proteus.EncryptProteusMessage -> { + coreCrypto.transaction({ context -> + context.proteusEncrypt( + sessionId = action.sessionId, + plaintext = action.message + ) + }).let { + Result.success(Base64.Default.encode(it)) + } + } + + is InteropAction.Proteus.DecryptProteusMessage -> { + coreCrypto.transaction { context -> + context.proteusDecrypt( + sessionId = action.sessionId, + ciphertext = action.message + ) + }.let { + Result.success(Base64.Default.encode(it)) + } + } + + is InteropAction.Proteus.GetProteusFingerprint -> { + coreCrypto.transaction { context -> + context.proteusFingerprint() + }.let { + Result.success(it) + } + } + } + } + + companion object { + private fun genDatabaseKey(): DatabaseKey { + val bytes = ByteArray(32) + val random = SecureRandom() + random.nextBytes(bytes) + return DatabaseKey(bytes) + } + + private fun randomIdentifier(n: Int = 12): String { + val charPool: List = ('a'..'z') + ('A'..'Z') + ('0'..'9') + return (1..n) + .map { Random.nextInt(0, charPool.size).let { charPool[it] } } + .joinToString("") + } + + suspend fun defaultCoreCryptoClient(): CoreCrypto { + val root = Files.createTempDirectory("mls").toFile() + val path = root.resolve("keystore-${randomIdentifier()}") + val database = openDatabase(path.absolutePath, key = genDatabaseKey()) + + return CoreCrypto(database) + } + } +} diff --git a/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/InteropResponse.kt b/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/InteropResponse.kt new file mode 100644 index 0000000000..3a849d7028 --- /dev/null +++ b/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/InteropResponse.kt @@ -0,0 +1,15 @@ +package com.wire.androidinterop + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +sealed class InteropResponse { + @Serializable + @SerialName("success") + public data class Success(val value: String) : InteropResponse() + + @Serializable + @SerialName("failure") + public data class Failure(val message: String) : InteropResponse() +} diff --git a/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/MainActivity.kt b/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/MainActivity.kt new file mode 100644 index 0000000000..992923140e --- /dev/null +++ b/interop/src/clients/android-interop/src/main/java/com/wire/androidinterop/MainActivity.kt @@ -0,0 +1,39 @@ +package com.wire.androidinterop + +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json + +class MainActivity : ComponentActivity() { + val actionHandler = runBlocking { + InteropActionHandler(InteropActionHandler.defaultCoreCryptoClient()) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + println("Ready") + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + + if (intent.action?.compareTo(Intent.ACTION_RUN) != 0) { + return + } + + try { + val action = InteropAction.fromIntent(intent) + runBlocking { + actionHandler.handleAction(action) + .onSuccess { println(Json.encodeToString(InteropResponse.serializer(), InteropResponse.Success(it))) } + .onFailure { + println(Json.encodeToString(InteropResponse.serializer(), InteropResponse.Failure(it.message ?: "Unknown error"))) + } + } + } catch (e: Throwable) { + return println(Json.encodeToString(InteropResponse.serializer(), InteropResponse.Failure(e.message ?: "Unknown error"))) + } + } +} diff --git a/interop/src/clients/build.gradle.kts b/interop/src/clients/build.gradle.kts new file mode 100644 index 0000000000..7f09f7c5a9 --- /dev/null +++ b/interop/src/clients/build.gradle.kts @@ -0,0 +1,5 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +plugins { + alias(libs.plugins.android.application) apply false + alias(libs.plugins.kotlin.android) apply false +} diff --git a/interop/src/clients/corecrypto/android.rs b/interop/src/clients/corecrypto/android.rs new file mode 100644 index 0000000000..4e99b86ece --- /dev/null +++ b/interop/src/clients/corecrypto/android.rs @@ -0,0 +1,402 @@ +#[cfg(feature = "proteus")] +use std::cell::Cell; +use std::{ + cell::RefCell, + io::{BufRead as _, BufReader, Read as _}, + process::{Child, ChildStdout, Command, Stdio}, + time::Duration, +}; + +use anyhow::Result; +use base64::{Engine as _, engine::general_purpose}; +use core_crypto::{KeyPackageIn, Keypackage}; +use tls_codec::Deserialize as _; + +use crate::{ + CIPHERSUITE_IN_USE, + clients::{EmulatedClient, EmulatedClientProtocol, EmulatedClientType, EmulatedMlsClient}, +}; + +#[derive(Debug)] +struct SimulatorDriver { + device: String, + process: Child, + output: RefCell>, +} + +#[derive(Debug, serde::Deserialize)] +#[serde(tag = "type")] +enum InteropResult { + #[serde(rename = "success")] + Success { value: String }, + #[serde(rename = "failure")] + Failure { message: String }, +} + +#[derive(thiserror::Error, Debug)] +#[error("simulator driver error: {msg}")] +struct SimulatorDriverError { + msg: String, +} + +impl SimulatorDriver { + fn new(device: String, application: String) -> Self { + let application = Self::launch_application(&device, &application).expect("Failed to launch application"); + + Self { + device, + process: application.0, + output: RefCell::new(application.1), + } + } + + fn launch_application(device: &str, application: &str) -> Result<(Child, BufReader)> { + log::info!("launching application: {} on {}", application, device); + + let activity = format!("{}/.MainActivity", application); + + log::info!("killing any existing activity of {}", application); + // Kill any existing activity to be in a clean state + Command::new("adb") + .args(["-s", device, "shell", "am", "force-stop", application]) + .output() + .expect("Failed to launch application"); + + log::info!("starting {}", application); + // Start the interop application + Command::new("adb") + .args(["-s", device, "shell", "am", "start", "-W", "-n", activity.as_str()]) + .output() + .expect("Failed to launch application"); + + // Retrieve the current process id of our application + let pidof = Command::new("adb") + .args(["-s", device, "shell", "pidof", "-s", application]) + .output() + .expect("Failed to launch application"); + + let pid = String::from_utf8(pidof.stdout) + .expect("pidof output is not valid utf8") + .trim() + .to_string(); + log::info!("retrieved {} pid", pid); + + // Start monitoring the system output of our application + // + // without formatting (raw) + // only include system out and silence all other logs (System.out:I *:S) + let mut process = Command::new("adb") + .args([ + "-s", + device, + "logcat", + "--pid", + pid.as_str(), + "-v", + "raw", + "System.out:I *:S", + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("Failed to launch application"); + + let mut output = BufReader::new( + process + .stdout + .take() + .expect("Expected stdout to be available on child process"), + ); + + // Wait for the child process to launch or fail + std::thread::sleep(Duration::from_secs(3)); + match process.try_wait() { + Ok(None) => {} + Ok(Some(exit_status)) => { + let mut error_message = String::new(); + process + .stderr + .map(|mut stderr| stderr.read_to_string(&mut error_message)); + panic!("Failed to launch application ({}): {}", exit_status, error_message) + } + Err(error) => { + panic!("Failed to launch application: {}", error) + } + } + + log::info!("waiting for ready signal on system.out"); + + // Waiting for confirmation that the application has launched. + let mut line = String::new(); + while !line.contains("Ready") { + line.clear(); + output + .read_line(&mut line) + .expect("was expecting ready signal on stdout"); + } + + log::info!("application launched: {}", line); + Ok((process, output)) + } + + async fn execute(&self, action: String) -> Result { + let args = [ + "-s", + self.device.as_str(), + "shell", + "am", + "start", + "-W", + "-a", + "android.intent.action.RUN", + action.as_str(), + ]; + + log::info!("adb {}", args.join(" ")); + + Command::new("adb") + .args(args) + .output() + .expect("Failed to execute action"); + + let mut result = String::new(); + let mut output = self.output.try_borrow_mut()?; + + output.read_line(&mut result)?; + + log::info!("{}", result); + + let result: InteropResult = serde_json::from_str(result.trim())?; + + match result { + InteropResult::Success { value } => Ok(value), + InteropResult::Failure { message } => Err(SimulatorDriverError { msg: message }.into()), + } + } +} + +impl Drop for SimulatorDriver { + fn drop(&mut self) { + self.process.kill().expect("expected child process to be killed") + } +} + +#[derive(Debug)] +pub(crate) struct CoreCryptoAndroidClient { + driver: SimulatorDriver, + client_id: Vec, + #[cfg(feature = "proteus")] + prekey_last_id: Cell, +} + +impl CoreCryptoAndroidClient { + pub(crate) async fn new() -> Result { + let client_id = uuid::Uuid::new_v4(); + let client_id_str = client_id.as_hyphenated().to_string(); + let client_id_base64 = general_purpose::STANDARD.encode(client_id_str.as_str()); + let ciphersuite = CIPHERSUITE_IN_USE as u16; + + let output = Command::new("adb") + .args(["get-serialno"]) + .output() + .expect("Failed to get connected android device"); + + let device = String::from_utf8(output.stdout) + .expect("output is not valid utf8") + .trim() + .to_string(); + let driver = SimulatorDriver::new(device, "com.wire.androidinterop".into()); + log::info!("initialising core crypto with ciphersuite {ciphersuite}"); + driver + .execute(format!( + "--es action init-mls --es client_id {client_id_base64} --ei ciphersuite {ciphersuite}" + )) + .await?; + + Ok(Self { + driver, + client_id: client_id.into_bytes().into(), + #[cfg(feature = "proteus")] + prekey_last_id: Cell::new(0), + }) + } +} + +#[async_trait::async_trait(?Send)] +impl EmulatedClient for CoreCryptoAndroidClient { + fn client_name(&self) -> &str { + "CoreCrypto::android" + } + + fn client_type(&self) -> EmulatedClientType { + EmulatedClientType::Android + } + + fn client_id(&self) -> &[u8] { + self.client_id.as_slice() + } + + fn client_protocol(&self) -> EmulatedClientProtocol { + EmulatedClientProtocol::MLS | EmulatedClientProtocol::PROTEUS + } + + async fn wipe(&mut self) -> Result<()> { + Ok(()) + } +} + +#[async_trait::async_trait(?Send)] +impl EmulatedMlsClient for CoreCryptoAndroidClient { + async fn get_keypackage(&self) -> Result> { + let ciphersuite = CIPHERSUITE_IN_USE as u16; + let start = std::time::Instant::now(); + let kp_base64 = self + .driver + .execute(format!("--es action get-key-package --ei ciphersuite {ciphersuite}")) + .await?; + let kp_raw = general_purpose::STANDARD.decode(kp_base64)?; + let kp: Keypackage = KeyPackageIn::tls_deserialize(&mut kp_raw.as_slice())?.into(); + + log::info!( + "KP Init Key [took {}ms]: Client {} [{}] - {}", + start.elapsed().as_millis(), + self.client_name(), + hex::encode(&self.client_id), + hex::encode(kp.hpke_init_key()), + ); + + Ok(kp_raw) + } + + async fn kick_client(&self, conversation_id: &[u8], client_id: &[u8]) -> Result<()> { + let cid_base64 = general_purpose::STANDARD.encode(conversation_id); + let client_id_base64 = general_purpose::STANDARD.encode(client_id); + self.driver + .execute(format!( + "--es action remove-client --es cid {cid_base64} --es client {client_id_base64}" + )) + .await?; + + Ok(()) + } + + async fn process_welcome(&self, welcome: &[u8]) -> Result> { + let welcome_base64 = general_purpose::STANDARD.encode(welcome); + let conversation_id_base64 = self + .driver + .execute(format!("--es action process-welcome --es welcome {welcome_base64}")) + .await?; + let conversation_id = general_purpose::STANDARD.decode(conversation_id_base64)?; + + Ok(conversation_id) + } + + async fn encrypt_message(&self, conversation_id: &[u8], message: &[u8]) -> Result> { + let cid_base64 = general_purpose::STANDARD.encode(conversation_id); + let message_base64 = general_purpose::STANDARD.encode(message); + let encrypted_message_base64 = self + .driver + .execute(format!( + "--es action encrypt-message --es cid {cid_base64} --es message {message_base64}" + )) + .await?; + let encrypted_message = general_purpose::STANDARD.decode(encrypted_message_base64)?; + + Ok(encrypted_message) + } + + async fn decrypt_message(&self, conversation_id: &[u8], message: &[u8]) -> Result>> { + let cid_base64 = general_purpose::STANDARD.encode(conversation_id); + let message_base64 = general_purpose::STANDARD.encode(message); + let result = self + .driver + .execute(format!( + "--es action decrypt-message --es cid {cid_base64} --es message {message_base64}" + )) + .await?; + + if result == "decrypted protocol message" { + Ok(None) + } else { + let decrypted_message = general_purpose::STANDARD.decode(result)?; + Ok(Some(decrypted_message)) + } + } +} + +#[cfg(feature = "proteus")] +#[async_trait::async_trait(?Send)] +impl crate::clients::EmulatedProteusClient for CoreCryptoAndroidClient { + async fn init(&mut self) -> Result<()> { + self.driver.execute("--es action init-proteus".into()).await?; + Ok(()) + } + + async fn get_prekey(&self) -> Result> { + let prekey_last_id = self.prekey_last_id.get() + 1; + self.prekey_last_id.replace(prekey_last_id); + + let prekey_base64 = self + .driver + .execute(format!("--es action get-prekey --es id {prekey_last_id}")) + .await?; + let prekey = general_purpose::STANDARD.decode(prekey_base64)?; + + Ok(prekey) + } + + async fn session_from_prekey(&self, session_id: &str, prekey: &[u8]) -> Result<()> { + let prekey_base64 = general_purpose::STANDARD.encode(prekey); + self.driver + .execute(format!( + "--es action session-from-prekey --es session_id {session_id} --es prekey {prekey_base64}" + )) + .await?; + + Ok(()) + } + + async fn session_from_message(&self, session_id: &str, message: &[u8]) -> Result> { + let message_base64 = general_purpose::STANDARD.encode(message); + let decrypted_message_base64 = self + .driver + .execute(format!( + "--es action session-from-message --es session_id {session_id} --es message {message_base64}" + )) + .await?; + let decrypted_message = general_purpose::STANDARD.decode(decrypted_message_base64)?; + + Ok(decrypted_message) + } + async fn encrypt(&self, session_id: &str, plaintext: &[u8]) -> Result> { + let plaintext_base64 = general_purpose::STANDARD.encode(plaintext); + let encrypted_message_base64 = self + .driver + .execute(format!( + "--es action encrypt-proteus --es session_id {session_id} --es message {plaintext_base64}" + )) + .await?; + let encrypted_message = general_purpose::STANDARD.decode(encrypted_message_base64)?; + + Ok(encrypted_message) + } + + async fn decrypt(&self, session_id: &str, ciphertext: &[u8]) -> Result> { + let ciphertext_base64 = general_purpose::STANDARD.encode(ciphertext); + let decrypted_message_base64 = self + .driver + .execute(format!( + "--es action decrypt-proteus --es session_id {session_id} --es message {ciphertext_base64}" + )) + .await?; + let decrypted_message = general_purpose::STANDARD.decode(decrypted_message_base64)?; + + Ok(decrypted_message) + } + + async fn fingerprint(&self) -> Result { + let fingerprint = self.driver.execute("--es action get-fingerprint".into()).await?; + + Ok(fingerprint) + } +} diff --git a/interop/src/clients/corecrypto/ios.rs b/interop/src/clients/corecrypto/ios.rs index 3d8c6923e7..fa0465382d 100644 --- a/interop/src/clients/corecrypto/ios.rs +++ b/interop/src/clients/corecrypto/ios.rs @@ -231,20 +231,6 @@ impl EmulatedMlsClient for CoreCryptoIosClient { Ok(kp_raw) } - async fn add_client(&self, conversation_id: &[u8], kp: &[u8]) -> Result<()> { - let cid_base64 = general_purpose::STANDARD.encode(conversation_id); - let kp_base64 = general_purpose::STANDARD.encode(kp); - let ciphersuite = CIPHERSUITE_IN_USE as u16; - self.driver - .execute(format!( - "add-client?cid={}&ciphersuite={}&kp={}", - cid_base64, ciphersuite, kp_base64 - )) - .await?; - - Ok(()) - } - async fn kick_client(&self, conversation_id: &[u8], client_id: &[u8]) -> Result<()> { let cid_base64 = general_purpose::STANDARD.encode(conversation_id); let client_id_base64 = general_purpose::STANDARD.encode(client_id); diff --git a/interop/src/clients/corecrypto/mod.rs b/interop/src/clients/corecrypto/mod.rs index 51985987d9..f18f3e05bd 100644 --- a/interop/src/clients/corecrypto/mod.rs +++ b/interop/src/clients/corecrypto/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod android; pub(crate) mod ffi; pub(crate) mod native; pub(crate) mod web; diff --git a/interop/src/clients/gradle.properties b/interop/src/clients/gradle.properties new file mode 100644 index 0000000000..00947a94cc --- /dev/null +++ b/interop/src/clients/gradle.properties @@ -0,0 +1,11 @@ +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m + +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true + +# Automatically convert third-party libraries to use AndroidX +android.enableJetifier=true diff --git a/interop/src/clients/gradle/libs.versions.toml b/interop/src/clients/gradle/libs.versions.toml new file mode 100644 index 0000000000..c37561f064 --- /dev/null +++ b/interop/src/clients/gradle/libs.versions.toml @@ -0,0 +1,22 @@ +[versions] +kotlin = "2.3.0" +coroutines = "1.10.2" +android-tools = "8.12.3" +kotlin-gradle = "1.9.21" +agp = "8.12.3" +ktx-serialization = "1.9.0" +activity = "1.12.2" + +[plugins] +android-application = { id = "com.android.application", version.ref = "agp" } +kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } +kotlin-serialisation = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } + +[libraries] +coroutines-bom = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-bom", version.ref = "coroutines" } +coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } +coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" } +android-tools = { module = "com.android.tools.build:gradle", version.ref = "android-tools" } +kotlin-gradle = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin-gradle" } +ktxSerialization = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "ktx-serialization" } +androidx-activity = { group = "androidx.activity", name = "activity", version.ref = "activity" } diff --git a/interop/src/clients/gradle/wrapper/gradle-wrapper.jar b/interop/src/clients/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..8bdaf60c75 Binary files /dev/null and b/interop/src/clients/gradle/wrapper/gradle-wrapper.jar differ diff --git a/interop/src/clients/gradle/wrapper/gradle-wrapper.properties b/interop/src/clients/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..2a84e188b8 --- /dev/null +++ b/interop/src/clients/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/interop/src/clients/gradlew b/interop/src/clients/gradlew new file mode 100755 index 0000000000..ef07e0162b --- /dev/null +++ b/interop/src/clients/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/interop/src/clients/gradlew.bat b/interop/src/clients/gradlew.bat new file mode 100644 index 0000000000..5eed7ee845 --- /dev/null +++ b/interop/src/clients/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/interop/src/clients/settings.gradle.kts b/interop/src/clients/settings.gradle.kts new file mode 100644 index 0000000000..0b671489d4 --- /dev/null +++ b/interop/src/clients/settings.gradle.kts @@ -0,0 +1,19 @@ +rootProject.name = "interop" + +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +include(":android-interop") +includeBuild("../../../crypto-ffi/bindings") diff --git a/interop/src/main.rs b/interop/src/main.rs index 164cab269f..8a5d524db7 100644 --- a/interop/src/main.rs +++ b/interop/src/main.rs @@ -21,8 +21,6 @@ const ROUNDTRIP_MSG_AMOUNT: usize = 100; const CIPHERSUITE_IN_USE: MlsCiphersuite = MlsCiphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519; -// TODO: Add support for Android emulator. Tracking issue: WPB-9646 -// TODO: Add support for iOS emulator when on macOS. Tracking issue: WPB-9646 fn main() -> Result<()> { run_test() } @@ -33,6 +31,11 @@ async fn create_mls_clients<'a>( web_server: &'a std::net::SocketAddr, ) -> Vec> { vec![ + Box::new( + clients::corecrypto::android::CoreCryptoAndroidClient::new() + .await + .unwrap(), + ), #[cfg(target_os = "ios")] Box::new(clients::corecrypto::ios::CoreCryptoIosClient::new().await.unwrap()), Box::new( @@ -55,6 +58,11 @@ async fn create_proteus_clients<'a>( web_server: &'a std::net::SocketAddr, ) -> Vec> { vec![ + Box::new( + clients::corecrypto::android::CoreCryptoAndroidClient::new() + .await + .unwrap(), + ), #[cfg(target_os = "ios")] Box::new(clients::corecrypto::ios::CoreCryptoIosClient::new().await.unwrap()), Box::new(