Architecture and security
Basthon runs untrusted code (students' programs, shared activities) in the page of a platform where users are logged in (Capytale, for instance). Its kernels are therefore designed so that this code can't act on the page or on behalf of the user: it runs isolated, in a worker with an opaque origin, and everything it displays is rendered in sandboxed iframes. This page explains how.
Overview
A kernel has two parts, connected by message channels (comlink for the calls, a MessageChannel for the kernel's messages):
KernelMainBase(packages/kernel-base/src/worker/kernel-main.ts) lives in the page: it implements theKernelBaseAPI used by the frontends, starts the worker and turns the worker's messages into events (eval.output,eval.display,eval.input...).KernelWorkerBase(packages/kernel-base/src/worker/kernel-worker.ts) lives in the worker: it runs the code with the language's runtime and posts messages (outputs, displays, input requests, downloads).- Each language has its own pair:
kernel.tsandworker.tsinpackages/kernel-<language>/src/.
The legacy kernel (Python only, kernel=python3-legacy) runs the worker's code in the main thread, with the same message channels: it has none of the isolation below. It is kept for the features that need the page (e.g. js.document) and for Capytale.
A "host" layer (packages/kernel-base/src/host/) isolates what depends on the platform (browser or Node.js): kernel-node runs the same kernels in Node.js workers for the basthon command.
The opaque origin worker
A worker created from a URL of the site has the site's origin: it could read its cookies-protected resources with fetch, use its storage or call its API with the user's credentials. Basthon's kernel workers are therefore created from a data: URL, which gives them an opaque origin: for the browser, the worker comes from nowhere, it shares nothing with the page's site.
This is done by SandboxedWorker (mockWorker in packages/kernel-base/src/commons.ts), which replaces the global Worker class. A worker created with the sandboxed: true option (see newWorker in each kernel) is started from a small data: script that loads the real worker script with importScripts (allowed for classic scripts from another origin) and keeps webpack's code splitting working.
new Worker(new URL("./comlink-worker.js", import.meta.url), {
sandboxed: true, // removing this line will cause security issues
});Fetching Basthon's files: the proxy worker
With an opaque origin, the worker can't fetch the site's files anymore (they are now cross-origin). The page starts a second worker, with the site's origin, the proxy (ProxyFetch in packages/kernel-base/src/worker/proxy.ts), and gives the kernel worker a port to it. The kernel worker's fetch is replaced (mockFetch in commons.ts):
- requests to the site's origin are sent to the proxy, which only accepts URLs under the assets directory and without credentials, so the worker can load Basthon's files (Python packages, WebAssembly modules...) and nothing else of the site;
- requests to other origins (CDNs, PyPI, user's requests) are made directly, without credentials (
credentials: "omit"); filesystem:/URLs are served from the kernel's virtual filesystem.
Synchronous communication
A program waiting for an input (input() in Python, scanf in C...) must block until the user answers, but a worker blocked in its code can't receive messages. Two mechanisms are used:
SharedArrayBuffer, when the page is cross-origin isolated: the worker sends aninputmessage, then waits withAtomics.waiton a shared buffer where the page writes the answer.time.sleepalso usesAtomics.wait.- Otherwise, Basthon's ephemeral API (
api.basthon.fr, see basthon-api): the page posts the answer to the API under a random key, the worker waits for it with synchronous HTTP requests (long polling). The answers are encrypted with AES-GCM (fallback-cipher.ts) with a 256-bit key drawn at each start of the kernel, which never leaves the browser: the server only relays data it can't read, and an answer can't reach another kernel.
Kernel iframes
Interactive outputs (p5 sketches, matplotlib figures, tkinter windows...) are displayed by kernel iframes: the worker sends an eval.display event with display_type "kernel-iframe", the HTML of a page and a MessagePort. The frontend renders the page in a sandboxed iframe (a data: URL, without allow-same-origin: an opaque origin again) and transfers the port to it, so the iframe and the worker talk directly, without the page:
- Canvases (
packages/kernel-base/src/canvas/): the worker draws on anOffscreenCanvasand sends frames (ImageBitmap); the iframe displays them and sends back serialized mouse, touch and keyboard events (canvas/protocol.ts). OCaml's and JavaScript's canvases use it, p5 extends it. - p5 (
packages/kernel-python3/src/modules/p5/): p5.js runs in the worker on a minimal DOM emulation (dom.ts); the HTML elements of a sketch (buttons, sliders...) are mirrored in the iframe, and their events sent back. - matplotlib (
matplotlib-basthon-backend): matplotlib's WebAgg backend, whose web page runs in the iframe and talks to the figure through the port, as it would through a WebSocket. - tkinter (tkinter-web-backend): a Tk engine written in Python, one iframe per
Tk()window. A dialog makes the program wait for the answer while the iframe can't reach a blocked worker: the iframe sends the answer to the frontend (iframe-message), which relays it to the worker by the synchronous communication above (postIFrameMessage,waitIFrameMessage).
The second port, given by the frontend (gui-port, see handleKernelIFrame in packages/gui-base/src/main.ts), only carries size requests (numbers, checked) and these relayed messages.
Camera and sound
The page's devices are opened by the main thread on the worker's request, never by the worker itself:
- camera (
packages/kernel-base/src/camera/): the frontend asks the user to confirm each request of the code (confirmCamera), on top of the browser's permission granted once for the whole site; frames are sent to the worker asImageBitmap, and the camera is released when the sketch is replaced or the kernel stops; - sound (
packages/kernel-base/src/audio/): the Web Audio API is emulated in the worker and the audio graph mirrored in a realAudioContextof the page.
Outputs and downloads
The page never trusts the worker's messages:
- HTML outputs (MIME bundles) are rendered by the frontends in sandboxed iframes or sanitized (DOMPurify in the console);
- a download request is only accepted with bytes or a
data:URL (a string could be ajavascript:URL used as a link); - iframe size messages are only accepted as numbers.
Where to look
| Topic | Files |
|---|---|
| kernel API and events | packages/kernel-base/src/kernel.ts |
| main thread side | packages/kernel-base/src/worker/kernel-main.ts |
| worker side | packages/kernel-base/src/worker/kernel-worker.ts |
| opaque origin, fetch | packages/kernel-base/src/commons.ts, worker/proxy.ts |
| encrypted inputs | packages/kernel-base/src/worker/fallback-cipher.ts |
| kernel iframes | packages/kernel-base/src/canvas/, packages/gui-base/src/main.ts |
| platform layer | packages/kernel-base/src/host/ |
| Pyodide snapshots | Pyodide snapshots |
| adding a language | Writing a new kernel |