Aria2RpcClientTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/Aria2RpcClientTest.kt
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.services.http.*4import kotlinx.coroutines.CancellationException5import kotlinx.coroutines.test.runTest6import kotlinx.serialization.json.*7import kotlin.test.*89class Aria2RpcClientTest {10 @Test fun rpcTimeoutIsAnOrdinaryFailureAndDoesNotCancelTheQueueOwner() = runTest {11 val hanging = HttpService { kotlinx.coroutines.awaitCancellation() }12 assertFailsWith<Aria2RpcException> { Aria2RpcClient(hanging, "https://aria.example.org/jsonrpc", "").version() }13 assertTrue(kotlinx.coroutines.currentCoroutineContext()[kotlinx.coroutines.Job]?.isActive == true)14 }15 private val gid = "1234567890abcdef"16 private val otherGid = "abcdef1234567890"1718 @Test fun admissionUsesPersistableIdentityTokenHeadersAndNoOverwriteOptions() = runTest {19 val client = client { request ->20 assertEquals("aria2.addUri", request["method"]?.jsonPrimitive?.content)21 val params = request.getValue("params").jsonArray22 assertEquals("token:private-token", params[0].jsonPrimitive.content)23 assertEquals("https://images.example.org/page.jpg", params[1].jsonArray[0].jsonPrimitive.content)24 val options = params[2].jsonObject25 assertEquals(gid, options["gid"]?.jsonPrimitive?.content)26 assertEquals("false", options["allow-overwrite"]?.jsonPrimitive?.content)27 assertEquals("false", options["auto-file-renaming"]?.jsonPrimitive?.content)28 assertEquals("true", options["continue"]?.jsonPrimitive?.content)29 assertEquals("Referer: https://source.example.org", options["header"]?.jsonArray?.single()?.jsonPrimitive?.content)30 JsonPrimitive(gid)31 }32 client.addUri(gid, "https://images.example.org/page.jpg", "/downloads/Title", "0001.jpg", mapOf("Referer" to "https://source.example.org"))33 }3435 @Test fun controlsOnlyTouchTheRequestedGidAndNeverGlobalQueue() = runTest {36 val methods = mutableListOf<String>()37 val client = client { request ->38 val method = request.getValue("method").jsonPrimitive.content39 methods += method40 assertEquals(gid, request.getValue("params").jsonArray.last().jsonPrimitive.content)41 JsonPrimitive(if (method == "aria2.removeDownloadResult") "OK" else gid)42 }43 client.pause(gid); client.resume(gid); client.cancel(gid); client.forgetResult(gid)44 assertEquals(listOf("aria2.forcePause", "aria2.unpause", "aria2.forceRemove", "aria2.removeDownloadResult"), methods)45 }4647 @Test fun batchResponsesAreMatchedByIdentityAndKeepPerFileFailures() = runTest {48 val transport = HttpService { request ->49 val requests = Json.parseToJsonElement(requireNotNull(request.body)).jsonArray50 val response = JsonArray(requests.reversed().map { element ->51 val call = element.jsonObject52 val requested = call["params"]?.jsonArray?.get(1)?.jsonPrimitive?.content53 buildJsonObject {54 put("jsonrpc", "2.0"); put("id", call.getValue("id"))55 if (requested == otherGid) put("error", buildJsonObject { put("code", 1); put("message", "secret message must not leak") })56 else put("result", progress(gid))57 }58 })59 HttpResponse(200, response.toString())60 }61 val result = Aria2RpcClient(transport, "https://aria.example.org/jsonrpc", "token").statuses(listOf(gid, otherGid))62 assertEquals(Aria2Status.Active, result.getValue(gid).getOrThrow().status)63 assertEquals(50L, result.getValue(gid).getOrThrow().completedBytes)64 val error = assertIs<Aria2RpcException>(result.getValue(otherGid).exceptionOrNull())65 assertEquals(1, error.code)66 assertFalse(error.message.orEmpty().contains("secret"))67 }6869 @Test fun invalidIdentitiesPathsAndHeaderInjectionAreRejectedBeforeNetwork() = runTest {70 val client = client { error("Must not contact server") }71 for (bad in listOf("1", "0000000000000000", "../other", "gggggggggggggggg")) assertFailsWith<IllegalArgumentException> { client.cancel(bad) }72 for (name in listOf("../page.jpg", "page\n.jpg", "..", "")) assertFailsWith<IllegalArgumentException> { client.addUri(gid, "https://source.example.org/page", "/downloads", name, emptyMap()) }73 assertFailsWith<IllegalArgumentException> { client.addUri(gid, "https://source.example.org/page", "/downloads", "page.jpg", mapOf("Referer" to "ok\r\nCookie: secret")) }74 assertFalse(Aria2RpcClient.validEndpoint("https://user:secret@aria.example.org/jsonrpc"))75 assertFalse(Aria2RpcClient.validEndpoint("https://aria.example.org/jsonrpc?token=secret"))76 assertTrue(Aria2RpcClient.validEndpoint("http://localhost:6800/jsonrpc"))77 }7879 @Test fun mismatchedResponseIdentityAndUnexpectedAdmissionGidFail() = runTest {80 assertFailsWith<Aria2RpcException> { client { JsonPrimitive(otherGid) }.addUri(gid, "https://source.example.org/page", "/downloads", "page.jpg", emptyMap()) }81 val transport = HttpService { HttpResponse(200, "{\"jsonrpc\":\"2.0\",\"id\":\"other-request\",\"result\":{\"version\":\"1.37\"}}") }82 assertFailsWith<Aria2RpcException> { Aria2RpcClient(transport, "https://aria.example.org/jsonrpc", "").version() }83 }8485 @Test fun oversizedResponseAndCancellationDoNotBecomeSuccessfulRequests() = runTest {86 val oversized = HttpService { HttpResponse(200, " ".repeat(1024 * 1024 + 1)) }87 assertFailsWith<Aria2RpcException> { Aria2RpcClient(oversized, "https://aria.example.org/jsonrpc", "").version() }88 val cancelled = HttpService { throw CancellationException("profile retired") }89 assertFailsWith<CancellationException> { Aria2RpcClient(cancelled, "https://aria.example.org/jsonrpc", "").version() }90 }9192 private fun progress(gid: String) = buildJsonObject { put("gid", gid); put("status", "active"); put("totalLength", "100"); put("completedLength", "50"); put("downloadSpeed", "10") }93 private fun client(action: (JsonObject) -> JsonElement): Aria2RpcClient {94 val http = HttpService { request ->95 assertEquals("POST", request.method)96 assertEquals("application/json", request.headers["Content-Type"])97 val call = Json.parseToJsonElement(requireNotNull(request.body)).jsonObject98 HttpResponse(200, buildJsonObject { put("jsonrpc", "2.0"); put("id", call.getValue("id")); put("result", action(call)) }.toString())99 }100 return Aria2RpcClient(http, "https://aria.example.org/jsonrpc", "private-token")101 }102}103