package com.cottondb.android.platform import android.content.Intent import android.os.Build import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ProcessLifecycleOwner import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.cottondb.android.core.CottonCalling import com.cottondb.android.core.CottonEvent import com.cottondb.android.core.CoreException import com.cottondb.android.core.MalformedCoreEventException import com.cottondb.android.passwords.VaultAccess import com.cottondb.android.passwords.VaultKeyRepublisher import com.cottondb.android.passwords.VaultOperations import com.cottondb.android.passwords.VaultResult import com.cottondb.android.passwords.VaultSession import java.io.File import java.security.KeyStore import java.util.UUID import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put 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 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() private val errorsFlow = MutableSharedFlow() override val events: SharedFlow = eventsFlow override val eventErrors: SharedFlow = 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 } }