tera icon indicating copy to clipboard operation
tera copied to clipboard

Escaping is not applied at the expected level

Open WesleyAC opened this issue 1 year ago • 5 comments

I found the following tera template very surprising when evaluated with the default autoescaping:

{% set foo = 'def' %}
{{ 'abcdef' == 'abc' ~ foo }}
{{ 'abc/def' == 'abc/' ~ 'def' }}
{{ 'abc/def' == 'abc/' ~ foo }}

It returns:

true
true
false

This is because the last statement is evaluating 'abcdef' == 'abc/def'

There are two behaviours that would seem roughly sensible to me here:

  • foo is escaped, equaling foo (since it does not have any special characters), then the rest of the statement is evaluated.
  • The entire statement is evaluated, and because it's tainted with a unsafe value, the entire result (true) is escaped.

The first seems most sensible to me, but the latter would also be defensible, in my opinion.

The actual behavior seems very strange, where the escaping happens at some kind of intermediate level, determining that the RHS of the expression is tainted and escaping the entire thing before evaluating the rest of the expression. This appears to be a bug to me.

WesleyAC avatar Feb 06 '24 19:02 WesleyAC

In the unlikely event that anyone manages to find this issue and is wondering how to work around this, creating a temporary variable with safe seems to be the way to go:

{% set tmp = 'abc/' ~ foo | safe %}
{{ 'abc/def' == tmp }}

WesleyAC avatar Feb 06 '24 19:02 WesleyAC

I've added those tests in https://github.com/Keats/tera2 and it return true for all 3 rows as escaping is now done only when writing to the buffer.

Keats avatar Feb 06 '24 20:02 Keats

Great! Do you have a rough idea of when Tera 2 will start to be ready for use?

WesleyAC avatar Feb 07 '24 01:02 WesleyAC

Not for a few months at least, when it's ready it's going to be used in Zola first before releasing 2.0.0 to make sure it's battle tested

Keats avatar Feb 07 '24 10:02 Keats

I believe I have found a bug similar to this:

{{  foo.bar | default(value=foo.baz) }}

foo.baz will be escaped TWICE if foo.bar is not present.

It works perfectly this way:

{% if foo.bar %}{{ foo.bar }}{% else %}{{ foo.baz }}{% endif %}

However, it does NOT happen on all templates. I have several templates and it only happens on one. It does not happen on the rest, although they all have identical code.

schungx avatar Jun 13 '24 12:06 schungx