package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
class EnhancedHttpStreamCloudflareTest {
private val image = byteArrayOf(1, 2, 3)
private val challengePage = "
Just a moment...".encodeToByteArray()
/** Serves [image] only with the proxy's clearance + UA; otherwise a Cloudflare challenge, per the stream contract. */
private class ProtectedHost(
private val image: ByteArray,
private val challenge: HttpStreamResponse,
private val onChallenged: () -> Unit = {},
private val beforeSolve: suspend () -> Unit = {},
) : HttpService {
val proxyRequests = mutableListOf()
val streams = mutableListOf()
override suspend fun request(request: HttpRequest): HttpResponse {
proxyRequests += request
beforeSolve()
return HttpResponse(
statusCode = 200,
body = """{"status":"ok","solution":{"userAgent":"Solver/1",
"cookies":[{"name":"cf_clearance","value":"CLEAR","domain":".example.org"}]}}""",
)
}
override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
streams += request
val cleared = "cf_clearance=CLEAR" in request.headers["Cookie"].orEmpty() &&
request.headers["User-Agent"] == "Solver/1"
if (!cleared) {
onChallenged()
return challenge
}
onChunk(image)
return HttpStreamResponse(statusCode = 200)
}
}
private suspend fun service(delegate: HttpService, proxyUrl: String = "http://127.0.0.1:8191"): EnhancedHttpService {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
database.updateSettings(database.settings().copy(cloudflareBypassProxyUrl = proxyUrl))
return EnhancedHttpService(delegate, database, CookieJar(database))
}
private fun challenge(headers: Map) = HttpStreamResponse(statusCode = 403, headers = headers, body = challengePage)
@Test
fun streamChallengeIsSolvedThenRetriedOnceWithFreshCookieAndUserAgent() = runTest {
val host = ProtectedHost(image, challenge(mapOf("cf-mitigated" to "challenge")))
val http = service(host)
val received = mutableListOf()
val response = http.stream(HttpRequest(url = "https://img.example.org/p1.jpg")) { received += it.toList() }
assertEquals(200, response.statusCode)
assertContentEquals(image, received.toByteArray(), "challenge page bytes must never reach onChunk")
assertEquals(2, host.streams.size)
val proxy = host.proxyRequests.single()
assertEquals("http://127.0.0.1:8191/v1", proxy.url, "bare host:port posts to the FlareSolverr endpoint")
assertEquals(true, Json.parseToJsonElement(proxy.body.orEmpty()).jsonObject["returnOnlyCookies"]?.jsonPrimitive?.boolean)
}
@Test
fun plainForbiddenFromCloudflareIsNotSolved() = runTest {
val hotlinkBlock = challenge(mapOf("Server" to "cloudflare", "Content-Type" to "image/jpeg"))
val host = ProtectedHost(image, hotlinkBlock)
val http = service(host)
var webViewCalled = false
http.cloudflareSolver = { _, _ ->
webViewCalled = true
null
}
var chunks = 0
val response = http.stream(HttpRequest(url = "https://img.example.org/p1.jpg")) { chunks++ }
assertEquals(403, response.statusCode)
assertEquals(1, host.streams.size)
assertEquals(0, host.proxyRequests.size)
assertFalse(webViewCalled)
assertEquals(0, chunks)
}
@Test
fun parallelChallengedStreamsShareOneSolve() = runTest {
val pages = 5
var challenged = 0
val allChallenged = CompletableDeferred()
val host = ProtectedHost(
image,
challenge(mapOf("Server" to "cloudflare", "Content-Type" to "text/html")),
onChallenged = { if (++challenged == pages) allChallenged.complete(Unit) },
// Hold the first solve until every page has hit the challenge and queued behind it.
beforeSolve = { allChallenged.await() },
)
val http = service(host)
val statuses = (1..pages).map { page ->
async { http.stream(HttpRequest(url = "https://img.example.org/p$page.jpg")) {}.statusCode }
}.awaitAll()
assertEquals(List(pages) { 200 }, statuses)
assertEquals(1, host.proxyRequests.size)
assertEquals(pages * 2, host.streams.size)
}
@Test
fun explicitProxyPathIsKept() {
assertEquals("http://solver:8191/v1", cloudflareProxyEndpoint("solver:8191/"))
assertEquals("https://solver.lan/api/v1", cloudflareProxyEndpoint("https://solver.lan/api/v1"))
}
}