188 lines · 7.6 KB · KotlinRaw
package com.cottondb.android.platformimport android.content.Intentimport android.os.Buildimport androidx.lifecycle.DefaultLifecycleObserverimport androidx.lifecycle.LifecycleOwnerimport androidx.lifecycle.ProcessLifecycleOwnerimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport com.cottondb.android.core.CottonCallingimport com.cottondb.android.core.CottonEventimport com.cottondb.android.core.CoreExceptionimport com.cottondb.android.core.MalformedCoreEventExceptionimport com.cottondb.android.passwords.VaultAccessimport com.cottondb.android.passwords.VaultKeyRepublisherimport com.cottondb.android.passwords.VaultOperationsimport com.cottondb.android.passwords.VaultResultimport com.cottondb.android.passwords.VaultSessionimport java.io.Fileimport java.security.KeyStoreimport java.util.UUIDimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.asyncimport kotlinx.coroutines.cancelimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.SharedFlowimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withContextimport kotlinx.coroutines.withTimeoutimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.putimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertTrueimport org.junit.Assume.assumeTrueimport org.junit.Testimport org.junit.runner.RunWith/** * Real system-auth coverage with an intentionally synthetic core. The runner completes the * visible credential or fingerprint prompt; this test never contains a PIN or biometric input. */@RunWith(AndroidJUnit4::class)class VaultLifecycleAuthenticationTest { private val instrumentation = InstrumentationRegistry.getInstrumentation() private val context = instrumentation.targetContext private val id = UUID.randomUUID().toString() private val alias = "com.cottondb.cotton.test.vault-lifecycle.$id" private val directory = File(context.noBackupFilesDir, "vault-lifecycle-test-$id") private val privateSlot = File(directory, "vault-key.v1") private val publicSlot = File(directory, "vault-public-key.v1") private var activity: VaultUnlockHarnessActivity? = null private var session: VaultSession? = null private var scope: CoroutineScope? = null private val runtimeLifecycle = object : DefaultLifecycleObserver { override fun onStart(owner: LifecycleOwner) { session?.foreground() } override fun onStop(owner: LifecycleOwner) { // This is the same ProcessLifecycleOwner hand-off CottonApplication makes to AppRuntime. session?.background() } } @After fun cleanUp() = runBlocking { withContext(Dispatchers.Main.immediate) { ProcessLifecycleOwner.get().lifecycle.removeObserver(runtimeLifecycle) session?.retire()?.await() } scope?.cancel() instrumentation.runOnMainSync { activity?.finish() } directory.deleteRecursively() KeyStore.getInstance("AndroidKeyStore").also { it.load(null) it.deleteEntry(alias) } Unit } @Test fun realPromptStaysAdmittedWhenProcessLifecycleRemainsForeground() = runBlocking { requireRealLifecycleAuthentication() val fakeCore = FakeVaultCore() val access = VaultAccess(fakeCore) val testScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) scope = testScope val vaultSession = VaultSession( access = access, operations = VaultOperations(access, VaultKeyRepublisher { error("Fake core never republished a key.") }), scope = testScope, onLockFailure = { error("Fake vault lock failed.") }, ) session = vaultSession mintKeyring() val harness = startHarness() withContext(Dispatchers.Main.immediate) { ProcessLifecycleOwner.get().lifecycle.addObserver(runtimeLifecycle) vaultSession.foreground() } val pending = async(Dispatchers.Main.immediate) { val authenticator = AndroidVaultAuthenticator(harness, VaultUnlock(VaultKeyring(alias, privateSlot, publicSlot))) vaultSession.perform(authenticator) { fakeCore.readSyntheticProtectedValue() } } // The system sheet remains in front until the externally supplied emulator PIN or enrolled // fingerprint completes it. If that sheet produces ProcessLifecycleOwner.onStop, the // observer above calls VaultSession.background(), cancels this request, and this test fails. delay(PROMPT_SETTLE_MS) val result = withTimeout(PROMPT_TIMEOUT_MS) { pending.await() } assertTrue(result is VaultResult.Success) assertEquals(1, fakeCore.unlockCalls) } private fun requireRealLifecycleAuthentication() { assumeTrue( "Run on Android 11+ with a configured emulator PIN or enrolled fingerprint and -e cotton.realVaultLifecycleAuth true.", Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && InstrumentationRegistry.getArguments().getString("cotton.realVaultLifecycleAuth") == "true", ) } private fun mintKeyring() { checkNotNull(VaultKeyring(alias, privateSlot, publicSlot).publicKey()) } private fun startHarness(): VaultUnlockHarnessActivity { activity?.let { return it } val started = instrumentation.startActivitySync( Intent(context, VaultUnlockHarnessActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), ) check(started is VaultUnlockHarnessActivity) { "Unexpected test activity: $started" } return started.also { activity = it } } /** * Synthetic native answers only. It neither unwraps crypto nor inspects or persists the * authenticated private-key request, so success proves lifecycle/prompt behavior only. */ private class FakeVaultCore : CottonCalling { private val eventsFlow = MutableSharedFlow<CottonEvent>() private val errorsFlow = MutableSharedFlow<MalformedCoreEventException>() override val events: SharedFlow<CottonEvent> = eventsFlow override val eventErrors: SharedFlow<MalformedCoreEventException> = errorsFlow private var unlocked = false var unlockCalls = 0 private set override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) { "vault.unlock" -> { // The request deliberately goes unread: this is not fake cryptography or a key wrap. unlockCalls += 1 unlocked = true buildJsonObject { put("unlocked", true) put("until", "2030-01-01T00:00:00Z") } } "vault.lock" -> { unlocked = false buildJsonObject { put("locked", true) } } else -> error("Unexpected fake-core method: $method") } suspend fun readSyntheticProtectedValue() { if (!unlocked) { throw CoreException("vault_locked", "Synthetic core is locked.", null) } } override suspend fun close() = Unit } private companion object { const val PROMPT_SETTLE_MS = 750L const val PROMPT_TIMEOUT_MS = 60_000L }}