package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.services.http.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.test.runTest import kotlinx.serialization.json.* import kotlin.test.* class Aria2RpcClientTest { @Test fun rpcTimeoutIsAnOrdinaryFailureAndDoesNotCancelTheQueueOwner() = runTest { val hanging = HttpService { kotlinx.coroutines.awaitCancellation() } assertFailsWith { Aria2RpcClient(hanging, "https://aria.example.org/jsonrpc", "").version() } assertTrue(kotlinx.coroutines.currentCoroutineContext()[kotlinx.coroutines.Job]?.isActive == true) } private val gid = "1234567890abcdef" private val otherGid = "abcdef1234567890" @Test fun admissionUsesPersistableIdentityTokenHeadersAndNoOverwriteOptions() = runTest { val client = client { request -> assertEquals("aria2.addUri", request["method"]?.jsonPrimitive?.content) val params = request.getValue("params").jsonArray assertEquals("token:private-token", params[0].jsonPrimitive.content) assertEquals("https://images.example.org/page.jpg", params[1].jsonArray[0].jsonPrimitive.content) val options = params[2].jsonObject assertEquals(gid, options["gid"]?.jsonPrimitive?.content) assertEquals("false", options["allow-overwrite"]?.jsonPrimitive?.content) assertEquals("false", options["auto-file-renaming"]?.jsonPrimitive?.content) assertEquals("true", options["continue"]?.jsonPrimitive?.content) assertEquals("Referer: https://source.example.org", options["header"]?.jsonArray?.single()?.jsonPrimitive?.content) JsonPrimitive(gid) } client.addUri(gid, "https://images.example.org/page.jpg", "/downloads/Title", "0001.jpg", mapOf("Referer" to "https://source.example.org")) } @Test fun controlsOnlyTouchTheRequestedGidAndNeverGlobalQueue() = runTest { val methods = mutableListOf() val client = client { request -> val method = request.getValue("method").jsonPrimitive.content methods += method assertEquals(gid, request.getValue("params").jsonArray.last().jsonPrimitive.content) JsonPrimitive(if (method == "aria2.removeDownloadResult") "OK" else gid) } client.pause(gid); client.resume(gid); client.cancel(gid); client.forgetResult(gid) assertEquals(listOf("aria2.forcePause", "aria2.unpause", "aria2.forceRemove", "aria2.removeDownloadResult"), methods) } @Test fun batchResponsesAreMatchedByIdentityAndKeepPerFileFailures() = runTest { val transport = HttpService { request -> val requests = Json.parseToJsonElement(requireNotNull(request.body)).jsonArray val response = JsonArray(requests.reversed().map { element -> val call = element.jsonObject val requested = call["params"]?.jsonArray?.get(1)?.jsonPrimitive?.content buildJsonObject { put("jsonrpc", "2.0"); put("id", call.getValue("id")) if (requested == otherGid) put("error", buildJsonObject { put("code", 1); put("message", "secret message must not leak") }) else put("result", progress(gid)) } }) HttpResponse(200, response.toString()) } val result = Aria2RpcClient(transport, "https://aria.example.org/jsonrpc", "token").statuses(listOf(gid, otherGid)) assertEquals(Aria2Status.Active, result.getValue(gid).getOrThrow().status) assertEquals(50L, result.getValue(gid).getOrThrow().completedBytes) val error = assertIs(result.getValue(otherGid).exceptionOrNull()) assertEquals(1, error.code) assertFalse(error.message.orEmpty().contains("secret")) } @Test fun invalidIdentitiesPathsAndHeaderInjectionAreRejectedBeforeNetwork() = runTest { val client = client { error("Must not contact server") } for (bad in listOf("1", "0000000000000000", "../other", "gggggggggggggggg")) assertFailsWith { client.cancel(bad) } for (name in listOf("../page.jpg", "page\n.jpg", "..", "")) assertFailsWith { client.addUri(gid, "https://source.example.org/page", "/downloads", name, emptyMap()) } assertFailsWith { client.addUri(gid, "https://source.example.org/page", "/downloads", "page.jpg", mapOf("Referer" to "ok\r\nCookie: secret")) } assertFalse(Aria2RpcClient.validEndpoint("https://user:secret@aria.example.org/jsonrpc")) assertFalse(Aria2RpcClient.validEndpoint("https://aria.example.org/jsonrpc?token=secret")) assertTrue(Aria2RpcClient.validEndpoint("http://localhost:6800/jsonrpc")) } @Test fun mismatchedResponseIdentityAndUnexpectedAdmissionGidFail() = runTest { assertFailsWith { client { JsonPrimitive(otherGid) }.addUri(gid, "https://source.example.org/page", "/downloads", "page.jpg", emptyMap()) } val transport = HttpService { HttpResponse(200, "{\"jsonrpc\":\"2.0\",\"id\":\"other-request\",\"result\":{\"version\":\"1.37\"}}") } assertFailsWith { Aria2RpcClient(transport, "https://aria.example.org/jsonrpc", "").version() } } @Test fun oversizedResponseAndCancellationDoNotBecomeSuccessfulRequests() = runTest { val oversized = HttpService { HttpResponse(200, " ".repeat(1024 * 1024 + 1)) } assertFailsWith { Aria2RpcClient(oversized, "https://aria.example.org/jsonrpc", "").version() } val cancelled = HttpService { throw CancellationException("profile retired") } assertFailsWith { Aria2RpcClient(cancelled, "https://aria.example.org/jsonrpc", "").version() } } private fun progress(gid: String) = buildJsonObject { put("gid", gid); put("status", "active"); put("totalLength", "100"); put("completedLength", "50"); put("downloadSpeed", "10") } private fun client(action: (JsonObject) -> JsonElement): Aria2RpcClient { val http = HttpService { request -> assertEquals("POST", request.method) assertEquals("application/json", request.headers["Content-Type"]) val call = Json.parseToJsonElement(requireNotNull(request.body)).jsonObject HttpResponse(200, buildJsonObject { put("jsonrpc", "2.0"); put("id", call.getValue("id")); put("result", action(call)) }.toString()) } return Aria2RpcClient(http, "https://aria.example.org/jsonrpc", "private-token") } }