EnhancedHttpStreamCloudflareTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/EnhancedHttpStreamCloudflareTest.kt
1package eu.friedcutlet.yokan.services.http23import eu.friedcutlet.yokan.database.InMemoryYokanDatabase4import eu.friedcutlet.yokan.database.seedDatabaseSnapshot5import eu.friedcutlet.yokan.services.http.cookies.CookieJar6import kotlin.test.Test7import kotlin.test.assertContentEquals8import kotlin.test.assertEquals9import kotlin.test.assertFalse10import kotlinx.coroutines.CompletableDeferred11import kotlinx.coroutines.async12import kotlinx.coroutines.awaitAll13import kotlinx.coroutines.test.runTest14import kotlinx.serialization.json.Json15import kotlinx.serialization.json.boolean16import kotlinx.serialization.json.jsonObject17import kotlinx.serialization.json.jsonPrimitive1819class EnhancedHttpStreamCloudflareTest {20 private val image = byteArrayOf(1, 2, 3)21 private val challengePage = "<html><head><title>Just a moment...</title></head></html>".encodeToByteArray()2223 /** Serves [image] only with the proxy's clearance + UA; otherwise a Cloudflare challenge, per the stream contract. */24 private class ProtectedHost(25 private val image: ByteArray,26 private val challenge: HttpStreamResponse,27 private val onChallenged: () -> Unit = {},28 private val beforeSolve: suspend () -> Unit = {},29 ) : HttpService {30 val proxyRequests = mutableListOf<HttpRequest>()31 val streams = mutableListOf<HttpRequest>()3233 override suspend fun request(request: HttpRequest): HttpResponse {34 proxyRequests += request35 beforeSolve()36 return HttpResponse(37 statusCode = 200,38 body = """{"status":"ok","solution":{"userAgent":"Solver/1",39 "cookies":[{"name":"cf_clearance","value":"CLEAR","domain":".example.org"}]}}""",40 )41 }4243 override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {44 streams += request45 val cleared = "cf_clearance=CLEAR" in request.headers["Cookie"].orEmpty() &&46 request.headers["User-Agent"] == "Solver/1"47 if (!cleared) {48 onChallenged()49 return challenge50 }51 onChunk(image)52 return HttpStreamResponse(statusCode = 200)53 }54 }5556 private suspend fun service(delegate: HttpService, proxyUrl: String = "http://127.0.0.1:8191"): EnhancedHttpService {57 val database = InMemoryYokanDatabase(seedDatabaseSnapshot())58 database.updateSettings(database.settings().copy(cloudflareBypassProxyUrl = proxyUrl))59 return EnhancedHttpService(delegate, database, CookieJar(database))60 }6162 private fun challenge(headers: Map<String, String>) = HttpStreamResponse(statusCode = 403, headers = headers, body = challengePage)6364 @Test65 fun streamChallengeIsSolvedThenRetriedOnceWithFreshCookieAndUserAgent() = runTest {66 val host = ProtectedHost(image, challenge(mapOf("cf-mitigated" to "challenge")))67 val http = service(host)68 val received = mutableListOf<Byte>()6970 val response = http.stream(HttpRequest(url = "https://img.example.org/p1.jpg")) { received += it.toList() }7172 assertEquals(200, response.statusCode)73 assertContentEquals(image, received.toByteArray(), "challenge page bytes must never reach onChunk")74 assertEquals(2, host.streams.size)75 val proxy = host.proxyRequests.single()76 assertEquals("http://127.0.0.1:8191/v1", proxy.url, "bare host:port posts to the FlareSolverr endpoint")77 assertEquals(true, Json.parseToJsonElement(proxy.body.orEmpty()).jsonObject["returnOnlyCookies"]?.jsonPrimitive?.boolean)78 }7980 @Test81 fun plainForbiddenFromCloudflareIsNotSolved() = runTest {82 val hotlinkBlock = challenge(mapOf("Server" to "cloudflare", "Content-Type" to "image/jpeg"))83 val host = ProtectedHost(image, hotlinkBlock)84 val http = service(host)85 var webViewCalled = false86 http.cloudflareSolver = { _, _ ->87 webViewCalled = true88 null89 }90 var chunks = 09192 val response = http.stream(HttpRequest(url = "https://img.example.org/p1.jpg")) { chunks++ }9394 assertEquals(403, response.statusCode)95 assertEquals(1, host.streams.size)96 assertEquals(0, host.proxyRequests.size)97 assertFalse(webViewCalled)98 assertEquals(0, chunks)99 }100101 @Test102 fun parallelChallengedStreamsShareOneSolve() = runTest {103 val pages = 5104 var challenged = 0105 val allChallenged = CompletableDeferred<Unit>()106 val host = ProtectedHost(107 image,108 challenge(mapOf("Server" to "cloudflare", "Content-Type" to "text/html")),109 onChallenged = { if (++challenged == pages) allChallenged.complete(Unit) },110 // Hold the first solve until every page has hit the challenge and queued behind it.111 beforeSolve = { allChallenged.await() },112 )113 val http = service(host)114115 val statuses = (1..pages).map { page ->116 async { http.stream(HttpRequest(url = "https://img.example.org/p$page.jpg")) {}.statusCode }117 }.awaitAll()118119 assertEquals(List(pages) { 200 }, statuses)120 assertEquals(1, host.proxyRequests.size)121 assertEquals(pages * 2, host.streams.size)122 }123124 @Test125 fun explicitProxyPathIsKept() {126 assertEquals("http://solver:8191/v1", cloudflareProxyEndpoint("solver:8191/"))127 assertEquals("https://solver.lan/api/v1", cloudflareProxyEndpoint("https://solver.lan/api/v1"))128 }129}130