From 3a85bd5d0fbe9764c58cf7a913a2787d0d077ba5 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 09:41:17 -0300 Subject: [PATCH 1/5] fix: refuse pubky auth requests for another pubky Co-Authored-By: Claude Fable 5.2 --- .../java/to/bitkit/models/PubkyAuthRequest.kt | 46 +++++++- .../java/to/bitkit/repositories/PubkyRepo.kt | 10 ++ .../profile/PubkyAuthApprovalViewModel.kt | 14 +++ .../bitkit/ui/utils/PubkyAuthErrorMessage.kt | 10 ++ app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../to/bitkit/models/PubkyAuthRequestTest.kt | 108 ++++++++++++++++++ .../to/bitkit/repositories/PubkyRepoTest.kt | 54 +++++++++ .../profile/PubkyAuthApprovalViewModelTest.kt | 60 ++++++++++ changelog.d/next/1761.fixed.md | 1 + journeys/README.md | 1 + journeys/pubky-auth/README.md | 4 + journeys/pubky-auth/signin-expected-pubky.xml | 29 +++++ 27 files changed, 352 insertions(+), 1 deletion(-) create mode 100644 changelog.d/next/1761.fixed.md create mode 100644 journeys/pubky-auth/signin-expected-pubky.xml diff --git a/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt b/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt index e897b5cc61..9bd8889d04 100644 --- a/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt +++ b/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt @@ -99,6 +99,7 @@ sealed class PubkyAuthRequestError(cause: Throwable? = null) : AppError(cause = data object DuplicateBitkitClaim : PubkyAuthRequestError() data class UnsupportedBitkitClaim(val value: String) : PubkyAuthRequestError() data object InvalidBitkitClaimCapabilities : PubkyAuthRequestError() + data class SignerMismatch(val expectedSigner: String) : PubkyAuthRequestError() } @Immutable @@ -130,6 +131,7 @@ data class PubkyAuthRequest( val homeserverPublicKey: String? = null, val signupToken: String? = null, val authorizationUrl: String? = rawUrl, + val expectedSigner: String? = null, ) { val isSignup: Boolean get() = isSignupUrl(rawUrl) @@ -140,6 +142,46 @@ data class PubkyAuthRequest( fun requiresIdentityCreation(hasIdentity: Boolean): Boolean = isSignup && (!isGrantSignup || !hasIdentity) companion object { + /** Query parameter naming the only pubky that may approve a grant sign-in. */ + private const val EXPECTED_SIGNER_PARAMETER = "spk" + + /** A 32-byte key in canonical z-base-32: 52 symbols, the last one carrying a single bit. */ + private val CANONICAL_Z32_KEY = Regex("[ybndrfg8ejkmcpqxot1uwisza345h769]{51}[yo]") + + /** Length of a z-base-32 key carrying the `pubky` prefix. */ + private const val PREFIXED_KEY_LENGTH = 57 + + /** + * Reads the pubky a sign-in request must be approved with. Absent is fine; a repeated value or anything other + * than a bare canonical z-base-32 key makes the request invalid, as in the Pubky SDK parser for `signin_grant`. + * Only signup requests ignore the parameter, so a sign-in this parser reads differently from the SDK is still + * held to it. + */ + fun parseExpectedSigner(rawUrl: String): Result = runCatching { + val uri = URI(rawUrl) + if (uri.isSignupRequest()) return@runCatching null + val values = uri.rawQuery.orEmpty() + .split("&") + .filter { it.isNotEmpty() } + .map { it.split("=", limit = 2) } + .filter { decodeQueryComponent(it.first()) == EXPECTED_SIGNER_PARAMETER } + .map { decodeQueryComponent(it.getOrElse(1) { "" }) } + require(values.size <= 1) { "Duplicate Pubky auth parameter: $EXPECTED_SIGNER_PARAMETER" } + values.singleOrNull()?.also { + require(CANONICAL_Z32_KEY.matches(it)) { "Malformed Pubky auth parameter: $EXPECTED_SIGNER_PARAMETER" } + } + }.fold( + onSuccess = { Result.success(it) }, + onFailure = { Result.failure(PubkyAuthRequestError.InvalidUrl(it)) }, + ) + + /** Whether [publicKey], bare or with the `pubky` prefix, may approve a request naming [expectedSigner]. */ + fun isExpectedSigner(expectedSigner: String?, publicKey: String): Boolean { + if (expectedSigner == null) return true + val isPrefixed = publicKey.length == PREFIXED_KEY_LENGTH && publicKey.startsWith("pubky") + return expectedSigner == if (isPrefixed) publicKey.removePrefix("pubky") else publicKey + } + fun parse( rawUrl: String, clientId: String, @@ -148,7 +190,8 @@ data class PubkyAuthRequest( homeserverPublicKey: String? = null, signupToken: String? = null, authorizationUrl: String? = rawUrl, - ): Result = parseBitkitClaim(rawUrl, capabilities).map { bitkitClaim -> + ): Result = parseBitkitClaim(rawUrl, capabilities).mapCatching { bitkitClaim -> + val expectedSigner = parseExpectedSigner(rawUrl).getOrThrow() val permissions = parseCapabilities(capabilities) PubkyAuthRequest( rawUrl = rawUrl, @@ -161,6 +204,7 @@ data class PubkyAuthRequest( homeserverPublicKey = homeserverPublicKey, signupToken = signupToken, authorizationUrl = authorizationUrl, + expectedSigner = expectedSigner, ) } diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 1efe4815aa..16570d852f 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -2198,6 +2198,7 @@ class PubkyRepo @Inject constructor( val secretKeyHex = requireNotNull(activeSecretKeyHex()) { "No secret key available — use Ring to manage authorizations" } + requireExpectedSigner(authUrl, secretKeyHex) pubkyService.approveAuth(authUrl, expectedCapabilities, approvedClientId, secretKeyHex) } } @@ -2215,6 +2216,7 @@ class PubkyRepo @Inject constructor( val secretKeyHex = requireNotNull(activeSecretKeyHex()) { "No secret key available — use Ring to manage authorizations" } + requireExpectedSigner(authUrl, secretKeyHex) pubkyService.approveAuthWithCompanionClaim( authUrl = authUrl, expectedCapabilities = PubkyAuthClaim.REQUIRED_CAPABILITIES, @@ -2229,6 +2231,14 @@ class PubkyRepo @Inject constructor( } } + private suspend fun requireExpectedSigner(authUrl: String, secretKeyHex: String) { + val expectedSigner = PubkyAuthRequest.parseExpectedSigner(authUrl).getOrThrow() ?: return + val signer = pubkyService.publicKeyFromSecret(secretKeyHex) + if (!PubkyAuthRequest.isExpectedSigner(expectedSigner, signer)) { + throw PubkyAuthRequestError.SignerMismatch(expectedSigner) + } + } + // endregion // region Wake diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt index e02ad06ebd..5a65016f74 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt @@ -114,6 +114,20 @@ class PubkyAuthApprovalViewModel @Inject constructor( }?.joinToString(context.getString(R.string.profile__auth_approval_services_separator)) ?: unknownService val usdtEnabled = usdtPreferences.enabled.first() val identityPublicKey = pubkyRepo.publicKey.value ?: pubkyRepo.localIdentityPublicKey() + val expectedSigner = request.expectedSigner + if (expectedSigner != null && identityPublicKey != null && + !PubkyAuthRequest.isExpectedSigner(expectedSigner, identityPublicKey) + ) { + Logger.warn("Refused auth request for another pubky", context = TAG) + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.profile__auth_error_title), + description = PubkyAuthRequestError.SignerMismatch(expectedSigner) + .localizedPubkyAuthMessage(context), + ) + _effects.emit(PubkyAuthApprovalEffect.Dismiss) + return@launch + } val profile = approvalProfile(identityPublicKey) _uiState.update { it.copy( diff --git a/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt b/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt index 1b4255252f..772c9af2ec 100644 --- a/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt +++ b/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt @@ -9,9 +9,19 @@ import to.bitkit.models.PubkyAuthRequestError import to.bitkit.repositories.WatchOnlyAccountError import to.bitkit.services.PubkyRingAuthTimeoutError +/** Characters shown from each end of the pubky a request names. */ +private const val SIGNER_EDGE_LENGTH = 4 + fun Throwable.localizedPubkyAuthMessage(context: Context): String? { var current: Throwable? = this while (current != null) { + if (current is PubkyAuthRequestError.SignerMismatch) { + val signer = current.expectedSigner + return context.getString( + R.string.profile__auth_error_other_pubky, + "${signer.take(SIGNER_EDGE_LENGTH)}...${signer.takeLast(SIGNER_EDGE_LENGTH)}", + ) + } val messageResource = current.pubkyAuthMessageResource() if (messageResource != null) { return context.getString(messageResource) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 77614b84c1..f38cf4daee 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -576,6 +576,7 @@ إضافة علامة التفاصيل حسنًا + هذا الطلب موجّه إلى %1$s، وليس إلى pubky هذه المحفظة. إنشاء ملف شخصي الملف الشخصي حاول مرة أخرى diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 06b95bfe98..6a4baa829e 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -587,6 +587,7 @@ Autorizar Detalles Autorizar + Esta solicitud es para %1$s, no para el pubky de esta billetera. Crear perfil Editar Perfil Perfil diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index d6d4a9f2cb..6c0ce1e80f 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -582,6 +582,7 @@ Nota: Qualsevol enllaç que afegiu serà visible públicament. Afegeix etiqueta Detalls + Aquesta sol·licitud és per a %1$s, no per al pubky d\'aquesta cartera. Crear perfil Editar perfil Perfil diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 82f4fd4833..472c76fc1f 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -587,6 +587,7 @@ Autorizovat Podrobnosti Autorizovat + Tento požadavek je určen pro %1$s, ne pro pubky této peněženky. Vytvořit profil Upravit profil Profil diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index b596372ffc..e2fe0360e4 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -568,6 +568,7 @@ Tag hinzufügen Autorisieren Sie Autorisieren Sie + Diese Anfrage ist für %1$s bestimmt, nicht für den Pubky dieses Wallets. Profil erstellen Profil bearbeiten Profil diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 42a34f22fe..8eb5d85dac 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -576,6 +576,7 @@ Προσθήκη ετικέτας Λεπτομέρειες ΟΚ + Αυτό το αίτημα προορίζεται για το %1$s, όχι για το pubky αυτού του πορτοφολιού. Δημιουργία προφίλ Προφίλ Προσπαθήστε Ξανά diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 6dc0e1e3d2..df64277b4c 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -584,6 +584,7 @@ Nota: Cualquier enlace que añada será públicamente visible. Añadir etiqueta Detalles + Esta solicitud es para %1$s, no para el pubky de este monedero. Crear perfil Editar Perfil Perfil diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 263394119f..63c6255398 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -581,6 +581,7 @@ Nota: Cualquier enlace que añada será públicamente visible. Añadir etiqueta Detalles + Esta solicitud es para %1$s, no para el pubky de este monedero. Crear perfil Editar Perfil Perfil diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f5a04008e8..8d96fc72fa 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -568,6 +568,7 @@ Autoriser Détails Autoriser + Cette demande est destinée à %1$s, pas au pubky de ce portefeuille. Créer un profil Modifier le profil Profil diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 93b5988584..09ab047a35 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -583,6 +583,7 @@ Nota: qualsiasi link aggiunto sarà visibile pubblicamente. Aggiungi Tag Dettagli + Questa richiesta è per %1$s, non per il pubky di questo portafoglio. Crea Profilo Modifica Profilo Profilo diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index da06deedb7..3092ae37a1 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -581,6 +581,7 @@ Bijvoorbeeld \'Website\' Let op: Iedere link die u toevoegt is openbaar beschikbaar. Tag toevoegen + Dit verzoek is voor %1$s, niet voor de pubky van deze wallet. Profiel aanmaken Profiel Bewerken Profiel diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 2eca3d9717..425a5adf3c 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -568,6 +568,7 @@ Autoryzuj Szczegóły Autoryzuj + To żądanie jest przeznaczone dla %1$s, a nie dla pubky tego portfela. Utwórz profil Edytuj profil Profil diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index ecf958ac73..7e850cf852 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -588,6 +588,7 @@ Autorizar Detalhes Autorizar + Esta solicitação é para %1$s, não para o pubky desta carteira. Criar Perfil Editar perfil Perfil diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index fe167db418..057b7c40e0 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -546,6 +546,7 @@ Atualizar\n<accent>Bitkit</accent> Adicionar Tag Detalhes + Este pedido destina-se a %1$s, não ao pubky desta carteira. Criar Perfil Perfil Tente novamente diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 08e92af37c..eb8d343879 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -599,6 +599,7 @@ Подробности Ок Авторизовать + Этот запрос предназначен для %1$s, а не для pubky этого кошелька. Создать Профиль Редактировать Профиль Профиль diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 47968335dd..0a6d079c29 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -820,6 +820,7 @@ The requested access does not match this Bitkit claim. This Pubky authorization link is invalid. This authorization is missing its required Bitkit claim. + This request is for %1$s, not this wallet\'s pubky. The homeserver did not accept this signup code. Try again or use another signup link. The authorization relay did not respond in time. Please try again. Authorization Failed diff --git a/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt b/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt index 0339f19820..1685ff7cd6 100644 --- a/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt +++ b/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt @@ -12,6 +12,10 @@ import kotlin.test.assertNull import kotlin.test.assertTrue class PubkyAuthRequestTest { + companion object { + private const val SIGNER = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + private const val OTHER_SIGNER = "5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + } @Test fun `optional USDT omission preserves delegated Paykit authority`() { @@ -207,6 +211,106 @@ class PubkyAuthRequestTest { assertEquals(PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1), request.bitkitClaim) } + @Test + fun `grant sign-in reads the pubky it must be approved with`() { + assertEquals(SIGNER.length, 52) + assertNull(PubkyAuthRequest.parseExpectedSigner(grantSigninUrl()).getOrThrow()) + assertEquals(SIGNER, PubkyAuthRequest.parseExpectedSigner(grantSigninUrl("spk=$SIGNER")).getOrThrow()) + assertEquals(SIGNER, PubkyAuthRequest.parseExpectedSigner(grantSigninUrl("%73pk=$SIGNER#spk=x")).getOrThrow()) + + val request = PubkyAuthRequest.parse( + rawUrl = grantSigninUrl("spk=$SIGNER"), + clientId = "example.app", + relay = "https://relay.example/inbox/", + capabilities = "/pub/example.app/:rw", + ).getOrThrow() + + assertEquals(SIGNER, request.expectedSigner) + } + + @Test + fun `grant sign-in with a repeated or malformed expected signer is invalid`() { + val invalidQueries = listOf( + "spk", + "spk=", + "spk=not-a-public-key", + "spk=pubky$SIGNER", + "spk=pk:$SIGNER", + "spk=https://$SIGNER/", + "spk=${SIGNER.uppercase()}", + "spk=%20$SIGNER", + "spk=$SIGNER%20", + "spk=$SIGNER/", + "spk=${SIGNER.dropLast(1)}", + "spk=${SIGNER.dropLast(1)}b", + "spk=$SIGNER&spk=$SIGNER", + "spk=$SIGNER&spk=$OTHER_SIGNER", + "spk=$SIGNER&%73pk=$SIGNER", + "spk=$SIGNER&spk=", + ) + + invalidQueries.forEach { query -> + val url = grantSigninUrl(query) + assertIs( + PubkyAuthRequest.parseExpectedSigner(url).exceptionOrNull(), + query, + ) + assertIs( + PubkyAuthRequest.parse( + rawUrl = url, + clientId = "example.app", + relay = "https://relay.example/inbox/", + capabilities = "/pub/example.app/:rw", + ).exceptionOrNull(), + query, + ) + } + } + + @Test + fun `sign-in read differently from the SDK is still held to its expected signer`() { + listOf("pubkyauth://user@signin_grant:80", "pubkyauth://signin_grant/", "pubkyauth://signin").forEach { + assertEquals(SIGNER, PubkyAuthRequest.parseExpectedSigner("$it?spk=$SIGNER").getOrThrow(), it) + assertIs( + PubkyAuthRequest.parseExpectedSigner("$it?spk=$SIGNER&spk=$SIGNER").exceptionOrNull(), + it, + ) + } + assertIs( + PubkyAuthRequest.parseExpectedSigner(grantSigninUrl("spk=${SIGNER.take(26)}\t${SIGNER.drop(26)}")) + .exceptionOrNull(), + ) + } + + @Test + fun `signup requests ignore the expected signer`() { + val signupUrls = listOf( + "pubkyauth://signup_grant", + "pubkyauth://signup", + "pubkyauth://direct_signup", + "pubkyring://signup", + ) + signupUrls.forEach { + val url = "$it?caps=/pub/example.app/:rw&hs=homeserver&spk=not-a-public-key&spk=other" + + assertNull(PubkyAuthRequest.parseExpectedSigner(url).getOrThrow(), it) + } + } + + @Test + fun `expected signer matches only this pubky with or without its prefix`() { + val bareKeyStartingWithPrefix = "pubky" + SIGNER.drop(5) + + assertTrue(PubkyAuthRequest.isExpectedSigner(null, SIGNER)) + assertTrue(PubkyAuthRequest.isExpectedSigner(SIGNER, SIGNER)) + assertTrue(PubkyAuthRequest.isExpectedSigner(SIGNER, "pubky$SIGNER")) + assertTrue(PubkyAuthRequest.isExpectedSigner(bareKeyStartingWithPrefix, bareKeyStartingWithPrefix)) + assertFalse(PubkyAuthRequest.isExpectedSigner(OTHER_SIGNER, SIGNER)) + assertFalse(PubkyAuthRequest.isExpectedSigner(OTHER_SIGNER, "pubky$SIGNER")) + assertFalse(PubkyAuthRequest.isExpectedSigner(SIGNER.drop(5), bareKeyStartingWithPrefix)) + assertFalse(PubkyAuthRequest.isExpectedSigner(SIGNER, "")) + } + @Test fun `matcher recognizes the Paykit scope with surrounding whitespace`() { val capabilities = " ${PubkyAuthClaim.REQUIRED_CAPABILITIES} " @@ -443,6 +547,10 @@ class PubkyAuthRequestTest { return "pubkyauth://signin?caps=$capabilities&relay=https%3A%2F%2Fhttprelay.pubky.app%2Finbox%2F$claims" } + private fun grantSigninUrl(extraQuery: String? = null): String = + "pubkyauth://signin_grant?caps=/pub/example.app/:rw&relay=https%3A%2F%2Frelay.example%2Finbox%2F" + + "&secret=secret&cid=example.app&cpk=$OTHER_SIGNER" + extraQuery?.let { "&$it" }.orEmpty() + private fun ringSignupUrl(signupToken: String? = null, scheme: String = "pubkyring"): String = "$scheme://signup?hs=homeserver" + "&relay=https%3A%2F%2Frelay.example%2Finbox%2F" + diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 43a2124b81..cf778a30b3 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -86,6 +86,7 @@ import to.bitkit.ext.runSuspendCatching import to.bitkit.models.PubkyAuthClaim import to.bitkit.models.PubkyAuthClaim.Item import to.bitkit.models.PubkyAuthRequest +import to.bitkit.models.PubkyAuthRequestError import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileData import to.bitkit.models.PubkyProfileDataLink @@ -541,6 +542,59 @@ class PubkyRepoTest : BaseUnitTest() { verifyBlocking(pubkyService) { approveAuth(authUrl, capabilities, clientId, secretKey) } } + @Test + fun `approveAuth signs a grant sign-in that names this pubky`() = test { + val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + val authUrl = "pubkyauth://signin_grant?caps=/pub/bitkit.to/:rw&spk=$signer" + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local_secret") + whenever(pubkyService.publicKeyFromSecret("local_secret")).thenReturn(signer) + + val result = sut.approveAuth(authUrl, "/pub/bitkit.to/:rw", "paykit.test") + + assertTrue(result.isSuccess) + verifyBlocking(pubkyService) { approveAuth(authUrl, "/pub/bitkit.to/:rw", "paykit.test", "local_secret") } + } + + @Test + fun `approval never signs a grant sign-in that names another pubky`() = test { + val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + val other = "5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + val claim = PubkyAuthClaim(Item.PAYKIT_ACCESS_V1).wireValue + val authUrl = "pubkyauth://signin_grant?caps=/pub/paykit/:rw&x-bitkit-claim=$claim&spk=$other" + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local_secret") + whenever(pubkyService.publicKeyFromSecret("local_secret")).thenReturn(signer) + + val results = listOf( + sut.approveAuth(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, "paykit.test"), + sut.approveAuthWithCompanionClaim(authUrl, "paykit.test", byteArrayOf()), + ) + + results.forEach { + assertEquals(PubkyAuthRequestError.SignerMismatch(other), it.exceptionOrNull()) + } + verifyBlocking(pubkyService, never()) { approveAuth(any(), any(), any(), any()) } + verifyBlocking(pubkyService, never()) { approveAuthWithCompanionClaim(any(), any(), any(), any(), any()) } + } + + @Test + fun `approval never signs a grant sign-in with a repeated or malformed expected signer`() = test { + val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + val claim = PubkyAuthClaim(Item.PAYKIT_ACCESS_V1).wireValue + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local_secret") + whenever(pubkyService.publicKeyFromSecret("local_secret")).thenReturn(signer) + + listOf("spk=$signer&spk=$signer", "spk=pubky$signer", "spk=").forEach { query -> + val authUrl = "pubkyauth://signin_grant?caps=/pub/paykit/:rw&x-bitkit-claim=$claim&$query" + + listOf( + sut.approveAuth(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, "paykit.test"), + sut.approveAuthWithCompanionClaim(authUrl, "paykit.test", byteArrayOf()), + ).forEach { assertIs(it.exceptionOrNull(), query) } + } + verifyBlocking(pubkyService, never()) { approveAuth(any(), any(), any(), any()) } + verifyBlocking(pubkyService, never()) { approveAuthWithCompanionClaim(any(), any(), any(), any(), any()) } + } + @Test fun `approveAuthWithCompanionClaim forwards exact claim identifiers and capability`() = test { val clientId = "paykit.test" diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt index efecbe3b0c..0f464179c7 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt @@ -9,6 +9,7 @@ import com.synonym.paykit.PubkyAuthCompanionClaimApprovalException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent import kotlinx.serialization.json.Json @@ -38,6 +39,7 @@ import to.bitkit.models.PubkyAuthClaim.Item import to.bitkit.models.PubkyAuthPermission import to.bitkit.models.PubkyAuthRequest import to.bitkit.models.PubkyProfile +import to.bitkit.models.Toast import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.repositories.Endpoint @@ -48,6 +50,7 @@ import to.bitkit.repositories.UsdtRepo import to.bitkit.repositories.WatchOnlyAccountAuthorizationStartError import to.bitkit.repositories.WatchOnlyAccountRepo import to.bitkit.test.BaseUnitTest +import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -336,6 +339,63 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any()) } } + @Test + fun `request naming another pubky is refused before consent and never signed`() = test { + val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + val other = "5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + val authUrl = "pubkyauth://signin_grant?caps=/pub/example/:rw&spk=$other" + val capabilities = "/pub/example/:rw" + publicKeyFlow.value = "pubky$signer" + whenever(context.getString(R.string.profile__auth_error_other_pubky, "5jsj...tryo")) + .thenReturn("This request is for 5jsj...tryo, not this wallet's pubky.") + whenever { pubkyRepo.parseAuthUrl(authUrl) }.thenReturn( + Result.success(authRequest(authUrl, capabilities).copy(expectedSigner = other)), + ) + val sut = createSut() + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + + sut.effects.test { + sut.load(authUrl) + advanceUntilIdle() + assertEquals(PubkyAuthApprovalEffect.Dismiss, awaitItem()) + + sut.requestAuthorize(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + expectNoEvents() + } + + assertEquals(ApprovalState.Loading, sut.uiState.value.state) + assertEquals("This request is for 5jsj...tryo, not this wallet's pubky.", toasts.single().description) + verifyBlocking(pubkyRepo, never()) { approveAuth(any(), any(), any()) } + verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } + verifyBlocking(pubkyRepo, never()) { approveSignupAuth(any()) } + toastJob.cancel() + } + + @Test + fun `request naming this pubky reaches consent and is approved`() = test { + val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + val authUrl = "pubkyauth://signin_grant?caps=/pub/example/:rw&spk=$signer" + val capabilities = "/pub/example/:rw" + publicKeyFlow.value = "pubky$signer" + whenever { pubkyRepo.parseAuthUrl(authUrl) }.thenReturn( + Result.success(authRequest(authUrl, capabilities).copy(expectedSigner = signer)), + ) + whenever { pubkyRepo.approveAuth(authUrl, capabilities, clientId) }.thenReturn(Result.success(Unit)) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + assertEquals(ApprovalState.Authorize, sut.uiState.value.state) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + assertEquals(ApprovalState.Success, sut.uiState.value.state) + verifyBlocking(pubkyRepo) { approveAuth(authUrl, capabilities, clientId) } + } + @Test fun `signup requires consent and local auth before registration`() = test { listOf("pubkyauth://direct_signup", "pubkyauth://signup", "pubkyring://signup", "pubkyauth://signup_grant") diff --git a/changelog.d/next/1761.fixed.md b/changelog.d/next/1761.fixed.md new file mode 100644 index 0000000000..fa9b7527fe --- /dev/null +++ b/changelog.d/next/1761.fixed.md @@ -0,0 +1 @@ +Fixed Pubky sign-in requests meant for another pubky being signed; Bitkit now refuses them and names the pubky they are for. diff --git a/journeys/README.md b/journeys/README.md index db63baa3fe..8bb5f27a6f 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -182,6 +182,7 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691): | `security/forgot-pin-nav-bar-inset.xml` | not ported — Android-only fix (synonymdev/bitkit-android#1572): the Android sheet host adds no navigation-bar inset, so each sheet screen pads itself. iOS sheets keep their content inside the bottom safe area | | `deeplinks/pubky-contact.xml` | ported — same contact routing and unlock behavior | | `pubky-auth/signin-cold-start.xml` | `pubky-auth/open-signin-link.xml`, adapted — iOS opens the same sign-in link on a terminated app through `bitkit://pubky-auth/signin`. Android only: the raw `pubkyauth` scheme, the "Loading Your Pubky Profile" toast while the session restores, and Authorize through to `PubkyAuthOK` | +| `pubky-auth/signin-expected-pubky.xml` | ported — same file, journey name and steps; iOS opens the same query through `bitkit://pubky-auth/signin` and its toasts carry the ids `PubkyAuthOtherPubkyToast` and `PubkyAuthInvalidRequestToast` | | `pubky-auth/loading-toast-long-locale.xml` | not ported — iOS has no Pubky loading toast; `settings/applying-toast-close-button.xml` checks the same close-button inset on both platforms | | `pubky-auth/signin-with-second-link.xml` | not ported — iOS still drops a pending sign-in link when a second link opens on the PIN screen (synonymdev/bitkit-ios#985); port it with that fix | | `pubky-profile/cached-profile-header.xml` | same file, journey name and steps — one step differs: Android adds a screenshot check of the cached avatar, which comes from the Pubky image disk cache synonymdev/bitkit-android#1399 adds | diff --git a/journeys/pubky-auth/README.md b/journeys/pubky-auth/README.md index 45dffe13df..ad4c36b2c4 100644 --- a/journeys/pubky-auth/README.md +++ b/journeys/pubky-auth/README.md @@ -13,6 +13,10 @@ - `signin-with-second-link.xml` checks that a payment link opened while a sign-in link is pending, on the PIN screen in either order or over the open authorization sheet, opens only after the authorization sheet closes, and never drops the sign-in. +- `signin-expected-pubky.xml` checks a `pubkyauth://signin_grant` link that names the pubky it must be + approved with (`spk`): this wallet's pubky opens the authorization sheet, another pubky is refused + with a message naming it, and a repeated or malformed `spk` is an invalid request. Nothing is + authorized. ## Grant signup diff --git a/journeys/pubky-auth/signin-expected-pubky.xml b/journeys/pubky-auth/signin-expected-pubky.xml new file mode 100644 index 0000000000..1663c4a8d9 --- /dev/null +++ b/journeys/pubky-auth/signin-expected-pubky.xml @@ -0,0 +1,29 @@ + + + Verifies that a grant sign-in link naming the pubky that must approve it (spk) opens the authorization sheet only + when it names this wallet's pubky, is refused with a message naming the other pubky otherwise, and is invalid when + spk is repeated or malformed. Precondition: an unlocked regtest wallet with a locally managed Pubky identity. The + links are local-only dummy requests and nothing is authorized; never tap Authorize. BASE is + pubkyauth://signin_grant?caps=/pub/locks.app/:rw&relay=https%3A%2F%2Fhttprelay.pubky.app%2Finbox%2F&secret=e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3s&cid=locks.test&cpk=5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo + and OTHER is 8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty. Android opens each link with + adb shell "am start -a android.intent.action.VIEW -d '<link>' to.bitkit.dev" and reads toasts from a + screenshot; iOS opens the same query through bitkit://pubky-auth/signin and its toasts carry the ids + PubkyAuthOtherPubkyToast and PubkyAuthInvalidRequestToast. + + + Open the Profile screen and read this wallet's pubky: tap Share (id "ProfileShare") and read the text preview, then close the share sheet (iOS: tap Copy (id "ProfileCopy") and run xcrun simctl pbpaste) + Set OWN to that pubky without its leading "pubky" prefix; it is 52 characters long + Open BASE&spk=OWN + Verify the authorize button (id "PubkyAuthAuthorize") is visible and the profile card (id "PubkyAuthProfile") shows the first and last four characters of OWN + Tap Cancel + Open BASE&spk=OTHER + Verify an error toast reads "This request is for 8um7...d1ty, not this wallet's pubky." + Wait 5 seconds, then verify the authorize button (id "PubkyAuthAuthorize") is not visible + Open BASE&spk=OWN&spk=OWN + Verify the invalid request toast is shown and the authorize button (id "PubkyAuthAuthorize") is not visible + Open BASE&spk=pubkyOWN + Verify the invalid request toast is shown and the authorize button (id "PubkyAuthAuthorize") is not visible + Open BASE&spk=not-a-public-key + Verify the invalid request toast is shown and the authorize button (id "PubkyAuthAuthorize") is not visible + + From a81bee2a2729e76fe81b6a25a6d7eb15b5c332f0 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 13:01:43 -0300 Subject: [PATCH 2/5] fix: harden pubky auth spk checks after review Co-Authored-By: Claude Fable 5.2 --- .../java/to/bitkit/repositories/PubkyRepo.kt | 20 +++++++- .../java/to/bitkit/services/PubkyService.kt | 5 ++ .../profile/PubkyAuthApprovalViewModel.kt | 6 +++ .../java/to/bitkit/viewmodels/AppViewModel.kt | 15 ++++++ .../to/bitkit/models/PubkyAuthRequestTest.kt | 14 +++++- .../to/bitkit/repositories/PubkyRepoTest.kt | 48 +++++++++++++++++++ .../profile/PubkyAuthApprovalViewModelTest.kt | 35 ++++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 16 +++++++ journeys/pubky-auth/signin-expected-pubky.xml | 2 +- 9 files changed, 158 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 16570d852f..6838da0cf7 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -2104,6 +2104,7 @@ class PubkyRepo @Inject constructor( suspend fun parseAuthUrl(authUrl: String): Result = runSuspendCatching { withContext(ioDispatcher) { + validatedExpectedSigner(authUrl) if (PubkyAuthRequest.isSignupUrl(authUrl) && !PubkyAuthRequest.isGrantSignupUrl(authUrl)) { val request = PubkyAuthRequest.parseSignup(authUrl).getOrThrow() pubkyService.validateSignupRequest( @@ -2231,8 +2232,25 @@ class PubkyRepo @Inject constructor( } } + /** Fails when [authUrl] names a pubky other than the one that would sign it, before anything is prepared. */ + suspend fun checkExpectedSigner(authUrl: String): Result = runSuspendCatching { + withContext(ioDispatcher) { + val secretKeyHex = requireNotNull(activeSecretKeyHex()) { + "No secret key available — use Ring to manage authorizations" + } + requireExpectedSigner(authUrl, secretKeyHex) + } + } + + private suspend fun validatedExpectedSigner(authUrl: String): String? { + val expectedSigner = PubkyAuthRequest.parseExpectedSigner(authUrl).getOrThrow() ?: return null + runSuspendCatching { pubkyService.validatePublicKey(expectedSigner) } + .onFailure { throw PubkyAuthRequestError.InvalidUrl(it) } + return expectedSigner + } + private suspend fun requireExpectedSigner(authUrl: String, secretKeyHex: String) { - val expectedSigner = PubkyAuthRequest.parseExpectedSigner(authUrl).getOrThrow() ?: return + val expectedSigner = validatedExpectedSigner(authUrl) ?: return val signer = pubkyService.publicKeyFromSecret(secretKeyHex) if (!PubkyAuthRequest.isExpectedSigner(expectedSigner, signer)) { throw PubkyAuthRequestError.SignerMismatch(expectedSigner) diff --git a/app/src/main/java/to/bitkit/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt index 180195c2fd..5f1f0e4887 100644 --- a/app/src/main/java/to/bitkit/services/PubkyService.kt +++ b/app/src/main/java/to/bitkit/services/PubkyService.kt @@ -147,6 +147,11 @@ class PubkyService @Inject constructor( Unit } + suspend fun validatePublicKey(publicKey: String): Unit = ServiceQueue.PUBKY.background { + PaykitPublicKeys.normalize(publicKey) + Unit + } + suspend fun approveAuth( authUrl: String, expectedCapabilities: String, diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt index 5a65016f74..e9dda5906f 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt @@ -292,6 +292,12 @@ class PubkyAuthApprovalViewModel @Inject constructor( request: PubkyAuthRequest, authUrl: String, ): Boolean { + if (request.expectedSigner != null) { + pubkyRepo.checkExpectedSigner(authUrl).onFailure { + handleApprovalFailure(it, authUrl) + return false + } + } val endpoint = runSuspendCatching { validatedUsdtEndpoint(request) }.getOrElse { diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index e06d777c1d..3acfbdfd5a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -158,6 +158,7 @@ import to.bitkit.models.PaykitAmountError import to.bitkit.models.PaykitAsset import to.bitkit.models.PaykitRequestPayment import to.bitkit.models.PubkyAuthRequest +import to.bitkit.models.PubkyAuthRequestError import to.bitkit.models.PubkyContactLink import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyPublicKeyFormat @@ -10729,6 +10730,20 @@ class AppViewModel @Inject constructor( return } + val expectedSigner = PubkyAuthRequest.parseExpectedSigner(authUrl).getOrNull() + val publicKey = pubkyRepo.publicKey.value + if (expectedSigner != null && publicKey != null && + !PubkyAuthRequest.isExpectedSigner(expectedSigner, publicKey) + ) { + Logger.warn("Refused auth request for another pubky", context = TAG) + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.profile__auth_error_title), + description = PubkyAuthRequestError.SignerMismatch(expectedSigner).localizedPubkyAuthMessage(context), + ) + return + } + if (!pubkyRepo.hasSecretKey()) { ToastEventBus.send( type = Toast.ToastType.WARNING, diff --git a/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt b/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt index 1685ff7cd6..04015daf87 100644 --- a/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt +++ b/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt @@ -213,7 +213,7 @@ class PubkyAuthRequestTest { @Test fun `grant sign-in reads the pubky it must be approved with`() { - assertEquals(SIGNER.length, 52) + assertEquals(52, SIGNER.length) assertNull(PubkyAuthRequest.parseExpectedSigner(grantSigninUrl()).getOrThrow()) assertEquals(SIGNER, PubkyAuthRequest.parseExpectedSigner(grantSigninUrl("spk=$SIGNER")).getOrThrow()) assertEquals(SIGNER, PubkyAuthRequest.parseExpectedSigner(grantSigninUrl("%73pk=$SIGNER#spk=x")).getOrThrow()) @@ -282,6 +282,18 @@ class PubkyAuthRequestTest { ) } + @Test + fun `control characters cannot hide the expected signer`() { + val hidden = listOf("s\tpk=$SIGNER", "sp\nk=$SIGNER", "spk\r=$SIGNER", "spk=$SIGNER\u007F", "\t&spk=$SIGNER") + + hidden.forEach { + assertIs( + PubkyAuthRequest.parseExpectedSigner(grantSigninUrl(it)).exceptionOrNull(), + it, + ) + } + } + @Test fun `signup requests ignore the expected signer`() { val signupUrls = listOf( diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index cf778a30b3..9f3914bcab 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -595,6 +595,54 @@ class PubkyRepoTest : BaseUnitTest() { verifyBlocking(pubkyService, never()) { approveAuthWithCompanionClaim(any(), any(), any(), any(), any()) } } + @Test + fun `expected signer that is not a public key makes the request invalid and is never signed`() = test { + val notAKey = "y".repeat(52) + val authUrl = "pubkyauth://signin_grant?caps=/pub/bitkit.to/:rw&spk=$notAKey" + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local_secret") + whenever(pubkyService.validatePublicKey(notAKey)).thenAnswer { throw TestAppError("not a public key") } + + listOf( + sut.parseAuthUrl(authUrl), + sut.checkExpectedSigner(authUrl), + sut.approveAuth(authUrl, "/pub/bitkit.to/:rw", "paykit.test"), + ).forEach { assertIs(it.exceptionOrNull()) } + verifyBlocking(pubkyService, never()) { parseAuthUrl(any()) } + verifyBlocking(pubkyService, never()) { approveAuth(any(), any(), any(), any()) } + } + + @Test + fun `checkExpectedSigner fails for another pubky and passes for this one or none`() = test { + val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + val other = "5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + val base = "pubkyauth://signin_grant?caps=/pub/bitkit.to/:rw" + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local_secret") + whenever(pubkyService.publicKeyFromSecret("local_secret")).thenReturn(signer) + + assertTrue(sut.checkExpectedSigner(base).isSuccess) + assertTrue(sut.checkExpectedSigner("$base&spk=$signer").isSuccess) + assertEquals( + PubkyAuthRequestError.SignerMismatch(other), + sut.checkExpectedSigner("$base&spk=$other").exceptionOrNull(), + ) + } + + @Test + fun `grant signup with an existing identity is approved whatever its spk says`() = test { + val capabilities = "/pub/pubky.app/:rw" + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local_secret") + whenever(pubkyService.publicKeyFromSecret("local_secret")) + .thenReturn("8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty") + + listOf("5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo", "not-a-public-key", "a&spk=b").forEach { + val authUrl = "pubkyauth://signup_grant?hs=homeserver&cid=shop.pubky.app&spk=$it" + + assertTrue(sut.approveAuth(authUrl, capabilities, "shop.pubky.app").isSuccess, it) + verifyBlocking(pubkyService) { approveAuth(authUrl, capabilities, "shop.pubky.app", "local_secret") } + } + verifyBlocking(pubkyService, never()) { validatePublicKey(any()) } + } + @Test fun `approveAuthWithCompanionClaim forwards exact claim identifiers and capability`() = test { val clientId = "paykit.test" diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt index 0f464179c7..3e337a3057 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt @@ -38,6 +38,7 @@ import to.bitkit.models.PubkyAuthClaim import to.bitkit.models.PubkyAuthClaim.Item import to.bitkit.models.PubkyAuthPermission import to.bitkit.models.PubkyAuthRequest +import to.bitkit.models.PubkyAuthRequestError import to.bitkit.models.PubkyProfile import to.bitkit.models.Toast import to.bitkit.models.WatchOnlyAccountRecord @@ -374,6 +375,39 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { toastJob.cancel() } + @Test + fun `request for another pubky prepares nothing when this pubky was unknown at load`() = test { + val other = "5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + val authUrl = "pubkyauth://signin_grant?x-bitkit-claim=paykit-access-v1.watch-only-account-v1&spk=$other" + val request = authRequest( + authUrl, + PubkyAuthClaim.REQUIRED_CAPABILITIES, + PubkyAuthClaim(Item.PAYKIT_ACCESS_V1, Item.WATCH_ONLY_ACCOUNT_V1), + ).copy(expectedSigner = other) + whenever(context.getString(R.string.profile__auth_error_other_pubky, "5jsj...tryo")) + .thenReturn("This request is for 5jsj...tryo, not this wallet's pubky.") + whenever { pubkyRepo.parseAuthUrl(authUrl) }.thenReturn(Result.success(request)) + whenever { pubkyRepo.checkExpectedSigner(authUrl) } + .thenReturn(Result.failure(PubkyAuthRequestError.SignerMismatch(other))) + val sut = createSut() + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + + sut.load(authUrl) + advanceUntilIdle() + assertEquals(ApprovalState.WatchOnlyConsent, sut.uiState.value.state) + sut.approveWatchOnlyConsent(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + assertEquals(ApprovalState.Authorize, sut.uiState.value.state) + assertEquals("This request is for 5jsj...tryo, not this wallet's pubky.", toasts.single().description) + verifyNoInteractions(watchOnlyAccountRepo) + verifyBlocking(pubkyRepo, never()) { approveAuth(any(), any(), any()) } + verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } + toastJob.cancel() + } + @Test fun `request naming this pubky reaches consent and is approved`() = test { val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" @@ -384,6 +418,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { Result.success(authRequest(authUrl, capabilities).copy(expectedSigner = signer)), ) whenever { pubkyRepo.approveAuth(authUrl, capabilities, clientId) }.thenReturn(Result.success(Unit)) + whenever { pubkyRepo.checkExpectedSigner(authUrl) }.thenReturn(Result.success(Unit)) val sut = createSut() sut.load(authUrl) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 80d409ce9c..d7da393ff4 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5945,6 +5945,22 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(Sheet.PubkyAuth(authUrl), sut.currentSheet.value) } + @Test + fun `pubky auth deeplink for another pubky is refused before the Ring hint`() = test { + enablePaykitUi() + pubkyPublicKey.value = testPublicKey + whenever(pubkyRepo.hasSecretKey()).thenReturn(false) + val authUrl = "pubkyauth://signin_grant?caps=/pub/paykit/v0/:rw" + + "&spk=8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + + sut.handleDeeplinkIntent(Intent(Intent.ACTION_VIEW, authUrl.toUri())) + advanceUntilIdle() + + assertNull(sut.currentSheet.value) + verify(context).getString(R.string.profile__auth_error_other_pubky, "8um7...1dty") + verify(context, never()).getString(R.string.pubky_auth__use_ring) + } + @Test fun `cold pubky auth deeplink waits for settings identity and wallet unlock`() = test { val initialized = CompletableDeferred() diff --git a/journeys/pubky-auth/signin-expected-pubky.xml b/journeys/pubky-auth/signin-expected-pubky.xml index 1663c4a8d9..c28a8fd007 100644 --- a/journeys/pubky-auth/signin-expected-pubky.xml +++ b/journeys/pubky-auth/signin-expected-pubky.xml @@ -17,7 +17,7 @@ Verify the authorize button (id "PubkyAuthAuthorize") is visible and the profile card (id "PubkyAuthProfile") shows the first and last four characters of OWN Tap Cancel Open BASE&spk=OTHER - Verify an error toast reads "This request is for 8um7...d1ty, not this wallet's pubky." + Verify an error toast reads "This request is for 8um7...1dty, not this wallet's pubky." Wait 5 seconds, then verify the authorize button (id "PubkyAuthAuthorize") is not visible Open BASE&spk=OWN&spk=OWN Verify the invalid request toast is shown and the authorize button (id "PubkyAuthAuthorize") is not visible From baeabb3081680557c78f774dc05e9c1f62b87646 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 13:14:12 -0300 Subject: [PATCH 3/5] docs: cite upstream spk scope in pubky auth parser Co-Authored-By: Claude Fable 5.2 --- app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt b/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt index 9bd8889d04..cfc61995b2 100644 --- a/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt +++ b/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt @@ -155,7 +155,9 @@ data class PubkyAuthRequest( * Reads the pubky a sign-in request must be approved with. Absent is fine; a repeated value or anything other * than a bare canonical z-base-32 key makes the request invalid, as in the Pubky SDK parser for `signin_grant`. * Only signup requests ignore the parameter, so a sign-in this parser reads differently from the SDK is still - * held to it. + * held to it. Upstream reads `spk` for `signin_grant` alone (pubky/pubky-homeserver at d95161af3e: + * `pubky-sdk/src/actors/auth/deep_links/signin_grant.rs:106` is the only caller of `parse_expected_signer`, + * `deep_link.rs:211` tests that `signin` and `signup_grant` ignore it, `docs/AUTH.md:81`). */ fun parseExpectedSigner(rawUrl: String): Result = runCatching { val uri = URI(rawUrl) From 0f8fbc2d18298ce3604ecb85dde411679cd4b924 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 27 Nov 2026 05:46:31 -0300 Subject: [PATCH 4/5] fix: validate spk as a real key before reporting a mismatch Co-Authored-By: Claude Fable 5.2 --- .../java/to/bitkit/repositories/PubkyRepo.kt | 5 +++++ .../java/to/bitkit/services/PubkyService.kt | 4 +++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 2 +- .../to/bitkit/repositories/PubkyRepoTest.kt | 6 +++++- .../viewmodels/AppViewModelSendFlowTest.kt | 17 +++++++++++++++++ 5 files changed, 31 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 6838da0cf7..cc630b1ddb 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -2242,6 +2242,11 @@ class PubkyRepo @Inject constructor( } } + /** The pubky [authUrl] must be approved with, or null when it names none or the request is invalid. */ + suspend fun validExpectedSigner(authUrl: String): String? = runSuspendCatching { + withContext(ioDispatcher) { validatedExpectedSigner(authUrl) } + }.getOrNull() + private suspend fun validatedExpectedSigner(authUrl: String): String? { val expectedSigner = PubkyAuthRequest.parseExpectedSigner(authUrl).getOrThrow() ?: return null runSuspendCatching { pubkyService.validatePublicKey(expectedSigner) } diff --git a/app/src/main/java/to/bitkit/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt index 5f1f0e4887..2ad6b297ab 100644 --- a/app/src/main/java/to/bitkit/services/PubkyService.kt +++ b/app/src/main/java/to/bitkit/services/PubkyService.kt @@ -12,6 +12,7 @@ import com.synonym.paykit.PubkyAuthCompanionClaim import com.synonym.paykit.PubkyProfileSnapshot import com.synonym.paykit.PubkyProfileUpdate import com.synonym.paykit.PubkySessionBootstrapResult +import com.synonym.paykit.normalizePubkyPublicKey import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.withTimeoutOrNull @@ -147,8 +148,9 @@ class PubkyService @Inject constructor( Unit } + /** Throws unless [publicKey] decodes to an Ed25519 point; `PaykitPublicKeys.normalize` checks only its spelling. */ suspend fun validatePublicKey(publicKey: String): Unit = ServiceQueue.PUBKY.background { - PaykitPublicKeys.normalize(publicKey) + normalizePubkyPublicKey(publicKey) Unit } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 3acfbdfd5a..3b2d0440e3 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -10730,7 +10730,7 @@ class AppViewModel @Inject constructor( return } - val expectedSigner = PubkyAuthRequest.parseExpectedSigner(authUrl).getOrNull() + val expectedSigner = pubkyRepo.validExpectedSigner(authUrl) val publicKey = pubkyRepo.publicKey.value if (expectedSigner != null && publicKey != null && !PubkyAuthRequest.isExpectedSigner(expectedSigner, publicKey) diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 9f3914bcab..23b3db6584 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -597,7 +597,7 @@ class PubkyRepoTest : BaseUnitTest() { @Test fun `expected signer that is not a public key makes the request invalid and is never signed`() = test { - val notAKey = "y".repeat(52) + val notAKey = "ye" + "y".repeat(50) val authUrl = "pubkyauth://signin_grant?caps=/pub/bitkit.to/:rw&spk=$notAKey" whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local_secret") whenever(pubkyService.validatePublicKey(notAKey)).thenAnswer { throw TestAppError("not a public key") } @@ -607,6 +607,10 @@ class PubkyRepoTest : BaseUnitTest() { sut.checkExpectedSigner(authUrl), sut.approveAuth(authUrl, "/pub/bitkit.to/:rw", "paykit.test"), ).forEach { assertIs(it.exceptionOrNull()) } + assertNull(sut.validExpectedSigner(authUrl)) + assertNull(sut.validExpectedSigner("pubkyauth://signin_grant?caps=/pub/bitkit.to/:rw")) + val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + assertEquals(signer, sut.validExpectedSigner("pubkyauth://signin_grant?spk=$signer")) verifyBlocking(pubkyService, never()) { parseAuthUrl(any()) } verifyBlocking(pubkyService, never()) { approveAuth(any(), any(), any(), any()) } } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index d7da393ff4..f1d4b1ccc0 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5952,6 +5952,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkyRepo.hasSecretKey()).thenReturn(false) val authUrl = "pubkyauth://signin_grant?caps=/pub/paykit/v0/:rw" + "&spk=8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + whenever(pubkyRepo.validExpectedSigner(authUrl)) + .thenReturn("8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty") sut.handleDeeplinkIntent(Intent(Intent.ACTION_VIEW, authUrl.toUri())) advanceUntilIdle() @@ -5961,6 +5963,21 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(context, never()).getString(R.string.pubky_auth__use_ring) } + @Test + fun `pubky auth deeplink with an spk that is not a public key is not reported as another pubky`() = test { + enablePaykitUi() + pubkyPublicKey.value = testPublicKey + whenever(pubkyRepo.hasSecretKey()).thenReturn(true) + val authUrl = "pubkyauth://signin_grant?caps=/pub/paykit/v0/:rw&spk=ye${"y".repeat(50)}" + whenever(pubkyRepo.validExpectedSigner(authUrl)).thenReturn(null) + + sut.handleDeeplinkIntent(Intent(Intent.ACTION_VIEW, authUrl.toUri())) + advanceUntilIdle() + + assertEquals(Sheet.PubkyAuth(authUrl), sut.currentSheet.value) + verify(context, never()).getString(eq(R.string.profile__auth_error_other_pubky), any()) + } + @Test fun `cold pubky auth deeplink waits for settings identity and wallet unlock`() = test { val initialized = CompletableDeferred() From 465a4701b335d5a8d3e1f19f2f653843c1549540 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 27 Nov 2026 09:27:17 -0300 Subject: [PATCH 5/5] fix: validate the whole request before the signer mismatch Co-Authored-By: Claude Fable 5.2 --- .../java/to/bitkit/repositories/PubkyRepo.kt | 9 +++--- .../to/bitkit/repositories/PubkyRepoTest.kt | 19 ++++++++++-- .../profile/PubkyAuthApprovalViewModelTest.kt | 31 +++++++++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 21 +++++++++---- 4 files changed, 67 insertions(+), 13 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index efcbf1e7c0..8339f47316 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -2192,10 +2192,11 @@ class PubkyRepo @Inject constructor( } } - /** The pubky [authUrl] must be approved with, or null when it names none or the request is invalid. */ - suspend fun validExpectedSigner(authUrl: String): String? = runSuspendCatching { - withContext(ioDispatcher) { validatedExpectedSigner(authUrl) } - }.getOrNull() + /** + * The pubky [authUrl] must be approved with, or null when it names none or any part of the request is invalid, + * so an unusable link is never reported as meant for another pubky. + */ + suspend fun validExpectedSigner(authUrl: String): String? = parseAuthUrl(authUrl).getOrNull()?.expectedSigner private suspend fun validatedExpectedSigner(authUrl: String): String? { val expectedSigner = PubkyAuthRequest.parseExpectedSigner(authUrl).getOrThrow() ?: return null diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 23b3db6584..2aeda45520 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -608,13 +608,26 @@ class PubkyRepoTest : BaseUnitTest() { sut.approveAuth(authUrl, "/pub/bitkit.to/:rw", "paykit.test"), ).forEach { assertIs(it.exceptionOrNull()) } assertNull(sut.validExpectedSigner(authUrl)) - assertNull(sut.validExpectedSigner("pubkyauth://signin_grant?caps=/pub/bitkit.to/:rw")) - val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" - assertEquals(signer, sut.validExpectedSigner("pubkyauth://signin_grant?spk=$signer")) verifyBlocking(pubkyService, never()) { parseAuthUrl(any()) } verifyBlocking(pubkyService, never()) { approveAuth(any(), any(), any(), any()) } } + @Test + fun `validExpectedSigner names a pubky only for a request that parses in full`() = test { + val other = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + val authUrl = "pubkyauth://signin_grant?caps=/pub/locks.app/:rw&spk=$other" + val details = mock() + whenever(details.clientId).thenReturn("locks.test") + whenever(details.capabilities).thenReturn("/pub/locks.app/:rw") + whenever(details.relayUrl).thenReturn("https://relay.example/inbox/", "ftp://relay.example/inbox/") + whenever(pubkyService.parseAuthUrl(authUrl)).thenReturn(details) + + assertEquals(other, sut.validExpectedSigner(authUrl)) + assertNull(sut.validExpectedSigner(authUrl)) + assertIs(sut.parseAuthUrl(authUrl).exceptionOrNull()) + assertNull(sut.validExpectedSigner("pubkyauth://signin_grant?caps=/pub/locks.app/:rw")) + } + @Test fun `checkExpectedSigner fails for another pubky and passes for this one or none`() = test { val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt index 232e372dc0..881f49c1a9 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt @@ -28,6 +28,7 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.same import org.mockito.kotlin.times +import org.mockito.kotlin.verify import org.mockito.kotlin.verifyBlocking import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever @@ -55,6 +56,7 @@ import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertIs import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) @@ -476,6 +478,35 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { verifyBlocking(pubkyRepo, never()) { approveAuth(any(), any(), any()) } } + @Test + fun `invalid link naming another pubky shows the invalid link message`() = test { + val authUrl = "pubkyauth://signin_grant?caps=/pub/example/:rw&relay=ftp%3A%2F%2Frelay.example%2Finbox%2F" + + "&spk=5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + publicKeyFlow.value = "pubky8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + val invalidRelay = PubkyAuthRequest.parse( + rawUrl = authUrl, + clientId = clientId, + relay = "ftp://relay.example/inbox/", + capabilities = "/pub/example/:rw", + ) + assertIs(invalidRelay.exceptionOrNull()) + whenever(context.getString(R.string.profile__auth_error_invalid_url)).thenReturn("Invalid link") + whenever { pubkyRepo.parseAuthUrl(authUrl) }.thenReturn(invalidRelay) + val sut = createSut() + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + + sut.effects.test { + sut.load(authUrl) + advanceUntilIdle() + assertEquals(PubkyAuthApprovalEffect.Dismiss, awaitItem()) + } + + assertEquals("Invalid link", toasts.single().description) + verify(context, never()).getString(eq(R.string.profile__auth_error_other_pubky), any()) + toastJob.cancel() + } + @Test fun `request naming this pubky reaches consent and is approved`() = test { val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 2e7e57aade..87e6cdcd32 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5976,17 +5976,26 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } @Test - fun `pubky auth deeplink with an spk that is not a public key is not reported as another pubky`() = test { + fun `pubky auth deeplink that is invalid is not reported as meant for another pubky`() = test { enablePaykitUi() pubkyPublicKey.value = testPublicKey whenever(pubkyRepo.hasSecretKey()).thenReturn(true) - val authUrl = "pubkyauth://signin_grant?caps=/pub/paykit/v0/:rw&spk=ye${"y".repeat(50)}" - whenever(pubkyRepo.validExpectedSigner(authUrl)).thenReturn(null) + val invalidLinks = listOf( + "pubkyauth://signin_grant?caps=/pub/paykit/v0/:rw&spk=ye${"y".repeat(50)}", + "pubkyauth://signin_grant?caps=/pub/paykit/v0/:rw&relay=ftp%3A%2F%2Frelay.example%2Finbox%2F" + + "&spk=8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty", + ) - sut.handleDeeplinkIntent(Intent(Intent.ACTION_VIEW, authUrl.toUri())) - advanceUntilIdle() + invalidLinks.forEach { authUrl -> + whenever(pubkyRepo.validExpectedSigner(authUrl)).thenReturn(null) - assertEquals(Sheet.PubkyAuth(authUrl), sut.currentSheet.value) + sut.handleDeeplinkIntent(Intent(Intent.ACTION_VIEW, authUrl.toUri())) + advanceUntilIdle() + + assertEquals(Sheet.PubkyAuth(authUrl), sut.currentSheet.value) + sut.hideSheet() + advanceUntilIdle() + } verify(context, never()).getString(eq(R.string.profile__auth_error_other_pubky), any()) }