MangayomiSyncServiceTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncServiceTest.kt
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.database.DbSyncPreference4import eu.friedcutlet.yokan.database.DbManga5import eu.friedcutlet.yokan.database.InMemoryYokanDatabase6import eu.friedcutlet.yokan.database.SyncServerProvider7import eu.friedcutlet.yokan.database.emptySnapshot8import eu.friedcutlet.yokan.services.http.HttpRequest9import eu.friedcutlet.yokan.services.http.HttpResponse10import eu.friedcutlet.yokan.services.http.HttpService11import eu.friedcutlet.yokan.services.http.RecordingHttpService12import kotlin.test.Test13import kotlin.test.assertEquals14import kotlin.test.assertFalse15import kotlin.test.assertTrue16import kotlin.test.assertNotNull17import kotlinx.coroutines.test.runTest18import kotlinx.serialization.json.Json19import kotlinx.serialization.json.jsonArray20import kotlinx.serialization.json.jsonObject21import kotlinx.serialization.json.jsonPrimitive2223class MangayomiSyncServiceTest {24 @Test25 fun loginRequiresRealSessionCookieAndStoresProvider() = runTest {26 val db = InMemoryYokanDatabase(emptySnapshot())27 val http = RecordingHttpService { HttpResponse(200, """{"ok":true}""", setCookies = listOf("id=jwt-value; Path=/; HttpOnly")) }28 val service = MangayomiSyncService(db, http)29 val result = service.login(1, "https://mangayomi.test/", "user", "secret")30 assertTrue(result.success, result.message)31 assertEquals("https://mangayomi.test/api/login", http.requests.single().url)32 assertEquals(SyncServerProvider.Mangayomi, db.syncPreferences().single().serverProvider)33 assertEquals("jwt-value", db.syncPreferences().single().authToken)3435 val badDb = InMemoryYokanDatabase(emptySnapshot())36 val noCookie = MangayomiSyncService(badDb, HttpService { HttpResponse(200, """{"ok":true}""") })37 assertFalse(noCookie.login(1, "https://mangayomi.test", "user", "secret").success)38 assertTrue(badDb.syncPreferences().isEmpty())39 }4041 @Test42 fun rejectsTotpInsteadOfClaimingAuthenticated() = runTest {43 val db = InMemoryYokanDatabase(emptySnapshot())44 val service = MangayomiSyncService(db, HttpService { HttpResponse(200, """{"ok":true,"requiresTotp":true,"pendingToken":"pending"}""", setCookies = listOf("id=not-session")) })45 val result = service.login(1, "https://mangayomi.test", "user", "secret")46 assertFalse(result.success)47 assertTrue(db.syncPreferences().isEmpty())48 }4950 @Test51 fun browserLoginExchangesCodeWithMatchingPkceVerifierOnceAndIgnoresOtherPages() = runTest {52 val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(53 DbSyncPreference(syncId = 1, serverProvider = SyncServerProvider.Mangayomi))))54 val http = RecordingHttpService { HttpResponse(200, """{"access_token":"jwt-oauth","token_type":"Bearer","expires_in":60,"username":"reader"}""") }55 val service = MangayomiSyncService(db, http)56 val attempt = assertNotNull(service.beginBrowserLogin(1, "https://mangayomi.test/"))57 val authorize = io.ktor.http.Url(attempt.url)58 assertEquals("/api/oauth/authorize", authorize.encodedPath)59 assertEquals("S256", authorize.parameters["code_challenge_method"])60 val redirect = assertNotNull(authorize.parameters["redirect_uri"])61 assertEquals(redirect, attempt.callbackUrl)6263 // Pages of the server's own login flow are not the callback, and a forged state never reaches the server.64 assertEquals(null, service.completeBrowserLogin(attempt, "https://mangayomi.test/login?next=%2Fapi%2Foauth%2Fauthorize"))65 assertEquals(null, service.completeBrowserLogin(attempt, "$redirect/extra?code=c&state=${attempt.state}"))66 assertTrue(http.requests.isEmpty())6768 val result = assertNotNull(service.completeBrowserLogin(attempt, "$redirect?code=one-use&state=${attempt.state}"))69 assertTrue(result.success, result.message)70 val exchange = Json.parseToJsonElement(http.requests.single().body!!).jsonObject71 assertEquals("https://mangayomi.test/api/oauth/token", http.requests.single().url)72 assertEquals("one-use", exchange.getValue("code").jsonPrimitive.content)73 assertEquals(redirect, exchange.getValue("redirectUri").jsonPrimitive.content)74 val verifier = exchange.getValue("codeVerifier").jsonPrimitive.content75 assertTrue(verifier.length in 43..128)76 val challenge = kotlin.io.encoding.Base64.UrlSafe.withPadding(kotlin.io.encoding.Base64.PaddingOption.ABSENT)77 .encode(eu.friedcutlet.yokan.util.sha256(verifier.encodeToByteArray()))78 assertEquals(authorize.parameters["code_challenge"], challenge)79 val pref = db.syncPreferences().single()80 assertEquals("jwt-oauth", pref.authToken)81 assertEquals("reader", pref.email) // the server's username is the account namespace82 assertEquals("https://mangayomi.test", pref.server)8384 assertEquals(null, service.completeBrowserLogin(attempt, "$redirect?code=one-use&state=${attempt.state}"))85 assertEquals(1, http.requests.size)86 }8788 @Test89 fun browserLoginRejectsMismatchedStateWithoutExchangingTheCode() = runTest {90 val db = InMemoryYokanDatabase(emptySnapshot())91 val http = RecordingHttpService { HttpResponse(200, """{"access_token":"stolen","username":"attacker"}""") }92 val service = MangayomiSyncService(db, http)93 val attempt = assertNotNull(service.beginBrowserLogin(1, "https://mangayomi.test"))94 val result = assertNotNull(service.completeBrowserLogin(attempt, "${attempt.callbackUrl}?code=c&state=forged"))95 assertFalse(result.success)96 assertTrue(http.requests.isEmpty())97 assertTrue(db.syncPreferences().isEmpty())98 }99100 @Test101 fun syncUploadsMappedRowsWithCookieAndFullPullsBeforeWatermarkCommit() = runTest {102 val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test/Case", email = "user", authToken = "jwt",103 syncOn = true, serverProvider = SyncServerProvider.Mangayomi)104 val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref), mangas = listOf(DbManga(105 id = 29, name = "Title", link = "/title", source = "source", favorite = true, updatedAt = 1_700_000_000_000,106 ))))107 val http = ScriptedSyncHttp(listOf(108 HttpResponse(200, """{"supported":["1"]}"""),109 completePage(), // mapping bootstrap pull110 completePage(), // manga upload111 completePage(), // full post-upload pull112 ))113 val result = MangayomiSyncService(db, http).sync(1, db.settings())114 assertTrue(result.errors.isEmpty(), result.errors.toString())115 val posts = http.requests.filter { it.url.endsWith("/api/sync/v1") }116 assertEquals(3, posts.size)117 assertTrue(posts.all { it.headers["Cookie"] == "id=jwt" })118 assertTrue(posts.all { it.body?.contains("\"since\":0") == true })119 val upload = posts[1].body?.let { Json.parseToJsonElement(it).jsonObject }120 val manga = assertNotNull(upload?.get("manga")).jsonArray.single().jsonObject121 val safeId = manga["clientId"]!!.jsonPrimitive.content.toLong()122 assertTrue(safeId in 1..9_007_199_254_740_991L)123 assertEquals(1_700_000_000_000L, manga["updatedAt"]!!.jsonPrimitive.content.toLong())124 assertNotNull(db.syncPreferences().single().mangayomiIdMappings)125 assertEquals(1_700_000_000_100L, db.syncPreferences().single().lastSyncManga)126 }127128 @Test129 fun failedUploadDoesNotAcknowledgeTombstoneOrAdvanceWatermark() = runTest {130 val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",131 syncOn = true, serverProvider = SyncServerProvider.Mangayomi,132 mangayomiIdMappings = """{"version":1,"namespaces":{"https://mangayomi.test\nuser":{"2":{"42":{"canonical":4200,"aliases":[]}}}}}""")133 val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref), mangas = listOf(DbManga(134 id = 42, name = "Deleted", link = "/deleted", source = "source", updatedAt = 10,135 ))))136 db.removeManga(42)137 val http = ScriptedSyncHttp(listOf(138 HttpResponse(200, """{"supported":["1"]}"""), completePage(), HttpResponse(500, "server error"),139 ))140 val result = MangayomiSyncService(db, http).sync(1, db.settings())141 assertFalse(result.errors.isEmpty())142 assertTrue(db.changedParts().any { it.data.contains("\"provider\":\"mangayomi\"") })143 assertEquals(null, db.syncPreferences().single().lastSyncManga)144 }145146 @Test147 fun invalidVersionPreventsSyncPostAndExactPreferenceLookupHasNoFallback() = runTest {148 val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",149 serverProvider = SyncServerProvider.Mangayomi)150 val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref)))151 val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["2"]}""")))152 val result = MangayomiSyncService(db, http).sync(1, db.settings())153 assertFalse(result.errors.isEmpty())154 assertEquals(1, http.requests.size)155 val otherDb = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref.copy(syncId = 2))))156 assertEquals(null, MangayomiSyncService(otherDb, http).status(1).server)157 }158159 @Test160 fun unevenPagesRetainOpaqueCursorAndSessionUntilComplete() = runTest {161 val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",162 serverProvider = SyncServerProvider.Mangayomi)163 val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref)))164 val http = ScriptedSyncHttp(listOf(165 HttpResponse(200, """{"supported":["1"]}"""),166 page(hasMore = true, syncedAt = null, cursor = "boot-1", token = "st-1"),167 completePage(), // bootstrap second page168 completePage(), // empty upload batch169 page(hasMore = true, syncedAt = null, cursor = "pull-1", token = "st-2"),170 completePage(), // final pull second page171 ))172 val result = MangayomiSyncService(db, http).sync(1, db.settings())173 assertTrue(result.errors.isEmpty(), result.errors.toString())174 val posts = http.requests.filter { it.url.endsWith("/api/sync/v1") }175 val continuation = Json.parseToJsonElement(posts[1].body!!).jsonObject176 assertEquals("boot-1", continuation["cursors"]!!.jsonObject["manga"]!!.jsonPrimitive.content)177 assertEquals("st-1", continuation["sessionToken"]!!.jsonPrimitive.content)178 assertEquals(1_700_000_000_100L, db.syncPreferences().single().lastSyncManga)179 }180181 @Test182 fun uploadOnlyUsesBootstrapIdentityWithoutApplyingRemoteRowsOrTombstones() = runTest {183 val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",184 serverProvider = SyncServerProvider.Mangayomi)185 val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref), mangas = listOf(DbManga(186 id = 29, name = "Local", link = "/title", source = "source", favorite = true, updatedAt = 100,187 ))))188 val remote = HttpResponse(200, """{"hasMore":false,"syncedAt":1700000000100,"sessionToken":"s","cursors":{},"categories":[],"manga":[{"clientId":4200,"source":"source","link":"/title","itemType":"MANGA","status":"UNKNOWN","name":"Remote newer","updatedAt":999}],"chapters":[],"tracks":[],"histories":[],"updates":[],"tombstones":{"categories":[],"manga":[4200],"chapters":[],"tracks":[],"histories":[],"updates":[]}}""")189 val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["1"]}"""), remote, completePage()))190 val result = MangayomiSyncService(db, http).pushChanges(1)191 assertTrue(result.errors.isEmpty(), result.errors.toString())192 assertEquals("Local", db.manga(29)?.name)193 assertEquals(null, db.syncPreferences().single().lastSyncManga)194 val posts = http.requests.filter { it.url.endsWith("/api/sync/v1") }195 assertEquals(2, posts.size)196 val upload = Json.parseToJsonElement(posts.last().body!!).jsonObject197 assertEquals("4200", upload["manga"]!!.jsonArray.single().jsonObject["clientId"]!!.jsonPrimitive.content)198 }199200 @Test201 fun completionAcknowledgesOnlyCapturedDeletionRecordsNotSameIdReplacement() = runTest {202 val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",203 serverProvider = SyncServerProvider.Mangayomi,204 mangayomiIdMappings = """{"version":1,"namespaces":{"https://mangayomi.test\nuser":{"2":{"42":{"canonical":4200,"aliases":[]}}}}}""")205 val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref), mangas = listOf(DbManga(id = 42, name = "removed"))))206 db.removeManga(42)207 val captured = db.changedParts().single()208 val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["1"]}"""), completePage(), completePage(), completePage()))209 http.beforeResponse = { request ->210 if (request.url.endsWith("/api/sync/v1") && http.requests.count { it.url.endsWith("/api/sync/v1") } == 3) {211 val snapshot = db.snapshot()212 db.replaceAll(snapshot.copy(changedParts = listOf(captured.copy(213 data = captured.data.replace("\"localId\":\"42\"", "\"localId\":\"43\""),214 isarId = 43,215 ))), snapshot)216 }217 }218 val result = MangayomiSyncService(db, http).sync(1, db.settings())219 assertTrue(result.errors.isEmpty(), result.errors.toString())220 assertEquals(43L, Json.parseToJsonElement(db.changedParts().single().data).jsonObject["localId"]!!.jsonPrimitive.content.toLong())221 }222223 @Test224 fun uploadRemapPersistsBeforeContinuationFailureAndConcurrentDelete() = runTest {225 val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",226 serverProvider = SyncServerProvider.Mangayomi)227 val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref),228 mangas = listOf(DbManga(id = 29, name = "M", link = "/m", source = "s")),229 chapters = listOf(eu.friedcutlet.yokan.database.DbChapter(id = 30, mangaId = 29, name = "C", url = "/c"))))230 val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["1"]}"""), completePage()))231 var canonicalWireId: Long? = null232 http.responseFor = { request ->233 if (!request.url.endsWith("/api/sync/v1")) null else {234 val payload = request.body?.let { Json.parseToJsonElement(it).jsonObject }.orEmpty()235 val manga = payload["manga"] as? kotlinx.serialization.json.JsonArray236 val chapters = payload["chapters"] as? kotlinx.serialization.json.JsonArray237 when {238 !manga.isNullOrEmpty() -> {239 canonicalWireId = manga.single().jsonObject["clientId"]!!.jsonPrimitive.content.toLong()240 HttpResponse(200, """{"hasMore":true,"syncedAt":null,"sessionToken":"continued","cursors":{"manga":"opaque"},"mangaClientIdRemap":{"$canonicalWireId":9000}}""")241 }242 !chapters.isNullOrEmpty() -> {243 db.removeManga(29)244 db.removeChapter(30)245 HttpResponse(500, "later chunk failed")246 }247 else -> null248 }249 }250 }251 val result = MangayomiSyncService(db, http).sync(1, db.settings())252 assertFalse(result.errors.isEmpty())253 val mappings = Json.parseToJsonElement(db.syncPreferences().single().mangayomiIdMappings!!).jsonObject254 .getValue("namespaces").jsonObject.getValue("https://mangayomi.test\nuser").jsonObject255 .getValue("2").jsonObject.getValue("29").jsonObject256 assertEquals("9000", mappings.getValue("canonical").jsonPrimitive.content)257 assertTrue(canonicalWireId != null)258 assertEquals(2, db.changedParts().size)259 val chapterRequest = http.requests.last { it.body?.contains("\"chapters\"") == true }260 assertTrue(chapterRequest.body!!.contains("\"sessionToken\":\"continued\""))261 }262263 @Test264 fun repeatedEntityAcrossPagesKeepsGreatestUpdatedAt() = runTest {265 val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",266 serverProvider = SyncServerProvider.Mangayomi)267 val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref)))268 val row10 = """{"clientId":555,"source":"s","link":"/m","itemType":"MANGA","status":"UNKNOWN","name":"older","updatedAt":10}"""269 val row20 = """{"clientId":555,"source":"s","link":"/m","itemType":"MANGA","status":"UNKNOWN","name":"newer","updatedAt":20}"""270 val firstPage = HttpResponse(200, """{"hasMore":true,"syncedAt":null,"sessionToken":"s","cursors":{"manga":"c1"},"manga":[$row10],"categories":[],"chapters":[],"tracks":[],"histories":[],"updates":[],"tombstones":{}}""")271 val secondPage = HttpResponse(200, """{"hasMore":false,"syncedAt":1700000000100,"sessionToken":"s","cursors":{"manga":null},"manga":[$row20],"categories":[],"chapters":[],"tracks":[],"histories":[],"updates":[],"tombstones":{}}""")272 val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["1"]}"""), firstPage, secondPage, completePage(), completePage()))273 val result = MangayomiSyncService(db, http).sync(1, db.settings())274 assertTrue(result.errors.isEmpty(), result.errors.toString())275 assertEquals("newer", db.mangas().single().name)276 assertEquals(20L, db.mangas().single().updatedAt)277 }278279 @Test280 fun tombstoneStillAppliesWhenLocalWriteDuringPullForcesMergeRetry() = runTest {281 val pref = DbSyncPreference(syncId = 1, server = "https://mangayomi.test", email = "user", authToken = "jwt",282 serverProvider = SyncServerProvider.Mangayomi,283 mangayomiIdMappings = """{"version":1,"namespaces":{"https://mangayomi.test\nuser":{"2":{"42":{"canonical":4200,"aliases":[]},"43":{"canonical":4300,"aliases":[]}}}}}""")284 val db = InMemoryYokanDatabase(emptySnapshot().copy(syncPreferences = listOf(pref),285 mangas = listOf(DbManga(id = 42, name = "deleted remotely", source = "s", link = "/a"), DbManga(id = 43, name = "kept", source = "s", link = "/b"))))286 val tombstonePage = HttpResponse(200, completePage().body.replace("\"tombstones\":{\"categories\":[],\"manga\":[]", "\"tombstones\":{\"categories\":[],\"manga\":[4200]"))287 val http = ScriptedSyncHttp(listOf(HttpResponse(200, """{"supported":["1"]}"""), completePage(), completePage(), tombstonePage))288 http.beforeResponse = { request ->289 // A reader-progress style write while the final pull is in flight makes the first persist lose its CAS.290 if (http.requests.count { it.url.endsWith("/api/sync/v1") } == 3) db.upsertManga(db.manga(43)!!.copy(name = "edited"))291 }292 val result = MangayomiSyncService(db, http).sync(1, db.settings())293 assertTrue(result.errors.isEmpty(), result.errors.toString())294 assertEquals(null, db.manga(42))295 assertEquals("edited", db.manga(43)?.name)296 }297298 private class ScriptedSyncHttp(responses: List<HttpResponse>) : HttpService {299 private val responses = responses.toMutableList()300 val requests = mutableListOf<HttpRequest>()301 var beforeResponse: suspend (HttpRequest) -> Unit = {}302 var responseFor: suspend (HttpRequest) -> HttpResponse? = { null }303 override suspend fun request(request: HttpRequest): HttpResponse {304 requests += request305 beforeResponse(request)306 return responseFor(request) ?: responses.removeAt(0)307 }308 }309310 private fun completePage() = HttpResponse(200, """{"hasMore":false,"syncedAt":1700000000100,"sessionToken":"session","cursors":{"categories":null,"manga":null,"chapters":null,"tracks":null,"histories":null,"updates":null,"tombstones":null},"categories":[],"manga":[],"chapters":[],"tracks":[],"histories":[],"updates":[],"tombstones":{"categories":[],"manga":[],"chapters":[],"tracks":[],"histories":[],"updates":[]}}""")311 private fun page(hasMore: Boolean, syncedAt: Long?, cursor: String, token: String) = HttpResponse(200,312 """{"hasMore":$hasMore,"syncedAt":${syncedAt?.toString() ?: "null"},"sessionToken":"$token","cursors":{"categories":null,"manga":"$cursor","chapters":null,"tracks":null,"histories":null,"updates":null,"tombstones":null},"categories":[],"manga":[],"chapters":[],"tracks":[],"histories":[],"updates":[],"tombstones":{"categories":[],"manga":[],"chapters":[],"tracks":[],"histories":[],"updates":[]}}""")313}314