Repository Public License
1import Foundation2import NavigatorCore3import TestSupport4import Testing5import WebKit6@testable import WebRuntime78extension WebRuntimeTests {9 @Suite struct Popups {10 @Test func popupWithoutUserGestureIsBlockedAndCounted() async throws {11 try await withHarness { harness in12 let engine = harness.makeEngine()13 let spy = NavigationSpy()14 engine.navigationDelegate = spy15 try await harness.load(engine, "/popup/auto", expectingTitle: "popup-blocked")16 #expect(spy.children.isEmpty)17 #expect(engine.blockedPopups.count == 1)18 #expect(engine.blockedPopups.first?.url == harness.server.url("/page/popup-target"))19 #expect(engine.blockedPopups.first?.sourceOrigin == WebOrigin(url: harness.server.baseURL))20 #expect(harness.server.requests(path: "/page/popup-target").isEmpty)2122 // The user can still open it from the "popup blocked" notice: as an unrelated tab.23 engine.openBlockedPopup(try #require(engine.blockedPopups.first))24 #expect(engine.blockedPopups.isEmpty)25 #expect(spy.newTabRequests.map(\.url) == [harness.server.url("/page/popup-target")])2627 // The count is per page.28 try await harness.load(engine, "/popup/auto", expectingTitle: "popup-blocked")29 #expect(engine.blockedPopups.count == 1)30 try await harness.load(engine, "/", expectingTitle: "Fixture Home")31 #expect(engine.blockedPopups.isEmpty)32 }33 }3435 @Test func sitePermissionAllowsPopupsAndChildIsARealTab() async throws {36 try await withHarness { harness in37 let origin = try #require(WebOrigin(url: harness.server.baseURL))38 await harness.permissions.set(.allow, .popups, origin)39 let engine = harness.makeEngine()40 let spy = NavigationSpy()41 engine.navigationDelegate = spy42 // The verdict is cached when a page of the site commits; the popup page comes second.43 try await harness.load(engine, "/", expectingTitle: "Fixture Home")44 try await waitUntil("popup verdict cached") { engine.popupVerdicts[origin] == .allow }45 try await harness.load(engine, "/popup/auto", expectingTitle: "popup-opened")4647 #expect(engine.blockedPopups.isEmpty)48 let (child, request) = try #require(spy.children.first)49 harness.adopt(child)50 #expect(request.openerTabID == engine.id && child.openerID == engine.id)51 #expect(request.url == harness.server.url("/page/popup-target"))52 #expect(!request.isUserGesture)53 try await waitUntil("child loaded") { child.title == "Fixture popup-target" && !child.isLoading }54 #expect(child.profile === engine.profile)55 #expect(child.webView?.configuration.websiteDataStore === engine.webView?.configuration.websiteDataStore)5657 // The child has its own bridge: its reports reach the child, not the opener.58 #expect(child.webView?.configuration.userContentController !== engine.webView?.configuration.userContentController)59 try await waitUntil("child metadata") { child.metadata?.title == "Fixture popup-target" }60 #expect(engine.metadata?.title == "popup-opened" || engine.metadata?.title == "Auto Popup Fixture")61 #expect(engine.rejectedBridgeMessageCount == 0 && child.rejectedBridgeMessageCount == 0)62 #expect(await child.string("return String(window.opener !== null);") == "true")63 }64 }6566 @Test func windowOpenAfterUserActivationAndTargetBlankLink() async throws {67 try await withHarness { harness in68 let engine = harness.makeEngine()69 let spy = NavigationSpy()70 engine.navigationDelegate = spy71 try await harness.load(engine, "/popup", expectingTitle: "Popup Fixture")7273 // A script-synthesised click is not a trusted event: no activation is reported, the popup is blocked.74 try await engine.evaluate("document.getElementById('open').click();")75 try await waitUntil("blocked without trusted input") { engine.blockedPopups.count == 1 }76 #expect(engine.lastUserActivation == nil)77 #expect(spy.children.isEmpty)7879 // Trusted input cannot be produced through public API in a test; the activation timestamp the80 // bridge would set is set directly, then the same window.open goes through.81 engine.lastUserActivation = .now82 try await engine.evaluate("document.getElementById('open').click();")83 try await waitUntil("popup after activation") { spy.children.count == 1 }84 #expect(spy.children[0].request.isUserGesture)85 harness.adopt(spy.children[0].child)8687 // An expired activation no longer authorises anything.88 engine.lastUserActivation = Date().addingTimeInterval(-10)89 try await engine.evaluate("document.getElementById('open').click();")90 try await waitUntil("blocked after expiry") { engine.blockedPopups.count == 2 }9192 // An activated target=_blank link always opens.93 try await engine.evaluate("document.getElementById('blank').click();")94 try await waitUntil("target=_blank child") { spy.children.count == 2 }95 let blank = spy.children[1].child96 harness.adopt(blank)97 try await waitUntil("blank target loaded") { blank.title == "Fixture blank-target" && !blank.isLoading }98 #expect(engine.title == "Popup Fixture")99 }100 }101102 @Test func delegateCanRefuseChildAndDenyBlocksScriptedWindows() async throws {103 try await withHarness { harness in104 let origin = try #require(WebOrigin(url: harness.server.baseURL))105 let engine = harness.makeEngine()106 let spy = NavigationSpy()107 spy.acceptsChildren = false108 engine.navigationDelegate = spy109 try await harness.load(engine, "/popup", expectingTitle: "Popup Fixture")110 engine.lastUserActivation = .now111 try await engine.evaluate("document.getElementById('open').click();")112 await settle()113 #expect(spy.children.isEmpty && engine.blockedPopups.isEmpty)114 #expect(harness.server.requests(path: "/page/popup-target").isEmpty)115116 // "Deny" for the site: window.open is blocked even right after a click.117 await harness.permissions.set(.deny, .popups, origin)118 engine.refreshCachedPermissions()119 try await waitUntil("deny cached") { engine.popupVerdicts[origin] == .deny }120 spy.acceptsChildren = true121 engine.lastUserActivation = .now122 try await engine.evaluate("document.getElementById('open').click();")123 try await waitUntil("blocked by site permission") { engine.blockedPopups.count == 1 }124 #expect(spy.children.isEmpty)125 }126 }127 }128129 @Suite struct Downloads {130 @Test func attachmentBecomesDownloadAndPageStays() async throws {131 try await withHarness { harness in132 let engine = harness.makeEngine()133 try await harness.load(engine, "/", expectingTitle: "Fixture Home")134 engine.load(harness.server.url("/download/attachment"))135 try await waitUntilAsync("download candidate") { await harness.downloads.candidates.count == 1 }136 let candidate = try #require(await harness.downloads.candidates.first)137 try await waitUntilAsync("download finished") { await harness.downloads.terminalEvent(candidate.id) != nil }138139 #expect(candidate.sourceURL == harness.server.url("/download/attachment"))140 #expect(candidate.originURL == harness.server.url("/"))141 #expect(candidate.profileID == engine.profile.profile.id && !candidate.isGhost)142 let response = try #require(await harness.downloads.responses[candidate.id])143 #expect(response.suggestedFilename == "report.txt")144 #expect(response.mimeType == "text/plain")145 #expect(response.expectedBytes == 24)146 let destination = try #require(await harness.downloads.destinations[candidate.id])147 #expect(await harness.downloads.terminalEvent(candidate.id) == .finished(fileURL: destination))148 #expect(try String(contentsOf: destination, encoding: .utf8) == "fixture report\nline two\n")149150 // The tab still shows the page the download was started from, without an error.151 await settle()152 #expect(engine.title == "Fixture Home" && engine.loadError == nil && !engine.isLoading)153 }154 }155156 @Test func unknownMIMETypeAndUnicodeFilenameAndDownloadAttribute() async throws {157 try await withHarness { harness in158 let engine = harness.makeEngine()159 try await harness.load(engine, "/download/page", expectingTitle: "Download Page")160161 engine.load(harness.server.url("/download/unknown"))162 try await waitUntilAsync("unknown MIME download") { await harness.downloads.candidates.count == 1 }163 let unknown = try #require(await harness.downloads.candidates.last)164 try await waitUntilAsync("unknown finished") { await harness.downloads.terminalEvent(unknown.id) != nil }165 #expect(await harness.downloads.responses[unknown.id]?.mimeType == "application/x-orix-unknown")166 let file = try #require(await harness.downloads.destinations[unknown.id])167 #expect(try Data(contentsOf: file) == Data([0x4F, 0x52, 0x49, 0x58, 0x00, 0x01, 0x02, 0x03]))168169 engine.load(harness.server.url("/download/unicode"))170 try await waitUntilAsync("unicode download") { await harness.downloads.candidates.count == 2 }171 let unicode = try #require(await harness.downloads.candidates.last)172 try await waitUntilAsync("unicode finished") { await harness.downloads.terminalEvent(unicode.id) != nil }173 #expect(await harness.downloads.responses[unicode.id]?.suggestedFilename == "résumé 日本.txt")174175 // <a download>: WebKit flags the action itself (`shouldPerformDownload`).176 try await engine.evaluate("document.getElementById('dl-attr').click();")177 try await waitUntilAsync("download attribute") { await harness.downloads.candidates.count == 3 }178 let attribute = try #require(await harness.downloads.candidates.last)179 try await waitUntilAsync("attribute finished") { await harness.downloads.terminalEvent(attribute.id) != nil }180 #expect(await harness.downloads.responses[attribute.id]?.suggestedFilename == "saved-page.html")181 #expect(engine.title == "Download Page")182183 // API-initiated download (context menu "Download Linked File").184 await engine.startDownload(harness.server.url("/page/a"))185 try await waitUntilAsync("startDownload") { await harness.downloads.candidates.count == 4 }186 }187 }188189 @Test func largeDownloadReportsProgressAndCancels() async throws {190 try await withHarness { harness in191 let engine = harness.makeEngine()192 try await harness.load(engine, "/", expectingTitle: "Fixture Home")193 let size = 3_000_000194 engine.load(harness.server.url("/download/large?size=\(size)&chunk=32768&pause=15"))195 try await waitUntilAsync("large candidate") { await harness.downloads.candidates.count == 1 }196 let candidate = try #require(await harness.downloads.candidates.first)197 try await waitUntilAsync("some progress") { (await harness.downloads.progressEvents(candidate.id).last ?? 0) > 100_000 }198 #expect(await harness.downloads.responses[candidate.id]?.expectedBytes == Int64(size))199 #expect(await harness.downloads.terminalEvent(candidate.id) == nil)200201 let control = try #require(await harness.downloads.control(candidate.id))202 let resumeData = await control.cancel()203 try await waitUntilAsync("cancelled event") { await harness.downloads.terminalEvent(candidate.id) != nil }204 guard case .cancelled(let reported) = await harness.downloads.terminalEvent(candidate.id) else {205 Issue.record("expected a cancelled event"); return206 }207 #expect(reported == resumeData)208 let progress = await harness.downloads.progressEvents(candidate.id)209 #expect(progress == progress.sorted(), "progress must arrive in order")210 #expect((progress.last ?? 0) < Int64(size))211212 // Resume: the fixture supports Range + ETag, so WebKit hands out resume data.213 let data = try #require(resumeData, "WebKit produced no resume data for a range-capable server")214 let destination = try #require(await harness.downloads.destinations[candidate.id])215 let before = harness.server.requests(path: "/download/large").count216 await engine.resumeDownload(resumeData: data, id: candidate.id, destination: destination)217 try await waitUntilAsync("resumed download finished", timeout: 30) {218 if case .finished = await harness.downloads.terminalEvent(candidate.id) { true } else { false }219 }220 let resumed = try #require(harness.server.requests(path: "/download/large").dropFirst(before).first)221 #expect(resumed.header("range")?.hasPrefix("bytes=") == true)222 #expect(resumed.header("range") != "bytes=0-")223 #expect(try Data(contentsOf: destination) == FixtureRoutes.largeBody(size: size))224 }225 }226227 @Test func sinkCanRefuseDestination() async throws {228 try await withHarness { harness in229 await harness.downloads.setRefuseAll(true)230 let engine = harness.makeEngine()231 engine.load(harness.server.url("/download/attachment"))232 try await waitUntilAsync("candidate") { await harness.downloads.candidates.count == 1 }233 let candidate = try #require(await harness.downloads.candidates.first)234 try await waitUntilAsync("cancelled") { await harness.downloads.terminalEvent(candidate.id) != nil }235 guard case .cancelled = await harness.downloads.terminalEvent(candidate.id) else {236 Issue.record("expected cancellation, got \(String(describing: await harness.downloads.terminalEvent(candidate.id)))"); return237 }238 #expect(try FileManager.default.contentsOfDirectory(atPath: harness.downloadDirectory.url.path).isEmpty)239 }240 }241 }242243 @Suite struct Authentication {244 @Test func basicAuthGoesThroughDelegate() async throws {245 try await withHarness { harness in246 let engine = harness.makeEngine()247 // Without a UI nobody can type a password: the server's 401 page is shown.248 try await harness.load(engine, "/auth/basic", expectingTitle: "Unauthorized")249250 let ui = UISpy()251 engine.uiDelegate = ui252 ui.authenticationResponse = { request in253 request.previousFailureCount == 0254 ? .credential(user: FixtureRoutes.basicAuthUser, password: "wrong", rememberForSession: false)255 : .credential(user: FixtureRoutes.basicAuthUser, password: FixtureRoutes.basicAuthPassword, rememberForSession: false)256 }257 try await harness.load(engine, "/auth/basic", expectingTitle: "Authenticated")258 #expect(ui.authenticationRequests.count == 2)259 let request = try #require(ui.authenticationRequests.first)260 #expect(request.host == "127.0.0.1" && request.port == harness.server.port)261 #expect(request.realm == FixtureRoutes.basicAuthRealm)262 #expect(request.method == .basic && !request.isProxy)263 // Plain http: the prompt must warn that the password travels in clear text.264 #expect(!request.isSecureTransport)265 #expect(ui.authenticationRequests[1].previousFailureCount == 1)266 // Nothing went to the persistent credential store.267 let space = URLProtectionSpace(host: "127.0.0.1", port: harness.server.port, protocol: "http",268 realm: FixtureRoutes.basicAuthRealm, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)269 #expect(URLCredentialStorage.shared.credentials(for: space) == nil)270 }271 }272273 @Test func cancellingThePromptShowsTheServerPage() async throws {274 try await withHarness { harness in275 let engine = harness.makeEngine()276 let ui = UISpy()277 engine.uiDelegate = ui278 try await harness.load(engine, "/auth/basic", expectingTitle: "Unauthorized")279 #expect(ui.authenticationRequests.count == 1)280 #expect(engine.loadError == nil)281 }282 }283 }284}285