Two bugs, both mine. The profile page arrived unstyled because its CSS was in a <style> block. default-src 'self' covers style-src, 'self' does not permit inline, so the browser dropped the whole block without a word — the photo loaded because img-src allows same-origin, which is what made the screenshot look like a half-working page rather than a blocked one. The third time this policy has silently made something inert, after two rounds of inline event handlers. Moved to static/profile.css, where the policy allows it, and test_templates.py now fails on an inline <style> the way it already does on an inline onclick. Private messages had an "Abrir conversación" button that created an empty conversation and sent you to a page where you then had to type. It bought nothing and littered the inbox with rows reading "Sin mensajes todavía" for people nobody had written to. A conversation is now addressed by the person — /privados/con/<member_id> — and the page always carries the history and the box together. The row is created by the first message, not by looking at somebody's name. That also makes the access rule structural instead of checked. Every lookup is scoped to the member doing the looking, so there is no query that could return somebody else's correspondence, and the two helpers that took a conversation id are gone. A third person opening the same URL now sees their own empty conversation, which the tests assert directly rather than asserting a 404. 281 tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
119 lines
5.3 KiB
Python
119 lines
5.3 KiB
Python
"""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."""
|
|
found = INLINE_HANDLER.findall(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 <style>. The browser drops the whole block without a word, and the
|
|
page arrives in Times New Roman with blue links — which is exactly how the
|
|
public profile page shipped. Put it in static/ and link it, where the
|
|
policy allows it and the browser caches it.
|
|
"""
|
|
# Comments stripped first: profile.html explains in a Jinja comment why it
|
|
# has no <style> block, and a guard that trips on its own documentation is
|
|
# a guard people delete.
|
|
html = JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))
|
|
assert "<style" not in html, (
|
|
f"{template.name} has an inline <style> block, which the CSP ignores. "
|
|
"Move it to apps/board/static/ and link it with url_for('static', …)."
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
|
|
def test_every_post_form_carries_a_csrf_token(template):
|
|
"""The hook in app.py rejects a POST without one, so a form that forgets it
|
|
is a button that always fails — and fails with a 400 that reads like the
|
|
page is broken rather than like a missing field."""
|
|
html = template.read_text(encoding="utf-8")
|
|
forms = re.findall(r"<form[^>]*method=[\"']post[\"'][^>]*>(.*?)</form>", html,
|
|
re.IGNORECASE | re.DOTALL)
|
|
for form in forms:
|
|
assert "csrf_token" in form, f"{template.name} has a POST form without a CSRF token"
|
|
|
|
|
|
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
|
|
def test_nothing_links_to_the_account_server_logout(template):
|
|
"""A link there is a GET, and that route is POST-only, so the browser gets
|
|
a 404 and the session it was meant to end carries on. We shipped exactly
|
|
that and it went unnoticed for a week, because a dead link on a page nobody
|
|
reaches twice looks like nothing at all.
|
|
|
|
It cannot be fixed by turning the link into a form either: the POST needs a
|
|
CSRF token belonging to that other domain, which is unreadable from here by
|
|
design. The page has to tell the member what to do instead."""
|
|
html = JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))
|
|
assert "/user/logout" not in html, (
|
|
f"{template.name} links to /user/logout, which answers 404 to a GET"
|
|
)
|
|
|
|
|
|
# --- the name of the software behind the login ---------------------------
|
|
#
|
|
# Members sign in through an OAuth provider that happens to be Gitea. They are
|
|
# never told so: as far as anyone using vienalatina.com is concerned there is
|
|
# one site, and a stray brand name in an error message is the seam showing.
|
|
# Comments and docstrings are exempt — the code has to stay honest about what
|
|
# it talks to, and neither reaches a browser.
|
|
|
|
JINJA_COMMENT = re.compile(r"\{#.*?#\}", re.DOTALL)
|
|
|
|
|
|
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
|
|
def test_no_template_shows_the_name_of_the_account_server(template):
|
|
body = JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))
|
|
assert "Gitea" not in body, (
|
|
f"{template.name} shows 'Gitea' to the member; call it el servidor de "
|
|
"cuentas, or put the remark in a {# Jinja comment #}"
|
|
)
|
|
|
|
|
|
def test_no_message_in_the_code_shows_it_either():
|
|
"""String literals only, docstrings excluded, and case-sensitive on
|
|
purpose: `gitea_login` and `gitea_tokens` are column names nobody sees, so
|
|
only the capitalised prose form is worth failing on."""
|
|
import ast
|
|
|
|
offenders = []
|
|
for path in sorted(Path(__file__).resolve().parents[1].glob("*.py")):
|
|
tree = ast.parse(path.read_text(encoding="utf-8"))
|
|
docstrings = {
|
|
doc for node in ast.walk(tree)
|
|
if isinstance(node, (ast.Module, ast.FunctionDef,
|
|
ast.AsyncFunctionDef, ast.ClassDef))
|
|
and (doc := ast.get_docstring(node, clean=False))
|
|
}
|
|
offenders += [
|
|
f"{path.name}:{node.lineno}: {node.value!r}"
|
|
for node in ast.walk(tree)
|
|
if isinstance(node, ast.Constant) and isinstance(node.value, str)
|
|
and "Gitea" in node.value and node.value not in docstrings
|
|
]
|
|
assert not offenders, "\n".join(offenders)
|