From ec16d210e7e13f862eccdb0bc9af9f60ff6749d6 Mon Sep 17 00:00:00 2001 From: Frankie Dintino Date: Wed, 12 Apr 2023 14:31:51 -0400 Subject: [PATCH] fix: html encode backslashes if used with escape filter or autoescape (#1437) Backslashes should be html encoded when present in expressions that are passed to the escape filter (including when this happens automatically with autoescape) --- CHANGELOG.md | 7 +++++++ nunjucks/src/lib.js | 5 +++-- tests/compiler.js | 12 +++++++++++- tests/filters.js | 4 ++-- 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bc4b1ffb..14f929935 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ Changelog ========= +3.2.4 (unreleased) +------------------ + +* HTML encode backslashes when expressions are passed through the escape + filter (including when this is done automatically with autoescape). Merge + of [#1427](https://github.com/mozilla/nunjucks/pull/1427). + 3.2.3 (Feb 15 2021) ------------------- diff --git a/nunjucks/src/lib.js b/nunjucks/src/lib.js index 376db95aa..e99589f79 100644 --- a/nunjucks/src/lib.js +++ b/nunjucks/src/lib.js @@ -8,10 +8,11 @@ var escapeMap = { '"': '"', '\'': ''', '<': '<', - '>': '>' + '>': '>', + '\\': '\', }; -var escapeRegex = /[&"'<>]/g; +var escapeRegex = /[&"'<>\\]/g; var exports = module.exports = {}; diff --git a/tests/compiler.js b/tests/compiler.js index 8e133e7f7..62f0aa912 100644 --- a/tests/compiler.js +++ b/tests/compiler.js @@ -1976,6 +1976,16 @@ finish(done); }); + it('should autoescape backslashes', function(done) { + equal( + '{{ foo }}', + { foo: 'foo \\\' bar' }, + { autoescape: true }, + 'foo \' bar'); + + finish(done); + }); + it('should not autoescape when extension set false', function(done) { function TestExtension() { // jshint validthis: true @@ -2031,7 +2041,7 @@ }); it('should render regexs', function(done) { - equal('{{ r/name [0-9] \\// }}', + equal('{{ r/name [0-9] \\// }}', {}, { autoescape: false }, '/name [0-9] \\//'); equal('{{ r/x/gi }}', diff --git a/tests/filters.js b/tests/filters.js index 6a975a185..554c10dd1 100644 --- a/tests/filters.js +++ b/tests/filters.js @@ -108,9 +108,9 @@ it('escape', function() { equal( - '{{ "" | escape }}', {}, + '{{ "\\\\" | escape }}', {}, { autoescape: false }, - '<html>'); + '<html>\'); }); it('escape skip safe', function() {