Files
strata/serve/test_web_preview.py
Niko1221andThomas Ivesdal-Tronstad 0aa64b2de3 Web chat: preview a generated svg or html block in a sandboxed frame (#1628)
A complete ```svg or ```html block in an answer gets a Preview button. The
block's own code is drawn in an iframe (srcdoc) that is cut off from the page:
sandbox="" (an opaque origin: no access to the page's DOM, storage, cookies or
server, no scripts, forms, popups, downloads or navigation of the page), a CSP
in the frame's document (default-src 'none': no network, fonts, frames or media;
styles inline, pictures as data: only; no <base>, no form target), no referrer
and no permissions. A well-formed svg is shown as an <img> with a data: URL: an
image runs no script, loads nothing and animates in every browser. The frame
takes the page's light or dark colours and is built again when the theme
changes. A page (html) can also be run WITH scripts, one block at a time, after
a warning that is shown every time: sandbox="allow-scripts" only (still an
opaque origin), the CSP allows the block's inline script and no address; closing
the preview ends it.

What the sandbox flags alone do not stop is a link or <meta refresh> inside the
model's html loading a web page into the frame. The browser test shows it does
(tools/webtest/browser_test.mjs, with and without the header). So the page is
served with Content-Security-Policy: frame-src 'none' (nothing else: a srcdoc
frame inherits the page's policy, and the script preview needs its inline
script), and a <meta http-equiv=refresh> in a previewed page is dropped.

tools/webtest holds the mock server (the page's own files, scripted answers,
no model) and the browser tests; serve/test_web_preview.js checks the documents,
flags and frames, serve/test_web_preview.py the header and that the page never
listens for a frame's postMessage.

Ported by hand from PR #1628 by thoives.

Co-authored-by: Thomas Ivesdal-Tronstad <325436323+thoives@users.noreply.github.com>
2026-10-26 19:57:56 +01:00

80 lines
3.5 KiB
Python

"""The chat's svg/html preview: sandboxed, no network, no way to the page (serve/web/preview.js)."""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import unittest
import urllib.request
from pathlib import Path
from serve.frontend import ChatTemplate
from serve.server import PAGE_CSP, ByteTokenizer, MockEngine, Service, serve
ROOT = Path(__file__).resolve().parents[1]
WEB = Path(__file__).parent / "web"
@unittest.skipUnless(shutil.which("node"), "node is not installed")
class PreviewInNode(unittest.TestCase):
def test_documents_frames_and_flags(self):
r = subprocess.run([shutil.which("node"), str(Path(__file__).with_name("test_web_preview.js"))],
capture_output=True, text=True, timeout=60)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class ThePageSource(unittest.TestCase):
def test_no_way_for_a_frame_to_reach_the_page(self):
scripts = {p.name: p.read_text(encoding="utf-8") for p in WEB.glob("*.js")}
for name, src in scripts.items():
with self.subTest(name=name):
self.assertNotIn("allow-same-origin", src.replace("no allow-same-origin", ""), "a frame with the page's origin is the page")
self.assertNotRegex(src, r"allow-(top-navigation|popups|forms|modals|downloads)")
# the page never listens for what a frame posts to it
self.assertNotRegex(scripts["app.js"], r"addEventListener\(\s*[\"']message[\"']")
self.assertNotRegex(scripts["app.js"], r"\bonmessage\b")
# every iframe starts closed, and is only ever made by preview.js
for tag in re.findall(r"<iframe\b[^>]*>", scripts["app.js"]):
self.assertIn('sandbox=""', tag)
self.assertNotIn("createElement(\"iframe\")", scripts["app.js"])
self.assertIn("srcdoc", scripts["preview.js"])
self.assertNotRegex(scripts["preview.js"], r"\.src\s*=")
class TheHeader(unittest.TestCase):
@classmethod
def setUpClass(cls):
tok = ByteTokenizer()
cls.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(ROOT / "serve" / "chat_template.jinja"))
cls.httpd = serve(cls.svc, port=0)
cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
@classmethod
def tearDownClass(cls):
cls.httpd.shutdown()
cls.httpd.server_close()
def test_the_page_forbids_a_frame_to_load_an_address(self):
with urllib.request.urlopen(self.base + "/", timeout=10) as r:
self.assertEqual(r.headers.get("Content-Security-Policy"), PAGE_CSP)
self.assertEqual(PAGE_CSP, "frame-src 'none'",
"only this directive: a srcdoc frame inherits the page's policy, and the opt-in script preview needs its inline script")
def test_other_files_do_not_carry_it(self):
with urllib.request.urlopen(self.base + "/web/app.js", timeout=10) as r:
self.assertIsNone(r.headers.get("Content-Security-Policy"))
@unittest.skipUnless(os.environ.get("WEBTEST_MODULES") and shutil.which("node"),
"set WEBTEST_MODULES (a folder with node_modules/puppeteer-core) to run the browser tests")
class InABrowser(unittest.TestCase):
def test_sandbox_in_chrome(self):
r = subprocess.run([shutil.which("node"), str(ROOT / "tools" / "webtest" / "browser_test.mjs"), "preview"],
capture_output=True, text=True, timeout=300)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
if __name__ == "__main__":
unittest.main()