Skip to content
Myr

Merge pull request from GHSA-h75v-3vvj-5mfj

Before adoption: this commit came in with the history the project adopted, so no landing records it.

disallow invalid characters in keys to xmlattr filter

authored by David Lord · committed by GitHub · parents a7863ba, d655030 · Browse files · 3 files+29 added−10 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+29 added−10 removed

  • tests:+6 added−5 removed
  • other:+23 added−5 removed

3 files+29 added−10 removed

modified:src/jinja2/filters.py+17 added-5 removed
248 unmodified lines
249250 yield from value.items()251252253_space_re = re.compile(r"\s", flags=re.ASCII)253# Check for characters that would move the parser state from key to value.254# https://html.spec.whatwg.org/#attribute-name-state255_attr_key_re = re.compile(r"[\s/>=]", flags=re.ASCII)256257258@pass_eval_context259def do_xmlattr(260 eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True261) -> str:262 """Create an SGML/XML attribute string based on the items in a dict.263262 If any key contains a space, this fails with a ``ValueError``. Values that263 are neither ``none`` nor ``undefined`` are automatically escaped.264 **Values** that are neither ``none`` nor ``undefined`` are automatically265 escaped, safely allowing untrusted user input.266267 User input should not be used as **keys** to this filter. If any key268 contains a space, ``/`` solidus, ``>`` greater-than sign, or ``=`` equals269 sign, this fails with a ``ValueError``. Regardless of this, user input270 should never be used as keys to this filter, or must be separately validated271 first.272273 .. sourcecode:: html+jinja274275 <ul{{ {'class': 'my_list', 'missing': none,276 'id': 'list-%d'|format(variable)}|xmlattr }}>
10 unmodified lines
287288 As you can see it automatically prepends a space in front of the item289 if the filter returned something unless the second parameter is false.290291 .. versionchanged:: 3.1.4292 Keys with ``/`` solidus, ``>`` greater-than sign, or ``=`` equals sign293 are not allowed.294295 .. versionchanged:: 3.1.3296 Keys with spaces are not allowed.297 """298 items = []
1 unmodified line
300 for key, value in d.items():301 if value is None or isinstance(value, Undefined):302 continue303292 if _space_re.search(key) is not None:293 raise ValueError(f"Spaces are not allowed in attributes: '{key}'")304 if _attr_key_re.search(key) is not None:305 raise ValueError(f"Invalid character in attribute name: {key!r}")306307 items.append(f'{escape(key)}="{escape(value)}"')308309 rv = " ".join(items)
1557 unmodified lines
modified:tests/test_filters.py+6 added-5 removed
472 unmodified lines
473 assert 'foo="42"' in out474 assert 'bar="23"' in out475 assert 'blub:blub="&lt;?&gt;"' in out476477 def test_xmlattr_key_with_spaces(self, env):478 with pytest.raises(ValueError, match="Spaces are not allowed"):479 env.from_string(480 "{{ {'src=1 onerror=alert(1)': 'my_class'}|xmlattr }}"481 ).render()477 @pytest.mark.parametrize("sep", ("\t", "\n", "\f", " ", "/", ">", "="))478 def test_xmlattr_key_invalid(self, env: Environment, sep: str) -> None:479 with pytest.raises(ValueError, match="Invalid character"):480 env.from_string("{{ {key: 'my_class'}|xmlattr }}").render(481 key=f"class{sep}onclick=alert(1)"482 )483484 def test_sort1(self, env):485 tmpl = env.from_string("{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}")486 assert tmpl.render() == "[1, 2, 3]|[3, 2, 1]"
396 unmodified lines
modified:CHANGES.rst+6 added
3 unmodified lines
4-------------56Unreleased78- The ``xmlattr`` filter does not allow keys with ``/`` solidus, ``>``9 greater-than sign, or ``=`` equals sign, in addition to disallowing spaces.10 Regardless of any validation done by Jinja, user input should never be used11 as keys to this filter, or must be separately validated first.12 GHSA-h75v-3vvj-5mfj131415Version 3.1.316-------------1718Released 2024-01-10
981 unmodified lines