Security, templates and XSS prevention


Ensuring that you don't fall victim to cross site scripting and other injection attacks takes vigilance, eye for details and especially some good naming habits.


A small mistake can open the flood gates of attacks to your website. Common errors are cross site scripting attacks (xss).


Readers are assumed to be comfortable in writing or editing templates.


If we have the following request:

For the dispatch rule:

{page, [ "page", id ], contoller_page, []}

Then in the template we can access the query arguments:

Hello {{|escape }} your id is {{|escape }}.
Controller page said the resource id is {{ id }}.

You see  that and are both escaped before they are shown. But id is not.

This is because and both contain unfiltered content supplied by the user. This content could even be a complete script tag that transfers the users information to some other server or modified content on our site. To prevent this we apply the escape filter to the content so that input like:

Will not add the following script tag to the HTML:


But instead the escape filter transforms it into the following safe HTML text:


But why was id not escaped? The id provided by controller_page is the output of the mapping of to a resource id, using the function m_rsc:rid/2 function. The output of this function is either a number or undefined, so doesn't need any further escaping when used.

Special care

There are more functions that can give unfiltered user input back to the template. Examples are m.req, m.identity (for example email addresses which can contain HTML unsafe characters), and exif or other metadata in the medium records.

A good habit is to prefix all untrusted content with a q, like this:

{% with id| as qid %} {# is unsafe #}
{% with m.rsc[id|].id as id %} {# The m.rsc lookup ensure a safe mapping #}

And NEVER something like this:

{% with id| as id %} {# DO NOT DO THIS #}

Why not?  In templates we have the shorthand:

{{ q.title }}

And templates might be rendered using API calls, which can pass structured data for the query arguments like the following JSON:

{ "id": { "title": "<script>...</script>" } }

It is clear that this is not something you want to echo directly in your templates.

Why is m.rsc safe?

As a rule of thumb all data inside m.rsc is safe to echo in the templates. This is because all data stored into resource records is sanitized. The sanitization removes or escapes all dangerous content. For exampe, HTML body texts have malicious content like scripts and iframes without a white-listed domain removed. All HTML attributes that might contain scripts are removed or cleaned, and css is also cleaned up to remove external content references.

An exception is content that is postfixed with ..._unsafe.  Like myprop_unsafe. This content is passed as-is through the sanitizer without any modification.