@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.services.webview import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.emptySnapshot import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.cookies.CookieJar import eu.friedcutlet.yokan.services.http.cookies.platformBrowserIsolation import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue class ProfileWebViewServiceTest { @Test fun extraOwnersUseTheBrowserOnlyWithPlatformIsolation() = runTest { val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), Extra) val browser = FakeBrowser(); var creations = 0 val service = ProfileWebViewService(jar, null) { creations++; browser } assertEquals(platformBrowserIsolation, service.open(Request)) assertEquals(if (platformBrowserIsolation) "result" else "", service.evaluateScript(Request.url, "script")) assertEquals(if (platformBrowserIsolation) 1 else 0, creations) assertEquals(platformBrowserIsolation, jar.canUseBrowserStorage) } @Test fun retiredExtraCannotConstructOrCallTheBrowser() = runTest { val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), Extra) { false } val service = ProfileWebViewService(jar, null) { error("Browser store accessed by retired extra owner") } assertFalse(service.open(Request)); assertNull(service.resolveCloudflare(Request)) assertEquals("", service.evaluateScript(Request.url, "script")); assertNull(service.syncCookies(Request.url)) } @Test fun retiredDefaultCannotConstructOrCallTheBrowser() = runTest { val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), ProfileId.Default) { false } val service = ProfileWebViewService(jar, null) { error("Shared store accessed by retired owner") } assertFalse(service.open(Request)); assertNull(service.resolveCloudflare(Request)) assertEquals("", service.evaluateScript(Request.url, "script")); assertNull(service.syncCookies(Request.url)) } @Test fun defaultUsesOneLazyBrowserAndPreservesAllRequestArguments() = runTest { val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot())) val browser = FakeBrowser(); var creations = 0 val service = ProfileWebViewService(jar, null) { creations++; browser } assertEquals(0, creations) assertTrue(service.open(Request)); assertEquals(200, service.resolveCloudflare(Request)?.statusCode) assertEquals("result", service.evaluateScript(Request.url, "script", "agent")) assertEquals("session=cookie", service.syncCookies(Request.url)) assertEquals(1, creations) assertEquals(listOf("open:$Request", "resolve:$Request", "script:${Request.url}:script:agent", "cookies:${Request.url}"), browser.calls) } @Test fun ownerRetirementJoinsNativeCleanupAndSuppressesLateCookieHarvest() = runTest { val database = InMemoryYokanDatabase(emptySnapshot()) val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val jar = CookieJar(database, ProfileId.Default) { parent.isActive } jar.put("source.test", "session=original") val entered = CompletableDeferred(); val release = CompletableDeferred() var finalized = false val browser = FakeBrowser().apply { action = { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await(); jar.put("source.test", "session=late"); finalized = true } } } } val service = ProfileWebViewService(jar, scope) { browser } val caller = launch { service.resolveCloudflare(Request) } entered.await() val retiring = launch { parent.cancelAndJoin() } testScheduler.runCurrent(); assertFalse(retiring.isCompleted); assertFalse(caller.isCompleted) assertNull(service.syncCookies(Request.url)) release.complete(Unit); retiring.join(); caller.join() assertTrue(finalized) assertEquals("session=original", CookieJar(database).cookieHeader(Request.url)) assertEquals(1, browser.calls.size) } @Test fun callerExpiryJoinsBrowserCleanupWithoutRetiringTheOwner() = runTest { val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), ProfileId.Default) { parent.isActive } val entered = CompletableDeferred(); val release = CompletableDeferred() val browser = FakeBrowser().apply { action = { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } } } val service = ProfileWebViewService(jar, scope) { browser } val sibling = scope.launch { awaitCancellation() } val caller = launch { service.evaluateScript(Request.url, "script") } entered.await(); caller.cancel(); testScheduler.runCurrent() assertFalse(caller.isCompleted); assertTrue(parent.isActive); assertTrue(sibling.isActive) release.complete(Unit); caller.join(); browser.action = {} assertTrue(service.open(Request)) parent.cancelAndJoin() } @Test fun alreadyExpiredCallerCannotAccessTheBrowserWithImmediateDispatch() = runTest { val parent = SupervisorJob(); val scope = CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler)) var creations = 0 val service = ProfileWebViewService(CookieJar(InMemoryYokanDatabase(emptySnapshot())), scope) { creations++; FakeBrowser() } val caller = launch { currentCoroutineContext().cancel() assertFailsWith { service.open(Request) } } caller.join(); assertEquals(0, creations); assertTrue(parent.isActive) parent.cancelAndJoin() } @Test fun queuedCallCanceledBeforeDispatchCannotInitializeTheBrowser() = runTest { val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) var creations = 0 val service = ProfileWebViewService(CookieJar(InMemoryYokanDatabase(emptySnapshot())), scope) { creations++; FakeBrowser() } val caller = launch(UnconfinedTestDispatcher(testScheduler)) { service.open(Request) } parent.cancel(); testScheduler.runCurrent(); caller.join(); parent.join() assertEquals(0, creations) assertFalse(service.open(Request)) // The owner gate also covers standalone jars with no lifetime predicate. } @Test fun browserFailureDoesNotCancelAnOrdinaryParentJobOrSiblingWork() = runTest { val parent = Job(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val browser = FakeBrowser().apply { action = { error("Native browser failure") } } val service = ProfileWebViewService(CookieJar(InMemoryYokanDatabase(emptySnapshot())), scope) { browser } val sibling = scope.launch { awaitCancellation() } assertFailsWith { service.syncCookies(Request.url) } assertTrue(parent.isActive); assertTrue(sibling.isActive) browser.action = {}; assertTrue(service.open(Request)); parent.cancelAndJoin() } private class FakeBrowser : WebViewService { val calls = mutableListOf() var action: suspend () -> Unit = {} override suspend fun open(request: WebViewRequest): Boolean { calls += "open:$request"; action(); return true } override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse { calls += "resolve:$request"; action(); return HttpResponse(200, "ok") } override suspend fun evaluateScript(url: String, script: String, userAgent: String?): String { calls += "script:$url:$script:$userAgent"; action(); return "result" } override suspend fun syncCookies(url: String): String { calls += "cookies:$url"; action(); return "session=cookie" } } private companion object { val Extra = ProfileId("p_11111111111111111111111111111111") val Request = WebViewRequest("https://source.test/", "Source", mapOf("Referer" to "https://source.test")) } }