passwords: fix passkeys failing outside listed browsers
- Commit
6542bc816c44ed41d113aa792a5a4a1aec49ef18- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-19 18:25 UTC (16 days ago)
- Parents
cc942ec
Four provenance-checked breaks in the Credential Manager path (the CTAP path already handled the last two correctly): - getPrivilegedOrigin caught IllegalArgumentException, but CallingAppInfo.getOrigin throws IllegalStateException for an unlisted caller (verified in the androidx.credentials AAR), which escaped as a silent RESULT_CANCELED - every create/get from an unlisted browser or rotated cert failed. - The native-app android origin used colon-hex (the assetlinks fingerprint form); WebAuthn expects base64url(SHA-256 cert). Every native-app ceremony was rejected on origin mismatch. - GET offered every credential for the RP, ignoring allowCredentials; CREATE ignored pubKeyCredParams (stored an ES256 credential RPs then rejected) and excludeCredentials (silently replacing an existing credential). New unit tests fail pre-fix (exact exception, 1-vs-0 entries, wrong origin) and pass now: :passwords:testDevUnitTest 436/436. A real RP create/get ceremony still needs a device.
Diff
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 6ffd776122..eee3dc7028 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyEntries.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyEntries.kt@@ -32,9 +32,17 @@ suspend fun buildGetCredentialResponse( when (option) { is BeginGetPublicKeyCredentialOption -> { // requestJson comes from the calling app; skip malformed options.- val rpId = runCatching { JSONObject(option.requestJson).optString("rpId", "") }.getOrNull() ?: continue+ val request = runCatching { JSONObject(option.requestJson) }.getOrNull() ?: continue+ val rpId = request.optString("rpId", "") if (rpId.isBlank()) continue+ // An allowCredentials list constrains which credentials may be+ // offered; offering the rest only lets the user pick one the+ // relying party will reject.+ val allowedIds = PasskeyUtils.credentialDescriptorIds(request, "allowCredentials") for (passkey in passkeyDao.getByRpId(rpId)) {+ if (allowedIds.isNotEmpty() &&+ allowedIds.none { PasskeyUtils.credentialIdsMatch(passkey.credentialId, it) }+ ) continue val intent = Intent(context, PasskeyAuthActivity::class.java).apply { putExtra(PasskeyAuthActivity.EXTRA_FLOW, PasskeyAuthActivity.FLOW_GET) putExtra(PasskeyAuthActivity.EXTRA_CREDENTIAL_ID, passkey.credentialId)
passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyUtils.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyUtils.kt b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyUtils.ktindex f67b0a7c56..fc3f80df14 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyUtils.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyUtils.kt@@ -3,6 +3,7 @@ package com.vayunmathur.passwords.platform import android.content.Context import com.vayunmathur.library.log.Log import androidx.credentials.provider.CallingAppInfo+import org.json.JSONObject import java.security.MessageDigest import java.security.SecureRandom import kotlin.io.encoding.Base64@@ -56,6 +57,54 @@ object PasskeyUtils { return id } + // -- Request-descriptor helpers --+ //+ // Credential ids cross the Credential Manager boundary as base64url strings. A relying+ // party may spell the same id with padding, so compare decoded bytes, not raw strings.++ /** True when [storedId] and [requestedId] name the same credential bytes. */+ fun credentialIdsMatch(storedId: String, requestedId: String): Boolean {+ if (storedId == requestedId) return true+ if (storedId.isEmpty() || requestedId.isEmpty()) return false+ return runCatching {+ decodeB64Url(storedId).contentEquals(decodeB64Url(requestedId))+ }.getOrDefault(false)+ }++ /**+ * The `public-key` credential ids named by a `allowCredentials` / `excludeCredentials`+ * array in a request JSON object; empty when the array is absent.+ */+ fun credentialDescriptorIds(request: JSONObject, key: String): List<String> {+ val descriptors = request.optJSONArray(key) ?: return emptyList()+ return buildList {+ for (i in 0 until descriptors.length()) {+ val item = descriptors.optJSONObject(i) ?: continue+ val type = item.optString("type", "")+ if (type.isNotEmpty() && type != "public-key") continue+ val id = item.optString("id", "")+ if (id.isNotEmpty()) add(id)+ }+ }+ }++ /**+ * True when this authenticator can satisfy a creation request: it only makes ES256+ * (alg -7) keys, so a `pubKeyCredParams` list that does not offer -7 cannot be served.+ * An absent or empty list imposes no constraint.+ */+ fun supportsEs256(request: JSONObject): Boolean {+ val params = request.optJSONArray("pubKeyCredParams") ?: return true+ if (params.length() == 0) return true+ for (i in 0 until params.length()) {+ val item = params.optJSONObject(i) ?: continue+ val type = item.optString("type", "")+ if (type.isNotEmpty() && type != "public-key") continue+ if (item.has("alg") && item.optInt("alg") == -7) return true+ }+ return false+ }+ // -- Origin resolution -- fun getPrivilegedOrigin(callingAppInfo: CallingAppInfo, context: Context): String? {@@ -70,21 +119,34 @@ object PasskeyUtils { } catch (expected: IllegalArgumentException) { Log.dev(TAG, "No privileged browser match: ${expected.message}") null+ } catch (expected: IllegalStateException) {+ // CallingAppInfo.getOrigin() throws IllegalStateException (not+ // IllegalArgumentException) when the system populated an origin but+ // the caller is not on the allow-list, e.g. a browser this app does+ // not list. That caller is simply not privileged: fall back to its+ // android: origin instead of aborting the whole ceremony.+ Log.dev(TAG, "Caller is not a privileged browser: ${expected.message}")+ null } } - @OptIn(ExperimentalStdlibApi::class) fun getAndroidOrigin(callingAppInfo: CallingAppInfo): String {- val fingerprint = callingAppInfo.signingInfo+ val signer = callingAppInfo.signingInfoCompat .apkContentsSigners .firstOrNull() ?.toByteArray()- ?.let { MessageDigest.getInstance("SHA-256").digest(it) }- ?.toHexString(HexFormat.UpperCase)- ?: "unknown"- return "android:apk-key-hash:$fingerprint"+ return if (signer != null) androidOriginFromSigner(signer) else "android:apk-key-hash:unknown" } + /**+ * WebAuthn's android facet origin for a signing certificate:+ * `android:apk-key-hash:` + base64url(SHA-256 of the certificate). The+ * colon-separated hex form is the assetlinks / privileged-allow-list+ * fingerprint, and a relying party expecting the facet origin rejects it.+ */+ fun androidOriginFromSigner(signerBytes: ByteArray): String =+ "android:apk-key-hash:" + encodeB64Url(MessageDigest.getInstance("SHA-256").digest(signerBytes))+ // -- AuthenticatorData builder -- fun buildAuthenticatorData(
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 26aad18556..4cc050b452 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt@@ -109,6 +109,29 @@ class PasskeyAuthActivity : FragmentActivity() { val userDisplayName = user.optString("displayName", userName) val challenge = json.getString("challenge") + // This authenticator only makes ES256 keys. Honouring a request that+ // does not offer alg -7 would persist a credential the relying party+ // then rejects; refuse before anything is generated or stored.+ if (!PasskeyUtils.supportsEs256(json)) {+ Log.error(TAG, "Create request offers no ES256 in pubKeyCredParams")+ setResult(RESULT_CANCELED)+ return+ }+ // excludeCredentials names credentials the relying party already has:+ // creating (and, via the shared helper, silently replacing) one of+ // them must not happen.+ val excludedIds = PasskeyUtils.credentialDescriptorIds(json, "excludeCredentials")+ if (excludedIds.isNotEmpty()) {+ val excluded = runBlocking { repository.getPasskeysByRpId(rpId) }.any { stored ->+ excludedIds.any { PasskeyUtils.credentialIdsMatch(stored.credentialId, it) }+ }+ if (excluded) {+ Log.error(TAG, "Create request excludes an existing credential for rpId=$rpId")+ setResult(RESULT_CANCELED)+ return+ }+ }+ // Privileged browsers provide clientDataHash directly val callingAppInfo = request.callingAppInfo val privilegedOrigin = PasskeyUtils.getPrivilegedOrigin(callingAppInfo, applicationContext)@@ -206,6 +229,17 @@ class PasskeyAuthActivity : FragmentActivity() { val json = JSONObject(publicKeyOption.requestJson) val challenge = json.getString("challenge") + // Entry enumeration already filters by allowCredentials, but never+ // sign for a credential this request did not allow.+ val allowedIds = PasskeyUtils.credentialDescriptorIds(json, "allowCredentials")+ if (allowedIds.isNotEmpty() &&+ allowedIds.none { PasskeyUtils.credentialIdsMatch(passkey.credentialId, it) }+ ) {+ Log.error(TAG, "Selected credential is not in allowCredentials for rpId=${passkey.rpId}")+ setResult(RESULT_CANCELED)+ return+ }+ val callingAppInfo = providerRequest.callingAppInfo val privilegedOrigin = PasskeyUtils.getPrivilegedOrigin(callingAppInfo, applicationContext) val isPrivileged = privilegedOrigin != null@@ -270,10 +304,15 @@ class PasskeyAuthActivity : FragmentActivity() { private fun readPrivilegedHash(option: GetPublicKeyCredentialOption): ByteArray? { return try {- option.clientDataHash+ // An empty hash is no hash: signing over it cannot verify, so let+ // the caller fall back to hashing its own clientDataJSON.+ option.clientDataHash?.takeIf { it.isNotEmpty() } } catch (expected: GetCredentialUnknownException) { Log.dev(TAG, "privileged clientDataHash unavailable", expected) null+ } catch (expected: IllegalStateException) {+ Log.dev(TAG, "privileged clientDataHash unavailable", expected)+ null } }
passwords/src/test/java/com/vayunmathur/passwords/platform/CallingAppInfoFactory.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/CallingAppInfoFactory.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/CallingAppInfoFactory.ktindex 40920210d2..7d15910c54 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/platform/CallingAppInfoFactory.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/CallingAppInfoFactory.kt@@ -40,4 +40,7 @@ object CallingAppInfoFactory { fun callingAppInfo(packageName: String): CallingAppInfo = CallingAppInfo(packageName, signingInfo())++ fun callingAppInfo(packageName: String, origin: String): CallingAppInfo =+ CallingAppInfo(packageName, signingInfo(), origin) }
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 a18aea068d..4cc48098d9 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.kt@@ -90,6 +90,24 @@ class PasskeyEntriesTest { assertEquals(0, otherRp.credentialEntries.size) } + @Test fun publicKeyOptionHonoursAllowCredentials() = runBlocking {+ val matching = buildGetCredentialResponse(+ ctx,+ listOf(BeginGetPublicKeyCredentialOption(Bundle(), "req-allow", """{"rpId":"example.com","challenge":"Y2hhbGxlbmdl","allowCredentials":[{"type":"public-key","id":"cred-1"}]}""")),+ FakePasskeyDao(),+ FakePasswordDao(),+ )+ assertEquals(1, matching.credentialEntries.size)++ val nonMatching = buildGetCredentialResponse(+ ctx,+ listOf(BeginGetPublicKeyCredentialOption(Bundle(), "req-allow-other", """{"rpId":"example.com","challenge":"Y2hhbGxlbmdl","allowCredentials":[{"type":"public-key","id":"b3RoZXItY3JlZA"}]}""")),+ FakePasskeyDao(),+ FakePasswordDao(),+ )+ assertEquals(0, nonMatching.credentialEntries.size)+ }+ @Test fun noOptionsYieldEmptyResponse() = runBlocking { val response = buildGetCredentialResponse(ctx, emptyList(), FakePasskeyDao(), FakePasswordDao()) assertEquals(0, response.credentialEntries.size)
passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsExtraTest.ktindex 8c031f2410..d845a10c44 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsExtraTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsExtraTest.kt@@ -58,4 +58,36 @@ class PasskeyUtilsExtraTest { val info = CallingAppInfoFactory.callingAppInfo("com.example.app") assertNull(PasskeyUtils.getPrivilegedOrigin(info, ctx)) }++ @Test fun privilegedOriginReturnsNullForUnlistedCallerWithOrigin() {+ // CallingAppInfo.getOrigin() throws IllegalStateException (not+ // IllegalArgumentException) when the system populated an origin but+ // the caller is not on the bundled allow-list, e.g. an unlisted+ // browser. That must resolve to "not privileged", not escape and+ // cancel the whole create/get flow.+ val info = CallingAppInfoFactory.callingAppInfo("com.example.app", "https://example.com")+ assertNull(PasskeyUtils.getPrivilegedOrigin(info, ctx))+ }++ @Test fun requestDescriptorHelpers() {+ val create = org.json.JSONObject(+ """{"pubKeyCredParams":[{"type":"public-key","alg":-257},{"type":"public-key","alg":-7}],""" ++ """"excludeCredentials":[{"type":"public-key","id":"Y3JlZC0x"},{"type":"other","id":"eA"}]}""",+ )+ assertEquals(true, PasskeyUtils.supportsEs256(create))+ assertEquals(listOf("Y3JlZC0x"), PasskeyUtils.credentialDescriptorIds(create, "excludeCredentials"))+ assertEquals(+ false,+ PasskeyUtils.supportsEs256(org.json.JSONObject("""{"pubKeyCredParams":[{"type":"public-key","alg":-257}]}""")),+ )+ assertEquals(true, PasskeyUtils.supportsEs256(org.json.JSONObject("""{}""")))+ assertEquals(+ emptyList<String>(),+ PasskeyUtils.credentialDescriptorIds(org.json.JSONObject("""{}"""), "allowCredentials"),+ )+ // Same credential bytes spelled with base64url padding still match.+ val stored = PasskeyUtils.encodeB64Url(ByteArray(16) { it.toByte() })+ assertEquals(true, PasskeyUtils.credentialIdsMatch(stored, stored + "=="))+ assertEquals(false, PasskeyUtils.credentialIdsMatch(stored, "b3RoZXItY3JlZA"))+ } }
passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsTest.ktindex 17999a43fe..bfda99bb54 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsTest.kt@@ -38,6 +38,18 @@ class PasskeyUtilsTest { assertEquals(0x40, data[32].toInt() and 0xFF) } + @Test fun androidOriginIsBase64UrlSha256OfSigningCert() {+ // WebAuthn android facet: "android:apk-key-hash:" + base64url(SHA-256+ // of the signing certificate), not the colon-hex fingerprint form+ // used in assetlinks / the privileged allow-list.+ val cert = byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8)+ val digest = java.security.MessageDigest.getInstance("SHA-256").digest(cert)+ assertEquals(+ "android:apk-key-hash:" + PasskeyUtils.encodeB64Url(digest),+ PasskeyUtils.androidOriginFromSigner(cert),+ )+ }+ @Test fun aaguidIs16Bytes() { assertEquals(16, PasskeyUtils.SAME_DEVICE_AAGUID.size) }