TablePad

Sandboxing untrusted Python in the browser: I tested my Pyodide worker, and three walls had holes

Pyodide in a Web Worker with fetch removed looks like a sandbox. I probed mine in Chromium: fetch came back through the prototype, two storage APIs were never removed, and one run could tamper with the next. Here are the probes, the fixes and the timings.

6 min read

Some data reshaping is awkward in SQL: pivoting, parsing a JSON column into rows, fuzzy-matching names. In TablePad, the database client I build, a canvas step can be Python instead of SQL. The AI agent can write it, or a person can.

Running that code on a server means containers, timeouts and a lot of operations work. Running it in the browser is much simpler: Pyodide is CPython compiled to WebAssembly, and a Web Worker gives it its own thread. Remove the network APIs from the worker and you have a sandbox.

That was the plan. While writing this post I attacked my own worker, and three of its walls had holes. This is what I tested, why each hole exists, the fix, and what the fix costs.

The setup

The worker loads Pyodide, then removes what Python shouldn't touch:

importScripts(PYODIDE_BASE_URL + 'pyodide.js');
const pyodide = await loadPyodide({ indexURL: PYODIDE_BASE_URL });

const blocked = () => { throw new Error('Network access is disabled in canvas Python.'); };
for (const name of ['XMLHttpRequest', 'WebSocket', 'EventSource', 'indexedDB', 'caches',
                    'BroadcastChannel', 'Worker', 'SharedWorker']) {
  try { self[name] = undefined; } catch (_) {}
}
self.fetch = blocked;
self.importScripts = blocked;

Each run gets a fresh globals dictionary. Inputs arrive as JSON, the code must assign result, and the result goes back as JSON. If a run takes more than 10 seconds, the main thread terminates the worker.

Why the network matters more than you'd think. The worker is created from a Blob URL, so it runs with the page's origin. A fetch('/api/…') from inside it is a same-origin request with the user's cookies attached. In a database tool, the page's own API can run write queries. "No network" really means "no access to your own backend".

Who writes the code? An AI agent that has just read rows from your database, which is where prompt injection lives. Or a saved block someone shared with you. Either way, code you didn't read.

The probes

I took the worker source verbatim, served Pyodide 0.28.3 from a local copy, put a fake same-origin endpoint next to it that only answers when the session cookie is present, and ran eight Python snippets in headless Chromium 153:

import js
resp = await js.WorkerGlobalScope.prototype.fetch.call(js.self, 'http://127.0.0.1:8123/api/workspaces')
result = 'RAN: HTTP ' + str(resp.status) + ' ' + (await resp.text())
Probe Result
from js import fetch; await fetch(url) Blocked
js.WorkerGlobalScope.prototype.fetch.call(js.self, url) HTTP 200 from the same-origin API, with the cookie
js.WorkerGlobalScope.prototype.importScripts.call(js.self, url) Loaded and ran a script from the network
js.XMLHttpRequest Removed
js.indexedDB Still there ([object IDBFactory])
js.caches Still there ([object CacheStorage])
Run 1: import json; json.dumps = lambda *a, **k: '"tampered"' Ran
Run 2: result = [{'revenue': 83925.60}] Returned "tampered by an earlier run"

Why each hole exists

1. Assigning to self.fetch doesn't delete fetch. It creates an own property on the global object that shadows the real one. In Chromium the real one is still on WorkerGlobalScope.prototype, and Pyodide's js module can reach any JavaScript object, prototypes included. importScripts works the same way.

2. Some globals are getters you can't assign over. indexedDB and caches are accessor properties with no setter, defined up the prototype chain. In non-strict code, assigning to them does nothing and throws nothing. In strict code it would throw, and the try/catch would have swallowed that too. The loop looked like it worked.

3. A fresh namespace isn't a fresh interpreter. Each run got a new globals dictionary, but import json returns the same module object from sys.modules every time, and the worker serialized results with that module. So one run could patch a standard library function and change the output of every run after it. The same goes for anything in builtins.

The fixes

Lock the names on every object in the chain

Walk the prototype chain from self and redefine each name wherever it's defined, as a non-configurable getter:

const lock = (name, value) => {
  for (let o = self; o; o = Object.getPrototypeOf(o)) {
    if (!Object.prototype.hasOwnProperty.call(o, name)) continue;
    Object.defineProperty(o, name, { get: () => value, set() {}, configurable: false });
  }
  if (!(name in self)) Object.defineProperty(self, name, { get: () => value, configurable: false });
};

for (const name of ['fetch', 'importScripts']) lock(name, blocked);
for (const name of ['XMLHttpRequest', 'WebSocket', 'WebTransport', 'EventSource', 'indexedDB',
                    'caches', 'BroadcastChannel', 'Worker', 'SharedWorker', 'fetchLater']) {
  lock(name, undefined);
}

Do this after Pyodide has loaded, because loading itself needs fetch and importScripts. Re-running the same probes against the locked worker:

Probe Before After
fetch via the prototype HTTP 200 with cookie Network access is disabled in canvas Python.
importScripts via the prototype Loaded a script Network access is disabled in canvas Python.
indexedDB Present Removed
caches Present Removed
Run-to-run tampering Tampered Still tampered

Run-to-run state: pay for a fresh worker, or don't share one

Locking globals doesn't touch Python's module cache. The only clean reset is a new interpreter, so I measured what that costs: the same trivial snippet, three times each, with Pyodide served from the local machine (4 cores, warm HTTP cache):

Run 1 Run 2 Run 3
New worker per run 1,055 ms 993 ms 968 ms
Reused warm worker 2 ms 1 ms 1 ms

About one second per run, and more on a first visit, since the npm package alone is 13 MB. My take:

  • Code the person typed in front of them: reuse the warm worker. They can only tamper with their own results.
  • Code from the model or from a shared block: start a fresh worker. A second is cheap next to a model call that already took several.
  • Either way: don't serialize results with a module user code can reach. Convert with result.toJs() and call JSON.stringify in JavaScript, so at least the output path can't be patched from Python.

Give the worker an origin that can't reach anything

The deepest fix is to make the hole harmless even if a future one appears. Create the worker from a sandboxed iframe (sandbox="allow-scripts", without allow-same-origin). Code there has an opaque origin, so any request it manages to send carries no cookies, and your API's CORS policy rejects the response. Add a Content Security Policy whose connect-src allows only the host Pyodide loads from. That's the layer I'd add next. The prototype lock closes the holes I found, and an opaque origin protects against the ones I haven't found yet.

What a browser sandbox does and doesn't give you

It does:

  • Keep the code off your servers and away from database credentials, which only the backend holds.
  • Stop CPU runaways: worker.terminate() stops WebAssembly mid-loop, so a 10-second timer is a real limit.
  • Isolate one browser tab's worth of damage, if you get the network and the origin right.

It doesn't:

  • Limit memory. A runaway allocation is a crash risk for the worker or the tab.
  • Give you packages without the network. Anything beyond the standard library has to be loaded before you lock down, from a list you choose.
  • Protect anything the page can already see. The worker is a smaller room in the same house.

If the code needs real packages, large data or secrets, use a server-side sandbox. For "reshape these 200 rows the SQL step returned", a locked-down worker is enough, as long as you've actually tried to break out of it.

Checklist

  • Remove globals on every prototype in the chain, not just on self, and use defineProperty with configurable: false.
  • Don't trust try { self.x = undefined } catch {}. Read the property back and check it's gone.
  • Remember that a Blob or same-origin worker shares your origin and cookies.
  • Treat sys.modules and builtins as shared state between runs. Use a fresh worker for code you didn't write.
  • Serialize results outside the interpreter.
  • Add an opaque origin and a CSP as the last line.
  • Write the probes down and run them after every Pyodide or browser upgrade. They take seconds.