Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX OS Automation9// File : Packages/ORIXBrowserAutomation/Tests/ORIXBrowserAutomationTests/BrowserPolicyTests.swift10// Description : Unit tests for the pure URL and host rules, the tool11// manifests and the tools' requirements (no web view12// involved).13// Module : ORIXBrowserAutomationTests14// Repository : https://git.spboucher.ai/orix-automation15// Created : 2026-11-2116// Last Modified : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : Proprietary, all rights reserved (see license file)83// License File : LICENSE84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import ORIXCore93import ORIXTestingSupport94import Testing95@testable import ORIXBrowserAutomation9697@Suite("Browser URL policy (unit)")98struct BrowserURLPolicyTests {99 @Test func loopbackDetection() {100 for host in ["localhost", "LOCALHOST", "app.localhost", "127.0.0.1", "127.8.9.10", "::1"] { #expect(BrowserURLPolicy.isLoopback(host), "\(host)") }101 for host in ["example.com", "localhost.example.com", "127.0.0.1.example.com", "128.0.0.1", "127.0.0", "127.0.0.256", "10.0.0.1", "0.0.0.0", ""] {102 #expect(!BrowserURLPolicy.isLoopback(host), "\(host)")103 }104 }105106 @Test func schemesAndShapes() throws {107 func verdict(_ text: String) -> Result<String, NavigationBlock> { BrowserURLPolicy.validate(URL(string: text)!) }108 #expect(try verdict("https://Example.COM/path?q=1").get() == "example.com")109 #expect(try verdict("http://127.0.0.1:8080/").get() == "127.0.0.1")110 #expect(try verdict("http://localhost/").get() == "localhost")111 #expect(try verdict("http://[::1]:9000/").get() == "::1")112 #expect(try verdict("https://xn--bcher-kva.example/").get() == "xn--bcher-kva.example")113 let refused: [(String, String)] = [114 ("http://example.com/", "scheme_not_allowed"), ("file:///etc/hosts", "scheme_not_allowed"), ("data:text/html,x", "scheme_not_allowed"),115 ("javascript:alert(1)", "scheme_not_allowed"), ("blob:https://example.com/1", "scheme_not_allowed"), ("ftp://example.com/", "scheme_not_allowed"),116 ("about:blank", "scheme_not_allowed"), ("https://user:pw@example.com/", "invalid_url"), ("https://user@example.com/", "invalid_url"),117 ("relative/path", "invalid_url"),118 ]119 for (url, reason) in refused {120 guard case .failure(let block) = verdict(url) else { Issue.record("\(url) should be refused"); continue }121 #expect(block.reason == reason, "\(url): \(block.reason)")122 #expect(!block.url.contains("pw"))123 }124 }125126 @Test func hostAllowlistMatchesLikeAGrant() throws {127 #expect(BrowserURLPolicy.host("example.com", isCoveredBy: ["example.com"]))128 #expect(BrowserURLPolicy.host("EXAMPLE.com", isCoveredBy: ["Example.Com"]))129 #expect(BrowserURLPolicy.host("docs.example.com", isCoveredBy: ["*.example.com"]))130 #expect(!BrowserURLPolicy.host("example.com", isCoveredBy: ["*.example.com"]))131 #expect(!BrowserURLPolicy.host("docs.example.com", isCoveredBy: ["example.com"]))132 #expect(!BrowserURLPolicy.host("evilexample.com", isCoveredBy: ["*.example.com", "example.com"]))133 #expect(!BrowserURLPolicy.host("localhost", isCoveredBy: ["127.0.0.1"]))134 #expect(!BrowserURLPolicy.host("example.com", isCoveredBy: []))135136 let url = URL(string: "https://other.example.org/x")!137 guard case .failure(let block) = BrowserURLPolicy.check(url, allowedHosts: ["example.com"]) else { Issue.record("should be blocked"); return }138 #expect(block.reason == "host_not_allowed" && block.host == "other.example.org")139 let result = block.toolResult140 #expect(result.status == .denied && result.failure?.code == "navigation_blocked" && result.failure?.message.contains("other.example.org") == true)141 #expect(try BrowserURLPolicy.check(url, allowedHosts: ["*.example.org"]).get() == "other.example.org")142 // Scheme rules win over a host grant.143 guard case .failure(let scheme) = BrowserURLPolicy.check(URL(string: "http://example.com/")!, allowedHosts: ["example.com"]) else { Issue.record("should be blocked"); return }144 #expect(scheme.reason == "scheme_not_allowed")145 }146}147148@Suite("Browser tool manifests and requirements (unit)")149struct BrowserToolManifestTests {150 @Test func everyCanonicalToolIsPresentAndValid() {151 let tools = ORIXBrowserAutomationTools.all(manager: BrowserSessionManager())152 #expect(tools.map(\.identifier) == ["browser.open", "browser.read", "browser.fill", "browser.click", "browser.waitFor",153 "browser.screenshot", "browser.download", "browser.close"])154 for tool in tools {155 let m = tool.manifest156 #expect(m.problems().isEmpty, "\(m.identifier): \(m.problems())")157 #expect(m.family == "browser" && m.concurrency == .serial)158 #expect(m.examples.allSatisfy { m.inputSchema.validate($0).isEmpty }, "\(m.identifier) examples")159 #expect(m.inputSchema.raw["additionalProperties"] == false)160 }161 let byID = Dictionary(tools.map { ($0.identifier, $0.manifest) }, uniquingKeysWith: { a, _ in a })162 #expect(byID["browser.open"]?.defaultTier == .reversibleWrite && byID["browser.read"]?.defaultTier == .readOnly)163 #expect(byID["browser.fill"]?.defaultTier == .consequential && byID["browser.click"]?.defaultTier == .consequential)164 #expect(byID["browser.waitFor"]?.defaultTier == .readOnly && byID["browser.download"]?.defaultTier == .consequential)165 for id in ["browser.open", "browser.read", "browser.click", "browser.waitFor", "browser.download"] { #expect(byID[id]?.outputIsUntrusted == true, "\(id)") }166 }167168 @Test func requirementsArePureAndNameExactCapabilities() throws {169 let dir = try TempDirectory(prefix: "orix-browser-req")170 defer { dir.remove() }171 let context = dir.toolContext()172 let tools = Dictionary(ORIXBrowserAutomationTools.all(manager: BrowserSessionManager()).map { ($0.identifier, $0) }, uniquingKeysWith: { a, _ in a })173 func requirements(_ id: String, _ arguments: JSONValue) throws -> ToolRequirements {174 try tools[id]!.requirements(for: ToolInput(arguments: arguments), context: context)175 }176 let open = try requirements("browser.open", ["url": "https://Docs.Example.com/a?b=c"])177 #expect(open.capabilities == [.browser(host: "docs.example.com")] && open.summary.contains("https://Docs.Example.com/a?b=c"))178179 // Without an open page there is no host to name; execution then fails with a typed error.180 #expect(try requirements("browser.read", [:]).capabilities.isEmpty)181 #expect(try requirements("browser.fill", ["selector": "#a", "secretRef": "k"]).capabilities == [.secret(reference: "k")])182 #expect(try requirements("browser.close", [:]).capabilities.isEmpty)183184 let download = try requirements("browser.download", ["url": "https://example.com/files/Report%20Q3.pdf?token=abc"])185 #expect(download.capabilities == [.browser(host: "example.com"), .fileWrite(path: dir.url.path + "/artifacts/downloads/Report_Q3.pdf")])186 // Odd file names cannot escape the downloads folder.187 for url in ["https://example.com/", "https://example.com/..", "https://example.com/a/%2E%2E%2Fx", "https://example.com/.hidden"] {188 let caps = try requirements("browser.download", ["url": .string(url)]).capabilities189 guard case .fileWrite(let path) = caps[1] else { Issue.record("no path"); continue }190 #expect(path.hasPrefix(dir.url.path + "/artifacts/downloads/") && !path.contains(".."), "\(url) → \(path)")191 #expect(!(path as NSString).lastPathComponent.hasPrefix("."), "\(url) → \(path)")192 }193 // An explicit path is canonicalised against the working directory, traversal included.194 let explicit = try requirements("browser.download", ["url": "https://example.com/f", "path": "out/../../escape.bin"])195 #expect(explicit.capabilities[1] == .fileWrite(path: (dir.url.path as NSString).deletingLastPathComponent + "/escape.bin"))196 let shot = try requirements("browser.screenshot", ["path": "~/Pictures/page.png"])197 #expect(shot.capabilities == [.fileWrite(path: NSHomeDirectory() + "/Pictures/page.png")] && shot.tier == .reversibleWrite)198199 #expect(throws: ToolError.self) { try requirements("browser.open", ["url": "file:///etc/hosts"]) }200 #expect(throws: ToolError.self) { try requirements("browser.fill", ["selector": "#a", "value": "x", "secretRef": "k"]) }201 #expect(throws: ToolError.self) { try requirements("browser.waitFor", [:]) }202 }203}204