Repository Public License
1import Foundation2import NavigatorCore3import Security4import TestSupport5import Testing6import WebKit7@testable import WebRuntime89extension WebRuntimeTests {10 @Suite struct Security {11 // MARK: Invalid certificates, end to end1213 @Test func invalidCertificateNeverLoadsWithoutExplicitException() async throws {14 try await withHarness { harness in15 let identity = try FixtureTLSIdentity.makeSelfSigned()16 let tls = FixtureServer(tls: identity.tlsOptions())17 try await tls.start()18 defer { tls.stop() }1920 let profile = harness.makeProfile()21 let engine = harness.makeEngine(profile: profile)22 try await harness.load(engine, "/", expectingTitle: "Fixture Home")2324 engine.load(tls.url("/page/secret"))25 try await waitUntil("certificate error surfaced") { engine.certificateError != nil }26 let failure = try #require(engine.certificateError)27 #expect(failure.host == "127.0.0.1" && failure.port == tls.port)28 #expect(failure.reason == .selfSigned)29 #expect(failure.failingURL == tls.url("/page/secret"))30 #expect(!failure.systemMessage.isEmpty && failure.osStatus != 0)31 let certificate = try #require(failure.certificate)32 #expect(certificate.sha256Fingerprint == CertificateSummary(certificate: identity.certificate).sha256Fingerprint)33 #expect(certificate.sha256Fingerprint.count == 64)34 #expect(certificate.isSelfIssued)35 #expect(certificate.commonName == "127.0.0.1")36 let start = try #require(certificate.notValidBefore), end = try #require(certificate.notValidAfter)37 #expect(start < .now && end > .now && end.timeIntervalSince(start) < 3 * 86_400)38 #expect(failure.chain.count == 1)3940 // Nothing was requested over the untrusted connection and the previous page is still there.41 await settle()42 #expect(tls.requests.isEmpty)43 #expect(engine.loadError == nil)44 #expect(await engine.string("return document.title;") == "Fixture Home")45 #expect(engine.url == tls.url("/page/secret"), "the failing address stays in the address bar")46 #expect(engine.profile.certificateExceptions.isEmpty)4748 // Reload does not get around it either.49 engine.reload()50 await settle(milliseconds: 400)51 try await waitUntil("still refused") { engine.certificateError != nil && !engine.isLoading }52 #expect(tls.requests.isEmpty)5354 // Only the explicit user action loads the page — flagged, for this session and this certificate.55 engine.proceedIgnoringCertificateError()56 try await waitUntil("loaded with exception") { engine.title == "Fixture secret" && !engine.isLoading }57 #expect(engine.certificateError == nil)58 #expect(engine.profile.certificateExceptions.map(\.host) == ["127.0.0.1"])59 #expect(engine.profile.certificateExceptions.first?.sha256Fingerprint == certificate.sha256Fingerprint)60 try await waitUntil("trust summary") { engine.serverTrust != nil }61 #expect(engine.serverTrust?.usesUserException == true)62 #expect(engine.serverTrust?.leaf?.sha256Fingerprint == certificate.sha256Fingerprint)63 #expect(tls.requests(path: "/page/secret").count == 1)6465 // The exception is not shared with another profile…66 let other = harness.makeEngine()67 other.load(tls.url("/page/secret"))68 try await waitUntil("other profile refused") { other.certificateError != nil }69 // …it is bound to that certificate (a server presenting another one is refused again)…70 let secondIdentity = try FixtureTLSIdentity.makeSelfSigned()71 let impostor = FixtureServer(tls: secondIdentity.tlsOptions())72 try await impostor.start()73 defer { impostor.stop() }74 var forged = failure75 forged.port = impostor.port76 engine.profile.grantCertificateException(for: forged)77 engine.load(impostor.url("/"))78 try await waitUntil("different certificate refused") { engine.certificateError != nil }79 #expect(impostor.requests.isEmpty)80 // …and it can be revoked.81 engine.profile.revokeAllCertificateExceptions()82 #expect(engine.profile.certificateExceptions.isEmpty)83 }84 }8586 // MARK: Trust decision function8788 @Test func trustEvaluatorRejectsInvalidChainsAndHonoursOnlyMatchingExceptions() throws {89 let identity = try FixtureTLSIdentity.makeSelfSigned(commonName: "fixture.invalid")90 let trust = try #require(CertificateTrustEvaluator.makeTrust(certificates: [identity.certificate], host: "127.0.0.1"))91 let fingerprint = CertificateSummary(certificate: identity.certificate).sha256Fingerprint9293 guard case .reject(let failure) = CertificateTrustEvaluator.decide(trust: trust, host: "127.0.0.1", port: 8443, exceptions: []) else {94 Issue.record("a self-signed certificate must be rejected"); return95 }96 #expect(failure.reason == .selfSigned)97 #expect(failure.certificate?.sha256Fingerprint == fingerprint)98 #expect(failure.host == "127.0.0.1" && failure.port == 8443)99100 // Exceptions for another host, port or certificate do not apply.101 let wrong = [102 CertificateException(host: "other.invalid", port: 8443, sha256Fingerprint: fingerprint, reason: .selfSigned),103 CertificateException(host: "127.0.0.1", port: 9443, sha256Fingerprint: fingerprint, reason: .selfSigned),104 CertificateException(host: "127.0.0.1", port: 8443, sha256Fingerprint: String(repeating: "0", count: 64), reason: .selfSigned),105 ]106 if case .reject = CertificateTrustEvaluator.decide(trust: trust, host: "127.0.0.1", port: 8443, exceptions: wrong) {} else {107 Issue.record("non-matching exceptions must not be honoured")108 }109 let exact = CertificateException(host: "127.0.0.1", port: 8443, sha256Fingerprint: fingerprint, reason: .selfSigned)110 #expect(CertificateTrustEvaluator.decide(trust: trust, host: "127.0.0.1", port: 8443, exceptions: wrong + [exact])111 == .acceptWithUserException(exact))112113 // A certificate that expired is reported as such (0 days of validity: already over).114 let expired = try FixtureTLSIdentity.makeSelfSigned(days: 0)115 let expiredTrust = try #require(CertificateTrustEvaluator.makeTrust(certificates: [expired.certificate], host: "127.0.0.1"))116 Thread.sleep(forTimeInterval: 1.1)117 guard case .reject(let expiredFailure) = CertificateTrustEvaluator.decide(trust: expiredTrust, host: "127.0.0.1", port: 443, exceptions: []) else {118 Issue.record("an expired certificate must be rejected"); return119 }120 #expect([CertificateError.Reason.expired, .selfSigned].contains(expiredFailure.reason))121 #expect(expiredFailure.certificate?.notValidAfter != nil)122 }123124 @Test func statusToReasonMapping() {125 #expect(CertificateTrustEvaluator.reason(forStatus: Int(errSecCertificateExpired), leaf: nil) == .expired)126 #expect(CertificateTrustEvaluator.reason(forStatus: Int(errSecCertificateNotValidYet), leaf: nil) == .notYetValid)127 #expect(CertificateTrustEvaluator.reason(forStatus: Int(errSecHostNameMismatch), leaf: nil) == .hostnameMismatch)128 #expect(CertificateTrustEvaluator.reason(forStatus: Int(errSecCertificateRevoked), leaf: nil) == .revoked)129 #expect(CertificateTrustEvaluator.reason(forStatus: Int(errSecNotTrusted), leaf: nil) == .untrustedIssuer)130 let selfIssued = CertificateSummary(subject: "x", sha256Fingerprint: "AA", isSelfIssued: true)131 #expect(CertificateTrustEvaluator.reason(forStatus: Int(errSecNotTrusted), leaf: selfIssued) == .selfSigned)132 let past = CertificateSummary(subject: "x", notValidAfter: Date(timeIntervalSinceNow: -60), sha256Fingerprint: "AA")133 #expect(CertificateTrustEvaluator.reason(forStatus: -1, leaf: past) == .expired)134 #expect(CertificateTrustEvaluator.reason(forStatus: -1, leaf: nil) == .unknown)135 }136137 // MARK: HTTPS-only138139 @Test func httpsOnlyUpgradesAndStopsAtAnInterstitial() async throws {140 try await withHarness { harness in141 var settings = WebEngineSettings()142 settings.navigation.httpsOnly = true143 settings.navigation.httpsOnlyExemptsLoopback = false144 let engine = harness.makeEngine(settings: settings)145 let http = harness.server.url("/page/plain")146147 // The fixture speaks only http: the https attempt fails and nothing is fetched in clear.148 engine.load(http)149 try await waitUntil("upgrade failure") { engine.httpsUpgradeFailure != nil }150 let failure = try #require(engine.httpsUpgradeFailure)151 #expect(failure.originalURL == http)152 #expect(engine.url == http, "the address the user asked for stays visible")153 #expect(failure.attemptedURL == URL(string: "https://127.0.0.1:\(harness.server.port)/page/plain"))154 #expect(failure.error != nil || failure.certificateError != nil)155 #expect(engine.loadError == nil)156 #expect(harness.server.requests(path: "/page/plain").isEmpty)157158 // The explicit fallback loads over http and is remembered for that host in this session.159 engine.proceedWithInsecureHTTP()160 try await waitUntil("http fallback") { engine.title == "Fixture plain" && !engine.isLoading }161 #expect(engine.httpsUpgradeFailure == nil)162 #expect(engine.profile.httpAllowedHosts == ["127.0.0.1"])163 try await engine.evaluate("document.getElementById('next').click();")164 try await waitUntil("links on the allowed host keep working") { engine.title == "Fixture plain-next" && !engine.isLoading }165166 // A link to another http host is upgraded too (and fails here, for the same reason).167 engine.load(harness.server.url("/page/other", host: "localhost"))168 try await waitUntil("other host upgraded") { engine.httpsUpgradeFailure?.originalURL.host() == "localhost" }169 #expect(harness.server.requests(path: "/page/other").isEmpty)170 }171 }172173 @Test func httpsOnlySucceedsSilentlyWhenTheSiteSpeaksTLS() async throws {174 try await withHarness { harness in175 let identity = try FixtureTLSIdentity.makeSelfSigned()176 let tls = FixtureServer(tls: identity.tlsOptions())177 try await tls.start()178 defer { tls.stop() }179 var settings = WebEngineSettings()180 settings.navigation.httpsOnly = true181 settings.navigation.httpsOnlyExemptsLoopback = false182 let engine = harness.makeEngine(settings: settings)183 // Stand-in for a valid certificate: the session exception for the fixture's self-signed one.184 let leaf = CertificateSummary(certificate: identity.certificate)185 engine.profile.grantCertificateException(for: CertificateError(host: "127.0.0.1", port: tls.port, reason: .selfSigned,186 systemMessage: "", osStatus: 0, certificate: leaf))187 engine.load(URL(string: "http://127.0.0.1:\(tls.port)/page/upgraded")!)188 try await waitUntil("upgraded load") { engine.title == "Fixture upgraded" && !engine.isLoading }189 #expect(engine.url?.scheme == "https")190 #expect(engine.httpsUpgradeFailure == nil)191 #expect(tls.requests(path: "/page/upgraded").count == 1)192 }193 }194195 // MARK: Page-initiated navigations to privileged schemes196197 @Test func pageCannotNavigateTopLevelToPrivilegedSchemes() async throws {198 try await withHarness { harness in199 let engine = harness.makeEngine()200 for (target, reason) in [("orix", NavigationBlockReason.internalPageFromWeb), ("file", .localFileFromWeb), ("data", .opaqueTopLevelDocument)] {201 let page = harness.server.url("/adversarial?nav=\(target)")202 engine.load(page)203 try await waitUntil("adversarial \(target) ran") { engine.title == "adversarial-done" && !engine.isLoading }204 await settle(milliseconds: 500)205 #expect(engine.webView?.url == page, "\(target): the page must not have navigated")206 #expect(await engine.string("return document.title;") == "adversarial-done")207 // WebKit refuses some of these before asking the app; when it does ask, the policy says no.208 let asked = engine.blockedNavigations.filter { $0.isMainFrame && $0.url.scheme == target }209 #expect(asked.allSatisfy { $0.reason == reason }, "\(target): \(asked)")210 }211 #expect(engine.blockedNavigations.contains { $0.isMainFrame && $0.reason == .internalPageFromWeb })212213 // javascript: is never a navigation the browser performs.214 let page = harness.server.url("/adversarial?nav=javascript")215 engine.load(page)216 try await waitUntil("adversarial javascript ran") { engine.title == "adversarial-done" && !engine.isLoading }217 await settle(milliseconds: 500)218 #expect(engine.webView?.url == page)219 }220 }221 }222223 @Suite struct InternalPages {224 @MainActor final class Provider: InternalContentProvider {225 var requested: [URL] = []226 func internalResource(for url: URL, profile: Profile) async -> InternalResource? {227 requested.append(url)228 switch (url.host(), url.path) {229 case ("start", "/"):230 return .html("""231 <!doctype html><title>Internal Start</title><link rel="stylesheet" href="orix://start/style.css">232 <a id="next" href="orix://start/second">second</a><img id="logo" src="orix://start/logo.png">233 <script src="orix://start/app.js"></script>234 <script>document.documentElement.dataset.inline = "ran";</script>235 """)236 case ("start", "/second"): return .html("<!doctype html><title>Internal Second</title>")237 case ("start", "/style.css"): return InternalResource(data: Data("body { color: rgb(7, 8, 9); }".utf8), mimeType: "text/css")238 case ("start", "/app.js"): return InternalResource(data: Data("document.documentElement.dataset.app = 'ran';".utf8), mimeType: "text/javascript")239 case ("start", "/logo.png"): return InternalResource(data: Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==")!, mimeType: "image/png", textEncodingName: nil)240 default: return nil241 }242 }243 }244245 @Test func internalPagesAreServedToTheAppOnly() async throws {246 try await withHarness { harness in247 let profile = harness.makeProfile()248 let provider = Provider()249 harness.context(profile).internalContentProvider = provider250 let engine = harness.makeEngine(profile: profile)251252 // Built-in new-tab document when the app supplies none.253 #expect(engine.loadInternal(InternalPage.newTab) == nil)254 try await waitUntil("new tab committed") { engine.webView?.url == InternalPage.newTab && !engine.isLoading }255 #expect(engine.loadError == nil)256 // Internal pages are not history.257 #expect(await harness.history.visits.isEmpty)258259 // App-provided page with its own sub-resources.260 let start = try #require(InternalPage.url(host: "start"))261 engine.loadInternal(start)262 try await waitUntil("internal start") { engine.title == "Internal Start" && !engine.isLoading }263 #expect(await engine.string("return getComputedStyle(document.body).color;") == "rgb(7, 8, 9)")264 #expect(await engine.string("return document.documentElement.dataset.app || 'missing';") == "ran")265 #expect(await engine.string("return String(document.getElementById('logo').naturalWidth);") == "1")266 // The default policy of internal pages forbids inline script.267 #expect(await engine.string("return document.documentElement.dataset.inline || 'blocked';") == "blocked")268 // Internal → internal links work; unknown internal addresses fail cleanly.269 try await engine.evaluate("document.getElementById('next').click();")270 try await waitUntil("internal link") { engine.title == "Internal Second" && !engine.isLoading }271 engine.loadInternal(try #require(InternalPage.url(host: "nowhere")))272 try await waitUntil("unknown internal page") { engine.loadError != nil }273 #expect(!engine.loadInternal(harness.server.url("/")).isNil, "loadInternal only takes orix:// URLs")274275 // From a web page: neither navigation, nor frame, nor sub-resource reaches the provider.276 provider.requested.removeAll()277 try await harness.load(engine, "/adversarial?nav=orix", expectingTitle: "adversarial-done")278 await settle(milliseconds: 600)279 #expect(provider.requested.isEmpty, "\(provider.requested)")280 #expect(engine.webView?.url == harness.server.url("/adversarial?nav=orix"))281 // Going back to the internal page the user came from is still possible.282 engine.go(toOffset: -1)283 try await waitUntil("back to internal") { engine.webView?.url?.scheme == "orix" && !engine.isLoading }284 }285 }286 }287288 @Suite struct ContentRules {289 static let blockTracker = """290 [{"trigger": {"url-filter": ".*/resource/tracker\\\\.js"}, "action": {"type": "block"}}]291 """292293 @Test func compiledRuleListBlocksAFixtureResource() async throws {294 try await withHarness { harness in295 let directory = try TemporaryDirectory(prefix: "orix-rules")296 defer { directory.remove() }297 let compiler = try ContentRuleListCompiler(directory: directory.url)298 let profile = harness.makeProfile()299 let context = harness.context(profile)300 let engine = harness.makeEngine(profile: profile)301302 try await harness.load(engine, "/page/with-resources", expectingTitle: "tracker-loaded")303 #expect(harness.server.requests(path: "/resource/tracker.js").count == 1)304305 let list = try await compiler.compile(identifier: "fixture.block-tracker", json: Self.blockTracker)306 #expect(list.identifier == "fixture.block-tracker")307 #expect(await compiler.availableIdentifiers() == ["fixture.block-tracker"])308 #expect(await compiler.lookUp(identifier: "fixture.block-tracker") != nil)309310 // Attached to the profile: live tabs and new tabs both get it.311 context.attach(list)312 #expect(context.attachedRuleListIdentifiers == ["fixture.block-tracker"])313 try await harness.load(engine, "/page/with-resources", expectingTitle: "tracker-missing")314 #expect(harness.server.requests(path: "/resource/tracker.js").count == 1, "the request never left the browser")315 #expect(harness.server.requests(path: "/resource/pixel.png").count >= 2, "unrelated resources still load")316 let second = harness.makeEngine(profile: profile)317 try await harness.load(second, "/page/with-resources", expectingTitle: "tracker-missing")318319 // Per-tab switch ("shields down").320 second.setContentBlockingEnabled(false)321 try await harness.load(second, "/page/with-resources", expectingTitle: "tracker-loaded")322 second.setContentBlockingEnabled(true)323 try await harness.load(second, "/page/with-resources", expectingTitle: "tracker-missing")324 // Another profile is not affected.325 let other = harness.makeEngine()326 try await harness.load(other, "/page/with-resources", expectingTitle: "tracker-loaded")327328 context.detach(identifier: "fixture.block-tracker")329 #expect(context.attachedRuleListIdentifiers.isEmpty)330 try await harness.load(engine, "/page/with-resources", expectingTitle: "tracker-loaded")331332 try await compiler.remove(identifier: "fixture.block-tracker")333 #expect(await compiler.availableIdentifiers().isEmpty)334 #expect(await compiler.lookUp(identifier: "fixture.block-tracker") == nil)335 }336 }337338 @Test @MainActor func compileErrorsAreReported() async throws {339 let directory = try TemporaryDirectory(prefix: "orix-rules")340 defer { directory.remove() }341 let compiler = try ContentRuleListCompiler(directory: directory.url)342 for (name, json) in [("not-json", "this is not json"), ("no-trigger", #"[{"action": {"type": "block"}}]"#),343 ("bad-action", #"[{"trigger": {"url-filter": ".*"}, "action": {"type": "explode"}}]"#),344 ("bad-regex", #"[{"trigger": {"url-filter": "(unclosed"}, "action": {"type": "block"}}]"#)] {345 do {346 _ = try await compiler.compile(identifier: name, json: json)347 Issue.record("\(name) compiled")348 } catch {349 guard case .compileFailed(let identifier, let message) = error else { Issue.record("unexpected \(error)"); continue }350 #expect(identifier == name && !message.isEmpty)351 }352 }353 #expect(await compiler.availableIdentifiers().isEmpty)354 }355 }356}357358private extension Optional {359 var isNil: Bool { self == nil }360}361