mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.48k stars 635 forks source link

nunjucks causes server crash on errored include #1368

Open vfilatov opened 2 years ago

vfilatov commented 2 years ago

I discovered a bug causing the server crash while using nunjucks template containing error.

how to reproduce

cd /tmp
npx create-foo crash
cd crash
npm install nunjucks express
# create template with an error
cat << EOF > template.njk
{# next line missing '%' before '}' #}
{% block body } <<< this done on purpose
Hi from Template
{% endblock %}
EOF
// server.js
const express = require('express');
const app = express();
const port = 3000;
const nunjucks = require ('nunjucks');
const template = '{% include "template.njk" %}';

app.get('/', (req, res) => {
  try {
    const body = nunjucks.renderString(template);
    res.send(JSON.stringify(body));
  }
  catch (error) {
    res.send(error.toString())
  }
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
# Run the server
node server.js 
Example app listening at http://localhost:3000

navigate browser to http://localhost:3000 Observe the server crash

logs

/tmp/crash/node_modules/nunjucks/src/environment.js:575
          throw err;
          ^

Template render error: (unknown path)
  Template render error: (/tmp/crash/template.njk) [Line 3, Column 1]
  expected block end in block statement
    at Object._prettifyError (/tmp/crash/node_modules/nunjucks/src/lib.js:36:11)
    at /tmp/crash/node_modules/nunjucks/src/environment.js:563:19
    at eval (eval at _compile (/tmp/crash/node_modules/nunjucks/src/environment.js:633:18), <anonymous>:19:11)
    at /tmp/crash/node_modules/nunjucks/src/environment.js:41:5
    at RawTask.call (/tmp/crash/node_modules/asap/asap.js:40:19)
    at flush (/tmp/crash/node_modules/asap/raw.js:50:29)
    at processTicksAndRejections (internal/process/task_queues.js:77:11)

Expected behavior

Server should not crash within try/catch block