SPB Git

Repository Public License

ConfirmationTests.swift 13.9 KB 224 lines swift

1import Foundation2import NavigatorCore3import ProviderKit4import Testing5@testable import AgentRuntime67@Suite struct ConfirmationTests {8    static let shopPage = FakePage(9        title: "Shop",10        segments: [AgentTextSegment("The blue ceramic teapot costs 49 dollars and ships within two days.")],11        links: [12            AgentElement(ref: "more", role: .link, text: "Read more", href: url("https://example.com/more")),13            AgentElement(ref: "away", role: .link, text: "Partner site", href: url("https://other.example.net/page")),14            AgentElement(ref: "file", role: .link, text: "Manual (PDF)", href: url("https://example.com/manual.pdf"), isDownload: true),15            AgentElement(ref: "ghost", role: .link, text: "Next", href: url("https://example.com/next"), isHidden: true),16        ],17        buttons: [18            AgentElement(ref: "buy", role: .button, text: "Buy now"),19            AgentElement(ref: "wipe", role: .button, text: "Tidy up", isIrreversible: true),20            AgentElement(ref: "send", role: .submit, text: "Send message", formRef: "contact"),21            AgentElement(ref: "pay", role: .submit, text: "Continue", formRef: "card"),22        ],23        forms: [24            AgentForm(ref: "contact", action: url("https://example.com/contact"), method: "POST", fields: [25                AgentFormField(ref: "name", name: "name", label: "Your name", value: "Ada"),26                AgentFormField(ref: "msg", name: "message", label: "Message", kind: .textArea, value: "Hello, is the teapot in stock?"),27                AgentFormField(ref: "csrf", name: "csrf", kind: .hidden, htmlType: "hidden", value: "tok-77", isHidden: true),28                AgentFormField(ref: "key", name: "api_token", label: "Token", value: "sk-abcdefghijklmnop1234"),29            ], submitLabel: "Send message"),30            AgentForm(ref: "card", action: url("https://example.com/pay"), method: "POST", fields: [31                AgentFormField(ref: "cc", name: "card", label: "Card number", kind: .creditCardNumber, autocomplete: "cc-number", value: "4111111111111111"),32                AgentFormField(ref: "cvc", name: "cvc", label: "CVC", kind: .creditCardSecurityCode, value: "123"),33                AgentFormField(ref: "amount", name: "amount", label: "Amount", kind: .number, value: "49"),34            ], submitLabel: "Continue"),35            AgentForm(ref: "leak", action: url("https://attacker.invalid/steal"), method: "POST", fields: [AgentFormField(ref: "q", name: "q", value: "x")], submitLabel: "Go"),36        ])3738    static func shop(_ script: [Turn], delegate: ScriptedDelegate?, policy: ((inout AgentPermissionPolicy) -> Void)? = nil) async -> Harness {39        let host = FakeHost()40        await host.setPage(Harness.start, shopPage)41        await host.setPage("https://example.com/more", .text("More about teapots."))42        return await Harness.make(script + [.finish("Nothing to report.")], delegate: delegate, limits: { $0.maxAnswerRevisions = 0 }, policy: policy, host: host)43    }4445    @Test func formSubmissionApprovedShowsDestinationAndExactData() async throws {46        let delegate = ScriptedDelegate(.approve)47        let h = await Self.shop([.tools([call(.submitForm, ["ref": "contact"])])], delegate: delegate)48        let (result, events) = await h.run()49        #expect(result.run.status == .completed)50        #expect(await h.host.called("submitForm contact"))51        let request = try #require(delegate.requests.first)52        #expect(delegate.requests.count == 1)53        #expect(request.kind == .sensitiveAction(.sendingMessage))54        #expect(request.tool == "browser.submit_form")55        #expect(request.destination == "https://example.com")56        #expect(request.url == url("https://example.com/contact"))57        #expect(request.risk == .high)58        #expect(request.runID == h.session.id)59        #expect(request.data.map(\.name) == ["name", "message", "csrf (hidden field)", "api_token"])60        #expect(request.data[0].value == "Ada" && request.data[1].value == "Hello, is the teapot in stock?" && request.data[2].value == "tok-77")61        #expect(!request.data[3].value.contains("sk-abcdefghijklmnop1234"))                   // secrets are masked, even in ordinary fields62        #expect(events.confirmations == [request])63        #expect(events.contains(.confirmationResolved(id: request.id, decision: .approved)))64        let step = try #require(events.steps.first { $0.kind == .confirmation })65        #expect(step.status == .done && step.summary.hasPrefix("Approved by you"))66        #expect(step.detail?.contains("sk-abcdefghijklmnop1234") == false)67    }6869    @Test func formSubmissionDeniedIsToldToTheModelAndTheRunContinues() async {70        let delegate = ScriptedDelegate(.deny)71        let h = await Self.shop([.tools([call(.submitForm, ["ref": "contact"])]), .tools([call(.read)])], delegate: delegate)72        let (result, events) = await h.run()73        #expect(result.run.status == .completed)74        #expect(await !h.host.called("submitForm"))75        #expect(await h.host.called("readText"))                                             // it went on with other work76        #expect(events.toolSteps.map(\.status) == [.denied, .done, .done])77        #expect(h.provider.requests[1].messages.last?.text.contains("the user refused the form submission") == true)78        #expect(events.contains(.confirmationResolved(id: 1, decision: .denied)))79        #expect(events.steps.first { $0.kind == .confirmation }?.status == .denied)80    }8182    @Test func withoutAConfirmationInterfaceEverythingGatedIsRefused() async {83        let h = await Self.shop([.tools([call(.submitForm, ["ref": "contact"]), call(.click, ["ref": "buy"]), call(.click, ["ref": "wipe"]),84                                         call(.download, ["url": "https://example.com/manual.pdf"]), call(.organize, ["action": "close", "tabs": [1]])])], delegate: nil)85        let (result, events) = await h.run()86        #expect(result.run.status == .completed)87        let calls = await h.host.calls88        #expect(!calls.contains { $0.hasPrefix("submitForm") || $0.hasPrefix("click") || $0.hasPrefix("download ") || $0.hasPrefix("close") })89        #expect(events.toolSteps.prefix(5).allSatisfy { $0.status == .denied })90        #expect(events.confirmations.isEmpty)91        #expect(events.steps.filter { $0.kind == .confirmation }.count == 5)92        #expect(events.steps.filter { $0.kind == .confirmation }.allSatisfy { $0.status == .denied && $0.summary.contains("no confirmation interface") })93    }9495    @Test func clickingASubmitButtonIsAFormSubmission() async throws {96        let delegate = ScriptedDelegate(.deny)97        let h = await Self.shop([.tools([call(.click, ["ref": "send"])])], delegate: delegate)98        _ = await h.run()99        #expect(delegate.requests.first?.tool == "browser.submit_form")100        #expect(delegate.requests.first?.data.count == 4)101        #expect(await !h.host.called("click"))102        #expect(await !h.host.called("submitForm"))103        // Without the capability the same click is refused before any question is asked.104        let limited = ScriptedDelegate(.approve)105        let host = FakeHost()106        await host.setPage(Harness.start, Self.shopPage)107        let g = await Harness.make([.tools([call(.click, ["ref": "send"])]), .finish("x")], capabilities: [.interact, .inspect], delegate: limited, host: host)108        _ = await g.run()109        #expect(limited.requests.isEmpty)110        #expect(await !host.called("submitForm"))111    }112113    @Test func paymentFormsMaskCardData() async throws {114        let delegate = ScriptedDelegate(.deny)115        let h = await Self.shop([.tools([call(.click, ["ref": "pay"])])], delegate: delegate)116        let (_, events) = await h.run()117        let request = try #require(delegate.requests.first)118        #expect(request.kind == .sensitiveAction(.payment))119        #expect(request.data.first { $0.name == "card" }?.value == "••••••")120        #expect(request.data.first { $0.name == "card" }?.isMasked == true)121        #expect(request.data.first { $0.name == "cvc" }?.isMasked == true)122        #expect(request.data.first { $0.name == "amount" }?.value == "49")123        #expect(!String(describing: events).contains("4111111111111111"))124        #expect(!h.provider.requests.map { String(describing: $0.messages) }.joined().contains("4111111111111111"))125    }126127    @Test func sensitiveAndIrreversibleClicksAsk() async throws {128        let delegate = ScriptedDelegate(.approve)129        let h = await Self.shop([.tools([call(.click, ["ref": "buy"]), call(.click, ["ref": "wipe"]), call(.click, ["ref": "more"])])], delegate: delegate)130        _ = await h.run()131        #expect(delegate.requests.map(\.kind) == [.sensitiveAction(.purchase), .irreversibleAction])132        #expect(delegate.requests[0].action == "Click “Buy now”")133        #expect(delegate.requests[0].destination == "https://example.com")134        #expect(delegate.requests[0].data.first?.value == "Buy now")135        let calls = await h.host.calls136        #expect(calls.contains("click buy") && calls.contains("click wipe") && calls.contains("click more"))   // "Read more" needed no question137    }138139    @Test func hiddenAndDownloadElementsAreNotClicked() async {140        let delegate = ScriptedDelegate(.approve)141        let h = await Self.shop([.tools([call(.click, ["ref": "ghost"]), call(.click, ["ref": "file"]), call(.click, ["ref": "nope"])])], delegate: delegate)142        let (_, events) = await h.run()143        #expect(await !h.host.called("click"))144        #expect(delegate.requests.isEmpty)145        #expect(events.toolSteps.prefix(3).map(\.status) == [.denied, .denied, .failed])146    }147148    @Test func theLabelIsReadFromThePageAtClickTime() async throws {149        // The page showed "Next" when inspected and "Delete account" when clicked.150        let delegate = ScriptedDelegate(.deny)151        let host = FakeHost()152        let benign = FakePage(title: "Shop", buttons: [AgentElement(ref: "b1", role: .button, text: "Next")])153        let swapped = FakePage(title: "Shop", buttons: [AgentElement(ref: "b1", role: .button, text: "Delete account")])154        await host.setPage(Harness.start, swapped)155        await host.setOutlineQueue([benign])156        let h = await Harness.make([.tools([call(.inspect)]), .tools([call(.click, ["ref": "b1"])]), .finish("x")], delegate: delegate, host: host)157        _ = await h.run()158        #expect(h.provider.requests[1].messages.last?.text.contains("b1 | Next") == true)159        #expect(delegate.requests.first?.kind == .sensitiveAction(.deletion))160        #expect(await !host.called("click"))161    }162163    @Test func downloadsAlwaysAsk() async throws {164        let approve = ScriptedDelegate(.approve)165        let h = await Self.shop([.tools([call(.download, ["url": "https://example.com/manual.pdf"])])], delegate: approve)166        _ = await h.run()167        let request = try #require(approve.requests.first)168        #expect(request.kind == .download && request.destination == "https://example.com")169        #expect(request.data.map(\.name) == ["file", "type", "size", "address"])170        #expect(request.data[0].value == "manual.pdf" && request.data[2].value == "100 bytes")171        #expect(await h.host.called("download https://example.com/manual.pdf"))172173        let deny = ScriptedDelegate(.deny)174        let g = await Self.shop([.tools([call(.download, ["url": "https://example.com/manual.pdf"])])], delegate: deny)175        _ = await g.run()176        #expect(deny.requests.count == 1)177        #expect(await !g.host.called("download "))178    }179180    @Test func offDomainNavigationIsDeniedByDefaultWithoutAsking() async {181        let delegate = ScriptedDelegate(.approve)182        let h = await Self.shop([.tools([call(.navigate, ["url": "https://other.example.net/page"]), call(.click, ["ref": "away"]),183                                         call(.createTab, ["url": "https://other.example.net/"])])], delegate: delegate)184        let (_, events) = await h.run()185        #expect(delegate.requests.isEmpty)186        let calls = await h.host.calls187        #expect(!calls.contains { $0.hasPrefix("navigate") || $0.hasPrefix("click") || $0.hasPrefix("createTab") })188        #expect(events.toolSteps.prefix(3).allSatisfy { $0.status == .denied })189    }190191    @Test func offDomainNavigationCanBeAskable() async throws {192        let approve = ScriptedDelegate(.approve)193        let h = await Self.shop([.tools([call(.navigate, ["url": "https://other.example.net/page"]), call(.navigate, ["url": "https://other.example.net/second"]),194                                         call(.navigate, ["url": "https://sub.other.example.net/"])])], delegate: approve, policy: { $0.offDomainNavigation = .ask })195        _ = await h.run()196        #expect(approve.requests.map(\.kind) == [.navigationOutsideAllowedDomains, .navigationOutsideAllowedDomains])   // the exact host once, the subdomain again197        #expect(approve.requests[0].destination == "https://other.example.net")198        #expect(await h.host.calls.filter { $0.hasPrefix("navigate") }.count == 3)199200        let deny = ScriptedDelegate(.deny)201        let g = await Self.shop([.tools([call(.navigate, ["url": "https://other.example.net/page"])])], delegate: deny, policy: { $0.offDomainNavigation = .ask })202        _ = await g.run()203        #expect(deny.requests.count == 1)204        #expect(await !g.host.called("navigate"))205    }206207    @Test func closingASharedTabAsks() async {208        let delegate = ScriptedDelegate(.deny)209        let h = await Self.shop([.tools([call(.createTab), call(.organize, ["action": "close", "tabs": [1, 2]])])], delegate: delegate)210        _ = await h.run()211        #expect(delegate.requests.map(\.kind) == [.closeSharedTab])212        #expect(await !h.host.called("close"))213    }214215    @Test func aDelegateAnsweringCancelledIsTreatedAsARefusal() async {216        let delegate = ScriptedDelegate(.decide { _ in .cancelled })217        let h = await Self.shop([.tools([call(.click, ["ref": "buy"])])], delegate: delegate)218        let (result, events) = await h.run()219        #expect(result.run.status == .completed)220        #expect(await !h.host.called("click"))221        #expect(events.contains(.confirmationResolved(id: 1, decision: .denied)))222    }223}224
Files main
Menu

Theme