A page on any *.gabvdl.xyz site could POST as the owner (Authelia cookie is same-site, a body without Content-Type needs no preflight); `Host: x?` emptied request.url.path and skipped the gate from the docker network; the Chrome websocket checked neither Origin nor the Authelia user; any Authelia account (the password-only bot) was the owner. Also: no served /openapi.json, a bounded /share, declared and bounded bodies for guests and anonymous callers, a CSP on the app shell, FastAPI 0.163 / Starlette 1.x (startup is a lifespan). Co-Authored-By: Claude <noreply@anthropic.com>
133 lines
6.4 KiB
Python
133 lines
6.4 KiB
Python
"""The Content-Security-Policy on the app shell and on the sandbox frame page
|
|
(core/csp.py, main.py's static route) — docs/security.md, the 2026-11-15 pass.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import base64
|
|
import hashlib
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import tempfile
|
|
import unittest
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
STATIC = TMP / "static"
|
|
(STATIC / "assets").mkdir(parents=True)
|
|
REPO = pathlib.Path(__file__).resolve().parent.parent
|
|
THEME = "\n try { document.documentElement.classList.add('dark'); } catch (e) {}\n "
|
|
(STATIC / "index.html").write_text(
|
|
'<!doctype html><html lang="en"><head><title>Claude Agent</title>'
|
|
'<meta name="apple-mobile-web-app-title" content="ai-agent" />'
|
|
f"<script>{THEME}</script>"
|
|
'<script type="module" crossorigin src="/assets/index-abc.js"></script>'
|
|
'</head><body><div id="root"></div></body></html>')
|
|
(STATIC / "assets" / "index-abc.js").write_text("console.log(1)")
|
|
(STATIC / "sandbox-frame.html").write_text(
|
|
(REPO / "frontend" / "public" / "sandbox-frame.html").read_text())
|
|
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
|
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
|
|
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"PROFILES_PATH": TMP / "profiles.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
|
|
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
|
|
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"SECURITY_LOG_PATH": TMP / "sec.jsonl", "SECURITY_STATE_PATH": TMP / "sec.json",
|
|
"PROJECTS_DIR": TMP / "projects", "STATIC_DIR": STATIC,
|
|
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "guest.example.test",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
(TMP / "projects").mkdir(parents=True)
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from core import csp # noqa: E402
|
|
|
|
CSP = "content-security-policy"
|
|
THEME_HASH = "'sha256-" + base64.b64encode(hashlib.sha256(THEME.encode()).digest()).decode() + "'"
|
|
SHELL = f"script-src 'self' {THEME_HASH}; object-src 'none'; base-uri 'self'; frame-ancestors 'self'"
|
|
|
|
|
|
class Shell(unittest.TestCase):
|
|
def setUp(self):
|
|
self.owner = TestClient(main.app, base_url="https://admin.example.test")
|
|
self.guest = TestClient(main.app, base_url="https://guest.example.test")
|
|
|
|
def test_the_shell_allows_its_own_scripts_and_the_builds_inline_one(self):
|
|
for path in ("/", "/index.html", "/settings/security", "/c/0190-not-a-file"):
|
|
r = self.owner.get(path)
|
|
self.assertEqual(r.status_code, 200, path)
|
|
self.assertEqual(r.headers[CSP], SHELL, path)
|
|
# nothing that would let an injected script or a javascript: URL run
|
|
for loose in ("unsafe-inline", "unsafe-eval", "data:", "blob:", "*"):
|
|
self.assertNotIn(loose, r.headers[CSP])
|
|
|
|
def test_the_guest_shell_gets_the_same_policy(self):
|
|
r = self.guest.get("/", headers={"Accept-Language": "fr"})
|
|
self.assertEqual(r.headers[CSP], SHELL)
|
|
self.assertIn('<html lang="fr"', r.text) # still the guest's page
|
|
self.assertIn(THEME, r.text) # the hashed script, untouched
|
|
self.assertEqual(self.guest.get("/login").headers[CSP], SHELL)
|
|
|
|
def test_the_policy_follows_a_new_build(self):
|
|
index = STATIC / "index.html"
|
|
old = index.read_text()
|
|
try:
|
|
index.write_text(old.replace("add('dark')", "add('light')"))
|
|
os.utime(index, ns=(index.stat().st_atime_ns, index.stat().st_mtime_ns + 10**9))
|
|
now = self.owner.get("/").headers[CSP]
|
|
self.assertNotEqual(now, SHELL)
|
|
self.assertEqual(now, csp.shell_policy(index.read_text()))
|
|
finally:
|
|
index.write_text(old)
|
|
os.utime(index, ns=(index.stat().st_atime_ns, index.stat().st_mtime_ns + 2 * 10**9))
|
|
self.assertEqual(self.owner.get("/").headers[CSP], SHELL)
|
|
|
|
def test_only_inline_scripts_are_hashed(self):
|
|
self.assertEqual(csp.script_hashes('<script src="/a.js"></script><script type="module" '
|
|
'crossorigin src="/b.js"></script><script> </script>'), [])
|
|
self.assertEqual(csp.script_hashes(f"<SCRIPT>{THEME}</SCRIPT><script>{THEME}</script>"),
|
|
[THEME_HASH])
|
|
# a browser hashes the text after newline normalisation
|
|
self.assertEqual(csp.script_hashes(f"<script>{THEME.replace(chr(10), chr(13) + chr(10))}</script>"),
|
|
[THEME_HASH])
|
|
# the source index.html has exactly the one bootstrap script
|
|
real = (REPO / "frontend" / "index.html").read_text()
|
|
self.assertEqual(len(csp.script_hashes(real)), 1)
|
|
|
|
def test_other_static_files_are_left_alone(self):
|
|
r = self.owner.get("/assets/index-abc.js")
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertNotIn(CSP, r.headers)
|
|
self.assertIn("immutable", r.headers["cache-control"])
|
|
|
|
|
|
class SandboxFrame(unittest.TestCase):
|
|
def test_the_frame_page_is_an_opaque_origin_whoever_loads_it(self):
|
|
for base in ("https://admin.example.test", "https://guest.example.test"):
|
|
r = TestClient(main.app, base_url=base).get("/sandbox-frame.html")
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertIn("text/html", r.headers["content-type"])
|
|
policy = r.headers[CSP]
|
|
self.assertTrue(policy.startswith("sandbox allow-scripts"), policy)
|
|
self.assertNotIn("allow-same-origin", policy)
|
|
self.assertIn("frame-ancestors 'self'", policy)
|
|
self.assertNotIn("script-src", policy) # the author's scripts run there
|
|
self.assertIn('self.origin !== "null"', r.text)
|
|
|
|
def test_header_and_iframe_attribute_carry_the_same_flags(self):
|
|
ts = (REPO / "frontend" / "src" / "lib" / "sandboxFrame.ts").read_text()
|
|
m = re.search(r'export const SANDBOX = "([^"]+)"', ts)
|
|
self.assertIsNotNone(m)
|
|
self.assertEqual(m.group(1), csp.SANDBOX_FLAGS)
|
|
self.assertIn(f'"/{csp.SANDBOX_FRAME}"', ts)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|