diff --git a/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt b/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt index e897b5cc61..862324639f 100644 --- a/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt +++ b/app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt @@ -139,7 +139,117 @@ data class PubkyAuthRequest( fun requiresIdentityCreation(hasIdentity: Boolean): Boolean = isSignup && (!isGrantSignup || !hasIdentity) + /** + * The relay URL that receives the authorization, without user info or fragment so the host cannot be disguised. + * This is a delivery destination, not a service identity. Null only when the request has no relay. + */ + val relayDisplayUrl: String? get() = displayRelay(relay) + companion object { + private val RELAY_SCHEMES = setOf("http", "https") + + /** A relay host as the Pubky SDK's URL parser would keep it, with an optional port. */ + private val RELAY_HOST_PORT = Regex("""(\[[0-9a-f:.]+]|[a-z0-9._~-]+)(:[0-9]{1,5})?""") + + /** A host label the SDK's URL parser reads as a number, which makes the whole host an IPv4 address. */ + private val NUMERIC_HOST_LABEL = Regex("[0-9]+|0x[0-9a-f]*") + + /** An IPv4 address in the only form the SDK's URL parser leaves unchanged. */ + private val CANONICAL_IPV4 = "(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])".let { Regex("""($it\.){3}$it""") } + + /** + * Characters the SDK's URL parser (rust-url 2.5.8, `url/src/parser.rs`) changes in the path of an http(s) URL: + * its `PATH` set percent-encodes them, and a backslash becomes a slash. + */ + private const val RELAY_PATH_REWRITTEN_CHARACTERS = "\\\"<>`{}" + + /** Characters the SDK's URL parser percent-encodes in the query of an http(s) URL (`SPECIAL_QUERY`). */ + private const val RELAY_QUERY_REWRITTEN_CHARACTERS = "\"<>'" + + /** Ports the SDK's URL parser drops because they are the scheme's default. */ + private val RELAY_DEFAULT_PORTS = mapOf("http" to 80, "https" to 443) + + /** Highest TCP port. */ + private const val MAX_PORT = 65535 + + /** Number of 16-bit groups in an IPv6 address. */ + private const val IPV6_GROUPS = 8 + + /** Highest value of one IPv6 group. */ + private const val MAX_IPV6_GROUP = 0xFFFF + + /** First code point past printable ASCII. */ + private const val DEL = 0x7F + + /** + * The relay as shown on the approval sheet: scheme, host, port, path and query, exactly as the Pubky SDK's URL + * parser keeps them. Null when [relay] is not already in that form apart from letter case, user info, the + * fragment and a missing root path: a space, control or non-ASCII characters, a backslash before the query, + * characters the parser percent-encodes in the path or in the query, a missing, percent-encoded or + * non-canonical host, a default, padded or out-of-range port, or a `.` or `..` path segment. + */ + fun displayRelay(relay: String): String? { + if (relay.any { it.code <= ' '.code || it.code >= DEL }) return null + val schemeEnd = relay.indexOf("://") + if (schemeEnd <= 0) return null + val scheme = relay.substring(0, schemeEnd).lowercase().takeIf { it in RELAY_SCHEMES } ?: return null + val rest = relay.substring(schemeEnd + "://".length) + val authorityEnd = rest.indexOfAny(charArrayOf('/', '?', '#')).takeIf { it >= 0 } ?: rest.length + val authority = rest.substring(0, authorityEnd) + val hostPort = authority.substringAfterLast('@').lowercase() + val pathAndQuery = rest.substring(authorityEnd).substringBefore('#') + val path = pathAndQuery.substringBefore('?') + val isRewritten = '\\' in authority || + path.any { it in RELAY_PATH_REWRITTEN_CHARACTERS } || + pathAndQuery.substringAfter('?', "").any { it in RELAY_QUERY_REWRITTEN_CHARACTERS } || + path.split('/').any { it.lowercase().replace("%2e", ".") in setOf(".", "..") } + if (isRewritten || !isUnchangedRelayHostPort(scheme, hostPort)) return null + val rootPath = if (pathAndQuery.startsWith("/")) "" else "/" + return "$scheme://$hostPort$rootPath$pathAndQuery" + } + + private fun isUnchangedRelayHostPort(scheme: String, hostPort: String): Boolean { + val (host, portSuffix) = RELAY_HOST_PORT.matchEntire(hostPort)?.destructured ?: return false + val port = portSuffix.removePrefix(":") + val isUnchangedPort = port.isEmpty() || port.toInt().let { + port == it.toString() && it <= MAX_PORT && it != RELAY_DEFAULT_PORTS[scheme] + } + if (!isUnchangedPort) return false + if (host.startsWith("[")) return isCanonicalIpv6(host.removeSurrounding("[", "]")) + val readsAsNumber = NUMERIC_HOST_LABEL.matches(host.removeSuffix(".").substringAfterLast('.')) + return !readsAsNumber || CANONICAL_IPV4.matches(host) + } + + private fun isCanonicalIpv6(address: String): Boolean { + val halves = address.split("::") + val head = halves[0].split(':').filter { it.isNotEmpty() } + val tail = halves.getOrNull(1)?.split(':')?.filter { it.isNotEmpty() }.orEmpty() + val missing = IPV6_GROUPS - head.size - tail.size + val isComplete = if (halves.size == 1) missing == 0 else halves.size == 2 && missing >= 1 + if (!isComplete || '.' in address) return false + val groups = (head + List(missing) { "0" } + tail).map { group -> + group.toIntOrNull(radix = 16)?.takeIf { it <= MAX_IPV6_GROUP } ?: return false + } + var runStart = -1 + var runLength = 0 + var index = 0 + while (index < groups.size) { + val end = (index until groups.size).firstOrNull { groups[it] != 0 } ?: groups.size + if (end - index > runLength) { + runStart = index + runLength = end - index + } + index = maxOf(end, index + 1) + } + val hex = { part: List -> part.joinToString(":") { it.toString(radix = 16) } } + val canonical = if (runLength < 2) { + hex(groups) + } else { + "${hex(groups.take(runStart))}::${hex(groups.drop(runStart + runLength))}" + } + return canonical == address + } + fun parse( rawUrl: String, clientId: String, @@ -148,7 +258,10 @@ data class PubkyAuthRequest( homeserverPublicKey: String? = null, signupToken: String? = null, authorizationUrl: String? = rawUrl, - ): Result = parseBitkitClaim(rawUrl, capabilities).map { bitkitClaim -> + ): Result = parseBitkitClaim(rawUrl, capabilities).mapCatching { bitkitClaim -> + if (relay.isNotEmpty() && displayRelay(relay) == null) { + throw PubkyAuthRequestError.InvalidUrl(IllegalArgumentException("Unreadable Pubky auth relay")) + } val permissions = parseCapabilities(capabilities) PubkyAuthRequest( rawUrl = rawUrl, diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt index 4dce36fa08..3621d40178 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt @@ -19,7 +19,9 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.Switch import androidx.compose.runtime.Composable @@ -516,13 +518,16 @@ private fun ColumnScope.ApprovalDetails( BodyM(text = stringResource(R.string.profile__auth_approval_usdt_disabled), color = Colors.White64) VerticalSpacer(24.dp) } + val showsPaykitAccess = uiState.bitkitClaim?.includesPaykitAccess == true if (uiState.permissions.isNotEmpty()) { PermissionsSection(permissions = uiState.permissions) + if (uiState.relayUrl != null || showsPaykitAccess) SectionDivider() } - if (uiState.bitkitClaim?.includesPaykitAccess == true) { - VerticalSpacer(32.dp) - PaykitAccessSection() + uiState.relayUrl?.let { + RelaySection(relayUrl = it) + if (showsPaykitAccess) SectionDivider() } + if (showsPaykitAccess) PaykitAccessSection() } Column { @@ -671,6 +676,31 @@ private fun PermissionsSection(permissions: ImmutableList) } } +@Composable +private fun RelaySection(relayUrl: String) { + Section(title = stringResource(R.string.profile__auth_approval_relay)) { + Row(modifier = Modifier.fillMaxWidth()) { + Icon( + painter = painterResource(R.drawable.ic_globe), + contentDescription = null, + tint = Colors.White, + modifier = Modifier + .padding(top = 2.dp) + .size(16.dp) + ) + HorizontalSpacer(4.dp) + SelectionContainer(modifier = Modifier.weight(1f)) { + BodySSB(text = relayUrl.asLiteralRequestText(), modifier = Modifier.testTag("PubkyAuthRelayOrigin")) + } + } + } +} + +@Composable +private fun SectionDivider() { + HorizontalDivider(color = Colors.White10, modifier = Modifier.padding(vertical = 12.dp)) +} + @Composable private fun PermissionRow(permission: PubkyAuthPermission) { Row( @@ -824,6 +854,7 @@ private fun AuthorizePreview() { permissions = persistentListOf( PubkyAuthPermission(path = "/pub/paykit/", accessLevel = "rw"), ), + relayUrl = "https://httprelay.pubky.app/inbox/", bitkitClaim = PubkyAuthClaim(Item.PAYKIT_ACCESS_V1, Item.WATCH_ONLY_ACCOUNT_V1), profile = PubkyProfile( publicKey = "pk8e3qm5f4kgczagxhertyuiop1gxag", 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..43eab4bc19 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 @@ -129,6 +129,7 @@ class PubkyAuthApprovalViewModel @Inject constructor( createsIdentity = request.requiresIdentityCreation(identityPublicKey != null), serviceName = serviceName, permissions = request.permissions.toImmutableList(), + relayUrl = request.relayDisplayUrl, bitkitClaim = request.bitkitClaim, profile = profile, isUsdtEnabled = usdtEnabled, @@ -241,7 +242,7 @@ class PubkyAuthApprovalViewModel @Inject constructor( val approvalState = _uiState.value if (approvalState.authUrl != authUrl) return if (request.bitkitClaim != approvalState.bitkitClaim || request.clientId != approvalState.clientId || - request.permissions != approvalState.permissions + request.permissions != approvalState.permissions || request.relayDisplayUrl != approvalState.relayUrl ) { handleApprovalFailure(PubkyAuthRequestError.RequesterChanged, authUrl) return @@ -442,6 +443,7 @@ data class PubkyAuthApprovalUiState( val createsIdentity: Boolean = false, val serviceName: String = "", val permissions: ImmutableList = persistentListOf(), + val relayUrl: String? = null, val bitkitClaim: PubkyAuthClaim? = null, val profile: PubkyProfile? = null, val usdtAddress: String? = null, diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 77614b84c1..dbd3e3f193 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -576,6 +576,7 @@ إضافة علامة التفاصيل حسنًا + المُرحّل إنشاء ملف شخصي الملف الشخصي حاول مرة أخرى 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..5a7f97e704 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -586,6 +586,7 @@ Añadir etiqueta Autorizar Detalles + Relay Autorizar Crear perfil Editar Perfil diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index d6d4a9f2cb..20d17a1ca8 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 + Relé 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..484ee1185c 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -586,6 +586,7 @@ Vložit tag Autorizovat Podrobnosti + Relay Autorizovat Vytvořit profil Upravit profil diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index b596372ffc..3d3f2601be 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -567,6 +567,7 @@ Beachte: Jeder Link den du hinzufügst ist öffentlich sichtbar. Tag hinzufügen Autorisieren Sie + Relay Autorisieren Sie Profil erstellen Profil bearbeiten diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 42a34f22fe..45d36d4d19 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -576,6 +576,7 @@ Προσθήκη ετικέτας Λεπτομέρειες ΟΚ + Αναμεταδότης Δημιουργία προφίλ Προφίλ Προσπαθήστε Ξανά diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 6dc0e1e3d2..754cb077d2 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 + Relé 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..8d37814c6c 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 + Relé 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..b04e6e88f7 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -567,6 +567,7 @@ Ajouter une étiquette Autoriser Détails + Relais Autoriser Créer un profil Modifier le profil diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 93b5988584..04918a0c4a 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 + Relay 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..201cb5da6d 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 + Relay 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..2466d0d9cc 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -567,6 +567,7 @@ Dodaj tag Autoryzuj Szczegóły + Przekaźnik Autoryzuj Utwórz profil Edytuj 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..e2bcb1ee8a 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -587,6 +587,7 @@ Adicionar Tag Autorizar Detalhes + Relay Autorizar Criar Perfil Editar perfil diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index fe167db418..1c29b32ec8 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 + Relay 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..d63bc13ada 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -598,6 +598,7 @@ Авторизовать Подробности Ок + Ретранслятор Авторизовать Создать Профиль Редактировать Профиль diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 47968335dd..f5c1d89855 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -792,6 +792,7 @@ OK This service will manage your private Paykit data and send Paykit messages for you. Your pubky secret and wallet keys stay private. Requested permissions + Relay A service is requesting permission to access and edit your <accent>%1$s</accent> data. <accent>%1$s</accent> is requesting permission to access and edit your <accent>%2$s</accent> data. Unknown service diff --git a/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt b/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt index 0339f19820..fb0549e490 100644 --- a/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt +++ b/app/src/test/java/to/bitkit/models/PubkyAuthRequestTest.kt @@ -207,6 +207,160 @@ class PubkyAuthRequestTest { assertEquals(PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1), request.bitkitClaim) } + @Test + fun `relay display url keeps the path and drops user info and fragment`() { + val origins = mapOf( + "https://Relay.Example:8443/inbox/" to "https://relay.example:8443/inbox/", + "https://httprelay.pubky.app/link" to "https://httprelay.pubky.app/link", + "https://httprelay.pubky.app" to "https://httprelay.pubky.app/", + "HTTPS://httprelay.pubky.app/link" to "https://httprelay.pubky.app/link", + "http://localhost:8080/link" to "http://localhost:8080/link", + "https://relay.example:0/link" to "https://relay.example:0/link", + "https://relay.example:80/link" to "https://relay.example:80/link", + "https://evil.example?@relay.example" to "https://evil.example/?@relay.example", + "https://relay.example/?x=@evil.example" to "https://relay.example/?x=@evil.example", + "https://evil.example#@relay.example" to "https://evil.example/", + "https://relay.example/a/.../b/..c/" to "https://relay.example/a/.../b/..c/", + "https://relay.example/inbox?next=../x" to "https://relay.example/inbox?next=../x", + "https://[::1]/link" to "https://[::1]/link", + "http://[::1]:443/" to "http://[::1]:443/", + "https://relay.example:65535/link" to "https://relay.example:65535/link", + "https://[2001:DB8::1]/link" to "https://[2001:db8::1]/link", + "https://[::ffff:102:304]/link" to "https://[::ffff:102:304]/link", + "https://relay.example/a/..;x" to "https://relay.example/a/..;x", + "https://relay.example/a/..%2f" to "https://relay.example/a/..%2f", + "https://[2001:db8:0:1::]/link" to "https://[2001:db8:0:1::]/link", + "http://user@10.0.2.2:15412/link?x=1#y" to "http://10.0.2.2:15412/link?x=1", + "https://trusted.example@relay.example/in%20box/" to "https://relay.example/in%20box/", + "https://relay.example/a|b?c=[e]" to "https://relay.example/a|b?c=[e]", + "https://relay.example/o'neil/inbox/" to "https://relay.example/o'neil/inbox/", + "https://relay.example/a^b/[c]" to "https://relay.example/a^b/[c]", + "https://relay.example/inbox/?x={y}" to "https://relay.example/inbox/?x={y}", + "https://relay.example/inbox/?x=a^b|c" to "https://relay.example/inbox/?x=a^b|c", + "https://relay.example/inbox/?x=a`b" to "https://relay.example/inbox/?x=a`b", + "https://relay.example/inbox/?x=a\\b" to "https://relay.example/inbox/?x=a\\b", + "https://relay.example?x={y}" to "https://relay.example/?x={y}", + "https://us'er:pa{ss}@relay.example/inbox/" to "https://relay.example/inbox/", + "https://relay.example/inbox/#a\"b'\\" to "https://relay.example/inbox/", + "https://relay.example?x=1" to "https://relay.example/?x=1", + "https://relay.example./link" to "https://relay.example./link", + "https://-re_lay~.1abc/link" to "https://-re_lay~.1abc/link", + "https://xn--e1aybc.example/link" to "https://xn--e1aybc.example/link", + "https://[2001:DB8::1]:8443/link" to "https://[2001:db8::1]:8443/link", + "https://127.0.0.1/link" to "https://127.0.0.1/link", + "https://evil.example/@httprelay.pubky.app/link" to "https://evil.example/@httprelay.pubky.app/link", + ) + + origins.forEach { (relay, origin) -> + assertEquals(origin, PubkyAuthRequest.displayRelay(relay), relay) + val request = PubkyAuthRequest.parse( + rawUrl = authUrl("/pub/example.app/:rw"), + clientId = "example.app", + relay = relay, + capabilities = "/pub/example.app/:rw", + ).getOrThrow() + + assertEquals(origin, request.relayDisplayUrl, relay) + } + } + + @Test + fun `relay whose destination cannot be read with certainty makes the request invalid`() { + val unreadable = listOf( + "https://evil.example\\@httprelay.pubky.app/link", + "https://httprelay.pubky.app\\.evil.example/link", + "https://реле.example/link", + "https://%65vil.example/link", + "https://0x7f.1/link", + "https://2130706433/link", + "https://1.2.3/link", + "https://127.0.0.1./link", + "https://relay.example /link", + "https://relay\t.example/link", + "https://relay.example:/link", + "https://relay.example\n/link", + "https://relay.example:443/link", + "http://relay.example:80/link", + "https://relay.example:65536/link", + "https://relay.example:08443/link", + "https://relay.example/inbox/../../other/", + "https://relay.example/inbox/./x", + "https://relay.example/inbox/%2e%2e/other/", + "https://relay.example/inbox/%2E./other/", + "https://relay.example/inbox/..", + "https://relay.example/..?x=1", + "https://relay.example/a{b}", + "https://relay.example/a?b='c'", + "https://relay.example/a\"b", + "https://relay.example/a}b", + "https://relay.example/a\\b", + "https://relay.example/a/\\..\\b", + "https://user\\@relay.example/inbox/", + "https://relay.example/inbox/?x=\"y\"", + "https://relay.example/inbox/?x=", + "https://relay.example/inbox/?x='y", + "https://relay.example/inbox/?x=a b", + "https://relay.example/ab", + "https://relay.example/a`b", + "https://relay.example/inbox/%2e/x", + "https://relay.example/inbox/.%2E/other/", + "https://[::1]:443/", + "https://[2001:db8:0:0:0:0:0:1]/link", + "https://[2001:0db8::1]/link", + "https://[1:0:0:2:0:0:0:3]/link", + "https://[::ffff:1.2.3.4]/link", + "https://[1::2::3]/link", + "https://[::12345]/link", + "https://[1:2:3:4:5:6:7:8:9]/link", + "https:///inbox/", + "https:/relay.example/inbox/", + "https:relay.example/inbox/", + "ftp://relay.example/inbox/", + "relay.example/inbox/", + "not a url", + ) + + unreadable.forEach { relay -> + assertNull(PubkyAuthRequest.displayRelay(relay), relay) + assertIs( + PubkyAuthRequest.parse( + rawUrl = authUrl("/pub/example.app/:rw"), + clientId = "example.app", + relay = relay, + capabilities = "/pub/example.app/:rw", + ).exceptionOrNull(), + relay, + ) + } + } + + @Test + fun `relay is shown whenever a request has one`() { + val withoutRelay = PubkyAuthRequest.parseSignup(directSignupUrl("direct_signup")).getOrThrow() + val ringSignup = PubkyAuthRequest.parseSignup(ringSignupUrl()).getOrThrow() + + assertEquals("", withoutRelay.relay) + assertNull(withoutRelay.relayDisplayUrl) + assertEquals("https://relay.example/inbox/", ringSignup.relayDisplayUrl) + assertIs( + PubkyAuthRequest.parseSignup( + ringSignupUrl().replace("relay.example", "evil.example%5C%40relay.example"), + ).exceptionOrNull(), + ) + assertIs( + PubkyAuthRequest.parseSignup(ringSignupUrl().replace("relay.example", "rel%C3%A4y.example")) + .exceptionOrNull(), + ) + listOf("inbox%2F..%2F..%2Fother%2F", "inbox%2F%252e%252e%2Fother%2F").forEach { + assertIs( + PubkyAuthRequest.parseSignup(ringSignupUrl().replace("inbox%2F", it)).exceptionOrNull(), + it, + ) + } + } + @Test fun `matcher recognizes the Paykit scope with surrounding whitespace`() { val capabilities = " ${PubkyAuthClaim.REQUIRED_CAPABILITIES} " 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..501a0718e2 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 @@ -314,6 +317,32 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { verifyBlocking(pubkyRepo, never()) { approveAuth(authUrl, capabilities, clientId) } } + @Test + fun `confirmAuthorize fails closed when the relay differs from the one shown`() = test { + val authUrl = "pubkyauth://signin?caps=/pub/current/:rw" + val capabilities = "/pub/current/:rw" + val shown = authRequest(authUrl, capabilities) + whenever(context.getString(R.string.profile__auth_error_invalid_url)).thenReturn("Invalid link") + whenever { pubkyRepo.parseAuthUrl(authUrl) }.thenReturn( + Result.success(shown), + Result.success(shown.copy(relay = "https://evil.example/inbox/")), + ) + val sut = createSut() + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + + sut.load(authUrl) + advanceUntilIdle() + assertEquals("https://httprelay.pubky.app/inbox/", sut.uiState.value.relayUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + assertEquals(ApprovalState.Authorize, sut.uiState.value.state) + assertEquals("Invalid link", toasts.single().description) + verifyBlocking(pubkyRepo, never()) { approveAuth(any(), any(), any()) } + toastJob.cancel() + } + @Test fun `ordinary authorization uses the requested capabilities`() = test { val authUrl = "pubkyauth://signin?caps=/pub/example/:rw" @@ -331,6 +360,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { assertEquals(ApprovalState.Success, sut.uiState.value.state) assertEquals(clientId, sut.uiState.value.clientId) + assertEquals("https://httprelay.pubky.app/inbox/", sut.uiState.value.relayUrl) verifyBlocking(pubkyRepo) { approveAuth(authUrl, capabilities, clientId) } verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any()) } diff --git a/changelog.d/next/1505.fixed.md b/changelog.d/next/1505.fixed.md new file mode 100644 index 0000000000..2573b8e0bd --- /dev/null +++ b/changelog.d/next/1505.fixed.md @@ -0,0 +1 @@ +Fixed the Pubky authorization screen not showing which relay receives the authorization. diff --git a/journeys/pubky-auth/signin-cold-start.xml b/journeys/pubky-auth/signin-cold-start.xml index 1cb4cfff0b..23eed52b12 100644 --- a/journeys/pubky-auth/signin-cold-start.xml +++ b/journeys/pubky-auth/signin-cold-start.xml @@ -15,6 +15,7 @@ Verify a toast with a spinner reads Loading Your Pubky Profile (screenshot; toasts are not in the layout) Verify the toast stays until the authorization sheet opens Verify the authorization sheet shows the requesting app and permissions + Verify the relay origin (id "PubkyAuthRelayOrigin") shows the link's relay URL with its path, for example "https://httprelay.pubky.app/inbox/" for relay=https%3A%2F%2Fhttprelay.pubky.app%2Finbox%2F, next to a globe icon under the RELAY label and below the requested permissions Tap Authorize (id "PubkyAuthAuthorize") and complete PIN or biometric approval when enabled Verify the authorization success state is shown (id "PubkyAuthOK") Verify the requesting app receives approval from the recorded public key