Repository Public License
1import Foundation2import NavigatorCore3import TestSupport4import Testing5@testable import WebRuntime67/// Pure logic: no web view involved.8@Suite struct NavigationPolicyTests {9 let settings = NavigationPolicySettings(allowsFileURLs: true)1011 private func decide(_ url: String, main: Bool = true, kind: NavigationContext.Kind = .other, app: Bool = false,12 source: String? = "https", document: String? = "https", download: Bool = false,13 settings: NavigationPolicySettings? = nil) -> NavigationVerdict {14 NavigationPolicy.decide(NavigationContext(url: URL(string: url)!, isMainFrame: main, kind: kind, isAppInitiated: app,15 sourceScheme: source, mainDocumentScheme: document, shouldPerformDownload: download),16 settings: settings ?? self.settings)17 }1819 @Test func webSchemes() {20 #expect(decide("https://example.com/") == .allow)21 #expect(decide("http://example.com/", main: false) == .allow)22 #expect(decide("about:blank") == .allow)23 #expect(decide("about:srcdoc", main: false) == .allow)24 #expect(decide("about:config") == .block(.malformed))25 #expect(decide("https://example.com/file.zip", download: true) == .download)26 }2728 @Test func scriptSchemesAreNeverNavigated() {29 for url in ["javascript:alert(1)", "JAVASCRIPT:alert(1)", "vbscript:msgbox(1)"] {30 #expect(decide(url) == .block(.scriptScheme))31 #expect(decide(url, app: true) == .block(.scriptScheme), "even when the app asks")32 #expect(decide(url, main: false) == .block(.scriptScheme))33 #expect(NavigationPolicy.decideAppLoad(URL(string: url)!, settings: settings) == .block(.scriptScheme))34 }35 }3637 @Test func opaqueDocuments() {38 #expect(decide("data:text/html,<h1>x</h1>") == .block(.opaqueTopLevelDocument))39 #expect(decide("blob:https://example.com/1234") == .block(.opaqueTopLevelDocument))40 #expect(decide("data:text/html,x", app: true) == .block(.opaqueTopLevelDocument))41 // Sub-frames and downloads are what WebKit permits them for.42 #expect(decide("data:text/html,x", main: false) == .allow)43 #expect(decide("blob:https://example.com/1234", main: false) == .allow)44 #expect(decide("blob:https://example.com/1234", download: true) == .download)45 #expect(decide("data:application/pdf;base64,AAAA", download: true) == .download)46 }4748 @Test func fileURLs() {49 #expect(decide("file:///etc/hosts") == .block(.localFileFromWeb))50 #expect(decide("file:///etc/hosts", kind: .linkActivated) == .block(.localFileFromWeb))51 #expect(decide("file:///etc/hosts", main: false) == .block(.localFileFromWeb))52 #expect(decide("file:///Users/me/a.html", app: true) == .allow)53 #expect(decide("file:///Users/me/b.html", kind: .linkActivated, source: "file", document: "file") == .allow)54 #expect(decide("file:///Users/me/b.html", main: false, source: "file", document: "file") == .allow)55 #expect(decide("file:///Users/me/a.html", kind: .backForward) == .allow)56 // A web frame inside a local document cannot pull other local files into view.57 #expect(decide("file:///etc/hosts", kind: .linkActivated, source: "https", document: "file") == .block(.localFileFromWeb))58 // iOS: no file access at all.59 let ios = NavigationPolicySettings(allowsFileURLs: false)60 #expect(decide("file:///a.html", app: true, settings: ios) == .block(.localFileFromWeb))61 }6263 @Test func internalPages() {64 #expect(decide("orix://newtab/") == .block(.internalPageFromWeb))65 #expect(decide("orix://newtab/", kind: .linkActivated) == .block(.internalPageFromWeb))66 #expect(decide("orix://newtab/", main: false) == .block(.internalPageFromWeb))67 #expect(decide("orix://newtab/", kind: .formSubmitted) == .block(.internalPageFromWeb))68 #expect(decide("orix://newtab/", app: true) == .allow)69 #expect(decide("orix://settings/", kind: .linkActivated, source: "orix", document: "orix") == .allow)70 #expect(decide("orix://start/frame", main: false, source: "orix", document: "orix") == .allow)71 #expect(decide("orix://newtab/", kind: .backForward) == .allow)72 #expect(decide("orix://newtab/", kind: .reload, source: "orix", document: "orix") == .allow)73 // A web frame embedded in an internal page stays outside.74 #expect(decide("orix://settings/", kind: .linkActivated, source: "https", document: "orix") == .block(.internalPageFromWeb))75 }7677 @Test func externalApplications() {78 for url in ["mailto:a@example.com", "tel:+15145550100", "facetime:a@example.com", "itms-apps://apps.apple.com/app/id1", "unknown-app://x"] {79 #expect(decide(url) == .external(URL(string: url)!))80 #expect(decide(url, main: false) == .block(.externalSchemeInSubframe), "frames cannot launch applications")81 }82 #expect(NavigationPolicy.wellKnownExternalSchemes.isSuperset(of: ["mailto", "tel", "facetime", "itms-apps"]))83 }8485 @Test func httpsOnly() {86 var strict = NavigationPolicySettings(allowsFileURLs: true, httpsOnly: true)87 #expect(decide("http://example.com/a?b=1#c", settings: strict) == .upgradeToHTTPS(URL(string: "https://example.com/a?b=1#c")!))88 #expect(decide("http://example.com:80/", settings: strict) == .upgradeToHTTPS(URL(string: "https://example.com/")!))89 #expect(decide("http://example.com:8080/", settings: strict) == .upgradeToHTTPS(URL(string: "https://example.com:8080/")!))90 #expect(decide("https://example.com/", settings: strict) == .allow)91 // Sub-resources and frames are WebKit's business (mixed content rules), not the navigation policy's.92 #expect(decide("http://example.com/", main: false, settings: strict) == .allow)93 // Loopback is exempt by default; the user's explicit fallback exempts a host.94 #expect(decide("http://localhost:3000/", settings: strict) == .allow)95 #expect(decide("http://127.0.0.1/", settings: strict) == .allow)96 #expect(decide("http://[::1]:8080/", settings: strict) == .allow)97 strict.httpsOnlyExemptsLoopback = false98 #expect(decide("http://localhost:3000/", settings: strict) == .upgradeToHTTPS(URL(string: "https://localhost:3000/")!))99 strict.httpAllowedHosts = ["example.com"]100 #expect(decide("http://example.com/", settings: strict) == .allow)101 #expect(decide("http://sub.example.com/", settings: strict) == .upgradeToHTTPS(URL(string: "https://sub.example.com/")!))102 }103104 @Test func responsesThatBecomeDownloads() {105 #expect(!NavigationPolicy.responseIsDownload(canShowMIMEType: true, contentDisposition: nil))106 #expect(!NavigationPolicy.responseIsDownload(canShowMIMEType: true, contentDisposition: "inline; filename=a.pdf"))107 #expect(NavigationPolicy.responseIsDownload(canShowMIMEType: true, contentDisposition: "attachment"))108 #expect(NavigationPolicy.responseIsDownload(canShowMIMEType: true, contentDisposition: " Attachment; filename=\"a.html\""))109 #expect(NavigationPolicy.responseIsDownload(canShowMIMEType: false, contentDisposition: nil))110 }111112 @Test func pendingRequestMatching() {113 func same(_ a: String, _ b: String) -> Bool { NavigationPolicy.sameDocumentTarget(URL(string: a)!, URL(string: b)!) }114 #expect(same("http://example.com", "http://example.com/"))115 #expect(same("HTTP://Example.COM:80/a", "http://example.com/a"))116 #expect(same("https://example.com/a#one", "https://example.com/a#two"))117 #expect(!same("https://example.com/a", "https://example.com/b"))118 #expect(!same("https://example.com/a?x=1", "https://example.com/a?x=2"))119 #expect(!same("http://example.com/", "https://example.com/"))120 #expect(same("file:///tmp/../tmp/a.html", "file:///tmp/a.html"))121 }122}123124@Suite struct BridgeValidatorTests {125 let page = URL(string: "https://example.com/article")!126 var origin: WebOrigin { WebOrigin(url: page)! }127128 private func envelope(kind: String, payload: [String: ScriptValue] = [:], handler: String = "orixBridge",129 world: String? = "orix.bridge", ownWebView: Bool = true, mainFrame: Bool = true,130 frameOrigin: WebOrigin? = WebOrigin(scheme: "https", host: "example.com")) -> BridgeEnvelope {131 BridgeEnvelope(handlerName: handler, worldName: world, isFromOwnWebView: ownWebView, isMainFrame: mainFrame,132 frameOrigin: frameOrigin, pageOrigin: origin, pageURL: page,133 body: .object(["v": 1, "kind": .string(kind), "payload": .object(payload)]))134 }135136 private func rejection(_ envelope: BridgeEnvelope) -> BridgeRejection? {137 do { _ = try BridgeValidator.validate(envelope); return nil } catch { return error }138 }139140 var metadataPayload: [String: ScriptValue] {141 ["url": "https://example.com/article#top", "title": "T", "description": "", "language": "en", "themeColor": "#fff",142 "canonical": "https://example.com/canonical",143 "icons": [.object(["href": "https://example.com/i.png", "rel": "icon", "sizes": "16x16 48x48", "type": "image/png"]),144 .object(["href": "javascript:alert(1)", "rel": "icon", "sizes": "any", "type": ""])],145 "openGraph": .object(["title": "OG", "image": "file:///etc/passwd", "url": "https://example.com/og"])]146 }147148 @Test func acceptsWellFormedMessagesFromTheRightWorld() throws {149 #expect(try BridgeValidator.validate(envelope(kind: "activation", mainFrame: false, frameOrigin: WebOrigin(scheme: "https", host: "ads.invalid"))) == .activation)150151 guard case .metadata(let metadata) = try BridgeValidator.validate(envelope(kind: "metadata", payload: metadataPayload)) else {152 Issue.record("expected metadata"); return153 }154 #expect(metadata.url == page && metadata.title == "T")155 // Non-web URLs inside an otherwise valid payload are dropped, not passed on.156 #expect(metadata.icons.map(\.url.absoluteString) == ["https://example.com/i.png"])157 #expect(metadata.icons.first?.declaredSize == 48)158 #expect(metadata.openGraph.imageURL == nil && metadata.openGraph.url == URL(string: "https://example.com/og"))159160 let scroll: [String: ScriptValue] = ["x": 0, "y": 120, "contentWidth": 800, "contentHeight": 4000, "viewportWidth": 800, "viewportHeight": 600]161 #expect(try BridgeValidator.validate(envelope(kind: "scroll", payload: scroll))162 == .scroll(ScrollMetrics(x: 0, y: 120, contentWidth: 800, contentHeight: 4000, viewportWidth: 800, viewportHeight: 600)))163164 let selection: [String: ScriptValue] = ["url": "https://example.com/article", "text": "hello", "isCollapsed": false,165 "rect": .object(["x": 1, "y": 2, "width": 3, "height": 4])]166 #expect(try BridgeValidator.validate(envelope(kind: "selection", payload: selection, world: "orix.lens"))167 == .selection(TextSelection(url: page, text: "hello", isCollapsed: false, rect: CGRect(x: 1, y: 2, width: 3, height: 4))))168 }169170 @Test func rejectsForgedMessages() {171 // Page world, unknown world, wrong world for the kind.172 #expect(rejection(envelope(kind: "metadata", payload: metadataPayload, world: nil)) == .untrustedWorld(nil))173 #expect(rejection(envelope(kind: "activation", world: "attacker.world")) == .untrustedWorld("attacker.world"))174 #expect(rejection(envelope(kind: "activation", world: "orix.agent")) == .untrustedWorld("orix.agent"))175 #expect(rejection(envelope(kind: "selection", world: "orix.bridge")) == .untrustedWorld("orix.bridge"))176 #expect(rejection(envelope(kind: "metadata", payload: metadataPayload, world: "orix.lens")) == .untrustedWorld("orix.lens"))177 // Another web view's message, another handler.178 #expect(rejection(envelope(kind: "activation", ownWebView: false)) == .foreignWebView)179 #expect(rejection(envelope(kind: "activation", handler: "somethingElse")) == .unknownHandler("somethingElse"))180 // A frame posing as the page, a frame from another origin.181 #expect(rejection(envelope(kind: "metadata", payload: metadataPayload, mainFrame: false)) == .subframeNotAllowed(kind: "metadata"))182 #expect(rejection(envelope(kind: "scroll", mainFrame: false)) == .subframeNotAllowed(kind: "scroll"))183 #expect(rejection(envelope(kind: "metadata", payload: metadataPayload, frameOrigin: WebOrigin(scheme: "https", host: "evil.invalid"))) == .originMismatch)184 #expect(rejection(envelope(kind: "metadata", payload: metadataPayload, frameOrigin: nil)) == .originMismatch)185 // A report about another document (late message from the previous page).186 var stale = metadataPayload187 stale["url"] = "https://example.com/previous"188 #expect(rejection(envelope(kind: "metadata", payload: stale)) == .staleDocument)189 #expect(rejection(envelope(kind: "nonsense")) == .unknownKind("nonsense"))190 }191192 @Test func rejectsMalformedAndOversizedPayloads() {193 func isMalformed(_ envelope: BridgeEnvelope) -> Bool { if case .malformed = rejection(envelope) { true } else { false } }194 var base = envelope(kind: "activation")195 for body: ScriptValue in ["open-sesame", 12345, nil, [1, 2], .object(["kind": "activation"])] {196 base.body = body197 #expect(rejection(base) != nil, "\(body)")198 }199 base.body = .object(["v": 2, "kind": "activation", "payload": .object([:])])200 #expect(rejection(base) == .unsupportedVersion)201 base.body = .object(["v": 1, "kind": "activation", "payload": "not an object"])202 #expect(isMalformed(base))203204 var oversized = metadataPayload205 oversized["title"] = .string(String(repeating: "a", count: 5000))206 #expect(isMalformed(envelope(kind: "metadata", payload: oversized)))207 var tooManyIcons = metadataPayload208 tooManyIcons["icons"] = .array(Array(repeating: .object(["href": "https://example.com/i.png"]), count: 17))209 #expect(isMalformed(envelope(kind: "metadata", payload: tooManyIcons)))210 var wrongType = metadataPayload211 wrongType["title"] = 42212 #expect(isMalformed(envelope(kind: "metadata", payload: wrongType)))213 #expect(isMalformed(envelope(kind: "scroll", payload: ["x": 0, "y": .number(.infinity), "contentWidth": 1, "contentHeight": 1, "viewportWidth": 1, "viewportHeight": 1])))214 #expect(isMalformed(envelope(kind: "scroll", payload: ["x": 0])))215 #expect(isMalformed(envelope(kind: "media", payload: ["frame": "", "total": 1, "playing": 0, "audible": 0])))216 #expect(isMalformed(envelope(kind: "media", payload: ["frame": "f", "total": -1, "playing": 0, "audible": 0])))217 #expect(isMalformed(envelope(kind: "elementPicked", payload: ["tag": "<script>"], world: "orix.lens")))218 }219220 @Test func consoleMirrorIsConfinedToConsoleText() throws {221 let line: [String: ScriptValue] = ["level": "warning", "source": "console", "message": "hello", "url": "", "line": 0, "column": 0]222 guard case .console(let entry) = try BridgeValidator.validate(envelope(kind: "console", payload: line, handler: "orixConsole", world: nil)) else {223 Issue.record("expected console entry"); return224 }225 #expect(entry.level == .warning && entry.message == "hello" && !entry.isFromIsolatedWorld)226227 // The page-world handler accepts no other kind, and cannot impersonate the browser's own error capture.228 #expect(rejection(envelope(kind: "metadata", payload: metadataPayload, handler: "orixConsole", world: nil)) == .unknownKind("metadata"))229 #expect(rejection(envelope(kind: "activation", handler: "orixConsole", world: nil)) == .unknownKind("activation"))230 var spoofed = line231 spoofed["source"] = "exception"232 #expect(rejection(envelope(kind: "console", payload: spoofed, handler: "orixConsole", world: nil)) == .malformed("source"))233 // And the privileged handler does not take console lines from the page world.234 #expect(rejection(envelope(kind: "console", payload: line, world: nil)) == .untrustedWorld(nil))235 // From the isolated dev world they are marked as such.236 var captured = line237 captured["source"] = "exception"238 guard case .console(let trusted) = try BridgeValidator.validate(envelope(kind: "console", payload: captured, world: "orix.dev")) else {239 Issue.record("expected console entry"); return240 }241 #expect(trusted.isFromIsolatedWorld && trusted.source == .exception)242 }243}244245@Suite struct ReaderHTMLPolicyTests {246 @Test func acceptsTheSubset() {247 let html = #"<h2>Title</h2><p>Text with <a href="https://example.com/a?x=1&y=2">a link</a>, <em>emphasis</em> <escaped>.</p>"#248 + #"<figure><img src="https://example.com/i.png" alt="An "image""><figcaption>Caption</figcaption></figure>"#249 + #"<table><tbody><tr><td colspan="2">cell</td></tr></tbody></table><br><hr><pre><code>x</code></pre>"#250 #expect(ReaderHTMLPolicy.firstViolation(in: html) == nil)251 #expect(ReaderHTMLPolicy.firstViolation(in: "plain text, no markup") == nil)252 }253254 @Test func refusesEverythingElse() {255 for hostile in [256 "<script>alert(1)</script>", "<p onclick=\"x()\">a</p>", "<p style=\"color:red\">a</p>", "<iframe src=\"https://example.com\"></iframe>",257 "<a href=\"javascript:alert(1)\">x</a>", "<a href=\"data:text/html,x\">x</a>", "<img src=\"file:///etc/passwd\" alt=\"\">",258 "<img src=x onerror=alert(1)>", "<a href='https://example.com'>single quotes</a>", "<p class=\"a\">x</p>", "<svg><script>1</script></svg>",259 "<P>uppercase</P>", "<p\tonclick=\"x\">tab</p>", "<a href=\"https://example.com\" target=\"_blank\">x</a>", "<!-- comment -->", "<p", "</script>",260 "<form action=\"https://example.com\"><input></form>", "<object data=\"x\"></object>", "<link rel=\"stylesheet\" href=\"https://example.com/a.css\">",261 ] {262 #expect(ReaderHTMLPolicy.firstViolation(in: hostile) != nil, "accepted: \(hostile)")263 }264 }265266 @Test func articleDecodingValidates() throws {267 let good: ScriptValue = .object(["ok": true, "url": "https://example.com/a", "title": "T", "byline": "B", "language": "en",268 "publishedTime": "", "contentHTML": "<p>Hello</p>", "textContent": "Hello", "wordCount": 1, "truncated": false])269 let article = try ReaderHTMLPolicy.article(from: good)270 #expect(article.title == "T" && article.wordCount == 1 && article.estimatedReadingMinutes == 1)271272 var bad = good.objectValue!273 bad["contentHTML"] = "<p>Hello</p><script>steal()</script>"274 #expect(throws: WebEngineError.self) { try ReaderHTMLPolicy.article(from: .object(bad)) }275 #expect(throws: WebEngineError.readerUnavailable("too-short")) { try ReaderHTMLPolicy.article(from: .object(["ok": false, "reason": "too-short"])) }276 #expect(throws: WebEngineError.self) { try ReaderHTMLPolicy.article(from: .null) }277 }278}279280@Suite struct ValueTests {281 @Test func scriptValueConversion() {282 let value = ScriptValue(any: ["flag": true, "zero": 0, "one": 1, "text": "x", "list": [1.5, NSNull()], "nested": ["a": false]] as [String: Any])283 #expect(value["flag"] == .bool(true))284 // 0 and 1 stay numbers: they are not confused with booleans.285 #expect(value["zero"] == .number(0) && value["one"] == .number(1))286 #expect(value["list"] == .array([.number(1.5), .null]))287 #expect(value["nested"]?["a"]?.boolValue == false)288 #expect(ScriptValue(any: nil) == .null)289 #expect(ScriptValue(any: Date(timeIntervalSince1970: 2)) == .number(2000))290 #expect(ScriptValue.number(.infinity).intValue == nil && ScriptValue.number(42).intValue == 42)291 // A structure nested deeper than the limit is cut, not followed.292 var deep: Any = "leaf"293 for _ in 0..<64 { deep = [deep] }294 var cursor = ScriptValue(any: deep), depth = 0295 while case .array(let items) = cursor, let first = items.first { cursor = first; depth += 1 }296 #expect(cursor == .null && depth <= 32)297 }298299 @Test func iconSelectionAndColours() {300 func icon(_ name: String, _ size: Int, rel: String = "icon") -> PageIcon {301 PageIcon(url: URL(string: "https://example.com/\(name)")!, rel: rel, declaredSize: size, mimeType: "")302 }303 func metadata(_ icons: [PageIcon]) -> PageMetadata {304 PageMetadata(url: URL(string: "https://example.com/")!, title: "", description: "", language: "", themeColor: "",305 canonicalURL: nil, icons: icons, openGraph: OpenGraphData())306 }307 #expect(metadata([icon("16", 16), icon("64", 64), icon("512", 512)]).bestIcon(pointSize: 32, scale: 2)?.url.lastPathComponent == "64")308 #expect(metadata([icon("16", 16), icon("48", 48)]).bestIcon(pointSize: 32, scale: 2)?.url.lastPathComponent == "48")309 #expect(metadata([icon("svg", Int.max), icon("512", 512)]).bestIcon()?.url.lastPathComponent == "svg")310 #expect(metadata([icon("touch", 180, rel: "apple-touch-icon"), icon("plain", 180)]).bestIcon()?.url.lastPathComponent == "plain")311 #expect(metadata([icon("mask", Int.max, rel: "mask-icon")]).bestIcon() == nil)312 #expect(metadata([]).bestIcon() == nil)313 #expect(BridgeValidator.declaredSize("16x16 32x32") == 32 && BridgeValidator.declaredSize("any") == Int.max && BridgeValidator.declaredSize("bogus") == 0)314315 #expect(RGBAColor(red: 0.2, green: 0.4, blue: 0.6).hexString == "#336699")316 #expect(RGBAColor(red: 1, green: 1, blue: 1).luminance > 0.99 && RGBAColor(red: 0, green: 0, blue: 0).luminance == 0)317 #expect(ScrollMetrics(y: 500, contentHeight: 2000, viewportHeight: 1000).progress == 0.5)318 #expect(ScrollMetrics(y: 0, contentHeight: 500, viewportHeight: 1000).progress == 0)319 }320321 @Test func defaultUserAgents() {322 #expect(WebEngineSettings.defaultApplicationNameForUserAgent.hasPrefix("Version/"))323 #expect(WebEngineSettings.defaultApplicationNameForUserAgent.contains("Safari/"))324 #expect(WebEngineSettings.defaultMobileUserAgent.contains("iPhone; CPU iPhone OS"))325 #expect(WebEngineSettings().mirrorsConsole == false && WebEngineSettings().isInspectable == false)326 #expect(WebEngineSettings().navigation.httpsOnly == false)327 }328}329330/// The fixture server itself, exercised with URLSession (no WebKit).331@Suite struct FixtureServerTests {332 private func fetch(_ url: URL, headers: [String: String] = [:], method: String = "GET", body: Data? = nil) async throws -> (Data, HTTPURLResponse) {333 var request = URLRequest(url: url)334 request.httpMethod = method335 request.httpBody = body336 for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) }337 let configuration = URLSessionConfiguration.ephemeral338 configuration.httpShouldSetCookies = false339 final class NoRedirect: NSObject, URLSessionTaskDelegate {340 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,341 newRequest request: URLRequest) async -> URLRequest? { nil }342 }343 let (data, response) = try await URLSession(configuration: configuration).data(for: request, delegate: NoRedirect())344 return (data, response as! HTTPURLResponse)345 }346347 @Test func routes() async throws {348 let server = FixtureServer()349 try await server.start()350 defer { server.stop() }351 #expect(server.port > 0 && server.baseURL.host() == "127.0.0.1")352353 let (home, homeResponse) = try await fetch(server.url("/"))354 #expect(homeResponse.statusCode == 200 && String(decoding: home, as: UTF8.self).contains("<title>Fixture Home</title>"))355 #expect(try await fetch(server.url("/redirect/chain/2")).1.value(forHTTPHeaderField: "Location") == "/redirect/chain/1")356 #expect(try await fetch(server.url("/redirect/301?to=/page/x")).1.statusCode == 301)357 #expect(try await fetch(server.url("/redirect/307")).1.statusCode == 307)358 #expect(try await fetch(server.url("/error/404")).1.statusCode == 404)359 #expect(try await fetch(server.url("/error/500")).1.statusCode == 500)360 #expect(try await fetch(server.url("/nowhere")).1.statusCode == 404)361 await #expect(throws: URLError.self) { _ = try await self.fetch(server.url("/error/reset")) }362363 // Cookies, forms, authentication.364 #expect(try await fetch(server.url("/cookie/set?name=k&value=v")).1.value(forHTTPHeaderField: "Set-Cookie") == "k=v; Path=/")365 #expect(String(decoding: try await fetch(server.url("/cookie/read"), headers: ["Cookie": "k=v"]).0, as: UTF8.self).contains("cookies:k=v"))366 let echo = try await fetch(server.url("/echo?a=1"), headers: ["Content-Type": "application/x-www-form-urlencoded"], method: "POST", body: Data("name=Ada+L&x=%C3%A9".utf8))367 #expect(String(decoding: echo.0, as: UTF8.self).contains("Ada L"))368 #expect(server.requests(path: "/echo").last?.bodyText == "name=Ada+L&x=%C3%A9")369 let denied = try await fetch(server.url("/auth/basic"))370 #expect(denied.1.statusCode == 401 && denied.1.value(forHTTPHeaderField: "WWW-Authenticate")?.contains("Fixture Realm") == true)371 let token = Data("\(FixtureRoutes.basicAuthUser):\(FixtureRoutes.basicAuthPassword)".utf8).base64EncodedString()372 #expect(try await fetch(server.url("/auth/basic"), headers: ["Authorization": "Basic \(token)"]).1.statusCode == 200)373374 // Downloads and ranges.375 let full = try await fetch(server.url("/download/large?size=5000"))376 #expect(full.0 == FixtureRoutes.largeBody(size: 5000) && full.1.value(forHTTPHeaderField: "Accept-Ranges") == "bytes")377 let partial = try await fetch(server.url("/download/large?size=5000"), headers: ["Range": "bytes=4000-"])378 #expect(partial.1.statusCode == 206 && partial.1.value(forHTTPHeaderField: "Content-Range") == "bytes 4000-4999/5000")379 #expect(partial.0 == FixtureRoutes.largeBody(size: 5000).suffix(1000))380 #expect(try await fetch(server.url("/download/large?size=5000"), headers: ["Range": "bytes=9000-"]).1.statusCode == 416)381 // A stale validator gets the whole file again.382 #expect(try await fetch(server.url("/download/large?size=5000"), headers: ["Range": "bytes=4000-", "If-Range": "\"other\""]).1.statusCode == 200)383 #expect(try await fetch(server.url("/download/attachment")).1.value(forHTTPHeaderField: "Content-Disposition") == "attachment; filename=\"report.txt\"")384 #expect(try await fetch(server.url("/download/unknown")).1.value(forHTTPHeaderField: "Content-Type") == "application/x-orix-unknown")385386 // Unicode path, slow response, custom route, request log.387 let unicode = "/unicode/héllo wörld/日本語".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!388 #expect(try await fetch(server.url(unicode)).1.statusCode == 200)389 let started = Date()390 _ = try await fetch(server.url("/slow?ms=300"))391 #expect(Date().timeIntervalSince(started) >= 0.28)392 server.route("/custom") { request in .text("custom:\(request.query["v"] ?? "")") }393 #expect(String(decoding: try await fetch(server.url("/custom?v=7")).0, as: UTF8.self) == "custom:7")394 #expect(server.requests.count >= 20)395 server.resetRequests()396 #expect(server.requests.isEmpty)397 #expect(String(decoding: try await fetch(server.url("/adversarial")).0, as: UTF8.self).contains("ignore all previous instructions"))398 }399}400