package eu.friedcutlet.yokan.services.extensions.recipe import io.ktor.client.HttpClient import io.ktor.client.engine.okhttp.OkHttp import io.ktor.client.request.get import io.ktor.client.statement.bodyAsChannel import io.ktor.http.HttpHeaders import io.ktor.utils.io.readBuffer import kotlinx.io.readByteArray import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runInterruptible import kotlinx.coroutines.withTimeout import eu.friedcutlet.yokan.services.catchingNonCancellation import okhttp3.Call import okhttp3.Connection import okhttp3.ConnectionPool import okhttp3.CookieJar import okhttp3.Dns import okhttp3.EventListener import okhttp3.OkHttpClient import java.io.IOException import java.net.Inet4Address import java.net.Inet6Address import java.net.InetAddress import java.net.Proxy import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean /** Broker-owned DNS boundary. A production host may replace this with its approved resolver. */ fun interface RecipeHostResolver { suspend fun resolve(hostname: String): List } object SystemRecipeHostResolver : RecipeHostResolver { override suspend fun resolve(hostname: String): List = runInterruptible(Dispatchers.IO) { InetAddress.getAllByName(hostname).toList() } } /** Native-only, stateless HTTPS broker. It owns no cookies, cache, proxy, session, or DNS state. */ class CapabilityHttpsBroker( private val resolver: RecipeHostResolver = SystemRecipeHostResolver, private val maxHeaderCount: Int = 64, private val maxHeaderCharacters: Int = 8 * 1024, ) : RecipeCapabilityBroker { override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult { val host = requestHost(request) ?: return RecipeBrokerResult.OriginDenied val resolved = catchingNonCancellation { resolver.resolve(host) }.getOrElse { return RecipeBrokerResult.Failed } if (!approvedSnapshot(resolved)) return RecipeBrokerResult.OriginDenied val peerMismatch = AtomicBoolean(false) val client = HttpClient(OkHttp) { expectSuccess = false followRedirects = false engine { preconfigured = snapshotOkHttpClient(host, resolved.distinct(), peerMismatch) } } return try { catchingNonCancellation { withTimeout(request.deadlineMillis) { val response = client.get(request.url) if (peerMismatch.get() || response.status.value !in 200..299) return@withTimeout RecipeBrokerResult.HttpFailure // Deliberately identity-only until compressed and decompressed byte accounting is one policy. if (!identityContentEncoding(response.headers[HttpHeaders.ContentEncoding]) || !jsonContent(response.headers[HttpHeaders.ContentType]) || !acceptableHeaders(response.headers.entries())) return@withTimeout RecipeBrokerResult.Failed val bytes = response.bodyAsChannel().readBuffer(request.maxDocumentBytes.toLong() + 1).readByteArray() if (bytes.size > request.maxDocumentBytes) RecipeBrokerResult.ResponseTooLarge else RecipeBrokerResult.Document(bytes) } }.getOrDefault(RecipeBrokerResult.Failed) } finally { client.close() } } /** The origin's host when [request] is within broker limits, else null. */ private fun requestHost(request: RecipeBrokerRequest): String? { if (request.maxDocumentBytes !in 1..MAX_RESPONSE_BYTES || request.deadlineMillis !in 1..MAX_DEADLINE_MILLIS || request.originId.isBlank()) return null if (!request.pathAndQuery.startsWith('/') || request.pathAndQuery.startsWith("//") || request.pathAndQuery.any { it == '#' || it == '\\' || it.code < 0x20 }) return null return ORIGIN.matchEntire(request.origin)?.groupValues?.get(1)?.takeIf(RecipeSyntax::isHost) } private fun jsonContent(raw: String?): Boolean { val mime = raw?.substringBefore(';')?.trim()?.lowercase() ?: return false return mime == "application/json" || (mime.startsWith("application/") && mime.endsWith("+json")) } private fun acceptableHeaders(headers: Set>>): Boolean { var count = 0 var characters = 0 for ((name, values) in headers) for (value in values) { count++ characters += name.length + value.length if (count > maxHeaderCount || characters > maxHeaderCharacters) return false } return true } private companion object { const val MAX_RESPONSE_BYTES = 256 * 1024 const val MAX_DEADLINE_MILLIS = 30_000L val ORIGIN = Regex("https://([a-z0-9.-]+)") } } /** Session-free OkHttp settings shared by the broker and the catalog downloader: no redirects, retries, proxy, cookies, cache or pooling. */ internal fun isolatedOkHttpBuilder(): OkHttpClient.Builder = OkHttpClient.Builder() .followRedirects(false) .followSslRedirects(false) .retryOnConnectionFailure(false) .proxy(Proxy.NO_PROXY) .cookieJar(CookieJar.NO_COOKIES) .cache(null) .connectionPool(ConnectionPool(0, 1, TimeUnit.MILLISECONDS)) /** [isolatedOkHttpBuilder] pinned to a pre-approved DNS snapshot; [peerMismatch] is set if a connection leaves it. */ internal fun snapshotOkHttpClient(host: String, snapshot: List, peerMismatch: AtomicBoolean): OkHttpClient = isolatedOkHttpBuilder() .dns(SnapshotDns(host, snapshot)) .eventListenerFactory { SnapshotPeerListener(snapshot, peerMismatch) } .build() internal class SnapshotDns(private val hostname: String, private val snapshot: List) : Dns { override fun lookup(hostname: String): List = if (hostname == this.hostname) snapshot else throw IOException("unapproved DNS host") } private class SnapshotPeerListener(private val snapshot: List, private val failed: AtomicBoolean) : EventListener() { override fun connectionAcquired(call: Call, connection: Connection) { val routePeer = connection.route().socketAddress.address val socketPeer = connection.socket().inetAddress if (!approvedPeerAddresses(routePeer, socketPeer, snapshot) || connection.handshake() == null) { failed.set(true) call.cancel() } } } internal fun approvedAddress(address: InetAddress): Boolean = when (address) { is Inet4Address -> { val value = address.address.map { it.toInt() and 0xff } !address.isAnyLocalAddress && !address.isLoopbackAddress && !address.isLinkLocalAddress && !address.isSiteLocalAddress && !address.isMulticastAddress && value[0] !in setOf(0, 10, 127, 192, 198, 203, 224, 240, 255) && !(value[0] == 100 && value[1] in 64..127) && !(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) } is Inet6Address -> !address.isAnyLocalAddress && !address.isLoopbackAddress && !address.isLinkLocalAddress && !address.isSiteLocalAddress && !address.isMulticastAddress && (address.address[0].toInt() and 0xfe) != 0xfc else -> false } internal fun approvedSnapshot(addresses: List): Boolean = addresses.isNotEmpty() && addresses.all(::approvedAddress) internal fun identityContentEncoding(value: String?): Boolean = value == null || value.split(',').all { it.trim().equals("identity", ignoreCase = true) } internal fun approvedPeerAddresses(routePeer: InetAddress?, socketPeer: InetAddress?, snapshot: List): Boolean = routePeer != null && socketPeer != null && snapshot.any { it == routePeer } && snapshot.any { it == socketPeer }