CapabilityCatalogDownloader.kt
composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityCatalogDownloader.kt
1package eu.friedcutlet.yokan.services.extensions.recipe23import kotlinx.coroutines.CancellationException4import kotlinx.coroutines.Dispatchers5import kotlinx.coroutines.TimeoutCancellationException6import kotlinx.coroutines.currentCoroutineContext7import kotlinx.coroutines.withContext8import kotlinx.coroutines.withTimeout9import okhttp3.OkHttpClient10import okhttp3.Request11import okhttp3.Response12import java.io.ByteArrayOutputStream13import java.io.IOException14import java.util.concurrent.atomic.AtomicBoolean1516/** Closed transport error: callers must not expose URL, parser, or response details. */17class RecipeCatalogDownloadException : IOException("catalog download failed")1819/**20 * Dedicated native catalog transport; it does not share broker requests, clients, or session state.21 * [developerMode] additionally admits plain-HTTP `127.0.0.1` catalogs for local test servers.22 */23class CapabilityCatalogDownloader(24 private val resolver: RecipeHostResolver = SystemRecipeHostResolver,25 private val maxHeaderCount: Int = 64,26 private val maxHeaderCharacters: Int = 8 * 1024,27 private val developerMode: () -> Boolean = { false },28) : RecipeCatalogDownloader {29 init {30 require(maxHeaderCount > 0 && maxHeaderCharacters > 0)31 }3233 override suspend fun download(url: String, maxBytes: Int, deadlineMillis: Long): ByteArray {34 val loopback = loopbackCatalogOrigin(url)35 val endpoint = if (loopback == null) parseCatalogEndpoint(url) ?: throw RecipeCatalogDownloadException() else null36 if (loopback != null && (!developerMode() || url.any { it.code !in 0x21..0x7e || it == '\\' || it == '?' || it == '#' } || !RecipeSyntax.isCanonicalPath(url.substring(loopback.length)))) {37 throw RecipeCatalogDownloadException()38 }39 if (maxBytes !in 1..MAX_RESPONSE_BYTES || deadlineMillis !in 1..MAX_DEADLINE_MILLIS) throw RecipeCatalogDownloadException()40 return try {41 withTimeout(deadlineMillis) {42 val peerMismatch = AtomicBoolean(false)43 val client = if (endpoint == null) {44 isolatedOkHttpBuilder().build()45 } else {46 val resolved = resolver.resolve(endpoint.host)47 if (!approvedSnapshot(resolved)) throw RecipeCatalogDownloadException()48 snapshotOkHttpClient(endpoint.host, resolved.distinct(), peerMismatch)49 }50 try {51 execute(client, url, maxBytes, peerMismatch)52 } finally {53 client.dispatcher.cancelAll()54 client.connectionPool.evictAll()55 client.cache?.close()56 }57 }58 } catch (_: TimeoutCancellationException) {59 throw RecipeCatalogDownloadException()60 } catch (error: CancellationException) {61 throw error62 } catch (_: Throwable) {63 // Closed transport error: every other failure, including our own, collapses to one opaque exception.64 throw RecipeCatalogDownloadException()65 }66 }6768 private suspend fun execute(client: OkHttpClient, url: String, maxBytes: Int, peerMismatch: AtomicBoolean): ByteArray = withContext(Dispatchers.IO) {69 val request = Request.Builder().url(url).header("Accept-Encoding", "identity").get().build()70 val call = client.newCall(request)71 val cancellation = currentCoroutineContext()[kotlinx.coroutines.Job]?.invokeOnCompletion { call.cancel() }72 try {73 call.execute().use { response ->74 if (peerMismatch.get() || !catalogResponseAllowed(response, maxBytes, maxHeaderCount, maxHeaderCharacters)) throw RecipeCatalogDownloadException()75 response.body.byteStream().readCatalogCapped(maxBytes)76 }77 } catch (error: CancellationException) {78 throw error79 } catch (_: Throwable) {80 throw RecipeCatalogDownloadException()81 } finally {82 cancellation?.dispose()83 call.cancel()84 }85 }8687 private companion object {88 const val MAX_RESPONSE_BYTES = RecipeCatalogLimits.maxEnvelopeBytes89 const val MAX_DEADLINE_MILLIS = 30_000L90 }91}9293internal fun parseCatalogEndpoint(url: String): CatalogEndpoint? {94 if (url.length !in 9..2_048 || !url.startsWith("https://") || url.any { it.code !in 0x21..0x7e || it == '\\' || it == '?' || it == '#' }) return null95 val authorityEnd = url.indexOf('/', 8).takeIf { it >= 0 } ?: return null96 val host = url.substring(8, authorityEnd)97 if (!RecipeSyntax.isHost(host) || !RecipeSyntax.isCanonicalPath(url.substring(authorityEnd))) return null98 return CatalogEndpoint(host)99}100101internal data class CatalogEndpoint(val host: String)102103internal fun catalogResponseAllowed(response: Response, maxBytes: Int, maxHeaderCount: Int, maxHeaderCharacters: Int): Boolean =104 response.code in 200..299 && maxBytes in 1..RecipeCatalogLimits.maxEnvelopeBytes && catalogHeadersAllowed(response, maxHeaderCount, maxHeaderCharacters) &&105 identityContentEncoding(response.header("Content-Encoding")) && catalogMimeAllowed(response.header("Content-Type")) &&106 response.body.contentLength().let { it == -1L || it in 0..maxBytes }107108internal fun catalogHeadersAllowed(response: Response, maxHeaderCount: Int, maxHeaderCharacters: Int): Boolean {109 if (maxHeaderCount <= 0 || maxHeaderCharacters <= 0 || response.headers.size > maxHeaderCount) return false110 var characters = 0111 for (index in 0 until response.headers.size) {112 characters += response.headers.name(index).length + response.headers.value(index).length113 if (characters > maxHeaderCharacters) return false114 }115 return true116}117118internal fun catalogMimeAllowed(raw: String?): Boolean {119 val mime = raw?.substringBefore(';')?.trim()?.lowercase() ?: return false120 return mime == "application/octet-stream" || mime == "application/json" || mime == "text/plain" ||121 (mime.startsWith("application/") && mime.endsWith("+json"))122}123124internal fun java.io.InputStream.readCatalogCapped(maxBytes: Int): ByteArray {125 if (maxBytes !in 1..RecipeCatalogLimits.maxEnvelopeBytes) throw RecipeCatalogDownloadException()126 val output = ByteArrayOutputStream(minOf(maxBytes, 8 * 1024))127 val buffer = ByteArray(8 * 1024)128 var total = 0129 while (true) {130 val read = read(buffer)131 if (read < 0) return output.toByteArray()132 if (read > maxBytes - total) throw RecipeCatalogDownloadException()133 output.write(buffer, 0, read)134 total += read135 }136}137