Debugging and Hardening a Lightweight Template Engine
StringsModel answerLast updated
Trace three root causes in a minimal template rendering engine—regex greediness, loop parsing, and path traversal—and present targeted fixes with regression tests.
You are tasked with reviewing and repairing a small Python templating library used to render automated emails. Following a recent refactoring pass, three distinct failures were reported in production and security audits.
Engine Mechanics
tokenize(src): Breaks template source strings into raw text segments and tags: expressions ({{ ... }}), control tags ({% ... %}), and comments ({# ... #}).parse(tokens, pos, until): Recursively builds an abstract syntax tree composed of nodes fortext,expr,for, andif.render_nodes(nodes, ctx): Recursively renders the AST using variable key-values provided in a context dictionaryctx.Loader(root).load(name): Reads template file contents from disk given a root template directory.
Current Implementation
import os
import re
TOKEN_RE = re.compile(r"(\{\{.*\}\}|\{%.*?%\}|\{#.*?#\})", re.S)
FILTERS = {"upper": str.upper, "lower": str.lower, "trim": str.strip}
class TemplateError(Exception):
pass
def tokenize(src):
return [t for t in TOKEN_RE.split(src) if t]
def parse(tokens, pos=0, until=None):
"""Return (nodes, next_pos). Stops when it meets a tag named in `until`."""
nodes = []
while pos < len(tokens):
tok = tokens[pos]
if tok.startswith("{#"):
pos += 1
elif tok.startswith("{{"):
nodes.append(("expr", tok[2:-2].strip()))
pos += 1
elif tok.startswith("{%"):
words = tok[2:-2].split()
if until and words[0] in until:
return nodes, pos
if words[0] == "for": # {% for x in items %}
end = tokens.index("{% endfor %}", pos)
body, _ = parse(tokens[pos + 1:end])
nodes.append(("for", words[1], words[3], body))
pos = end + 1
elif words[0] == "if": # {% if cond %}
body, pos = parse(tokens, pos + 1, until=("endif",))
nodes.append(("if", words[1], body))
pos += 1
else:
raise TemplateError(f"unknown tag {words[0]!r}")
else:
nodes.append(("text", tok))
pos += 1
if until:
raise TemplateError(f"missing {until[0]}")
return nodes, pos
def lookup(ctx, dotted):
val = ctx
for part in dotted.split("."):
val = val[part] if isinstance(val, dict) else getattr(val, part)
return val
def eval_expr(expr, ctx):
name, *filters = [p.strip() for p in expr.split("|")]
val = str(lookup(ctx, name))
for f in filters:
val = FILTERS[f](val)
return val
def render_nodes(nodes, ctx):
out = []
for node in nodes:
kind = node[0]
if kind == "text":
out.append(node[1])
elif kind == "expr":
out.append(eval_expr(node[1], ctx))
elif kind == "for":
_, var, seq, body = node
for item in lookup(ctx, seq):
out.append(render_nodes(body, {**ctx, var: item}))
elif kind == "if":
_, cond, body = node
if lookup(ctx, cond):
out.append(render_nodes(body, ctx))
return "".join(out)
def render(src, ctx):
nodes, _ = parse(tokenize(src))
return render_nodes(nodes, ctx)
class Loader:
def __init__(self, root):
self.root = root
def load(self, name):
path = os.path.join(self.root, name)
if not os.path.isfile(path):
raise TemplateError(f"template not found: {name}")
with open(path, encoding="utf-8") as fh:
return fh.read()
Issues to Resolve
- Issue 1 (Tokenizer): Rendering multiple expressions on a single line fails.
- Example:
render("Hello {{ user.first }} {{ user.last|upper }}", {"user": {"first": "Ada", "last": "Lovelace"}}) - Error:
KeyError: 'first }} {{ user.last'
- Example:
- Issue 2 (Parser): Rendering nested control loops triggers a failure.
- Example:
render("{% for r in matrix %}[{% for c in r %}{{ c }}{% endfor %}]{% endfor %}", {"matrix": [[1, 2], [3]]}) - Error:
ValueError: list.index(x): x not in list
- Example:
- Issue 3 (Security):
Loaderallows arbitrary file reads outside the designatedrootpath if relative (../) or absolute paths are provided in template names.
Requirements
- Identify the exact root cause for all three defects.
- Provide minimal patches fixing each issue while leaving the public interface intact.
- Write unit tests covering each bug fix without breaking standard features (filters, comments, conditional blocks).
- State at least one remaining latent bug or design risk in the system.
Hints
Hint 1
Examine how regular expression quantifiers match repeated pattern boundaries on a single line.
Hint 2
Compare how the parser handles nested 'if' blocks versus 'for' blocks when matching closing tags.
Hint 3
Consider edge cases with `os.path.join` and directory traversal checks, such as prefix matching vs true path ancestors.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Technical Analysis & Root Cause Breakdown
Issue 1: Greedy Expression Matching in TOKEN_RE
- Root Cause: In
TOKEN_RE, expression tags are matched via\{\{.*\}\}. The.*pattern is greedy, matching continuously across multiple}}delimeters until reaching the final}}in a line or string. When multiple expression tags appear on one line,tokenizemerges them into a single invalid token containing literal}} {{string fragments. - Fix: Change
\{\{.*\}\}to non-greedy matching\{\{.*?\}\}to mirror control and comment tags.
Issue 2: Linear list.index Search in for Block Parser
- Root Cause:
parse()parsesforloops by searching linearly for the next token equal to"{% endfor %}"usingtokens.index(...). In nested loops,index()returns the closing tag of the inner loop for the outer loop. The sub-slice then contains unbalanced tags, which causes child recursion calls to fail to find anendfortag and raiseValueError. - Fix: Delegate parsing of
forloop bodies to the recursiveparsefunction usinguntil=("endfor",), exactly as implemented forifblocks withuntil=("endif",).
Issue 3: Path Traversal Vulnerability in Loader
- Root Cause:
os.path.join(root, name)resolves absolute paths by completely overridingrootifnamestarts with/. Furthermore, path traversal sequences (../) are left un-resolved. Relying on simple prefix checks (e.g.,startswith) is vulnerable to sibling path attacks like/var/tplvs/var/tpl-secret. - Fix: Canonicalize paths using
os.path.realpathfor bothrootand the targeted target file path, then ensure that target path stays strictly underrootusingos.path.commonpath.
Complete Corrected Code
import os
import re
# Non-greedy expression capture fix
TOKEN_RE = re.compile(r"(\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\})", re.S)
FILTERS = {"upper": str.upper, "lower": str.lower, "trim": str.strip}
class TemplateError(Exception):
pass
def tokenize(src):
return [t for t in TOKEN_RE.split(src) if t]
def parse(tokens, pos=0, until=None):
"""Return (nodes, next_pos). Stops when it meets a tag named in `until`."""
nodes = []
while pos < len(tokens):
tok = tokens[pos]
if tok.startswith("{#"):
pos += 1
elif tok.startswith("{{"):
nodes.append(("expr", tok[2:-2].strip()))
pos += 1
elif tok.startswith("{%"):
words = tok[2:-2].split()
if until and words[0] in until:
return nodes, pos
if words[0] == "for": # {% for x in items %}
# Recursive parser call handles nested depth naturally
body, pos = parse(tokens, pos + 1, until=("endfor",))
nodes.append(("for", words[1], words[3], body))
pos += 1
elif words[0] == "if": # {% if cond %}
body, pos = parse(tokens, pos + 1, until=("endif",))
nodes.append(("if", words[1], body))
pos += 1
else:
raise TemplateError(f"unknown tag {words[0]!r}")
else:
nodes.append(("text", tok))
pos += 1
if until:
raise TemplateError(f"missing {until[0]}")
return nodes, pos
def lookup(ctx, dotted):
val = ctx
for part in dotted.split("."):
val = val[part] if isinstance(val, dict) else getattr(val, part)
return val
def eval_expr(expr, ctx):
name, *filters = [p.strip() for p in expr.split("|")]
val = str(lookup(ctx, name))
for f in filters:
val = FILTERS[f](val)
return val
def render_nodes(nodes, ctx):
out = []
for node in nodes:
kind = node[0]
if kind == "text":
out.append(node[1])
elif kind == "expr":
out.append(eval_expr(node[1], ctx))
elif kind == "for":
_, var, seq, body = node
for item in lookup(ctx, seq):
out.append(render_nodes(body, {**ctx, var: item}))
elif kind == "if":
_, cond, body = node
if lookup(ctx, cond):
out.append(render_nodes(body, ctx))
return "".join(out)
def render(src, ctx):
nodes, _ = parse(tokenize(src))
return render_nodes(nodes, ctx)
class Loader:
def __init__(self, root):
self.root = os.path.realpath(root)
def load(self, name):
# Resolve path safely and enforce root boundary constraints
target_path = os.path.realpath(os.path.join(self.root, name))
if os.path.commonpath([self.root, target_path]) != self.root:
raise TemplateError(f"access denied: template path '{name}' resolves outside root directory")
if not os.path.isfile(target_path):
raise TemplateError(f"template not found: {name}")
with open(target_path, encoding="utf-8") as fh:
return fh.read()
Regression Tests Suite
import os
import tempfile
import unittest
class TemplateEngineTests(unittest.TestCase):
def test_multiple_expressions_single_line(self):
ctx = {"user": {"first": "Ada", "last": "Lovelace"}}
rendered = render("Hello {{ user.first }} {{ user.last|upper }}", ctx)
self.assertEqual(rendered, "Hello Ada LOVELACE")
def test_nested_loops(self):
ctx = {"matrix": [[1, 2], [3, 4]]}
tpl = "{% for row in matrix %}<{% for item in row %}{{ item }}{% endfor %}>{% endfor %}"
self.assertEqual(render(tpl, ctx), "<12><34>")
def test_loader_directory_traversal_protection(self):
with tempfile.TemporaryDirectory() as base_dir:
tpl_dir = os.path.join(base_dir, "templates")
os.makedirs(tpl_dir)
secret_file = os.path.join(base_dir, "secrets.env")
with open(secret_file, "w") as f:
f.write("SECRET_KEY=12345")
valid_file = os.path.join(tpl_dir, "welcome.txt")
with open(valid_file, "w") as f:
f.write("Welcome!")
loader = Loader(tpl_dir)
self.assertEqual(loader.load("welcome.txt"), "Welcome!")
# Path traversal attempt
with self.assertRaises(TemplateError):
loader.load("../secrets.env")
# Absolute path escape attempt
with self.assertRaises(TemplateError):
loader.load(secret_file)
def test_existing_functionality(self):
tpl = "{# Comment #}{% if flag %}{{ text|trim|upper }}{% endif %}"
self.assertEqual(render(tpl, {"flag": True, "text": " hello "}), "HELLO")
if __name__ == "__main__":
unittest.main()
Latent Design Defect / Unfixed Edge Case
Whitespace Sensitivity in Control Tags:
The control flow matching in parse() inspects words[0] split on spaces (tok[2:-2].split()), but expected closing tags during loop lookups or tag parsing require explicit exact token matches if written manually or checked against raw tokens. More critically, variable scoping inside render_nodes for loops ({**ctx, var: item}) overrides any outer variables with identical names during loop iterations without restoring original parent contexts after iteration completes.