Repository Public License
1// ORIX Secure2// File: Packages/ORIXURLRisk/Tests/ORIXURLRiskTests/ExtractionAndQRTests.swift3// Description: Tests of link extraction from free text and of QR payload classification (Wi-Fi, contact, e-mail, phone,4// message, location, event, link, text), including that a Wi-Fi password is never echoed.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXSecureModel10import Testing11@testable import ORIXURLRisk1213@Suite("Link extraction")14struct ExtractionTests {15 @Test func linksInText() {16 let text = """17 Bonjour, votre colis est en attente : https://canadapost-postescanada.ca.suivi-colis.example.net/track?id=1 (voir aussi www.example.org/aide).18 Écrivez à support@example.com ou visitez example.co.uk, münchen.de et http://192.168.1.1/admin.19 Le fichier rapport.txt et la version 1.2.3 ne sont pas des liens. Encore: https://example.com/a, puis <https://bit.ly/abc>.20 """21 let urls = extractURLs(from: text)22 #expect(urls.contains("https://canadapost-postescanada.ca.suivi-colis.example.net/track?id=1"))23 #expect(urls.contains("www.example.org/aide"))24 #expect(urls.contains("example.co.uk"))25 #expect(urls.contains("münchen.de"))26 #expect(urls.contains("http://192.168.1.1/admin"))27 #expect(urls.contains("https://example.com/a"))28 #expect(urls.contains("https://bit.ly/abc"))29 #expect(!urls.contains { $0.contains("support@") })30 #expect(!urls.contains { $0.contains("rapport.txt") })31 #expect(!urls.contains("1.2.3"))32 #expect(Set(urls).count == urls.count)33 // Order of appearance.34 let first = urls.firstIndex(of: "www.example.org/aide") ?? -135 let second = urls.firstIndex(of: "example.co.uk") ?? -136 #expect(first >= 0 && first < second)37 }3839 @Test func edgeCases() {40 #expect(extractURLs(from: "").isEmpty)41 #expect(extractURLs(from: "no links here, just words.").isEmpty)42 #expect(extractURLs(from: "https://example.com") == ["https://example.com"])43 #expect(extractURLs(from: "see xn--80ak6aa92e.com now") == ["xn--80ak6aa92e.com"])44 #expect(extractURLs(from: "https://example.com https://example.com") == ["https://example.com"])45 #expect(extractURLs(from: "mailto:someone@example.com").count <= 1)46 #expect(extractURLs(from: String(repeating: "word ", count: 5_000)).isEmpty)47 #expect(LinkRecognition.looksLikeLink("https://example.com/x"))48 #expect(LinkRecognition.looksLikeLink("example.com"))49 #expect(LinkRecognition.looksLikeLink("пример.рф"))50 #expect(!LinkRecognition.looksLikeLink("hello"))51 #expect(!LinkRecognition.looksLikeLink("someone@example.com"))52 #expect(!LinkRecognition.looksLikeLink("file.txt"))53 #expect(!LinkRecognition.looksLikeLink("3.14"))54 }55}5657@Suite("QR payloads")58struct QRPayloadTests {59 private func allText(_ payload: QRPayload) -> String {60 var parts = payload.fields.flatMap { [$0.label, $0.value] } + payload.notInspected61 for finding in payload.findings {62 parts += [finding.title, finding.explanation, finding.recommendation ?? ""] + finding.notInspected63 parts += finding.evidence.flatMap { [$0.label, $0.value] }64 }65 return parts.joined(separator: "\n")66 }6768 private func checkFindings(_ payload: QRPayload) {69 #expect(!payload.findings.isEmpty)70 #expect(Set(payload.findings.map(\.id)).count == payload.findings.count)71 for finding in payload.findings {72 #expect(!finding.title.isEmpty)73 #expect(!finding.explanation.isEmpty)74 #expect(!finding.evidence.isEmpty, "\(finding.id)")75 }76 let tokens = Set(allText(payload).lowercased().split(whereSeparator: { !$0.isLetter }).map(String.init))77 for word in ["safe", "unsafe", "malicious", "clean", "infected", "virus"] {78 #expect(!tokens.contains(word), "\(word) in \(payload.kind)")79 }80 }8182 @Test func wifiProtected() {83 let payload = QRPayload(decoding: "WIFI:T:WPA;S:Maison Boucher;P:Tr3s\\;Secret:Pass!;H:false;;")84 #expect(payload.kind == .wifi)85 #expect(payload.wifi?.ssid == "Maison Boucher")86 #expect(payload.wifi?.security == .wpa)87 #expect(payload.wifi?.hasPassword == true)88 #expect(payload.wifi?.isHidden == false)89 #expect(payload.findings.contains { $0.id == "qr.wifi.protected" && $0.state == .verified })90 #expect(payload.findings.first?.category == .network)91 let text = allText(payload)92 #expect(!text.contains("Tr3s"))93 #expect(!text.contains("Secret:Pass"))94 #expect(text.contains("Maison Boucher"))95 // The password is not part of the structured, exportable configuration either.96 let wifiData = try? JSONEncoder().encode(payload.wifi)97 let wifiJSON = wifiData.map { String(decoding: $0, as: UTF8.self) } ?? ""98 #expect(!wifiJSON.contains("Tr3s"))99 checkFindings(payload)100 }101102 @Test func wifiOpenAndWEP() {103 let open = QRPayload(decoding: "WIFI:S:Cafe_Gratuit;T:nopass;;")104 #expect(open.wifi?.security == .open)105 #expect(open.findings.contains { $0.id == "qr.wifi.open" && $0.state == .attention && $0.severity == .moderate })106 checkFindings(open)107 let implicit = QRPayload(decoding: "wifi:S:Guest;;")108 #expect(implicit.kind == .wifi)109 #expect(implicit.wifi?.security == .open)110 let wep = QRPayload(decoding: "WIFI:T:WEP;S:OldRouter;P:abcde;;")111 #expect(wep.wifi?.security == .wep)112 #expect(wep.findings.contains { $0.id == "qr.wifi.wep" && $0.state == .attention })113 #expect(!allText(wep).contains("abcde"))114 let hidden = QRPayload(decoding: "WIFI:T:SAE;S:\"Quoted\";P:\"longpassword\";H:true;;")115 #expect(hidden.wifi?.ssid == "Quoted")116 #expect(hidden.wifi?.security == .wpa)117 #expect(hidden.wifi?.isHidden == true)118 #expect(hidden.findings.contains { $0.id == "qr.wifi.hidden" })119 #expect(!allText(hidden).contains("longpassword"))120 let enterprise = QRPayload(decoding: "WIFI:T:WPA2-EAP;S:eduroam;E:PEAP;I:user@uni.example;P:pw123456;;")121 #expect(enterprise.wifi?.security == .enterprise)122 #expect(!allText(enterprise).contains("pw123456"))123 let odd = QRPayload(decoding: "WIFI:T:FOO;S:x;P:y12345678;;")124 #expect(odd.wifi?.security == .unknown)125 #expect(odd.findings.contains { $0.id == "qr.wifi.unknown" })126 for payload in [implicit, wep, hidden, enterprise, odd, QRPayload(decoding: "WIFI:"), QRPayload(decoding: "WIFI:;;;;")] { checkFindings(payload) }127 }128129 @Test func linkPayloads() {130 let plain = QRPayload(decoding: "https://www.example.com/menu")131 #expect(plain.kind == .url)132 #expect(plain.urlAnalysis?.level == .noSignals)133 #expect(plain.highestURLLevel == .noSignals)134 #expect(plain.findings.contains { $0.id == "qr.link" })135 checkFindings(plain)136 let lookalike = QRPayload(decoding: " https://paypal.com.account-update.info/pay \n")137 #expect(lookalike.kind == .url)138 #expect(lookalike.urlAnalysis?.has(.brandEmbedded) == true)139 #expect((lookalike.highestURLLevel ?? .noSignals) >= .elevated)140 #expect(lookalike.findings.contains { $0.id == URLSignalKind.brandEmbedded.rawValue })141 #expect(!lookalike.notInspected.isEmpty)142 checkFindings(lookalike)143 #expect(QRPayload(decoding: "example.com/menu").kind == .url)144 #expect(QRPayload(decoding: "www.example.org").urlAnalysis?.schemeWasAssumed == true)145 let script = QRPayload(decoding: "javascript:alert(1)")146 #expect(script.kind == .url)147 #expect(script.urlAnalysis?.has(.nonWebScheme) == true)148 let app = QRPayload(decoding: "otpauth://totp/Example:alice?secret=JBSWY3DPEHPK3PXP&issuer=Example")149 #expect(app.kind == .url)150 #expect(app.urlAnalysis?.scheme == "otpauth")151 }152153 @Test func contactCards() {154 let vcard = """155 BEGIN:VCARD156 VERSION:3.0157 N:Tremblay;Marie;;;158 FN:Marie Tremblay159 ORG:Exemple inc.160 TEL;TYPE=CELL:+1-514-555-0100161 EMAIL:marie@example.com162 URL:https://paypal.com.account-update.info/marie163 NOTE:Voir aussi www.example.org164 END:VCARD165 """166 let payload = QRPayload(decoding: vcard)167 #expect(payload.kind == .contact)168 #expect(payload.fields.contains(QRPayload.Field("Name", "Marie Tremblay")))169 #expect(payload.fields.contains(QRPayload.Field("Phone", "+1-514-555-0100")))170 #expect(payload.fields.contains(QRPayload.Field("E-mail", "marie@example.com")))171 #expect(payload.embeddedURLAnalyses.count == 2)172 #expect((payload.highestURLLevel ?? .noSignals) >= .elevated)173 #expect(payload.findings.contains { $0.id == "link1.url.brand.embedded" })174 #expect(payload.findings.contains { $0.id == "qr.contact" })175 checkFindings(payload)176 let mecard = QRPayload(decoding: "MECARD:N:Tremblay,Marie;TEL:5145550100;EMAIL:marie@example.com;URL:https\\://example.com;;")177 #expect(mecard.kind == .contact)178 #expect(mecard.fields.contains(QRPayload.Field("Name", "Tremblay,Marie")))179 #expect(mecard.embeddedURLAnalyses.first?.host == "example.com")180 checkFindings(mecard)181 }182183 @Test func messagesCallsAndPlaces() {184 let mail = QRPayload(decoding: "mailto:info@example.com?subject=Bonjour%20!&body=Voir%20https%3A%2F%2Fbit.ly%2Fabc")185 #expect(mail.kind == .email)186 #expect(mail.fields.first?.value == "info@example.com")187 #expect(mail.fields.contains(QRPayload.Field("Subject", "Bonjour !")))188 #expect(mail.embeddedURLAnalyses.first?.has(.shortener) == true)189 checkFindings(mail)190 let matmsg = QRPayload(decoding: "MATMSG:TO:info@example.com;SUB:Hello;BODY:Text;;")191 #expect(matmsg.kind == .email)192 #expect(matmsg.fields.first?.value == "info@example.com")193 let tel = QRPayload(decoding: "tel:+1-900-555-0199")194 #expect(tel.kind == .phone)195 #expect(tel.fields.first?.value == "+1-900-555-0199")196 checkFindings(tel)197 let sms = QRPayload(decoding: "SMSTO:77777:JOIN PRIZES")198 #expect(sms.kind == .sms)199 #expect(sms.fields == [QRPayload.Field("Number", "77777"), QRPayload.Field("Message", "JOIN PRIZES")])200 checkFindings(sms)201 let sms2 = QRPayload(decoding: "sms:+15145550100?body=Hello%20there")202 #expect(sms2.kind == .sms)203 #expect(sms2.fields.last?.value == "Hello there")204 let geo = QRPayload(decoding: "geo:46.8139,-71.2080?q=Quebec")205 #expect(geo.kind == .location)206 #expect(geo.fields.count == 2)207 #expect(geo.findings.first?.state == .verified)208 let badGeo = QRPayload(decoding: "geo:abc,def")209 #expect(badGeo.kind == .location)210 #expect(badGeo.findings.first?.state == .attention)211 for payload in [matmsg, sms2, geo, badGeo] { checkFindings(payload) }212 let event = QRPayload(decoding: "BEGIN:VEVENT\nSUMMARY:Réunion\nDTSTART:20261201T140000Z\nDESCRIPTION:Lien http://185.199.108.153/join\nEND:VEVENT")213 #expect(event.kind == .calendarEvent)214 #expect(event.embeddedURLAnalyses.first?.has(.ipHost) == true)215 checkFindings(event)216 }217218 @Test func textAndEmpty() {219 let text = QRPayload(decoding: "Table 12 — commandez sur https://g00gle.com/menu ou demandez au serveur")220 #expect(text.kind == .text)221 #expect(text.embeddedURLAnalyses.count == 1)222 #expect(text.embeddedURLAnalyses.first?.has(.brandConfusable) == true)223 #expect(text.highestURLLevel == .high)224 checkFindings(text)225 let words = QRPayload(decoding: "Lot 4521-B")226 #expect(words.kind == .text)227 #expect(words.embeddedURLAnalyses.isEmpty)228 #expect(words.highestURLLevel == nil)229 checkFindings(words)230 let empty = QRPayload(decoding: " \n")231 #expect(empty.kind == .empty)232 #expect(empty.raw == " \n")233 checkFindings(empty)234 let data = try? JSONEncoder().encode(text)235 let decoded = data.flatMap { try? JSONDecoder().decode(QRPayload.self, from: $0) }236 #expect(decoded == text)237 }238}239