Restricted mode: Avoid variable expressions returning strings in processors for event handlers (th:on*)
See original GitHub issueWhen executing HTML template code such as:
<div th:onclick="|doSomething('${mydata}');|">
The resulting attribute value for onclick
will be correctly HTML-escaped, but the result of ${mydata}
inside that expression will not be escaped as a JavaScript literal because Thymeleaf does not know about the specifics of the JavaScript code written inside this attribute, or whether it is JavaScript code at all.
In some cases, this might lead to confusion from developers who might think their use of ${mydata}
in that code is safe, while from the standpoint of JavaScript code the value of that variable will be output unescaped (only HTML-escaping will be performed, but this is because of it being an HTML attribute). This could lead to unintended code injection scenarios.
In order to help devs avoiding this scenarios, Thymeleaf should extend its restricted expression evaluation mode for all th:on*
attribute processors –for JavaScript event handlers– in order to forbid output of any variable expression that results in anything but a Number
or a Boolean
. This will in effect forbid variable expressions returning String
or any other object that can be rendered as a text literal in a way that wouldn’t be necessarily trustable.
With this, a better way to write the code above would be to use (adequately HTML-escaped) data-
attributes for text literal variables, like:
<div th:data-thing="${mydata}" onclick="doSomething(this.getAttribute('data-thing'));">
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:7 (1 by maintainers)
Top GitHub Comments
This seems an extreme change for a patch release
It still works if you put a link expression around it. I doubt this is intended though.
<div th:onclick="@{doSomething('${mydata}');}">