Modern Apps git

← Modern-Apps.git

library/biometric: add tests for database helper and unlock

Commit
09702e3c5557d2e9830f7192bb917369cc238f16
Author
Vayun Mathur <[email protected]>
When
2026-11-07 07:38 UTC (29 days ago)
Parents
b1f05fd
Coverage work for library/biometric (was 0%, no tests): Robolectric
tests for BiometricDatabaseHelper over an in-memory FakeAndroidKeyStore
(taken from the passwords tests pattern), covering key generation under
the biometric alias, orphaned-key cleanup, passphrase store/decrypt
round-trips, deleteKey and corrupted/missing-state failures.

unlockDatabaseWithBiometrics is covered three ways: Robolectric tests
with small custom shadows for the framework BiometricManager (Robolectric
ships no biometric shadows, so canAuthenticate otherwise always reports
success) for the none-enrolled / no-hardware / unknown statuses and the
key-generation-failure path; Robolectric prompt-setup tests (key created
before the setup prompt, existing-key prompt without touching the stored
passphrase); and instrumented tests on the emulator that drive the real
system BiometricPrompt panel and cancel it, covering the
onAuthenticationError cancellation branch (the .ec folds into the
merged report). Test-only androidTest deps (test-core, uiautomator) are
added to the module build file for those instrumented tests.

Untestable remainder: onAuthenticationSucceeded and the two onCipher
lambdas - the emulator fingerprint HAL has no enrolled finger
(enrollment needs host-side emulator-console touches a test cannot
send) and its prompt panel offers no PIN fallback, so no authentication
can succeed on the available devices.

Verified with :library:biometric:createMergedCoverageReport and
./test --instrumented-only library/biometric after rebase onto main.

(cherry picked from commit e31363261a238ade7765ed40e983fefd65729366)

Diff

library/biometric/build.gradle.kts
diff --git a/library/biometric/build.gradle.kts b/library/biometric/build.gradle.ktsindex 849bc0bc28..fe6c211d76 100644--- a/library/biometric/build.gradle.kts+++ b/library/biometric/build.gradle.kts@@ -8,4 +8,7 @@ dependencies {     implementation(project(":library"))     implementation(libs.androidx.biometric)     implementation(libs.androidx.fragment.ktx)+    // The instrumented unlock tests drive the system credential screen.+    androidTestImplementation(libs.androidx.test.core)+    androidTestImplementation(libs.androidx.test.uiautomator) }
library/biometric/src/androidTest/AndroidManifest.xml
diff --git a/library/biometric/src/androidTest/AndroidManifest.xml b/library/biometric/src/androidTest/AndroidManifest.xmlnew file mode 100644index 0000000000..cbaa813bf7--- /dev/null+++ b/library/biometric/src/androidTest/AndroidManifest.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+    <application>+        <activity+            android:name="com.vayunmathur.library.biometric.UnlockTestActivity"+            android:exported="true" />+    </application>+</manifest>
library/biometric/src/androidTest/java/com/vayunmathur/library/biometric/UnlockInstrumentedTest.kt
diff --git a/library/biometric/src/androidTest/java/com/vayunmathur/library/biometric/UnlockInstrumentedTest.kt b/library/biometric/src/androidTest/java/com/vayunmathur/library/biometric/UnlockInstrumentedTest.ktnew file mode 100644index 0000000000..46b18b0549--- /dev/null+++ b/library/biometric/src/androidTest/java/com/vayunmathur/library/biometric/UnlockInstrumentedTest.kt@@ -0,0 +1,149 @@+package com.vayunmathur.library.biometric++import android.content.Context+import android.util.Base64+import androidx.biometric.BiometricManager+import androidx.fragment.app.FragmentActivity+import androidx.test.core.app.ActivityScenario+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Instrumented coverage for the biometric prompt's error callback, which cannot+ * arrive under Robolectric (there is no biometric HAL and AndroidX's prompt flow+ * never completes there). On the emulator the system BiometricPrompt panel does+ * appear; cancelling it delivers ERROR_CANCELED to the callback under test.+ *+ * The success callback is not exercised: the emulator's fingerprint HAL has no+ * enrolled finger (enrollment needs host-side emulator-console touches a test+ * cannot send) and its prompt panel offers no PIN fallback button, so no+ * authentication can succeed on this device.+ */+@RunWith(AndroidJUnit4::class)+class UnlockInstrumentedTest {++    private val instrumentation get() = InstrumentationRegistry.getInstrumentation()+    private val ctx: Context get() = instrumentation.targetContext+    private val device: UiDevice get() = UiDevice.getInstance(instrumentation)++    private fun shell(command: String) {+        instrumentation.uiAutomation.executeShellCommand(command).close()+    }++    private fun setPin() {+        // A previous test's credential may still be set (its clear is best-effort);+        // set-pin refuses to replace an existing credential without --old.+        shell("locksettings clear --old $PIN")+        shell("locksettings set-pin $PIN")+        // Keystore refuses auth-bound keys until the new credential registers as a+        // secure lock screen, which lands a moment after the shell command returns.+        val keyguard = ctx.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager+        val deadline = System.currentTimeMillis() + 10_000+        while (!keyguard.isDeviceSecure && System.currentTimeMillis() < deadline) {+            Thread.sleep(100)+        }+        assertTrue("lock screen never became secure after set-pin", keyguard.isDeviceSecure)+    }++    /** Waits until BiometricManager agrees authentication can proceed, then unlocks. */+    private fun unlockWhenReady(activity: FragmentActivity, onSuccess: (String) -> Unit, onFailure: (String?) -> Unit) {+        val manager = BiometricManager.from(activity)+        val authenticators = BiometricManager.Authenticators.BIOMETRIC_STRONG or+            BiometricManager.Authenticators.DEVICE_CREDENTIAL+        val deadline = System.currentTimeMillis() + 15_000+        while (manager.canAuthenticate(authenticators) != BiometricManager.BIOMETRIC_SUCCESS &&+            System.currentTimeMillis() < deadline+        ) {+            Thread.sleep(100)+        }+        unlockDatabaseWithBiometrics(activity, onSuccess, onFailure)+    }++    @Test+    fun cancellingSetupPromptFailsSilentlyAndGeneratesKey() {+        setPin()+        try {+            // Start from no key so unlock takes the first-time setup prompt.+            BiometricDatabaseHelper(ctx).deleteKey()+            val failureLatch = CountDownLatch(1)+            var failureMessage: String? = "unset"+            var succeeded = false+            ActivityScenario.launch(UnlockTestActivity::class.java).use { scenario ->+                scenario.onActivity { activity ->+                    unlockWhenReady(activity, { succeeded = true }, { message ->+                        failureMessage = message; failureLatch.countDown()+                    })+                }+                assertNotNull(+                    "setup prompt never appeared (failure=$failureMessage succeeded=$succeeded)",+                    device.wait(Until.findObject(By.text("Setup Secure Database")), PROMPT_TIMEOUT_MS),+                )+                device.pressBack()+                assertTrue("failure callback never fired", failureLatch.await(30, TimeUnit.SECONDS))+            }+            assertTrue(!succeeded)+            assertEquals(null, failureMessage)+        } finally {+            shell("locksettings clear --old $PIN")+        }+    }++    @Test+    fun cancellingUnlockPromptFailsSilently() {+        setPin()+        try {+            // Seed the stored-passphrase state (key + IV + ciphertext) so unlock takes+            // the decrypt prompt. The ciphertext is arbitrary: cancelling never+            // decrypts it, and an auth-bound key cannot encrypt before authentication+            // anyway, which is exactly why the real flow stores via the prompt cipher.+            val helper = BiometricDatabaseHelper(ctx)+            helper.deleteKey()+            helper.generateKey()+            val prefs = ctx.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+            prefs.edit()+                .putString("passphrase_iv", Base64.encodeToString(ByteArray(12) { it.toByte() }, Base64.NO_WRAP))+                .putString("encrypted_passphrase", Base64.encodeToString(ByteArray(32) { (it * 7).toByte() }, Base64.NO_WRAP))+                .commit()+            assertTrue(helper.isKeyGenerated())++            val failureLatch = CountDownLatch(1)+            var failureMessage: String? = "unset"+            ActivityScenario.launch(UnlockTestActivity::class.java).use { scenario ->+                scenario.onActivity { activity ->+                    unlockWhenReady(activity, { }, { message ->+                        failureMessage = message; failureLatch.countDown()+                    })+                }+                assertNotNull(+                    "unlock prompt never appeared (failure=$failureMessage)",+                    device.wait(Until.findObject(By.text("Unlock Database")), PROMPT_TIMEOUT_MS),+                )+                device.pressBack()+                assertTrue("failure callback never fired", failureLatch.await(30, TimeUnit.SECONDS))+            }+            assertEquals(null, failureMessage)+            // The stored passphrase state survives a cancelled prompt untouched.+            assertEquals(+                Base64.encodeToString(ByteArray(32) { (it * 7).toByte() }, Base64.NO_WRAP),+                prefs.getString("encrypted_passphrase", null),+            )+        } finally {+            shell("locksettings clear --old $PIN")+        }+    }++    private companion object {+        const val PIN = "1111"+        const val PROMPT_TIMEOUT_MS = 15_000L+    }+}
library/biometric/src/androidTest/java/com/vayunmathur/library/biometric/UnlockTestActivity.kt
diff --git a/library/biometric/src/androidTest/java/com/vayunmathur/library/biometric/UnlockTestActivity.kt b/library/biometric/src/androidTest/java/com/vayunmathur/library/biometric/UnlockTestActivity.ktnew file mode 100644index 0000000000..0a50f8f5cf--- /dev/null+++ b/library/biometric/src/androidTest/java/com/vayunmathur/library/biometric/UnlockTestActivity.kt@@ -0,0 +1,6 @@+package com.vayunmathur.library.biometric++import androidx.fragment.app.FragmentActivity++/** Minimal host so instrumented tests can drive [unlockDatabaseWithBiometrics]. */+class UnlockTestActivity : FragmentActivity()
library/biometric/src/test/java/com/vayunmathur/library/biometric/BiometricDatabaseHelperTest.kt
diff --git a/library/biometric/src/test/java/com/vayunmathur/library/biometric/BiometricDatabaseHelperTest.kt b/library/biometric/src/test/java/com/vayunmathur/library/biometric/BiometricDatabaseHelperTest.ktnew file mode 100644index 0000000000..29d98c0554--- /dev/null+++ b/library/biometric/src/test/java/com/vayunmathur/library/biometric/BiometricDatabaseHelperTest.kt@@ -0,0 +1,129 @@+package com.vayunmathur.library.biometric++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import java.security.KeyStore+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++/** Tests for [BiometricDatabaseHelper] over an in-memory fake AndroidKeyStore. */+@RunWith(RobolectricTestRunner::class)+class BiometricDatabaseHelperTest {++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+        // Start clean: the fake keystore is process-global.+        FakeAndroidKeyStore.remove("db_auth_key")+        val ctx = ApplicationProvider.getApplicationContext<Context>()+        ctx.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE).edit().clear().commit()+    }++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private fun helper() = BiometricDatabaseHelper(ctx)++    private fun keyStoreHas(alias: String): Boolean {+        val ks = KeyStore.getInstance("AndroidKeyStore")+        ks.load(null)+        return ks.containsAlias(alias)+    }++    @Test+    fun generateKeyCreatesAuthKeyUnderBiometricAlias() {+        val helper = helper()+        helper.generateKey()+        assertTrue(keyStoreHas("db_auth_key"))+        assertFalse(keyStoreHas("db_no_auth_key"), "base-class alias must not be used")+    }++    @Test+    fun keyWithoutIvIsOrphanedAndCleanedUp() {+        val helper = helper()+        helper.generateKey()+        // No IV has been persisted yet, so the key counts as not generated and+        // isKeyGenerated deletes the orphaned key.+        assertFalse(helper.isKeyGenerated())+        assertFalse(keyStoreHas("db_auth_key"))+    }++    @Test+    fun storeAndGetPassphraseRoundTrips() {+        val helper = helper()+        helper.storePassphrase("correct horse battery staple")+        assertTrue(helper.isKeyGenerated())+        assertEquals("correct horse battery staple", helper.getPassphrase())+        // Stored under the biometric prefs keys, not the base-class ones.+        val prefs = ctx.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+        assertTrue(prefs.contains("encrypted_passphrase"))+        assertTrue(prefs.contains("passphrase_iv"))+        assertFalse(prefs.contains("encrypted_passphrase_no_auth"))+        // The stored value is ciphertext, not the passphrase itself.+        assertNotEquals(+            "correct horse battery staple",+            prefs.getString("encrypted_passphrase", null),+        )+    }++    @Test+    fun createAndStorePassphraseReturnsDecryptableSecret() {+        val helper = helper()+        helper.generateKey()+        val passphrase = helper.createAndStorePassphrase(helper.getCipherForEncryption())+        assertTrue(passphrase.isNotBlank())+        val decrypted = helper.decryptPassphrase(helper.getCipherForDecryption())+        assertEquals(passphrase, decrypted)+    }++    @Test+    fun deleteKeyRemovesKeyAndPrefs() {+        val helper = helper()+        helper.storePassphrase("to-delete")+        assertTrue(helper.isKeyGenerated())+        helper.deleteKey()+        assertFalse(helper.isKeyGenerated())+        assertFalse(keyStoreHas("db_auth_key"))+        val prefs = ctx.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+        assertFalse(prefs.contains("encrypted_passphrase"))+        assertFalse(prefs.contains("passphrase_iv"))+    }++    @Test+    fun decryptWithoutPassphraseThrows() {+        val helper = helper()+        helper.generateKey()+        helper.storePassphrase("x")+        // Remove just the passphrase, leaving the IV: decryption must fail loudly.+        ctx.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+            .edit().remove("encrypted_passphrase").commit()+        assertFailsWith<IllegalStateException> {+            helper.decryptPassphrase(helper.getCipherForDecryption())+        }+    }++    @Test+    fun decryptionCipherWithoutIvThrows() {+        val helper = helper()+        helper.generateKey()+        assertFailsWith<IllegalStateException> { helper.getCipherForDecryption() }+    }++    @Test+    fun tamperedCiphertextDoesNotDecryptToPassphrase() {+        val helper = helper()+        helper.storePassphrase("sensitive")+        val prefs = ctx.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+        val stored = prefs.getString("encrypted_passphrase", null)!!+        // Flip the stored ciphertext; GCM must reject it rather than return garbage.+        val tampered = (if (stored.first() == 'A') 'B' else 'A') + stored.substring(1)+        prefs.edit().putString("encrypted_passphrase", tampered).commit()+        runCatching { helper.getPassphrase() }+            .onSuccess { throw AssertionError("tampered ciphertext decrypted to: $it") }+    }+}
library/biometric/src/test/java/com/vayunmathur/library/biometric/FakeAndroidKeyStore.kt
diff --git a/library/biometric/src/test/java/com/vayunmathur/library/biometric/FakeAndroidKeyStore.kt b/library/biometric/src/test/java/com/vayunmathur/library/biometric/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..62eb0f38fd--- /dev/null+++ b/library/biometric/src/test/java/com/vayunmathur/library/biometric/FakeAndroidKeyStore.kt@@ -0,0 +1,101 @@+package com.vayunmathur.library.biometric++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+import java.security.KeyStore+import java.security.KeyStoreSpi+import java.security.Provider+import java.security.SecureRandom+import java.security.Security+import java.security.cert.Certificate+import java.util.Collections+import java.util.Date+import java.util.Enumeration+import javax.crypto.KeyGenerator+import javax.crypto.KeyGeneratorSpi+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * Robolectric has no AndroidKeyStore provider, which otherwise blocks every+ * code path that opens the SQLCipher vault (PasswordRepository,+ * DatabaseHelper, KdbxPasswordHelper). Installing this JCA provider gives+ * tests a plain in-memory AES keystore with the same alias semantics; keys+ * never leave the test process.+ */+object FakeAndroidKeyStore {+    private val keys = mutableMapOf<String, SecretKey>()++    fun install() {+        if (Security.getProvider("AndroidKeyStore") == null) {+            Security.addProvider(FakeProvider())+        }+    }++    /** When true, the next key generation fails as it does with no way to authenticate the user. */+    var failGeneration: Boolean = false++    fun put(alias: String, key: SecretKey) {+        keys[alias] = key+    }++    fun get(alias: String): SecretKey? = keys[alias]++    fun remove(alias: String) {+        keys.remove(alias)+    }++    fun contains(alias: String): Boolean = keys.containsKey(alias)++    fun aliases(): List<String> = keys.keys.toList()++    class FakeProvider : Provider("AndroidKeyStore", 1.0, "in-memory test keystore") {+        init {+            put("KeyStore.AndroidKeyStore", FakeKeyStoreSpi::class.java.name)+            put("KeyGenerator.AES", FakeKeyGeneratorSpi::class.java.name)+        }+    }++    class FakeKeyStoreSpi : KeyStoreSpi() {+        override fun engineLoad(stream: InputStream?, password: CharArray?) = Unit+        override fun engineContainsAlias(alias: String) = contains(alias)+        override fun engineDeleteEntry(alias: String) = remove(alias)+        override fun engineGetKey(alias: String, password: CharArray?): Key? = get(alias)+        override fun engineIsKeyEntry(alias: String) = contains(alias)+        override fun engineAliases(): Enumeration<String> = Collections.enumeration(aliases())+        override fun engineSize() = aliases().size+        override fun engineGetCertificate(alias: String): Certificate? = null+        override fun engineGetCertificateAlias(cert: Certificate) = null+        override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null+        override fun engineGetCreationDate(alias: String) = Date()+        override fun engineIsCertificateEntry(alias: String) = false+        override fun engineSetCertificateEntry(alias: String, cert: Certificate) = Unit+        override fun engineStore(stream: OutputStream?, password: CharArray?) = Unit+        override fun engineSetKeyEntry(alias: String, key: Key, password: CharArray?, chain: Array<out Certificate>?) {+            if (key is SecretKey) put(alias, key)+        }+        override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) = Unit+    }++    class FakeKeyGeneratorSpi : KeyGeneratorSpi() {+        private var alias: String = "test-key"++        override fun engineInit(random: SecureRandom) = Unit+        override fun engineInit(keysize: Int, random: SecureRandom) = Unit+        override fun engineInit(params: java.security.spec.AlgorithmParameterSpec?, random: SecureRandom) {+            if (failGeneration) throw IllegalStateException("no authentication method available")+            if (params is KeyGenParameterSpec) alias = params.keystoreAlias+        }++        override fun engineGenerateKey(): SecretKey {+            val bytes = ByteArray(32)+            SecureRandom().nextBytes(bytes)+            return SecretKeySpec(bytes, "AES").also { put(alias, it) }+        }+    }++    /** Convenience for tests that obtain a generator through JCA. */+    fun generator(): KeyGenerator = KeyGenerator.getInstance("AES", "AndroidKeyStore")+}
library/biometric/src/test/java/com/vayunmathur/library/biometric/FrameworkShadows.kt
diff --git a/library/biometric/src/test/java/com/vayunmathur/library/biometric/FrameworkShadows.kt b/library/biometric/src/test/java/com/vayunmathur/library/biometric/FrameworkShadows.ktnew file mode 100644index 0000000000..163565fbfa--- /dev/null+++ b/library/biometric/src/test/java/com/vayunmathur/library/biometric/FrameworkShadows.kt@@ -0,0 +1,26 @@+package com.vayunmathur.library.biometric++import android.hardware.biometrics.BiometricManager+import android.hardware.biometrics.BiometricPrompt+import android.os.CancellationSignal+import java.util.concurrent.Executor+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements++/**+ * Robolectric has no biometric shadows, so the framework biometric service always+ * reports success and its prompt never answers. These shadows stand in for that+ * missing HAL: they only replace the android.hardware.biometrics framework calls+ * AndroidX delegates to, never the code under test.+ */+@Implements(BiometricManager::class)+class ShadowFrameworkBiometricManager {+    @Implementation+    fun canAuthenticate(authenticators: Int): Int = statusToReturn++    companion object {+        /** The status the next canAuthenticate call reports; BiometricManager codes. */+        var statusToReturn: Int = BiometricManager.BIOMETRIC_SUCCESS+    }+}+
library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockBiometricsTest.kt
diff --git a/library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockBiometricsTest.kt b/library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockBiometricsTest.ktnew file mode 100644index 0000000000..29e8ae2ce6--- /dev/null+++ b/library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockBiometricsTest.kt@@ -0,0 +1,98 @@+package com.vayunmathur.library.biometric++import android.content.Context+import android.os.Looper+import androidx.fragment.app.FragmentActivity+import androidx.test.core.app.ApplicationProvider+import java.security.KeyStore+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Tests for [unlockDatabaseWithBiometrics] prompt setup.+ *+ * Robolectric's biometric manager reports BIOMETRIC_SUCCESS and the prompt itself+ * never produces an authentication result, so these pin the parts that run before+ * a result could arrive: key generation on first use, and reaching the prompt+ * without invoking either callback. The unavailable-device branch and the+ * authentication callbacks cannot be driven without a biometric HAL.+ */+@RunWith(RobolectricTestRunner::class)+class UnlockBiometricsTest {++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+        FakeAndroidKeyStore.remove("db_auth_key")+        ApplicationProvider.getApplicationContext<Context>()+            .getSharedPreferences("secure_prefs", Context.MODE_PRIVATE).edit().clear().commit()+    }++    private fun activity(): FragmentActivity =+        Robolectric.buildActivity(FragmentActivity::class.java).create().start().resume().get()++    private fun keyStoreHas(alias: String): Boolean {+        val ks = KeyStore.getInstance("AndroidKeyStore")+        ks.load(null)+        return ks.containsAlias(alias)+    }++    @Test+    fun firstUnlockGeneratesKeyAndShowsSetupPrompt() {+        val activity = activity()+        var success: String? = null+        var failure: String? = "not-called"+        unlockDatabaseWithBiometrics(activity, { success = it }, { failure = it })+        shadowOf(Looper.getMainLooper()).idle()+        // The auth-bound key is generated before the setup prompt is shown.+        assertTrue(keyStoreHas("db_auth_key"))+        // No result has arrived, so neither callback may fire.+        assertEquals(null, success)+        assertEquals("not-called", failure)+        // A biometric prompt fragment is now attached to the activity.+        assertTrue(+            activity.supportFragmentManager.fragments.isNotEmpty(),+            "expected a BiometricPrompt fragment",+        )+    }++    @Test+    fun unlockWithExistingKeyShowsUnlockPromptAndKeepsPassphrase() {+        val ctx = ApplicationProvider.getApplicationContext<Context>()+        val helper = BiometricDatabaseHelper(ctx)+        helper.storePassphrase("existing-secret")++        val activity = activity()+        var success: String? = null+        var failure: String? = "not-called"+        unlockDatabaseWithBiometrics(activity, { success = it }, { failure = it })+        shadowOf(Looper.getMainLooper()).idle()+        assertEquals(null, success)+        assertEquals("not-called", failure)+        assertTrue(activity.supportFragmentManager.fragments.isNotEmpty())+        // Merely showing the prompt must not rotate or clear the stored passphrase.+        assertEquals("existing-secret", helper.getPassphrase())+    }++    @Test+    fun secondUnlockStillReachesPrompt() {+        val activity = activity()+        var failures = 0+        unlockDatabaseWithBiometrics(activity, {}, { failures++ })+        shadowOf(Looper.getMainLooper()).idle()+        unlockDatabaseWithBiometrics(activity, {}, { failures++ })+        shadowOf(Looper.getMainLooper()).idle()+        assertEquals(0, failures)+        assertFalse(+            activity.supportFragmentManager.fragments.isEmpty(),+            "prompt fragment should be attached",+        )+    }+}
library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockStatusTest.kt
diff --git a/library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockStatusTest.kt b/library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockStatusTest.ktnew file mode 100644index 0000000000..9d04c00f24--- /dev/null+++ b/library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockStatusTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.library.biometric++import android.hardware.biometrics.BiometricManager+import android.os.Looper+import androidx.fragment.app.FragmentActivity+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Tests for the unavailable-device and prompt-error paths of+ * [unlockDatabaseWithBiometrics], using [FrameworkShadows] for the missing+ * biometric HAL (see that file for why the shadows exist).+ */+@RunWith(RobolectricTestRunner::class)+class UnlockStatusTest {++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+        ShadowFrameworkBiometricManager.statusToReturn = BiometricManager.BIOMETRIC_SUCCESS+    }++    private fun activity(): FragmentActivity =+        Robolectric.buildActivity(FragmentActivity::class.java).create().start().resume().get()++    @Test+    @Config(shadows = [ShadowFrameworkBiometricManager::class])+    fun noneEnrolledShowsScreenLockMessage() {+        ShadowFrameworkBiometricManager.statusToReturn = BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED+        var failure: String? = null+        var succeeded = false+        unlockDatabaseWithBiometrics(activity(), { succeeded = true }, { failure = it })+        assertEquals(+            "Set up a screen lock (PIN, pattern, password, or biometric) to use the secure folder.",+            failure,+        )+        assertTrue(!succeeded)+    }++    @Test+    @Config(shadows = [ShadowFrameworkBiometricManager::class])+    fun noHardwareShowsUnavailableMessage() {+        ShadowFrameworkBiometricManager.statusToReturn = BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE+        var failure: String? = null+        unlockDatabaseWithBiometrics(activity(), {}, { failure = it })+        assertEquals(+            "Device authentication isn't available, so the secure folder can't be opened.",+            failure,+        )+    }++    @Test+    @Config(shadows = [ShadowFrameworkBiometricManager::class])+    fun hwUnavailableShowsUnavailableMessage() {+        ShadowFrameworkBiometricManager.statusToReturn = BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE+        var failure: String? = null+        unlockDatabaseWithBiometrics(activity(), {}, { failure = it })+        assertEquals(+            "Device authentication isn't available, so the secure folder can't be opened.",+            failure,+        )+    }++    @Test+    @Config(shadows = [ShadowFrameworkBiometricManager::class])+    fun unknownStatusShowsGenericMessage() {+        ShadowFrameworkBiometricManager.statusToReturn = 999+        var failure: String? = null+        unlockDatabaseWithBiometrics(activity(), {}, { failure = it })+        assertEquals("Device authentication is required to use the secure folder.", failure)+    }++    @Test+    fun keyGenerationFailureShowsGenericMessage() {+        FakeAndroidKeyStore.remove("db_auth_key")+        FakeAndroidKeyStore.failGeneration = true+        try {+            var failure: String? = null+            var succeeded = false+            unlockDatabaseWithBiometrics(activity(), { succeeded = true }, { failure = it })+            assertEquals("Device authentication is required to use the secure folder.", failure)+            assertTrue(!succeeded)+        } finally {+            FakeAndroidKeyStore.failGeneration = false+        }+    }+}