Modern Apps git

← Modern-Apps.git

library/biometric: authentication failures reach onFailure instead of crashing the gate

Commit
4219bfc7a0a4edcf88cb78bc5dd4bceefe37cd9b
Author
Vayun Mathur <[email protected]>
When
2026-12-01 10:13 UTC (4 days ago)
Parents
d479d87
Every crypto failure escaped as an uncaught exception
instead of the documented onFailure. Pre-prompt, the eager
cipher build threw KeyPermanentlyInvalidatedException when
the key was invalidated but its alias/IV remained — crashing
biometric-gated hosts (MaFragmentActivity gates) in
onCreateBeforeContent with neither callback run. In the
callback, unguarded cipher use threw AEADBadTagException on
tampered ciphertext or IllegalStateException when the
ciphertext pref was missing — after the user had already
authenticated, again with neither onSuccess nor onFailure.

The callback now routes through deliverAuthenticatedCipher
(null cipher or security/state exceptions become onFailure)
and both pre-prompt cipher builds are guarded the same way
(no prompt shown). Five regression tests fail against the
unguarded paths. Verified: :library:biometric:
testDebugUnitTest 21 tests pass; lint no issues; detekt
clean. library/work was audited alongside and cleared (its
separate commit only corrects the documented verify commands
and a deterministic test fixture).

Diff

library/biometric/AGENTS.md
diff --git a/library/biometric/AGENTS.md b/library/biometric/AGENTS.mdindex 51ac6bc610..809de7b3af 100644--- a/library/biometric/AGENTS.md+++ b/library/biometric/AGENTS.md@@ -20,6 +20,7 @@  ## Verify (this module only) ```-./gradlew :library:biometric:compileDevKotlin+./gradlew :library:biometric:compileDebugKotlin+./gradlew :library:biometric:testDebugUnitTest ./gradlew :library:biometric:lint ```
library/biometric/src/main/java/com/vayunmathur/library/biometric/BiometricDatabaseHelper.kt
diff --git a/library/biometric/src/main/java/com/vayunmathur/library/biometric/BiometricDatabaseHelper.kt b/library/biometric/src/main/java/com/vayunmathur/library/biometric/BiometricDatabaseHelper.ktindex 16aac3241e..880d58beec 100644--- a/library/biometric/src/main/java/com/vayunmathur/library/biometric/BiometricDatabaseHelper.kt+++ b/library/biometric/src/main/java/com/vayunmathur/library/biometric/BiometricDatabaseHelper.kt@@ -8,9 +8,13 @@ import androidx.biometric.BiometricPrompt import androidx.core.content.ContextCompat import androidx.fragment.app.FragmentActivity import com.vayunmathur.library.util.DatabaseHelper+import java.security.GeneralSecurityException import javax.crypto.Cipher import javax.crypto.KeyGenerator +/** User-facing message when authentication completes but the stored key can't be used. */+private const val CIPHER_UNLOCK_FAILED_MESSAGE = "Device authentication didn't unlock the secure folder."+ /**  * Database key helper whose AES key is bound to biometric/device-credential  * authentication, so the SQLCipher passphrase can only be unwrapped after the@@ -72,14 +76,7 @@ fun unlockDatabaseWithBiometrics(     fun prompt(title: String, subtitle: String, cipher: Cipher, onCipher: (Cipher) -> String) {         val biometricPrompt = BiometricPrompt(activity, executor, object : BiometricPrompt.AuthenticationCallback() {             override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {-                // Device-credential success can deliver no CryptoObject on some-                // devices; fail gracefully instead of crashing on a force-unwrap.-                val cipher = result.cryptoObject?.cipher-                if (cipher == null) {-                    onFailure("Device authentication didn't unlock the secure folder.")-                    return-                }-                onSuccess(onCipher(cipher))+                deliverAuthenticatedCipher(result.cryptoObject?.cipher, onCipher, onSuccess, onFailure)             }              override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {@@ -112,20 +109,70 @@ fun unlockDatabaseWithBiometrics(             onFailure(biometricUnavailableMessage(status))             return         }+        val encryptionCipher = cipherForPrompt({ helper.getCipherForEncryption() }, onFailure) ?: return         prompt(             "Setup Secure Database",             "Authenticate to create your secure encryption key",-            helper.getCipherForEncryption()+            encryptionCipher         ) { helper.createAndStorePassphrase(it) }     } else {+        val decryptionCipher = cipherForPrompt({ helper.getCipherForDecryption() }, onFailure) ?: return         prompt(             "Unlock Database",             "Authenticate to access your secure data",-            helper.getCipherForDecryption()+            decryptionCipher         ) { helper.decryptPassphrase(it) }     } } +/**+ * Runs [factory] to build the prompt's cipher, reporting failure through+ * [onFailure] instead of throwing: a permanently invalidated key surfaces as a+ * [GeneralSecurityException] from `Cipher.init` here, before any prompt is+ * shown, and the caller asked for a callback — not a crash inside its gate.+ */+private fun cipherForPrompt(factory: () -> Cipher, onFailure: (String?) -> Unit): Cipher? = try {+    factory()+} catch (expected: GeneralSecurityException) {+    onFailure(CIPHER_UNLOCK_FAILED_MESSAGE)+    null+} catch (expected: IllegalStateException) {+    onFailure(CIPHER_UNLOCK_FAILED_MESSAGE)+    null+}++/**+ * Delivers the result of using the cipher a successful authentication unlocked.+ *+ * [onCipher] does the crypto after the prompt reports success; a missing cipher+ * (device-credential success can deliver no CryptoObject on some devices), a key+ * that no longer matches the stored ciphertext, or a lost stored passphrase all+ * surface as exceptions there. Report them through [onFailure] — throwing out+ * of the authentication callback crashed the host instead, and the caller saw+ * neither callback.+ */+internal fun deliverAuthenticatedCipher(+    cipher: Cipher?,+    onCipher: (Cipher) -> String,+    onSuccess: (String) -> Unit,+    onFailure: (String?) -> Unit,+) {+    if (cipher == null) {+        onFailure(CIPHER_UNLOCK_FAILED_MESSAGE)+        return+    }+    val passphrase = try {+        onCipher(cipher)+    } catch (expected: GeneralSecurityException) {+        onFailure(CIPHER_UNLOCK_FAILED_MESSAGE)+        return+    } catch (expected: IllegalStateException) {+        onFailure(CIPHER_UNLOCK_FAILED_MESSAGE)+        return+    }+    onSuccess(passphrase)+}+ /** User-facing reason why the device can't authenticate for the secure folder. */ private fun biometricUnavailableMessage(status: Int): String = when (status) {     BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED ->
library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockCipherDeliveryTest.kt
diff --git a/library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockCipherDeliveryTest.kt b/library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockCipherDeliveryTest.ktnew file mode 100644index 0000000000..58e972209f--- /dev/null+++ b/library/biometric/src/test/java/com/vayunmathur/library/biometric/UnlockCipherDeliveryTest.kt@@ -0,0 +1,117 @@+package com.vayunmathur.library.biometric++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Regression tests for result delivery in [unlockDatabaseWithBiometrics] (after+ * authentication).+ *+ * The prompt's success callback runs the crypto on the unlocked cipher, and the+ * stored state can make that throw: a tampered ciphertext (GCM tag mismatch), a+ * stored IV whose passphrase is gone, or a key that no longer decrypts the stored+ * bytes. Before the fix those exceptions escaped the callback, so neither+ * onSuccess nor onFailure ran and the host crashed in its biometric gate (the+ * module contract is to report through onFailure instead). Robolectric has no+ * biometric HAL, so these drive [deliverAuthenticatedCipher] — the callback body —+ * with real ciphers, and pin the decrypted/failed states at the helper level the+ * same way the instrumented tests seed them.+ */+@RunWith(RobolectricTestRunner::class)+class UnlockCipherDeliveryTest {++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+        FakeAndroidKeyStore.remove("db_auth_key")+        ApplicationProvider.getApplicationContext<Context>()+            .getSharedPreferences("secure_prefs", Context.MODE_PRIVATE).edit().clear().commit()+    }++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private fun helper() = BiometricDatabaseHelper(ctx)++    private class Delivery {+        var success: String? = null+        var failure: String? = "not-called"+    }++    private fun deliver(+        cipher: javax.crypto.Cipher?,+        onCipher: (javax.crypto.Cipher) -> String,+    ): Delivery {+        val delivery = Delivery()+        deliverAuthenticatedCipher(+            cipher,+            onCipher,+            { delivery.success = it },+            { delivery.failure = it },+        )+        return delivery+    }++    @Test+    fun missingCipherReportsFailure() {+        val delivery = deliver(null) { "never-used" }+        assertEquals(null, delivery.success)+        assertEquals("Device authentication didn't unlock the secure folder.", delivery.failure)+    }++    @Test+    fun authenticatedDecryptionDeliversPassphrase() {+        val helper = helper()+        helper.storePassphrase("open sesame")+        val delivery = deliver(helper.getCipherForDecryption()) { helper.decryptPassphrase(it) }+        assertEquals("open sesame", delivery.success)+        assertEquals("not-called", delivery.failure)+    }++    @Test+    fun setupCipherCreatesStoredPassphrase() {+        val helper = helper()+        helper.generateKey()+        val delivery = deliver(helper.getCipherForEncryption()) { helper.createAndStorePassphrase(it) }+        val created = delivery.success+        assertNotNull(created)+        assertTrue(created.isNotBlank())+        assertEquals("not-called", delivery.failure)+        assertEquals(delivery.success, helper.decryptPassphrase(helper.getCipherForDecryption()))+    }++    @Test+    fun tamperedCiphertextReportsFailureInsteadOfThrowing() {+        val helper = helper()+        helper.storePassphrase("sensitive")+        val prefs = ctx.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+        val stored = prefs.getString("encrypted_passphrase", null)!!+        // Same tampering the helper test pins as a decrypt-time failure: GCM must+        // reject it, and the failure must land in onFailure, not escape.+        val tampered = (if (stored.first() == 'A') 'B' else 'A') + stored.substring(1)+        prefs.edit().putString("encrypted_passphrase", tampered).commit()+        val delivery = deliver(helper.getCipherForDecryption()) { helper.decryptPassphrase(it) }+        assertEquals(null, delivery.success)+        assertEquals("Device authentication didn't unlock the secure folder.", delivery.failure)+    }++    @Test+    fun missingPassphraseReportsFailureInsteadOfThrowing() {+        val helper = helper()+        helper.generateKey()+        helper.storePassphrase("x")+        // The IV survives, so the key counts as generated — but with the ciphertext+        // gone, decryption can only throw IllegalStateException("Passphrase not found").+        ctx.getSharedPreferences("secure_prefs", Context.MODE_PRIVATE)+            .edit().remove("encrypted_passphrase").commit()+        assertTrue(helper.isKeyGenerated())+        val delivery = deliver(helper.getCipherForDecryption()) { helper.decryptPassphrase(it) }+        assertEquals(null, delivery.success)+        assertEquals("Device authentication didn't unlock the secure folder.", delivery.failure)+    }+}