CapabilityCatalogDownloaderTest.kt
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityCatalogDownloaderTest.kt
1package eu.friedcutlet.yokan.services.extensions.recipe23import kotlinx.coroutines.CancellationException4import kotlinx.coroutines.delay5import kotlinx.coroutines.test.runTest6import okhttp3.MediaType.Companion.toMediaType7import okhttp3.Protocol8import okhttp3.Request9import okhttp3.Response10import okhttp3.ResponseBody.Companion.toResponseBody11import java.io.ByteArrayInputStream12import java.net.InetAddress13import java.net.Proxy14import java.util.concurrent.atomic.AtomicBoolean15import kotlin.test.Test16import kotlin.test.assertContentEquals17import kotlin.test.assertEquals18import kotlin.test.assertFailsWith19import kotlin.test.assertFalse20import kotlin.test.assertTrue2122class CapabilityCatalogDownloaderTest {23 @Test24 fun invalidCatalogUrlsFailBeforeDnsResolution() = runTest {25 var resolved = false26 val downloader = CapabilityCatalogDownloader(RecipeHostResolver { resolved = true; listOf(InetAddress.getByName("8.8.8.8")) })27 listOf(28 "http://catalog.example.test/catalog.yrc",29 "https://Catalog.example.test/catalog.yrc",30 "https://catalog.example.test:443/catalog.yrc",31 "https://127.0.0.1/catalog.yrc",32 "https://user@catalog.example.test/catalog.yrc",33 "https://catalog.example.test/catalog.yrc?query=x",34 "https://catalog.example.test/catalog.yrc#fragment",35 "https://catalog.example.test\\catalog.yrc",36 ).forEach { url -> assertFailsWith<RecipeCatalogDownloadException> { downloader.download(url, 64, 1_000) } }37 assertFalse(resolved)38 }3940 @Test41 fun mixedOrForbiddenDnsSnapshotsFailClosed() = runTest {42 val validUrl = "https://catalog.example.test/catalog.yrc"43 val forbidden = CapabilityCatalogDownloader(RecipeHostResolver { listOf(InetAddress.getByName("127.0.0.1")) })44 val mixed = CapabilityCatalogDownloader(RecipeHostResolver { listOf(InetAddress.getByName("8.8.8.8"), InetAddress.getByName("127.0.0.1")) })45 assertFailsWith<RecipeCatalogDownloadException> { forbidden.download(validUrl, 64, 1_000) }46 assertFailsWith<RecipeCatalogDownloadException> { mixed.download(validUrl, 64, 1_000) }47 }4849 @Test50 fun loopbackHttpCatalogsNeedDeveloperMode(): Unit = kotlinx.coroutines.runBlocking {51 val body = "signed-envelope".encodeToByteArray()52 val server = com.sun.net.httpserver.HttpServer.create(java.net.InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0), 0)53 server.createContext("/") { exchange ->54 exchange.responseHeaders.add("Content-Type", "application/octet-stream")55 exchange.sendResponseHeaders(if (exchange.requestURI.path == "/catalog.yrc") 200 else 404, body.size.toLong())56 exchange.responseBody.use { it.write(body) }57 }58 server.start()59 try {60 val url = "http://127.0.0.1:${server.address.port}/catalog.yrc"61 var developerMode = false62 val downloader = CapabilityCatalogDownloader(RecipeHostResolver { error("loopback must not resolve") }, developerMode = { developerMode })63 assertFailsWith<RecipeCatalogDownloadException> { downloader.download(url, 64, 5_000) }64 developerMode = true65 assertContentEquals(body, downloader.download(url, 64, 5_000))66 // Only the literal loopback address is admitted; other plain-HTTP hosts stay rejected.67 assertFailsWith<RecipeCatalogDownloadException> { downloader.download("http://localhost:${server.address.port}/catalog.yrc", 64, 5_000) }68 assertFailsWith<RecipeCatalogDownloadException> { downloader.download("http://127.0.0.1:${server.address.port}/a/../catalog.yrc", 64, 5_000) }69 } finally {70 server.stop(0)71 }72 }7374 @Test75 fun snapshotDnsAndPeerMembershipAreExact() {76 val first = InetAddress.getByName("8.8.8.8")77 val second = InetAddress.getByName("1.1.1.1")78 val dns = SnapshotDns("catalog.example.test", listOf(first))79 assertEquals(listOf(first), dns.lookup("catalog.example.test"))80 assertFailsWith<Exception> { dns.lookup("other.example.test") }81 assertTrue(approvedPeerAddresses(first, first, listOf(first)))82 assertFalse(approvedPeerAddresses(first, second, listOf(first)))83 assertFalse(approvedPeerAddresses(null, first, listOf(first)))84 }8586 @Test87 fun responsePoliciesRejectStatusEncodingMimeHeadersAndSize() {88 assertFalse(catalogResponseAllowed(response(302), 64, 64, 8_192))89 assertFalse(catalogResponseAllowed(response(200, encoding = "gzip"), 64, 64, 8_192))90 assertFalse(catalogResponseAllowed(response(200, mime = "text/html"), 64, 64, 8_192))91 assertFalse(catalogResponseAllowed(response(200, headers = listOf("X-Long" to "x".repeat(32))), 64, 64, 8))92 assertFalse(catalogResponseAllowed(response(200, bytes = ByteArray(65)), 64, 64, 8_192))93 assertTrue(catalogResponseAllowed(response(200, mime = "application/problem+json"), 64, 64, 8_192))94 assertTrue(catalogResponseAllowed(response(200, mime = "text/plain; charset=utf-8"), 64, 64, 8_192))95 }9697 @Test98 fun bodyCapIsStreamingAndLimitsAreBounded() {99 assertContentEquals(byteArrayOf(1, 2), ByteArrayInputStream(byteArrayOf(1, 2)).readCatalogCapped(2))100 assertFailsWith<RecipeCatalogDownloadException> { ByteArrayInputStream(byteArrayOf(1, 2, 3)).readCatalogCapped(2) }101 assertFailsWith<RecipeCatalogDownloadException> { ByteArrayInputStream(byteArrayOf()).readCatalogCapped(96 * 1024 + 1) }102 }103104 @Test105 fun timeoutBecomesClosedFailureAndCancellationPropagates() = runTest {106 val timeout = CapabilityCatalogDownloader(RecipeHostResolver { delay(100); listOf(InetAddress.getByName("8.8.8.8")) })107 assertFailsWith<RecipeCatalogDownloadException> { timeout.download("https://catalog.example.test/catalog.yrc", 64, 1) }108 val cancelled = CapabilityCatalogDownloader(RecipeHostResolver { throw CancellationException("cancel") })109 assertFailsWith<CancellationException> { cancelled.download("https://catalog.example.test/catalog.yrc", 64, 1_000) }110 }111112 @Test113 fun dedicatedSessionDisablesStatefulAndUnsafeTransportFeatures() {114 val client = snapshotOkHttpClient("catalog.example.test", listOf(InetAddress.getByName("8.8.8.8")), AtomicBoolean())115 try {116 assertFalse(client.followRedirects)117 assertFalse(client.followSslRedirects)118 assertFalse(client.retryOnConnectionFailure)119 assertEquals(Proxy.NO_PROXY, client.proxy)120 assertEquals(okhttp3.CookieJar.NO_COOKIES, client.cookieJar)121 assertEquals(null, client.cache)122 } finally {123 client.dispatcher.cancelAll()124 client.connectionPool.evictAll()125 }126 }127128 private fun response(129 status: Int,130 mime: String = "application/json",131 encoding: String? = null,132 headers: List<Pair<String, String>> = emptyList(),133 bytes: ByteArray = byteArrayOf(1),134 ): Response {135 val builder = Response.Builder()136 .request(Request.Builder().url("https://catalog.example.test/catalog.yrc").build())137 .protocol(Protocol.HTTP_2)138 .code(status)139 .message("fixture")140 .header("Content-Type", mime)141 .body(bytes.toResponseBody(mime.substringBefore(';').toMediaType()))142 encoding?.let { builder.header("Content-Encoding", it) }143 headers.forEach { (name, value) -> builder.addHeader(name, value) }144 return builder.build()145 }146}147