Repository Public
1import WebKit2import XCTest3@testable import SPBrowser45/// SP Search inside real tabs and windows (real WKWebView, real scheme handler), and what is — and is not —6/// handed to synchronization. The backend address points at a closed port: these tests exercise the browser,7/// not the provider (covered by the core integration and live tests).8@MainActor9final class SearchAndSyncAppTests: XCTestCase {10 private var root: URL!11 private var environment: AppEnvironment!12 private var state: BrowserWindowState!13 private var privateState: BrowserWindowState!1415 override func setUp() async throws {16 root = FileManager.default.temporaryDirectory.appendingPathComponent("spb-search-tests-" + UUID().uuidString, isDirectory: true)17 environment = AppEnvironment(root: root, secrets: InMemorySecretStore(),18 backend: BackendConfiguration(baseURL: URL(string: "http://127.0.0.1:9")!, relyingParty: "browser.test"))19 state = BrowserWindowState(environment: environment, profile: environment.defaultContext)20 privateState = BrowserWindowState(environment: environment, profile: try ProfileContext(privateFrom: environment.defaultContext))21 }2223 override func tearDown() async throws {24 state.teardown(); privateState.teardown()25 state = nil; privateState = nil26 await environment.removeAllWebsiteDataStores()27 environment = nil28 try? FileManager.default.removeItem(at: root)29 }3031 private func waitUntil(_ timeout: TimeInterval = 15, _ condition: () -> Bool) async -> Bool {32 let deadline = Date().addingTimeInterval(timeout)33 while Date() < deadline {34 if condition() { return true }35 try? await Task.sleep(for: .milliseconds(40))36 }37 return condition()38 }3940 func testTypedQueryOpensNativeSearchPageNotDuckDuckGo() async {41 let tab = state.newTab()42 state.navigate("best apple silicon computers for local ai", in: tab)43 XCTAssertEqual(tab.url?.scheme, "spsearch")44 XCTAssertTrue(tab.isSearchPage)45 XCTAssertEqual(tab.searchPage?.query, "best apple silicon computers for local ai")46 XCTAssertEqual(tab.searchPage?.kind, .web)47 XCTAssertEqual(tab.displayTitle, "best apple silicon computers for local ai")48 let committed = await waitUntil { !tab.isLoading && tab.webView?.url?.scheme == "spsearch" }49 XCTAssertTrue(committed, "the placeholder document is a real navigation in the web view")50 XCTAssertNil(tab.error)51 XCTAssertEqual(tab.security, SecurityState.none)52 XCTAssertTrue(state.profile.history.recent().isEmpty, "a results page is not browsing history")53 // The provider is unreachable in this test: the page reports it instead of inventing results.54 let failed = await waitUntil { if case .failed = tab.searchPage?.phase { return true } else { return false } }55 XCTAssertTrue(failed)56 XCTAssertEqual(tab.searchPage?.resultCount, 0)57 // An address still loads as an address.58 state.navigate("example.com", in: tab)59 XCTAssertEqual(tab.url?.absoluteString, "https://example.com")60 XCTAssertNil(tab.searchPage)61 }6263 func testBackAndForwardMoveBetweenSearchPages() async {64 let tab = state.newTab()65 tab.search("first query")66 // The second search is issued while the first placeholder may still be loading: it must win.67 var ok = true68 tab.search("second query", kind: .images)69 ok = await waitUntil { !tab.isLoading && SPSearchURL.parse(tab.webView?.backForwardList.currentItem?.url)?.query == "second query" }70 XCTAssertTrue(ok, "a search issued right after another one is the one that loads")71 tab.search("first query")72 ok = await waitUntil { !tab.isLoading && SPSearchURL.parse(tab.webView?.backForwardList.currentItem?.url)?.query == "first query" && tab.canGoBack }73 tab.search("second query", kind: .images)74 ok = await waitUntil { !tab.isLoading && tab.canGoBack && SPSearchURL.parse(tab.webView?.backForwardList.currentItem?.url)?.query == "second query" && tab.backList.count >= 2 }75 XCTAssertTrue(ok, "each search is an entry of the tab's back/forward list")76 XCTAssertEqual(tab.searchPage?.kind, .images)77 tab.goBack()78 ok = await waitUntil { tab.searchPage?.query == "first query" && tab.searchPage?.kind == .web && tab.canGoForward }79 XCTAssertTrue(ok, "Back returns to the previous results page")80 tab.goForward()81 ok = await waitUntil { tab.searchPage?.query == "second query" && tab.searchPage?.kind == .images }82 XCTAssertTrue(ok)83 // The session keeps the search tab and restores it as a search page.84 let snapshot = tab.snapshot()85 XCTAssertEqual(SPSearchURL.parse(snapshot.url.flatMap(URL.init(string:)))?.query, "second query")86 let restored = BrowserTab(snapshot: snapshot, profile: state.profile, environment: environment)87 XCTAssertTrue(restored.isSearchPage)88 restored.refreshSearchPage()89 XCTAssertEqual(restored.searchPage?.query, "second query")90 }9192 func testWebContentCannotOpenSearchPages() async {93 let tab = state.newTab()94 let view = tab.ensureWebView()95 view.loadHTMLString("<html><head><title>Page</title></head><body><script>setTimeout(function(){ location.href = 'spsearch://results?q=injected'; }, 50)</script></body></html>",96 baseURL: URL(string: "https://attacker.example/"))97 _ = await waitUntil { tab.title == "Page" }98 try? await Task.sleep(for: .milliseconds(600))99 XCTAssertFalse(tab.isSearchPage, "a page cannot push the tab to a search of its choosing")100 XCTAssertTrue(environment.services.library.recentSearches().isEmpty)101 XCTAssertEqual(URLSafety.verdict(for: URL(string: "spsearch://results?q=x")!, isMainFrame: false, typedByUser: true), .block("search pages are opened by the user only"))102 }103104 func testSearchHistoryIsRecordedInRegularWindowsOnly() async {105 let regular = state.newTab()106 regular.search("public query")107 XCTAssertEqual(environment.services.library.recentSearches().map(\.query), ["public query"])108 XCTAssertEqual(environment.services.library.searchSuggestions(for: "pub").map(\.query), ["public query"])109110 let secret = privateState.newTab()111 secret.search("very private query")112 XCTAssertTrue(secret.isSearchPage)113 XCTAssertEqual(secret.searchPage?.query, "very private query")114 XCTAssertEqual(environment.services.library.recentSearches().map(\.query), ["public query"], "private searches are never recorded")115 XCTAssertTrue(environment.services.mirror.records(SyncCollection.searches).allSatisfy { !$0.key.contains("private") })116117 // Turning search history off stops recording in regular windows too.118 var prefs = environment.services.searchPreferences119 prefs.keepSearchHistory = false120 environment.services.searchPreferences = prefs121 regular.search("not kept")122 XCTAssertEqual(environment.services.library.recentSearches().map(\.query), ["public query"])123 }124125 func testPrivateBrowsingNeverReachesTheSyncMirror() async throws {126 environment.start()127 defer { environment.services.sync.stop() }128 let regularController = try XCTUnwrap(environment.openWindow(initialURL: URL(string: "https://regular.example/page")))129 let privateController = try XCTUnwrap(environment.openWindow(isPrivate: true, initialURL: URL(string: "https://secret.example/private")))130 defer { regularController.close(); privateController.close() }131132 // What the app hands to sync as "open tabs" comes from regular windows only.133 let published = try XCTUnwrap(environment.services.tabsProvider?())134 XCTAssertEqual(published.open.map(\.url), ["https://regular.example/page"])135 XCTAssertFalse(published.open.contains { $0.url.contains("secret") })136137 // A private visit writes nothing a sync capture could pick up.138 let privateTab = try XCTUnwrap(privateController.state.selectedTab)139 privateTab.ensureWebView().loadHTMLString("<title>Secret</title>", baseURL: URL(string: "https://secret.example/private"))140 _ = await waitUntil { privateTab.title == "Secret" }141 let regularTab = try XCTUnwrap(regularController.state.selectedTab)142 regularTab.ensureWebView().loadHTMLString("<title>Regular</title>", baseURL: URL(string: "https://regular.example/page"))143 _ = await waitUntil { self.environment.defaultContext.history.recent().first?.title == "Regular" }144 privateController.state.close(privateTab)145146 HistorySyncBridge(history: environment.defaultContext.history, mirror: environment.services.mirror).captureLocalChanges()147 let library = environment.services.library148 if let tabs = environment.services.tabsProvider?() {149 library.publishTabs(tabs.open, closed: tabs.closed, deviceID: "this-mac", deviceName: "Mac", platform: "macos")150 }151 let everything = SyncCollection.all.flatMap { environment.services.mirror.records($0) }152 XCTAssertFalse(everything.isEmpty)153 for record in everything {154 XCTAssertFalse(record.key.contains("secret"), "\(record.collection) must not hold private data")155 XCTAssertFalse(String(decoding: record.json, as: UTF8.self).localizedCaseInsensitiveContains("secret"), "\(record.collection) must not hold private data")156 }157 XCTAssertEqual(environment.services.mirror.records(SyncCollection.history).map(\.key), ["https://regular.example/page"])158 // Signed out: nothing is scheduled and nothing is sent.159 XCTAssertEqual(environment.services.sync.phase, .signedOut)160 let report = await environment.services.sync.syncNow()161 XCTAssertNil(report)162 }163164 func testFavoritesReadingListAndCommands() async {165 let tab = state.newTab()166 tab.ensureWebView().loadHTMLString("<title>Article</title>", baseURL: URL(string: "https://read.example/article"))167 _ = await waitUntil { tab.title == "Article" && tab.url?.host == "read.example" }168 state.select(tab)169 XCTAssertTrue(state.isEnabled(.addToReadingList))170 state.perform(.addToReadingList)171 XCTAssertEqual(environment.services.library.readingList().map(\.url), ["https://read.example/article"])172 state.perform(.toggleFavorite)173 XCTAssertEqual(environment.services.library.favorites().map(\.title), ["Article"])174 state.perform(.toggleFavorite)175 XCTAssertTrue(environment.services.library.favorites().isEmpty)176177 // Page-only commands are disabled on a native search page; private windows cannot add to synced lists.178 tab.search("anything")179 XCTAssertFalse(state.isEnabled(.addBookmark))180 XCTAssertFalse(state.isEnabled(.toggleReader))181 XCTAssertFalse(state.isEnabled(.addToReadingList))182 XCTAssertTrue(state.isEnabled(.reload))183 let secret = privateState.newTab()184 secret.ensureWebView().loadHTMLString("<title>S</title>", baseURL: URL(string: "https://secret.example/"))185 _ = await waitUntil { secret.title == "S" }186 privateState.select(secret)187 XCTAssertFalse(privateState.isEnabled(.addToReadingList))188 XCTAssertFalse(privateState.isEnabled(.toggleFavorite))189 XCTAssertNil(privateState.searchActions(for: secret).addToReadingList)190191 // Clearing all history also clears what was searched.192 environment.clearHistory(since: nil)193 XCTAssertTrue(environment.services.library.recentSearches().isEmpty)194 XCTAssertTrue(CommandID.conflicts(overrides: [:]).isEmpty, "the new default shortcuts collide with none of the existing ones")195 }196}197