Repository Public
1import XCTest2@testable import SPBrowserCore34final class AddressResolverTests: XCTestCase {5 private let ddg = SearchEngine.builtIn.first { $0.id == "duckduckgo" }!67 private func resolve(_ text: String) -> ResolvedInput? { AddressResolver.resolve(text, engine: ddg) }89 func testEmptyInputResolvesToNothing() {10 XCTAssertNil(resolve(""))11 XCTAssertNil(resolve(" \n"))12 }1314 func testExplicitURLsAreKept() {15 XCTAssertEqual(resolve("https://example.com/a?b=c#d"), .url(URL(string: "https://example.com/a?b=c#d")!))16 XCTAssertEqual(resolve(" http://example.com "), .url(URL(string: "http://example.com")!))17 XCTAssertEqual(resolve("about:blank"), .url(URL(string: "about:blank")!))18 XCTAssertEqual(resolve("file:///tmp/a.html"), .url(URL(string: "file:///tmp/a.html")!))19 }2021 func testBareHostsGetHTTPS() {22 XCTAssertEqual(resolve("example.com"), .url(URL(string: "https://example.com")!))23 XCTAssertEqual(resolve("sub.example.co.uk/path?q=1"), .url(URL(string: "https://sub.example.co.uk/path?q=1")!))24 XCTAssertEqual(resolve("example.com:8443/x"), .url(URL(string: "https://example.com:8443/x")!))25 }2627 func testLocalHostsGetHTTP() {28 XCTAssertEqual(resolve("localhost"), .url(URL(string: "http://localhost")!))29 XCTAssertEqual(resolve("localhost:3000/app"), .url(URL(string: "http://localhost:3000/app")!))30 XCTAssertEqual(resolve("127.0.0.1:8080"), .url(URL(string: "http://127.0.0.1:8080")!))31 XCTAssertEqual(resolve("192.168.2.10"), .url(URL(string: "http://192.168.2.10")!))32 XCTAssertEqual(resolve("[::1]:8080/x"), .url(URL(string: "http://[::1]:8080/x")!))33 XCTAssertEqual(resolve("printer.local"), .url(URL(string: "http://printer.local")!))34 }3536 func testPlainWordsAreSearched() {37 XCTAssertEqual(resolve("swift")?.isSearch, true)38 XCTAssertEqual(resolve("what is webkit")?.isSearch, true)39 XCTAssertEqual(resolve("3.14")?.isSearch, true)40 XCTAssertEqual(resolve("example.com is down")?.isSearch, true)41 XCTAssertEqual(resolve("user@example.com")?.isSearch, true)42 }4344 func testQueryIsPercentEncoded() {45 let url = resolve("c++ & rust?")!.url46 XCTAssertEqual(url.host, "duckduckgo.com")47 XCTAssertTrue(url.absoluteString.hasSuffix("q=c%2B%2B%20%26%20rust%3F"), url.absoluteString)48 XCTAssertTrue(resolve("café déjà")!.url.absoluteString.contains("caf%C3%A9%20d%C3%A9j%C3%A0"))49 }5051 func testDangerousSchemesAreSearchedNotLoaded() {52 for text in ["javascript:alert(1)", "JavaScript:alert(1)", "data:text/html,<script>1</script>", "vbscript:x"] {53 let result = resolve(text)54 XCTAssertEqual(result?.isSearch, true, text)55 XCTAssertEqual(result?.url.scheme, "https", text)56 }57 }5859 func testOtherSchemesArePassedToPolicy() {60 XCTAssertEqual(resolve("mailto:a@example.com"), .url(URL(string: "mailto:a@example.com")!))61 }6263 func testSearchShortcuts() {64 XCTAssertEqual(resolve("w swift language")?.url.host, "www.wikipedia.org")65 XCTAssertEqual(resolve("!gh webkit")?.url.host, "github.com")66 XCTAssertEqual(resolve("g")?.url.host, "duckduckgo.com", "a shortcut alone is an ordinary query")67 XCTAssertEqual(resolve("zz hello")?.url.host, "duckduckgo.com")68 }6970 func testInvalidPortsAreNotHosts() {71 XCTAssertEqual(resolve("example.com:99999")?.isSearch, true)72 XCTAssertEqual(resolve("example.com:abc")?.isSearch, true)73 }7475 func testCustomEngineValidation() {76 XCTAssertTrue(SearchEngine(id: "x", name: "X", template: "https://x.test/?q=%s", shortcut: "x").isValid)77 XCTAssertFalse(SearchEngine(id: "x", name: "X", template: "https://x.test/", shortcut: "x").isValid)78 XCTAssertFalse(SearchEngine(id: "x", name: "X", template: "javascript:%s", shortcut: "x").isValid)79 XCTAssertFalse(SearchEngine(id: "x", name: " ", template: "https://x.test/?q=%s", shortcut: "x").isValid)80 }81}8283final class URLSafetyTests: XCTestCase {84 private func verdict(_ s: String, main: Bool = true, typed: Bool = false, fromFile: Bool = false) -> NavigationVerdict {85 URLSafety.verdict(for: URL(string: s)!, isMainFrame: main, typedByUser: typed, sourceIsFile: fromFile)86 }8788 func testWebSchemesAllowed() {89 XCTAssertEqual(verdict("https://example.com"), .allow)90 XCTAssertEqual(verdict("http://example.com"), .allow)91 XCTAssertEqual(verdict("about:blank"), .allow)92 }9394 func testScriptSchemesBlockedEverywhere() {95 for main in [true, false] {96 if case .block = verdict("javascript:alert(1)", main: main, typed: true) {} else { XCTFail("javascript must be blocked") }97 }98 }99100 func testTopLevelDataBlockedButSubframeAllowed() {101 if case .block = verdict("data:text/html,hi") {} else { XCTFail() }102 XCTAssertEqual(verdict("data:image/png;base64,AAAA", main: false), .allow)103 }104105 func testFileOnlyFromUserOrFile() {106 if case .block = verdict("file:///etc/passwd") {} else { XCTFail("web content must not open files") }107 XCTAssertEqual(verdict("file:///tmp/a.html", typed: true), .allow)108 XCTAssertEqual(verdict("file:///tmp/b.html", fromFile: true), .allow)109 }110111 func testExternalSchemesNeedConfirmationAndNeverFromSubframes() {112 XCTAssertEqual(verdict("mailto:a@b.co"), .external)113 XCTAssertEqual(verdict("zoommtg://join"), .external)114 if case .block = verdict("zoommtg://join", main: false) {} else { XCTFail() }115 }116117 func testWarnings() {118 func warn(_ s: String) -> [URLWarning] { URLInspector.warnings(for: URL(string: s)!) }119 XCTAssertEqual(warn("https://example.com/"), [])120 XCTAssertTrue(warn("https://paypal.com@evil.example/login").contains(.embeddedCredentials))121 XCTAssertTrue(warn("https://xn--pypal-4ve.com/").contains(.punycodeHost))122 XCTAssertTrue(warn("http://example.com/").contains(.insecureTransport))123 XCTAssertFalse(warn("http://localhost:3000/").contains(.insecureTransport))124 XCTAssertFalse(warn("http://localhost:3000/").contains(.nonStandardPort))125 XCTAssertTrue(warn("https://93.184.216.34/").contains(.ipAddressHost))126 XCTAssertFalse(warn("http://127.0.0.1/").contains(.ipAddressHost))127 XCTAssertTrue(warn("https://a.b.c.d.e.example.com/").contains(.excessiveSubdomains))128 XCTAssertTrue(warn("https://example.com:4444/").contains(.nonStandardPort))129 XCTAssertEqual(warn("file:///tmp/x"), [])130 }131132 func testMixedScriptDetection() {133 XCTAssertTrue(URLInspector.hasMixedScripts("pаypal.com"), "Cyrillic а inside a Latin label")134 XCTAssertFalse(URLInspector.hasMixedScripts("paypal.com"))135 XCTAssertFalse(URLInspector.hasMixedScripts("пример.com"), "a fully Cyrillic label next to a Latin TLD is legitimate")136 }137138 func testRegistrableDomain() {139 XCTAssertEqual(URLInspector.registrableDomain(of: "a.b.example.com"), "example.com")140 XCTAssertEqual(URLInspector.registrableDomain(of: "www.bbc.co.uk"), "bbc.co.uk")141 XCTAssertEqual(URLInspector.registrableDomain(of: "www.revenu.gouv.qc.ca"), "gouv.qc.ca")142 XCTAssertEqual(URLInspector.registrableDomain(of: "example.com"), "example.com")143 XCTAssertEqual(URLInspector.registrableDomain(of: "192.168.1.1"), "192.168.1.1")144 }145}146147final class DownloadSafetyTests: XCTestCase {148 func testSanitizeRemovesPathsAndHiddenPrefixes() {149 XCTAssertEqual(DownloadSafety.sanitize(filename: "../../etc/passwd"), "passwd")150 XCTAssertEqual(DownloadSafety.sanitize(filename: "..\\..\\evil.exe"), "evil.exe")151 XCTAssertEqual(DownloadSafety.sanitize(filename: ".bashrc"), "bashrc")152 XCTAssertEqual(DownloadSafety.sanitize(filename: "/"), "download")153 XCTAssertEqual(DownloadSafety.sanitize(filename: ""), "download")154 XCTAssertEqual(DownloadSafety.sanitize(filename: "a:b\u{0}c\n.pdf"), "abc.pdf")155 XCTAssertEqual(DownloadSafety.sanitize(filename: "report.pdf. "), "report.pdf")156 }157158 func testSanitizeStripsBidiOverrides() {159 // "invoice<RLO>fdp.exe" displays as "invoiceexe.pdf"; the override must not survive.160 XCTAssertEqual(DownloadSafety.sanitize(filename: "invoice\u{202E}fdp.exe"), "invoicefdp.exe")161 }162163 func testSanitizeBoundsLengthAndKeepsExtension() {164 let long = String(repeating: "a", count: 400) + ".pdf"165 let out = DownloadSafety.sanitize(filename: long)166 XCTAssertLessThanOrEqual(out.utf8.count, 200)167 XCTAssertTrue(out.hasSuffix(".pdf"))168 }169170 func testUniqueURL() {171 let dir = URL(fileURLWithPath: "/tmp/dl")172 let taken: Set<String> = ["/tmp/dl/a.pdf", "/tmp/dl/a (2).pdf", "/tmp/dl/noext"]173 let exists: (URL) -> Bool = { taken.contains($0.path) }174 XCTAssertEqual(DownloadSafety.uniqueURL(in: dir, filename: "a.pdf", exists: exists).lastPathComponent, "a (3).pdf")175 XCTAssertEqual(DownloadSafety.uniqueURL(in: dir, filename: "b.pdf", exists: exists).lastPathComponent, "b.pdf")176 XCTAssertEqual(DownloadSafety.uniqueURL(in: dir, filename: "noext", exists: exists).lastPathComponent, "noext (2)")177 XCTAssertEqual(DownloadSafety.uniqueURL(in: dir, filename: "../../x.sh", exists: exists).deletingLastPathComponent().path, "/tmp/dl")178 }179180 func testRisk() {181 XCTAssertEqual(DownloadSafety.risk(forFilename: "Setup.DMG"), .executable)182 XCTAssertEqual(DownloadSafety.risk(forFilename: "run.command"), .executable)183 XCTAssertEqual(DownloadSafety.risk(forFilename: "a.zip"), .archive)184 XCTAssertEqual(DownloadSafety.risk(forFilename: "photo.jpg"), .normal)185 XCTAssertEqual(DownloadSafety.risk(forFilename: "noext"), .normal)186 }187}188189final class BlockerTests: XCTestCase {190 func testRulesAreValidContentBlockerJSON() throws {191 let json = BlockerRuleBuilder.json(for: .init(disabledHosts: ["example.com"]))192 let rules = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [[String: Any]])193 XCTAssertGreaterThan(rules.count, 100)194 for rule in rules {195 let trigger = try XCTUnwrap(rule["trigger"] as? [String: Any])196 let action = try XCTUnwrap(rule["action"] as? [String: Any])197 let filter = try XCTUnwrap(trigger["url-filter"] as? String)198 XCTAssertNoThrow(try NSRegularExpression(pattern: filter))199 XCTAssertTrue(["block", "ignore-previous-rules"].contains(action["type"] as? String ?? ""))200 }201 let last = try XCTUnwrap(rules.last)202 XCTAssertEqual((last["action"] as? [String: Any])?["type"] as? String, "ignore-previous-rules")203 XCTAssertNotNil((last["trigger"] as? [String: Any])?["if-top-url"])204 }205206 func testBlockingIsThirdPartyOnly() throws {207 let rules = BlockerRuleBuilder.rules(for: .init())208 for rule in rules {209 XCTAssertEqual((rule["trigger"] as? [String: Any])?["load-type"] as? [String], ["third-party"])210 }211 }212213 func testURLFilterMatchesDomainAndSubdomainsOnly() throws {214 let regex = try NSRegularExpression(pattern: BlockerRuleBuilder.urlFilter(forDomain: "tracker.example"))215 func matches(_ s: String) -> Bool { regex.firstMatch(in: s, range: NSRange(s.startIndex..., in: s)) != nil }216 XCTAssertTrue(matches("https://tracker.example/p.gif"))217 XCTAssertTrue(matches("https://cdn.tracker.example:443/p.gif"))218 XCTAssertTrue(matches("wss://tracker.example/socket"))219 XCTAssertFalse(matches("https://nottracker.example/p.gif"))220 XCTAssertFalse(matches("https://tracker.example.evil.test/"))221 XCTAssertFalse(matches("https://site.test/?u=https://tracker.example/"))222 }223224 func testOptionsControlTheSet() {225 XCTAssertEqual(BlockerRuleBuilder.json(for: .init(trackers: false, ads: false)), "[]")226 let onlyAds = BlockerRuleBuilder.domains(for: .init(trackers: false, ads: true))227 XCTAssertTrue(onlyAds.contains("doubleclick.net"))228 XCTAssertFalse(onlyAds.contains("hotjar.com"))229 let extra = BlockerRuleBuilder.domains(for: .init(trackers: false, ads: false, extraDomains: ["x.example", "not a domain", "localhost"]))230 XCTAssertEqual(extra, ["x.example"])231 }232233 func testIdentifierChangesWithRules() {234 let a = BlockerRuleBuilder.identifier(for: .init())235 XCTAssertEqual(a, BlockerRuleBuilder.identifier(for: .init()))236 XCTAssertNotEqual(a, BlockerRuleBuilder.identifier(for: .init(disabledHosts: ["example.com"])))237 }238239 func testBuiltInListsAreCleanDomains() {240 for domain in BuiltInBlockList.trackers + BuiltInBlockList.ads {241 XCTAssertTrue(BlockerRuleBuilder.isValidDomain(domain), domain)242 }243 }244245 func testListParser() {246 let text = """247 ! Title: sample248 [Adblock Plus 2.0]249 # hosts comment250 0.0.0.0 ads.example251 127.0.0.1 localhost252 127.0.0.1 track.example # trailing comment253 ||pixel.example^254 ||cdn.example^$third-party255 ||scripts.example^$script256 ||path.example/ads/*257 @@||allowed.example^258 example.com##.banner259 plain.example260 not a domain line261 10.0.0.1 internal.example262 """263 XCTAssertEqual(BlockListParser.domains(from: text), ["ads.example", "cdn.example", "pixel.example", "plain.example", "track.example"])264 }265266 func testSourceMustBeHTTPS() {267 XCTAssertTrue(BlockListSource(name: "a", url: "https://lists.example/a.txt").isFetchable)268 XCTAssertFalse(BlockListSource(name: "a", url: "http://lists.example/a.txt").isFetchable)269 XCTAssertFalse(BlockListSource(name: "a", url: "file:///etc/hosts").isFetchable)270 for source in BlockListSource.suggested { XCTAssertTrue(source.isFetchable) }271 }272}273274final class PermissionAndScriptTests: XCTestCase {275 func testDefaultsAndOverrides() {276 let store = SitePermissionStore(url: nil)277 XCTAssertEqual(store.decision(.camera, host: "example.com"), .ask)278 XCTAssertEqual(store.decision(.popups, host: "example.com"), .deny)279 XCTAssertEqual(store.decision(.javascript, host: "example.com"), .allow)280 store.set(.allow, for: .camera, host: "www.Example.com")281 XCTAssertEqual(store.decision(.camera, host: "example.com"), .allow, "www. and case are normalised")282 XCTAssertEqual(store.decision(.camera, host: "other.com"), .ask)283 XCTAssertEqual(store.decision(.microphone, host: "example.com"), .ask, "granting the camera does not grant the microphone")284 store.set(nil, for: .camera, host: "example.com")285 XCTAssertNil(store.storedDecision(.camera, host: "example.com"))286 XCTAssertTrue(store.allSites.isEmpty)287 }288289 func testPermissionsPersistAndNeverApplyWithoutHost() throws {290 let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".json")291 defer { try? FileManager.default.removeItem(at: url) }292 SitePermissionStore(url: url).set(.deny, for: .javascript, host: "example.com")293 XCTAssertEqual(SitePermissionStore(url: url).decision(.javascript, host: "example.com"), .deny)294 let store = SitePermissionStore(url: nil)295 store.set(.allow, for: .camera, host: nil)296 XCTAssertEqual(store.decision(.camera, host: nil), .ask)297 }298299 func testZoomIsStoredPerSite() {300 let store = SitePermissionStore(url: nil)301 store.setZoom(1.25, host: "example.com")302 XCTAssertEqual(store.zoom(forHost: "www.example.com"), 1.25)303 store.setZoom(1.0, host: "example.com")304 XCTAssertNil(store.zoom(forHost: "example.com"))305 }306307 func testUserScriptMatching() {308 var script = UserScript(name: "s", source: "1", hosts: ["example.com", "*.docs.test"])309 XCTAssertFalse(script.applies(to: "example.com"), "scripts are disabled until explicitly enabled")310 script.enabled = true311 XCTAssertTrue(script.applies(to: "example.com"))312 XCTAssertTrue(script.applies(to: "www.example.com"))313 XCTAssertFalse(script.applies(to: "notexample.com"))314 XCTAssertTrue(script.applies(to: "a.docs.test"))315 XCTAssertFalse(script.applies(to: "docs.test"))316 XCTAssertFalse(script.applies(to: nil))317 script.hosts = []318 XCTAssertFalse(script.applies(to: "example.com"), "no pattern means no site")319 XCTAssertFalse(HostPattern.matches("*", host: "example.com"), "there is no match-everything wildcard")320 XCTAssertFalse(HostPattern.isValid("*"))321 XCTAssertTrue(HostPattern.isValid("localhost"))322 }323}324325final class CommandTests: XCTestCase {326 func testDefaultShortcutsDoNotConflict() {327 XCTAssertTrue(CommandID.conflicts(overrides: [:]).isEmpty, "\(CommandID.conflicts(overrides: [:]))")328 }329330 func testEveryCommandHasATitle() {331 for command in CommandID.allCases { XCTAssertFalse(command.title.isEmpty, command.rawValue) }332 XCTAssertEqual(Set(CommandID.allCases.map(\.rawValue)).count, CommandID.allCases.count)333 }334335 func testOverridesAndConflictDetection() {336 let overrides = [CommandID.newTab.rawValue: KeyCombo("n"), CommandID.reload.rawValue: KeyCombo("", command: false)]337 XCTAssertEqual(CommandID.newTab.shortcut(overrides: overrides), KeyCombo("n"))338 XCTAssertNil(CommandID.reload.shortcut(overrides: overrides), "an empty override removes the shortcut")339 let conflicts = CommandID.conflicts(overrides: overrides)340 XCTAssertEqual(Set(conflicts[KeyCombo("n")] ?? []), [.newTab, .newWindow])341 }342343 func testKeyComboDisplayAndUsability() {344 XCTAssertEqual(KeyCombo("t", shift: true).display, "⇧⌘T")345 XCTAssertEqual(KeyCombo("left", option: true, control: true).display, "⌃⌥⌘←")346 XCTAssertFalse(KeyCombo("a", command: false).isUsable)347 XCTAssertTrue(KeyCombo("a", command: false, control: true).isUsable)348 }349}350