How to secure an agent that drives a web browser

Run the agent in a fresh browser context that holds no stored sessions, and check every request against an allowlist of hosts, including each redirect hop and WebSocket connection. In the Playwright run below, the user's own profile exposed a logged-in session to the agent, a fresh context did not, and a per-request allowlist that looked right still let a redirect and a WebSocket reach the attacker until each was handled.

Updated 29 Nov 2026

What this agent can reach

A browser agent opens pages, clicks, types and reads the result. Everything it reaches comes through the browser's profile and its network. If it uses your profile, it inherits every logged-in session and saved login; if it uses a fresh profile, it holds only what you give it. Every page it opens is written by a third party, and a page can carry text aimed at the agent. OWASP's Securing Agentic Applications V2 lists the web-use capability's risks as "Authenticated session reuse; internal-network reach", and its controls as a sandboxed browser, no extensions or operation "directly in the user's browser", URL filtering with allow lists, blocking open redirects and long redirect chains, DNS-based filtering in addition to HTTP-level filtering, and logging every URL accessed.1 This page builds the profile and allowlist parts and tests them.

Threats and controls for this shape

Capabilities: Reads content it does not control; Calls tools, APIs or MCP servers; Holds credentials or sessions; Browses the web or operates a browser or screen; Acts without a person approving each step.

Threats that apply (14)

Repudiation and untraceable actions

OWASP Agentic v1.1: T8

Rogue and misaligned agent behavior

OWASP Agentic v1.1: T7, T13; OWASP Agentic 2026: ASI10; MITRE ATLAS: AML.T0103

Overwhelming the human in the loop

OWASP Agentic v1.1: T10

Controls in order (14)

2. Scoped, short-lived credentials

Why here: An agent acts with some credential: one given for its tools, its host's or the user's when it has none of its own, or the authority it passes on when it talks to other agents. Scoping that credential and giving it a short life caps the damage from every other failure: a hijacked agent can only do what the credential allows, for as long as it lives.

3. Secrets kept out of the model's context

Why here: Anything in the prompt, memory or tool results can be repeated back by the model or read by an attacker who finds a way to ask. Keep secrets where the model cannot see them before anything else is exposed.

4. Egress allowlist

Why here: It removes the exit. An injected instruction that cannot send data anywhere has little to steal for, even when the earlier controls fail.

5. Tool allowlist and argument validation

Why here: After credentials and network are bounded, the next question is which actions the agent may take at all (tool calls, browser actions, code it runs) and with which arguments.

8. Untrusted-content isolation

Why here: The earlier controls limit what a hijacked agent can do; this one reduces how easily it is hijacked and keeps a hijack from spreading.

9. Output handling

Why here: Model output goes into other systems; once inputs and actions are bounded, the last gap is what those systems do with it.

10. Human approval gates

Why here: After the actions are bounded and checked, a person decides on what is left that is irreversible or high-impact.

11. Rate, cost and loop limits

Why here: Limits on volume protect availability and budget and slow an attacker, but they do not stop a single harmful action, so they come after the controls that do.

12. Action logging and reconstruction

Why here: Detection and investigation come after containment. Logs do not stop an attack but make the other controls testable and the incident explainable.

13. Kill switch and rollback

Why here: Response needs logging to know what to undo and controls in place to make stopping safe. It is the last control to build and the first one used in an incident.

The general controls are untrusted content isolation, egress allowlist, scoped, short-lived credentials and human approval gates. The rest of this page covers what is specific to a browser.

Part 1: give the agent a profile with nothing in it

Playwright runs each test "in isolated clean-slate environments called browser contexts", each with "its own local storage, session storage, cookies etc."; contexts are "equivalent to incognito-like profiles".2 launchPersistentContext(userDataDir) is the other model: it "launches browser that uses persistent storage located at userDataDir".3 The test (harness.mjs isolation) logs in to a fake site, bank.test, in the user's profile (a cookie with a 24-hour lifetime and a localStorage token). It then opens a page in four setups and checks three things: whether /account shows the balance, whether the agent, once it has opened bank.test, sees the stored token, and whether the cookie jar holds the session. Each line is ATTACK SUCCEEDED if the agent could see the user's data. The block below is condensed from isolation.log (the per-setup label column is dropped and case C's three identical lines are shown as one); the full output is in the log.

== A. agent uses the user's own profile (launchPersistentContext on the profile dir)
  ATTACK SUCCEEDED  open bank.test/account, see the balance
  ATTACK SUCCEEDED  read the bank localStorage token
  ATTACK SUCCEEDED  cookie jar holds the bank session
== B. agent gets a fresh context (browser.newContext(), nothing stored, discarded at the end)
  blocked  open bank.test/account, see the balance
  blocked  read the bank localStorage token
  blocked  cookie jar holds the bank session
== C. agent has its own persistent profile dir; the agent logs in once, a later run reuses it
  ATTACK SUCCEEDED  (all three)
== D. fresh context after the same login inside a context that was discarded
  blocked  (all three)

One detail from building the test: a session cookie with no expiry was not written to the profile in this Chromium when the browser closed, so the harness uses a 24-hour Max-Age, as a "remember me" login would. A profile that holds only session cookies behaves differently from one that holds persistent logins.

OWASP's computer-use section adds that "sandbox should not accumulate data and sessions", which is C stated as a rule.1

Part 2: allow only the hosts the task needs

The test page lives on the allowed host (http://localhost:18431). It is hostile: the page and the harness make ten attempts to reach evil.test, six from the page's own script and markup (image, iframe, fetch, WebSocket, window.open, service worker) and four driven as the agent would (open a link, follow a redirect, submit a form, open a raw IP), and the same local server logs every request addressed to evil.test or the raw IP. The attacker host is a local server; evil.test resolves to loopback only inside this Chromium. A probe counts as ATTACK SUCCEEDED if the attacker host received any request for it.

ProbeWhat it does
n1The agent itself navigates to the attacker URL (a link the page told it to open)
n2, n3An <img> and a fetch() to the attacker
n4An allowed URL that answers with a 302 redirect to the attacker
n5, n6window.open() and an <iframe> to the attacker
n7A WebSocket to the attacker
n8A service worker registered by the allowed page, which fetches the attacker
n9A form POST to the attacker
n10The attacker by raw IP address, not name

Five configurations ran against it. The table is condensed from allowlist.log (probe names shortened, ATTACK SUCCEEDED shortened to SUCCEEDED); the log has the full text:

probe               off          route        route+redir+ws+sw-block   resolver   route+redir+ws+sw-block+resolver
n1 agent navigates  SUCCEEDED    blocked      blocked                   blocked    blocked
n2 img              SUCCEEDED    blocked      blocked                   blocked    blocked
n3 fetch            SUCCEEDED    blocked      blocked                   blocked    blocked
n4 redirect         SUCCEEDED    SUCCEEDED    blocked                   blocked    blocked
n5 popup            SUCCEEDED    blocked      blocked                   blocked    blocked
n6 iframe           SUCCEEDED    blocked      blocked                   blocked    blocked
n7 websocket        SUCCEEDED    SUCCEEDED    blocked                   blocked    blocked
n8 service worker   SUCCEEDED    blocked      blocked                   blocked    blocked
n9 form             SUCCEEDED    blocked      blocked                   blocked    blocked
n10 ip literal      SUCCEEDED    blocked      blocked                   blocked    blocked
total succeeded     10           2            0                         0          0

route is the allowlist most people write first: a handler on context.route('**/*') that continues a request if its host is allowed and aborts it otherwise. It stops eight of ten probes, and two get through, for reasons the Playwright documentation gives:

The third column adds both fixes, plus serviceWorkers: 'block', which the documentation recommends because browserContext.route() "will not intercept requests intercepted by Service Worker".5 The handler, from harness.mjs, in outline:

const ctx = await browser.newContext({ serviceWorkers: 'block' });
await ctx.route('**/*', async (route) => {
  let url = route.request().url();
  if (!allowed(url)) return route.abort('blockedbyclient');
  for (let hop = 0; hop < 5; hop++) {            // follow redirects ourselves, checking every hop
    const resp = await route.fetch({ url, maxRedirects: 0 });
    const loc = resp.headers()['location'];
    if (resp.status() >= 300 && resp.status() < 400 && loc) {
      url = new URL(loc, url).href;
      if (!allowed(url)) return route.abort('blockedbyclient');
      continue;
    }
    return route.fulfill({ response: resp });
  }
  return route.abort('blockedbyclient');
});
await ctx.routeWebSocket(/.*/, (ws) => allowed(ws.url()) ? ws.connectToServer() : ws.close());

allowed() compares scheme, host and port exactly, and lets data: and other non-network schemes pass. route.fetch() runs in Node, not in the browser, so it does not use the browser's name-resolution settings; the harness sends the test's fake hostnames to 127.0.0.1 with a Host header for that reason, and a real deployment does not need that.

allowlist-ablation.log adds one fix at a time to route, without serviceWorkers: 'block':

                    route+redir   route+ws      route+redir+ws
n4 redirect         blocked       SUCCEEDED     blocked
n7 websocket        SUCCEEDED     blocked       blocked
total succeeded     1             1             0

Each fix closes its own probe and neither closes the other's. In this Chromium and Playwright version, a service worker's own request (n8) was already stopped by route alone, so serviceWorkers: 'block' was not needed to pass n8. Keep it anyway: the documentation recommends it, and it also covers requests a service worker handles on the page's behalf, which this test does not exercise.

resolver is a different layer. Chromium takes --host-resolver-rules, whose rules are MAP <hostname_pattern> <replacement_host> and EXCLUDE <hostname_pattern>.6 The run maps localhost to loopback and sends every other name to ~NOTFOUND, so the browser cannot resolve any other name. In this run it blocked all ten probes alone, including the IP literal. Layered under the handler (last column) it adds a second stop that does not depend on the handler being complete. It acts inside the browser process only, in a run with no proxy configured; it is not a network control.

Which part of this to build

  1. A fresh newContext() per task, closed at the end (Part 1, B and D).
  2. The route handler with per-hop redirect checks, routeWebSocket, and serviceWorkers: 'block'.
  3. A name-resolution rule as a second layer, if the browser can be launched with flags.
  4. A network the browser process cannot leave except through an allowlisting proxy, so that a bug in the handler is not the only thing in the way: egress allowlist. OWASP's guide also lists network segmentation so the browser cannot reach internal systems.1
  5. A log of every URL the context requests, including those the handler blocked (action logging and reconstruction); OWASP lists "Log all URL accesses and HTTP responses".1

Evidence to keep

Where this stops

Files

In /runs/shape-browser-agent/: harness.mjs, and the logs isolation.log, allowlist.log, allowlist-ablation.log. The harness starts Chromium with --disable-features=LocalNetworkAccessChecks, so loopback probes are not blocked for that unrelated reason. Environment: Playwright 1.65.1, Chromium 159.0.8154.6, Node 22.23.5, run 29 Nov 2026. Run with PLAYWRIGHT_DIR=<folder with node_modules/playwright> node harness.mjs isolation|allowlist; the ablation log came from MODES=route+redir,route+ws,route+redir+ws node harness.mjs allowlist.

Sources

  1. OWASP Securing Agentic Applications V2 (v2.0, October 2026), Sections 5.0, 5.4 and 5.5, OWASP GenAI Security Project, https://genai.owasp.org/download/58849/?tmstv=1794197547, read 29 Nov 2026
  2. Isolation, Playwright documentation, https://playwright.dev/docs/browser-contexts, read 29 Nov 2026
  3. BrowserType, Playwright documentation, https://playwright.dev/docs/api/class-browsertype, read 29 Nov 2026
  4. Network, Playwright documentation, https://playwright.dev/docs/network, read 29 Nov 2026
  5. BrowserContext, Playwright documentation, https://playwright.dev/docs/api/class-browsercontext, read 29 Nov 2026
  6. net/base/host_mapping_rules.h, Chromium source, https://chromium.googlesource.com/chromium/src/+/main/net/base/host_mapping_rules.h, read 29 Nov 2026