Server-side template injection: pass the text into the template, never build the template from it
Server-side template injection happens when text from a visitor, a customer or a staff member becomes part of a template your server renders, so the template engine reads it as instructions instead of printing it.
This guide explains what a template engine is for, where the flaw comes from, how to tell it from XSS and what the engines' own sandboxes cover. It comes with a Node.js lab, a harmless arithmetic canary and a regression test you can run on your own machine.
In this guide
Template-rendering lab, arithmetic canary and engine checks
An illustration written for this page, not client code. A deliberately tiny stand-in engine renders an invented shop's email preview through a flawed handler that builds the template from the visitor's text and a fixed handler that passes it as a value, with the real output of each.
How to use itHide the instructions
Tests on Node.js's built-in runner show the stand-in engine rejecting every name it was not given, and a regression test fails on the flawed handler and passes on the fixed one. Engine-specific checks for Jinja, Twig, Handlebars, Mustache and Nunjucks follow, each from that engine's own documentation. For learning and for testing a template path you own.
server-side-template-injection.txt
Introduction6 lines
Part 1: The template-rendering lab310 lines
Part 2: The tests195 lines
Part 3: Engine-specific remediation checks43 lines
Whole template572 lines
ILLUSTRATION FOR LEARNING. The hardware shop, its order email and every input below were written for this page. Nothing here is a client's code or a client's result. Run the lab on your own machine to learn, and use what it teaches to test a template path you own. Do not point any part of it at a system you do not own or are not authorised in writing to test.
The asset has three parts:
Part 1 The template-rendering lab: a stand-in engine, a flawed and a fixed handler, and what each one rendered.
Part 2 The tests: one file that checks the stand-in engine rejects everything except supplied values and arithmetic, and a regression test that fails on the flawed handler and passes on the fixed one.
Part 3 Engine-specific remediation checks for Jinja, Twig, Handlebars, Mustache and Nunjucks, each answer taken from that engine's own documentation.
================================================================
PART 1: THE TEMPLATE-RENDERING LAB
================================================================
WHAT IT NEEDS
Node.js, with nothing to install. The files import only node:test, node:assert and node:fs, and the lab installs no packages. The Node.js documentation marks the test runner stable from version 20.0.0. The outputs below were recorded on Node.js v26.0.0 on macOS. Test timings will differ on your machine.
WHY THERE IS A STAND-IN ENGINE
This lab installs no template engine, so engine.mjs is a deliberately tiny one written for it. It stands in for a real engine and is not one. It has double-brace placeholders, as Jinja, Twig and Nunjucks do. Inside a placeholder it accepts a name from the values the code supplied, a number, or arithmetic on those with + - * / and round brackets, and it rejects everything else. It escapes values for HTML. It reads the arithmetic with its own small parser, so no text is ever run as JavaScript. A real engine gives a template far more than this, which is why Part 3 exists.
THE CANARY
The canary is {{ 7*7 }}. Its only effect, if an engine evaluates it, is that the number 49 appears where the visitor's text should have been. WSTG-INPV-18 and CWE-1336 both use the same arithmetic in their examples, written without spaces as {{7*7}}; CWE-1336 gives it as an example for some template languages. On a real page, choose a product that is unlikely to appear by chance, so a match means something.
WHAT IT DOES NOT DO
Nothing here reads a file other than the lab's own engine.mjs, opens a network connection, starts a process or reaches anything outside the values the code passes in. Input I4 names a value the shop's code holds, and input I5 names something nobody supplied, which the stand-in engine rejects.
THE SCENARIO
An invented hardware shop lets a customer add a gift message to an order and shows a preview of the order confirmation email. Two handlers build that preview:
flawed joins the visitor's text into the template source, and gives the template every value the code holds.
fixed keeps the template source fixed, passes the visitor's text as a value called giftMessage, and gives the template only the values it prints.
SET-UP
Create an empty folder, save the six files below into it under the names shown, and open a terminal in that folder.
==== File 1 of 6: engine.mjs ====
// engine.mjs: a deliberately tiny template engine, written for this lab. It
// stands in for a real engine such as Jinja, Twig or Nunjucks and is not one.
// A placeholder is text between double braces. Inside one, the engine
// accepts a name from the values the code supplied, a number, or arithmetic
// on those with + - * / and round brackets. It rejects anything else.
// Values are escaped for HTML. Template text outside placeholders is not,
// because an engine trusts its template. The arithmetic is read by the small
// parser below, so no text is ever run as JavaScript.
export class TemplateError extends Error {
constructor(message) {
super(message)
this.name = 'TemplateError'
}
}
const OPEN = '{{'
const CLOSE = '}}'
const SYMBOLS = ['+', '-', '*', '/', '(', ')']
const HTML_ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }
export function escapeHtml(text) {
return String(text).replace(/[&<>"']/g, (character) => HTML_ENTITIES[character])
}
// Splits a placeholder's text into numbers, names and symbols.
function readTokens(expression) {
const tokens = []
let rest = expression.trim()
while (rest.length > 0) {
const number = /^\d+(\.\d+)?/.exec(rest)
const name = /^[A-Za-z_]\w*/.exec(rest)
let token
if (number) token = { kind: 'number', text: number[0] }
else if (name) token = { kind: 'name', text: name[0] }
else if (SYMBOLS.includes(rest[0])) token = { kind: 'symbol', text: rest[0] }
else throw new TemplateError('character not allowed in a placeholder: ' + rest[0])
tokens.push(token)
rest = rest.slice(token.text.length).trimStart()
}
return tokens
}
// A name must be the code's own value, holding text or a number. Inherited
// properties and anything outside the values object are unknown names.
function lookUpValue(values, name) {
if (!Object.hasOwn(values, name)) throw new TemplateError('unknown name: ' + name)
const value = values[name]
if (typeof value !== 'string' && typeof value !== 'number') {
throw new TemplateError('not text or a number: ' + name)
}
return value
}
function requireNumber(value) {
if (typeof value !== 'number') throw new TemplateError('arithmetic needs numbers, not text')
return value
}
function nextSymbolIn(state, allowed) {
const token = state.tokens[state.index]
if (token && token.kind === 'symbol' && allowed.includes(token.text)) return token.text
return null
}
// sum: a product, then any number of "+ product" or "- product"
function readSum(state) {
let result = readProduct(state)
let operator = nextSymbolIn(state, ['+', '-'])
while (operator) {
state.index += 1
const right = requireNumber(readProduct(state))
const left = requireNumber(result)
result = operator === '+' ? left + right : left - right
operator = nextSymbolIn(state, ['+', '-'])
}
return result
}
// product: a factor, then any number of "* factor" or "/ factor"
function readProduct(state) {
let result = readFactor(state)
let operator = nextSymbolIn(state, ['*', '/'])
while (operator) {
state.index += 1
const right = requireNumber(readFactor(state))
const left = requireNumber(result)
result = operator === '*' ? left * right : left / right
operator = nextSymbolIn(state, ['*', '/'])
}
return result
}
// factor: a number, a supplied name, "- factor" or "( sum )"
function readFactor(state) {
const token = state.tokens[state.index]
if (!token) throw new TemplateError('placeholder ends too early')
state.index += 1
if (token.kind === 'number') return Number(token.text)
if (token.kind === 'name') return lookUpValue(state.values, token.text)
if (token.text === '-') return -requireNumber(readFactor(state))
if (token.text === '(') return readBracketed(state)
throw new TemplateError('unexpected ' + token.text)
}
function readBracketed(state) {
const inner = readSum(state)
if (nextSymbolIn(state, [')']) === null) throw new TemplateError('missing )')
state.index += 1
return inner
}
export function evaluatePlaceholder(expression, values) {
const state = { tokens: readTokens(expression), index: 0, values: values }
if (state.tokens.length === 0) throw new TemplateError('empty placeholder')
const result = readSum(state)
if (state.index < state.tokens.length) {
throw new TemplateError('unexpected ' + state.tokens[state.index].text)
}
if (typeof result === 'number' && !Number.isFinite(result)) {
throw new TemplateError('result is not a finite number')
}
return result
}
// Copies template text as it is and replaces each placeholder with its
// escaped result. A value is inserted as text and never read as a template.
export function renderTemplate(source, values) {
let output = ''
let position = 0
while (position < source.length) {
const start = source.indexOf(OPEN, position)
if (start === -1) return output + source.slice(position)
const end = source.indexOf(CLOSE, start + OPEN.length)
if (end === -1) throw new TemplateError('placeholder is not closed')
output += source.slice(position, start)
output += escapeHtml(evaluatePlaceholder(source.slice(start + OPEN.length, end), values))
position = end + CLOSE.length
}
return output
}
==== File 2 of 6: handlers.mjs ====
// handlers.mjs: two ways for an invented hardware shop to show a customer's
// gift message in an order confirmation email preview. Each handler returns
// the template source and the values it would render. The flawed handler is
// wrong on purpose: run it only on your own machine and never copy it into
// an application.
// What the shop's code knows about the order. internalNote is there to show
// what a template can read when it is given more than it needs.
export const ORDER = {
customer: "Sam O'Neill",
orderNumber: 1042,
internalNote: 'Staff only: repeat customer, check stock before dispatch',
}
const EMAIL_START = '<p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: '
const EMAIL_END = '</p>'
// Flawed: the visitor's text is joined into the template source, and the
// template is given every value the code holds.
export function previewFlawed(giftMessage) {
return { source: EMAIL_START + giftMessage + EMAIL_END, values: ORDER }
}
// Fixed: the template never changes, the visitor's text is passed as a
// value, and the template is given only the values it prints.
const FIXED_SOURCE = EMAIL_START + '{{ giftMessage }}' + EMAIL_END
export function previewFixed(giftMessage) {
const values = { customer: ORDER.customer, orderNumber: ORDER.orderNumber, giftMessage: giftMessage }
return { source: FIXED_SOURCE, values: values }
}
export const HANDLERS = { flawed: previewFlawed, fixed: previewFixed }
==== File 3 of 6: inputs.mjs ====
// inputs.mjs: what the visitor types into the gift message box. I3 is the
// canary: harmless arithmetic whose only effect, if an engine evaluates it,
// is that a number appears where the text should have been.
export const INPUTS = [
{ id: 'I1', label: 'ordinary message', text: 'Happy birthday, Alex!' },
{ id: 'I2', label: 'markup', text: 'See you <b>soon</b>' },
{ id: 'I3', label: 'arithmetic canary', text: '{{ 7*7 }}' },
{ id: 'I4', label: 'a value the code holds', text: '{{ internalNote }}' },
{ id: 'I5', label: 'a name nobody supplied', text: '{{ constructor }}' },
{ id: 'I6', label: 'unclosed braces', text: 'Love you {{' },
]
==== File 4 of 6: compare.mjs ====
// compare.mjs: sends each input through both handlers and prints the
// template source the engine was given and what it rendered.
import { renderTemplate } from './engine.mjs'
import { HANDLERS } from './handlers.mjs'
import { INPUTS } from './inputs.mjs'
function renderOrReject(prepared) {
try {
return renderTemplate(prepared.source, prepared.values)
} catch (error) {
return 'REJECTED (' + error.message + ')'
}
}
for (const input of INPUTS) {
console.log(input.id + ' ' + input.label)
console.log(' visitor typed: ' + input.text)
for (const handlerName of Object.keys(HANDLERS)) {
const prepared = HANDLERS[handlerName](input.text)
console.log(' ' + handlerName + ' handler')
console.log(' template source: ' + prepared.source)
console.log(' rendered: ' + renderOrReject(prepared))
}
console.log('')
}
STEP 1: compare the two handlers
Command: node compare.mjs
I1 ordinary message
visitor typed: Happy birthday, Alex!
flawed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: Happy birthday, Alex!</p>
rendered: <p>Hi Sam O'Neill, order 1042 is confirmed. Your gift message: Happy birthday, Alex!</p>
fixed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: {{ giftMessage }}</p>
rendered: <p>Hi Sam O'Neill, order 1042 is confirmed. Your gift message: Happy birthday, Alex!</p>
I2 markup
visitor typed: See you <b>soon</b>
flawed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: See you <b>soon</b></p>
rendered: <p>Hi Sam O'Neill, order 1042 is confirmed. Your gift message: See you <b>soon</b></p>
fixed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: {{ giftMessage }}</p>
rendered: <p>Hi Sam O'Neill, order 1042 is confirmed. Your gift message: See you <b>soon</b></p>
I3 arithmetic canary
visitor typed: {{ 7*7 }}
flawed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: {{ 7*7 }}</p>
rendered: <p>Hi Sam O'Neill, order 1042 is confirmed. Your gift message: 49</p>
fixed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: {{ giftMessage }}</p>
rendered: <p>Hi Sam O'Neill, order 1042 is confirmed. Your gift message: {{ 7*7 }}</p>
I4 a value the code holds
visitor typed: {{ internalNote }}
flawed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: {{ internalNote }}</p>
rendered: <p>Hi Sam O'Neill, order 1042 is confirmed. Your gift message: Staff only: repeat customer, check stock before dispatch</p>
fixed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: {{ giftMessage }}</p>
rendered: <p>Hi Sam O'Neill, order 1042 is confirmed. Your gift message: {{ internalNote }}</p>
I5 a name nobody supplied
visitor typed: {{ constructor }}
flawed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: {{ constructor }}</p>
rendered: REJECTED (unknown name: constructor)
fixed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: {{ giftMessage }}</p>
rendered: <p>Hi Sam O'Neill, order 1042 is confirmed. Your gift message: {{ constructor }}</p>
I6 unclosed braces
visitor typed: Love you {{
flawed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: Love you {{</p>
rendered: REJECTED (placeholder is not closed)
fixed handler
template source: <p>Hi {{ customer }}, order {{ orderNumber }} is confirmed. Your gift message: {{ giftMessage }}</p>
rendered: <p>Hi Sam O'Neill, order 1042 is confirmed. Your gift message: Love you {{</p>
exit code: 0
READING THE OUTPUT
Read the "template source" lines first. The flawed handler's template is different for every input, because it is built from the input. The fixed handler's template never changes. Everything else follows from that.
I1 Both handlers render the ordinary message the same way, so a test that only tries ordinary text passes on both. The apostrophe in the customer's name is escaped by both, because the name is always a value.
I2 The flawed handler puts the visitor's bold tags into the template itself. An engine copies template text as it is, so the markup reaches the page: the symptom that makes template injection look like cross-site scripting. The fixed handler escapes it.
I3 The canary. The flawed handler rendered 49, so the server evaluated the visitor's text. The fixed handler rendered the braces as typed.
I4 The flawed handler printed a staff-only note, because the visitor's text could name any value the template was given. The fixed handler showed the braces as typed, and its template was never given the note.
I5 The stand-in engine refused a name nobody supplied, so the flawed handler's page did not render at all. A real engine may print nothing, raise an error or resolve the name to something it can reach: Part 3 says what to check for yours.
I6 Two stray braces broke the flawed handler's page. The fixed handler showed them as text.
================================================================
PART 2: THE TESTS
================================================================
==== File 5 of 6: engine.test.mjs ====
// engine.test.mjs: checks the lab engine itself. A placeholder may hold a
// supplied value, a number or arithmetic. Every other name or symbol is
// rejected, and values come out as escaped text.
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { test } from 'node:test'
import { renderTemplate, TemplateError } from './engine.mjs'
const VALUES = { customer: 'Sam', itemCount: 3 }
function assertRejected(source, values) {
assert.throws(() => renderTemplate(source, values), TemplateError, source)
}
test('arithmetic on numbers and supplied numbers is evaluated', () => {
assert.equal(renderTemplate('{{ 7*7 }}', VALUES), '49')
assert.equal(renderTemplate('{{ (2 + 3) * 4 - 1 }}', VALUES), '19')
assert.equal(renderTemplate('{{ itemCount * 2 }}', VALUES), '6')
})
test('a supplied value is printed as escaped text', () => {
const html = renderTemplate('{{ customer }}', { customer: '<b>Sam & "Jo"</b>' })
assert.equal(html, '<b>Sam & "Jo"</b>')
})
test('a value is never read as a template', () => {
assert.equal(renderTemplate('{{ customer }}', { customer: '{{ 7*7 }}' }), '{{ 7*7 }}')
})
test('a name the code did not supply is rejected', () => {
const names = ['missing', 'constructor', 'toString', '__proto__', 'hasOwnProperty', 'process', 'globalThis', 'require']
for (const name of names) assertRejected('{{ ' + name + ' }}', VALUES)
})
test('an inherited property is rejected even though it exists', () => {
const values = Object.create({ inherited: 'from the prototype' })
values.customer = 'Sam'
assertRejected('{{ inherited }}', values)
})
test('a supplied value that is not text or a number is rejected', () => {
assertRejected('{{ customer }}', { customer: { first: 'Sam' } })
assertRejected('{{ customer }}', { customer: function () { return 'Sam' } })
})
test('anything other than names, numbers and arithmetic is rejected', () => {
const expressions = ['customer.length', 'customer()', '"text"', 'itemCount = 1', '7 ** 2', '1; 2', 'customer + 1', '1 / 0', '']
for (const expression of expressions) assertRejected('{{ ' + expression + ' }}', VALUES)
})
test('the engine evaluates without eval, Function or node:vm', () => {
const code = readFileSync(new URL('./engine.mjs', import.meta.url), 'utf8')
for (const forbidden of ['eval(', 'Function(', 'node:vm', 'import ', 'require(']) {
assert.equal(code.includes(forbidden), false, 'engine.mjs contains ' + forbidden)
}
})
==== File 6 of 6: preview.test.mjs ====
// preview.test.mjs: a regression test for the handler LAB_HANDLER names,
// flawed or fixed (fixed when it is not set). It fails for the flawed
// handler and passes for the fixed one.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { escapeHtml, renderTemplate } from './engine.mjs'
import { HANDLERS } from './handlers.mjs'
import { INPUTS } from './inputs.mjs'
const handlerName = process.env.LAB_HANDLER || 'fixed'
const handler = HANDLERS[handlerName]
const sourceForPlainText = handler('plain text').source
for (const input of INPUTS) {
test(input.id + ' ' + input.label + ': the template source does not change', () => {
assert.equal(handler(input.text).source, sourceForPlainText)
})
test(input.id + ' ' + input.label + ': the message shows as typed', () => {
const prepared = handler(input.text)
const html = renderTemplate(prepared.source, prepared.values)
assert.ok(html.includes(escapeHtml(input.text)), handlerName + ' rendered: ' + html)
})
}
STEP 2: test the stand-in engine
Command: node --test engine.test.mjs
✔ arithmetic on numbers and supplied numbers is evaluated (0.910375ms)
✔ a supplied value is printed as escaped text (0.064875ms)
✔ a value is never read as a template (0.0505ms)
✔ a name the code did not supply is rejected (0.2245ms)
✔ an inherited property is rejected even though it exists (0.063916ms)
✔ a supplied value that is not text or a number is rejected (0.055791ms)
✔ anything other than names, numbers and arithmetic is rejected (0.105542ms)
✔ the engine evaluates without eval, Function or node:vm (0.142875ms)
ℹ tests 8
ℹ suites 0
ℹ pass 8
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 82.272709
exit code: 0
STEP 3: run the regression test against the fixed handler
Command: node --test preview.test.mjs
✔ I1 ordinary message: the template source does not change (0.658917ms)
✔ I1 ordinary message: the message shows as typed (0.271167ms)
✔ I2 markup: the template source does not change (0.039292ms)
✔ I2 markup: the message shows as typed (0.0655ms)
✔ I3 arithmetic canary: the template source does not change (0.040292ms)
✔ I3 arithmetic canary: the message shows as typed (0.05075ms)
✔ I4 a value the code holds: the template source does not change (0.033917ms)
✔ I4 a value the code holds: the message shows as typed (0.042458ms)
✔ I5 a name nobody supplied: the template source does not change (0.091791ms)
✔ I5 a name nobody supplied: the message shows as typed (0.084333ms)
✔ I6 unclosed braces: the template source does not change (0.039417ms)
✔ I6 unclosed braces: the message shows as typed (0.03525ms)
ℹ tests 12
ℹ suites 0
ℹ pass 12
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 81.885208
exit code: 0
STEP 4: run it against the flawed handler
Command: LAB_HANDLER=flawed node --test preview.test.mjs
✖ I1 ordinary message: the template source does not change (1.3565ms)
✔ I1 ordinary message: the message shows as typed (0.2835ms)
✖ I2 markup: the template source does not change (0.085958ms)
✖ I2 markup: the message shows as typed (0.061958ms)
✖ I3 arithmetic canary: the template source does not change (0.067584ms)
✖ I3 arithmetic canary: the message shows as typed (0.083084ms)
✖ I4 a value the code holds: the template source does not change (0.056333ms)
✖ I4 a value the code holds: the message shows as typed (0.116792ms)
✖ I5 a name nobody supplied: the template source does not change (0.091ms)
✖ I5 a name nobody supplied: the message shows as typed (0.105042ms)
✖ I6 unclosed braces: the template source does not change (0.0735ms)
✖ I6 unclosed braces: the message shows as typed (0.036291ms)
ℹ tests 12
ℹ suites 0
ℹ pass 1
ℹ fail 11
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 88.274
✖ failing tests:
(216 lines of failure reports follow in the full output, one report for each failed test. Two are shown here, each cut after its error message.)
test at preview.test.mjs:19:3
✖ I3 arithmetic canary: the message shows as typed (0.083084ms)
AssertionError [ERR_ASSERTION]: flawed rendered: <p>Hi Sam O'Neill, order 1042 is confirmed. Your gift message: 49</p>
(14 lines cut here: the stack trace, which shows local file paths, and the assertion's property list)
test at preview.test.mjs:19:3
✖ I5 a name nobody supplied: the message shows as typed (0.105042ms)
Error [TemplateError]: unknown name: constructor
(10 lines cut here: the stack trace, which shows local file paths)
exit code: 1
STEP 5: run every test file at once
Command: node --test
With no file named, the test runner finds both .test.mjs files. LAB_HANDLER is not set, so the regression test checks the fixed handler.
(20 result lines cut here, each one marked ✔)
ℹ tests 20
ℹ suites 0
ℹ pass 20
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 88.981
exit code: 0
WHAT THE TESTS PROVE, AND WHAT THEY DO NOT
engine.test.mjs shows a property of the stand-in engine only: a placeholder reaches the values the code supplied, numbers and arithmetic, and nothing else. Names every JavaScript object inherits, such as constructor and toString, the runtime's globals, such as process and globalThis, inherited properties, property access, calls, quotes and assignment are all rejected, and a value is never read as a template. The last test checks that engine.mjs contains no call to eval or Function and no import of node:vm. None of this tells you anything about Jinja, Twig, Handlebars, Mustache, Nunjucks or any other real engine, each of which gives a template far more to work with. For those, use Part 3.
preview.test.mjs is the regression test to keep. It makes two checks per input: the template source must not change with the input, and the message must come back as typed, escaped. The fixed handler passed all twelve. The flawed handler failed eleven: every input changed its template source, the ordinary message included, and five of the six messages did not come back as typed. The process exit code was 1, so the test stops a build in a pipeline.
STEP 6: point the test at your own template path
1. Find every call that builds a template from a string: Environment.from_string() or the Template class in Jinja, a template created from a string such as with createTemplate() in Twig, Handlebars.compile() in Handlebars, and renderString() or compile() in Nunjucks. Trace each string back to where it came from. A constant in your code is fine. Anything that came from a request, a record a customer can edit or a setting staff can change is the flaw.
2. Wrap each render in a function shaped like the handlers: it takes the untrusted text and returns the template name or source and the values.
3. Keep I1 to I6. Add the canary in your own engine's syntax: engines use other delimiters, such as a dollar sign before braces or angle brackets with percent signs, and WSTG-INPV-18 lists several.
4. Replace escapeHtml in the second check with your engine's own escaping, so the test compares like with like.
5. Keep the test in your suite, so a change that builds the template from input again fails a build instead of reaching customers.
================================================================
PART 3: ENGINE-SPECIFIC REMEDIATION CHECKS
================================================================
Four questions for each engine. Each answer comes from that engine's own documentation, opened on 14 November 2026, and the version each page shows is given with the engine's name. Where an answer is this page's advice rather than the documentation's, it says so.
Q1 Is any template source built from input?
Q2 Is a sandbox in use, and what does its documentation say it covers?
Q3 Is auto-escaping on?
Q4 Who can edit templates, and are they treated as code?
JINJA (Python). Documentation for Jinja 3.1.x. Its changelog lists 3.1.6, released 5 March 2025, as the latest version.
Q1 Search for Environment.from_string() and the Template class, which take template source as a string. Jinja allows basic expressions everywhere and calculates with values (its documentation gives {{ 2 * 2 }} as returning 4), so the canary is evaluated wherever input becomes source.
Q2 SandboxedEnvironment. The documentation says it can be used to render untrusted templates, that access to attributes, method calls, operators, mutating data structures and string formatting can be intercepted and prohibited, and that by default it prevents private and internal attribute access. It also says the sandbox alone is not a solution for perfect security: templates can still raise errors, a small template can render a very large output, so run with CPU and memory limits, and Jinja does not understand JavaScript it may output. Pass only the data relevant to the template, mark methods with unsafe() to stop templates calling them, and use ImmutableSandboxedEnvironment to stop templates changing lists and dictionaries. The changelog lists sandbox changes in both 3.1.5 and 3.1.6, so check the installed version.
Q3 The default configuration is no automatic escaping. The documentation encourages configuring it explicitly, and recommends select_autoescape(), whose defaults turn it on for templates ending in html, htm or xml and for templates loaded from a string.
Q4 The documentation's example of a sandbox use is an internal reporting system whose users write custom email templates against data the developers document. This page's advice: any template written by someone outside your development team goes in a SandboxedEnvironment, with resource limits around it.
TWIG (PHP). Documentation for Twig 3.x, which describes the Sandbox class added in Twig 3.29.
Q1 Twig treats templates as trusted code, and its documentation says rendering a template written by an untrusted author without the sandbox gives its author the same power as your application code. Search for templates created from strings, such as with createTemplate(). Twig allows math in templates ({{ 2 * 2 }} returns 4), so the canary is evaluated.
Q2 The Sandbox class, created from an environment dedicated to untrusted templates (never your application environment) and a strict SecurityPolicy that allow-lists tags, filters, functions, tests, methods and properties. Its section on what the sandbox does not protect against lists: data you pass is readable, and a template can iterate over every variable; allowed operations use their arguments freely; objects must behave consistently, since an object that produces different elements on each iteration can give an operation elements that were never checked, which Twig does not consider a security issue; your own filters, functions and extensions run with full power; template text is output as written, HTML and JavaScript included; and resources are not limited, so contain sandboxed renders at the process level. The older SandboxExtension is internal as of 3.29, and its methods for switching the sandbox on are deprecated.
Q3 Automatic escaping is on by default with the html strategy, set by the autoescape option. Values printed in JavaScript, CSS, URL or attribute contexts need the matching strategy. Auto-escaping applies only to printed expressions.
Q4 The sandbox is the documentation's only security boundary for templates by untrusted authors. Error messages shown to template authors reveal class and registered names. This page's advice: keep those messages out of the template editor.
HANDLEBARS (JavaScript). The guide, Security and compilation pages at handlebarsjs.com. They show no version number.
Q1 Search for Handlebars.compile(), which compiles a template string. The Security page says to treat the template, its input data, registered helpers, partials and runtime configuration as parts of your application's security boundary. An expression is replaced with a value from the input object.
Q2 No sandbox. The Security page says not to rely on Handlebars alone as a security sandbox, and to compile and render user-supplied templates in an isolated sandbox, such as a separate process or container with strict CPU, memory, file system and network limits, exposing only an allowlist of safe helpers and partials, with a minimal data object and no application credentials or host access. Keep Handlebars up to date, do not relax prototype-property access controls or enable allowCallsToHelperMissing, and compile ASTs only from trusted template source.
Q3 Values rendered with double braces are HTML-escaped by default. Triple braces and Handlebars.SafeString turn escaping off. HTML escaping does not make data safe in JavaScript, CSS, URLs or event-handler attributes.
Q4 The Security page says templates from users are untrusted programs for resource-consumption purposes, even when they cannot execute arbitrary JavaScript, and lists limits including template size, nesting depth, partial recursion, input and output size, timeouts and rate limits. A helper must validate its arguments and must not turn template input into arbitrary file, network, database or command access.
MUSTACHE (many languages). The mustache(5) page, which reflects version 1.3.0 of the Mustache specification. Check your library's own documentation as well.
Q1 A variable tag names a key that is looked up in the current context of the hash or object your code supplies, then in parent contexts; section and inverted-section tags render depending on the value of a key; and a partial tag, which begins with a greater than sign, like {{> box}}, renders another template at runtime with the calling context. Text joined into a Mustache template can still name any key in that data, as input I4 does with the stand-in engine (this page's reasoning, not a statement in the mustache(5) page).
Q2 The page calls Mustache logic-less: no if statements, else clauses or for loops, only tags. It describes no sandbox, and lists lambdas as an optional extension. PortSwigger's 2015 research names a trivial engine such as Mustache as the lowest risk approach where user-supplied templates are a business requirement.
Q3 All variables are HTML escaped by default. The triple mustache and the ampersand tag return raw contents.
Q4 This page's advice: what a template author can reach is the data you pass, so pass only what the template prints.
NUNJUCKS (JavaScript). The API and templating pages at mozilla.github.io/nunjucks. They show no version number.
Q1 Search for renderString() and compile(), which take a template as a string. The documentation says nunjucks does not sandbox execution, so it is not safe to run user-defined templates or inject user-defined content into template definitions, and that on the server this can expose attack vectors for accessing sensitive data and remote code execution. Nunjucks lists arithmetic operators ({{ 2 + 3 }} outputs 5), so the canary is evaluated.
Q2 None. The documentation says it does not sandbox execution.
Q3 The autoescape option defaults to true. The safe filter marks output so it is not escaped.
Q4 The same warning: user-defined templates are not safe to run. This page's advice: treat every template as application code, edited only by the people who change your code.
AT A GLANCE
Engine Arithmetic in templates Escaping by default Sandbox in its documentation
Jinja yes off SandboxedEnvironment, "not a solution for perfect security"
Twig yes on, html strategy Sandbox class, strict policy, dedicated environment
Handlebars not in the pages cited on for double braces none; do not rely on Handlebars alone
Mustache tags only (logic-less) on for double braces none described
Nunjucks yes on (autoescape true) none; "does not sandbox execution"What server-side template injection is
Server-side template injection (SSTI) is what happens when a server renders a template that was built, in part, out of someone else's text.
The template engine cannot tell that text apart from the template your developers wrote, so any template syntax inside it runs. MITRE catalogues the weakness as CWE-1336, Improper Neutralization of Special Elements Used in a Template Engine: a product uses a template engine to insert or process externally influenced input, but does not neutralise, or incorrectly neutralises, special elements or syntax that the engine can interpret as template expressions or other code directives.
CWE-1336 gives Server-Side Template Injection (SSTI) as an alternate term for injection into template engines used by a server, and Client-Side Template Injection (CSTI) for engines used by a client.
James Kettle, Director of Research at PortSwigger, set out the technique in a research paper titled "Server-Side Template Injection", published on 5 August 2015 and also presented at Black Hat USA. Its conclusion says template injection had remained relatively unknown up to that point.
The paper calls it a frequently critical vulnerability that is extremely easy to mistake for cross-site scripting, or miss entirely. OWASP's Web Security Testing Guide covers it as WSTG-INPV-18, Testing for Server-side Template Injection, which says these vulnerabilities occur when user input is embedded in a template in an unsafe manner and results in remote code execution on the server.
The standards file it with code injection. CWE-1336 sits beneath CWE-94, Improper Control of Generation of Code, and lists the execution of unauthorised code or commands as a consequence, and the OWASP Top 10:2025 maps CWE-94 to A05 Injection. ASVS 5.0 requirement 1.3.7, at Level 2, asks that an application protects against template injection by not allowing templates to be built from untrusted input, and that where there is no alternative, any untrusted input included dynamically during template creation is sanitised or strictly validated.
What a template engine is for, and the two ways to give it text
An order confirmation, an invoice, a password reset email, a shipping notification and a page listing a customer's bookings all have a fixed shape with a few details that change.
A template is that shape written once, with marked gaps for the details, and a template engine fills the gaps each time an email, document or page is produced. PortSwigger's paper opens on the same point: template engines are widely used by web applications to present dynamic data via web pages and emails.
Engines give a template more than gaps. Jinja's documentation says a template contains variables and/or expressions, which get replaced with values when it is rendered, and tags, which control the logic of the template, and Twig's documentation says much the same.
Both list arithmetic operators: in Jinja's words, {{ 2 * 2 }} would return 4. Nunjucks lists the same kind of operators, with the note that they should be used sparingly because most of your logic should be in code.
That power is useful to the developer who writes a template. It becomes the problem when someone else writes part of it.
There are two ways to put a customer's text into a template. The first passes it in as a value: the template has a gap called giftMessage, and the code fills it with whatever the customer typed. The second builds the template out of the text: the code joins the customer's words into the template source and asks the engine to render the result, so the engine reads those words as part of the template, braces and all.
Kettle's paper uses a marketing application that greets email recipients by name.
Passing the name in to the template works fine; once users are allowed to customise the emails, the user controls the content of the template itself rather than a value passed into it.
Where template injection comes from in practice
Kettle's paper describes two routes in.
Template injection can arise through developer error, and through the intentional exposure of templates to offer rich functionality, which it says is commonly done by wikis, blogs, marketing applications and content management systems. WSTG-INPV-18 names wiki pages, reviews, marketing applications and CMS systems among the features that may be vulnerable. In a business application, these are the shapes to look for:
- A "customise your email template" setting, where a customer or a staff member edits the wording of emails your system sends. If what they type is saved and later rendered as a template, they are writing template code.
- A preview feature that joins the visitor's text into the template so the preview looks right, such as the gift message preview in the lab on this page.
- An error page or a "page not found" message whose template is built from the address that was requested, so whatever was in the address becomes template text.
- A marketing or newsletter tool that lets staff edit templates in the browser. Twig's documentation is direct about what that hands over: Twig treats templates as trusted code, and rendering a template written by an untrusted author without its sandbox gives that author the same power as your application code.
- Input that lands inside a template statement rather than in its text, such as a parameter that names which variable to print. WSTG-INPV-18 calls this the code context, and Kettle's paper says this variant is even easier to miss, because it does not result in obvious XSS.
Why the accidental route goes unnoticed
The paper says template injection can also arise by accident, when user input is concatenated directly into a template, and compares it to SQL injection in poorly written prepared statements. It adds that unintentional template injection is extremely easy to miss, as there typically won't be any visible cues.
The first input in the lab shows why: an ordinary message renders identically through the flawed handler and the fixed one, so a feature can pass any test that only checks how real customer text looks on the page, while building its template from that text.
How to tell template injection from cross-site scripting
From the outside the two can look the same, because text a visitor typed changes the page.
The difference is where the text is interpreted. Cross-site scripting is the browser reading text as markup or script, inside one visitor's session, and the XSS guide in this library covers it. Template injection is the server's template engine reading text as template syntax before the page or email is sent, with whatever the engine can reach on the server.
MITRE and PortSwigger both warn about the overlap. CWE-1336 says that in some cases XSS-style attacks can work, which can obscure the root cause if the developer does not closely investigate it, and its notes say XSS is also co-located with template injection. In Kettle's marketing email example the flaw produces an XSS vulnerability that is hard to miss, and the paper calls that XSS just a symptom of a subtler, more serious vulnerability: unlike XSS, it says, template injection can be used to directly attack web servers' internals and often obtain remote code execution.
A canary separates them. Send harmless arithmetic, such as {{ 7*7 }}, through the input, then read the response the server sent, not the page the browser shows. If the response holds 49 where the text should be, the server evaluated it, and that is template injection, whatever the page also does with markup.
If the braces come back as typed, the engine treated the text as data, at least for that syntax. CWE-1336 uses the same arithmetic, written without spaces as {{7*7}}, as its example for some template languages, and WSTG-INPV-18's Flask and Jinja2 example, which writes it the same way, returns Hello 49!.
The lab's flawed handler shows both findings from one root cause: a bold tag passes through as markup, and the canary comes back as 49.
From a number on the page to code on the server
A 49 on the page is where the trouble starts, not where it ends.
WSTG-INPV-18 sets three objectives: detect template injection points, identify the template engine, and build the exploit. Kettle's paper follows the same order. After detection it identifies the engine, then reads the engine's documentation and explores what a template can reach, where it says you can expect to find both default objects provided by the engine and application-specific objects passed in by the developer, and that developer-supplied objects are particularly likely to contain sensitive information.
The consequences match. CWE-1336 lists executing unauthorised code or commands. WSTG-INPV-18 says working through the objects, methods and properties a template can reach could lead to privilege escalation and to disclosure of application passwords, API keys, configuration and environment variables. Kettle's conclusion says that when template injection occurs, regardless of whether it was intentional, it is frequently a critical vulnerability that exposes the web application, the underlying webserver and adjacent network services.
What code can do once it runs on a server depends on the process it runs in, which the remote code execution guide covers.
This page stops at the canary. It describes the rest at the level a defender needs and publishes no expressions that reach an engine's internals, read files or run commands, in any engine's syntax. Proving the flaw does not need them: a computed number where the customer's text should be is enough evidence to fix the code.
Template sandboxing: what the engines' own documentation says
A sandbox is a mode that limits what a template can reach, meant for templates written by people you do not trust.
CWE-1336's mitigations are to choose a template engine that offers a sandbox or restricted mode, or at least limits the power of any available expressions, function calls or commands, and to use the engine's sandbox or restricted mode if available.
Kettle's paper explains why such modes exist: intentional template injection is such a common use-case that many template engines offer a sandboxed mode for that express purpose. Each engine's documentation is careful about the limits of its own.
Jinja: SandboxedEnvironment
Jinja's documentation says its sandbox can be used to render untrusted templates, and that access to attributes, method calls, operators, mutating data structures and string formatting can be intercepted and prohibited. Its security considerations begin with the sentence "The sandbox alone is not a solution for perfect security", then list what remains: templates can still raise errors, a relatively small template can render a very large amount of output, which could mean high CPU or memory use, Jinja only renders text and does not understand, for example, JavaScript code, and you should pass only the data relevant to the template.
Jinja's changelog lists changes to how the sandbox applies its checks in both 3.1.5, released on 21 December 2024, and 3.1.6, released on 5 March 2025, so the installed version matters.
Twig: the Sandbox class
Twig's documentation says its sandbox is the only security boundary for templates written by untrusted authors. A sandboxed template can use only the tags, filters, functions and tests you allow, and only the object methods and properties you allow, under a strict security policy and an environment dedicated to the sandbox, never your application environment.
From Twig 3.29 that is the Sandbox class; the older SandboxExtension is internal, and its methods for switching the sandbox on are deprecated. A section titled What the Sandbox Does Not Protect Against lists six things: data you pass is readable; allowed operations use their arguments freely; objects must behave consistently, because an object that produces different elements on each iteration can give an operation elements the sandbox never checked, and Twig does not consider such bypasses security issues; your own filters, functions and extensions run with full power; template text is output as written, HTML and JavaScript included; and resources are not limited, which it says to contain at the process level.
Handlebars, Mustache and Nunjucks
Handlebars documents no sandbox. Its Security page says not to rely on Handlebars alone as a security sandbox, and to compile and render user-supplied templates in an isolated sandbox, such as a separate process or container with strict CPU, memory, file system and network limits. Nunjucks says it does not sandbox execution, so it is not safe to run user-defined templates or inject user-defined content into template definitions, and that on the server this can expose attack vectors for accessing sensitive data and remote code execution.
The mustache(5) page describes a logic-less language, with no if statements, else clauses or for loops, only tags, and describes no sandbox.
Anyone tempted to build a sandbox for a JavaScript engine out of Node.js should note that its documentation says the node:vm module is not a security mechanism and not to use it to run untrusted code.
SSTI prevention: a fixed template, with the text passed as a value
The fix is the one ASVS 5.0 requirement 1.3.7 asks for: do not build templates from untrusted input.
OWASP's Top 10:2025 says the best means to prevent injection requires keeping data separate from commands and queries. To a template engine, the template source is the command. Load templates from files your developers control, refer to each by a fixed name, and pass every piece of customer text in as a value. In the lab, that is the whole difference between the flawed handler and the fixed one.
- Find every call that compiles a template from a string: Environment.from_string() or the Template class in Jinja, a template created from a string in Twig, Handlebars.compile() in Handlebars, and renderString() or compile() in Nunjucks. Trace each string back to its origin. A constant in your code is fine. A string holding anything from a request, a record a customer can edit or a setting staff can change is the flaw.
- Where a template genuinely has to vary with input, such as a choice between two layouts, map the input to one of a fixed set of template names in code. ASVS 1.3.7 falls back to sanitising or strictly validating input only where there is no alternative, and Kettle's paper found that regular expressions are not an effective defence, so prefer a fixed list to a filter.
- Pass a template only what it prints. Twig's documentation says a template can iterate over every variable it is given, Handlebars says not to give a template access to secrets or privileged application objects unless it genuinely needs them, and Jinja says to pass only the data relevant to the template. Input I4 in the lab shows why: the flawed handler printed a staff-only note it had been handed for no reason.
- Turn auto-escaping on, and know where it stops. Jinja's default configuration is no automatic escaping, and its documentation encourages configuring it explicitly. Twig and Nunjucks escape by default, and Handlebars and Mustache escape double-brace output but not triple-brace output. Twig's documentation puts the limit plainly: auto-escaping only applies to printed expressions. Text that has become part of the template is not a printed value, which is why the flawed handler's bold tag reached the page, and why escaping does not fix template injection.
- Treat helpers and filters as code that template input reaches. Handlebars says a helper must validate its arguments and must not turn template input into arbitrary file, network, database or command access. A helper or filter that starts an operating system program is a command injection question, and the command injection guide covers it.
- Keep engine errors away from template authors and visitors. Kettle's paper notes that engines may identify themselves in error messages, and Twig's documentation says error messages shown to template authors reveal names, such as the class of an object or registered filters with similar names.
When customers or staff need to edit templates
Sometimes editing is the feature: customers write their own invoice wording, or a marketing team changes campaign emails without a developer.
Kettle's paper answers the question directly. If user-supplied templates are a business requirement, the lowest risk approach is to use a trivial template engine such as Mustache, or Python's Template. A fixed list of merge fields, such as the customer's first name and the order number, that your own code swaps for escaped values follows the same idea, and the lab's stand-in engine shows how narrow such a feature can be kept: supplied values and arithmetic, nothing else.
Where a fuller template language is needed, use the engine's sandbox exactly as its documentation describes, and add the limits that the same documentation says the sandbox leaves out. The paper's 2015 verdict explains the caution: it demonstrated escapes from sandboxes whose entire purpose is to handle user-supplied templates, called parser-level sandboxes error prone, and concluded that many of the technologies designed to prevent templates from doing harm were immature and should not be relied on except as a defence in depth measure.
- Render user templates in an environment kept for them: a SandboxedEnvironment in Jinja, or in Twig the Sandbox class with a strict security policy and a dedicated environment. Allow only the tags, filters and functions the feature needs.
- Pass a small, documented set of data. Jinja's sandbox page gives the model: users of an internal reporting system create custom emails, the developers document what data is available, and the code passes the report data to the user's sandboxed template. Avoid objects with methods that have side effects; Jinja offers an unsafe() decorator to stop templates calling a method, and an ImmutableSandboxedEnvironment to stop them changing lists and dictionaries.
- Limit resources. Jinja says to run with limits on CPU and memory. Twig says a template can consume as much CPU, memory or time as it wants even under the strictest policy, and to contain sandboxed renders at the process level. Handlebars calls templates from users untrusted programs for resource-consumption purposes, and lists limits including template size, nesting depth, input and output size, timeouts and rate limits.
- Isolate the renderer. Handlebars says to compile and render user-supplied templates in an isolated sandbox, such as a separate process or container with strict CPU, memory, file system and network limits, with a minimal data object and no application credentials or host access. Kettle's paper describes a locked-down container as another, complementary approach.
- Treat template editing as code access. Twig says rendering an untrusted author's template without the sandbox gives that author the same power as your application code. Decide who may edit templates the way you decide who may change code: named people, every change recorded and reviewed, and the permission removed when someone leaves.
- Check the output where it lands. Jinja notes that it only renders text and does not understand JavaScript, and Twig that a sandboxed template's text is output as written, HTML and JavaScript included. If a customer's template ends up in a page or email other people open, handle it like any other HTML a user supplied.
Server-side template injection testing on a template path you own
WSTG-INPV-18 describes two contexts.
In the plaintext context, the tester sends common template expressions and watches the responses for one the server executed. In the code context, the input lands inside a template statement, such as a variable name, so the tester looks for blank or error responses and then for a way out of the statement.
The guide then moves on to identifying the engine and building an exploit. On a template path you own, the first step is the useful one: you are looking for evidence that the template is built from input, and a computed number is that evidence.
CWE-1336 lists automated static analysis as a detection method that can find some instances of the weakness, typically by modelling data flow and control flow and searching for patterns that connect sources of input with sinks, and rates its effectiveness as High.
OWASP's Top 10:2025 says injection is best detected by combining source code review with automated testing of all parameters, headers, URL, cookies, JSON, SOAP and XML inputs. Test only systems you own or are authorised in writing to test.
- Start in the code, with the template-from-string calls listed in the prevention section, and trace each string back to its origin.
- Send the arithmetic canary through every input that ends up in a rendered page, email or document: form fields, URL parameters, profile fields and anything staff edit later. Use a product unlikely to appear by chance.
- Read the raw response or the source of the generated email, not the browser's rendering. A computed number means the server evaluated the input.
- Try your own engine's delimiters as well as double braces, and follow stored values: text saved through one form can be rendered later in a different template, such as a staff notification.
- Stop at the number. It is enough to report and fix, and on a live system there is nothing to gain from going further.
- Add a regression test like the lab's, which fails while the template source changes with the input.
Running the template lab and reading its output
The lab in the asset is an illustration for learning and for testing a template path you own.
The lab installs no template engine, so it includes a deliberately tiny one written for this page: double-brace placeholders, small arithmetic expressions inside them, and HTML escaping for values. It stands in for a real engine, and nothing it shows about itself carries over to Jinja, Twig, Handlebars, Mustache or Nunjucks. Everything runs with Node.js alone, and every output in the asset was recorded on Node.js v26.0.0 on macOS.
compare.mjs sends six inputs through two handlers for an invented hardware shop's gift message preview, and prints the template source each one gave the engine beside what it rendered. The flawed handler's template source is different for every input, because it is built from the input, while the fixed handler's never changes and the visitor's text arrives as a value called giftMessage.
With the canary, the flawed handler rendered 49 and the fixed handler rendered the braces as typed.
Asked for {{ internalNote }}, the flawed handler printed a staff-only note it had been given, and the fixed handler, which passes only the values its template prints, showed the braces.
Two test files use Node's built-in test runner. engine.test.mjs checks the stand-in engine: arithmetic works, values come out escaped, a value is never read as a template, and every name the code did not supply is rejected, including properties every JavaScript object inherits, such as constructor and toString, and runtime globals such as process and globalThis.
Property access, calls, quotes and assignment are rejected too, and a last check confirms the engine's source contains no call to eval or Function and no import of node:vm.
That proves the property for this engine only. A real engine gives a template far more to work with, so for yours, work through Part 3 of the asset.
preview.test.mjs is the regression test. For each input it checks that the template source does not change and that the message comes back exactly as typed, escaped. Against the fixed handler all twelve checks passed and the process exited with code 0.
Against the flawed handler eleven failed and it exited with code 1: every input changed the template source, the ordinary message included, and five of the six did not come back as typed.
The Node.js documentation says the exit code is set to 1 when any test fails, so the test can sit in a build pipeline and stop a change that brings the flaw back.
Where an outside review fits
The lab checks the template paths you already know about.
A review looks for the ones you do not, such as a preview feature added for one campaign or a template string assembled several calls away from the request. Clever Ops reviews code for custom web applications and their APIs, such as Next.js, React and Node applications, using read-only access to your repository, and the review follows the paths in scope with untrusted input in view.
Code findings are confirmed against a running build where the scope allows, and the report marks any that rest on the code alone. The secure code review guide explains how that review is scoped and what its report records.
A web application and API penetration test exercises the running application, and read-only code access to named areas can be added to confirm how a control is enforced. If your application runs on Next.js, the Next.js guide in this library shows how each of its server entry points is tested.
If Clever Ops built or hosts the application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
If a tender or contract requires a CREST-accredited provider, Clever Ops is not CREST accredited, so we refer that work to a provider that is.
Frequently asked questions
It is what happens when a website builds a template, the pattern it uses for an email, document or page, out of text someone else typed, so the template engine reads that text as instructions instead of printing it. If the engine does arithmetic, {{ 7*7 }} comes back as 49. Depending on the engine and what it can reach, the same mistake can expose data the template was given or let code run on the server. CWE-1336 lists executing unauthorised code or commands as a consequence.
No, although one can look like the other. XSS is a visitor's browser running text as script. Template injection is the server's template engine running text as template syntax before the page is sent. CWE-1336 notes that in some cases XSS-style attacks can work, which can obscure the root cause if the developer does not closely investigate it, and PortSwigger's research calls the XSS just a symptom of the more serious server-side flaw. A canary that comes back as a computed number in the server's response points to the server.
No. Escaping protects the values a template prints, and Twig's documentation says auto-escaping only applies to printed expressions. Once a visitor's text has been joined into the template source it is part of the template, not a value, so it is not escaped. The lab shows both sides: the fixed handler escaped a bold tag, while the flawed handler passed it through and evaluated the canary.
A sandbox narrows what a template can reach, and the engines' own documentation says not to stop there. Jinja says its sandbox alone is not a solution for perfect security. Twig lists what its sandbox does not protect against, including readable data and unlimited resources. Handlebars says not to rely on Handlebars alone as a security sandbox, and Nunjucks says it does not sandbox execution. Pair a sandbox with a small data set, resource limits and an isolated process, or give customers a fixed list of merge fields instead.
Not entirely. The mustache(5) page calls Mustache logic-less, with no if statements, else clauses or for loops, only tags, and PortSwigger's research names a trivial engine such as Mustache as the lowest risk approach when user-supplied templates are a business requirement. A tag still reaches whatever data you pass, so pass only what the template prints. Handlebars also warns that user templates can consume substantial CPU, memory or output space even when they cannot execute arbitrary JavaScript.
On a template path you own, send harmless arithmetic such as {{ 7*7 }} through each input and read the raw response or the generated email. A number where the text should be is the finding, and there is no need to go further. Test only systems you own or are authorised in writing to test, and keep a regression test that fails if the template source ever changes with the input, like the one in the lab.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.