okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-web: the served web chat page for 0.2.75d9f47922

main
3.5 KiB79 linesraw
1"""The chat's svg/html preview: sandboxed, no network, no way to the page (serve/web/preview.js)."""
2from __future__ import annotations
3
4import os
5import re
6import shutil
7import subprocess
8import unittest
9import urllib.request
10from pathlib import Path
11
12from serve.frontend import ChatTemplate
13from serve.server import PAGE_CSP, ByteTokenizer, MockEngine, Service, serve
14
15ROOT = Path(__file__).resolve().parents[1]
16WEB = Path(__file__).parent / "web"
17
18
19@unittest.skipUnless(shutil.which("node"), "node is not installed")
20class PreviewInNode(unittest.TestCase):
21    def test_documents_frames_and_flags(self):
22        r = subprocess.run([shutil.which("node"), str(Path(__file__).with_name("test_web_preview.js"))],
23                           capture_output=True, text=True, timeout=60)
24        self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
25
26
27class ThePageSource(unittest.TestCase):
28    def test_no_way_for_a_frame_to_reach_the_page(self):
29        scripts = {p.name: p.read_text(encoding="utf-8") for p in WEB.glob("*.js")}
30        for name, src in scripts.items():
31            with self.subTest(name=name):
32                self.assertNotIn("allow-same-origin", src.replace("no allow-same-origin", ""), "a frame with the page's origin is the page")
33                self.assertNotRegex(src, r"allow-(top-navigation|popups|forms|modals|downloads)")
34        # the page never listens for what a frame posts to it
35        self.assertNotRegex(scripts["app.js"], r"addEventListener\(\s*[\"']message[\"']")
36        self.assertNotRegex(scripts["app.js"], r"\bonmessage\b")
37        # every iframe starts closed, and is only ever made by preview.js
38        for tag in re.findall(r"<iframe\b[^>]*>", scripts["app.js"]):
39            self.assertIn('sandbox=""', tag)
40        self.assertNotIn("createElement(\"iframe\")", scripts["app.js"])
41        self.assertIn("srcdoc", scripts["preview.js"])
42        self.assertNotRegex(scripts["preview.js"], r"\.src\s*=")
43
44
45class TheHeader(unittest.TestCase):
46    @classmethod
47    def setUpClass(cls):
48        tok = ByteTokenizer()
49        cls.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(ROOT / "serve" / "chat_template.jinja"))
50        cls.httpd = serve(cls.svc, port=0)
51        cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
52
53    @classmethod
54    def tearDownClass(cls):
55        cls.httpd.shutdown()
56        cls.httpd.server_close()
57
58    def test_the_page_forbids_a_frame_to_load_an_address(self):
59        with urllib.request.urlopen(self.base + "/", timeout=10) as r:
60            self.assertEqual(r.headers.get("Content-Security-Policy"), PAGE_CSP)
61        self.assertEqual(PAGE_CSP, "frame-src 'none'",
62                         "only this directive: a srcdoc frame inherits the page's policy, and the opt-in script preview needs its inline script")
63
64    def test_other_files_do_not_carry_it(self):
65        with urllib.request.urlopen(self.base + "/web/app.js", timeout=10) as r:
66            self.assertIsNone(r.headers.get("Content-Security-Policy"))
67
68
69@unittest.skipUnless(os.environ.get("WEBTEST_MODULES") and shutil.which("node"),
70                     "set WEBTEST_MODULES (a folder with node_modules/puppeteer-core) to run the browser tests")
71class InABrowser(unittest.TestCase):
72    def test_sandbox_in_chrome(self):
73        r = subprocess.run([shutil.which("node"), str(ROOT / "tools" / "webtest" / "browser_test.mjs"), "preview"],
74                           capture_output=True, text=True, timeout=300)
75        self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
76
77
78if __name__ == "__main__":
79    unittest.main()