Skip to content

Commit 8cbcb9b

Browse files
authored
Merge pull request #190 from tina4stack/fix/csp-nonce-inline
fix(csp): render framework inline content under the strict default CSP via a per-response nonce
2 parents ff02c74 + af4235d commit 8cbcb9b

28 files changed

Lines changed: 5604 additions & 187 deletions

‎plan/csp-crud-onclick.md‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Task: De-inline crud component onclick handlers (CSP-clean under default-src 'self')
2+
3+
Outcome: the CRUD component's buttons fire under the strict default CSP
4+
(`default-src 'self'`). A CSP nonce covers `<script>`/`<style>` ELEMENTS but NOT
5+
inline `on*=` event-handler attributes, so every `onclick="..."` the component
6+
emits is dead under the policy. Replace each with `data-*` attributes +
7+
`addEventListener` wiring inside the already-nonce'd `<script>`. Follow-up to
8+
[plan/csp-nonce-inline.md](tina4-python/plan/csp-nonce-inline.md).
9+
10+
## Scope
11+
- [x] Python: `tina4_python/templates/components/crud.twig` — de-inline 5 onclick
12+
HTML attrs + the form's onsubmit + the JS-generated pagination onclick
13+
- [x] Python: event delegation (click + submit) on `#crudTarget{{table_name}}` (survives AJAX reload)
14+
- [x] Python: pagination link rebuilt with createElement + addEventListener
15+
- [x] Ruby (parity): `lib/tina4/crud.rb` — de-inline all 9 onclick + the modal form onsubmit
16+
- [x] PHP / Node: AutoCrud is REST-only, NO HTML crud component with onclick → nothing to de-inline (finding)
17+
- [x] Real test (no mocks) renders the component, asserts zero on*= + buttons wired (Python + Ruby)
18+
19+
## Parity
20+
| Feature | Python | PHP | Ruby | Node |
21+
|---------|--------|-----|------|------|
22+
| crud HTML component exists | ✅ crud.twig | ❌ REST-only | ✅ crud.rb | ❌ REST-only |
23+
| onclick de-inlined (CSP-clean) | ✅ | n/a | ✅ | n/a |
24+
25+
## Tests (real, no mocks, positive + negative)
26+
- [x] Python: render crud.twig via real Frond → 0 on*= attrs, data-crud-action add/edit/delete present, pagination + delegation wired + source scan (tests/test_crud_csp_onclick.py, 6 passed)
27+
- [x] Python negative: record JSON rides in `data-record` (JSON-safe, `'`); mutation (restore an onclick) turns the gate red — proven
28+
- [x] Ruby: render Crud.to_crud + generate_table (real SQLite, real Request) → 0 on*=, data-crud-action/-inline wired (spec/crud_csp_onclick_spec.rb, 6 examples); mutation-proven
29+
30+
## Bugs
31+
- [x] crud component buttons never fire under strict default CSP (inline onclick blocked) — fixed; no-on*= gate green + mutation-proven in Python and Ruby
32+
33+
## Commits
34+
- (py) <hash> crud.twig de-inline on*= → data-* + delegation; real CSP render test
35+
- (ruby) <hash> crud.rb de-inline on*= → data-* + delegation; real CSP render spec
36+
37+
## Status: Complete (Python + Ruby). PHP/Node have no HTML crud component (REST-only). PR to v3, do not merge.
38+
```
39+
Branch: fix/csp-nonce-inline (all four repos). PR to v3, do not merge.
40+
```

‎plan/csp-nonce-inline.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Task: CSP nonce for framework inline content (fix unstyled fresh-init render)
2+
3+
Outcome: fresh `tina4 init python` renders STYLED under the strict default CSP. Keep
4+
`default-src 'self'`; make the framework's own inline `<style>`/`<script>` CSP-clean via a
5+
per-response nonce, and de-inline every `style="..."` the framework emits. No 'unsafe-inline'.
6+
7+
## Scope
8+
- [x] Per-response nonce module (`tina4_python/core/csp.py`): contextvar + generate + Frond global `csp_nonce`
9+
- [x] `response.csp_nonce` attribute (Response __slots__ + __init__)
10+
- [x] Wire nonce per request in `server.handle()` (set/clear in try/finally, mirror request_id)
11+
- [x] Frond global `csp_nonce()` registered in engine `_register_builtins`
12+
- [x] CSP header: inject `'nonce-X'` into style-src AND script-src (default + user TINA4_CSP) in SecurityHeadersMiddleware
13+
- [x] Update TINA4_CSP one-time warning text (inline now works via nonce)
14+
- [x] Nonce every framework inline `<style>`/`<script>`: welcome page, swagger, error_overlay, error twigs, crud.twig, gallery
15+
- [x] De-inline every `style="..."` the framework emits (classes in the page's nonce'd <style> / bundled CSS)
16+
- [x] De-inline welcome-page + gallery inline `onclick=` → data-* + addEventListener
17+
- [x] Scaffold auth forms (login/register) de-inlined + nonce'd `<style>` demonstrating csp_nonce()
18+
- [x] Document csp_nonce() for app developers (tina4_python/CLAUDE.md)
19+
- [ ] FOLLOW-UP (flagged, out of this scope): de-inline crud.twig's ~6 row-level onclick handlers (dynamic JSON payloads) — its <script> is nonce'd; onclick needs event delegation + its own tests
20+
21+
## Parity
22+
| Feature | Python | PHP | Ruby | Node |
23+
|---------|--------|-----|------|------|
24+
| csp-nonce | ❌ BUILD | ❌ (mirror) | ❌ (mirror) | ❌ (mirror) |
25+
26+
## Tests (real, no mocks, positive + negative)
27+
- [x] CSP header on `/` carries 'nonce-' in style-src AND script-src (real boot) — test_csp_nonce_inline.py
28+
- [x] welcome page inline <style>/<script> carry that exact nonce — real child server
29+
- [x] no style= / onclick= emitted by framework welcome page
30+
- [x] negative: two requests get DIFFERENT nonces (per-response)
31+
- [x] updated contract mirrors: test_security_headers_contract.py, test_http_hardening_contract.py, test_csp_default_warning.py
32+
33+
## Bugs
34+
- [x] fresh-init `/` welcome page rendered unstyled under default CSP — fixed via per-response nonce
35+
36+
## Commits
37+
- (squashed on branch fix/csp-nonce-inline — see PR)
38+
39+
## Status: Complete (Python reference). Deterministic verify + metrics gate green. PHP/Ruby/Node mirror pending.

‎tests/test_crud_csp_onclick.py‎

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
# Copyright (c) 2026 Code Infinity
2+
# SPDX-License-Identifier: MPL-2.0
3+
# This Source Code Form is subject to the terms of the Mozilla Public
4+
# License, v. 2.0. If a copy of the MPL was not distributed with this
5+
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
6+
7+
"""The CRUD component is CSP-clean under the strict default policy (ADR-0088).
8+
9+
The framework serves ``default-src 'self'``. A CSP nonce authorises a
10+
``<script>``/``<style>`` ELEMENT but NEVER an inline ``on*=`` event-handler
11+
attribute, so a button that wires its action with ``onclick="..."`` (or a form
12+
with ``onsubmit="..."``) is dead under the policy — the handler never fires.
13+
``components/crud.twig`` must therefore carry ZERO inline ``on*=`` attributes
14+
and bind every action with ``addEventListener`` inside its already-nonce'd
15+
``<script>``.
16+
17+
NO MOCKS: the tests read the REAL shipped ``components/crud.twig`` and render it
18+
through a REAL ``Frond`` engine. The only things registered on the engine are
19+
template helpers the component references (``RANDOM``, ``formToken``,
20+
``nice_label``, ``detect_image``) — not stand-ins for any external collaborator
21+
— so the assertions run against the exact bytes the framework ships and emits.
22+
"""
23+
import re
24+
from pathlib import Path
25+
26+
import pytest
27+
28+
import tina4_python
29+
from tina4_python.frond import Frond
30+
31+
32+
TEMPLATES_DIR = Path(tina4_python.__file__).parent / "templates"
33+
CRUD_TEMPLATE = TEMPLATES_DIR / "components" / "crud.twig"
34+
35+
# Matches an inline HTML event-handler attribute (onclick=, onsubmit=, …) but
36+
# NOT a JS property assignment (``el.onclick = fn``), which is CSP-allowed.
37+
_INLINE_HANDLER_ATTR = re.compile(r"""\son[a-z]+\s*=\s*["']""")
38+
39+
# A record whose text carries BOTH a single and a double quote, so the
40+
# data-record JSON payload is exercised against attribute-quoting hazards.
41+
RECORDS = [
42+
{"id": 1, "name": "Alice's \"Gadget\"", "email": "alice@example.com"},
43+
{"id": 2, "name": "Bob", "email": "bob@example.com"},
44+
]
45+
COLUMNS = [
46+
{"name": "id", "type": "integer"},
47+
{"name": "name", "type": "text"},
48+
{"name": "email", "type": "text"},
49+
]
50+
51+
52+
class _AttrDict(dict):
53+
"""dict whose keys are also attribute-readable (Frond's ``a.b`` → ``a['b']``)."""
54+
55+
def __getattr__(self, item):
56+
return self.get(item)
57+
58+
59+
def _engine():
60+
"""A real Frond engine pointed at the shipped framework templates, with the
61+
CRUD component's template helpers registered on THIS instance only."""
62+
engine = Frond(template_dir=str(TEMPLATES_DIR))
63+
engine.add_filter("nice_label", lambda v, *a: str(v).replace("_", " ").title())
64+
# detect_image reports "not an image" so the loops take the plain-value path.
65+
engine.add_filter(
66+
"detect_image",
67+
lambda v, *a: _AttrDict(content_type=None, content="", mime_type=""),
68+
)
69+
engine.add_filter("formToken", lambda v, *a: "test-token")
70+
engine.add_global("formToken", lambda *a, **k: "test-token")
71+
engine.add_global("RANDOM", lambda *a, **k: "RND123")
72+
return engine
73+
74+
75+
def _render(card_view=True):
76+
# card_view=True renders the record rows (the card branch) so the per-row
77+
# Update/Delete buttons appear in the rendered output.
78+
data = {
79+
"table_name": "widget",
80+
"columns": COLUMNS,
81+
"records": RECORDS,
82+
"total_records": len(RECORDS),
83+
"options": {"limit": 10, "search": "", "card_view": card_view},
84+
}
85+
return _engine().render("components/crud.twig", data)
86+
87+
88+
def test_shipped_template_source_has_no_inline_event_handler_attributes():
89+
"""The whole shipped file — both the table AND card branches, the modal
90+
form, the pagination — carries zero inline on*= attributes. This is the
91+
mutation gate: restore any onclick=/onsubmit= and this turns red."""
92+
source = CRUD_TEMPLATE.read_text(encoding="utf-8")
93+
offenders = _INLINE_HANDLER_ATTR.findall(source)
94+
assert offenders == [], f"inline on*= attribute(s) in crud.twig: {offenders}"
95+
96+
97+
def test_rendered_component_has_no_inline_event_handler_attributes():
98+
html = _render()
99+
offenders = _INLINE_HANDLER_ATTR.findall(html)
100+
assert offenders == [], f"inline on*= handler attribute(s) emitted: {offenders}"
101+
102+
103+
def test_buttons_wire_their_actions_with_data_attributes():
104+
html = _render()
105+
# Create / Update / Delete are addressed by data-crud-action, not onclick.
106+
assert 'data-crud-action="add"' in html
107+
assert 'data-crud-action="edit"' in html
108+
assert 'data-crud-action="delete"' in html
109+
# Edit carries its per-row payload + index as data-*, delete carries the id.
110+
assert "data-record='" in html
111+
assert 'data-index="' in html
112+
assert 'data-id="' in html
113+
114+
115+
def test_delegated_listener_is_wired_in_a_nonced_script():
116+
html = _render()
117+
assert "<script nonce=" in html # the script that carries the wiring is nonce'd
118+
# A single delegated click listener on the persistent container dispatches
119+
# add / edit / delete and parses the row payload back out of data-record.
120+
assert "addEventListener('click'" in html
121+
assert "data-crud-action" in html
122+
assert "JSON.parse(button.dataset.record)" in html
123+
assert "addRecord" in html and "loadRecord" in html and "confirmDelete" in html
124+
# The modal form's native submit is stopped by a listener, not onsubmit=.
125+
assert "addEventListener('submit'" in html
126+
127+
128+
def test_pagination_link_built_without_inline_onclick():
129+
html = _render()
130+
# The JS-generated pager uses createElement + addEventListener, never an
131+
# inline onclick= baked into innerHTML.
132+
assert "createElement('a')" in html
133+
assert "link.addEventListener('click'" in html
134+
assert "onclick=\"window[" not in html
135+
assert "li.innerHTML = `<a" not in html
136+
137+
138+
def test_row_payload_is_json_safe_in_the_data_attribute():
139+
"""The edit payload rides in data-record as JSON-safe text: a single quote
140+
in the data is escaped (\\u0027) so it can never break out of the
141+
single-quoted attribute into a new handler."""
142+
html = _render()
143+
assert "\\u0027" in html # Alice's apostrophe, JSON-escaped
144+
assert "data-record='{" in html # the JSON object opens inside the attr
145+
# The raw apostrophe must NOT appear unescaped inside data-record (would
146+
# otherwise close the attribute).
147+
assert "Alice's" not in html

‎tests/test_csp_default_warning.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,9 +89,12 @@ def test_default_csp_warns_exactly_once(capfd):
8989
captured = capfd.readouterr()
9090
hits = (captured.out + captured.err).count(WARNING_MARK)
9191
assert hits == 1, f"expected the default-CSP warning exactly once, saw {hits}"
92-
# Behaviour unchanged: the header is still the secure default on every response.
92+
# Behaviour unchanged: the header is still the secure default on every
93+
# response — now with a per-response nonce in style-src/script-src (ADR-0088).
9394
for r in responses:
94-
assert _header(r, "content-security-policy") == "default-src 'self'"
95+
csp = _header(r, "content-security-policy")
96+
assert csp.startswith("default-src 'self'"), csp
97+
assert "style-src 'self' 'nonce-" in csp and "script-src 'self' 'nonce-" in csp, csp
9598

9699

97100
def test_set_csp_does_not_warn(capfd, monkeypatch):
@@ -103,4 +106,9 @@ def test_set_csp_does_not_warn(capfd, monkeypatch):
103106
assert WARNING_MARK not in (captured.out + captured.err), (
104107
"setting TINA4_CSP is an explicit opt-in and must not warn"
105108
)
106-
assert _header(r, "content-security-policy") == "default-src 'self' https://api.example"
109+
# The user policy is honoured and the framework's nonce is added to
110+
# style-src/script-src so its own inline content still runs (ADR-0088).
111+
csp = _header(r, "content-security-policy")
112+
assert csp.startswith("default-src 'self' https://api.example"), csp
113+
assert "style-src 'self' https://api.example 'nonce-" in csp, csp
114+
assert "script-src 'self' https://api.example 'nonce-" in csp, csp

‎tests/test_csp_nonce_inline.py‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# Copyright (c) 2026 Code Infinity
2+
# SPDX-License-Identifier: MPL-2.0
3+
# This Source Code Form is subject to the terms of the Mozilla Public
4+
# License, v. 2.0. If a copy of the MPL was not distributed with this
5+
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
6+
7+
"""The framework's own inline content runs under the strict default CSP (ADR-0088).
8+
9+
The framework serves ``default-src 'self'`` by default. A browser refuses every
10+
inline ``<style>``/``<script>`` under that policy unless the element carries a
11+
nonce the ``Content-Security-Policy`` header also names. So the framework mints
12+
one nonce per response, injects ``'nonce-<X>'`` into style-src AND script-src,
13+
and stamps the SAME value on every inline ``<style>``/``<script>`` it emits. It
14+
also de-inlines every ``style="..."`` attribute, because a nonce covers a
15+
``<style>`` ELEMENT but never a style attribute.
16+
17+
NO MOCKS: a real project served by ``run()``'s own server over real HTTP. The
18+
welcome page at ``/`` is the page the reported bug rendered unstyled.
19+
"""
20+
import http.client
21+
import re
22+
23+
import pytest
24+
25+
from conftest import boot_child_server
26+
27+
# A project with NO "/" route, so GET / falls through to the framework's own
28+
# welcome page (served at "/" in dev mode).
29+
APP = "from tina4_python.core import run\nif __name__ == '__main__':\n run()\n"
30+
31+
32+
def _write_app(project_dir, port):
33+
(project_dir / "app.py").write_text(APP)
34+
35+
36+
@pytest.fixture(scope="module")
37+
def served(tmp_path_factory):
38+
root = tmp_path_factory.mktemp("csp_nonce_inline")
39+
process, port = boot_child_server(
40+
root, _write_app,
41+
extra_env=lambda port: {
42+
"TINA4_DEBUG": "true",
43+
"TINA4_AUTO_MIGRATE": "false",
44+
"TINA4_NO_BROWSER": "true",
45+
"TINA4_OVERRIDE_CLIENT": "true",
46+
"TINA4_SECRET": "csp-nonce-secret-0123456789abcdef",
47+
},
48+
unset_env=("TINA4_CSP",),
49+
log_dir=root / "logs",
50+
)
51+
try:
52+
yield port
53+
finally:
54+
process.terminate()
55+
process.wait(timeout=15)
56+
57+
58+
def _get(port, path="/"):
59+
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=15)
60+
connection.request("GET", path)
61+
reply = connection.getresponse()
62+
body = reply.read().decode("utf-8", "replace")
63+
headers = {name.lower(): value for name, value in reply.getheaders()}
64+
connection.close()
65+
return reply.status, headers, body
66+
67+
68+
def _csp_nonce(csp):
69+
match = re.search(r"'nonce-([^']+)'", csp)
70+
return match.group(1) if match else None
71+
72+
73+
def test_welcome_csp_header_carries_a_nonce_in_style_and_script_src(served):
74+
status, headers, _ = _get(served)
75+
assert status == 200, status
76+
csp = headers["content-security-policy"]
77+
assert "default-src 'self'" in csp, csp
78+
directives = {d.strip().split()[0]: d.strip() for d in csp.split(";") if d.strip()}
79+
assert "'nonce-" in directives.get("style-src", ""), csp
80+
assert "'nonce-" in directives.get("script-src", ""), csp
81+
assert "'unsafe-inline'" not in csp, csp
82+
83+
84+
def test_welcome_inline_style_and_script_carry_the_header_nonce(served):
85+
status, headers, body = _get(served)
86+
assert status == 200, status
87+
nonce = _csp_nonce(headers["content-security-policy"])
88+
assert nonce, headers["content-security-policy"]
89+
90+
# Every inline <style>/<script> the framework emits must carry THIS nonce.
91+
# An external <script src=...> (the dev toolbar) is exempt and must NOT be
92+
# forced to carry one, so only inspect tags with no src attribute.
93+
inline_style_open = re.findall(r"<style\b([^>]*)>", body, re.IGNORECASE)
94+
inline_script_open = re.findall(r"<script\b([^>]*)>", body, re.IGNORECASE)
95+
assert inline_style_open, "welcome page emitted no <style>"
96+
assert inline_script_open, "welcome page emitted no <script>"
97+
98+
for attrs in inline_style_open:
99+
assert f'nonce="{nonce}"' in attrs, f"<style{attrs}> missing the header nonce"
100+
for attrs in inline_script_open:
101+
if "src=" in attrs:
102+
continue # external script needs no nonce
103+
assert f'nonce="{nonce}"' in attrs, f"<script{attrs}> missing the header nonce"
104+
105+
106+
def test_welcome_page_emits_no_inline_style_attribute(served):
107+
status, _, body = _get(served)
108+
assert status == 200, status
109+
# The welcome page is framework-served HTML; the dev toolbar it injects is
110+
# itself CSP-clean (external link + script), so zero style= is the contract.
111+
assert 'style="' not in body, "framework welcome page still emits a style= attribute"
112+
# An inline event handler is an attribute like onclick="..."; a nonce does
113+
# not cover it, so the framework must bind via addEventListener instead.
114+
assert 'onclick="' not in body, (
115+
"framework welcome page still emits an inline onclick handler"
116+
)
117+
118+
119+
def test_each_response_gets_a_distinct_nonce(served):
120+
_, h1, _ = _get(served)
121+
_, h2, _ = _get(served)
122+
n1 = _csp_nonce(h1["content-security-policy"])
123+
n2 = _csp_nonce(h2["content-security-policy"])
124+
assert n1 and n2 and n1 != n2, f"nonce reused across responses: {n1}"

0 commit comments

Comments
 (0)