Modern Apps git

← Modern-Apps.git

passwords: passkey PendingIntents could alias across entries

Commit
9b6c11572f2f1fc71a7bb2378254948b3d348eb3
Author
Vayun Mathur <[email protected]>
When
2026-11-23 16:51 UTC (12 days ago)
Parents
c2195f4
Real defect found while chasing the Vanadium crash:
PendingIntent identity ignores extras, and all entry
intents targeted PasskeyAuthActivity with bare request
codes from overlapping ranges (passkey id, password
id+100000, unlock 999999, create 0) - passkey #100002
and password #2 were the SAME PendingIntent, silently
rewritten by FLAG_UPDATE_CURRENT. Entries now carry
per-flow intent actions and tagged request-code ranges.
Also: rpId fallback via privileged origin, entry text
capped at 128 chars / 256 per type, and Log.dev records
caller + entry counts per get request.

On the crash itself: the 11:26 logcat shows Vanadium
SIGSEGV'd 82ms after PrepareGetRequestSession with no
bind to our service - the provider almost certainly
never ran. Separately, the phone's Settings.Secure
credential_service values still name the deleted
.util.PasskeyCredentialService (renamed to .platform),
so framework resolution names a nonexistent class -
re-selecting Passwords as preferred provider rewrites
it. Verified: 310 tests green, lint green.

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 c3b59b5d81..d2654db61b 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyCredentialService.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyCredentialService.kt@@ -49,11 +49,12 @@ class PasskeyCredentialService : CredentialProviderService() {      private fun buildUnlockResponse(): BeginGetCredentialResponse {         val intent = Intent(applicationContext, PasskeyAuthActivity::class.java).apply {+            action = ACTION_UNLOCK             putExtra(PasskeyAuthActivity.EXTRA_FLOW, PasskeyAuthActivity.FLOW_UNLOCK)         }         val pendingIntent = PendingIntent.getActivity(             applicationContext,-            REQUEST_CODE_UNLOCK,+            entryRequestCode(REQUEST_CODE_TAG_UNLOCK, REQUEST_CODE_UNLOCK.toLong()),             intent,             PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,         )@@ -89,12 +90,26 @@ class PasskeyCredentialService : CredentialProviderService() {             // 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 failure).+            // WebAuthn rpId is optional (defaults to the origin host); resolve+            // it here, where CallingAppInfo is available, so enumeration in+            // PasskeyEntries can still match when requestJson omits rpId.+            val fallbackRpId = runCatching {+                val info = request.callingAppInfo ?: return@runCatching null+                val origin = PasskeyUtils.getPrivilegedOrigin(info, applicationContext)+                origin?.let { android.net.Uri.parse(it).host }+            }.getOrNull()+            Log.dev(+                TAG,+                "onBeginGetCredentialRequest from ${request.callingAppInfo?.packageName}: " ++                    "${request.beginGetCredentialOptions.size} options, fallbackRpId=$fallbackRpId",+            )             val job = serviceScope.launch {                 try {                     val response = buildGetCredentialResponse(                         applicationContext,                         request.beginGetCredentialOptions,                         repository,+                        fallbackRpId,                     )                     deliverGet(callback) { response }                 } catch (expected: CancellationException) {@@ -153,11 +168,12 @@ class PasskeyCredentialService : CredentialProviderService() {         try {             if (request is BeginCreatePublicKeyCredentialRequest) {                 val intent = Intent(applicationContext, PasskeyAuthActivity::class.java).apply {+                    action = ACTION_CREATE                     putExtra(PasskeyAuthActivity.EXTRA_FLOW, PasskeyAuthActivity.FLOW_CREATE)                 }                 val pendingIntent = PendingIntent.getActivity(                     applicationContext,-                    0,+                    entryRequestCode(REQUEST_CODE_TAG_CREATE, 0),                     intent,                     PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,                 )
passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyEntries.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyEntries.kt b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyEntries.ktindex 50ad111e57..8b8f9f0b95 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyEntries.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyEntries.kt@@ -18,6 +18,41 @@ import org.json.JSONObject  private const val TAG = "PasskeyEntries" +/**+ * Entry text (username / display name) comes from imported vault rows and is+ * otherwise unbounded. Entries cross to Credential Manager as parcels/slices,+ * so cap every field: a multi-kilobyte imported name must not bloat (or, in+ * bulk, overflow) the response binder transaction.+ */+private const val MAX_ENTRY_TEXT_LENGTH = 128++/** Per-type entry ceiling for the same parcel-size reason as above. */+private const val MAX_ENTRIES_PER_TYPE = 256++// PendingIntent identity is (requestCode + Intent.filterEquals), and+// filterEquals ignores extras: every entry intent targets the same activity,+// so without distinct actions the only thing separating one entry's+// PendingIntent from another's is the request code. Give each flow its own+// action AND a request-code range tagged by flow, so a passkey entry can+// never FLAG_UPDATE_CURRENT-rewrite a password/unlock entry's extras (the+// ranges overlapped when codes were raw row ids / id+100000 / 999999).+internal const val ACTION_GET_PASSKEY = "com.vayunmathur.passwords.action.GET_PASSKEY"+internal const val ACTION_GET_PASSWORD = "com.vayunmathur.passwords.action.GET_PASSWORD"+internal const val ACTION_UNLOCK = "com.vayunmathur.passwords.action.UNLOCK"+internal const val ACTION_CREATE = "com.vayunmathur.passwords.action.CREATE"++private const val REQUEST_CODE_TAG_SHIFT = 28+internal const val REQUEST_CODE_TAG_PASSKEY = 1+internal const val REQUEST_CODE_TAG_PASSWORD = 2+internal const val REQUEST_CODE_TAG_UNLOCK = 3+internal const val REQUEST_CODE_TAG_CREATE = 4++internal fun entryRequestCode(tag: Int, id: Long): Int =+    (tag shl REQUEST_CODE_TAG_SHIFT) or (id.toInt() and ((1 shl REQUEST_CODE_TAG_SHIFT) - 1))++private fun entryText(value: String, fallback: String): String =+    value.take(MAX_ENTRY_TEXT_LENGTH).ifBlank { fallback.take(MAX_ENTRY_TEXT_LENGTH) }+ /**  * Builds the credential entries (passkeys + saved passwords) shown to the  * Credential Manager for a get-credential request. Shared by@@ -29,17 +64,26 @@ suspend fun buildGetCredentialResponse(     options: List<BeginGetCredentialOption>,     passkeyDao: PasskeyDao,     passwordDao: PasswordDao,+    fallbackRpId: String? = null, ): BeginGetCredentialResponse {     val responseBuilder = BeginGetCredentialResponse.Builder()     for (option in options) {         when (option) {             is BeginGetPublicKeyCredentialOption ->-                addPasskeyEntries(context, option, passkeyDao, responseBuilder)+                addPasskeyEntries(context, option, passkeyDao, responseBuilder, fallbackRpId)             is BeginGetPasswordOption ->                 addPasswordEntries(context, option, passwordDao, responseBuilder)         }     }-    return responseBuilder.build()+    val response = responseBuilder.build()+    // Attributability: a get ceremony that later goes wrong downstream must+    // be traceable to what this provider actually handed Credential Manager.+    Log.dev(+        TAG,+        "Built get response: ${response.credentialEntries.size} entries, " ++            "${response.authenticationActions.size} auth actions for ${options.size} options",+    )+    return response }  private suspend fun addPasskeyEntries(@@ -47,10 +91,14 @@ private suspend fun addPasskeyEntries(     option: BeginGetPublicKeyCredentialOption,     passkeyDao: PasskeyDao,     responseBuilder: BeginGetCredentialResponse.Builder,+    fallbackRpId: String?, ) {     // requestJson comes from the calling app; skip malformed options.     val request = runCatching { JSONObject(option.requestJson) }.getOrNull() ?: return-    val rpId = request.optString("rpId", "")+    // rpId is optional in WebAuthn (it defaults to the origin's host); a+    // caller that omits it must still be offered its credentials, so fall+    // back to the origin host the service resolved from CallingAppInfo.+    val rpId = request.optString("rpId", "").ifBlank { fallbackRpId.orEmpty() }     if (rpId.isBlank()) return     // An allowCredentials list constrains which credentials may be offered;     // offering the rest only lets the user pick one the RP will reject.@@ -61,35 +109,45 @@ private suspend fun addPasskeyEntries(     val passkeys = runCatching { passkeyDao.getByRpId(rpId) }         .onFailure { Log.error(TAG, "Listing passkeys for rpId=$rpId failed", it) }         .getOrDefault(emptyList())+    var added = 0     for (passkey in passkeys) {+        if (added >= MAX_ENTRIES_PER_TYPE) break         val allowed = allowedIds.isEmpty() ||             allowedIds.any { PasskeyUtils.credentialIdsMatch(passkey.credentialId, it) }         // A stored row with a blank id can never be asserted with; offering         // it would only hand the caller a dead entry.         if (allowed && passkey.credentialId.isNotBlank()) {-            runCatching {+            val built = runCatching {                 val intent = Intent(context, PasskeyAuthActivity::class.java).apply {+                    action = ACTION_GET_PASSKEY                     putExtra(PasskeyAuthActivity.EXTRA_FLOW, PasskeyAuthActivity.FLOW_GET)                     putExtra(PasskeyAuthActivity.EXTRA_CREDENTIAL_ID, passkey.credentialId)                 }                 val pendingIntent = PendingIntent.getActivity(                     context,-                    passkey.id.toInt(),+                    entryRequestCode(REQUEST_CODE_TAG_PASSKEY, passkey.id),                     intent,                     PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,                 )-                responseBuilder.addCredentialEntry(-                    PublicKeyCredentialEntry.Builder(-                        context,-                        // Entry builders reject blank usernames; fall back so-                        // an import with no name still lists.-                        passkey.userName.ifBlank { passkey.userDisplayName }-                            .ifBlank { passkey.rpId }.ifBlank { "Passkey" },-                        pendingIntent,-                        option,-                    ).build()-                )+                // No setIcon: the builder substitutes the androidx default+                // passkey icon, a *resource* Icon (package + res id parcel,+                // no bitmap), which is the smallest safe parcel shape.+                PublicKeyCredentialEntry.Builder(+                    context,+                    // Entry builders reject blank usernames; fall back so+                    // an import with no name still lists.+                    entryText(+                        passkey.userName.ifBlank { passkey.userDisplayName }.ifBlank { passkey.rpId },+                        "Passkey",+                    ),+                    pendingIntent,+                    option,+                ).build()             }.onFailure { Log.error(TAG, "Skipping unusable passkey entry id=${passkey.id}", it) }+            if (built.isSuccess) {+                responseBuilder.addCredentialEntry(built.getOrThrow())+                added+++            }         }     } }@@ -103,28 +161,33 @@ private suspend fun addPasswordEntries(     val passwords = runCatching { passwordDao.getAll() }         .onFailure { Log.error(TAG, "Listing passwords failed", it) }         .getOrDefault(emptyList())+    var added = 0     for (pass in passwords) {-        runCatching {+        if (added >= MAX_ENTRIES_PER_TYPE) break+        val built = runCatching {             val intent = Intent(context, PasskeyAuthActivity::class.java).apply {+                action = ACTION_GET_PASSWORD                 putExtra(PasskeyAuthActivity.EXTRA_FLOW, PasskeyAuthActivity.FLOW_PASSWORD)                 putExtra(PasskeyCredentialService.EXTRA_PASSWORD_ID, pass.id)             }             val pendingIntent = PendingIntent.getActivity(                 context,-                (pass.id + 100000).toInt(),+                entryRequestCode(REQUEST_CODE_TAG_PASSWORD, pass.id),                 intent,                 PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,             )-            responseBuilder.addCredentialEntry(-                PasswordCredentialEntry.Builder(-                    context,-                    pass.username.ifBlank { pass.name }.ifBlank { "Password" },-                    pendingIntent,-                    option,-                ).setDisplayName(pass.name.ifBlank { null })-                    .build()-            )+            PasswordCredentialEntry.Builder(+                context,+                entryText(pass.username.ifBlank { pass.name }, "Password"),+                pendingIntent,+                option,+            ).setDisplayName(pass.name.take(MAX_ENTRY_TEXT_LENGTH).ifBlank { null })+                .build()         }.onFailure { Log.error(TAG, "Skipping unusable password entry id=${pass.id}", it) }+        if (built.isSuccess) {+            responseBuilder.addCredentialEntry(built.getOrThrow())+            added+++        }     } } @@ -133,10 +196,12 @@ suspend fun buildGetCredentialResponse(     context: Context,     options: List<BeginGetCredentialOption>,     repository: PasswordRepository,+    fallbackRpId: String? = null, ): BeginGetCredentialResponse =     buildGetCredentialResponse(         context,         options,+        fallbackRpId = fallbackRpId,         passkeyDao = object : PasskeyDao() {             override fun getAllFlow(): kotlinx.coroutines.flow.Flow<List<com.vayunmathur.passwords.data.Passkey>> =                 repository.passkeys
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 27b453bbc4..8c0e648d86 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt@@ -257,11 +257,17 @@ class PasskeyAuthActivity : FragmentActivity() {             return         } +        val fallbackRpId = runCatching {+            val info = request.callingAppInfo ?: return@runCatching null+            val origin = PasskeyUtils.getPrivilegedOrigin(info, applicationContext)+            origin?.let { android.net.Uri.parse(it).host }+        }.getOrNull()         val response = withContext(Dispatchers.IO) {             buildGetCredentialResponse(                 applicationContext,                 request.beginGetCredentialOptions,                 repository,+                fallbackRpId,             )         } 
passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.ktindex 279b05d669..a933ba626a 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.kt@@ -12,11 +12,14 @@ import com.vayunmathur.passwords.data.PasswordDao import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.runBlocking+import androidx.credentials.provider.PublicKeyCredentialEntry import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue  @RunWith(RobolectricTestRunner::class) @Config(sdk = [35])@@ -108,6 +111,70 @@ class PasskeyEntriesTest {         assertEquals(0, nonMatching.credentialEntries.size)     } +    @Test fun missingRpIdFallsBackToOriginHost() = runBlocking {+        // rpId is optional in WebAuthn; with the origin-host fallback the+        // stored credential for that host is still offered.+        val response = buildGetCredentialResponse(+            ctx,+            listOf(BeginGetPublicKeyCredentialOption(Bundle(), "req-norp", """{"challenge":"Y2g"}""")),+            FakePasskeyDao(),+            FakePasswordDao(),+            fallbackRpId = "example.com",+        )+        assertEquals(1, response.credentialEntries.size)++        val noFallback = buildGetCredentialResponse(+            ctx,+            listOf(BeginGetPublicKeyCredentialOption(Bundle(), "req-norp2", """{"challenge":"Y2g"}""")),+            FakePasskeyDao(),+            FakePasswordDao(),+        )+        assertEquals(0, noFallback.credentialEntries.size)+    }++    @Test fun entryTextIsCappedForParcelSafety() = runBlocking {+        val longNamed = Passkey(+            id = 7, rpId = "example.com", userName = "u".repeat(5000),+            credentialId = "cred-7", syncId = "pk-7",+        )+        val dao = object : PasskeyDao() {+            override fun getAllFlow(): Flow<List<Passkey>> = flowOf(listOf(longNamed))+            override suspend fun getAll(): List<Passkey> = listOf(longNamed)+            override suspend fun getByRpId(rpId: String): List<Passkey> = listOf(longNamed)+            override suspend fun getByCredentialId(credentialId: String): Passkey? = null+            override suspend fun getBySyncId(syncId: String): Passkey? = null+            override suspend fun getUpdatedSince(since: Long): List<Passkey> = emptyList()+            override suspend fun upsertRaw(passkey: Passkey): Long = passkey.id+            override suspend fun delete(passkey: Passkey): Int = 0+            override suspend fun deleteBySyncId(syncId: String): Int = 0+            override suspend fun deleteAll() = Unit+        }+        val response = buildGetCredentialResponse(+            ctx,+            listOf(BeginGetPublicKeyCredentialOption(Bundle(), "req-long", """{"rpId":"example.com","challenge":"Y2g"}""")),+            dao,+            FakePasswordDao(),+        )+        assertEquals(1, response.credentialEntries.size)+        val entry = response.credentialEntries.single() as PublicKeyCredentialEntry+        assertTrue(entry.username.length <= 128, "username was ${entry.username.length} chars")+    }++    @Test fun entryRequestCodesCannotCollideAcrossFlows() {+        // Old scheme: passkey code = id, password code = id + 100000, so+        // passkey 100002 and password 2 shared a PendingIntent identity+        // (same target activity, extras ignored by filterEquals).+        assertNotEquals(+            entryRequestCode(REQUEST_CODE_TAG_PASSKEY, 100002),+            entryRequestCode(REQUEST_CODE_TAG_PASSWORD, 2),+        )+        assertNotEquals(+            entryRequestCode(REQUEST_CODE_TAG_UNLOCK, 999999),+            entryRequestCode(REQUEST_CODE_TAG_PASSKEY, 999999),+        )+        assertNotEquals(ACTION_GET_PASSKEY, ACTION_GET_PASSWORD)+    }+     @Test fun noOptionsYieldEmptyResponse() = runBlocking {         val response = buildGetCredentialResponse(ctx, emptyList(), FakePasskeyDao(), FakePasswordDao())         assertEquals(0, response.credentialEntries.size)