SPB Git

Repository Public License

ShieldRulesTests.swift 24.1 KB 399 lines swift

1import Foundation2import NavigatorCore3import Testing4@testable import PrivacyEngine56@Suite struct ShieldDomainTests {7    @Test(arguments: [8        ("Example.COM", "example.com"), ("  tracker.example.co.uk ", "tracker.example.co.uk"), ("*.ads.example.com", "ads.example.com"),9        (".example.com", "example.com"), ("example.com.", "example.com"), ("a-b.example.com", "a-b.example.com"),10        ("bücher.example", "xn--bcher-kva.example"), ("51.la", "51.la"),11    ])12    func validDomainsAreNormalised(raw: String, expected: String) {13        #expect(ShieldDomain.normalize(raw) == expected)14    }1516    @Test(arguments: [17        "", "com", "localhost", "example..com", "-bad.example.com", "bad-.example.com", "exa mple.com", "example.com/path",18        "https://example.com", "example.com:8080", "user@example.com", "192.168.1.1", "exam_ple.com", "example.com?x",19        "*", "a.b|c.com", "[::1]", "ex\u{202E}ample.com", String(repeating: "a", count: 64) + ".com",20        String(repeating: "a.", count: 130) + "com",21    ])22    func invalidDomainsAreRejected(raw: String) {23        #expect(ShieldDomain.normalize(raw) == nil)24    }2526    @Test func parentsAndContainment() {27        #expect(ShieldDomain.selfAndParents(of: "a.b.example.com") == ["a.b.example.com", "b.example.com", "example.com"])28        #expect(ShieldDomain.host("cdn.example.com", isWithin: "example.com"))29        #expect(!ShieldDomain.host("notexample.com", isWithin: "example.com"))30        #expect(ShieldDomain.site(of: URL(string: "https://WWW.Example.com:8443/x")!) == "www.example.com")31        #expect(ShieldDomain.site(of: URL(string: "http://127.0.0.1/")!) == nil)32    }33}3435@Suite struct ShieldListParserTests {36    @Test func theDocumentedFormatIsAccepted() {37        let text = """38        ! title: My list39        ! version: 740        # a comment41        [Adblock Plus 2.0]4243        plain.example.com44        withexceptions.example unless=owner.example,Other.Example45        ||abp.example.net^46        ||abp3p.example.net^$third-party47        @@||allowed.example.org^48        0.0.0.0 hosts.example.com49        127.0.0.1 hosts2.example.com   # trailing comment50        127.0.0.1 localhost51        [ads]52        ad.example.com53        ##.sponsored-banner54        news.example.com,blog.example.com##div[data-ad="1"] > .slot55        plain.example.com56        """57        let result = ShieldListParser.parse(text)58        #expect(result.diagnostics.isEmpty)59        #expect(result.list.title == "My list" && result.list.version == "7")60        #expect(result.list.blocked.map(\.domain) == ["plain.example.com", "withexceptions.example", "abp.example.net", "abp3p.example.net",61                                                    "hosts.example.com", "hosts2.example.com", "ad.example.com"])62        #expect(result.list.blocked[1].exceptOnSites == ["owner.example", "other.example"])63        #expect(result.list.blocked.prefix(6).allSatisfy { $0.category == .custom } && result.list.blocked[6].category == .ads)64        #expect(result.list.unblocked == ["allowed.example.org"])65        #expect(result.list.cosmetic == [66            CosmeticRule(selector: ".sponsored-banner"),67            CosmeticRule(selector: "div[data-ad=\"1\"] > .slot", scope: .only(["news.example.com", "blog.example.com"])),68        ])69        #expect(result.acceptedLines == 11 && result.rejectedLines == 0)   // the duplicate counts as accepted, is stored once70    }7172    @Test(arguments: [73        "||example.com/ads/*", "||example.com^$script", "||example.com^$domain=a.com", "|https://example.com/", "/banner[0-9]+/",74        "example.com/path", "*.doubleclick.*", "@@||example.com^$document", "@@example.com", "example.com#@#.ad", "example.com#?#div:has(.ad)",75        "example.com##+js(abort-on-property-read, x)", "~example.com##.ad", "##div { display: none }", "##", "##.a,", "##[unclosed",76        "##a:not(.b", "##\"quote", "two words", "bad_domain.example", "example.com unless=not a site", "-bad.example.com",77        "example.com$third-party", "##.ad; body", "exam<ple>.com##x", "example.com##<script>",78    ])79    func unsupportedSyntaxIsRejectedNotGuessed(line: String) {80        let result = ShieldListParser.parse(line)81        #expect(result.list.ruleCount == 0 && result.list.unblocked.isEmpty, "accepted: \(line)")82        #expect(result.rejectedLines == 1)83        #expect(result.diagnostics.first?.line == 1)84    }8586    @Test func diagnosticsCarryLineNumbersAndAreBounded() {87        let result = ShieldListParser.parse("good.example.com\n||bad/path\n\nalso.example.com\r\n$$$")88        #expect(result.list.blocked.count == 2)89        #expect(result.diagnostics.map(\.line) == [2, 5])90        #expect(result.diagnostics[0].description.hasPrefix("line 2:"))91        let many = ShieldListParser.parse(Array(repeating: "||x/y", count: 700).joined(separator: "\n"))92        #expect(many.diagnostics.count == ShieldListParser.maximumDiagnostics + 1)93        #expect(many.diagnostics.last?.severity == .note)94        let long = ShieldListParser.parse(String(repeating: "a", count: 3_000) + ".com")95        #expect(long.diagnostics.first?.message == "line too long" && long.diagnostics.first?.text.count == 120)96    }9798    @Test func oversizedInputIsRefusedAsAWhole() {99        let huge = String(repeating: "example.com\n", count: ShieldListParser.maximumBytes / 12 + 1)100        let result = ShieldListParser.parse(huge)101        #expect(result.list.ruleCount == 0 && result.rejectedLines == 1)102    }103104    @Test func theBuiltInListLoadsAndIsWellFormed() throws {105        let url = try #require(Bundle.module.url(forResource: "shield-builtin", withExtension: "txt"))106        let text = try String(contentsOf: url, encoding: .utf8)107        let parsed = ShieldListParser.parse(text, defaultCategory: .trackers)108        #expect(parsed.diagnostics.isEmpty)109        let list = ShieldList.builtIn110        #expect(list == parsed.list)111        #expect(list.title.contains("ORIX") && list.version == "2026.11.25.1")112        #expect(list.blocked.count >= 250 && list.blocked.count <= 500)   // "a few hundred at most"113        #expect(Set(list.blocked.map(\.domain)).count == list.blocked.count)114        #expect(list.blocked.allSatisfy { ShieldDomain.normalize($0.domain) == $0.domain })115        #expect(list.blocked.allSatisfy { $0.category == .trackers || $0.category == .ads })116        #expect(list.blocked.contains { $0.category == .trackers } && list.blocked.contains { $0.category == .ads })117        #expect(list.cosmetic.isEmpty && list.unblocked.isEmpty)118        #expect(text.contains("NOT EasyList"))119        // Nothing that would break sign-in, payments or content delivery.120        let mustNotBlock = ["google.com", "gstatic.com", "googleapis.com", "facebook.com", "apple.com", "cloudflare.com", "paypal.com",121                            "stripe.com", "recaptcha.net", "hcaptcha.com", "cloudfront.net", "akamaihd.net", "youtube.com", "microsoft.com"]122        for domain in mustNotBlock { #expect(!list.blocked.contains { $0.domain == domain }) }123    }124}125126@Suite struct CosmeticSelectorTests {127    @Test(arguments: [".ad", "#banner", "div.ad > span", "a[href^=\"https://ads.\"]", "div:not(.keep)", "li:nth-child(2)", "p + .x, .y ~ .z",128                      "[data-x='a b']", "input[name=\"q[]\"]"])129    func ordinarySelectorsPass(selector: String) { #expect(CosmeticRule.validate(selector: selector) == nil) }130131    @Test(arguments: ["", "   ", ".a {", "} body", ".a; .b", "@import", "a\\b", ".a/b", "<x>", ".ad\n.b", "div >", ", .a", "(.a", ".a)", "[a", "a]",132                      "'open", String(repeating: "a", count: 513), ".émoji"])133    func riskySelectorsAreRefused(selector: String) { #expect(CosmeticRule.validate(selector: selector) != nil) }134}135136@Suite struct ContentBlockerRegexTests {137    @Test(arguments: [".*", "^http://", "^https?://([^/]+\\.)?example\\.com[:/]", "ads[0-9]+\\.js$", "^[^:]+://+([^:/]+\\.)?a-b\\.example[:/]",138                      "(foo)+bar", "a\\.b\\?c", "[^a-z]", "\\[", "x.+y", "^http://\\["])139    func supportedPatterns(pattern: String) { #expect(ContentBlockerRegex.problem(in: pattern) == nil, "\(pattern)") }140141    @Test(arguments: ["", "a|b", "a{2,3}", "\\d+", "\\w", "\\bword", "(?:x)", "(?=x)", "(?!x)", "a^b", "a$b", "*a", "+", "a**", "(a", "a)", "[a", "a]",142                      "[]", "()", "caf\u{E9}", "a\u{0}b", "trailing\\", "[\\d]", "\\1", "a?+", "^*", String(repeating: "a", count: 1_025)])143    func unsupportedPatterns(pattern: String) { #expect(ContentBlockerRegex.problem(in: pattern) != nil, "\(pattern)") }144145    @Test func hostFilterMatchesTheDomainAndItsSubdomainsOnly() throws {146        let filter = ContentBlockerRegex.hostFilter(for: "ad-server.example.com")147        #expect(ContentBlockerRegex.problem(in: filter) == nil)148        let regex = try NSRegularExpression(pattern: filter)149        func matches(_ url: String) -> Bool { regex.firstMatch(in: url, range: NSRange(url.startIndex..., in: url)) != nil }150        #expect(matches("https://ad-server.example.com/x.js"))151        #expect(matches("http://cdn.eu.ad-server.example.com:8080/"))152        #expect(matches("wss://ad-server.example.com/socket"))153        #expect(!matches("https://notad-server.example.com/"))154        #expect(!matches("https://ad-serverXexample.com/"))            // the dots are literal155        #expect(!matches("https://ad-server.example.com.evil.net/"))156        #expect(!matches("https://evil.net/?u=https://ad-server.example.com/"))157        #expect(!matches("https://evil.net/ad-server.example.com/"))158        #expect(ContentBlockerRegex.escape("a.b*c") == "a\\.b\\*c")159    }160}161162@Suite struct ContentRuleListGeneratorTests {163    let builtIn = ShieldList(title: "T", version: "1", blocked: [164        BlockedDomain(domain: "tracker.example", category: .trackers),165        BlockedDomain(domain: "pixel.social.example", category: .trackers, exceptOnSites: ["social.example"]),166        BlockedDomain(domain: "ads.example", category: .ads),167    ])168169    private func rules(_ compilation: ShieldCompilation, _ identifier: String) throws -> [ContentRule] {170        let list = try #require(compilation.lists.first { $0.identifier == identifier })171        // Decoding the string proves it is valid JSON of the right shape.172        let rules = try ContentRuleListGenerator.decode(list.json)173        #expect(rules.count == list.ruleCount)174        return rules175    }176177    @Test func defaultSettingsProduceHTTPSTrackerAndAdLists() throws {178        let compilation = ContentRuleListGenerator.compile(settings: ShieldSettings(), builtIn: builtIn)179        #expect(compilation.lists.map(\.identifier) == ["orix.shield.https", "orix.shield.trackers.0", "orix.shield.ads.0"])180        #expect(compilation.diagnostics.isEmpty && compilation.totalRuleCount == 1 + ContentRuleListGenerator.localHTTPFilters.count + 3)181182        let trackers = try rules(compilation, "orix.shield.trackers.0")183        #expect(trackers.count == 2)184        #expect(trackers.allSatisfy { $0.action.type == .block && $0.trigger.loadType == ["third-party"] && $0.trigger.ifDomain == nil })185        #expect(trackers[0].trigger.urlFilter == ContentBlockerRegex.hostFilter(for: "pixel.social.example"))186        #expect(trackers[0].trigger.unlessDomain == ["*social.example"] && trackers[1].trigger.unlessDomain == nil)187188        let httpsRules = try rules(compilation, "orix.shield.https")189        #expect(httpsRules[0] == ContentRule(trigger: .init(urlFilter: "^http://"), action: .init(type: .makeHTTPS)))190        #expect(httpsRules.dropFirst().allSatisfy { $0.action.type == .ignorePreviousRules })191    }192193    @Test func rawJSONUsesWebKitKeyNames() throws {194        var settings = ShieldSettings(blockThirdPartyCookies: true)195        settings.disabledSites = ["trusted.example"]196        let compilation = ContentRuleListGenerator.compile(settings: settings, builtIn: builtIn)197        for list in compilation.lists {198            let array = try #require(try JSONSerialization.jsonObject(with: Data(list.json.utf8)) as? [[String: Any]])199            for rule in array {200                let trigger = try #require(rule["trigger"] as? [String: Any]), action = try #require(rule["action"] as? [String: Any])201                #expect(Set(rule.keys) == ["trigger", "action"])202                #expect(trigger["url-filter"] is String)203                #expect(Set(trigger.keys).isSubset(of: ["url-filter", "if-domain", "unless-domain", "load-type", "resource-type"]))204                #expect(Set(action.keys).isSubset(of: ["type", "selector"]))205                #expect(["block", "block-cookies", "css-display-none", "ignore-previous-rules", "make-https"].contains(action["type"] as? String ?? ""))206                // WebKit refuses a trigger carrying both conditions.207                #expect(!(trigger["if-domain"] != nil && trigger["unless-domain"] != nil))208            }209        }210        let cookies = try rules(compilation, "orix.shield.cookies")211        #expect(cookies[0] == ContentRule(trigger: .init(urlFilter: ".*", loadType: ["third-party"]), action: .init(type: .blockCookies)))212    }213214    @Test func everyGeneratedFilterIsInTheSupportedSubsetAndDomainsAreASCII() {215        var settings = ShieldSettings(blockThirdPartyCookies: true)216        settings.disabledSites = ["bücher.example", "Trusted.Example"]217        settings.httpAllowedSites = ["legacy.example"]218        let user = ShieldListParser.parse("custom.example\n##.ad\nshop.example##.promo").list219        let compilation = ContentRuleListGenerator.compile(settings: settings, builtIn: .builtIn, userLists: [user])220        #expect(compilation.diagnostics.isEmpty)221        var total = 0222        for list in compilation.lists {223            let rules = (try? ContentRuleListGenerator.decode(list.json)) ?? []224            #expect(!rules.isEmpty && rules.count <= ContentRuleListGenerator.maximumRulesPerList)225            for rule in rules {226                total += 1227                #expect(ContentBlockerRegex.problem(in: rule.trigger.urlFilter) == nil)228                for domain in (rule.trigger.ifDomain ?? []) + (rule.trigger.unlessDomain ?? []) {229                    #expect(domain.hasPrefix("*") && domain.utf8.allSatisfy { $0 < 0x80 } && domain == domain.lowercased())230                }231            }232        }233        #expect(total == compilation.totalRuleCount && total > 300)234    }235236    @Test func shieldOffForASiteEndsEveryListWithAnAllowRule() throws {237        var settings = ShieldSettings(blockThirdPartyCookies: true)238        settings.disabledSites = ["b.example", "a.example", "a.example", "not a site"]239        let user = ShieldListParser.parse("##.ad").list240        let compilation = ContentRuleListGenerator.compile(settings: settings, builtIn: builtIn, userLists: [user])241        #expect(compilation.lists.count == 5)242        for list in compilation.lists {243            let last = try #require(try ContentRuleListGenerator.decode(list.json).last)244            #expect(last == ContentRule(trigger: .init(urlFilter: ".*", ifDomain: ["*a.example", "*b.example"]),245                                        action: .init(type: .ignorePreviousRules)))246        }247        #expect(compilation.diagnostics.count == 1 && compilation.diagnostics[0].contains("invalid site"))248    }249250    @Test func userAllowedHTTPSitesAreExemptFromTheUpgrade() throws {251        var settings = ShieldSettings()252        settings.httpAllowedSites = ["legacy.example"]253        let upgrade = try #require(try rules(ContentRuleListGenerator.compile(settings: settings, builtIn: .empty), "orix.shield.https").first)254        #expect(upgrade.trigger.unlessDomain == ["*legacy.example"] && upgrade.action.type == .makeHTTPS)255    }256257    @Test func localHostsStayOnHTTP() throws {258        let filters = try ContentRuleListGenerator.localHTTPFilters.map { try NSRegularExpression(pattern: $0) }259        func exempt(_ url: String) -> Bool { filters.contains { $0.firstMatch(in: url, range: NSRange(url.startIndex..., in: url)) != nil } }260        for url in ["http://localhost/", "http://localhost:3000/x", "http://app.localhost/", "http://printer.local/", "http://nas.internal:8080/",261                    "http://router/", "http://127.0.0.1:8000/", "http://10.0.0.5/", "http://192.168.1.1/admin", "http://172.16.0.1/",262                    "http://172.31.255.255/", "http://169.254.1.1/", "http://[::1]:8080/", "http://[fe80::1]/"] {263            #expect(exempt(url), "\(url) should stay on HTTP")264        }265        for url in ["http://example.com/", "http://10.example.com/", "http://172.32.0.1/", "http://192.168.example.com/", "http://localhost.evil.com/",266                    "http://my.localdomain.com/", "http://8.8.8.8/", "http://172.160.1.1/"] {267            #expect(!exempt(url), "\(url) should be upgraded")268        }269    }270271    @Test func categoriesCanBeSwitchedOff() {272        let none = ContentRuleListGenerator.compile(settings: ShieldSettings(isEnabled: false), builtIn: builtIn)273        #expect(none.lists.isEmpty)274        let adsOnly = ContentRuleListGenerator.compile(settings: ShieldSettings(blockTrackers: false, upgradeToHTTPS: false), builtIn: builtIn)275        #expect(adsOnly.identifiers == ["orix.shield.ads.0"])276        let user = ShieldListParser.parse("custom.example\n##.ad").list277        let noCosmetic = ContentRuleListGenerator.compile(settings: ShieldSettings(blockTrackers: false, blockAds: false, upgradeToHTTPS: false, hideElements: false),278                                                          builtIn: builtIn, userLists: [user])279        #expect(noCosmetic.identifiers == ["orix.shield.custom.0"])280    }281282    @Test func longListsAreSplitUnderTheRuleLimit() throws {283        let many = ShieldList(blocked: (0..<1_050).map { BlockedDomain(domain: "t\($0).example", category: .trackers) })284        var settings = ShieldSettings(upgradeToHTTPS: false)285        settings.disabledSites = ["off.example"]286        let compilation = ContentRuleListGenerator.compile(settings: settings, builtIn: many, maximumRulesPerList: 500)287        #expect(compilation.lists.map(\.identifier) == ["orix.shield.trackers.0", "orix.shield.trackers.1", "orix.shield.trackers.2"])288        #expect(compilation.lists.map(\.ruleCount) == [500, 500, 53])   // 499 + allow, 499 + allow, 52 + allow289        var blocked = Set<String>()290        for list in compilation.lists {291            let rules = try ContentRuleListGenerator.decode(list.json)292            #expect(rules.count <= 500 && rules.last?.action.type == .ignorePreviousRules)293            blocked.formUnion(rules.filter { $0.action.type == .block }.map(\.trigger.urlFilter))294        }295        #expect(blocked.count == 1_050)296        #expect(ContentRuleListGenerator.maximumRulesPerList == 50_000)297    }298299    @Test func outputIsDeterministicAndHashed() {300        var settings = ShieldSettings()301        settings.disabledSites = ["b.example", "a.example"]302        var reordered = settings303        reordered.disabledSites = ["a.example", "b.example"]304        let shuffled = ShieldList(blocked: builtIn.blocked.reversed())305        let first = ContentRuleListGenerator.compile(settings: settings, builtIn: builtIn)306        let second = ContentRuleListGenerator.compile(settings: reordered, builtIn: shuffled)307        #expect(first.lists.map(\.json) == second.lists.map(\.json))308        #expect(first.lists.map(\.contentHash) == second.lists.map(\.contentHash))309        #expect(first.lists.allSatisfy { $0.contentHash.count == 64 })310        let changed = ContentRuleListGenerator.compile(settings: ShieldSettings(), builtIn: builtIn)311        #expect(changed.lists[1].contentHash != first.lists[1].contentHash)312    }313314    @Test func exceptionsAndDuplicatesAcrossLists() throws {315        let user = ShieldListParser.parse("""316        @@||tracker.example^317        @@||cdn.ads.example^318        tracker.example319        PIXEL.social.example320        extra.example321        """).list322        let compilation = ContentRuleListGenerator.compile(settings: ShieldSettings(upgradeToHTTPS: false), builtIn: builtIn, userLists: [user])323        // tracker.example is unblocked; ads.example too, because an exception for its subdomain could not be324        // honoured otherwise; the duplicate keeps its built-in category; extra.example is custom.325        #expect(compilation.identifiers == ["orix.shield.trackers.0", "orix.shield.custom.0"])326        #expect(try rules(compilation, "orix.shield.trackers.0").count == 1)327        #expect(try rules(compilation, "orix.shield.custom.0").map(\.trigger.urlFilter) == [ContentBlockerRegex.hostFilter(for: "extra.example")])328    }329330    @Test func cosmeticRulesAreScopedAndInvalidOnesDropped() throws {331        let user = ShieldList(cosmetic: [332            CosmeticRule(selector: " .ad "), CosmeticRule(selector: ".promo", scope: .only(["Shop.example"])),333            CosmeticRule(selector: ".x", scope: .everywhere(except: ["keep.example"])),334            CosmeticRule(selector: ".bad { }"), CosmeticRule(selector: ".y", scope: .only(["not a site"])), CosmeticRule(selector: " .ad "),335        ])336        let compilation = ContentRuleListGenerator.compile(settings: ShieldSettings(upgradeToHTTPS: false), builtIn: .empty, userLists: [user])337        let cosmetic = try rules(compilation, "orix.shield.cosmetic.0")338        #expect(cosmetic == [339            ContentRule(trigger: .init(urlFilter: ".*"), action: .init(type: .cssDisplayNone, selector: ".ad")),340            ContentRule(trigger: .init(urlFilter: ".*", ifDomain: ["*shop.example"]), action: .init(type: .cssDisplayNone, selector: ".promo")),341            ContentRule(trigger: .init(urlFilter: ".*", unlessDomain: ["*keep.example"]), action: .init(type: .cssDisplayNone, selector: ".x")),342        ])343        #expect(compilation.diagnostics.count == 3)344    }345346    @Test func settingsDecodeFromOlderShapes() throws {347        let decoded = try JSONDecoder().decode(ShieldSettings.self, from: Data(#"{"blockAds":false}"#.utf8))348        #expect(decoded == ShieldSettings(blockAds: false))349    }350}351352#if canImport(WebKit) && os(macOS)353import WebKit354355/// The only test that involves WebKit: it feeds the generated JSON to the real compiler. The module itself356/// never imports WebKit; the test target does, to verify the claim "these lists compile".357@Suite(.serialized) struct WebKitCompilationTests {358    @MainActor @Test func everyGeneratedListCompilesInWebKit() async throws {359        let directory = FileManager.default.temporaryDirectory.appending(path: "orix-shield-\(UUID().uuidString)", directoryHint: .isDirectory)360        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)361        defer { try? FileManager.default.removeItem(at: directory) }362        let store = try #require(WKContentRuleListStore(url: directory))363364        var settings = ShieldSettings(blockThirdPartyCookies: true)365        settings.disabledSites = ["trusted.example", "bücher.example"]366        settings.httpAllowedSites = ["legacy.example"]367        let user = ShieldListParser.parse("""368        custom.example369        ||abp.example.net^370        ##.sponsored371        news.example##div[data-ad="1"] > .slot, a[href^="https://ads."]372        """).list373        let compilation = ContentRuleListGenerator.compile(settings: settings, builtIn: .builtIn, userLists: [user])374        #expect(compilation.lists.count == 6)375        for list in compilation.lists {376            let compiled = try await store.compileContentRuleList(forIdentifier: list.identifier, encodedContentRuleList: list.json)377            #expect(compiled?.identifier == list.identifier)378        }379        #expect(Set(await store.availableIdentifiers() ?? []) == compilation.identifiers)380    }381382    /// Proves the validator is not stricter than needed in the wrong direction: a pattern it refuses really383    /// does make WebKit reject the list.384    @MainActor @Test func webKitRejectsWhatTheValidatorRejects() async throws {385        let directory = FileManager.default.temporaryDirectory.appending(path: "orix-shield-\(UUID().uuidString)", directoryHint: .isDirectory)386        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)387        defer { try? FileManager.default.removeItem(at: directory) }388        let store = try #require(WKContentRuleListStore(url: directory))389        for pattern in ["a|b", "a{2,3}", "\\d+", "(?=x)y", "caf\u{E9}"] {390            #expect(ContentBlockerRegex.problem(in: pattern) != nil)391            let json = ContentRuleListGenerator.encode([ContentRule(trigger: .init(urlFilter: pattern), action: .init(type: .block))])392            await #expect(throws: (any Error).self, "WebKit accepted \(pattern)") {393                _ = try await store.compileContentRuleList(forIdentifier: "bad", encodedContentRuleList: json)394            }395        }396    }397}398#endif399
Files main
Menu

Theme