SPB Git

Repository Public License

AGENT_SECURITY.md 20.5 KB

# Agent security

How AgentRuntime limits what a misled or compromised model can do. Architecture and API: docs/AGENT.md. General threat model: docs/THREAT_MODEL.md (its section 5 predates this module).

Tested against scripts, not against a model or the web. No API key was available. In the adversarial tests a scripted model obeys the injected instruction and the runtime must block the action by itself; a scripted fake host plays the browser. Nothing here was attacked by a real model, a real page or a person trying to break it. The mitigations are code that exists and tests that pass; that is all that is claimed.

# Principle

The model is not trusted. The system prompt states the rules, but no defence below depends on the model following them. Every tool call is treated as hostile input: validated, checked against the user's policy and the limits, and only then executed. Page content is data; it is delimited and labelled for the model's benefit, but the enforcement is in the runtime, where page content has no voice.

What a model that obeys every injected instruction can still do is bounded by: the tools that exist, the capabilities the user granted, the tabs the user shared, the sites the user allowed, the budget, and what the user approves in a confirmation.

# Threats, defences, tests

Tests are in Packages/NavigatorKit/Tests/AgentRuntimeTests. Adv. = AdversarialTests.

# 1. Page content gives instructions (prompt injection)

Defence Where Test
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
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
Text from host errors and echoed model text is neutralised and shortened before it appears in a runtime line AgentSession.handle, validate SessionLoopTests.hostErrorsGoBackToTheModelAndTheRunContinues
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
Everything the injection could ask for is blocked by the sections below, with the model obeying — all of AdversarialTests

# 2. Navigation to an attacker's site

Defence Where Test
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
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)
Redirects: the host calls the run's guard before each redirect commits AgentSession.redirectGuard Adv.aRedirectToTheAttackerDomainIsStoppedBeforeItCommits
The final address is checked again by the runtime, in case the host let a redirect through settled Adv.aHostThatLetsARedirectThroughIsCaughtOnTheFinalAddress, Adv.aDownloadThatRedirectsOffTheListIsRefused
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
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
The search engine is reachable only with the search capability, and only its exact host search SessionLoopTests.searchUsesTheUsersEngineAndOnlyThat

# 3. Reading what was not shared

Defence Where Test
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)
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
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
browser.organize acts only on those tabs; closing a shared one asks organize ConfirmationTests.closingASharedTabAsks, Adv.tabsThatWereNotSharedCannotBeReached

# 4. Exfiltration through outgoing requests

Defence Where Test
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
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
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
A per-host budget (600 characters of model-composed URL parts per run) limits slow leaks hostBudget ExfiltrationGuardTests.dripBudgetPerHost
Search queries (60 characters of overlap) and typed text (40) get the same check evaluate(outboundText:) ExfiltrationGuardTests.outboundText, Adv.plainTextExfiltrationIsShownToTheUserExactly
Form submission always shows every field and value section 6 ConfirmationTests.formSubmissionApprovedShowsDestinationAndExactData

# 5. Secrets reaching the model, the log or the database

Defence Where Test
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)
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
Logs carry the status and the step count, never content Log.agent in end, persist by inspection

# 6. Sensitive actions

Defence Where Test
Form submission always needs confirmation: destination origin, every field name and value (secrets masked, hidden fields labelled), the action submit ConfirmationTests.formSubmissionApproved…, …Denied…, clickingASubmitButtonIsAFormSubmission
A form posting outside the allowed sites is refused submit Adv.aFormPostingToAnotherSiteIsRefused
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
Actions the host flags as irreversible need confirmation click, submit ConfirmationTests.sensitiveAndIrreversibleClicksAsk
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
Hidden elements are not listed and cannot be clicked; hidden and file fields cannot be typed into click, type, render ConfirmationTests.hiddenAndDownloadElementsAreNotClicked, Adv.hiddenLinksAndButtonsAreNotListed
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
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
No confirmation interface → every gated action is refused confirm ConfirmationTests.withoutAConfirmationInterfaceEverythingGatedIsRefused
A refusal is told to the model and the run continues handle ConfirmationTests.formSubmissionDeniedIsToldToTheModelAndTheRunContinues

# 7. CAPTCHAs and sign-in

Defence Where Test
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
After the user deals with it, the page is checked again before the agent continues standingWall Adv.afterTheUserDealsWithTheWallTheAgentMayContinue
A form with a password or one-time-code field is never submitted by the agent submit, WallDetector.isAuthenticationForm Adv.typingASecretIsAlwaysRefusedAndNeverAsked

# 8. Hidden text

Defence Where Test
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
Hidden text is still scanned, and instruction-like hidden text is reported as a finding injectionNote same

# 9. Changing the rules

Defence Where Test
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)
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)
Each rejected call costs a step; three in a row end the run handle SessionLoopTests.repeatedInvalidCallsEndTheRun, Adv.aModelCannotTalkItsWayPastTheStepLimit
Each limit is enforced by the runtime budgetViolation, tools BudgetTests (16 tests, one or more per limit)
With one step left, only finish runs handle SessionLoopTests.onlyFinishRunsOnTheLastStep

# 10. False reports and unsupported answers

Defence Where Test
Steps of kind toolCall are created only when the runtime handles a call. Model text is shown as commentary loop, handle SessionLoopTests.textOnlyModelNeverProducesActionSteps
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
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
Excerpts are limited to the configured length SourceRegistry SessionLoopTests.excerptIsLimitedToTheConfiguredLength

# 11. Resource exhaustion

Defence Where Test
Every tool result is bounded; long pages are paginated ResultSanitizer.bound, read SessionLoopTests.everyToolResultIsBounded, longPagesArePaginatedUnderOneSource
Screenshots above maxScreenshotBytes or of an unexpected type are refused screenshot SessionLoopTests.oversizedScreenshotsAreRefused (size only; the type check has no test)
Scanners and the diff cap their input (80 000 characters; 1 500 lines per side) InjectionScanner, TextDiff TextDiffTests.boundedOnLargeInputs

# 12. Stop and private windows

Defence Where Test
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)
The time limit does the same, including while a confirmation is open watchdog BudgetTests.wallClockLimitWhileTheModelIsSilent, …WhileWaitingForConfirmation
A run in a private window has no storage sink AgentSession.init PersistenceTests.aGhostRunIsNeverWritten, ghostRunsNeverReachASinkAtAnyPoint
A run cut short by the app quitting is shown as interrupted and is never resumed (no API exists to resume) AgentRunHistory PersistenceTests.anInterruptedRunIsShownAsInterruptedAndNeverResumed
Helpers cannot run without an acknowledgement for the same provider and space AssistantHelpers.run AssistantHelpersTests.anAcknowledgementForAnotherProviderOrSpaceSendsNothing, consentIsPerProviderAndSpace

# Residual risks

Stated plainly; none of these is solved.

  1. Wrong answers from allowed sites. Malicious or simply wrong content on a site the user allowed can lead the model to a wrong answer, with a valid citation. The verifier checks that a source was read and that quotations exist in it — not that the source is right or that it supports the sentence.
  2. Actions inside allowed sites. On a site the user allowed, with the interact capability, an obedient model can click any control whose label does not look sensitive, scroll, and type non-secret text. A page can label a destructive control "Next". The classifier sees labels, not consequences; only the host's isIrreversible flag and the user's choice of sites and capabilities stand in the way. Grant interact and submitForms only on sites where a wrong click is cheap.
  3. Typed text is visible to the page. Scripts on the page can read what the agent types before any submission, and send it. The 40-character overlap check and credential check reduce what can leak that way; they do not stop short data.
  4. The exfiltration guard is a heuristic. Not detected: data shorter than 20 normalised characters (a name, a code, an e-mail address), paraphrased or translated data, data split into small pieces under the per-host budget, data encoded in ways other than base64 and hex (a custom alphabet, compression), data conveyed by the choice of which allowed URL to visit, and timing. A site on the allow-list that cooperates with the attacker can receive such data.
  5. The search engine is a channel. Queries go to the user's search engine; short copied fragments (under 60 characters) are not questioned.
  6. Heuristics are incomplete. The injection scanner, the sensitive-action classifier, the secret-field classifier and the wall detector are word lists and patterns in English and French. Other languages, images of text, novel phrasing and deliberate evasion are missed. A missed injection changes nothing about enforcement; a missed sensitive label or a missed CAPTCHA does (the click is not asked about).
  7. Hidden text depends on the host. Visibility is computed by the host in the page; a page can use a technique the host does not recognise. The runtime trusts those marks. Screenshots show whatever is rendered, and text in images is not scanned or redacted at all.
  8. Redaction is pattern-based. Secrets that do not look like one (a passphrase in a sentence, an account number, personal data in general) reach the model. The agent reads what the user shares: sharing a tab with private content sends that content to the AI provider.
  9. The host is trusted. The runtime checks final addresses and passes a redirect guard, but an incorrect BrowserAgentHost (wrong field kinds, wrong visibility, evaluating scripts in the page world, starting downloads on click) defeats several defences. No production host exists yet; its tests must cover the contract in AGENT.md.
  10. Cookies travel. Navigation uses the tab's profile, so requests to allowed sites carry the user's session there. An agent allowed on a site where the user is signed in acts as the user on that site, within the limits above. Running the agent in a profile without sessions is safer.
  11. Confirmation fatigue. Erring on the side of asking produces questions for harmless controls ("Continue reading", cookie banners). A user who approves by reflex removes the protection.
  12. Budget overshoot and unknown costs. A response in flight is not cut by the token or cost limit; the cost limit is not enforced when no price is known (a warning says so); cost is always an estimate.
  13. Private windows. Nothing is stored, but everything read is still sent to the provider, and it sits in process memory until the session is released.
  14. Stop is cooperative below the runtime. The run ends at once from the user's point of view, but a host call or a network request that ignores cancellation finishes on its own; a form submission or click already handed to the page cannot be recalled.
  15. Denial of service by a page. A page can waste the budget (huge pages, endless pagination, pages that always look like a wall). The budget bounds the cost; the task fails.
  16. Model output shown to the user (textDelta, the answer) is model-written and may contain persuasive or misleading text influenced by a page. The UI must render it as plain text or sanitised markdown, never as HTML, and must not auto-load links or images from it.

# Not verified

  • No real model, no real provider, no real page, no WebKit: see the note at the top.
  • No fuzzing and no review by a second person; the regular expressions were not measured for worst-case time on hostile input beyond the size caps.
  • The production BrowserAgentHost and the confirmation UI do not exist yet; a defence the user never sees, or a host that does not honour the contract, protects nobody.
  • Unicode confusables in labels and host names beyond IDN normalisation (see THREAT_MODEL.md, homographs) are not handled here.
Files main
Menu

Theme