Repository Public License
1# Agent security23How `AgentRuntime` limits what a misled or compromised model can do. Architecture and API: `docs/AGENT.md`.4General threat model: `docs/THREAT_MODEL.md` (its section 5 predates this module).56> **Tested against scripts, not against a model or the web.** No API key was available. In the adversarial tests7> a *scripted* model obeys the injected instruction and the runtime must block the action by itself; a scripted8> fake host plays the browser. Nothing here was attacked by a real model, a real page or a person trying to9> break it. The mitigations are code that exists and tests that pass; that is all that is claimed.1011## Principle1213**The model is not trusted.** The system prompt states the rules, but no defence below depends on the model14following them. Every tool call is treated as hostile input: validated, checked against the user's policy and the15limits, and only then executed. Page content is data; it is delimited and labelled for the model's benefit, but16the enforcement is in the runtime, where page content has no voice.1718What a model that obeys every injected instruction can still do is bounded by: the tools that exist, the19capabilities the user granted, the tabs the user shared, the sites the user allowed, the budget, and what the20user approves in a confirmation.2122## Threats, defences, tests2324Tests are in `Packages/NavigatorKit/Tests/AgentRuntimeTests`. `Adv.` = `AdversarialTests`.2526### 1. Page content gives instructions (prompt injection)2728| Defence | Where | Test |29|---|---|---|30| Tool results are wrapped in `<<<ORIX_DATA nonce tool=…>>> … <<<END_ORIX_DATA nonce>>>` with a 128-bit nonce per run; runtime-written lines are outside the envelope | `DataEnvelope`, `AgentSession.renderMessages` | `SessionLoopTests.readThenFinishProducesACitedAnswer`, `EnvelopeAndSanitizerTests.noncesAreRandomAndLong` |31| Any `<<<`, `>>>`, tag name or the nonce itself inside page text is neutralised, so content cannot close the envelope or forge a "Runtime:" line outside it — even if it guessed the nonce | `DataEnvelope.neutralise` | `EnvelopeAndSanitizerTests.delimitersInContentAreNeutralised`, `Adv.forgedEnvelopesAndRuntimeLinesStayInsideTheData` |32| Text from host errors and echoed model text is neutralised and shortened before it appears in a runtime line | `AgentSession.handle`, `validate` | `SessionLoopTests.hostErrorsGoBackToTheModelAndTheRunContinues` |33| Instruction-like text is flagged (override, role impersonation, tool-call look-alikes, requests for secrets, exfiltration, forged markers; English and French; zero-width characters removed first). The step is annotated for the user, the model gets a runtime warning, and the content is still only data | `InjectionScanner` | `InjectionScannerTests` (27 flagged, 8 ordinary), `Adv.navigatingToTheAttackerDomainIsBlocked` |34| Everything the injection could ask for is blocked by the sections below, with the model obeying | — | all of `AdversarialTests` |3536### 2. Navigation to an attacker's site3738| Defence | Where | Test |39|---|---|---|40| Allow-list on every URL in tool arguments (`navigate`, `create_tab`, `download`, link targets of `click`, form actions): exact host or subdomain, after IDN normalisation (punycode, lowercase, trailing dot) | `DomainPolicy`, `AgentSession.authorise` | `DomainPolicyTests.allowList` (32 cases), `Adv.navigatingToTheAttackerDomainIsBlocked` |41| Strict URL parsing: http(s) only, no credentials, no backslash, whitespace, control or format characters (browser engines and Foundation read those differently) | `AgentURL.parse` | `DomainPolicyTests.strictParsingRefuses` (17 cases) |42| Redirects: the host calls the run's guard before each redirect commits | `AgentSession.redirectGuard` | `Adv.aRedirectToTheAttackerDomainIsStoppedBeforeItCommits` |43| The final address is checked again by the runtime, in case the host let a redirect through | `settled` | `Adv.aHostThatLetsARedirectThroughIsCaughtOnTheFinalAddress`, `Adv.aDownloadThatRedirectsOffTheListIsRefused` |44| The address is re-read before every read or action and again on what was actually read, so a page that moves itself after loading is not returned | `accessiblePage`, `read` | `Adv.aPageThatMovesItselfWhileBeingReadIsNotReturned` |45| Off-list navigation is denied without asking by default; the user may choose "ask", and an approval covers that exact host only | `AgentPermissionPolicy.offDomainNavigation` | `ConfirmationTests.offDomainNavigationIsDeniedByDefaultWithoutAsking`, `…CanBeAskable` |46| The search engine is reachable only with the search capability, and only its exact host | `search` | `SessionLoopTests.searchUsesTheUsersEngineAndOnlyThat` |4748### 3. Reading what was not shared4950| Defence | Where | Test |51|---|---|---|52| The host protocol has no method to list tabs or to read cookies, storage, passwords, the Keychain, history, bookmarks, files or another profile. The runtime cannot ask for what the protocol cannot express | `BrowserAgentHost` | `Adv.theHostProtocolHasNoDoorToPrivateData` (restates a compile-time fact) |53| The model names tabs by integer handle; handles exist only for shared tabs and tabs the agent opened. Any other value is an unknown tab or invalid arguments | `resolveTab` | `Adv.tabsThatWereNotSharedCannotBeReached`, `Adv.withNoSharedTabNothingCanBeRead` |54| A shared tab showing an off-list site is readable only on the host it showed when it was shared | `TabRecord.sharedHosts` | `SessionLoopTests.aSharedTabIsReadableAsItIsWithoutAnyAllowedSite`, `Adv.aHostThatLetsARedirectThroughIsCaughtOnTheFinalAddress` |55| `browser.organize` acts only on those tabs; closing a shared one asks | `organize` | `ConfirmationTests.closingASharedTabAsks`, `Adv.tabsThatWereNotSharedCannotBeReached` |5657### 4. Exfiltration through outgoing requests5859| Defence | Where | Test |60|---|---|---|61| Every part of an outgoing URL the model can fill (query names and values, fragment, path segments, host labels) is compared with a fingerprint of all text the model was given (pages, the goal): 20 or more matching normalised characters need the user's confirmation, which shows the decoded data | `ExfiltrationGuard.evaluate(url:)` | `ExfiltrationGuardTests.urls` (21 cases), `Adv.exfiltratingTheConversationOrPageTextInAUrlIsBlocked`, `Adv.plainTextExfiltrationIsShownToTheUserExactly` |62| base64 / base64url / hex values that decode to such text are refused outright; opaque blobs and parts over 200 characters need confirmation; URLs over 2 000 characters are refused | same | `Adv.encodedExfiltrationIsRefusedEvenIfTheUserWouldApprove` |63| An address offered verbatim by a page or the user is not model-composed and passes; the same address with added data does not | `isKnown` | `ExfiltrationGuardTests.knownAddressWithNewDataIsChecked` |64| A per-host budget (600 characters of model-composed URL parts per run) limits slow leaks | `hostBudget` | `ExfiltrationGuardTests.dripBudgetPerHost` |65| Search queries (60 characters of overlap) and typed text (40) get the same check | `evaluate(outboundText:)` | `ExfiltrationGuardTests.outboundText`, `Adv.plainTextExfiltrationIsShownToTheUserExactly` |66| Form submission always shows every field and value | section 6 | `ConfirmationTests.formSubmissionApprovedShowsDestinationAndExactData` |6768### 5. Secrets reaching the model, the log or the database6970| Defence | Where | Test |71|---|---|---|72| Page text, outlines, extracted values, titles, URLs shown in results, step summaries and the final answer pass through `ResultSanitizer`: `Diagnostics.Redactor`, JSON Web Tokens, and card numbers (13–19 digits passing Luhn) | `ResultSanitizer.redact` | `EnvelopeAndSanitizerTests.secretsAreRedacted`, `Adv.secretsInPageContentAreRedactedEverywhere` (model input, events, stored run) |73| Values of password, card, one-time-code and similar fields are replaced by a fixed mask in outlines and confirmations. The kind reported by the host is cross-checked by the runtime from `type`, `autocomplete`, name and label (EN/FR) | `SecretFieldClassifier` | `SecretFieldAndWallTests.secretFields` (18), `ConfirmationTests.paymentFormsMaskCardData`, `Adv.typingASecretIsAlwaysRefusedAndNeverAsked` |74| Logs carry the status and the step count, never content | `Log.agent` in `end`, `persist` | by inspection |7576### 6. Sensitive actions7778| Defence | Where | Test |79|---|---|---|80| Form submission always needs confirmation: destination origin, every field name and value (secrets masked, hidden fields labelled), the action | `submit` | `ConfirmationTests.formSubmissionApproved…`, `…Denied…`, `clickingASubmitButtonIsAFormSubmission` |81| A form posting outside the allowed sites is refused | `submit` | `Adv.aFormPostingToAnotherSiteIsRefused` |82| Clicks whose label matches the deterministic classifier (purchase, payment, subscription, publishing, sending, account, sign-in, settings, deletion, consent; English and French, case- and accent-insensitive) need confirmation. It errs on the side of asking | `SensitiveActionClassifier` | `SensitiveActionClassifierTests` (56 sensitive, 24 ordinary), `Adv.buyNowIsNotClickedWithoutTheUser` |83| Actions the host flags as irreversible need confirmation | `click`, `submit` | `ConfirmationTests.sensitiveAndIrreversibleClicksAsk` |84| The label is read from a fresh outline at click time (a page cannot show "Next" at inspection and "Delete account" at click) | `click` | `ConfirmationTests.theLabelIsReadFromThePageAtClickTime` |85| Hidden elements are not listed and cannot be clicked; hidden and file fields cannot be typed into | `click`, `type`, `render` | `ConfirmationTests.hiddenAndDownloadElementsAreNotClicked`, `Adv.hiddenLinksAndButtonsAreNotListed` |86| Typing into password, payment-card or one-time-code fields is **always refused** — no confirmation exists that allows it. Text that itself looks like a credential or card number is refused in any field | `type` | `Adv.typingASecretIsAlwaysRefusedAndNeverAsked` |87| Downloads always need confirmation (file, type, size, address); programs, installers and scripts (by extension, MIME type or the host's classifier, after redirects) are refused unless the user enabled them, and then still confirmed | `download` | `ConfirmationTests.downloadsAlwaysAsk`, `Adv.executablesAreNotDownloaded`, `Adv.executablesStillNeedConfirmationWhenTheUserAllowsThem` |88| No confirmation interface → every gated action is refused | `confirm` | `ConfirmationTests.withoutAConfirmationInterfaceEverythingGatedIsRefused` |89| A refusal is told to the model and the run continues | `handle` | `ConfirmationTests.formSubmissionDeniedIsToldToTheModelAndTheRunContinues` |9091### 7. CAPTCHAs and sign-in9293| Defence | Where | Test |94|---|---|---|95| A CAPTCHA or sign-in wall is detected from the host's own signal and from the outline (title, headings, buttons, field labels, link hosts; English and French). The tab is handed to the user once per page; click, type and submit on it are refused while it stands | `WallDetector`, `standingWall` | `SecretFieldAndWallTests.walls` (14), `Adv.captchasAreNeverSolved`, `Adv.aWallMetAfterNavigationIsReported` |96| After the user deals with it, the page is checked again before the agent continues | `standingWall` | `Adv.afterTheUserDealsWithTheWallTheAgentMayContinue` |97| A form with a password or one-time-code field is never submitted by the agent | `submit`, `WallDetector.isAuthenticationForm` | `Adv.typingASecretIsAlwaysRefusedAndNeverAsked` |9899### 8. Hidden text100101| Defence | Where | Test |102|---|---|---|103| Text the host marks as not visible is left out of `browser.read` and `browser.compare` unless the user opts in; the count is reported to the user and the model | `visibleText` | `Adv.hiddenTextIsLeftOutAndReported` |104| Hidden text is still scanned, and instruction-like hidden text is reported as a finding | `injectionNote` | same |105106### 9. Changing the rules107108| Defence | Where | Test |109|---|---|---|110| Limits, policy, domain list, system prompt, envelope and tool list are `let` properties set at construction. There is no tool, argument or code path that writes them | `AgentSession` | `Adv.theBudgetPolicyToolListAndPromptCannotBeChanged` (16 attempts: unknown tools, extra properties, forged names; same budget, prompt and tools on every request) |111| The tool list is a compile-time constant looked up by exact name; every schema is closed (`additionalProperties: false`) and the validator refuses schemas it does not fully understand | `AgentToolCatalog`, `SchemaValidator` | `SchemaValidatorTests` (25 values, 15 unsupported schemas, every tool schema) |112| Each rejected call costs a step; three in a row end the run | `handle` | `SessionLoopTests.repeatedInvalidCallsEndTheRun`, `Adv.aModelCannotTalkItsWayPastTheStepLimit` |113| Each limit is enforced by the runtime | `budgetViolation`, tools | `BudgetTests` (16 tests, one or more per limit) |114| With one step left, only `finish` runs | `handle` | `SessionLoopTests.onlyFinishRunsOnTheLastStep` |115116### 10. False reports and unsupported answers117118| Defence | Where | Test |119|---|---|---|120| Steps of kind `toolCall` are created only when the runtime handles a call. Model text is shown as commentary | `loop`, `handle` | `SessionLoopTests.textOnlyModelNeverProducesActionSteps` |121| Citation ids come from the registry of this run; an id that is not in it is removed, so a source that was not read cannot be cited | `SourceRegistry`, `AnswerVerifier` | `AnswerVerifierTests.citationsToSourcesNotReadAreRemoved`, `Adv.aMisledModelCannotCiteWhatWasNotRead` |122| Claims without a valid citation and quotations not found in a cited source are marked or dropped by the runtime; the model's own revision is re-checked the same way | `AnswerVerifier`, `finish` | `AnswerVerifierTests` (7), `SessionLoopTests.aRevisedAnswerIsAcceptedAndRecheckedDeterministically` |123| Excerpts are limited to the configured length | `SourceRegistry` | `SessionLoopTests.excerptIsLimitedToTheConfiguredLength` |124125### 11. Resource exhaustion126127| Defence | Where | Test |128|---|---|---|129| Every tool result is bounded; long pages are paginated | `ResultSanitizer.bound`, `read` | `SessionLoopTests.everyToolResultIsBounded`, `longPagesArePaginatedUnderOneSource` |130| Screenshots above `maxScreenshotBytes` or of an unexpected type are refused | `screenshot` | `SessionLoopTests.oversizedScreenshotsAreRefused` (size only; the type check has no test) |131| Scanners and the diff cap their input (80 000 characters; 1 500 lines per side) | `InjectionScanner`, `TextDiff` | `TextDiffTests.boundedOnLargeInputs` |132133### 12. Stop and private windows134135| Defence | Where | Test |136|---|---|---|137| Stop ends the run before `stop()` returns: provider stream cancelled, pending host call cancelled, open confirmation or hand-off resolved as cancelled, nothing emitted after `.finished` | `end`, `waitForUser` | `CancellationTests` (7: before start, while streaming, during a tool, during a confirmation, during a hand-off, after completion, event order) |138| The time limit does the same, including while a confirmation is open | watchdog | `BudgetTests.wallClockLimitWhileTheModelIsSilent`, `…WhileWaitingForConfirmation` |139| A run in a private window has no storage sink | `AgentSession.init` | `PersistenceTests.aGhostRunIsNeverWritten`, `ghostRunsNeverReachASinkAtAnyPoint` |140| A run cut short by the app quitting is shown as interrupted and is never resumed (no API exists to resume) | `AgentRunHistory` | `PersistenceTests.anInterruptedRunIsShownAsInterruptedAndNeverResumed` |141| Helpers cannot run without an acknowledgement for the same provider and space | `AssistantHelpers.run` | `AssistantHelpersTests.anAcknowledgementForAnotherProviderOrSpaceSendsNothing`, `consentIsPerProviderAndSpace` |142143## Residual risks144145Stated plainly; none of these is solved.1461471. **Wrong answers from allowed sites.** Malicious or simply wrong content on a site the user allowed can lead148 the model to a wrong answer, with a valid citation. The verifier checks that a source was read and that149 quotations exist in it — not that the source is right or that it supports the sentence.1502. **Actions inside allowed sites.** On a site the user allowed, with the interact capability, an obedient model151 can click any control whose label does not look sensitive, scroll, and type non-secret text. A page can label152 a destructive control "Next". The classifier sees labels, not consequences; only the host's `isIrreversible`153 flag and the user's choice of sites and capabilities stand in the way. Grant `interact` and `submitForms`154 only on sites where a wrong click is cheap.1553. **Typed text is visible to the page.** Scripts on the page can read what the agent types before any156 submission, and send it. The 40-character overlap check and credential check reduce what can leak that way;157 they do not stop short data.1584. **The exfiltration guard is a heuristic.** Not detected: data shorter than 20 normalised characters (a name,159 a code, an e-mail address), paraphrased or translated data, data split into small pieces under the per-host160 budget, data encoded in ways other than base64 and hex (a custom alphabet, compression), data conveyed by the161 *choice* of which allowed URL to visit, and timing. A site on the allow-list that cooperates with the attacker162 can receive such data.1635. **The search engine is a channel.** Queries go to the user's search engine; short copied fragments (under 60164 characters) are not questioned.1656. **Heuristics are incomplete.** The injection scanner, the sensitive-action classifier, the secret-field166 classifier and the wall detector are word lists and patterns in English and French. Other languages, images167 of text, novel phrasing and deliberate evasion are missed. A missed injection changes nothing about168 enforcement; a missed sensitive label or a missed CAPTCHA does (the click is not asked about).1697. **Hidden text depends on the host.** Visibility is computed by the host in the page; a page can use a170 technique the host does not recognise. The runtime trusts those marks. Screenshots show whatever is rendered,171 and text in images is not scanned or redacted at all.1728. **Redaction is pattern-based.** Secrets that do not look like one (a passphrase in a sentence, an account173 number, personal data in general) reach the model. The agent reads what the user shares: sharing a tab with174 private content sends that content to the AI provider.1759. **The host is trusted.** The runtime checks final addresses and passes a redirect guard, but an incorrect176 `BrowserAgentHost` (wrong field kinds, wrong visibility, evaluating scripts in the page world, starting177 downloads on click) defeats several defences. No production host exists yet; its tests must cover the178 contract in AGENT.md.17910. **Cookies travel.** Navigation uses the tab's profile, so requests to allowed sites carry the user's session180 there. An agent allowed on a site where the user is signed in acts as the user on that site, within the181 limits above. Running the agent in a profile without sessions is safer.18211. **Confirmation fatigue.** Erring on the side of asking produces questions for harmless controls ("Continue183 reading", cookie banners). A user who approves by reflex removes the protection.18412. **Budget overshoot and unknown costs.** A response in flight is not cut by the token or cost limit; the cost185 limit is not enforced when no price is known (a warning says so); cost is always an estimate.18613. **Private windows.** Nothing is stored, but everything read is still sent to the provider, and it sits in187 process memory until the session is released.18814. **Stop is cooperative below the runtime.** The run ends at once from the user's point of view, but a host189 call or a network request that ignores cancellation finishes on its own; a form submission or click already190 handed to the page cannot be recalled.19115. **Denial of service by a page.** A page can waste the budget (huge pages, endless pagination, pages that192 always look like a wall). The budget bounds the cost; the task fails.19316. **Model output shown to the user** (`textDelta`, the answer) is model-written and may contain persuasive or194 misleading text influenced by a page. The UI must render it as plain text or sanitised markdown, never as195 HTML, and must not auto-load links or images from it.196197## Not verified198199- No real model, no real provider, no real page, no WebKit: see the note at the top.200- No fuzzing and no review by a second person; the regular expressions were not measured for worst-case time on201 hostile input beyond the size caps.202- The production `BrowserAgentHost` and the confirmation UI do not exist yet; a defence the user never sees, or203 a host that does not honour the contract, protects nobody.204- Unicode confusables in labels and host names beyond IDN normalisation (see THREAT_MODEL.md, homographs) are not205 handled here.206