SPB Git

Repository Public License

AnalyzerTests.swift 24.4 KB 467 lines swift

1// ORIX Secure2// File: Packages/ORIXURLRisk/Tests/ORIXURLRiskTests/AnalyzerTests.swift3// Description: Tests of the link analyzer: decomposition, each signal, the benign corpus (false-positive rate), the4//              suspicious corpus, wording rules, robustness and timing.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXSecureModel10import Testing11@testable import ORIXURLRisk1213private let analyzer = URLRiskAnalyzer()1415private func wordsFound(in text: String, among words: [String]) -> [String] {16    let tokens = Set(text.lowercased().split(whereSeparator: { !$0.isLetter }).map(String.init))17    return words.filter { tokens.contains($0) }18}1920private let forbiddenWords = ["safe", "unsafe", "safely", "malicious", "clean", "infected", "virus", "viruses"]2122private func check(_ finding: Finding, context: String) {23    #expect(!finding.id.isEmpty, "\(context)")24    #expect(!finding.title.trimmingCharacters(in: .whitespaces).isEmpty, "\(context) \(finding.id)")25    #expect(finding.explanation.count >= 40, "\(context) \(finding.id)")26    #expect(!finding.evidence.isEmpty, "\(context) \(finding.id)")27    for evidence in finding.evidence {28        #expect(!evidence.label.isEmpty, "\(context) \(finding.id)")29        #expect(!evidence.value.isEmpty, "\(context) \(finding.id) evidence \(evidence.label)")30    }31    let prose = [finding.title, finding.explanation, finding.recommendation ?? ""] + finding.notInspected + finding.evidence.map(\.label)32    for text in prose {33        let found = wordsFound(in: text, among: forbiddenWords)34        #expect(found.isEmpty, "\(context) \(finding.id): \(found) in \"\(text)\"")35    }36    if finding.state == .attention {37        #expect(finding.severity > .none, "\(context) \(finding.id)")38        #expect(finding.confidence == .heuristic || finding.confidence == .measured)39        #expect(finding.verification == .heuristic || finding.verification == .parsedData)40    }41}4243@Suite("Decomposition")44struct DecompositionTests {45    @Test func fullURL() {46        let a = analyzer.analyze("  HTTPS://User:Secret@Shop.Example.CO.UK:8443/a/b%20c?x=1&name=J%C3%A9r%C3%B4me+B&flag#top  ")47        #expect(a.isParsed)48        #expect(a.scheme == "https")49        #expect(!a.schemeWasAssumed)50        #expect(a.hasUserinfo)51        #expect(a.host == "shop.example.co.uk")52        #expect(a.unicodeHost == "shop.example.co.uk")53        #expect(a.hostKind == .domain)54        #expect(a.registrableDomain == "example.co.uk")55        #expect(a.publicSuffix == "co.uk")56        #expect(a.subdomainLabels == ["shop"])57        #expect(a.port == 8443)58        #expect(a.path == "/a/b%20c")59        #expect(a.queryItems == [URLQueryPair(name: "x", value: "1"), URLQueryPair(name: "name", value: "Jérôme B"), URLQueryPair(name: "flag", value: nil)])60        #expect(a.fragment == "top")61        #expect(a.normalizedURL == "https://User:Secret@shop.example.co.uk:8443/a/b%20c?x=1&name=J%C3%A9r%C3%B4me+B&flag#top")62        #expect(a.findings.count == a.signals.count)63        // The password of the userinfo is never copied into evidence.64        for finding in a.findings {65            for evidence in finding.evidence { #expect(!evidence.value.contains("Secret")) }66        }67    }6869    @Test func internationalHost() {70        let a = analyzer.analyze("https://www.münchen.de/rathaus")71        #expect(a.host == "www.xn--mnchen-3ya.de")72        #expect(a.unicodeHost == "www.münchen.de")73        #expect(a.registrableDomain == "xn--mnchen-3ya.de")74        #expect(a.unicodeRegistrableDomain == "münchen.de")75        #expect(a.publicSuffix == "de")76        let b = analyzer.analyze("https://WWW.XN--MNCHEN-3YA.DE/rathaus")77        #expect(b.unicodeHost == "www.münchen.de")78        #expect(b.host == a.host)79        let signal = a.signal(.internationalizedHost)80        #expect(signal != nil)81        let values = signal?.finding.evidence.map(\.value) ?? []82        #expect(values.contains("www.münchen.de"))83        #expect(values.contains("www.xn--mnchen-3ya.de"))84    }8586    @Test func defaultPortIsRemovedAndNotASignal() {87        let a = analyzer.analyze("https://example.com:443/x")88        #expect(a.port == 443)89        #expect(a.normalizedURL == "https://example.com/x")90        #expect(!a.has(.nonDefaultPort))91        #expect(!analyzer.analyze("http://example.com:80/").has(.nonDefaultPort))92        #expect(analyzer.analyze("http://example.com:443/").has(.nonDefaultPort))93    }9495    @Test func schemeDetection() {96        #expect(analyzer.analyze("example.com:8080/path").scheme == "https")97        #expect(analyzer.analyze("example.com:8080/path").port == 8080)98        #expect(analyzer.analyze("example.com:8080/path").schemeWasAssumed)99        #expect(analyzer.analyze("localhost:3000").host == "localhost")100        #expect(analyzer.analyze("//example.com/x").host == "example.com")101        #expect(analyzer.analyze("https:example.com").host == "example.com")102        #expect(analyzer.analyze("https:\\\\example.com\\path").host == "example.com")103        #expect(analyzer.analyze("com.example.app:open").scheme == "com.example.app")104        #expect(analyzer.analyze("mailto:someone@example.com").scheme == "mailto")105        #expect(analyzer.analyze("mailto:someone@example.com").host == nil)106        #expect(analyzer.analyze("apple.com:443@evil.example/").host == "evil.example")107        #expect(analyzer.analyze("apple.com:443@evil.example/").has(.userinfo))108        #expect(analyzer.analyze("HTTP://EXAMPLE.COM").scheme == "http")109        #expect(analyzer.analyze("example.com.").host == "example.com")110    }111112    @Test func ipHosts() {113        let a = analyzer.analyze("http://3232235777/admin")114        #expect(a.hostKind == .ipv4)115        #expect(a.host == "192.168.1.1")116        #expect(a.ipLiteral?.canonical == "192.168.1.1")117        #expect(a.ipLiteral?.isObfuscated == true)118        #expect(a.ipLiteral?.scope == .privateNetwork)119        #expect(a.registrableDomain == nil)120        let evidence = a.signal(.obfuscatedIP)?.finding.evidence.map(\.value) ?? []121        #expect(evidence.contains("3232235777"))122        #expect(evidence.contains("192.168.1.1"))123        let b = analyzer.analyze("https://[FE80::1]/")124        #expect(b.hostKind == .ipv6)125        #expect(b.host == "[fe80::1]")126        #expect(b.signal(.ipHost)?.weight == 5)127        #expect(analyzer.analyze("http://192.168.0.1/").signal(.ipHost)?.weight == 5)128        #expect(analyzer.analyze("http://8.8.8.8/").signal(.ipHost)?.weight == 30)129        #expect(!analyzer.analyze("http://192.168.0.1/").has(.obfuscatedIP))130        #expect(analyzer.analyze("https://1.2.3.4.example.com/").hostKind == .domain)131    }132133    @Test func codableRoundTrip() throws {134        let a = analyzer.analyze("https://paypal.com.account-update.info/?next=https://evil.example.net")135        let data = try JSONEncoder().encode(a)136        let decoded = try JSONDecoder().decode(URLAnalysis.self, from: data)137        #expect(decoded == a)138        #expect(decoded.hashValue == a.hashValue)139        let document = a.reportDocument()140        #expect(document.kind == .urlAnalysis)141        #expect(document.allFindings.count == a.findings.count)142        #expect(!document.unavailable.isEmpty)143    }144}145146@Suite("Scoring")147struct ScoringTests {148    @Test func thresholds() {149        #expect(URLRiskScoring.level(forScore: 0) == .noSignals)150        #expect(URLRiskScoring.level(forScore: 1) == .low)151        #expect(URLRiskScoring.level(forScore: URLRiskScoring.elevatedThreshold - 1) == .low)152        #expect(URLRiskScoring.level(forScore: URLRiskScoring.elevatedThreshold) == .elevated)153        #expect(URLRiskScoring.level(forScore: URLRiskScoring.highThreshold - 1) == .elevated)154        #expect(URLRiskScoring.level(forScore: URLRiskScoring.highThreshold) == .high)155        #expect(URLRiskScoring.level(forScore: 1000) == .high)156        #expect(URLRiskLevel.noSignals < .low && URLRiskLevel.low < .elevated && URLRiskLevel.elevated < .high)157        #expect(URLRiskScoring.methodology.count >= 4)158    }159160    @Test func scoreIsTheCappedSumOfWeights() {161        for item in Corpora.suspicious {162            let a = analyzer.analyze(item.url)163            let sum = a.signals.reduce(0) { $0 + $1.weight }164            #expect(a.score == min(100, sum), "\(item.url)")165            #expect(a.level == URLRiskScoring.level(forScore: a.score), "\(item.url)")166            #expect(Set(a.signals.map(\.id)).count == a.signals.count, "duplicate signal id in \(item.url)")167            for signal in a.signals {168                #expect(signal.id == signal.kind.rawValue)169                #expect(signal.finding.id == signal.id)170                #expect(signal.weight >= 0)171                #expect(signal.isInformational == (signal.finding.state == .verified))172            }173        }174    }175176    @Test func keywordsAloneStayLow() {177        for url in ["https://login-verify-secure-account-update-wallet-banking.example.org/", "https://secure.login.example.org", "https://verify.example.org"] {178            let a = analyzer.analyze(url)179            #expect(a.has(.sensitiveKeywords), "\(url)")180            #expect((a.signal(.sensitiveKeywords)?.weight ?? 99) <= 10)181        }182        // Keywords are looked for in the host only.183        #expect(!analyzer.analyze("https://example.org/login/verify/secure?account=update").has(.sensitiveKeywords))184        #expect(analyzer.analyze("https://verify.example.org").level == .low)185    }186187    @Test func everyAnalysisStatesItsLimits() {188        for url in ["https://example.com", "", "javascript:alert(1)", "https://аррӏе.com"] {189            let a = analyzer.analyze(url)190            #expect(a.notInspected.count >= 5)191            let joined = a.notInspected.joined(separator: " ").lowercased()192            #expect(joined.contains("not fetched"))193            #expect(joined.contains("reputation"))194            #expect(joined.contains("redirects are not followed"))195            #expect(joined.contains("not proven"))196            #expect(joined.contains("public suffix list"))197            #expect(!a.methodology.isEmpty)198            #expect(!a.summary.isEmpty)199        }200    }201}202203@Suite("Brands")204struct BrandTests {205    static let brandKinds: Set<URLSignalKind> = [.brandConfusable, .brandTyposquat, .brandEmbedded, .brandOtherSuffix, .brandInPath, .sensitiveKeywords]206207    @Test("No brand signal on any embedded genuine domain or its sub-domains")208    func genuineDomains() {209        #expect(BrandList.brands.count >= 60)210        var checked = 0211        for brand in BrandList.brands {212            // Hosting platforms whose sub-domains belong to customers are public suffixes: not the brand's own hosts.213            for domain in brand.domains where !PublicSuffix.multiLabelSuffixes.contains(domain) {214                for url in ["https://\(domain)/", "https://www.\(domain)/account/login", "https://secure.login.\(domain)/verify?next=/home"] {215                    let a = analyzer.analyze(url)216                    let fired = a.signals.filter { Self.brandKinds.contains($0.kind) }.map(\.id)217                    #expect(fired.isEmpty, "\(url): \(fired)")218                    #expect(a.level <= .low, "\(url): \(a.level) \(a.signals.map(\.id))")219                    checked += 1220                }221            }222        }223        #expect(checked > 500)224    }225226    @Test func brandNamesInsideOrdinaryWordsDoNotFire() {227        let urls = [228            "https://www.pineapple.com/", "https://www.snapple.com/", "https://www.aircanada.com/", "https://www.canadiantire.ca/",229            "https://www.tdsynnex.com/", "https://www.upstart.com/", "https://www.groups.io/", "https://www.rbcapitalmarkets-example.org/",230            "https://www.brno.cz/", "https://www.nbc.com/", "https://www.ubs.com/", "https://www.bmw.com/", "https://www.dhs.gov/",231            "https://www.chasebank-fans.example.org/", "https://www.stripes.com/", "https://zoominfo.com/", "https://www.québec.com/",232            "https://www.theverge.com/2024/5/1/apple-google-microsoft-amazon-paypal-earnings",233            "https://example.org/search?q=paypal+login+apple+id",234        ]235        for url in urls {236            let a = analyzer.analyze(url)237            let fired = a.signals.filter { [.brandConfusable, .brandTyposquat, .brandEmbedded, .brandOtherSuffix, .brandInPath].contains($0.kind) }.map(\.id)238            #expect(fired.isEmpty, "\(url): \(fired)")239        }240    }241242    @Test func confusableEvidenceShowsTheSkeleton() {243        let a = analyzer.analyze("https://аррӏе.com/")244        let brand = a.signal(.brandConfusable)245        #expect(brand?.weight == 70)246        #expect(brand?.finding.confidence == .heuristic)247        #expect(brand?.finding.verification == .heuristic)248        let values = brand?.finding.evidence.map(\.value) ?? []249        #expect(values.contains("apple"))250        #expect(values.contains("аррӏе"))251        #expect(values.contains("xn--80ak6aa92e"))252        #expect(values.contains { $0.contains("apple.com") })253        let whole = a.signal(.wholeScriptConfusable)?.finding.evidence.map(\.value) ?? []254        #expect(whole.contains("apple"))255        #expect(a.host == "xn--80ak6aa92e.com")256        #expect(a.unicodeHost == "аррӏе.com")257    }258259    @Test func wholeScriptLabelUnderNativeSuffixIsDownWeighted() {260        #expect(analyzer.analyze("https://сосо.com").signal(.wholeScriptConfusable)?.weight == 30)261        #expect(analyzer.analyze("https://сосо.ru").signal(.wholeScriptConfusable)?.weight == 10)262        #expect(analyzer.analyze("https://сосо.рф").signal(.wholeScriptConfusable)?.weight == 10)263        #expect(!analyzer.analyze("https://пример.com").has(.wholeScriptConfusable))264        #expect(!analyzer.analyze("https://日本語.com").has(.mixedScript))265        #expect(!analyzer.analyze("https://東京タワー.jp").has(.mixedScript))266        #expect(!analyzer.analyze("https://tokyo東京.jp").has(.mixedScript))267    }268269    @Test func redirectToTheSameSiteOrBrandIsNotASignal() {270        #expect(!analyzer.analyze("https://example.com/login?next=https%3A%2F%2Fwww.example.com%2Fhome").has(.redirectParameter))271        #expect(!analyzer.analyze("https://example.com/login?next=/home").has(.redirectParameter))272        #expect(!analyzer.analyze("https://accounts.google.com/signin?continue=https://www.youtube.com/").has(.redirectParameter))273        #expect(!analyzer.analyze("https://example.com/?utm_source=https://other.example.net").has(.redirectParameter))274        #expect(analyzer.analyze("https://example.com/login?next=https%3A%2F%2Fother.example.net").has(.redirectParameter))275        #expect(!analyzer.analyze("https://example.com/proxy/https://example.com/x").has(.nestedURLInPath))276    }277}278279@Suite("Corpora")280struct CorpusTests {281    @Test("Benign corpus: false-positive rate")282    func benign() {283        #expect(Corpora.benign.count >= 60)284        #expect(Set(Corpora.benign).count == Corpora.benign.count)285        var counts: [URLRiskLevel: Int] = [:]286        var aboveLow: [String] = []287        for url in Corpora.benign {288            let a = analyzer.analyze(url)289            #expect(a.isParsed, "\(url)")290            #expect(a.level != .high, "\(url): \(a.signals.map(\.id))")291            counts[a.level, default: 0] += 1292            if a.level > .low { aboveLow.append("\(url) [\(a.signals.filter { $0.weight > 0 }.map { "\($0.id)=\($0.weight)" }.joined(separator: ","))]") }293            for finding in a.findings { check(finding, context: url) }294        }295        let total = Double(Corpora.benign.count)296        let rate = Double(aboveLow.count) / total297        print("BENIGN CORPUS: \(Corpora.benign.count) links — no signals: \(counts[.noSignals, default: 0]), low: \(counts[.low, default: 0]), elevated: \(counts[.elevated, default: 0]), high: \(counts[.high, default: 0])")298        print("BENIGN CORPUS: above low = \(aboveLow.count) / \(Corpora.benign.count) = \(String(format: "%.2f", rate * 100)) %")299        for line in aboveLow { print("BENIGN CORPUS: above low: \(line)") }300        #expect(rate <= 0.05)301        #expect(counts[.high, default: 0] == 0)302    }303304    @Test("Suspicious corpus: every expected signal fires")305    func suspicious() {306        #expect(Corpora.suspicious.count >= 50)307        var covered = Set<URLSignalKind>()308        var counts: [URLRiskLevel: Int] = [:]309        for item in Corpora.suspicious {310            let a = analyzer.analyze(item.url)311            for kind in item.expected {312                #expect(a.has(kind), "\(item.url): expected \(kind.rawValue), got \(a.signals.map(\.id))")313                covered.insert(kind)314            }315            #expect(a.level >= item.minimum, "\(item.url): \(a.level) < \(item.minimum), signals \(a.signals.map(\.id))")316            counts[a.level, default: 0] += 1317            for finding in a.findings { check(finding, context: item.url) }318        }319        let missing = URLSignalKind.allCases.filter { !covered.contains($0) }320        #expect(missing.isEmpty, "signal kinds without a corpus entry: \(missing.map(\.rawValue))")321        print("SUSPICIOUS CORPUS: \(Corpora.suspicious.count) links — no signals: \(counts[.noSignals, default: 0]), low: \(counts[.low, default: 0]), elevated: \(counts[.elevated, default: 0]), high: \(counts[.high, default: 0])")322    }323324    @Test("No analysis text uses verdict words")325    func wording() {326        var texts: [String] = URLRiskScoring.methodology + URLAnalysis.standardNotInspected327        texts += URLRiskLevel.allCases.map(\.title) + IPAddressScope.allCases.map(\.title) + QRPayload.Kind.allCases.map(\.title)328        for url in Corpora.benign + Corpora.suspicious.map(\.url) + ["", "   "] {329            let a = analyzer.analyze(url)330            texts.append(a.summary)331            texts += a.notInspected + a.methodology332        }333        for text in Set(texts) {334            let found = wordsFound(in: text, among: forbiddenWords)335            #expect(found.isEmpty, "\(found) in \"\(text)\"")336        }337    }338}339340@Suite("Robustness and timing")341struct RobustnessTests {342    @Test func emptyAndWhitespace() {343        for input in ["", " ", "\n\t  \r\n", "\u{200B}", "\u{FEFF}\u{200B} "] {344            let a = analyzer.analyze(input)345            #expect(!a.isParsed)346            #expect(a.has(.invalidInput))347            #expect(a.input == input)348            for finding in a.findings { check(finding, context: "empty") }349        }350    }351352    @Test func oddInputsNeverCrash() {353        let inputs = [354            ":", "://", "http://", "https:///", "http://@", "http://:80", "http://[", "http://[]", "http://[::1", "http://[zz]/",355            "http://a..b/", "http://.", "http://-/", "http://%", "http://%zz/", "http://%00/", "http://a:b:c/", "?", "#", "/", "\\",356            "@", "a@b", "http://user:pass@", "http://\u{0}/", "https://exa\u{0}mple.com", "xn--", "https://xn--/", "http://1.2.3.4.5/",357            "http://0x/", "http://0xffffffffffffffffffff/", "http://999999999999999999999/", "https://é", "https://😀.example/",358            "https://example.com/%", "https://example.com/%2", "https://example.com/%zz", "https://example.com/?=&=&&&", "https://example.com/?a=%FF%FE",359            "data:", "javascript:", "a:", "1:2", "http:/example.com", "http:example.com", "HtTp://ExAmPlE.CoM:65535", "https://example.com:65536",360            "https://example.com:-1", "https://example.com:8a", "\u{202E}\u{202E}\u{202E}", String(repeating: ".", count: 500), String(repeating: "@", count: 500),361            String(repeating: ":", count: 500), String(repeating: "%", count: 500), String(repeating: "xn--", count: 200) + ".com",362            String(repeating: "a.", count: 300) + "com", "https://" + String(repeating: "é", count: 300) + ".com", "WIFI:", "BEGIN:VCARD",363        ]364        for input in inputs {365            let a = analyzer.analyze(input)366            #expect(a.input == input)367            #expect(a.level == URLRiskScoring.level(forScore: a.score))368            for finding in a.findings { check(finding, context: input.prefix(40).description) }369            _ = extractURLs(from: input)370            _ = QRPayload(decoding: input)371        }372    }373374    @Test func randomBytesNeverCrash() {375        var generator = SplitMix(seed: 20261120)376        let fragments = ["http://", "https://", "xn--", "%", "%25", "%00", "@", ":", "/", "?", "#", "&", "=", ".", "..", "[", "]", "\\", "а", "。", "\u{202E}", "paypal", "login", "0x", "WIFI:", "url=", "com", "\u{0}", " "]377        var analyzed = 0378        for round in 0..<3000 {379            var input: String380            if round % 2 == 0 {381                let bytes = (0..<Int(generator.next() % 120)).map { _ in UInt8(truncatingIfNeeded: generator.next()) }382                input = String(decoding: bytes, as: UTF8.self)383            } else {384                input = ""385                for _ in 0..<Int(generator.next() % 25) {386                    if generator.next() % 3 == 0 {387                        input.unicodeScalars.append(Unicode.Scalar(UInt8(0x20 + generator.next() % 95)))388                    } else {389                        input += fragments[Int(generator.next() % UInt64(fragments.count))]390                    }391                }392            }393            let a = analyzer.analyze(input)394            #expect(a.score >= 0 && a.score <= 100)395            #expect(a.findings.count == a.signals.count)396            if round % 10 == 0 {397                _ = extractURLs(from: input)398                _ = QRPayload(decoding: input)399                for finding in a.findings { check(finding, context: "fuzz") }400            }401            analyzed += 1402        }403        #expect(analyzed == 3000)404    }405406    static let longInputs: [(String, String)] = [407        ("long path", "https://example.com/" + String(repeating: "a", count: 9_980)),408        ("long query", "https://example.com/?" + String(repeating: "k=v&", count: 2_495)),409        ("long host", "https://" + String(repeating: "a", count: 9_980) + ".com/"),410        ("many labels", "https://" + String(repeating: "ab.", count: 3_326) + "com/"),411        ("many escapes", "https://example.com/" + String(repeating: "%25", count: 3_326)),412        ("many nested", "https://example.com/" + String(repeating: "http:", count: 1_996)),413        ("many at signs", "https://" + String(repeating: "a@", count: 4_990) + "example.com/"),414        ("many colons", String(repeating: "a:", count: 5_000)),415        ("unicode", "https://example.com/" + String(repeating: "é\u{202E}а", count: 3_326)),416        ("redirect values", "https://example.com/?" + String(repeating: "url=https%3A%2F%2Fa.example.net&", count: 320)),417        ("spaces", String(repeating: "word ", count: 2_000)),418        ("random", String((0..<10_000).map { _ in "abcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%".randomElement() ?? "a" })),419    ]420421    @Test("A 10 000-character input is analyzed in under 100 ms")422    func longInputsAreBounded() {423        let clock = ContinuousClock()424        _ = analyzer.analyze("https://warm.example.com/")425        for (name, input) in Self.longInputs {426            #expect(input.unicodeScalars.count >= 9_900, "\(name)")427            var result: URLAnalysis?428            let elapsed = clock.measure { result = analyzer.analyze(input) }429            let milliseconds = Double(elapsed.components.attoseconds) / 1e15 + Double(elapsed.components.seconds) * 1000430            print("TIMING 10k \(name): \(String(format: "%.2f", milliseconds)) ms, level \(result?.level.title ?? "-")")431            #expect(milliseconds < 100, "\(name) took \(milliseconds) ms")432            #expect(result?.input == input)433        }434        let huge = String(repeating: "a", count: 300_000)435        var hugeResult: URLAnalysis?436        let elapsed = clock.measure { hugeResult = analyzer.analyze(huge) }437        #expect(hugeResult?.isParsed == false)438        #expect(elapsed < .milliseconds(100))439    }440441    @Test("Mean analysis time of typical links")442    func typicalTiming() {443        let typical = [444            "https://www.example.com/products/item?id=42&utm_source=newsletter",445            "https://accounts.google.com/o/oauth2/v2/auth?client_id=123&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback",446            "https://paypal.com.account-update.info/signin?next=https://evil.example.net",447            "https://аррӏе.com/login",448            "http://3232235777/admin",449        ]450        let clock = ContinuousClock()451        var sink = 0452        let runs = 1_000453        let elapsed = clock.measure {454            for index in 0..<runs { sink += analyzer.analyze(typical[index % typical.count]).score }455        }456        let total = Double(elapsed.components.attoseconds) / 1e15 + Double(elapsed.components.seconds) * 1000457        let mean = total / Double(runs)458        #if DEBUG459        let build = "debug build"460        #else461        let build = "release build"462        #endif463        print("TIMING typical: mean \(String(format: "%.3f", mean)) ms per link over \(runs) runs (\(build)), checksum \(sink)")464        #expect(mean < 20)465    }466}467
Files main
Menu

Theme