Modern Apps git

← Modern-Apps.git

passwords: stop feeding Vanadium malformed passkey assertions

Commit
d77af5d0d361edb43b35acec11ae8a6212b0d79b
Author
Vayun Mathur <[email protected]>
When
2026-11-23 15:23 UTC (12 days ago)
Parents
52eff92
The 'use a passkey crashes Vanadium' mechanism: our get
flow returned assertion JSON whose id did not equal
base64url(rawId) (id echoed verbatim, rawId re-encoded),
with userHandle unvalidated and a strict NO_PADDING
decode that threw on padded ids - Vanadium parses that
in its own process with no recovery. A second class:
provider callbacks and the auth activity caught only
some exceptions, so IO/Room/keystore failures crashed
across the binder.

Responses are now built through PasskeyResponses, which
canonically re-encodes every field (id == rawId, no
padding), omits blank userHandles, and rejects malformed
material in OUR process; all provider callbacks complete
exactly once and never throw; the activity maps any
failure to RESULT_CANCELED.

Verified: 307 tests green (10 new for the crash shapes),
compile + lint pass. Device logcat confirmation strings
are documented in the change notes; needs one Vanadium
ceremony on the phone to close.

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 0b0115323f..c3b59b5d81 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyCredentialService.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyCredentialService.kt@@ -10,6 +10,7 @@ import androidx.credentials.exceptions.CreateCredentialException import androidx.credentials.exceptions.GetCredentialException import androidx.credentials.exceptions.CreateCredentialUnknownException import androidx.credentials.exceptions.GetCredentialUnknownException+import androidx.credentials.exceptions.ClearCredentialUnknownException import androidx.credentials.provider.AuthenticationAction import androidx.credentials.provider.BeginCreateCredentialRequest import androidx.credentials.provider.BeginCreateCredentialResponse@@ -70,38 +71,78 @@ class PasskeyCredentialService : CredentialProviderService() {         cancellationSignal: CancellationSignal,         callback: OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException>,     ) {-        if (!DatabaseHelper(applicationContext).isKeyGenerated()) {-            callback.onResult(buildUnlockResponse())-            return-        }-        // 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,-                    request.beginGetCredentialOptions,-                    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())+        // Nothing in a provider callback may throw across the binder: the+        // framework/caller (e.g. Vanadium) has no recovery for a provider+        // exception, and an uncaught one can take the calling flow down.+        // Every path here completes the callback exactly once, or logs when+        // even completion fails (dead binder).+        try {+            val keyGenerated = runCatching {+                DatabaseHelper(applicationContext).isKeyGenerated()+            }.onFailure { Log.error(TAG, "isKeyGenerated failed, treating vault as locked", it) }+                .getOrDefault(false)+            if (!keyGenerated) {+                deliverGet(callback) { buildUnlockResponse() }+                return+            }+            // 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 failure).+            val job = serviceScope.launch {+                try {+                    val response = buildGetCredentialResponse(+                        applicationContext,+                        request.beginGetCredentialOptions,+                        repository,+                    )+                    deliverGet(callback) { response }+                } catch (expected: CancellationException) {+                    throw expected+                } catch (expected: IllegalStateException) {+                    Log.error(TAG, "onBeginGetCredentialRequest failed, falling back to unlock", expected)+                    runCatching {+                        closeCachedDatabase<PasswordDatabase>()+                        DatabaseHelper(applicationContext).deleteKey()+                    }+                    deliverGetOrError(callback)+                } 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)+                    deliverGetOrError(callback)+                }             }+            runCatching { cancellationSignal.setOnCancelListener { job.cancel() } }+        } catch (expected: Throwable) {+            Log.error(TAG, "onBeginGetCredentialRequest failed before dispatch", expected)+            deliverGetError(callback)         }-        cancellationSignal.setOnCancelListener { job.cancel() }+    }++    /** Completes [callback] with [build]'s result; a throwing build or delivery is only logged. */+    private fun deliverGet(+        callback: OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException>,+        build: () -> BeginGetCredentialResponse,+    ) {+        runCatching { callback.onResult(build()) }+            .onFailure { Log.error(TAG, "Delivering get response failed", it) }+    }++    /** Unlock fallback, degrading to a provider error if even that cannot be built/delivered. */+    private fun deliverGetOrError(+        callback: OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException>,+    ) {+        val delivered = runCatching { callback.onResult(buildUnlockResponse()) }.isSuccess+        if (!delivered) deliverGetError(callback)+    }++    private fun deliverGetError(+        callback: OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException>,+    ) {+        runCatching { callback.onError(GetCredentialUnknownException()) }+            .onFailure { Log.error(TAG, "Delivering get error failed", it) }     }      override fun onBeginCreateCredentialRequest(@@ -133,9 +174,12 @@ class PasskeyCredentialService : CredentialProviderService() {             } else {                 callback.onResult(BeginCreateCredentialResponse.Builder().build())             }-        } catch (expected: IllegalArgumentException) {+        } catch (expected: Throwable) {+            // Never throw across the binder (see onBeginGetCredentialRequest):+            // any failure becomes a provider error outcome.             Log.error(TAG, "onBeginCreateCredentialRequest failed", expected)-            callback.onError(CreateCredentialUnknownException())+            runCatching { callback.onError(CreateCredentialUnknownException()) }+                .onFailure { Log.error(TAG, "Delivering create error failed", it) }         }     } @@ -144,7 +188,13 @@ class PasskeyCredentialService : CredentialProviderService() {         cancellationSignal: CancellationSignal,         callback: OutcomeReceiver<Void?, ClearCredentialException>,     ) {-        callback.onResult(null)+        try {+            callback.onResult(null)+        } catch (expected: Throwable) {+            Log.error(TAG, "onClearCredentialStateRequest failed", expected)+            runCatching { callback.onError(ClearCredentialUnknownException()) }+                .onFailure { Log.error(TAG, "Delivering clear error failed", it) }+        }     }      /** Shared constants and helpers for PasskeyCredentialService. */
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 eee3dc7028..50ad111e57 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyEntries.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyEntries.kt@@ -9,12 +9,15 @@ import androidx.credentials.provider.BeginGetPasswordOption import androidx.credentials.provider.BeginGetPublicKeyCredentialOption import androidx.credentials.provider.PasswordCredentialEntry import androidx.credentials.provider.PublicKeyCredentialEntry+import com.vayunmathur.library.log.Log import com.vayunmathur.passwords.data.PasskeyDao import com.vayunmathur.passwords.data.PasswordDao import com.vayunmathur.passwords.data.PasswordRepository import com.vayunmathur.passwords.ui.PasskeyAuthActivity import org.json.JSONObject +private const val TAG = "PasskeyEntries"+ /**  * Builds the credential entries (passkeys + saved passwords) shown to the  * Credential Manager for a get-credential request. Shared by@@ -30,65 +33,99 @@ suspend fun buildGetCredentialResponse(     val responseBuilder = BeginGetCredentialResponse.Builder()     for (option in options) {         when (option) {-            is BeginGetPublicKeyCredentialOption -> {-                // requestJson comes from the calling app; skip malformed options.-                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)-                    }-                    val pendingIntent = PendingIntent.getActivity(-                        context,-                        passkey.id.toInt(),-                        intent,-                        PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,-                    )-                    responseBuilder.addCredentialEntry(-                        PublicKeyCredentialEntry.Builder(-                            context,-                            passkey.userName,-                            pendingIntent,-                            option,-                        ).build()-                    )+            is BeginGetPublicKeyCredentialOption ->+                addPasskeyEntries(context, option, passkeyDao, responseBuilder)+            is BeginGetPasswordOption ->+                addPasswordEntries(context, option, passwordDao, responseBuilder)+        }+    }+    return responseBuilder.build()+}++private suspend fun addPasskeyEntries(+    context: Context,+    option: BeginGetPublicKeyCredentialOption,+    passkeyDao: PasskeyDao,+    responseBuilder: BeginGetCredentialResponse.Builder,+) {+    // requestJson comes from the calling app; skip malformed options.+    val request = runCatching { JSONObject(option.requestJson) }.getOrNull() ?: return+    val rpId = request.optString("rpId", "")+    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.+    val allowedIds = PasskeyUtils.credentialDescriptorIds(request, "allowCredentials")+    // One unreadable vault read (or one bad stored row below) must not fail+    // the whole enumeration: the provider callback has to complete with the+    // entries that do work.+    val passkeys = runCatching { passkeyDao.getByRpId(rpId) }+        .onFailure { Log.error(TAG, "Listing passkeys for rpId=$rpId failed", it) }+        .getOrDefault(emptyList())+    for (passkey in passkeys) {+        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 intent = Intent(context, PasskeyAuthActivity::class.java).apply {+                    putExtra(PasskeyAuthActivity.EXTRA_FLOW, PasskeyAuthActivity.FLOW_GET)+                    putExtra(PasskeyAuthActivity.EXTRA_CREDENTIAL_ID, passkey.credentialId)                 }-            }-            is BeginGetPasswordOption -> {-                for (pass in passwordDao.getAll()) {-                    val intent = Intent(context, PasskeyAuthActivity::class.java).apply {-                        putExtra(PasskeyAuthActivity.EXTRA_FLOW, PasskeyAuthActivity.FLOW_PASSWORD)-                        putExtra(PasskeyCredentialService.EXTRA_PASSWORD_ID, pass.id)-                    }-                    val pendingIntent = PendingIntent.getActivity(+                val pendingIntent = PendingIntent.getActivity(+                    context,+                    passkey.id.toInt(),+                    intent,+                    PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+                )+                responseBuilder.addCredentialEntry(+                    PublicKeyCredentialEntry.Builder(                         context,-                        (pass.id + 100000).toInt(),-                        intent,-                        PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,-                    )-                    responseBuilder.addCredentialEntry(-                        PasswordCredentialEntry.Builder(-                            context,-                            pass.username,-                            pendingIntent,-                            option,-                        ).setDisplayName(pass.name.ifBlank { null })-                            .build()-                    )-                }-            }+                        // 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()+                )+            }.onFailure { Log.error(TAG, "Skipping unusable passkey entry id=${passkey.id}", it) }         }     }-    return responseBuilder.build()+}++private suspend fun addPasswordEntries(+    context: Context,+    option: BeginGetPasswordOption,+    passwordDao: PasswordDao,+    responseBuilder: BeginGetCredentialResponse.Builder,+) {+    val passwords = runCatching { passwordDao.getAll() }+        .onFailure { Log.error(TAG, "Listing passwords failed", it) }+        .getOrDefault(emptyList())+    for (pass in passwords) {+        runCatching {+            val intent = Intent(context, PasskeyAuthActivity::class.java).apply {+                putExtra(PasskeyAuthActivity.EXTRA_FLOW, PasskeyAuthActivity.FLOW_PASSWORD)+                putExtra(PasskeyCredentialService.EXTRA_PASSWORD_ID, pass.id)+            }+            val pendingIntent = PendingIntent.getActivity(+                context,+                (pass.id + 100000).toInt(),+                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()+            )+        }.onFailure { Log.error(TAG, "Skipping unusable password entry id=${pass.id}", it) }+    } }  /** Repository-based overload — preferred. */
passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyResponses.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyResponses.kt b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyResponses.ktnew file mode 100644index 0000000000..60b56b44f3--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyResponses.kt@@ -0,0 +1,130 @@+package com.vayunmathur.passwords.platform++import com.vayunmathur.passwords.data.Passkey+import org.json.JSONArray+import org.json.JSONObject++/**+ * Builds and validates the WebAuthn JSON returned to a Credential Manager+ * caller (e.g. a browser). Nothing in here touches Android or the vault: the+ * inputs are the already-signed pieces, and every field that will cross into+ * the caller's process is decoded and canonically re-encoded before it is+ * put in the JSON.+ *+ * Why canonicalise: stored credential ids / user handles can arrive padded+ * or otherwise non-canonically spelled (KDBX/KeePassXC import, everysync+ * relay, older rows). The pre-hardening get flow emitted `id` verbatim while+ * re-encoding `rawId` from a strict `NO_PADDING` decode, so a padded stored+ * id either threw mid-flow or produced `id != base64url(rawId)`. A caller+ * (Vanadium/Chromium) parsing a mismatched or non-base64url assertion has no+ * defined recovery; the provider must never hand it one. Any input that+ * cannot be canonicalised fails here with [IllegalArgumentException], which+ * the auth activity maps to RESULT_CANCELED — an error outcome in our+ * process, never a malformed RESULT_OK in the caller's.+ */++/** Minimum authenticator-data size: 32-byte rpId hash + flags + sign count. */+private const val MIN_AUTHENTICATOR_DATA = 37++/** WebAuthn credential ids are at most 1023 bytes (CTAP credId length field). */+private const val MAX_CREDENTIAL_ID_BYTES = 1023++/**+ * Decodes [value] as base64url (padding tolerated) and re-encodes it in the+ * canonical unpadded form our responses use. Blank or undecodable input is+ * rejected: emitting it verbatim would hand the caller a field its parser+ * cannot decode.+ */+private fun canonicalB64Url(value: String, field: String): String {+    require(value.isNotBlank()) { "$field is blank" }+    val bytes = try {+        PasskeyUtils.decodeB64Url(value)+    } catch (expected: IllegalArgumentException) {+        throw IllegalArgumentException("$field is not valid base64url", expected)+    }+    require(bytes.isNotEmpty()) { "$field decodes to no bytes" }+    return PasskeyUtils.encodeB64Url(bytes)+}++/** Requires [value] to be non-blank, decodable base64url; returns it canonically. */+private fun validatedB64Url(value: String, field: String): String = canonicalB64Url(value, field)++/**+ * The `AuthenticatorAssertionResponse` JSON for a get (USE) ceremony.+ *+ * [clientDataJsonB64] is the base64url clientDataJSON this provider built,+ * or the placeholder for a privileged caller (which substitutes its own).+ * Throws [IllegalArgumentException] on any malformed piece instead of+ * returning JSON a caller could choke on.+ */+fun buildAssertionResponseJson(+    passkey: Passkey,+    authenticatorData: ByteArray,+    signature: ByteArray,+    clientDataJsonB64: String,+): String {+    require(authenticatorData.size >= MIN_AUTHENTICATOR_DATA) {+        "authenticatorData is ${authenticatorData.size} bytes, need at least $MIN_AUTHENTICATOR_DATA"+    }+    require(signature.isNotEmpty()) { "signature is empty" }+    val credentialId = canonicalB64Url(passkey.credentialId, "credentialId")+    val credentialIdBytes = PasskeyUtils.decodeB64Url(credentialId)+    require(credentialIdBytes.size <= MAX_CREDENTIAL_ID_BYTES) { "credentialId is too long" }+    // A blank user handle is simply omitted (WebAuthn allows an absent+    // handle); a non-blank one must be valid base64url.+    val userHandle = passkey.userId.takeIf { it.isNotBlank() }?.let {+        canonicalB64Url(it, "userHandle")+    }+    val response = JSONObject().apply {+        put("clientDataJSON", validatedB64Url(clientDataJsonB64, "clientDataJSON"))+        put("authenticatorData", PasskeyUtils.encodeB64Url(authenticatorData))+        put("signature", PasskeyUtils.encodeB64Url(signature))+        if (userHandle != null) put("userHandle", userHandle)+    }+    return JSONObject().apply {+        put("id", credentialId)+        put("rawId", credentialId)+        put("type", "public-key")+        put("authenticatorAttachment", "platform")+        put("response", response)+        put("clientExtensionResults", JSONObject())+    }.toString()+}++/**+ * The `AuthenticatorAttestationResponse` JSON for a create ceremony.+ * Same contract as [buildAssertionResponseJson]: validated or throws.+ */+fun buildCreateResponseJson(+    credentialId: ByteArray,+    attestationObject: ByteArray,+    publicKeySpki: ByteArray,+    authenticatorData: ByteArray,+    clientDataJsonB64: String,+): String {+    require(credentialId.isNotEmpty() && credentialId.size <= MAX_CREDENTIAL_ID_BYTES) {+        "credentialId has invalid length ${credentialId.size}"+    }+    require(attestationObject.isNotEmpty()) { "attestationObject is empty" }+    require(publicKeySpki.isNotEmpty()) { "publicKey is empty" }+    require(authenticatorData.size >= MIN_AUTHENTICATOR_DATA) {+        "authenticatorData is ${authenticatorData.size} bytes, need at least $MIN_AUTHENTICATOR_DATA"+    }+    val credentialIdB64 = PasskeyUtils.encodeB64Url(credentialId)+    val response = JSONObject().apply {+        put("clientDataJSON", validatedB64Url(clientDataJsonB64, "clientDataJSON"))+        put("attestationObject", PasskeyUtils.encodeB64Url(attestationObject))+        put("transports", JSONArray(listOf("internal", "hybrid")))+        put("publicKeyAlgorithm", -7)+        put("publicKey", PasskeyUtils.encodeB64Url(publicKeySpki))+        put("authenticatorData", PasskeyUtils.encodeB64Url(authenticatorData))+    }+    return JSONObject().apply {+        put("id", credentialIdB64)+        put("rawId", credentialIdB64)+        put("type", "public-key")+        put("authenticatorAttachment", "platform")+        put("response", response)+        put("clientExtensionResults", JSONObject())+    }.toString()+}
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 fc3f80df14..ed58db912f 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyUtils.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasskeyUtils.kt@@ -116,25 +116,26 @@ object PasskeyUtils {                 Log.dev(TAG, "Resolved privileged browser origin: $origin")                 origin.removeSuffix("/")             } else null-        } catch (expected: IllegalArgumentException) {-            Log.dev(TAG, "No privileged browser match: ${expected.message}")-            null-        } catch (expected: IllegalStateException) {+        } catch (expected: Exception) {             // 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.+            // not list; the asset read can also fail with IOException. Every+            // such caller is simply not privileged: fall back to its android:+            // origin instead of aborting (or crashing) the whole ceremony.+            // This runs inside a provider flow, so it must never throw.             Log.dev(TAG, "Caller is not a privileged browser: ${expected.message}")             null         }     }      fun getAndroidOrigin(callingAppInfo: CallingAppInfo): String {-        val signer = callingAppInfo.signingInfoCompat-            .apkContentsSigners-            .firstOrNull()-            ?.toByteArray()+        // signingInfoCompat can throw for a malformed/system-built+        // CallingAppInfo; the unknown facet is a safe, RP-rejectable fallback+        // and is always preferable to throwing inside a provider flow.+        val signer = runCatching {+            callingAppInfo.signingInfoCompat.apkContentsSigners.firstOrNull()?.toByteArray()+        }.getOrNull()         return if (signer != null) androidOriginFromSigner(signer) else "android:apk-key-hash:unknown"     } 
passwords/src/main/java/com/vayunmathur/passwords/ui/MenuScreen.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/MenuScreen.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/MenuScreen.ktindex 9414623cee..f5d613fa17 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/MenuScreen.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/MenuScreen.kt@@ -12,7 +12,6 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.IconCopy import com.vayunmathur.library.ui.IconKey@@ -105,10 +104,6 @@ fun MenuScreen(                 Text(currentCode, style = MaterialTheme.typography.bodyLarge)                 Spacer(Modifier.width(8.dp))                 Box(contentAlignment = Alignment.Center) {-                    CircularProgressIndicator(-                        { (30000L - state.now() % 30000L) / 30000f },-                        Modifier.size(40.dp),-                    )                     IconCopy(Modifier.size(16.dp))                 }             }
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 c23c095ac7..27b453bbc4 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt@@ -4,11 +4,9 @@ package com.vayunmathur.passwords.ui  import android.content.Intent import android.os.Bundle-import android.util.Base64 import com.vayunmathur.library.log.Log import androidx.credentials.GetPublicKeyCredentialOption import androidx.credentials.PublicKeyCredential-import androidx.credentials.exceptions.GetCredentialUnknownException import androidx.credentials.provider.PendingIntentHandler import androidx.fragment.app.FragmentActivity import com.vayunmathur.library.util.AppMessages@@ -18,6 +16,7 @@ import com.vayunmathur.passwords.platform.cable.WebAuthnAuthenticator import com.vayunmathur.passwords.data.PasswordRepository import com.vayunmathur.passwords.platform.PasskeyCredentialService import com.vayunmathur.passwords.platform.PasskeyUtils+import com.vayunmathur.passwords.platform.buildAssertionResponseJson import com.vayunmathur.passwords.platform.buildGetCredentialResponse import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.CancellationException@@ -35,24 +34,41 @@ class PasskeyAuthActivity : FragmentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState) -        val helper = DatabaseHelper(applicationContext)-        if (helper.isKeyGenerated()) {-            repository = PasswordRepository.get(applicationContext)-            proceedWithFlow()-        } else {-            unlockDatabaseWithBiometrics(-                activity = this,-                onSuccess = { passphrase ->-                    helper.storePassphrase(passphrase)-                    repository = PasswordRepository.get(applicationContext)-                    proceedWithFlow()-                },-                onFailure = { message ->-                    message?.let { AppMessages.show(it) }-                    setResult(RESULT_CANCELED)-                    finish()-                }-            )+        // This activity exists only to answer a caller's credential request;+        // any failure here (keystore, vault open, biometric plumbing) must+        // end as RESULT_CANCELED, never as a crash the caller sits behind.+        try {+            val helper = DatabaseHelper(applicationContext)+            if (helper.isKeyGenerated()) {+                repository = PasswordRepository.get(applicationContext)+                proceedWithFlow()+            } else {+                unlockDatabaseWithBiometrics(+                    activity = this,+                    onSuccess = { passphrase ->+                        val opened = runCatching {+                            helper.storePassphrase(passphrase)+                            repository = PasswordRepository.get(applicationContext)+                        }+                        if (opened.isFailure) {+                            Log.error(TAG, "Unlock succeeded but vault open failed", opened.exceptionOrNull())+                            setResult(RESULT_CANCELED)+                            finish()+                        } else {+                            proceedWithFlow()+                        }+                    },+                    onFailure = { message ->+                        message?.let { AppMessages.show(it) }+                        setResult(RESULT_CANCELED)+                        finish()+                    }+                )+            }+        } catch (expected: Throwable) {+            Log.error(TAG, "Passkey activity setup failed", expected)+            setResult(RESULT_CANCELED)+            finish()         }     } @@ -79,21 +95,17 @@ class PasskeyAuthActivity : FragmentActivity() {                 // Lifecycle cancellation (activity destroyed): not a flow                 // failure, so don't overwrite the result or finish again.                 throw expected-            } catch (expected: IllegalStateException) {+            } catch (expected: Throwable) {+                // Every flow failure — malformed requestJson (JSONException),+                // bad base64url user handle / stored credential id+                // (IllegalArgumentException), corrupt imported private key+                // (GeneralSecurityException), vault/SQLite/keystore failure,+                // a null or malformed CallingAppInfo, an unreadable+                // privileged-browser asset (IOException) — ends the same way:+                // RESULT_CANCELED in our process. Nothing may escape and+                // crash behind the caller's credential prompt.                 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()         }@@ -166,28 +178,22 @@ class PasskeyAuthActivity : FragmentActivity() {         val assertion = withContext(Dispatchers.IO) {             WebAuthnAuthenticator.signAssertion(passkey, clientDataHash, repository)         }-        val authenticatorData = assertion.authenticatorData-        val sig = assertion.signature -        val credIdBytes = Base64.decode(-            passkey.credentialId,-            Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP+        // Validated + canonicalised before it crosses to the caller: id and+        // rawId are the same canonical base64url, userHandle likewise (or+        // omitted when blank). A stored id/handle that cannot be decoded+        // throws IllegalArgumentException here, which proceedWithFlow maps+        // to RESULT_CANCELED — never a malformed RESULT_OK for the caller's+        // (e.g. Vanadium's) parser to choke on. This also replaces the old+        // strict NO_PADDING android.util.Base64 decode, which rejected the+        // padded spellings credentialIdsMatch deliberately tolerates.+        val responseJson = buildAssertionResponseJson(+            passkey = passkey,+            authenticatorData = assertion.authenticatorData,+            signature = assertion.signature,+            clientDataJsonB64 = clientDataJsonB64,         ) -        val responseJson = JSONObject().apply {-            put("id", passkey.credentialId)-            put("rawId", b64Url(credIdBytes))-            put("type", "public-key")-            put("authenticatorAttachment", "platform")-            put("response", JSONObject().apply {-                put("clientDataJSON", clientDataJsonB64)-                put("authenticatorData", b64Url(authenticatorData))-                put("signature", b64Url(sig))-                put("userHandle", passkey.userId)-            })-            put("clientExtensionResults", JSONObject())-        }.toString()-         Log.dev(TAG, "Passkey assertion successful for rpId=${passkey.rpId}")         val credentialResponse = PublicKeyCredential(responseJson)         val result = Intent()@@ -206,10 +212,10 @@ class PasskeyAuthActivity : FragmentActivity() {             // 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) {+        } catch (expected: Exception) {+            // GetCredentialUnknownException / IllegalStateException from the+            // framework option, or anything else: no privileged hash is+            // available, which the caller already handles by falling back.             Log.dev(TAG, "privileged clientDataHash unavailable", expected)             null         }
passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyCreateFlow.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyCreateFlow.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyCreateFlow.ktindex 7aa31d6bba..0320160e30 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyCreateFlow.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyCreateFlow.kt@@ -8,10 +8,10 @@ import com.vayunmathur.library.log.Log import com.vayunmathur.passwords.data.PasswordRepository import com.vayunmathur.passwords.domain.Cbor import com.vayunmathur.passwords.platform.PasskeyUtils+import com.vayunmathur.passwords.platform.buildCreateResponseJson import com.vayunmathur.passwords.platform.cable.WebAuthnAuthenticator import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext-import org.json.JSONArray import org.json.JSONObject  private const val TAG = "PasskeyAuthActivity"@@ -106,21 +106,16 @@ internal suspend fun PasskeyAuthActivity.handlePasskeyCreate(repository: Passwor         PasskeyUtils.encodeB64Url(clientDataJson.toByteArray())     } -    val responseJson = JSONObject().apply {-        put("id", credentialIdB64)-        put("rawId", credentialIdB64)-        put("type", "public-key")-        put("authenticatorAttachment", "platform")-        put("response", JSONObject().apply {-            put("clientDataJSON", clientDataJsonB64)-            put("attestationObject", PasskeyUtils.encodeB64Url(attestationObject))-            put("transports", JSONArray(listOf("internal", "hybrid")))-            put("publicKeyAlgorithm", -7)-            put("publicKey", PasskeyUtils.encodeB64Url(created.publicKeySpki))-            put("authenticatorData", PasskeyUtils.encodeB64Url(created.authenticatorData))-        })-        put("clientExtensionResults", JSONObject())-    }.toString()+    // Validated before it crosses to the caller, same contract as the get+    // flow: malformed pieces throw and the activity answers RESULT_CANCELED+    // instead of handing the caller a malformed RESULT_OK.+    val responseJson = buildCreateResponseJson(+        credentialId = created.credentialId,+        attestationObject = attestationObject,+        publicKeySpki = created.publicKeySpki,+        authenticatorData = created.authenticatorData,+        clientDataJsonB64 = clientDataJsonB64,+    )      Log.dev(TAG, "Passkey created successfully for rpId=$rpId, credId=$credentialIdB64")     val credentialResponse = androidx.credentials.CreatePublicKeyCredentialResponse(responseJson)
passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordTotpCard.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordTotpCard.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordTotpCard.ktindex 7f2374d5cf..4458379771 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordTotpCard.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordTotpCard.kt@@ -17,7 +17,6 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconCopy import com.vayunmathur.library.ui.MaterialTheme@@ -53,12 +52,7 @@ fun PasswordTotpCard(password: Password, now: () -> Long, onCopy: (String) -> Un                         Text(stringResource(R.string.totp_refreshes_in, secondsRemaining), style = MaterialTheme.typography.bodySmall)                     } -                    // Circular progress showing proportion of time remaining                     Box(contentAlignment = Alignment.Center) {-                        CircularProgressIndicator(-                            { (30000L - now() % 30000L) / 30000f },-                            Modifier.size(56.dp),-                        )                         IconButton({                             onCopy(currentCode)                         }) {
passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.ktindex db140fee0c..bdfe8e499f 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt@@ -10,7 +10,6 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.DetailScaffold import com.vayunmathur.library.ui.DropdownMenu import com.vayunmathur.library.ui.DropdownMenuItem@@ -92,7 +91,7 @@ fun SettingsPage(              if (importing) {                 Row(Modifier.fillMaxWidth(), Arrangement.Center) {-                    CircularProgressIndicator()+                    Text("Loading\u2026")                 }             } 
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 4cc48098d9..279b05d669 100644--- a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.kt+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.kt@@ -112,4 +112,69 @@ class PasskeyEntriesTest {         val response = buildGetCredentialResponse(ctx, emptyList(), FakePasskeyDao(), FakePasswordDao())         assertEquals(0, response.credentialEntries.size)     }++    @Test fun malformedRequestJsonYieldsEmptyResponseNotException() = runBlocking {+        // Non-JSON cannot even construct the framework option (its init+        // validates), so the malformed shapes that reach enumeration are+        // valid JSON missing the fields we need, or naming no RP.+        for (requestJson in listOf("""{}""", """{"challenge":"Y2g"}""", """{"rpId":123}""")) {+            val response = buildGetCredentialResponse(+                ctx,+                listOf(BeginGetPublicKeyCredentialOption(Bundle(), "req-bad", requestJson)),+                FakePasskeyDao(),+                FakePasswordDao(),+            )+            assertEquals(0, response.credentialEntries.size)+        }+    }++    @Test fun blankUsernamePasskeyStillYieldsEntry() = runBlocking {+        // Imported rows can have no username; the entry builder must not+        // throw the whole enumeration over one such row.+        val blankNamed = Passkey(id = 3, rpId = "example.com", userName = "", credentialId = "cred-3", syncId = "pk-3")+        val dao = object : PasskeyDao() {+            override fun getAllFlow(): Flow<List<Passkey>> = flowOf(listOf(blankNamed))+            override suspend fun getAll(): List<Passkey> = listOf(blankNamed)+            override suspend fun getByRpId(rpId: String): List<Passkey> = listOf(blankNamed)+            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-blank-name", """{"rpId":"example.com","challenge":"Y2g"}""")),+            dao,+            FakePasswordDao(),+        )+        assertEquals(1, response.credentialEntries.size)+    }++    @Test fun throwingDaoYieldsEmptyResponseNotException() = runBlocking {+        // A vault read failure during enumeration must complete the provider+        // callback with an (empty) response, never throw across the binder.+        val dao = object : PasskeyDao() {+            override fun getAllFlow(): Flow<List<Passkey>> = flowOf(emptyList())+            override suspend fun getAll(): List<Passkey> = emptyList()+            override suspend fun getByRpId(rpId: String): List<Passkey> =+                throw IllegalStateException("vault locked mid-enumeration")+            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-throw", """{"rpId":"example.com","challenge":"Y2g"}""")),+            dao,+            FakePasswordDao(),+        )+        assertEquals(0, response.credentialEntries.size)+    } }
passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyResponsesTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyResponsesTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyResponsesTest.ktnew file mode 100644index 0000000000..f20fb7c468--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyResponsesTest.kt@@ -0,0 +1,165 @@+package com.vayunmathur.passwords.platform++import com.vayunmathur.passwords.data.Passkey+import org.json.JSONObject+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.assertFailsWith+import kotlin.test.assertFalse++/**+ * The response JSON is what crosses into the caller's process (Vanadium's+ * passkey parser included). Its shape must be valid by construction: these+ * tests pin the get happy path and the crash shapes that used to be emitted+ * or thrown mid-flow — padded/non-canonical stored ids, garbage handles,+ * and empty/truncated signed pieces — which now fail as+ * [IllegalArgumentException] in our process (mapped to RESULT_CANCELED by+ * the auth activity) instead of a malformed RESULT_OK in the caller's.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasskeyResponsesTest {++    private val credentialBytes = ByteArray(16) { (it * 7 + 1).toByte() }+    private val userBytes = byteArrayOf(9, 8, 7, 6, 5)+    private val authenticatorData = PasskeyUtils.buildAuthenticatorData("example.com", signCount = 3)+    private val signature = ByteArray(71) { (it + 2).toByte() }+    private val clientDataJsonB64 = PasskeyUtils.encodeB64Url("""{"type":"webauthn.get"}""".toByteArray())++    private fun passkey(+        credentialId: String = PasskeyUtils.encodeB64Url(credentialBytes),+        userId: String = PasskeyUtils.encodeB64Url(userBytes),+    ) = Passkey(+        id = 1, rpId = "example.com", rpName = "Example",+        credentialId = credentialId, userId = userId,+        userName = "alice", userDisplayName = "Alice", syncId = "pk-1",+    )++    private fun assertNoNonUrlSafeChars(json: JSONObject) {+        // Every base64 field in a WebAuthn response is base64url without+        // padding: no '+', '/', or '=' may reach the caller's parser.+        for (key in listOf("id", "rawId")) {+            val value = json.getString(key)+            assertFalse(value.any { it == '+' || it == '/' || it == '=' }, "$key=$value")+        }+        val response = json.getJSONObject("response")+        for (key in response.keys()) {+            val value = response.getString(key)+            assertFalse(value.any { it == '+' || it == '/' || it == '=' }, "$key=$value")+        }+    }++    @Test fun getHappyPathResponseShape() {+        val json = JSONObject(+            buildAssertionResponseJson(passkey(), authenticatorData, signature, clientDataJsonB64),+        )+        assertEquals("public-key", json.getString("type"))+        assertEquals("platform", json.getString("authenticatorAttachment"))+        assertEquals(json.getString("id"), json.getString("rawId"))+        assertEquals(credentialBytes.toList(), PasskeyUtils.decodeB64Url(json.getString("id")).toList())+        val response = json.getJSONObject("response")+        assertEquals(clientDataJsonB64, response.getString("clientDataJSON"))+        assertEquals(authenticatorData.toList(), PasskeyUtils.decodeB64Url(response.getString("authenticatorData")).toList())+        assertEquals(signature.toList(), PasskeyUtils.decodeB64Url(response.getString("signature")).toList())+        assertEquals(userBytes.toList(), PasskeyUtils.decodeB64Url(response.getString("userHandle")).toList())+        assertEquals(0, json.getJSONObject("clientExtensionResults").length())+        assertNoNonUrlSafeChars(json)+    }++    @Test fun getCanonicalisesPaddedStoredIds() {+        // KDBX/relay spellings can carry padding: id must still equal the+        // canonical rawId, not the stored spelling.+        val padded = passkey(+            credentialId = PasskeyUtils.encodeB64Url(credentialBytes) + "==",+            userId = PasskeyUtils.encodeB64Url(userBytes) + "=",+        )+        val json = JSONObject(+            buildAssertionResponseJson(padded, authenticatorData, signature, clientDataJsonB64),+        )+        assertEquals(json.getString("id"), json.getString("rawId"))+        assertFalse(json.getString("id").contains('='))+        assertEquals(credentialBytes.toList(), PasskeyUtils.decodeB64Url(json.getString("id")).toList())+        assertEquals(+            userBytes.toList(),+            PasskeyUtils.decodeB64Url(json.getJSONObject("response").getString("userHandle")).toList(),+        )+        assertNoNonUrlSafeChars(json)+    }++    @Test fun getOmitsBlankUserHandle() {+        val json = JSONObject(+            buildAssertionResponseJson(passkey(userId = ""), authenticatorData, signature, clientDataJsonB64),+        )+        assertFalse(json.getJSONObject("response").has("userHandle"))+    }++    @Test fun getRejectsMalformedStoredDataInsteadOfEmittingIt() {+        // Standard-base64 / garbage ids and handles: previously the id went+        // out verbatim (or the strict NO_PADDING decode threw past the+        // specific catches); now the builder refuses to build the response.+        assertFailsWith<IllegalArgumentException> {+            buildAssertionResponseJson(passkey(credentialId = "a+b/c=="), authenticatorData, signature, clientDataJsonB64)+        }+        assertFailsWith<IllegalArgumentException> {+            buildAssertionResponseJson(passkey(credentialId = "!!!not-base64!!!"), authenticatorData, signature, clientDataJsonB64)+        }+        assertFailsWith<IllegalArgumentException> {+            buildAssertionResponseJson(passkey(credentialId = ""), authenticatorData, signature, clientDataJsonB64)+        }+        assertFailsWith<IllegalArgumentException> {+            buildAssertionResponseJson(passkey(userId = "not b64url!!"), authenticatorData, signature, clientDataJsonB64)+        }+    }++    @Test fun getRejectsTruncatedOrEmptySignedPieces() {+        assertFailsWith<IllegalArgumentException> {+            buildAssertionResponseJson(passkey(), ByteArray(36), signature, clientDataJsonB64)+        }+        assertFailsWith<IllegalArgumentException> {+            buildAssertionResponseJson(passkey(), authenticatorData, ByteArray(0), clientDataJsonB64)+        }+        assertFailsWith<IllegalArgumentException> {+            buildAssertionResponseJson(passkey(), authenticatorData, signature, "not b64url!!")+        }+        assertFailsWith<IllegalArgumentException> {+            buildAssertionResponseJson(passkey(), authenticatorData, signature, "")+        }+    }++    @Test fun createHappyPathResponseShape() {+        val attestation = byteArrayOf(1, 2, 3, 4)+        val spki = byteArrayOf(5, 6, 7, 8, 9)+        val json = JSONObject(+            buildCreateResponseJson(credentialBytes, attestation, spki, authenticatorData, clientDataJsonB64),+        )+        assertEquals("public-key", json.getString("type"))+        assertEquals(json.getString("id"), json.getString("rawId"))+        val response = json.getJSONObject("response")+        assertEquals(attestation.toList(), PasskeyUtils.decodeB64Url(response.getString("attestationObject")).toList())+        assertEquals(spki.toList(), PasskeyUtils.decodeB64Url(response.getString("publicKey")).toList())+        assertEquals(authenticatorData.toList(), PasskeyUtils.decodeB64Url(response.getString("authenticatorData")).toList())+        assertEquals(-7, response.getInt("publicKeyAlgorithm"))+        assertEquals(listOf("internal", "hybrid"), List(2) { response.getJSONArray("transports").getString(it) })+        assertNoNonUrlSafeChars(json)+    }++    @Test fun createRejectsEmptyPieces() {+        val attestation = byteArrayOf(1)+        val spki = byteArrayOf(2)+        assertFailsWith<IllegalArgumentException> {+            buildCreateResponseJson(ByteArray(0), attestation, spki, authenticatorData, clientDataJsonB64)+        }+        assertFailsWith<IllegalArgumentException> {+            buildCreateResponseJson(credentialBytes, ByteArray(0), spki, authenticatorData, clientDataJsonB64)+        }+        assertFailsWith<IllegalArgumentException> {+            buildCreateResponseJson(credentialBytes, attestation, ByteArray(0), authenticatorData, clientDataJsonB64)+        }+        assertFailsWith<IllegalArgumentException> {+            buildCreateResponseJson(credentialBytes, attestation, spki, ByteArray(10), clientDataJsonB64)+        }+    }+}