Difference between revisions of "Escaping HTML attribute values in TT views"

From Dreamwidth Notes
Jump to: navigation, search
(New page)
 
(No difference)

Latest revision as of 21:55, 26 March 2015

To avoid accidental or malicious HTML or JS injection, variables or expressions in HTML should be properly escaped, unless you're sure they don't need to. This is finicky because there are several ways to escape depending on what needs to be escaped and where, and they all have quirks.

Text should be escaped if listed in both What to escape and Where and how to escape it.

What to escape

As a rule of thumb, the following should be escaped:

  • All values entered by a user in a form
  • All user content from the database
  • All translation text

For the first 2, you will likely need to check dataflow between the TT view and the controller.

Where and how to escape it

Text values in HTML attributes

This applies to the following HTML tag attributes: value=, for=, id=, label=, name=, alt=, width=, height=, and style=.

Use value="..." instead of value='...' because | html doesn't escape single quotes, and likewise for other attributes.

Use | html to escape.

Text values between <textarea> </textarea>

Use | html to escape.

URL and URL fragment values

This applies to the following HTML tag attributes: href=, action=, and src=.

Use href='...' instead of href="..." because | uri and | url don't escape double quotes, and likewise for other attributes.

Use | uri to escape query arguments (bar in ?foo=bar or &foo=bar), | url for everything else except URLs that contain fragment IDs (the part after #). Note that it's preferable to escape query arguments rather than the full URL, even if you need to do it earlier in the page code.

Variable assignment in JavaScript

Use | js to escape the value assigned. Note that this is actually LJ::ejs_string and as such you don't need to (and in fact shouldn't) include quotes around the value assigned, as it will automatically be made into a JS string constant.