CapabilityHttpsBroker.kt
composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityHttpsBroker.kt
1package eu.friedcutlet.yokan.services.extensions.recipe23import io.ktor.client.HttpClient4import io.ktor.client.engine.okhttp.OkHttp5import io.ktor.client.request.get6import io.ktor.client.statement.bodyAsChannel7import io.ktor.http.HttpHeaders8import io.ktor.utils.io.readBuffer9import kotlinx.io.readByteArray10import kotlinx.coroutines.Dispatchers11import kotlinx.coroutines.runInterruptible12import kotlinx.coroutines.withTimeout13import eu.friedcutlet.yokan.services.catchingNonCancellation14import okhttp3.Call15import okhttp3.Connection16import okhttp3.ConnectionPool17import okhttp3.CookieJar18import okhttp3.Dns19import okhttp3.EventListener20import okhttp3.OkHttpClient21import java.io.IOException22import java.net.Inet4Address23import java.net.Inet6Address24import java.net.InetAddress25import java.net.Proxy26import java.util.concurrent.TimeUnit27import java.util.concurrent.atomic.AtomicBoolean2829/** Broker-owned DNS boundary. A production host may replace this with its approved resolver. */30fun interface RecipeHostResolver {31 suspend fun resolve(hostname: String): List<InetAddress>32}3334object SystemRecipeHostResolver : RecipeHostResolver {35 override suspend fun resolve(hostname: String): List<InetAddress> = runInterruptible(Dispatchers.IO) {36 InetAddress.getAllByName(hostname).toList()37 }38}3940/** Native-only, stateless HTTPS broker. It owns no cookies, cache, proxy, session, or DNS state. */41class CapabilityHttpsBroker(42 private val resolver: RecipeHostResolver = SystemRecipeHostResolver,43 private val maxHeaderCount: Int = 64,44 private val maxHeaderCharacters: Int = 8 * 1024,45) : RecipeCapabilityBroker {46 override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult {47 val host = requestHost(request) ?: return RecipeBrokerResult.OriginDenied48 val resolved = catchingNonCancellation { resolver.resolve(host) }.getOrElse { return RecipeBrokerResult.Failed }49 if (!approvedSnapshot(resolved)) return RecipeBrokerResult.OriginDenied50 val peerMismatch = AtomicBoolean(false)51 val client = HttpClient(OkHttp) {52 expectSuccess = false53 followRedirects = false54 engine { preconfigured = snapshotOkHttpClient(host, resolved.distinct(), peerMismatch) }55 }56 return try {57 catchingNonCancellation { withTimeout(request.deadlineMillis) {58 val response = client.get(request.url)59 if (peerMismatch.get() || response.status.value !in 200..299) return@withTimeout RecipeBrokerResult.HttpFailure60 // Deliberately identity-only until compressed and decompressed byte accounting is one policy.61 if (!identityContentEncoding(response.headers[HttpHeaders.ContentEncoding]) || !jsonContent(response.headers[HttpHeaders.ContentType]) || !acceptableHeaders(response.headers.entries())) return@withTimeout RecipeBrokerResult.Failed62 val bytes = response.bodyAsChannel().readBuffer(request.maxDocumentBytes.toLong() + 1).readByteArray()63 if (bytes.size > request.maxDocumentBytes) RecipeBrokerResult.ResponseTooLarge else RecipeBrokerResult.Document(bytes)64 } }.getOrDefault(RecipeBrokerResult.Failed)65 } finally {66 client.close()67 }68 }6970 /** The origin's host when [request] is within broker limits, else null. */71 private fun requestHost(request: RecipeBrokerRequest): String? {72 if (request.maxDocumentBytes !in 1..MAX_RESPONSE_BYTES || request.deadlineMillis !in 1..MAX_DEADLINE_MILLIS || request.originId.isBlank()) return null73 if (!request.pathAndQuery.startsWith('/') || request.pathAndQuery.startsWith("//") || request.pathAndQuery.any { it == '#' || it == '\\' || it.code < 0x20 }) return null74 return ORIGIN.matchEntire(request.origin)?.groupValues?.get(1)?.takeIf(RecipeSyntax::isHost)75 }7677 private fun jsonContent(raw: String?): Boolean {78 val mime = raw?.substringBefore(';')?.trim()?.lowercase() ?: return false79 return mime == "application/json" || (mime.startsWith("application/") && mime.endsWith("+json"))80 }8182 private fun acceptableHeaders(headers: Set<Map.Entry<String, List<String>>>): Boolean {83 var count = 084 var characters = 085 for ((name, values) in headers) for (value in values) {86 count++87 characters += name.length + value.length88 if (count > maxHeaderCount || characters > maxHeaderCharacters) return false89 }90 return true91 }9293 private companion object {94 const val MAX_RESPONSE_BYTES = 256 * 102495 const val MAX_DEADLINE_MILLIS = 30_000L96 val ORIGIN = Regex("https://([a-z0-9.-]+)")97 }98}99100/** Session-free OkHttp settings shared by the broker and the catalog downloader: no redirects, retries, proxy, cookies, cache or pooling. */101internal fun isolatedOkHttpBuilder(): OkHttpClient.Builder = OkHttpClient.Builder()102 .followRedirects(false)103 .followSslRedirects(false)104 .retryOnConnectionFailure(false)105 .proxy(Proxy.NO_PROXY)106 .cookieJar(CookieJar.NO_COOKIES)107 .cache(null)108 .connectionPool(ConnectionPool(0, 1, TimeUnit.MILLISECONDS))109110/** [isolatedOkHttpBuilder] pinned to a pre-approved DNS snapshot; [peerMismatch] is set if a connection leaves it. */111internal fun snapshotOkHttpClient(host: String, snapshot: List<InetAddress>, peerMismatch: AtomicBoolean): OkHttpClient = isolatedOkHttpBuilder()112 .dns(SnapshotDns(host, snapshot))113 .eventListenerFactory { SnapshotPeerListener(snapshot, peerMismatch) }114 .build()115116internal class SnapshotDns(private val hostname: String, private val snapshot: List<InetAddress>) : Dns {117 override fun lookup(hostname: String): List<InetAddress> = if (hostname == this.hostname) snapshot else throw IOException("unapproved DNS host")118}119120private class SnapshotPeerListener(private val snapshot: List<InetAddress>, private val failed: AtomicBoolean) : EventListener() {121 override fun connectionAcquired(call: Call, connection: Connection) {122 val routePeer = connection.route().socketAddress.address123 val socketPeer = connection.socket().inetAddress124 if (!approvedPeerAddresses(routePeer, socketPeer, snapshot) || connection.handshake() == null) {125 failed.set(true)126 call.cancel()127 }128 }129}130131internal fun approvedAddress(address: InetAddress): Boolean = when (address) {132 is Inet4Address -> {133 val value = address.address.map { it.toInt() and 0xff }134 !address.isAnyLocalAddress && !address.isLoopbackAddress && !address.isLinkLocalAddress && !address.isSiteLocalAddress && !address.isMulticastAddress &&135 value[0] !in setOf(0, 10, 127, 192, 198, 203, 224, 240, 255) && !(value[0] == 100 && value[1] in 64..127) &&136 !(value[0] == 172 && value[1] in 16..31) && !(value[0] == 192 && value[1] == 0) && !(value[0] == 192 && value[1] == 88) && !(value[0] == 192 && value[1] == 175) && !(value[0] == 198 && value[1] in 18..19)137 }138 is Inet6Address -> !address.isAnyLocalAddress && !address.isLoopbackAddress && !address.isLinkLocalAddress && !address.isSiteLocalAddress && !address.isMulticastAddress &&139 (address.address[0].toInt() and 0xfe) != 0xfc140 else -> false141}142143internal fun approvedSnapshot(addresses: List<InetAddress>): Boolean = addresses.isNotEmpty() && addresses.all(::approvedAddress)144145internal fun identityContentEncoding(value: String?): Boolean = value == null || value.split(',').all { it.trim().equals("identity", ignoreCase = true) }146147internal fun approvedPeerAddresses(routePeer: InetAddress?, socketPeer: InetAddress?, snapshot: List<InetAddress>): Boolean =148 routePeer != null && socketPeer != null && snapshot.any { it == routePeer } && snapshot.any { it == socketPeer }149