"""Guards on the templates themselves. These check one thing that no request-level test can: the Content-Security- Policy makes a whole category of markup silently inert rather than broken, so nothing at runtime will ever fail to tell you about it. """ from __future__ import annotations import re from pathlib import Path import pytest TEMPLATES = sorted((Path(__file__).resolve().parents[1] / "templates").glob("*.html")) INLINE_HANDLER = re.compile(r"\son[a-z]+\s*=", re.IGNORECASE) @pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name) def test_no_inline_event_handlers(template): """`default-src 'self'` with no 'unsafe-inline' means the browser ignores an onsubmit="" attribute without complaining. A delete button written that way loses its confirmation dialog and nobody finds out until something is deleted by accident. Use data-confirm, handled in static/board.js. Comments stripped first, like the two guards below: base.html explains in a Jinja comment why its account menu is a
rather than a button with an onclick, and a guard that fails on its own reasoning gets deleted rather than obeyed.""" found = INLINE_HANDLER.findall( JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))) assert not found, f"{template.name} has inline handler(s): {found}" @pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name) def test_no_inline_style_blocks(template): """The same policy, the same silence, a different symptom. `default-src 'self'` covers style-src too, and 'self' does not permit an inline