Form links are https with the form's own id and never framed on the app origin; /api/diff-blob answers under `CSP: sandbox`; the asset inliner fetches media routes only; the deploy preview is sandboxed on a same-origin URL. Sandboxed form HTML is written into /sandbox-frame.html (its own policy) because srcdoc and blob: documents inherit the shell's script-src. npm audit fix. Co-Authored-By: Claude <noreply@anthropic.com>
132 lines
6.4 KiB
Python
132 lines
6.4 KiB
Python
"""Bytes served on the app's own origin (docs/security.md, 2026-11-15): a
|
||
repo's SVG is never a page, an attachment's name never breaks its header, and
|
||
a push's picture never redirects off-site.
|
||
|
||
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
||
|
||
import os
|
||
import pathlib
|
||
import subprocess
|
||
import tempfile
|
||
import unittest
|
||
|
||
TMP = pathlib.Path(tempfile.mkdtemp())
|
||
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", "ASKFORM_PATH": TMP / "af.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",
|
||
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
|
||
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
||
os.environ[k] = str(v)
|
||
|
||
from fastapi.testclient import TestClient # noqa: E402
|
||
|
||
import main # noqa: E402
|
||
from files import assets # noqa: E402
|
||
from notifications import image_proxy # noqa: E402
|
||
from users.caller import SESSION_COOKIE # noqa: E402
|
||
|
||
DEPS = main.app.state.ai
|
||
OWNER_H = {"X-Internal-Auth": "tok"}
|
||
SVG = b'<svg xmlns="http://www.w3.org/2000/svg"><script>fetch("/api/spawn")</script></svg>'
|
||
|
||
|
||
class DiffBlob(unittest.TestCase):
|
||
@classmethod
|
||
def setUpClass(cls):
|
||
repo = pathlib.Path(os.environ["PROJECTS_DIR"]) / "film"
|
||
repo.mkdir(parents=True, exist_ok=True)
|
||
subprocess.run(["git", "init", "-q", str(repo)], check=True)
|
||
(repo / "x.svg").write_bytes(SVG)
|
||
(repo / "shot.png").write_bytes(b"\x89PNG")
|
||
if not DEPS.users.get("dom"):
|
||
DEPS.users.create("dom@example.com", "Dom", projects={"film": "view"})
|
||
|
||
def _sandboxed(self, r):
|
||
self.assertEqual(r.status_code, 200, r.text)
|
||
csp = r.headers["content-security-policy"]
|
||
# An opaque origin with scripts off: opened by its URL, the SVG's
|
||
# <script> can't run as the app. <img src> still draws it.
|
||
self.assertTrue(csp.startswith("sandbox;"), csp)
|
||
self.assertNotIn("allow-scripts", csp)
|
||
self.assertNotIn("allow-same-origin", csp)
|
||
self.assertIn("default-src 'none'", csp)
|
||
self.assertEqual(r.headers["x-content-type-options"], "nosniff")
|
||
|
||
def test_an_svg_is_served_sandboxed_to_a_guest_and_to_the_owner(self):
|
||
guest = TestClient(main.app, base_url="https://claude.example.test")
|
||
guest.cookies.set(SESSION_COOKIE, DEPS.auth.open_session("dom"))
|
||
for c in (guest, TestClient(main.app, headers=OWNER_H)):
|
||
r = c.get("/api/diff-blob", params={"repo": "project:film", "path": "x.svg"})
|
||
self._sandboxed(r)
|
||
self.assertEqual(r.headers["content-type"], "image/svg+xml")
|
||
self.assertEqual(r.content, SVG)
|
||
|
||
def test_every_blob_carries_the_policy(self):
|
||
c = TestClient(main.app, headers=OWNER_H)
|
||
self._sandboxed(c.get("/api/diff-blob", params={"repo": "project:film", "path": "shot.png"}))
|
||
|
||
|
||
class AttachmentName(unittest.TestCase):
|
||
def test_a_name_outside_latin_1_is_a_valid_header(self):
|
||
for name in ("notes – draft 🙂.html", "été.svg", 'a"b.html', "a\r\nX-Evil: 1.html",
|
||
"back\\slash.txt", "plain.txt"):
|
||
h = assets._attachment(name)
|
||
h.encode("latin-1") # what Starlette does with it
|
||
self.assertNotRegex(h, r"[\r\n]")
|
||
self.assertEqual(h.count('"'), 2, h) # the quoted fallback stays closed
|
||
self.assertTrue(h.startswith('attachment; filename="'))
|
||
self.assertEqual(assets._attachment("été 🙂.svg"),
|
||
"attachment; filename=\"_t_ _.svg\"; "
|
||
"filename*=UTF-8''%C3%A9t%C3%A9%20%F0%9F%99%82.svg")
|
||
|
||
def test_the_response_is_built_for_such_a_file(self):
|
||
p = TMP / "notes – draft 🙂.html"
|
||
p.write_text("<script>1</script>")
|
||
r = assets._safe_file_response(p)
|
||
self.assertIn("filename*=UTF-8''", r.headers["content-disposition"])
|
||
self.assertEqual(r.headers["x-content-type-options"], "nosniff")
|
||
img = TMP / "shot.png"
|
||
img.write_bytes(b"x")
|
||
self.assertNotIn("content-disposition", assets._safe_file_response(img).headers)
|
||
|
||
|
||
class NotifyImageRedirect(unittest.TestCase):
|
||
HUB = ("https://hub.example", "https://guests.example")
|
||
|
||
def test_own_path_never_leaves_the_host(self):
|
||
self.assertEqual(image_proxy.own_path("/api/upload-file?id=1", self.HUB), "/api/upload-file?id=1")
|
||
self.assertEqual(image_proxy.own_path("https://hub.example/api/x", self.HUB), "/api/x")
|
||
self.assertEqual(image_proxy.own_path("https://hub.example", self.HUB), "/")
|
||
for bad in ("//evil.example/x", "/\\evil.example/x", "/\\/evil.example", "/a\\b",
|
||
"/\tevil", "/x\ny", "https://hub.example//evil.example/x",
|
||
"https://hub.example/\\evil.example/x"):
|
||
self.assertIsNone(image_proxy.own_path(bad, self.HUB), bad)
|
||
|
||
def test_only_a_real_web_address_is_redirected_to(self):
|
||
self.assertTrue(image_proxy.is_web("https://files.lab.example/a.png"))
|
||
self.assertTrue(image_proxy.is_web("http://192.168.1.4/a.png"))
|
||
for bad in ("//evil.example/x", "/\\evil.example/x", "javascript:alert(1)",
|
||
"data:image/png;base64,AA", "https:///x", "https://a b/x", "", "ftp://x/y"):
|
||
self.assertFalse(image_proxy.is_web(bad), bad)
|
||
|
||
def test_the_route_does_not_send_the_owner_off_site(self):
|
||
c = TestClient(main.app, headers=OWNER_H, follow_redirects=False)
|
||
for bad in ("//evil.example/x.png", "/\\evil.example/x.png"):
|
||
n = DEPS.notify_store.record({"id": "ntf_" + os.urandom(6).hex(), "title": "t",
|
||
"message": "m", "image": bad})
|
||
r = c.get(f"/api/notify/{n['id']}/image")
|
||
self.assertEqual(r.status_code, 404, (bad, r.headers.get("location")))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|