diff --git a/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt b/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt index 862324639f..2201a91bd2 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) @@ -146,6 +148,48 @@ data class PubkyAuthRequest( val relayDisplayUrl: String? get() = displayRelay(relay) 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. 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) + 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 + } + private val RELAY_SCHEMES = setOf("http", "https") /** A relay host as the Pubky SDK's URL parser would keep it, with an optional port. */ @@ -259,6 +303,7 @@ data class PubkyAuthRequest( signupToken: String? = null, authorizationUrl: String? = rawUrl, ): Result = parseBitkitClaim(rawUrl, capabilities).mapCatching { bitkitClaim -> + val expectedSigner = parseExpectedSigner(rawUrl).getOrThrow() if (relay.isNotEmpty() && displayRelay(relay) == null) { throw PubkyAuthRequestError.InvalidUrl(IllegalArgumentException("Unreadable Pubky auth relay")) } @@ -274,6 +319,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 179cc78d25..8339f47316 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -2054,6 +2054,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( @@ -2148,6 +2149,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) } } @@ -2165,6 +2167,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, @@ -2179,6 +2182,37 @@ 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) + } + } + + /** + * 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 + runSuspendCatching { pubkyService.validatePublicKey(expectedSigner) } + .onFailure { throw PubkyAuthRequestError.InvalidUrl(it) } + return expectedSigner + } + + private suspend fun requireExpectedSigner(authUrl: String, secretKeyHex: String) { + val expectedSigner = validatedExpectedSigner(authUrl) ?: 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/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt index 180195c2fd..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,6 +148,12 @@ 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 { + normalizePubkyPublicKey(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 43eab4bc19..7af36f1a84 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( @@ -279,6 +293,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/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/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 99ac5938bf..b065b7c093 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -160,6 +160,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 @@ -10866,6 +10867,20 @@ class AppViewModel @Inject constructor( return } + val expectedSigner = pubkyRepo.validExpectedSigner(authUrl) + 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/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 9d924d424c..17bb97e0b7 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -578,6 +578,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 1a34813d52..da3d0d5778 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -589,6 +589,7 @@ Detalles Relay 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 e3c61d1f6b..af2922ed0b 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -584,6 +584,7 @@ Afegeix etiqueta Detalls Relé + 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 08e3f4e0ba..e5852bc410 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -589,6 +589,7 @@ Podrobnosti Relay 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 f581cb4e47..572673cfd9 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -570,6 +570,7 @@ Autorisieren Sie Relay 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 407620fe7b..6a659ccecc 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -578,6 +578,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 8f6b099259..8218db0103 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -586,6 +586,7 @@ Añadir etiqueta Detalles Relé + 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 c9cde21e6c..987c70b3e7 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -583,6 +583,7 @@ Añadir etiqueta Detalles Relé + 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 fcded2e9ee..2e7ceb57bf 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -570,6 +570,7 @@ Détails Relais 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 50054093a9..cba43f4d52 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -585,6 +585,7 @@ Aggiungi Tag Dettagli Relay + 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 e02cec70ed..e8e9059392 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -583,6 +583,7 @@ Let op: Iedere link die u toevoegt is openbaar beschikbaar. Tag toevoegen Relay + 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 eebe825ac9..2f2320716a 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -570,6 +570,7 @@ Szczegóły Przekaźnik 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 1371e4cb0d..8f731539ad 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -590,6 +590,7 @@ Detalhes Relay 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 e5ade6138e..178ea06831 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -548,6 +548,7 @@ Adicionar Tag Detalhes Relay + 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 e420f72581..dffd42f24c 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -601,6 +601,7 @@ Ок Ретранслятор Авторизовать + Этот запрос предназначен для %1$s, а не для pubky этого кошелька. Создать Профиль Редактировать Профиль Профиль diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8e99f5fa34..2599ffa933 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -825,6 +825,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 fb0549e490..3b76d26433 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`() { @@ -361,6 +365,118 @@ class PubkyAuthRequestTest { } } + @Test + fun `grant sign-in reads the pubky it must be approved with`() { + 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()) + + 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 `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( + "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} " @@ -597,6 +713,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..2aeda45520 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,124 @@ 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 `expected signer that is not a public key makes the request invalid and is never signed`() = test { + 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") } + + listOf( + sut.parseAuthUrl(authUrl), + sut.checkExpectedSigner(authUrl), + sut.approveAuth(authUrl, "/pub/bitkit.to/:rw", "paykit.test"), + ).forEach { assertIs(it.exceptionOrNull()) } + assertNull(sut.validExpectedSigner(authUrl)) + 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" + 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 501a0718e2..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 @@ -38,6 +39,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 @@ -54,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) @@ -366,6 +369,167 @@ 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 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 `expected signer and relay rules hold together`() = test { + val signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + val other = "5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + val relay = "https://httprelay.pubky.app/inbox/o'connor?token={abc}" + val capabilities = "/pub/example/:rw" + val matchingUrl = "pubkyauth://signin_grant?caps=/pub/example/:rw&spk=$signer" + val otherUrl = "pubkyauth://signin_grant?caps=/pub/example/:rw&spk=$other" + 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.") + listOf(matchingUrl to signer, otherUrl to other).forEach { (url, expectedSigner) -> + val request = PubkyAuthRequest.parse( + rawUrl = url, + clientId = clientId, + relay = relay, + capabilities = capabilities, + ).getOrThrow() + assertEquals(expectedSigner, request.expectedSigner) + assertEquals(relay, request.relayDisplayUrl) + whenever { pubkyRepo.parseAuthUrl(url) }.thenReturn(Result.success(request)) + } + val sut = createSut() + + sut.load(matchingUrl) + advanceUntilIdle() + assertEquals(ApprovalState.Authorize, sut.uiState.value.state) + assertEquals(relay, sut.uiState.value.relayUrl) + + sut.effects.test { + sut.load(otherUrl) + advanceUntilIdle() + assertEquals(PubkyAuthApprovalEffect.Dismiss, awaitItem()) + sut.confirmAuthorize(otherUrl) + advanceUntilIdle() + expectNoEvents() + } + assertEquals(ApprovalState.Loading, sut.uiState.value.state) + 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" + 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)) + whenever { pubkyRepo.checkExpectedSigner(authUrl) }.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/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 8f81c28343..87e6cdcd32 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -5957,6 +5957,48 @@ 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" + whenever(pubkyRepo.validExpectedSigner(authUrl)) + .thenReturn("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 `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 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", + ) + + invalidLinks.forEach { authUrl -> + whenever(pubkyRepo.validExpectedSigner(authUrl)).thenReturn(null) + + 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()) + } + @Test fun `cold pubky auth deeplink waits for settings identity and wallet unlock`() = test { val initialized = CompletableDeferred() 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 71d15acf0e..6cef03849f 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -183,6 +183,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..c28a8fd007 --- /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...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 + 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 + +