From 56e576a58ee5188cdfd960ff3d3ccdb0b1d9b8c1 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 11 Nov 2026 18:35:17 +0000 Subject: [PATCH] Proxy TLS trust UI and isolated connectivity checks Show certificate issues in proxy checks, prompt to trust with persistent or session-only pins, and add trusted-certificate management. Isolate health checks from the active route and remove the App settings category label. Co-authored-by: denis0001-dev --- .../ru/fromchat/api/ApiClient.android.kt | 6 +- .../network/proxy/ProxyEngine.android.kt | 1 + .../network/proxy/ProxyTlsEngine.android.kt | 62 ++++++++ .../composeResources/values-ru/strings.xml | 8 + .../composeResources/values/strings.xml | 8 + .../ru/fromchat/network/proxy/ProxyChecker.kt | 49 +++++- .../ru/fromchat/network/proxy/ProxyModels.kt | 1 + .../ru/fromchat/network/proxy/ProxyRuntime.kt | 17 ++- .../fromchat/network/proxy/ProxyTlsEngine.kt | 7 + .../fromchat/network/proxy/ProxyTlsErrors.kt | 22 +++ .../fromchat/network/proxy/ProxyTlsTrust.kt | 120 +++++++++++++++ .../ui/main/nav/MainDetailDestinations.kt | 12 ++ .../ui/main/settings/SettingsRoutes.kt | 1 + .../fromchat/ui/main/settings/SettingsTab.kt | 1 - .../ui/main/settings/proxy/ProxyScreen.kt | 87 ++++++++++- .../proxy/ProxyTrustCertificateDialog.kt | 88 +++++++++++ .../proxy/TrustedCertificatesScreen.kt | 143 ++++++++++++++++++ .../kotlin/ru/fromchat/api/ApiClient.ios.kt | 6 +- .../network/proxy/ProxyTlsEngine.ios.kt | 7 + .../kotlin/ru/fromchat/api/ApiClient.jvm.kt | 6 +- .../fromchat/network/proxy/ProxyEngine.jvm.kt | 3 +- .../network/proxy/ProxyTlsEngine.jvm.kt | 114 ++++++++++++++ 22 files changed, 754 insertions(+), 15 deletions(-) create mode 100644 app/shared/src/androidMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.android.kt create mode 100644 app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.kt create mode 100644 app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsErrors.kt create mode 100644 app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsTrust.kt create mode 100644 app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/ProxyTrustCertificateDialog.kt create mode 100644 app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/TrustedCertificatesScreen.kt create mode 100644 app/shared/src/iosMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.ios.kt create mode 100644 app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.jvm.kt diff --git a/app/shared/src/androidMain/kotlin/ru/fromchat/api/ApiClient.android.kt b/app/shared/src/androidMain/kotlin/ru/fromchat/api/ApiClient.android.kt index c3881b7..ef29cc0 100644 --- a/app/shared/src/androidMain/kotlin/ru/fromchat/api/ApiClient.android.kt +++ b/app/shared/src/androidMain/kotlin/ru/fromchat/api/ApiClient.android.kt @@ -18,7 +18,11 @@ actual fun createPlatformHttpClient( connectTimeoutMillis = 5_000 socketTimeoutMillis = 30_000 } - val route = proxyRoute ?: ProxyRuntime.currentRoute + val route = when { + proxyRoute != null -> proxyRoute + ProxyRuntime.probeIsolation -> ProxyRoute.Direct + else -> ProxyRuntime.currentRoute + } configureEngineProxy(this, route) block() } diff --git a/app/shared/src/androidMain/kotlin/ru/fromchat/network/proxy/ProxyEngine.android.kt b/app/shared/src/androidMain/kotlin/ru/fromchat/network/proxy/ProxyEngine.android.kt index 5189b00..97096f7 100644 --- a/app/shared/src/androidMain/kotlin/ru/fromchat/network/proxy/ProxyEngine.android.kt +++ b/app/shared/src/androidMain/kotlin/ru/fromchat/network/proxy/ProxyEngine.android.kt @@ -7,6 +7,7 @@ import java.net.InetSocketAddress import java.net.Proxy actual fun configureEngineProxy(config: HttpClientConfig<*>, route: ProxyRoute) { + configureEngineTls(config) val javaProxy = when (route) { ProxyRoute.Direct, ProxyRoute.System -> return is ProxyRoute.Custom -> when (route.endpointType) { diff --git a/app/shared/src/androidMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.android.kt b/app/shared/src/androidMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.android.kt new file mode 100644 index 0000000..a7c9416 --- /dev/null +++ b/app/shared/src/androidMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.android.kt @@ -0,0 +1,62 @@ +package ru.fromchat.network.proxy + +import io.ktor.client.HttpClientConfig +import io.ktor.client.engine.okhttp.OkHttpConfig +import ru.fromchat.config.ServerConfig +import java.security.KeyStore +import java.security.cert.CertificateException +import java.security.cert.X509Certificate +import java.util.Base64 +import javax.net.ssl.SSLContext +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.X509TrustManager + +actual fun configureEngineTls(config: HttpClientConfig<*>) { + val trustManager = androidProxyPinningTrustManager() + val sslContext = SSLContext.getInstance("TLS").apply { + init(null, arrayOf(trustManager), null) + } + config.engine { + (this as? OkHttpConfig)?.config { + sslSocketFactory(sslContext.socketFactory, trustManager) + } + } +} + +actual suspend fun fetchPeerCertificatePem(route: ProxyRoute): String? = null + +private fun androidProxyPinningTrustManager(): X509TrustManager { + val delegate = defaultAndroidTrustManager() + val apiHost = tlsHostFromUrl(ServerConfig.apiBaseUrl) + return object : X509TrustManager { + override fun checkClientTrusted(chain: Array?, authType: String?) { + delegate.checkClientTrusted(chain, authType) + } + + override fun getAcceptedIssuers(): Array = delegate.acceptedIssuers + + override fun checkServerTrusted(chain: Array?, authType: String?) { + try { + delegate.checkServerTrusted(chain, authType) + } catch (e: CertificateException) { + val leaf = chain?.firstOrNull() ?: throw e + val pem = androidCertificateToPem(leaf) + if (ProxyTlsTrust.extraPemForHost(apiHost).any { it.trim() == pem.trim() }) { + return + } + throw e + } + } + } +} + +private fun defaultAndroidTrustManager(): X509TrustManager { + val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + factory.init(null as KeyStore?) + return factory.trustManagers.filterIsInstance().first() +} + +private fun androidCertificateToPem(certificate: X509Certificate): String { + val encoded = Base64.getMimeEncoder(64, "\n".toByteArray()).encodeToString(certificate.encoded) + return "-----BEGIN CERTIFICATE-----\n$encoded\n-----END CERTIFICATE-----" +} diff --git a/app/shared/src/commonMain/composeResources/values-ru/strings.xml b/app/shared/src/commonMain/composeResources/values-ru/strings.xml index 0605f96..37e7c17 100644 --- a/app/shared/src/commonMain/composeResources/values-ru/strings.xml +++ b/app/shared/src/commonMain/composeResources/values-ru/strings.xml @@ -357,6 +357,14 @@ Удалить %1$d мс Недоступно + Проблема с сертификатом + Доверять этому сертификату? + TLS-сертификат сервера не подписан доверенным центром. Продолжайте только если узнаёте этот сервер. + Да + Только сейчас + Доверенные сертификаты + Нет сохранённых доверенных сертификатов + Доверенные сертификаты Как FromChat подключается к серверу по защищённому каналу. Тип прокси HTTP, SOCKS5 или SSH-туннель как SOCKS. diff --git a/app/shared/src/commonMain/composeResources/values/strings.xml b/app/shared/src/commonMain/composeResources/values/strings.xml index fd76a73..06e8a76 100644 --- a/app/shared/src/commonMain/composeResources/values/strings.xml +++ b/app/shared/src/commonMain/composeResources/values/strings.xml @@ -388,6 +388,14 @@ Delete %1$d ms Unreachable + Certificate issue + Trust this certificate? + The server TLS certificate is not signed by a trusted authority. Only continue if you recognize this server. + Yes + This time only + Trusted certificates + No trusted certificates saved + Trusted certificates Choose how FromChat reaches your server over an encrypted link. Proxy type HTTP, SOCKS5, or an SSH tunnel that acts like SOCKS. diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyChecker.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyChecker.kt index 2a8dd4c..f71d412 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyChecker.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyChecker.kt @@ -7,6 +7,7 @@ import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit +import ru.fromchat.api.ApiClient import ru.fromchat.api.createProbeHttpClient import ru.fromchat.api.schema.server.ServerInstanceIdResponse import ru.fromchat.config.ServerConfig @@ -76,11 +77,16 @@ object ProxyChecker { } } - private suspend fun checkWithRoute(route: ProxyRoute): ProxyCheckResult { + private suspend fun checkWithRoute(route: ProxyRoute): ProxyCheckResult = + ProxyRuntime.withProbeIsolation { + performCheckWithRoute(route) + } + + private suspend fun performCheckWithRoute(route: ProxyRoute): ProxyCheckResult { val mark = TimeSource.Monotonic.markNow() + val base = ServerConfig.apiBaseUrl.trimEnd('/') val client = createProbeHttpClient(proxyRoute = route, bypassHttpProxyForCalls = false) return try { - val base = ServerConfig.apiBaseUrl.trimEnd('/') val instanceId = client.get("$base/instance_id").body().instanceId.trim() if (instanceId.isEmpty()) { ProxyCheckResult.Failed("Empty instance id") @@ -91,9 +97,46 @@ object ProxyChecker { ) } } catch (e: Exception) { - ProxyCheckResult.Failed(e.message) + if (e.isCertificateError()) { + val host = tlsHostFromUrl(base) + val pem = fetchPeerCertificatePem(route).orEmpty() + if (pem.isNotEmpty() && ProxyTlsTrust.hasTrustForPem(host, pem)) { + client.close() + val retryClient = createProbeHttpClient(proxyRoute = route, bypassHttpProxyForCalls = false) + return try { + val instanceId = retryClient.get("$base/instance_id").body() + .instanceId.trim() + if (instanceId.isEmpty()) { + ProxyCheckResult.Failed("Empty instance id") + } else { + ProxyCheckResult.Success( + pingMs = mark.elapsedNow().inWholeMilliseconds.toInt(), + instanceId = instanceId, + ) + } + } catch (retry: Exception) { + if (retry.isCertificateError()) { + ProxyCheckResult.CertificateIssue( + pem = pem, + detail = retry.message, + ) + } else { + ProxyCheckResult.Failed(retry.message) + } + } finally { + retryClient.close() + } + } + ProxyCheckResult.CertificateIssue(pem = pem, detail = e.message) + } else { + ProxyCheckResult.Failed(e.message) + } } finally { client.close() } } + + fun notifyTlsTrustChanged() { + ApiClient.rebuildHttpClients() + } } diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyModels.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyModels.kt index 0590b5e..d2fed3a 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyModels.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyModels.kt @@ -85,4 +85,5 @@ sealed class ProxyCheckResult { data object Checking : ProxyCheckResult() data class Success(val pingMs: Int, val instanceId: String) : ProxyCheckResult() data class Failed(val reason: String? = null) : ProxyCheckResult() + data class CertificateIssue(val pem: String, val detail: String? = null) : ProxyCheckResult() } diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyRuntime.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyRuntime.kt index 25c6007..863f96e 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyRuntime.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyRuntime.kt @@ -8,6 +8,18 @@ import kotlinx.coroutines.sync.withLock import ru.fromchat.api.ApiClient object ProxyRuntime { + @Volatile + var probeIsolation: Boolean = false + + suspend fun withProbeIsolation(block: suspend () -> T): T { + probeIsolation = true + try { + return block() + } finally { + probeIsolation = false + } + } + private val applyMutex = Mutex() private val _selection = MutableStateFlow(ProxySelection.Direct) @@ -43,6 +55,9 @@ object ProxyRuntime { suspend fun applySelection(selection: ProxySelection) { applyMutex.withLock { stopSshTunnel() + if (_selection.value != selection) { + ProxyTlsTrust.clearSession() + } _selection.value = selection ProxyStore.setSelection(selection) refreshEffectiveRoute(startTunnel = true) @@ -169,7 +184,7 @@ object ProxyRuntime { } suspend fun routeForCheckTarget(target: ProxyCheckTarget): ProxyRoute? = when (target) { - ProxyCheckTarget.ActiveSelection -> currentRoute + ProxyCheckTarget.ActiveSelection -> ProxyRoute.Direct is ProxyCheckTarget.SavedProxyById -> { val proxy = ProxyStore.readProxies().firstOrNull { it.id == target.id } ?: return null ephemeralRouteForProxy(proxy) diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.kt new file mode 100644 index 0000000..aacaeb8 --- /dev/null +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.kt @@ -0,0 +1,7 @@ +package ru.fromchat.network.proxy + +import io.ktor.client.HttpClientConfig + +expect fun configureEngineTls(config: HttpClientConfig<*>) + +expect suspend fun fetchPeerCertificatePem(route: ProxyRoute): String? diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsErrors.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsErrors.kt new file mode 100644 index 0000000..ff71a83 --- /dev/null +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsErrors.kt @@ -0,0 +1,22 @@ +package ru.fromchat.network.proxy + +fun Throwable.isCertificateError(): Boolean { + var cur: Throwable? = this + while (cur != null) { + val name = cur::class.simpleName.orEmpty() + val msg = cur.message.orEmpty() + if ( + name.contains("Cert", ignoreCase = true) || + name.contains("SSL", ignoreCase = true) || + name.contains("TLS", ignoreCase = true) || + msg.contains("certificate", ignoreCase = true) || + msg.contains("CertPath", ignoreCase = true) || + msg.contains("handshake", ignoreCase = true) || + msg.contains("PKIX", ignoreCase = true) + ) { + return true + } + cur = cur.cause + } + return false +} diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsTrust.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsTrust.kt new file mode 100644 index 0000000..6736b91 --- /dev/null +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyTlsTrust.kt @@ -0,0 +1,120 @@ +package ru.fromchat.network.proxy + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.json.Json +import ru.fromchat.api.local.AttachmentMediaLog +import ru.fromchat.utils.settings.Settings as PlatformSettings + +@Serializable +data class TrustedTlsCertificate( + val id: String, + val host: String, + val label: String, + val pem: String, + val addedAtEpochMs: Long = 0, +) + +object ProxyTlsTrust { + private const val STORE_KEY = "proxy_trusted_certs_v1" + private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true } + private val listSerializer = ListSerializer(TrustedTlsCertificate.serializer()) + private val settings = PlatformSettings() + + @Volatile + var sessionHost: String? = null + private set + + @Volatile + var sessionPem: String? = null + private set + + fun clearSession() { + sessionHost = null + sessionPem = null + } + + fun trustThisSession(host: String, pem: String) { + sessionHost = host.trim() + sessionPem = pem.trim() + } + + fun trustPersistently(host: String, label: String, pem: String) { + runBlocking { + trustPersistentlySuspend(host, label, pem) + } + } + + suspend fun trustPersistentlySuspend(host: String, label: String, pem: String) { + withContext(Dispatchers.IO) { + val trimmedHost = host.trim() + val trimmedPem = pem.trim() + val id = certId(trimmedHost, trimmedPem) + val list = readPersisted().toMutableList() + list.removeAll { it.id == id || (it.host == trimmedHost && it.pem == trimmedPem) } + list.add( + TrustedTlsCertificate( + id = id, + host = trimmedHost, + label = label.trim(), + pem = trimmedPem, + addedAtEpochMs = AttachmentMediaLog.nowMs(), + ), + ) + savePersisted(list) + } + } + + fun removePersisted(id: String) { + runBlocking { + withContext(Dispatchers.IO) { + savePersisted(readPersisted().filterNot { it.id == id }) + } + } + } + + fun loadPersisted(): List = runBlocking { readPersisted() } + + suspend fun readPersisted(): List = withContext(Dispatchers.IO) { + val raw = settings.getString(STORE_KEY, "") + if (raw.isBlank()) return@withContext emptyList() + runCatching { + json.decodeFromString(listSerializer, raw) + }.getOrDefault(emptyList()) + } + + fun extraPemForHost(host: String): List { + val h = host.trim() + val persisted = loadPersisted().filter { it.host.equals(h, ignoreCase = true) }.map { it.pem } + val session = if (sessionHost.equals(h, ignoreCase = true)) { + sessionPem?.let { listOf(it) } ?: emptyList() + } else { + emptyList() + } + return (persisted + session).distinct() + } + + fun hasTrustForPem(host: String, pem: String?): Boolean { + if (pem.isNullOrBlank()) return false + val normalized = pem.trim() + return extraPemForHost(host).any { it.trim() == normalized } + } + + private suspend fun savePersisted(list: List) { + settings.putString(STORE_KEY, json.encodeToString(listSerializer, list)) + } + + private fun certId(host: String, pem: String): String = + "${host.lowercase()}_${pem.hashCode().toUInt().toString(16)}" +} + +fun tlsHostFromUrl(url: String): String = + url.trim() + .removePrefix("https://") + .removePrefix("http://") + .substringBefore('/') + .substringBefore(':') diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/nav/MainDetailDestinations.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/nav/MainDetailDestinations.kt index b01aec6..256fa5b 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/nav/MainDetailDestinations.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/nav/MainDetailDestinations.kt @@ -33,6 +33,7 @@ import ru.fromchat.ui.main.settings.account.changeyandex.ChangeYandexOAuthScreen import ru.fromchat.ui.main.settings.account.delete.DeleteAccountScreen import ru.fromchat.ui.main.settings.proxy.AddProxyFlowScreen import ru.fromchat.ui.main.settings.proxy.ProxyScreen +import ru.fromchat.ui.main.settings.proxy.TrustedCertificatesScreen import ru.fromchat.ui.main.settings.server.ServerConfigScreen import ru.fromchat.ui.main.desktop.detailPaneShowBackButton import ru.fromchat.ui.profile.EditProfileFocusField @@ -304,6 +305,17 @@ fun NavGraphBuilder.settingsDetailDestinations( launchSingleTop = true } }, + onManageTrustedCerts = { + navController.navigate(SettingsRoutes.ProxyTrustedCerts) { + launchSingleTop = true + } + }, + ) + } + + composable(SettingsRoutes.ProxyTrustedCerts) { + TrustedCertificatesScreen( + onBack = { navController.navigateUp() }, ) } diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/SettingsRoutes.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/SettingsRoutes.kt index 3c5c29f..3fd4178 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/SettingsRoutes.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/SettingsRoutes.kt @@ -22,4 +22,5 @@ object SettingsRoutes { const val Logs = "settings/logs" const val LogFiles = "settings/logs/files" const val ProxyAdd = "settings/proxy/add" + const val ProxyTrustedCerts = "settings/proxy/trusted-certs" } diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/SettingsTab.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/SettingsTab.kt index a1537b6..e28fb56 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/SettingsTab.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/SettingsTab.kt @@ -196,7 +196,6 @@ fun SettingsTab() { Category( Modifier.padding(top = 8.dp), - title = stringResource(Res.string.settings_category_app), ) { ExpressiveListItem( icon = Icons.Rounded.Info, diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/ProxyScreen.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/ProxyScreen.kt index 5e9dcba..802324e 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/ProxyScreen.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/ProxyScreen.kt @@ -53,15 +53,19 @@ import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import org.jetbrains.compose.resources.stringResource import ru.fromchat.Res +import ru.fromchat.config.ServerConfig import ru.fromchat.network.proxy.ProxyCheckResult import ru.fromchat.network.proxy.ProxyChecker import ru.fromchat.network.proxy.ProxyCheckTarget import ru.fromchat.network.proxy.ProxyRuntime import ru.fromchat.network.proxy.ProxySelection +import ru.fromchat.network.proxy.ProxyTlsTrust import ru.fromchat.network.proxy.ProxyType import ru.fromchat.network.proxy.SavedProxy import ru.fromchat.network.proxy.systemProxyAvailable +import ru.fromchat.network.proxy.tlsHostFromUrl import ru.fromchat.proxy_add +import ru.fromchat.proxy_certificate_issue import ru.fromchat.proxy_check_failed import ru.fromchat.proxy_checking import ru.fromchat.proxy_custom_proxies @@ -74,7 +78,11 @@ import ru.fromchat.proxy_system_proxy import ru.fromchat.proxy_type_http import ru.fromchat.proxy_type_socks import ru.fromchat.proxy_type_ssh +import ru.fromchat.proxy_trusted_certs_manage import ru.fromchat.settings_proxy_title +import ru.fromchat.ui.components.ExpressiveListItem +import ru.fromchat.ui.components.ExpressiveTints +import androidx.compose.material.icons.rounded.VerifiedUser import ru.fromchat.ui.components.Text import ru.fromchat.ui.main.settings.SettingsDetailTopBar import ru.fromchat.ui.main.settings.rememberSettingsCollapsingScrollBehavior @@ -89,6 +97,12 @@ import ru.fromchat.utils.conditional private val ProxyPingSuccessColor = Color(0xFF2E7D32) +private data class PendingCertTrust( + val selection: ProxySelection, + val pem: String, + val label: String, +) + @OptIn( ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class, @@ -98,6 +112,7 @@ private val ProxyPingSuccessColor = Color(0xFF2E7D32) fun ProxyScreen( onBack: () -> Unit, onAddProxy: () -> Unit, + onManageTrustedCerts: () -> Unit, ) { val scope = rememberCoroutineScope() val useCollapsing = settingsDetailUseCollapsingTopBar() @@ -115,6 +130,8 @@ fun ProxyScreen( var addSheetOpen by remember { mutableStateOf(false) } var editingProxy by remember { mutableStateOf(null) } + var pendingCertTrust by remember { mutableStateOf(null) } + val apiHost = remember { tlsHostFromUrl(ServerConfig.apiBaseUrl) } suspend fun runConnectivityChecks() { directCheck = ProxyCheckResult.Checking @@ -149,6 +166,18 @@ fun ProxyScreen( runConnectivityChecks() } + fun certPemFrom(result: ProxyCheckResult?): String? = + (result as? ProxyCheckResult.CertificateIssue)?.pem?.takeIf { it.isNotBlank() } + + fun requestSelection(selection: ProxySelection, check: ProxyCheckResult?, label: String) { + val pem = certPemFrom(check) + if (pem != null && !ProxyTlsTrust.hasTrustForPem(apiHost, pem)) { + pendingCertTrust = PendingCertTrust(selection = selection, pem = pem, label = label) + return + } + scope.launch { ProxyRuntime.applySelection(selection) } + } + LaunchedEffect(savedProxies) { savedProxies.forEach { proxy -> if (proxy.id !in customChecks) { @@ -243,7 +272,18 @@ fun ProxyScreen( } item { - Category(margin = PaddingValues(horizontal = 16.dp)) { + Category(margin = PaddingValues(start = 16.dp, end = 16.dp, bottom = 8.dp)) { + ExpressiveListItem( + icon = Icons.Rounded.VerifiedUser, + iconPreset = ExpressiveTints.Cyan, + headline = stringResource(Res.string.proxy_trusted_certs_manage), + onClick = onManageTrustedCerts, + ) + } + } + + item { + Category(margin = PaddingValues(start = 16.dp, end = 16.dp)) { ProxySelectionRow( headline = stringResource(Res.string.proxy_direct_connection), selected = selection is ProxySelection.Direct, @@ -253,7 +293,7 @@ fun ProxyScreen( divider = systemProxyEnabled, containerColor = scheme.surfaceContainer, onSelect = { - scope.launch { ProxyRuntime.applySelection(ProxySelection.Direct) } + requestSelection(ProxySelection.Direct, directCheck, apiHost) }, ) if (systemProxyEnabled) { @@ -266,7 +306,7 @@ fun ProxyScreen( divider = false, containerColor = scheme.surfaceContainer, onSelect = { - scope.launch { ProxyRuntime.applySelection(ProxySelection.System) } + requestSelection(ProxySelection.System, systemCheck, apiHost) }, ) } @@ -334,9 +374,11 @@ fun ProxyScreen( position = listItemPositionInGroup(index, sortedProxies.size), groupItemCount = sortedProxies.size, onClick = { - scope.launch { - ProxyRuntime.applySelection(ProxySelection.Custom(proxy.id)) - } + requestSelection( + ProxySelection.Custom(proxy.id), + check, + proxy.label, + ) }, contextMenu = { item(Icons.Rounded.Edit, editProxyLabel) { @@ -349,6 +391,31 @@ fun ProxyScreen( } } + ProxyTrustCertificateDialog( + visible = pendingCertTrust != null, + onDismiss = { pendingCertTrust = null }, + onTrustPermanent = { + val pending = pendingCertTrust ?: return@ProxyTrustCertificateDialog + ProxyTlsTrust.trustPersistently(apiHost, pending.label, pending.pem) + ProxyChecker.notifyTlsTrustChanged() + pendingCertTrust = null + scope.launch { + ProxyRuntime.applySelection(pending.selection) + runConnectivityChecks() + } + }, + onTrustSession = { + val pending = pendingCertTrust ?: return@ProxyTrustCertificateDialog + ProxyTlsTrust.trustThisSession(apiHost, pending.pem) + ProxyChecker.notifyTlsTrustChanged() + pendingCertTrust = null + scope.launch { + ProxyRuntime.applySelection(pending.selection) + runConnectivityChecks() + } + }, + ) + if (addSheetOpen && editingProxy != null) { val sheetState = rememberBottomSheetState( initialValue = SheetValue.Expanded, @@ -471,6 +538,14 @@ private fun ProxyCheckStatusText(result: ProxyCheckResult) { color = scheme.error, ) } + + is ProxyCheckResult.CertificateIssue -> { + Text( + text = stringResource(Res.string.proxy_certificate_issue), + style = MaterialTheme.typography.bodyMedium, + color = scheme.error, + ) + } } } } diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/ProxyTrustCertificateDialog.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/ProxyTrustCertificateDialog.kt new file mode 100644 index 0000000..848ea2b --- /dev/null +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/ProxyTrustCertificateDialog.kt @@ -0,0 +1,88 @@ +package ru.fromchat.ui.main.settings.proxy + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Lock +import androidx.compose.material3.BasicAlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import ru.fromchat.Res +import ru.fromchat.proxy_trust_cert_body +import ru.fromchat.proxy_trust_cert_title +import ru.fromchat.proxy_trust_once +import ru.fromchat.proxy_trust_yes +import ru.fromchat.ui.components.Text + +@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class) +@Composable +fun ProxyTrustCertificateDialog( + visible: Boolean, + onDismiss: () -> Unit, + onTrustPermanent: () -> Unit, + onTrustSession: () -> Unit, +) { + if (!visible) return + val scheme = MaterialTheme.colorScheme + BasicAlertDialog(onDismissRequest = onDismiss) { + Surface( + shape = MaterialTheme.shapes.extraLarge, + color = scheme.surfaceContainerHigh, + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp, vertical = 28.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Icon( + imageVector = Icons.Rounded.Lock, + contentDescription = null, + modifier = Modifier.size(56.dp), + tint = scheme.primary, + ) + Spacer(Modifier.height(16.dp)) + Text( + text = stringResource(Res.string.proxy_trust_cert_title), + style = MaterialTheme.typography.headlineSmall, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(8.dp)) + Text( + text = stringResource(Res.string.proxy_trust_cert_body), + style = MaterialTheme.typography.bodyLarge, + color = scheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(24.dp)) + Button( + onClick = onTrustPermanent, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(Res.string.proxy_trust_yes)) + } + TextButton( + onClick = onTrustSession, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(Res.string.proxy_trust_once)) + } + } + } + } +} diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/TrustedCertificatesScreen.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/TrustedCertificatesScreen.kt new file mode 100644 index 0000000..39b882d --- /dev/null +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/TrustedCertificatesScreen.kt @@ -0,0 +1,143 @@ +package ru.fromchat.ui.main.settings.proxy + +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.consumeWindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Delete +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import ru.fromchat.Res +import ru.fromchat.network.proxy.ProxyChecker +import ru.fromchat.network.proxy.ProxyTlsTrust +import ru.fromchat.network.proxy.TrustedTlsCertificate +import ru.fromchat.proxy_delete +import ru.fromchat.proxy_trusted_certs_empty +import ru.fromchat.proxy_trusted_certs_title +import ru.fromchat.ui.components.Text +import ru.fromchat.ui.main.settings.SettingsDetailTopBar +import ru.fromchat.ui.main.settings.rememberSettingsCollapsingScrollBehavior +import ru.fromchat.ui.main.settings.rememberSettingsDetailHazeState +import ru.fromchat.ui.main.settings.settingsDetailHazeSource +import ru.fromchat.ui.main.settings.settingsDetailUseCollapsingTopBar +import ru.fromchat.utils.components.ListItem +import ru.fromchat.utils.components.listItemPositionInGroup +import ru.fromchat.utils.conditional +import androidx.compose.ui.input.nestedscroll.nestedScroll + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun TrustedCertificatesScreen( + onBack: () -> Unit, +) { + val useCollapsing = settingsDetailUseCollapsingTopBar() + val scrollBehavior = rememberSettingsCollapsingScrollBehavior() + val hazeState = rememberSettingsDetailHazeState() + val scheme = MaterialTheme.colorScheme + + var certs by remember { mutableStateOf(ProxyTlsTrust.loadPersisted()) } + + fun reload() { + certs = ProxyTlsTrust.loadPersisted() + } + + Scaffold( + modifier = Modifier.fillMaxSize(), + containerColor = Color.Transparent, + contentColor = scheme.onSurface, + topBar = { + SettingsDetailTopBar( + title = stringResource(Res.string.proxy_trusted_certs_title), + onBack = onBack, + hazeState = hazeState, + scrollBehavior = scrollBehavior, + ) + }, + ) { innerPadding -> + LazyColumn( + modifier = Modifier + .fillMaxSize() + .consumeWindowInsets(innerPadding) + .settingsDetailHazeSource(hazeState) + .conditional(useCollapsing) { + Modifier.nestedScroll(scrollBehavior.nestedScrollConnection) + }, + contentPadding = PaddingValues( + top = innerPadding.calculateTopPadding(), + bottom = innerPadding.calculateBottomPadding() + 24.dp, + ), + ) { + if (certs.isEmpty()) { + item { + Text( + text = stringResource(Res.string.proxy_trusted_certs_empty), + style = MaterialTheme.typography.bodyLarge, + color = scheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 32.dp, vertical = 32.dp), + ) + } + } else { + items(certs, key = { it.id }) { cert -> + TrustedCertRow( + cert = cert, + index = certs.indexOf(cert), + total = certs.size, + onDelete = { + ProxyTlsTrust.removePersisted(cert.id) + ProxyChecker.notifyTlsTrustChanged() + reload() + }, + ) + } + } + } + } +} + +@Composable +private fun TrustedCertRow( + cert: TrustedTlsCertificate, + index: Int, + total: Int, + onDelete: () -> Unit, +) { + val scheme = MaterialTheme.colorScheme + ListItem( + modifier = Modifier.padding(horizontal = 16.dp), + headline = cert.label.ifBlank { cert.host }, + supportingText = cert.host, + trailingContent = { + IconButton(onClick = onDelete) { + Icon( + imageVector = Icons.Rounded.Delete, + contentDescription = stringResource(Res.string.proxy_delete), + tint = scheme.error, + ) + } + }, + containerColor = scheme.surfaceContainer, + position = listItemPositionInGroup(index, total), + groupItemCount = total, + divider = index < total - 1, + ) +} diff --git a/app/shared/src/iosMain/kotlin/ru/fromchat/api/ApiClient.ios.kt b/app/shared/src/iosMain/kotlin/ru/fromchat/api/ApiClient.ios.kt index 02a0218..9d8a805 100644 --- a/app/shared/src/iosMain/kotlin/ru/fromchat/api/ApiClient.ios.kt +++ b/app/shared/src/iosMain/kotlin/ru/fromchat/api/ApiClient.ios.kt @@ -15,7 +15,11 @@ actual fun createPlatformHttpClient( proxyRoute: ProxyRoute?, block: HttpClientConfig<*>.() -> Unit, ): HttpClient { - val route = proxyRoute ?: ProxyRuntime.currentRoute + val route = when { + proxyRoute != null -> proxyRoute + ProxyRuntime.probeIsolation -> ProxyRoute.Direct + else -> ProxyRuntime.currentRoute + } return HttpClient(Darwin) { engine { configureRequest { diff --git a/app/shared/src/iosMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.ios.kt b/app/shared/src/iosMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.ios.kt new file mode 100644 index 0000000..5948c05 --- /dev/null +++ b/app/shared/src/iosMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.ios.kt @@ -0,0 +1,7 @@ +package ru.fromchat.network.proxy + +import io.ktor.client.HttpClientConfig + +actual fun configureEngineTls(config: HttpClientConfig<*>) = Unit + +actual suspend fun fetchPeerCertificatePem(route: ProxyRoute): String? = null diff --git a/app/shared/src/jvmMain/kotlin/ru/fromchat/api/ApiClient.jvm.kt b/app/shared/src/jvmMain/kotlin/ru/fromchat/api/ApiClient.jvm.kt index 2aa2830..52db4f7 100644 --- a/app/shared/src/jvmMain/kotlin/ru/fromchat/api/ApiClient.jvm.kt +++ b/app/shared/src/jvmMain/kotlin/ru/fromchat/api/ApiClient.jvm.kt @@ -15,7 +15,11 @@ actual fun createPlatformHttpClient( proxyRoute: ProxyRoute?, block: HttpClientConfig<*>.() -> Unit, ): HttpClient { - val route = proxyRoute ?: ProxyRuntime.currentRoute + val route = when { + proxyRoute != null -> proxyRoute + ProxyRuntime.probeIsolation -> ProxyRoute.Direct + else -> ProxyRuntime.currentRoute + } return HttpClient(CIO) { defaultRequest { contentType(ContentType.Application.Json) diff --git a/app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/ProxyEngine.jvm.kt b/app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/ProxyEngine.jvm.kt index fabee80..06c2082 100644 --- a/app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/ProxyEngine.jvm.kt +++ b/app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/ProxyEngine.jvm.kt @@ -8,6 +8,7 @@ import java.net.ProxySelector import java.net.URI actual fun configureEngineProxy(config: HttpClientConfig<*>, route: ProxyRoute) { + configureEngineTls(config) val javaProxy = when (route) { ProxyRoute.Direct -> return ProxyRoute.System -> resolveSystemProxy() ?: return @@ -32,7 +33,7 @@ actual fun systemProxyIsHttp(): Boolean { internal fun jvmSystemProxyConfigured(): Boolean = resolveSystemProxy() != null -private fun resolveSystemProxy(): Proxy? { +internal fun resolveSystemProxy(): Proxy? { val target = URI(ServerConfig.apiBaseUrl) ProxySelector.getDefault()?.select(target)?.firstOrNull { it.type() != Proxy.Type.DIRECT }?.let { return it diff --git a/app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.jvm.kt b/app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.jvm.kt new file mode 100644 index 0000000..c793779 --- /dev/null +++ b/app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/ProxyTlsEngine.jvm.kt @@ -0,0 +1,114 @@ +package ru.fromchat.network.proxy + +import io.ktor.client.HttpClientConfig +import io.ktor.client.engine.cio.CIOEngineConfig +import ru.fromchat.config.ServerConfig +import java.io.ByteArrayInputStream +import java.net.InetSocketAddress +import java.net.Proxy +import java.net.URL +import java.security.KeyStore +import java.security.cert.CertificateException +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate +import java.util.Base64 +import javax.net.ssl.HttpsURLConnection +import javax.net.ssl.SSLContext +import javax.net.ssl.TrustManager +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.X509TrustManager + +actual fun configureEngineTls(config: HttpClientConfig<*>) { + val pinningTrustManager = ProxyPinningTrustManager() + config.engine { + val cio = this as? CIOEngineConfig ?: return@engine + cio.https { + trustManager = pinningTrustManager + } + } +} + +actual suspend fun fetchPeerCertificatePem(route: ProxyRoute): String? { + val apiUrl = ServerConfig.apiBaseUrl.trimEnd('/') + val host = tlsHostFromUrl(apiUrl) + val port = runCatching { + val url = URL(apiUrl) + if (url.port > 0) url.port else url.defaultPort + }.getOrDefault(443) + return runCatching { + val connection = URL("https://$host:$port/").openConnection(resolveJavaProxy(route)) as HttpsURLConnection + connection.connectTimeout = 5_000 + connection.readTimeout = 5_000 + connection.sslSocketFactory = trustAllSslContext().socketFactory + connection.hostnameVerifier = javax.net.ssl.HttpsURLConnection.getDefaultHostnameVerifier() + connection.requestMethod = "GET" + connection.connect() + val certs = connection.serverCertificates + val leaf = certs.firstOrNull() as? X509Certificate ?: return@runCatching null + certificateToPem(leaf) + }.getOrNull() +} + +private fun resolveJavaProxy(route: ProxyRoute): Proxy = when (route) { + ProxyRoute.Direct -> Proxy.NO_PROXY + ProxyRoute.System -> resolveSystemProxy() ?: Proxy.NO_PROXY + is ProxyRoute.Custom -> when (route.endpointType) { + ProxyType.HTTP -> Proxy(Proxy.Type.HTTP, InetSocketAddress(route.host, route.port)) + ProxyType.SOCKS5, ProxyType.SSH -> + Proxy(Proxy.Type.SOCKS, InetSocketAddress(route.host, route.port)) + } +} + +private fun trustAllSslContext(): SSLContext { + val trustAll = object : X509TrustManager { + override fun checkClientTrusted(chain: Array?, authType: String?) = Unit + override fun checkServerTrusted(chain: Array?, authType: String?) = Unit + override fun getAcceptedIssuers(): Array = emptyArray() + } + return SSLContext.getInstance("TLS").apply { + init(null, arrayOf(trustAll), null) + } +} + +internal class ProxyPinningTrustManager : X509TrustManager { + private val delegate: X509TrustManager = defaultTrustManager() + private val apiHost: String + get() = tlsHostFromUrl(ServerConfig.apiBaseUrl) + + override fun checkClientTrusted(chain: Array?, authType: String?) { + delegate.checkClientTrusted(chain, authType) + } + + override fun getAcceptedIssuers(): Array = delegate.acceptedIssuers + + override fun checkServerTrusted(chain: Array?, authType: String?) { + try { + delegate.checkServerTrusted(chain, authType) + } catch (e: CertificateException) { + val leaf = chain?.firstOrNull() ?: throw e + val pem = certificateToPem(leaf) + if (ProxyTlsTrust.extraPemForHost(apiHost).any { it.trim() == pem.trim() }) { + return + } + throw e + } + } + + private fun defaultTrustManager(): X509TrustManager { + val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + factory.init(null as KeyStore?) + return factory.trustManagers.filterIsInstance().first() + } +} + +internal fun certificateToPem(certificate: X509Certificate): String { + val encoded = Base64.getMimeEncoder(64, "\n".toByteArray()).encodeToString(certificate.encoded) + return "-----BEGIN CERTIFICATE-----\n$encoded\n-----END CERTIFICATE-----" +} + +internal fun pemToCertificate(pem: String): X509Certificate? { + val trimmed = pem.trim() + if (trimmed.isEmpty()) return null + val factory = CertificateFactory.getInstance("X.509") + return factory.generateCertificate(ByteArrayInputStream(trimmed.toByteArray())) as? X509Certificate +}