|
| 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 |
0 commit comments