Files
FabledSteward/tests/test_inline_handlers.py
T
bvandeusenandClaude Opus 5.5 f47fc23265 fix(ui): delete prompts use data-confirm, so a quote in a name no longer runs script (#5099)
#5099 "A name containing a quote runs script when an admin clicks Delete".
Inline handlers like onclick="return confirm('Delete {{ rule.name }}?')" are
HTML-decoded before the JavaScript is parsed, so autoescaping did not stop a
name such as  x');fetch(…);//  from running.

- Every prompt (22 handlers, plus the docker prune and token revoke ones)
  is now data-confirm="…", read through dataset by one submit listener in
  base.html; nothing rendered is parsed as JavaScript.
- The remaining inline handlers take integers only (|int), and the time
  range buttons pass this.dataset.range.
- tests/test_inline_handlers.py fails on any {{ }} in an inline handler that
  is not |int, with a self-test; tests/_templates.py is the one template
  walker the template guards now share.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 14:30:13 -04:00

44 lines
1.9 KiB
Python

"""No template puts a rendered value into inline JavaScript (#5099).
An onclick/onsubmit attribute is HTML-decoded before its JavaScript is
parsed, so autoescaping does not protect a name placed inside it: a monitor
called x');fetch(…);// ran as script when an admin clicked Delete. A
prompt goes in data-confirm="…" (base.html asks with it); any other value a
handler needs is an integer, rendered with |int.
"""
import re
from tests._templates import REPO as _REPO, template_files as _templates
_HANDLER = re.compile(r"""\bon[a-z]+\s*=\s*("[^"]*"|'[^']*')""", re.I)
_VALUE = re.compile(r"\{\{(.*?)\}\}", re.S)
def unsafe_handler_values(text: str) -> list[str]:
"""Each {{ … }} inside an inline handler that is not an |int."""
return [m.group(0) for h in _HANDLER.finditer(text) for m in _VALUE.finditer(h.group(1))
if not re.search(r"\|\s*int\s*$", m.group(1).strip())]
def test_the_guard_can_fail():
page = """
<button onclick="return confirm('Delete rule {{ rule.name }}?')">x</button>
<form onsubmit='return confirm({{ msg|tojson }})'>
<button onclick="toggle({{ idx|int }})">ok</button>
<button data-confirm="Delete {{ rule.name }}?" data-range="{{ key }}">ok</button>
"""
assert unsafe_handler_values(page) == ["{{ rule.name }}", "{{ msg|tojson }}"]
def test_no_template_renders_a_value_into_an_inline_handler():
files = _templates()
assert len(files) > 100
found = {str(p.relative_to(_REPO)): hits for p in files if (hits := unsafe_handler_values(p.read_text()))}
assert not found, f"use data-confirm, or render an integer with |int: {found}"
def test_base_asks_before_a_data_confirm_form_submits():
base = (_REPO / "steward" / "templates" / "base.html").read_text()
assert "dataset.confirm" in base and "window.confirm(ask)" in base
assert any("data-confirm=" in p.read_text() for p in _templates())