Skip to content

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 the KernelBase API 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.ts and worker.ts in packages/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.

ts
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 an input message, then waits with Atomics.wait on a shared buffer where the page writes the answer. time.sleep also uses Atomics.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.

    The server holds each get for 16 seconds, then ends it with 204 (since basthon-api 1.0.0) and the worker sends a new one. Older servers answer 408, which browsers resend themselves without telling the page: Firefox up to 10 times, then fails with a network error after about 3 minutes. The worker reads the API's version (GET /version, missing before 1.0.0) and, with an older server in Firefox, takes a network error on a request held at least 16 seconds for the end of a wait. See "Long polling and HTTP 408" in basthon-api's README: a server must never answer 408 there.

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 an OffscreenCanvas and 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 as ImageBitmap, 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 real AudioContext of 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 a javascript: URL used as a link);
  • iframe size messages are only accepted as numbers.

OpenStreetMap tiles in sandboxed outputs (folium) ​

Rendering outputs with an opaque origin broke folium maps in Chromium based browsers (Chrome, Edge, Brave...), hence a workaround in the frontends that is worth knowing about since it lives outside this repository and looks odd out of context:

  • a folium map is a Leaflet document in an <iframe srcdoc>; its background tiles come from tile.openstreetmap.org by default;
  • OpenStreetMap's tile usage policy requires a Referer header and serves "403 Access blocked" tiles without it;
  • from a sandboxed document without allow-same-origin, Chromium never sends a Referer, whatever the referrer policy is (Firefox sends the embedding page's one).

So the frontends inject a small script (a "shim") at the top of the sandboxed documents: it overrides the src setter of images and, for OpenStreetMap's tiles only, asks the page (postMessage) to fetch them. The page is not sandboxed, so its requests carry a Referer. It only fetches URLs of OpenStreetMap's tile servers, without credentials, and only sends images back.

This is fragile (it relies on Leaflet setting img.src, on one level of iframe, on OpenStreetMap's URLs) and duplicated in each frontend:

  • basthon-notebook: src/js/base/js/tilerelay.js;
  • console-react: src/gui/tile-relay.ts.

Both files explain what was tried before (referrer policies, same-origin static page, blob: URL: none makes Chromium send a Referer). Remove this workaround if outputs are ever rendered from a dedicated origin instead of an opaque one.

Where to look ​

TopicFiles
kernel API and eventspackages/kernel-base/src/kernel.ts
main thread sidepackages/kernel-base/src/worker/kernel-main.ts
worker sidepackages/kernel-base/src/worker/kernel-worker.ts
opaque origin, fetchpackages/kernel-base/src/commons.ts, worker/proxy.ts
encrypted inputspackages/kernel-base/src/worker/fallback-cipher.ts
kernel iframespackages/kernel-base/src/canvas/, packages/gui-base/src/main.ts
platform layerpackages/kernel-base/src/host/
Pyodide snapshotsPyodide snapshots
adding a languageWriting a new kernel