CloudflareHandlingTest.kt
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/http/CloudflareHandlingTest.kt
1package eu.friedcutlet.yokan.services.http23import eu.friedcutlet.yokan.database.InMemoryYokanDatabase4import eu.friedcutlet.yokan.services.http.cookies.CookieJar5import kotlin.test.Test6import kotlin.test.assertEquals7import kotlin.test.assertNotNull8import kotlin.test.assertTrue9import kotlinx.coroutines.runBlocking1011/**12 * Deterministic coverage of Yokan's Cloudflare-handling mechanism: the shared13 * [CookieJar] seeds a `cf_clearance` cookie (harvested by the WebView resolver14 * in production) and [EnhancedHttpService] must attach it to every subsequent15 * request for that host, and persist `Set-Cookie` clearances issued by the16 * server. This is the transport contract that lets extensions get past a17 * Cloudflare challenge once the WebView solves it.18 */19class CloudflareHandlingTest {20 private class CapturingSolver(private val response: HttpResponse) {21 var resolveCalls: Int = 022 var lastHeaders: Map<String, String>? = null2324 val solve: suspend (String, Map<String, String>) -> HttpResponse? = { _, headers ->25 resolveCalls += 126 lastHeaders = headers27 response28 }29 }3031 @Test32 fun attachesSeededClearanceCookieToRequests() = runBlocking {33 val database = InMemoryYokanDatabase()34 val cookieJar = CookieJar(database)35 cookieJar.put("animepahe.pw", "cf_clearance=SEEDED-TOKEN")36 val delegate = RecordingHttpService { HttpResponse(statusCode = 200, body = "ok") }37 val http = EnhancedHttpService(delegate, database, cookieJar)3839 http.request(HttpRequest(url = "https://animepahe.pw/api?m=airing"))4041 val sent = assertNotNull(delegate.requests.lastOrNull())42 val cookie = sent.headers.entries.firstOrNull { it.key.equals("Cookie", ignoreCase = true) }?.value.orEmpty()43 assertTrue(cookie.contains("cf_clearance=SEEDED-TOKEN"), "clearance cookie not attached: '$cookie'")44 assertTrue(45 sent.headers.keys.any { it.equals("User-Agent", ignoreCase = true) },46 "default User-Agent not applied",47 )48 }4950 @Test51 fun persistsClearanceFromSetCookie() = runBlocking {52 val database = InMemoryYokanDatabase()53 val cookieJar = CookieJar(database)54 val delegate = HttpService {55 HttpResponse(56 statusCode = 200,57 body = "ok",58 setCookies = listOf("cf_clearance=FRESH-TOKEN; Path=/; Domain=animepahe.pw"),59 )60 }61 val http = EnhancedHttpService(delegate, database, cookieJar)6263 http.request(HttpRequest(url = "https://animepahe.pw/"))6465 val header = cookieJar.cookieHeader("https://animepahe.pw/api")66 assertEquals(true, header?.contains("cf_clearance=FRESH-TOKEN"), "clearance not persisted: '$header'")67 }6869 @Test70 fun clearanceIsScopedToItsHost() = runBlocking {71 val database = InMemoryYokanDatabase()72 val cookieJar = CookieJar(database)73 cookieJar.put("animepahe.pw", "cf_clearance=SCOPED")74 val delegate = RecordingHttpService { HttpResponse(statusCode = 200, body = "ok") }75 val http = EnhancedHttpService(delegate, database, cookieJar)7677 http.request(HttpRequest(url = "https://mangadex.org/api"))7879 val cookie = delegate.requests.lastOrNull()?.headers?.entries80 ?.firstOrNull { it.key.equals("Cookie", ignoreCase = true) }?.value.orEmpty()81 assertTrue(!cookie.contains("cf_clearance"), "clearance leaked to a foreign host: '$cookie'")82 }8384 @Test85 fun forcedResolutionHeaderIsNotSentToTheServer() = runBlocking {86 val database = InMemoryYokanDatabase()87 val cookieJar = CookieJar(database)88 cookieJar.put("kwik.cx", "kwik_session=EXISTING")89 val delegate = RecordingHttpService { HttpResponse(statusCode = 200, body = "blocked") }90 val webView = CapturingSolver(HttpResponse(statusCode = 200, body = "stream page"))91 val http = EnhancedHttpService(delegate, database, cookieJar).apply {92 cloudflareSolver = webView.solve93 }9495 val response = http.request(96 HttpRequest(97 url = "https://kwik.cx/e/example",98 headers = mapOf("X-Yokan-Resolve-Cloudflare" to "1"),99 ),100 )101102 assertEquals("stream page", response.body)103 assertEquals(1, webView.resolveCalls)104 assertTrue(webView.lastHeaders?.get("Cookie")?.contains("kwik_session=EXISTING") == true)105 assertTrue(delegate.requests.lastOrNull()?.headers?.keys?.none {106 it.equals("X-Yokan-Resolve-Cloudflare", ignoreCase = true)107 } == true)108 }109110 @Test111 fun solvesChallengeViaCfProxyWhenConfigured() = runBlocking {112 val database = InMemoryYokanDatabase()113 database.updateSettings(114 database.settings().copy(cloudflareBypassProxyUrl = "http://127.0.0.1:8191/v1")115 )116 val cookieJar = CookieJar(database)117118 val router = RecordingHttpService { req ->119 when {120 req.url == "http://127.0.0.1:8191/v1" -> {121 assertEquals("POST", req.method)122 assertTrue(req.body.orEmpty().contains("request.get"))123 assertTrue(req.body.orEmpty().contains("https://protected.domain/page"))124 HttpResponse(125 statusCode = 200,126 body = """127 {128 "status": "ok",129 "message": "Challenge solved!",130 "solution": {131 "cookies": [132 { "name": "cf_clearance", "value": "SOLVED_PROXY_TOKEN", "domain": ".protected.domain" }133 ],134 "userAgent": "FlareSolverr-Browser/1.0"135 }136 }137 """.trimIndent(),138 )139 }140 req.url == "https://protected.domain/page" -> {141 val cookie = req.headers["Cookie"].orEmpty()142 if (cookie.contains("cf_clearance=SOLVED_PROXY_TOKEN")) {143 HttpResponse(statusCode = 200, body = "<html>success page</html>")144 } else {145 HttpResponse(146 statusCode = 403,147 body = "<html><head><title>Just a moment...</title></head></html>",148 headers = mapOf("Server" to "cloudflare"),149 )150 }151 }152 else -> HttpResponse(statusCode = 404, body = "not found")153 }154 }155156 val http = EnhancedHttpService(router, database, cookieJar)157 val res = http.request(HttpRequest(url = "https://protected.domain/page"))158159 assertEquals(200, res.statusCode)160 assertEquals("<html>success page</html>", res.body)161 assertEquals("SOLVED_PROXY_TOKEN", cookieJar.cookieHeader("https://protected.domain/page")?.substringAfter("cf_clearance=")?.substringBefore(";"))162 assertEquals("FlareSolverr-Browser/1.0", cookieJar.userAgent("https://protected.domain/page"))163 }164165 @Test166 fun cfProxyCookiesStayOnTheirOwnDomains() = runBlocking {167 val database = InMemoryYokanDatabase()168 database.updateSettings(169 database.settings().copy(cloudflareBypassProxyUrl = "http://127.0.0.1:8191/v1")170 )171 val cookieJar = CookieJar(database)172 val router = RecordingHttpService { req ->173 when {174 req.url == "http://127.0.0.1:8191/v1" -> HttpResponse(175 statusCode = 200,176 body = """177 {178 "status": "ok",179 "solution": {180 "cookies": [181 { "name": "cf_clearance", "value": "CLEAR", "domain": ".protected.domain" },182 { "name": "tracker", "value": "OTHER", "domain": "cdn.other.domain" }183 ]184 }185 }186 """.trimIndent(),187 )188 req.headers["Cookie"].orEmpty().contains("cf_clearance=CLEAR") ->189 HttpResponse(statusCode = 200, body = "<html>success page</html>")190 else -> HttpResponse(191 statusCode = 403,192 body = "<html><head><title>Just a moment...</title></head></html>",193 headers = mapOf("Server" to "cloudflare"),194 )195 }196 }197198 val res = EnhancedHttpService(router, database, cookieJar)199 .request(HttpRequest(url = "https://www.protected.domain/page"))200201 assertEquals(200, res.statusCode)202 val target = cookieJar.cookieHeader("https://www.protected.domain/page").orEmpty()203 val other = cookieJar.cookieHeader("https://cdn.other.domain/x").orEmpty()204 assertTrue("cf_clearance=CLEAR" in target && "tracker" !in target, "target cookies: '$target'")205 assertTrue("tracker=OTHER" in other && "cf_clearance" !in other, "other-domain cookies: '$other'")206 }207208 @Test209 fun fallsBackToWebViewWhenProxyFails() = runBlocking {210 val database = InMemoryYokanDatabase()211 database.updateSettings(212 database.settings().copy(cloudflareBypassProxyUrl = "http://127.0.0.1:8191/v1")213 )214 val cookieJar = CookieJar(database)215216 val router = RecordingHttpService { req ->217 when (req.url) {218 "http://127.0.0.1:8191/v1" -> {219 HttpResponse(220 statusCode = 500,221 body = """{"status": "error", "message": "Browser timeout"}""",222 )223 }224 "https://protected.domain/page" -> {225 HttpResponse(226 statusCode = 503,227 body = "<html><head><title>Just a moment...</title></head></html>",228 headers = mapOf("Server" to "cloudflare"),229 )230 }231 else -> HttpResponse(statusCode = 404, body = "not found")232 }233 }234235 val webView = CapturingSolver(HttpResponse(statusCode = 200, body = "<html>cleared by webview</html>"))236 val http = EnhancedHttpService(router, database, cookieJar).apply {237 cloudflareSolver = webView.solve238 }239240 val res = http.request(HttpRequest(url = "https://protected.domain/page"))241 assertEquals(200, res.statusCode)242 assertEquals("<html>cleared by webview</html>", res.body)243 assertEquals(1, webView.resolveCalls)244 }245}246