test_csp_templates.py
python
sha256:8060dc3efcb294674562ec9e6977ce5ded6c64374f4ebc361ee4fb1f3eabe299
fix(csp): HTMX allowScriptTags off; page data travels in an…
Opus 5.5
minor
⚠ breaking
1 day ago
| 1 | """Issue pages must run under the strict CSP without inline script. |
| 2 | |
| 3 | The CSP in ``musehub/main.py`` allows scripts from 'self' (and the Cloudflare |
| 4 | beacon) only, so inline ``<script>`` bodies and ``on*=`` handler attributes |
| 5 | are blocked by the browser. These tests render the issue list and issue |
| 6 | detail pages and check that they rely on neither. |
| 7 | """ |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import re |
| 11 | from datetime import datetime, timezone |
| 12 | |
| 13 | from httpx import AsyncClient |
| 14 | from sqlalchemy.ext.asyncio import AsyncSession |
| 15 | |
| 16 | from musehub.core.genesis import compute_identity_id, compute_issue_id, compute_repo_id |
| 17 | from musehub.db.musehub_repo_models import MusehubRepo |
| 18 | from musehub.db.musehub_social_models import MusehubIssue |
| 19 | |
| 20 | _SCRIPT_TAG = re.compile(r"<script\b([^>]*)>", re.IGNORECASE) |
| 21 | _INLINE_HANDLER = re.compile(r"\son[a-z]+\s*=", re.IGNORECASE) |
| 22 | _DATA_TYPES = ('type="application/json"', 'type="application/ld+json"') |
| 23 | |
| 24 | |
| 25 | async def _make_repo(db: AsyncSession, owner: str = "songwriter", slug: str = "melodies") -> str: |
| 26 | owner_id = compute_identity_id(owner.encode()) |
| 27 | created_at = datetime.now(tz=timezone.utc) |
| 28 | repo = MusehubRepo( |
| 29 | repo_id=compute_repo_id(owner_id, slug, "code", created_at.isoformat()), |
| 30 | name=slug, |
| 31 | owner=owner, |
| 32 | slug=slug, |
| 33 | visibility="public", |
| 34 | owner_user_id=owner_id, |
| 35 | created_at=created_at, |
| 36 | updated_at=created_at, |
| 37 | ) |
| 38 | db.add(repo) |
| 39 | await db.commit() |
| 40 | return str(repo.repo_id) |
| 41 | |
| 42 | |
| 43 | async def _make_issue(db: AsyncSession, repo_id: str, author: str = "songwriter") -> None: |
| 44 | now = datetime.now(tz=timezone.utc) |
| 45 | db.add(MusehubIssue( |
| 46 | issue_id=compute_issue_id(repo_id, compute_identity_id(author.encode()), now.isoformat()), |
| 47 | repo_id=repo_id, |
| 48 | number=1, |
| 49 | title="Verse needs a bridge", |
| 50 | body="The verse feels incomplete.", |
| 51 | state="open", |
| 52 | labels=[], |
| 53 | symbol_anchors=[], |
| 54 | author=author, |
| 55 | )) |
| 56 | await db.commit() |
| 57 | |
| 58 | |
| 59 | def _script_src(csp: str) -> str: |
| 60 | for directive in csp.split(";"): |
| 61 | if directive.strip().startswith("script-src"): |
| 62 | return directive |
| 63 | raise AssertionError(f"no script-src directive in {csp!r}") |
| 64 | |
| 65 | |
| 66 | def _assert_csp_clean(html: str, csp: str) -> None: |
| 67 | script_src = _script_src(csp) |
| 68 | assert "'unsafe-inline'" not in script_src |
| 69 | assert "'unsafe-eval'" not in script_src |
| 70 | |
| 71 | for attrs in _SCRIPT_TAG.findall(html): |
| 72 | if "src=" in attrs or any(t in attrs for t in _DATA_TYPES): |
| 73 | continue |
| 74 | raise AssertionError(f"inline <script{attrs}> would be blocked by the CSP") |
| 75 | |
| 76 | handlers = _INLINE_HANDLER.findall(html) |
| 77 | assert not handlers, f"inline event handler attributes would be blocked by the CSP: {handlers}" |
| 78 | |
| 79 | |
| 80 | async def test_issue_list_page_has_no_inline_script(client: AsyncClient, db_session: AsyncSession) -> None: |
| 81 | repo_id = await _make_repo(db_session) |
| 82 | await _make_issue(db_session, repo_id) |
| 83 | |
| 84 | resp = await client.get("/songwriter/melodies/issues") |
| 85 | |
| 86 | assert resp.status_code == 200 |
| 87 | assert "isl-check" in resp.text # the row checkbox is rendered |
| 88 | _assert_csp_clean(resp.text, resp.headers["content-security-policy"]) |
| 89 | |
| 90 | |
| 91 | async def test_issue_detail_page_has_no_inline_script(client: AsyncClient, db_session: AsyncSession) -> None: |
| 92 | repo_id = await _make_repo(db_session) |
| 93 | await _make_issue(db_session, repo_id) |
| 94 | |
| 95 | resp = await client.get("/songwriter/melodies/issues/1") |
| 96 | |
| 97 | assert resp.status_code == 200 |
| 98 | _assert_csp_clean(resp.text, resp.headers["content-security-policy"]) |
| 99 | |
| 100 | |
| 101 | async def test_theme_init_is_a_versioned_self_script_in_head(client: AsyncClient, db_session: AsyncSession) -> None: |
| 102 | repo_id = await _make_repo(db_session) |
| 103 | await _make_issue(db_session, repo_id) |
| 104 | |
| 105 | resp = await client.get("/songwriter/melodies/issues/1") |
| 106 | head = resp.text.split("</head>", 1)[0] |
| 107 | |
| 108 | # Same ?v= cache-buster as the other static assets (empty when app.css/app.js are not built). |
| 109 | match = re.search(r'<script src="(/static/theme-init\.js\?v=([^"]*))"></script>', head) |
| 110 | assert match, "theme-init.js must load synchronously (no defer/async) from /static with ?v=" |
| 111 | htmx_version = re.search(r'/static/htmx\.min\.js\?v=([^"]*)"', head) |
| 112 | assert htmx_version and match.group(2) == htmx_version.group(1) |
| 113 | asset = await client.get(match.group(1)) |
| 114 | assert asset.status_code == 200 |
| 115 | assert "musehub-theme" in asset.text |
| 116 | |
| 117 | |
| 118 | async def test_htmx_eval_is_disabled_before_htmx_loads(client: AsyncClient, db_session: AsyncSession) -> None: |
| 119 | repo_id = await _make_repo(db_session) |
| 120 | await _make_issue(db_session, repo_id) |
| 121 | |
| 122 | resp = await client.get("/songwriter/melodies/issues/1") |
| 123 | head = resp.text.split("</head>", 1)[0] |
| 124 | |
| 125 | meta = head.find('<meta name="htmx-config" content=\'{"allowEval":false,"allowScriptTags":false}\'>') |
| 126 | htmx = head.find("/static/htmx.min.js") |
| 127 | assert meta != -1, "htmx-config meta with allowEval:false and allowScriptTags:false is missing (#266 HX_04)" |
| 128 | assert meta < htmx, "htmx reads its meta config when it loads, so the meta must come first" |
| 129 | |
| 130 | |
| 131 | # ── musehub#267 CSP_01: the standing guard, across every template ───────────── |
| 132 | |
| 133 | _TEMPLATES = __import__("pathlib").Path(__file__).resolve().parents[1] / "musehub" / "templates" |
| 134 | _JINJA_COMMENT = re.compile(r"\{#.*?#\}", re.DOTALL) |
| 135 | _HX_ON = re.compile(r"\shx-on[:\-]", re.IGNORECASE) |
| 136 | _HX_JS_VALS = re.compile(r"""\shx-(?:vals|vars)\s*=\s*['"]\s*js:""", re.IGNORECASE) |
| 137 | |
| 138 | |
| 139 | def test_no_template_needs_inline_script_or_eval() -> None: |
| 140 | """No ``on*=`` handler, ``hx-on``, ``hx-vals="js:…"`` or ``<script>`` without ``src`` in any template (#267 CSP_01, #266 HX_01). |
| 141 | |
| 142 | With ``allowScriptTags:false`` HTMX drops every ``<script>`` in swapped content, JSON data islands included, so |
| 143 | page data travels in ``<template id="page-data">``. |
| 144 | """ |
| 145 | found: list[str] = [] |
| 146 | for path in sorted(_TEMPLATES.rglob("*.html")): |
| 147 | text = _JINJA_COMMENT.sub("", path.read_text()) |
| 148 | rel = path.relative_to(_TEMPLATES) |
| 149 | found += [f"{rel}: inline handler {m.group().strip()}" for m in _INLINE_HANDLER.finditer(text)] |
| 150 | found += [f"{rel}: hx-on" for _ in _HX_ON.finditer(text)] |
| 151 | found += [f"{rel}: js: hx-vals (needs eval)" for _ in _HX_JS_VALS.finditer(text)] |
| 152 | found += [ |
| 153 | f"{rel}: inline <script{attrs}>" |
| 154 | for attrs in _SCRIPT_TAG.findall(text) |
| 155 | if "src=" not in attrs |
| 156 | ] |
| 157 | assert not found, "would be blocked by the CSP:\n" + "\n".join(found) |
| 158 | |
| 159 | |
| 160 | # ── #266 HX_02: page data rides in an inert <template> and round-trips markup-like values ── |
| 161 | |
| 162 | _CARRIER = re.compile(r'<template id="page-data">(.*?)</template>', re.DOTALL) |
| 163 | |
| 164 | |
| 165 | def _page_data(html: str) -> dict: |
| 166 | import json |
| 167 | |
| 168 | found = _CARRIER.findall(html) |
| 169 | assert len(found) == 1, "exactly one <template id=\"page-data\"> carrier" |
| 170 | assert '<script id="page-data"' not in html |
| 171 | return json.loads(__import__("html").unescape(found[0])) # a <template> decodes entities before .content is read |
| 172 | |
| 173 | |
| 174 | async def test_issue_pages_carry_page_data_in_a_template(client: AsyncClient, db_session: AsyncSession) -> None: |
| 175 | repo_id = await _make_repo(db_session) |
| 176 | await _make_issue(db_session, repo_id) |
| 177 | listing = await client.get("/songwriter/melodies/issues") |
| 178 | assert _page_data(listing.text) == {"page": "issue-list", "repo_id": repo_id} |
| 179 | detail = await client.get("/songwriter/melodies/issues/1") |
| 180 | assert _page_data(detail.text)["page"] == "issue-detail" |
| 181 | |
| 182 | |
| 183 | def test_a_value_with_template_and_script_markup_round_trips() -> None: |
| 184 | from musehub.api.routes.musehub._templates import templates |
| 185 | |
| 186 | hostile = '</template><script>alert(1)</script> & "quoted" \'single\'' |
| 187 | html = templates.env.from_string('<template id="page-data">{"v": {{ v | tojson }}}</template>').render(v=hostile) |
| 188 | inner = _CARRIER.findall(html) |
| 189 | assert len(inner) == 1 and "<" not in inner[0] and "&" not in inner[0], "tojson leaves no markup or entity in the carrier" |
| 190 | assert _page_data(html) == {"v": hostile} |
File History
3 commits
sha256:8060dc3efcb294674562ec9e6977ce5ded6c64374f4ebc361ee4fb1f3eabe299
fix(csp): HTMX allowScriptTags off; page data travels in an…
Opus 5.5
minor
⚠
1 day ago
sha256:12a47d936d91d16ca58705b5e19fc1782cb8888b124c2b6087ecf0ae1a773a96
fix(csp): every template runs under the strict CSP; remove …
Opus 5.5
minor
⚠
1 day ago
sha256:1bb0091be06da0a6e031a66d7f797a3f0fae43392a7af737f4d8b90912f875cc
fix(ui): move inline scripts and event handlers out of issu…
Opus 5.5
minor
⚠
11 days ago