KatInterview

Debugging and Hardening a Lightweight Template Engine

StringsModel answer
MediumModel answerStringsdebuggingparsingregex

Last 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

  1. tokenize(src): Breaks template source strings into raw text segments and tags: expressions ({{ ... }}), control tags ({% ... %}), and comments ({# ... #}).
  2. parse(tokens, pos, until): Recursively builds an abstract syntax tree composed of nodes for text, expr, for, and if.
  3. render_nodes(nodes, ctx): Recursively renders the AST using variable key-values provided in a context dictionary ctx.
  4. 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

  1. 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'
  2. 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
  3. Issue 3 (Security): Loader allows arbitrary file reads outside the designated root path 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.