package com.cottondb.android.platform import android.content.Intent import android.os.Build import android.util.Base64 import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import java.io.File import java.security.KeyStore import java.util.UUID import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import org.bouncycastle.math.ec.rfc7748.X25519 import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Assume.assumeTrue import org.junit.Test import org.junit.runner.RunWith /** * Real prompt coverage. It runs only when the caller explicitly supplies * `-e cotton.realBiometric true` after enrolling a fingerprint in the emulator. */ @RunWith(AndroidJUnit4::class) class VaultUnlockTest { private val instrumentation = InstrumentationRegistry.getInstrumentation() private val context = instrumentation.targetContext private val id = UUID.randomUUID().toString() private val alias = "com.cottondb.cotton.test.vault-unlock.$id" private val directory = File(context.noBackupFilesDir, "vault-unlock-test-$id") private val privateSlot = File(directory, "vault-key.v1") private val publicSlot = File(directory, "vault-public-key.v1") private var activity: VaultUnlockHarnessActivity? = null @After fun cleanUp() { activity?.finish() directory.deleteRecursively() KeyStore.getInstance("AndroidKeyStore").also { it.load(null) it.deleteEntry(alias) } } @Test fun systemPromptCancellationPreservesSealedVaultKey() = runBlocking { requireRealBiometricRun() val keyring = mintKeyring() val expectedPublic = checkNotNull(keyring.cachedPublicKey()) val pending = async { runCatching { VaultUnlock(keyring).unlock(startHarness()) } } delay(PROMPT_SETTLE_MS) instrumentation.uiAutomation.executeShellCommand("input keyevent KEYCODE_BACK").close() val failure = withTimeout(PROMPT_TIMEOUT_MS) { pending.await() }.exceptionOrNull() assertTrue("Expected biometric cancellation, got $failure", failure is VaultUnlockCancelledException) assertEquals(expectedPublic, keyring.cachedPublicKey()) assertTrue(privateSlot.exists()) } @Test fun enrolledFingerprintUnlocksExactX25519Key() = runBlocking { requireRealBiometricRun() val keyring = mintKeyring() val expectedPublic = checkNotNull(keyring.cachedPublicKey()) val pending = async { runCatching { VaultUnlock(keyring).unlock(startHarness()) } } // This test deliberately waits for the external console command below rather than // fabricating a biometric success. While this prompt is visible, run: // adb -s emulator-5554 emu finger touch val privateKey = withTimeout(PROMPT_TIMEOUT_MS) { pending.await() }.getOrThrow() assertEquals(expectedPublic, publicOf(privateKey)) } @Test fun deviceCredentialUnlocksExactX25519KeyOnAndroid11AndLater() = runBlocking { requireRealDeviceCredentialRun() val keyring = mintKeyring() val expectedPublic = checkNotNull(keyring.cachedPublicKey()) val pending = async { runCatching { VaultUnlock(keyring).unlock(startHarness()) } } // Use the emulator's already-configured synthetic PIN in the system // sheet. This test deliberately carries no PIN: its runner supplies // input externally while this CryptoObject prompt is visible. val privateKey = withTimeout(PROMPT_TIMEOUT_MS) { pending.await() }.getOrThrow() assertEquals(expectedPublic, publicOf(privateKey)) } private fun requireRealBiometricRun() { assumeTrue( "Run with -e cotton.realBiometric true after enrolling an emulator fingerprint.", InstrumentationRegistry.getArguments().getString("cotton.realBiometric") == "true", ) } private fun requireRealDeviceCredentialRun() { assumeTrue( "Run only on Android 11+ with a synthetic emulator PIN supplied externally.", Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && InstrumentationRegistry.getArguments().getString("cotton.realDeviceCredential") == "true", ) } private fun mintKeyring(): VaultKeyring { val keyring = VaultKeyring(alias, privateSlot, publicSlot) checkNotNull(keyring.publicKey()) return keyring } private fun startHarness(): VaultUnlockHarnessActivity { activity?.let { return it } val intent = Intent(context, VaultUnlockHarnessActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) val started = instrumentation.startActivitySync(intent) check(started is VaultUnlockHarnessActivity) { "Unexpected test activity: $started" } return started.also { activity = it } } private fun publicOf(privateKey: String): String { val scalar = Base64.decode(privateKey, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP) val public = ByteArray(32) try { X25519.generatePublicKey(scalar, 0, public, 0) return Base64.encodeToString(public, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP) } finally { scalar.fill(0) public.fill(0) } } private companion object { const val PROMPT_SETTLE_MS = 750L const val PROMPT_TIMEOUT_MS = 60_000L } }