passwords: stop blocking the main thread in credential flows
- Commit
df45138be8e095535a8fe33f6c9cef1e66dc224e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-20 18:57 UTC (15 days ago)
- Parents
2f501a5
PasskeyAuthActivity ran six plain runBlocking repository calls on the main thread (SQLCipher open/read), and the autofill and Credential Manager services ran blocking full-table reads inside main-thread framework callbacks - ANR risk exactly where the user is waiting on a passkey prompt. Activity work now runs in lifecycleScope with IO hops; the services use a SupervisorJob+IO scope cancelled in onDestroy. Framework contracts preserved: OutcomeReceiver/FillCallback/ SaveCallback are invoked exactly once from the IO coroutine with the same success and failure outcomes (a throwable that used to be thrown synchronously into the framework now completes the callback with the existing fallback instead of hanging it), the framework CancellationSignal cancels the job, and activity RESULT_OK/CANCELED semantics are unchanged. Tests updated to the async completion behaviour (poll for callback, idle looper) - 436/436 pass. Real passkey ceremonies remain device-only.
Diff
passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyCredentialService.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyCredentialService.kt b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyCredentialService.ktindex 895b56c6e9..0b0115323f 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyCredentialService.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyCredentialService.kt@@ -25,13 +25,27 @@ import com.vayunmathur.passwords.R import com.vayunmathur.passwords.data.PasswordDatabase import com.vayunmathur.passwords.data.PasswordRepository import com.vayunmathur.passwords.ui.PasskeyAuthActivity-import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch /** Passkey Credential Service: a credential provider service implementation for passkey credential service. */ class PasskeyCredentialService : CredentialProviderService() { private val repository by lazy { PasswordRepository.get(applicationContext) } + // Owned by the service (no lifecycleScope on a Service): cancelled in+ // onDestroy. All repository work runs on Dispatchers.IO.+ private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ override fun onDestroy() {+ serviceScope.cancel()+ super.onDestroy()+ }+ private fun buildUnlockResponse(): BeginGetCredentialResponse { val intent = Intent(applicationContext, PasskeyAuthActivity::class.java).apply { putExtra(PasskeyAuthActivity.EXTRA_FLOW, PasskeyAuthActivity.FLOW_UNLOCK)@@ -60,7 +74,11 @@ class PasskeyCredentialService : CredentialProviderService() { callback.onResult(buildUnlockResponse()) return }- runBlocking {+ // Credential Manager awaits the OutcomeReceiver, so returning here+ // without blocking is the framework's async contract: the callback+ // is invoked exactly once, from the IO coroutine, when the vault+ // read completes (or with the unlock fallback on IllegalState).+ val job = serviceScope.launch { try { val response = buildGetCredentialResponse( applicationContext,@@ -68,13 +86,22 @@ class PasskeyCredentialService : CredentialProviderService() { repository, ) callback.onResult(response)+ } catch (expected: CancellationException) {+ throw expected } catch (expected: IllegalStateException) { Log.error(TAG, "onBeginGetCredentialRequest failed, falling back to unlock", expected) closeCachedDatabase<PasswordDatabase>() DatabaseHelper(applicationContext).deleteKey() callback.onResult(buildUnlockResponse())+ } catch (expected: Throwable) {+ // e.g. SQLCipher native load failure opening the vault: the+ // callback must still complete, so fall back to unlock rather+ // than leaving Credential Manager waiting on a dead coroutine.+ Log.error(TAG, "onBeginGetCredentialRequest failed, falling back to unlock", expected)+ callback.onResult(buildUnlockResponse()) } }+ cancellationSignal.setOnCancelListener { job.cancel() } } override fun onBeginCreateCredentialRequest(
passwords/src/main/java/com/vayunmathur/passwords/platform/PasswordAutofillService.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasswordAutofillService.kt b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasswordAutofillService.ktindex 486ea2887a..52b09f985d 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasswordAutofillService.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasswordAutofillService.kt@@ -27,7 +27,12 @@ import com.vayunmathur.library.util.DatabaseHelper import com.vayunmathur.passwords.R import com.vayunmathur.passwords.data.PasswordRepository import com.vayunmathur.passwords.domain.DomainMatch-import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch import com.vayunmathur.library.log.Log import com.vayunmathur.passwords.data.Password @@ -41,6 +46,15 @@ class PasswordAutofillService : AutofillService() { } private val repository by lazy { PasswordRepository.get(applicationContext) } + // Owned by the service (no lifecycleScope on a Service): cancelled in+ // onDestroy. All repository work runs on Dispatchers.IO.+ private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ override fun onDestroy() {+ serviceScope.cancel()+ super.onDestroy()+ }+ override fun onFillRequest(request: FillRequest, cancellationSignal: CancellationSignal, callback: FillCallback) { if (!isDatabaseAvailable) { callback.onSuccess(null)@@ -61,7 +75,10 @@ class PasswordAutofillService : AutofillService() { val inlineSpecs = request.inlineSuggestionsRequest?.inlinePresentationSpecs - runBlocking {+ // FillCallback is the autofill framework's async contract: return+ // without blocking and invoke the callback exactly once when the+ // IO vault read completes.+ val job = serviceScope.launch { try { val allPasswords = repository.getAllPasswords() @@ -71,7 +88,7 @@ class PasswordAutofillService : AutofillService() { if (matches.isEmpty()) { callback.onSuccess(null)- return@runBlocking+ return@launch } val responseBuilder = FillResponse.Builder()@@ -101,11 +118,19 @@ class PasswordAutofillService : AutofillService() { } callback.onSuccess(responseBuilder.build())+ } catch (expected: CancellationException) {+ throw expected } catch (expected: IllegalStateException) { Log.error(tag, "Error in onFillRequest", expected) callback.onSuccess(null)+ } catch (expected: Throwable) {+ // e.g. SQLCipher native load failure: the callback must+ // still complete, with the same no-fill outcome.+ Log.error(tag, "Error in onFillRequest", expected)+ callback.onSuccess(null) } }+ cancellationSignal.setOnCancelListener { job.cancel() } } override fun onSaveRequest(request: SaveRequest, callback: SaveCallback) {@@ -114,8 +139,12 @@ class PasswordAutofillService : AutofillService() { val password = parser.passwordText if (!username.isNullOrBlank() && !password.isNullOrBlank()) {- try {- runBlocking {+ // SaveCallback is the autofill framework's async contract:+ // invoke it exactly once when the IO vault write completes.+ // onSaveRequest has no CancellationSignal; serviceScope+ // cancellation in onDestroy is the cancellation path here.+ serviceScope.launch {+ try { val candidates = repository.getAllPasswords() val existing = candidates.firstOrNull { it.username == username || it.email == username } if (existing != null) {@@ -133,12 +162,20 @@ class PasswordAutofillService : AutofillService() { ) ) }+ callback.onSuccess()+ } catch (expected: CancellationException) {+ throw expected+ } catch (expected: IllegalStateException) {+ Log.error(tag, "Error in onSaveRequest", expected)+ callback.onFailure("Unable to open vault")+ } catch (expected: Throwable) {+ // e.g. SQLCipher native load failure: complete the+ // callback with the same vault-failure outcome.+ Log.error(tag, "Error in onSaveRequest", expected)+ callback.onFailure("Unable to open vault")+ } }- } catch (expected: IllegalStateException) {- Log.error(tag, "Error in onSaveRequest", expected)- callback.onFailure("Unable to open vault")- return- }+ return } callback.onSuccess() }
passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.ktindex 4cc050b452..9392f733ce 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt@@ -21,7 +21,11 @@ import com.vayunmathur.passwords.domain.Cbor import com.vayunmathur.passwords.platform.PasskeyCredentialService import com.vayunmathur.passwords.platform.PasskeyUtils import com.vayunmathur.passwords.platform.buildGetCredentialResponse-import kotlinx.coroutines.runBlocking+import androidx.lifecycle.lifecycleScope+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext import org.json.JSONArray import org.json.JSONObject import java.security.MessageDigest@@ -57,37 +61,48 @@ class PasskeyAuthActivity : FragmentActivity() { private fun proceedWithFlow() { val flow = intent.getStringExtra(EXTRA_FLOW)- try {- when (flow) {- FLOW_CREATE -> handleCreate()- FLOW_GET -> handleGet()- FLOW_PASSWORD -> handlePassword()- FLOW_UNLOCK -> handleUnlock()- else -> {- Log.error(TAG, "Unknown flow: $flow")- setResult(RESULT_CANCELED)+ // Repository work (SQLCipher Room open/read, key generation, signing)+ // runs on Dispatchers.IO inside each handler; this coroutine stays on+ // the main thread so setResult/finish keep their original ordering.+ // lifecycleScope cancels it in onDestroy, so a destroyed activity+ // never completes a ceremony late.+ lifecycleScope.launch {+ try {+ when (flow) {+ FLOW_CREATE -> handleCreate()+ FLOW_GET -> handleGet()+ FLOW_PASSWORD -> handlePassword()+ FLOW_UNLOCK -> handleUnlock()+ else -> {+ Log.error(TAG, "Unknown flow: $flow")+ setResult(RESULT_CANCELED)+ } }+ } catch (expected: CancellationException) {+ // Lifecycle cancellation (activity destroyed): not a flow+ // failure, so don't overwrite the result or finish again.+ throw expected+ } catch (expected: IllegalStateException) {+ Log.error(TAG, "Error in passkey $flow flow", expected)+ setResult(RESULT_CANCELED)+ } catch (expected: org.json.JSONException) {+ // Calling app supplied malformed requestJson; cancel, don't crash.+ Log.error(TAG, "Malformed passkey request JSON in $flow flow", expected)+ setResult(RESULT_CANCELED)+ } catch (expected: IllegalArgumentException) {+ // Bad Base64url user handle / stored credential id from the calling app or import.+ Log.error(TAG, "Malformed passkey data in $flow flow", expected)+ setResult(RESULT_CANCELED)+ } catch (expected: java.security.GeneralSecurityException) {+ // Corrupt imported private key cannot sign; cancel the assertion.+ Log.error(TAG, "Passkey signing failed in $flow flow", expected)+ setResult(RESULT_CANCELED) }- } catch (expected: IllegalStateException) {- Log.error(TAG, "Error in passkey $flow flow", expected)- setResult(RESULT_CANCELED)- } catch (expected: org.json.JSONException) {- // Calling app supplied malformed requestJson; cancel, don't crash.- Log.error(TAG, "Malformed passkey request JSON in $flow flow", expected)- setResult(RESULT_CANCELED)- } catch (expected: IllegalArgumentException) {- // Bad Base64url user handle / stored credential id from the calling app or import.- Log.error(TAG, "Malformed passkey data in $flow flow", expected)- setResult(RESULT_CANCELED)- } catch (expected: java.security.GeneralSecurityException) {- // Corrupt imported private key cannot sign; cancel the assertion.- Log.error(TAG, "Passkey signing failed in $flow flow", expected)- setResult(RESULT_CANCELED)+ finish() }- finish() } - private fun handleCreate() {+ private suspend fun handleCreate() { val request = PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent) ?: run { Log.error(TAG, "No create credential request in intent") setResult(RESULT_CANCELED)@@ -122,7 +137,7 @@ class PasskeyAuthActivity : FragmentActivity() { // them must not happen. val excludedIds = PasskeyUtils.credentialDescriptorIds(json, "excludeCredentials") if (excludedIds.isNotEmpty()) {- val excluded = runBlocking { repository.getPasskeysByRpId(rpId) }.any { stored ->+ val excluded = withContext(Dispatchers.IO) { repository.getPasskeysByRpId(rpId) }.any { stored -> excludedIds.any { PasskeyUtils.credentialIdsMatch(stored.credentialId, it) } } if (excluded) {@@ -140,7 +155,7 @@ class PasskeyAuthActivity : FragmentActivity() { Log.dev(TAG, "Create passkey for rpId=$rpId, origin=$origin, privileged=$isPrivileged") // Generate the credential and persist it; both transports share this.- val created = runBlocking {+ val created = withContext(Dispatchers.IO) { WebAuthnAuthenticator.createCredential( rpId = rpId, rpName = rpName,@@ -200,7 +215,7 @@ class PasskeyAuthActivity : FragmentActivity() { setResult(RESULT_OK, result) } - private fun handleGet() {+ private suspend fun handleGet() { val providerRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent) ?: run { Log.error(TAG, "No get credential request in intent") setResult(RESULT_CANCELED)@@ -212,7 +227,7 @@ class PasskeyAuthActivity : FragmentActivity() { return } - val passkey = runBlocking { repository.getPasskeyByCredentialId(credentialId) } ?: run {+ val passkey = withContext(Dispatchers.IO) { repository.getPasskeyByCredentialId(credentialId) } ?: run { Log.error(TAG, "Passkey not found for credentialId=$credentialId") setResult(RESULT_CANCELED) return@@ -264,7 +279,7 @@ class PasskeyAuthActivity : FragmentActivity() { clientDataJsonB64 = b64Url(clientDataJson.toByteArray()) } - val assertion = runBlocking {+ val assertion = withContext(Dispatchers.IO) { WebAuthnAuthenticator.signAssertion(passkey, clientDataHash, repository) } val authenticatorData = assertion.authenticatorData@@ -316,7 +331,7 @@ class PasskeyAuthActivity : FragmentActivity() { } } - private fun handlePassword() {+ private suspend fun handlePassword() { val providerRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent) ?: run { Log.error(TAG, "No get credential request in intent") setResult(RESULT_CANCELED)@@ -328,7 +343,7 @@ class PasskeyAuthActivity : FragmentActivity() { setResult(RESULT_CANCELED) return }- val password = runBlocking { repository.getPasswordById(passwordId) }+ val password = withContext(Dispatchers.IO) { repository.getPasswordById(passwordId) } if (password == null) { Log.error(TAG, "Password not found for id=$passwordId") setResult(RESULT_CANCELED)@@ -344,7 +359,7 @@ class PasskeyAuthActivity : FragmentActivity() { setResult(RESULT_OK, result) } - private fun handleUnlock() {+ private suspend fun handleUnlock() { val request = PendingIntentHandler.retrieveBeginGetCredentialRequest(intent) if (request == null) { Log.error(TAG, "No BeginGetCredentialRequest in unlock intent")@@ -352,7 +367,7 @@ class PasskeyAuthActivity : FragmentActivity() { return } - val response = runBlocking {+ val response = withContext(Dispatchers.IO) { buildGetCredentialResponse( applicationContext, request.beginGetCredentialOptions,
passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillServiceDispatchTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillServiceDispatchTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillServiceDispatchTest.ktindex 426e3f4462..c642db5450 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillServiceDispatchTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillServiceDispatchTest.kt@@ -23,7 +23,6 @@ import org.robolectric.annotation.Config import java.lang.reflect.Proxy import kotlin.test.Test import kotlin.test.assertEquals-import kotlin.test.assertFailsWith import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue@@ -39,8 +38,8 @@ import kotlin.test.assertTrue * Callbacks are the framework callbacks backed by a recording AIDL proxy, * so "the service answered with no datasets" is asserted, not assumed. * Matching itself needs the SQLCipher vault (unavailable under- * Robolectric), so the fill/save paths that reach the vault surface its- * [UnsatisfiedLinkError] after the parser has run.+ * Robolectric), so the fill/save paths that reach the vault fail there+ * on IO and complete their callback with the no-fill / failure outcome. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [35])@@ -229,12 +228,18 @@ class AutofillServiceDispatchTest { assertNull(log.calls.single().second) } - @Test fun fillRequestWithPasswordFieldReachesVault() {+ @Test fun fillRequestWithPasswordFieldReachesVaultAnswersNullAsync() { DatabaseHelper(app).storePassphrase("vault-pw") val log = CallbackLog()- assertFailsWith<UnsatisfiedLinkError> {- service().onFillRequest(fillRequest(listOf(loginContext())), CancellationSignal(), fillCallback(log))+ service().onFillRequest(fillRequest(listOf(loginContext())), CancellationSignal(), fillCallback(log))+ // The vault read now runs on Dispatchers.IO (SQLCipher is unavailable+ // under Robolectric, so it fails there) and the callback must still+ // complete, with the same no-fill outcome as the old IllegalState path.+ val deadline = System.currentTimeMillis() + 5_000+ while (System.currentTimeMillis() < deadline && log.calls.isEmpty()) {+ Thread.sleep(10) }+ assertEquals(listOf("onSuccess" to null), log.calls.map { it.first to it.second }) } @Test fun saveRequestWithBlankCredentialsAnswersWithoutVault() {@@ -243,10 +248,16 @@ class AutofillServiceDispatchTest { assertEquals(listOf("onSuccess"), log.calls.map { it.first }) } - @Test fun saveRequestWithCredentialsReachesVault() {- assertFailsWith<UnsatisfiedLinkError> {- service().onSaveRequest(saveRequest(listOf(loginContext())), saveCallback(CallbackLog()))+ @Test fun saveRequestWithCredentialsReachesVaultFailsAsync() {+ val log = CallbackLog()+ service().onSaveRequest(saveRequest(listOf(loginContext())), saveCallback(log))+ // Async IO vault write: SQLCipher is unavailable under Robolectric,+ // so the callback completes with the vault-failure outcome.+ val deadline = System.currentTimeMillis() + 5_000+ while (System.currentTimeMillis() < deadline && log.calls.isEmpty()) {+ Thread.sleep(10) }+ assertEquals(listOf("onFailure"), log.calls.map { it.first }) } // ---- matchesContext / createPresentations (private helpers) ----
passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesExtraTest.ktindex a8eab47e5c..8f128e26ce 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesExtraTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesExtraTest.kt@@ -75,6 +75,11 @@ class ServicesExtraTest { override fun onError(e: GetCredentialException) = Unit }, )+ // Async IO callback: wait for the OutcomeReceiver to complete.+ val deadline = System.currentTimeMillis() + 5_000+ while (System.currentTimeMillis() < deadline && response == null) {+ Thread.sleep(10)+ } assertNotNull(response) assertEquals(0, response!!.credentialEntries.size) assertEquals(0, response!!.authenticationActions.size)@@ -191,6 +196,11 @@ class ServicesExtraTest { override fun onError(e: GetCredentialException) = Unit }, )+ // Async IO callback: wait for the OutcomeReceiver to complete.+ val deadline = System.currentTimeMillis() + 5_000+ while (System.currentTimeMillis() < deadline && response == null) {+ Thread.sleep(10)+ } assertNotNull(response) assertEquals(0, response!!.credentialEntries.size) }
passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyAuthUnlockTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyAuthUnlockTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyAuthUnlockTest.ktindex 5d8584c496..60233205f6 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyAuthUnlockTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyAuthUnlockTest.kt@@ -43,6 +43,14 @@ class PasskeyAuthUnlockTest { val controller = Robolectric.buildActivity(PasskeyAuthActivity::class.java, intent) controller.create() val activity = controller.get()+ // The unlock flow now builds its response on Dispatchers.IO and+ // finishes from lifecycleScope on main: idle the main looper until+ // the IO hop has resumed and finished the activity.+ val deadline = System.currentTimeMillis() + 5_000+ while (System.currentTimeMillis() < deadline && !activity.isFinishing) {+ shadowOf(android.os.Looper.getMainLooper()).idle()+ Thread.sleep(10)+ } assertTrue(activity.isFinishing) assertEquals(Activity.RESULT_OK, shadowOf(activity).resultCode) // The result intent carries a begin-get response (empty: no options were requested).