PasskeyAssertionTest.kt

8.0 KB · raw

1package com.peachpasswords.passkeys23import com.peachpasswords.vault.PasskeyData4import com.peachpasswords.vault.VaultEntry5import java.math.BigInteger6import java.security.MessageDigest7import java.security.KeyPairGenerator8import java.security.Signature9import java.security.interfaces.ECPrivateKey10import java.security.interfaces.ECPublicKey11import java.security.spec.ECGenParameterSpec12import java.util.Base6413import kotlinx.serialization.json.Json14import kotlinx.serialization.json.contentOrNull15import kotlinx.serialization.json.jsonObject16import kotlinx.serialization.json.jsonPrimitive17import org.junit.Assert.assertEquals18import org.junit.Assert.assertNotNull19import org.junit.Assert.assertTrue20import org.junit.Test21import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters22import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters23import org.bouncycastle.crypto.signers.Ed25519Signer2425class PasskeyAssertionTest {26    @Test fun builds_es256_assertion_and_increments_counter() {27        val keyPair = KeyPairGenerator.getInstance("EC").apply {28            initialize(ECGenParameterSpec("secp256r1"))29        }.generateKeyPair()30        val entry = passkeyEntry(keyPair.private as ECPrivateKey)3132        val result = PasskeyAssertion.build(33            entry = entry,34            requestJson = """{"challenge":"Y2hhbGxlbmdl","rpId":"example.com"}""",35            origin = "https://login.example.com",36        )3738        assertNotNull(result)39        result!!40        assertEquals(42, result.nextSignCount)41        val response = Json.parseToJsonElement(result.responseJson).jsonObject42        assertEquals("cred-1", response["id"]?.jsonPrimitive?.contentOrNull)43        val payload = response["response"]!!.jsonObject44        val clientDataBytes = b64Decode(payload["clientDataJSON"]!!.jsonPrimitive.content)45        val clientData = String(clientDataBytes, Charsets.UTF_8)46        val client = Json.parseToJsonElement(clientData).jsonObject47        assertEquals("webauthn.get", client["type"]?.jsonPrimitive?.contentOrNull)48        assertEquals("https://login.example.com", client["origin"]?.jsonPrimitive?.contentOrNull)49        val authData = b64Decode(payload["authenticatorData"]!!.jsonPrimitive.content)50        assertEquals(37, authData.size)51        assertEquals(42, ((authData[33].toInt() and 0xff) shl 24) or ((authData[34].toInt() and 0xff) shl 16) or ((authData[35].toInt() and 0xff) shl 8) or (authData[36].toInt() and 0xff))5253        val verifier = Signature.getInstance("SHA256withECDSA")54        verifier.initVerify(keyPair.public as ECPublicKey)55        verifier.update(authData + MessageDigest.getInstance("SHA-256").digest(clientDataBytes))56        assertTrue(verifier.verify(b64Decode(payload["signature"]!!.jsonPrimitive.content)))57    }5859    @Test fun builds_ed25519_assertion() {60        val seed = ByteArray(32) { (it + 1).toByte() }61        val privateKey = Ed25519PrivateKeyParameters(seed, 0)62        val publicKey = privateKey.generatePublicKey().encoded63        val entry = passkeyEntry(null).copy(64            passkey = passkeyEntry(null).passkey!!.copy(65                privateKeyJwk = """{"kty":"OKP","crv":"Ed25519","d":"${b64(seed)}","x":"${b64(publicKey)}"}""",66                algorithm = -8,67            ),68        )6970        val result = PasskeyAssertion.build(71            entry = entry,72            requestJson = """{"challenge":"Y2hhbGxlbmdl","rpId":"example.com"}""",73            origin = "https://example.com",74        )7576        assertNotNull(result)77        result!!78        val payload = Json.parseToJsonElement(result.responseJson).jsonObject["response"]!!.jsonObject79        val authData = b64Decode(payload["authenticatorData"]!!.jsonPrimitive.content)80        val clientData = b64Decode(payload["clientDataJSON"]!!.jsonPrimitive.content)81        val message = authData + MessageDigest.getInstance("SHA-256").digest(clientData)82        val signature = b64Decode(payload["signature"]!!.jsonPrimitive.content)83        assertEquals(64, signature.size)84        val verifier = Ed25519Signer()85        verifier.init(false, Ed25519PublicKeyParameters(publicKey, 0))86        verifier.update(message, 0, message.size)87        assertTrue(verifier.verifySignature(signature))88    }8990    @Test fun returns_null_for_missing_private_key() {91        val entry = passkeyEntry(null)92        assertEquals(null, PasskeyAssertion.build(entry, """{"challenge":"c","rpId":"example.com"}""", "https://example.com"))93    }9495    @Test fun assertion_flag_byte_reflects_backup_and_uv_state() {96        // Backup-eligible + UV performed → UP | UV | BE = 0x0d. AT (0x40) must97        // NOT be set on an assertion (it's registration-only). BS depends on98        // passkey.backupState which is false here.99        val keyPair = KeyPairGenerator.getInstance("EC").apply {100            initialize(ECGenParameterSpec("secp256r1"))101        }.generateKeyPair()102        val privKey = keyPair.private as ECPrivateKey103        val backupEntry = passkeyEntry(privKey).copy(104            passkey = passkeyEntry(privKey).passkey!!.copy(105                backupEligible = true,106                backupState = false,107            ),108        )109110        val verified = PasskeyAssertion.build(111            entry = backupEntry,112            requestJson = """{"challenge":"Y2hhbGxlbmdl","rpId":"example.com"}""",113            origin = "https://example.com",114            userVerified = true,115        )116        assertNotNull(verified)117        assertEquals(0x0d, extractFlags(verified!!.responseJson))118119        // Same entry, no UV performed: UP | BE only = 0x09.120        val unverified = PasskeyAssertion.build(121            entry = backupEntry,122            requestJson = """{"challenge":"Y2hhbGxlbmdl","rpId":"example.com"}""",123            origin = "https://example.com",124            userVerified = false,125        )126        assertEquals(0x09, extractFlags(unverified!!.responseJson))127128        // No backup eligibility, no UV: just UP = 0x01.129        val plainEntry = passkeyEntry(privKey).copy(130            passkey = passkeyEntry(privKey).passkey!!.copy(131                backupEligible = false,132                backupState = false,133            ),134        )135        val plain = PasskeyAssertion.build(136            entry = plainEntry,137            requestJson = """{"challenge":"Y2hhbGxlbmdl","rpId":"example.com"}""",138            origin = "https://example.com",139            userVerified = false,140        )141        assertEquals(0x01, extractFlags(plain!!.responseJson))142        // AT (0x40) is never set on assertions regardless of the other bits.143        assertEquals(0, 0x40 and extractFlags(plain.responseJson))144    }145146    private fun extractFlags(responseJson: String): Int {147        val payload = Json.parseToJsonElement(responseJson).jsonObject["response"]!!.jsonObject148        val authData = b64Decode(payload["authenticatorData"]!!.jsonPrimitive.content)149        return authData[32].toInt() and 0xff150    }151152    private fun passkeyEntry(privateKey: ECPrivateKey?) = VaultEntry(153        id = "entry-1",154        type = "passkey",155        title = "Example",156        passkey = PasskeyData(157            credentialId = "cred-1",158            publicKeyCose = "cose",159            privateKeyJwk = privateKey?.let(::privateJwk),160            rpId = "example.com",161            userHandle = "user-handle",162            userName = "june",163            userDisplayName = "June",164            algorithm = -7,165            signCount = 41,166        ),167        createdAt = 1,168        modifiedAt = 1,169    )170171    private fun privateJwk(key: ECPrivateKey): String =172        """{"kty":"EC","crv":"P-256","d":"${b64(key.s.toFixed32())}"}"""173174    private fun BigInteger.toFixed32(): ByteArray {175        val raw = toByteArray()176        val unsigned = if (raw.size > 1 && raw[0] == 0.toByte()) raw.copyOfRange(1, raw.size) else raw177        return ByteArray(32).also { unsigned.copyInto(it, 32 - unsigned.size) }178    }179180    private fun b64(bytes: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)181    private fun b64Decode(value: String): ByteArray =182        Base64.getUrlDecoder().decode(value.padEnd(((value.length + 3) / 4) * 4, '='))183}