TRENDING
A worn dirt shortcut cutting across the grass beside a paved brick sidewalk, a desire path used as a visual pun on a shortcut in an eval
November 27, 2026
How to Check Whether an AI Eval Can Be Passed Without the Question: Build a Partial-Input Baseline in Python, Split by Group, and Reproduce the SNLI Hypothesis-Only Result
A blown glass cartridge fuse with metal end caps lying on a grey-green surface, its thin wire burned through in the middle
November 27, 2026
Google’s Fuse Turns Social Reasoning Into a 21,600-Message Benchmark, but the Code Its README Promised “Soon” Is Still Missing 71 Days Later, the Human Baseline Was Told to Focus on Facts, Not the User’s Interpretation, and a Per-Template Word Counter Gets 98.6% of the Held-Out Neutral Messages Right
A rusted accordion-style steel security gate pulled across a shopfront in a weathered yellow and teal wall
November 27, 2026
CISA Lists an Exploited ASP.NET Library Flaw That Has No Patch and a Day-After-Thanksgiving Deadline, but Mandiant’s Hash List Skips the 0.9.0 Beta Build, NVD Files the Library Under a Different Vendor Name, and Default Installs Use a Form Field Called RaiseException
A land monitor lizard looking out from a hollow in a mound of earth, a visual pun on sys.monitoring
November 27, 2026
How to Build a Line-Coverage Tool With sys.monitoring in Python 3.12+, Make It Nearly Free With DISABLE, and Check It Against coverage.py and sys.settrace
Close-up of a bay horse’s head and neck in a driving harness with blinkers and brass fittings against a pale sky
November 27, 2026
ShellBench Turns the Model-or-Harness Question Into a 53,100-Run Contest, but the Four Open Harnesses Are a Tie That Reorders When Two Rubric Families Are Dropped, the One Judge Is the Third-Ranked Model, and Only 20 of the 100 Tasks Are Designated for Release
27 Nov 2026
SXZ.io SXZ.io
  • Home
Search the Site
Popular Searches:
Technology Amazon AI
Recent Posts
A faded 1840 promissory note for one thousand dollars that promises payment seventeen months after its date, signed in ink
How to Use Python 3.14 Deferred Annotations: Drop Quoted Forward References, Read Annotations Safely With annotationlib, and Catch the Decorator, Dataclass, and FastAPI Traps
November 26, 2026
Wooden shelves lined with round glass jars of rice crackers and cookies, lit from within, in a Tokyo shop
Backblaze’s New Privacy Policy Drops Its Promise Not to Share E-mail Addresses for Marketing, but the Text Has Been Live Since Early November, the Scope Sentence Ars Quotes Exists Only in the Old Version, and No Ad Platform Was Contacted in a Browser Test Until Accept Was Clicked
November 26, 2026
An unfinished concrete house with open window frames and a palm tree in the Souss-Massa region of Morocco
Drupal Says Its Week-Old Installer Fix Left Some Sites Open to Takeover and Is Seeing Attacks, and in a Local Lab Upgrading the Code Alone Still Let the Visitor Who Got There First Continue the Install Until the Update Hook Ran
November 26, 2026
SXZ.io SXZ.io
  • Home

Categories

Articles 318 Posts
News 324 Posts
Learning Hub 290 Posts
Home/Learning Hub/How to Stop Template Injection in Python: Fix Flask and Jinja2 Pages That Build Templates From User Text, Close the str.format Leak, and Let Users Write Safe Templates
Learning Hub

How to Stop Template Injection in Python: Fix Flask and Jinja2 Pages That Build Templates From User Text, Close the str.format Leak, and Let Users Write Safe Templates

Watch a Flask page hand a secret to a visitor’s template text, fix it by passing data instead of source, close the str.format leak, and build a validated sandbox renderer with 112 tests, a fuzz run...

November 24, 2026 38 Min Read
27

Almost every web app has a template engine somewhere in the background. It sends a welcome email, prints an invoice, or lets an admin customise a notification, and it does so by taking fixed text with blanks in it and filling the blanks with real values. That split between a fixed template and changing data is the whole design. This tutorial is about what happens when the two get mixed up: a visitor’s text ends up inside the template, the engine runs it, and a form field becomes a way to read the server’s secrets. Security testers call it server-side template injection, and PortSwigger defines it as being “when an attacker is able to use native template syntax to inject a malicious payload into a template, which is then executed server-side.”

Table Of Content

  • The words you need first
  • What you will build, and what it does not do
  • Prerequisites
  • Step 1: Create the folder and install the tools
  • Step 2: See the bug on a real Flask page
  • What each probe shows
  • Step 3: Fix it by keeping the visitor’s text out of the template
  • What changed, and why it works
  • Step 4: The same bug in plain Python: format strings
  • Reading the six results
  • Step 5: When users must write templates, learn what the sandbox does and does not do
  • What the table tells you
  • Step 6: The sandbox blocks attributes, not appetite
  • Step 7: Build a renderer that only runs what you allow
  • How the code works
  • The lists at the top
  • The walk function
  • The render_message function
  • Step 8: Put it behind a route
  • Step 9: Prove it with tests, a fuzz run and planted bugs
  • Do the tests notice a broken rule?
  • Step 10: Add a CI gate so the bug cannot come back
  • How does it compare with Ruff?
  • Common mistakes and how to spot them
  • Pasting user text into a template, even “just a little”
  • Trusting the sandbox with your model objects
  • Catching only SecurityError
  • Thinking |safe is harmless
  • Forgetting the data is also a size limit
  • Confirm the whole thing works end to end
  • What to learn next
  • Sources

It is not a theoretical bug. Our report on GitLab’s AI Gateway covers two critical template flaws patched 238 days apart. The public tracking issue for the first one says the Jinja2 sandbox the gateway used “does not block method calls on objects.” You will meet that exact lesson in Step 5, and by the end of this tutorial you will have fixed the bug three different ways, each for a different situation.

The words you need first

A template is text with blanks, such as Hello {{ name }}. A template engine is the program that fills the blanks; Flask uses one called Jinja2. The context is the data you hand to the engine, here name. The important thing to understand is that a template language is a small programming language: it can do arithmetic, loop, and look up attributes on the objects you give it. So whoever writes the template text is, to some degree, writing a program that runs on your server.

Template injection is what happens when text from outside becomes part of the template source instead of part of the context. A sandbox is a restricted mode of an engine that tries to stop a template from reaching dangerous things. Autoescape is a separate safety feature that rewrites characters such as < in the output so a browser shows them as text instead of running them; it protects the visitor’s browser, not your server. An allowlist is a list of the things you permit, as opposed to a blocklist of things you forbid. A format string is the text you pass to Python’s str.format, such as "Hi {name}".

The difference between the safe and the unsafe path fits in two lines:

safe:    fixed template text  +  visitor's text as DATA     -->  engine  -->  page
unsafe:  template text built FROM the visitor's text       -->  engine  -->  page
                                  ^ the visitor is now writing the program

What you will build, and what it does not do

By the end you will have:

  • watched a Flask page leak a configuration secret and an environment variable through a visitor’s text, and fixed it by passing the text as data;
  • seen the same bug in plain Python with str.format, and fixed it three ways;
  • measured, probe by probe, what Jinja2’s sandbox blocks, what it lets through, and what it never limits (memory and time);
  • safe_templates.py, about 70 lines: a renderer for templates that your users write, with plain-data inputs, an allowlist of syntax, the sandbox, autoescape, and caps on size, output and loop nesting;
  • 112 pytest tests, a 50,000-case fuzz run and 17 planted bugs that the tests catch;
  • ssti_gate.py, a CI check that fails the build when a template or a format string can come from a variable.

What this does not do: it is not a full security review. I tested Jinja2 3.1.6 inside Flask 3.1.3 only. Other engines (Twig, Freemarker, ERB and many more) have the same shape of problem with different details, so test yours the same way. The Jinja documentation itself says that “the sandbox alone is not a solution for perfect security,” and the renderer below does not replace the CPU and memory limits it recommends at the process level. And if your templates are all files that you wrote and reviewed, Step 3 is all you need.

Prerequisites

  • Python 3.10 or newer. Everything below ran on Python 3.13.14 on Windows 11. The code uses @dataclass(slots=True), which needs 3.10, and pytest 9.2.0 declares Requires-Python >=3.10.
  • A terminal. The commands work in PowerShell, Command Prompt, macOS Terminal and Linux shells. Only the line that activates the virtual environment differs, and I show both.
  • Basic Python. You should be comfortable reading functions, classes and f-strings. You do not need to know Flask or Jinja2; each is explained when it first appears.
  • No server and no network traffic after the install. Flask’s built-in test client sends requests inside the same process, so nothing listens on a port. Every secret in this tutorial is a made-up demo value.

Step 1: Create the folder and install the tools

You will keep everything in one folder with its own virtual environment, so the exact versions below do not touch anything else on your machine. I pin the versions I tested. MarkupSafe 3.0.4 and Werkzeug 3.1.9 come along as dependencies.

mkdir ssti-lab
cd ssti-lab
python -m venv .venv
# Windows PowerShell:  .\.venv\Scripts\Activate.ps1
# macOS or Linux:      source .venv/bin/activate
pip install flask==3.1.3 jinja2==3.1.6 pytest==9.2.0 ruff==0.17.6

Next, create models.py. It stands in for the objects a real app keeps in its database layer: a Customer that has display fields, a secret field and a method that changes data, plus two made-up secrets. Importing the file also sets a fake environment variable called CANARY_TOKEN, which plays the part of a real server secret such as a database password. A “canary” is a harmless value you plant so that you can tell whether an attack reached it.

# models.py - stand-ins for the objects a real app keeps in its database layer
import os

# A module-level secret, the kind a settings or models module often holds.
SECRET_TOKEN = "format-demo-secret-789"

# A pretend server secret in the process environment. Importing this module sets it.
os.environ.setdefault("CANARY_TOKEN", "canary-value-12345")


class Customer:
    """Like an ORM row: display fields, a secret field, and a method that changes data."""

    def __init__(self, first_name, last_name, plan, password_hash):
        self.first_name = first_name
        self.last_name = last_name
        self.plan = plan
        self.password_hash = password_hash
        self.deleted = False

    def delete(self):
        self.deleted = True
        return "deleted"


def demo_customer():
    return Customer("Ada", "Lovelace", "pro", "pbkdf2$demo$ada-hash")

Then create step01_versions.py and run it:

# step01_versions.py - print the versions this tutorial was run with
import platform
from importlib.metadata import version

print("Python", platform.python_version(), "on", platform.system(), platform.release())
for name in ("Flask", "Jinja2", "MarkupSafe", "Werkzeug", "pytest", "ruff"):
    print(f"{name:<11}{version(name)}")
python step01_versions.py

You should see these versions (the Windows line will say your own system):

Python 3.13.14 on Windows 11
Flask      3.1.3
Jinja2     3.1.6
MarkupSafe 3.0.4
Werkzeug   3.1.9
pytest     9.2.0
ruff       0.17.6

Check that it worked: Flask 3.1.3 and Jinja2 3.1.6. If a different Jinja2 shows up, the pip line did not run inside the virtual environment, so activate it and install again.

Step 2: See the bug on a real Flask page

Here is the mistake in its most natural form. The page greets whoever the URL names, and the developer builds the greeting with an f-string because that is how Python programmers build strings. Create step02_vulnerable.py:

# step02_vulnerable.py - a Flask page that builds its template from the visitor's text
import models  # noqa: F401  (sets the demo CANARY_TOKEN environment variable)
from flask import Flask, render_template_string, request

app = Flask(__name__)
app.config["SECRET_KEY"] = "demo-flask-secret-key"


@app.get("/hello")
def hello():
    name = request.args.get("name", "world")
    # The bug: the visitor's text becomes part of the template source.
    return render_template_string(f"<h1>Hello {name}</h1>")


PROBES = [
    ("a normal name", "Ada"),
    ("arithmetic", "{{ 7 * 7 }}"),
    ("the Flask config", "{{ config.SECRET_KEY }}"),
    ("an environment variable", "{{ lipsum.__globals__['os'].environ['CANARY_TOKEN'] }}"),
]

if __name__ == "__main__":
    client = app.test_client()
    for label, probe in PROBES:
        reply = client.get("/hello", query_string={"name": probe})
        print(f"{label}: {probe}")
        print(f"  -> HTTP {reply.status_code} {reply.get_data(as_text=True).strip()}")

Look at the one line marked as the bug. render_template_string takes the template source as a string. The f-string pastes the visitor’s name into that source before the engine ever sees it, so the engine cannot tell the developer’s text from the visitor’s. The four probes at the bottom are a normal name and three harmless ways of asking “will you run my text?”. The script uses Flask’s test client, so it makes the requests itself.

python step02_vulnerable.py
a normal name: Ada
  -> HTTP 200 <h1>Hello Ada</h1>
arithmetic: {{ 7 * 7 }}
  -> HTTP 200 <h1>Hello 49</h1>
the Flask config: {{ config.SECRET_KEY }}
  -> HTTP 200 <h1>Hello demo-flask-secret-key</h1>
an environment variable: {{ lipsum.__globals__['os'].environ['CANARY_TOKEN'] }}
  -> HTTP 200 <h1>Hello canary-value-12345</h1>

What each probe shows

  • A normal name works as intended. Nothing looks wrong, which is why this bug survives code review and ordinary testing.
  • Arithmetic: {{ 7 * 7 }} came back as 49. The engine evaluated the visitor’s text. This is the simplest possible proof that the text is being treated as template code, and it is harmless.
  • The Flask config: Flask puts a few objects into every template’s context. Its documentation lists config, “the current configuration object,” among the globals available by default. So {{ config.SECRET_KEY }} printed a secret from the app’s configuration straight into the page.
  • An environment variable: Jinja2 gives templates a few helper globals, and its documentation lists range(), lipsum(), dict(), cycler, joiner and namespace. lipsum is an ordinary Python function, and every Python function has a __globals__ attribute: the dictionary of the variables in the module it was written in. That dictionary contains the os module, as the output shows, and os.environ is where servers often keep their secrets.

I stopped at reading a harmless canary on purpose. The point is the capability: a page that only meant to say hello now lets a visitor walk through the engine into the running Python process. Do not run probes like these against sites you do not own or have permission to test.

Step 3: Fix it by keeping the visitor’s text out of the template

The cure is not a smarter filter. It is to make the template a constant and pass the visitor’s text in as data. Create step03_fixed.py. The only change in the route is the marked line, and the script then repeats the probes and adds a script tag:

# step03_fixed.py - keep the visitor's text out of the template source
import models  # noqa: F401
from flask import Flask, render_template_string, request
from jinja2 import Environment, Template

app = Flask(__name__)
app.config["SECRET_KEY"] = "demo-flask-secret-key"


@app.get("/hello")
def hello():
    name = request.args.get("name", "world")
    # The fix: the template is a constant, and the visitor's text is passed in as data.
    return render_template_string("<h1>Hello {{ name }}</h1>", name=name)


PROBES = [
    ("a normal name", "Ada"),
    ("arithmetic", "{{ 7 * 7 }}"),
    ("the Flask config", "{{ config.SECRET_KEY }}"),
    ("an environment variable", "{{ lipsum.__globals__['os'].environ['CANARY_TOKEN'] }}"),
    ("a script tag", "<script>alert(1)</script>"),
]

if __name__ == "__main__":
    client = app.test_client()
    for label, probe in PROBES:
        reply = client.get("/hello", query_string={"name": probe})
        print(f"{label}: {probe}")
        print(f"  -> HTTP {reply.status_code} {reply.get_data(as_text=True).strip()}")

    print()
    print("=== escaping is a separate switch")
    attack = "<script>alert(1)</script>"
    print("jinja2.Template:                ", Template("<p>{{ x }}</p>").render(x=attack))
    print("Environment(autoescape=True):   ", Environment(autoescape=True).from_string("<p>{{ x }}</p>").render(x=attack))
python step03_fixed.py
a normal name: Ada
  -> HTTP 200 <h1>Hello Ada</h1>
arithmetic: {{ 7 * 7 }}
  -> HTTP 200 <h1>Hello {{ 7 * 7 }}</h1>
the Flask config: {{ config.SECRET_KEY }}
  -> HTTP 200 <h1>Hello {{ config.SECRET_KEY }}</h1>
an environment variable: {{ lipsum.__globals__['os'].environ['CANARY_TOKEN'] }}
  -> HTTP 200 <h1>Hello {{ lipsum.__globals__[&#39;os&#39;].environ[&#39;CANARY_TOKEN&#39;] }}</h1>
a script tag: <script>alert(1)</script>
  -> HTTP 200 <h1>Hello &lt;script&gt;alert(1)&lt;/script&gt;</h1>

=== escaping is a separate switch
jinja2.Template:                 <p><script>alert(1)</script></p>
Environment(autoescape=True):    <p>&lt;script&gt;alert(1)&lt;/script&gt;</p>

What changed, and why it works

The engine now sees the template <h1>Hello {{ name }}</h1>, which is fixed text that you wrote, and a variable called name. Data is never parsed as template code, so all three probes come back as plain text, including the one that asked for the config. This is the same idea as the parameterised queries in our SQL injection tutorial: the program and the data travel separately. Python’s t-strings, covered in our t-string tutorial, are the same principle built into the language.

Notice that the apostrophes in the environment-variable probe turned into &#39; and the script tag into &lt;script&gt;. That is autoescape, a different safety feature. Flask’s documentation says that “autoescaping is enabled for all strings when using render_template_string()”. Plain Jinja2 is not so careful: the last two lines show that jinja2.Template left the script tag untouched while Environment(autoescape=True) escaped it. Jinja’s own API documentation warns that “in future versions of Jinja we might enable autoescaping by default for security reasons” and encourages you to “explicitly configure autoescaping now instead of relying on the default.”

Keep the two problems apart in your head. Injection is about your server running text it should only have displayed; escaping is about the visitor’s browser. Escaping would not have stopped Step 2, and the fix in this step does not replace escaping. Our static site generator tutorial shows the autoescape side in more detail.

Check that it worked: the three template probes are printed back as text, and the script tag is escaped. Also note that templates stored as files, loaded with render_template("name.html"), use the same engine. The risk was never the engine; it was where the template source came from.

Step 4: The same bug in plain Python: format strings

Python has a second template system built in, str.format, and it has a version of the same problem. The Python documentation says: “The arg_name can be followed by any number of index or attribute expressions. An expression of the form ‘.name’ selects the named attribute using getattr(), while an expression of the form ‘[index]’ does an index lookup using __getitem__().” That is useful in your own code and dangerous when the format string comes from a user, for example a customisable greeting stored in a settings page. Create step04_format.py:

# step04_format.py - the same bug in plain Python: a format string that the user controls
import string

import models


class PlainFormatter(string.Formatter):
    """str.format rules, but a replacement field may only be a plain name."""

    def get_field(self, field_name, args, kwargs):
        if not field_name.isidentifier():
            raise ValueError(f"field {field_name!r} is not a plain name")
        return self.get_value(field_name, args, kwargs), field_name


ATTACK = "Hi {customer.__init__.__globals__[SECRET_TOKEN]}"
customer = models.demo_customer()
strings = {"customer": customer.first_name}


def attempt(label, call):
    try:
        print(f"{label:<38}{call()}")
    except Exception as exc:  # the point is to show every outcome
        print(f"{label:<38}{type(exc).__name__}: {exc}")


print("attack text:", ATTACK)
attempt("str.format, model object", lambda: ATTACK.format(customer=customer))
attempt("str.format, plain strings only", lambda: ATTACK.format_map(strings))
attempt("str.format, strings, class probe", lambda: "Hi {customer.__class__.__name__}".format_map(strings))
attempt("string.Template (needs $name)", lambda: string.Template("Hi $customer.__init__").safe_substitute(strings))
attempt("PlainFormatter, model object", lambda: PlainFormatter().format(ATTACK, customer=customer))
attempt("PlainFormatter, normal text", lambda: PlainFormatter().format("Hi {first_name}", first_name="Ada"))
python step04_format.py
attack text: Hi {customer.__init__.__globals__[SECRET_TOKEN]}
str.format, model object              Hi format-demo-secret-789
str.format, plain strings only        AttributeError: 'method-wrapper' object has no attribute '__globals__'
str.format, strings, class probe      Hi str
string.Template (needs $name)         Hi Ada.__init__
PlainFormatter, model object          ValueError: field 'customer.__init__.__globals__[SECRET_TOKEN]' is not a plain name
PlainFormatter, normal text           Hi Ada

Reading the six results

The attack text is {customer.__init__.__globals__[SECRET_TOKEN]}. Read it left to right: take the customer object, its __init__ method, that method’s __globals__ (the module’s variables, which here include SECRET_TOKEN from models.py), and index it with the key. No code was “run”; str.format only followed attributes, and that was enough to leak the secret in row one.

Row two shows a defence by accident: when the only values you pass are plain strings, the same walk fails with an AttributeError, because a string’s __init__ has no __globals__. Row three shows what does still work against strings, harmless class information. But you would be relying on every value being a string forever, and the failure is a crash, not a refusal. string.Template is safer by design: the Python documentation says an identifier in $identifier is limited to ASCII letters, digits and underscores, and that “the first non-identifier character after the $ character terminates this placeholder specification.” In row four the dot ends the placeholder, so only $customer was replaced and .__init__ stayed as plain text.

The last two rows are a small formatter of my own. string.Formatter resolves each replacement field in a method called get_field, so a subclass can refuse anything that is not a bare name. PlainFormatter still fills named fields such as {first_name}, but it refuses customer.__init__... with a clear error. It also refuses positional fields such as {0}, because those are not names. One more note from the same documentation page: the name safe_substitute is about missing keys, not security, since it “will silently ignore malformed templates.” An f-string is part of your source code, so a visitor can never write one; the problem exists only when .format is called on text that came from outside.

Check that it worked: only the str.format, model object line contains the demo secret format-demo-secret-789.

Step 5: When users must write templates, learn what the sandbox does and does not do

Sometimes a user-written template is the feature. The Jinja documentation names the case itself: “to allow users of an internal reporting system to create custom emails. You would document what data is available in the templates, then the user would write a template using that information.” For that, Jinja2 offers SandboxedEnvironment and ImmutableSandboxedEnvironment. The documentation says the 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.”

Before relying on it, test it. Create step05_matrix.py. It runs eight probes through three environments (the plain one and both sandboxes) and prints one cell per pair. The word BLOCKED in the output is my own label for a SecurityError. The last part of the script tries the documented unsafe decorator on a method.

# step05_matrix.py - what each Jinja2 environment lets a template do
import models
from jinja2 import Environment
from jinja2.sandbox import ImmutableSandboxedEnvironment, SandboxedEnvironment, unsafe

ENVIRONMENTS = [("Environment", Environment), ("SandboxedEnvironment", SandboxedEnvironment),
                ("ImmutableSandboxedEnv.", ImmutableSandboxedEnvironment)]
PROBES = [
    ("arithmetic", "{{ 7 * 7 }}"),
    ("environment variable", "{{ lipsum.__globals__['os'].environ['CANARY_TOKEN'] }}"),
    ("class walk to a global", "{{ user.__class__.__init__.__globals__['SECRET_TOKEN'] }}"),
    ("str.format walk", "{{ '{0.__init__.__globals__[SECRET_TOKEN]}'.format(user) }}"),
    ("public field", "{{ user.password_hash }}"),
    ("public method", "{{ user.delete() }}"),
    ("50 MB string", "{{ ('x' * 50000000) | length }}"),
    ("range(1000000)", "{{ range(1000000) | length }}"),
]


def cell(env_class, source):
    user = models.demo_customer()
    try:
        result = env_class().from_string(source).render(user=user)
    except Exception as exc:
        return "BLOCKED" if type(exc).__name__ == "SecurityError" else f"error: {type(exc).__name__}"
    return f"ran: {result}"


print(f"{'probe':<24}" + "".join(f"{name:<30}" for name, _ in ENVIRONMENTS))
for label, source in PROBES:
    print(f"{label:<24}" + "".join(f"{cell(env_class, source):<30}" for _, env_class in ENVIRONMENTS))

print()
print("=== what the sandbox says when it blocks")
sandbox = SandboxedEnvironment()
print("{{ user.__class__ }} renders as:", repr(sandbox.from_string("{{ user.__class__ }}").render(user=models.demo_customer())))
try:
    sandbox.from_string("{{ user.__class__.__init__.__globals__['SECRET_TOKEN'] }}").render(user=models.demo_customer())
except Exception as exc:
    print(f"{type(exc).__name__}: {exc}")


class GuardedCustomer(models.Customer):
    @unsafe  # the documented way to keep a method with side effects away from templates
    def delete(self):
        return super().delete()


print()
print("=== the documented fix for a method with side effects")
guarded = GuardedCustomer("Ada", "Lovelace", "pro", "pbkdf2$demo$ada-hash")
for source in ("{{ user.delete() }}", "{{ user.password_hash }}"):
    try:
        print(f"{source:<26}-> {sandbox.from_string(source).render(user=guarded)}")
    except Exception as exc:
        print(f"{source:<26}-> {type(exc).__name__}")
print("user.deleted after the template ran:", guarded.deleted)
python step05_matrix.py
probe                   Environment                   SandboxedEnvironment          ImmutableSandboxedEnv.        
arithmetic              ran: 49                       ran: 49                       ran: 49                       
environment variable    ran: canary-value-12345       BLOCKED                       BLOCKED                       
class walk to a global  ran: format-demo-secret-789   BLOCKED                       BLOCKED                       
str.format walk         ran: format-demo-secret-789   BLOCKED                       BLOCKED                       
public field            ran: pbkdf2$demo$ada-hash     ran: pbkdf2$demo$ada-hash     ran: pbkdf2$demo$ada-hash     
public method           ran: deleted                  ran: deleted                  ran: deleted                  
50 MB string            ran: 50000000                 ran: 50000000                 ran: 50000000                 
range(1000000)          ran: 1000000                  error: OverflowError          error: OverflowError          

What the table tells you

  • The plain Environment runs everything. Every probe works, which is the Step 2 situation.
  • The sandboxes stop the three “walk into Python’s internals” probes. The environment variable, the class walk and the str.format walk are all BLOCKED, just as the documentation promises.
  • They do not stop the others. Arithmetic runs, which is fine. But {{ user.password_hash }} printed the password hash, because it is an ordinary public field of the object I passed in, and {{ user.delete() }} ran the method and returned deleted. A sandbox protects Python’s internals; it cannot know that your public attributes are secret or that your public methods have side effects.
  • They do not limit resources. The 50 MB string was built in all three environments. The only size limit is that range(1000000) fails in both sandboxes with an OverflowError, a cap on a single call that Step 6 shows is easy to walk around.

The method call is exactly the lesson from the GitLab report: the sandbox does not block method calls on the objects you give it. The Jinja documentation says so directly: “Pass only the data that is relevant to the template. Avoid passing global data, or objects with methods that have side effects.” Here is what the sandbox says when it does block something, and the documented repair for the method problem:

=== what the sandbox says when it blocks
{{ user.__class__ }} renders as: ''
SecurityError: access to attribute '__init__' of 'Undefined' object is unsafe.

=== the documented fix for a method with side effects
{{ user.delete() }}       -> SecurityError
{{ user.password_hash }}  -> pbkdf2$demo$ada-hash
user.deleted after the template ran: False

Two details are worth understanding. First, the plain sandbox answers a forbidden lookup with a placeholder: {{ user.__class__ }} rendered as an empty string with no error, and the error only appears when something else touches the placeholder (the message names the second step, which is why it says '__init__' of 'Undefined' object; that is my reading of the output). Our final renderer will use StrictUndefined so that a blocked lookup fails immediately. Second, the unsafe decorator fixed the method, as the documentation describes, but the password_hash field is still readable. Decorating things one by one means you must remember every dangerous attribute forever, which is why Step 7 passes plain data objects instead.

Step 6: The sandbox blocks attributes, not appetite

The Jinja documentation has one more warning: “It is possible to construct a relatively small template that renders to a very large amount of output, which could correspond to a high use of CPU or memory. You should run your application with limits on resources such as CPU and memory to mitigate this.” Let us measure what “small” means. Create step06_limits.py. It times a string multiplication and two nested loops inside the strictest sandbox, then does a little arithmetic with the measured speed:

# step06_limits.py - the sandbox blocks attributes, not appetite
import time
import tracemalloc

from jinja2.sandbox import ImmutableSandboxedEnvironment

env = ImmutableSandboxedEnvironment()


def timed(source):
    started = time.perf_counter()
    env.from_string(source).render()
    return time.perf_counter() - started


def peak_mib(source):
    tracemalloc.start()
    env.from_string(source).render()
    peak = tracemalloc.get_traced_memory()[1]
    tracemalloc.stop()
    return peak / 2**20


print("=== memory: one multiplication in a template under 40 characters")
for n in (10_000_000, 50_000_000, 100_000_000):
    source = "{{ ('x' * %d) | length }}" % n
    print(f"{n:>12,} characters: {timed(source) * 1000:6.1f} ms, peak {peak_mib(source):6.1f} MiB")

print()
print("=== time: two nested loops in a template under 100 characters")
rate = 0
for n in (300, 1000, 2000):
    source = "{%% for i in range(%d) %%}{%% for j in range(%d) %%}{%% endfor %%}{%% endfor %%}" % (n, n)
    secs = timed(source)
    rate = n * n / secs
    print(f"{n:>5} x {n:<5}= {n * n:>9,} iterations: {secs * 1000:8.1f} ms ({rate / 1e6:.1f} million per second)")

print()
print("=== the one cap the sandbox has: a single range() call")
try:
    env.from_string("{{ range(1000000) | length }}").render()
except Exception as exc:
    print(f"{type(exc).__name__}: {exc}")
cap = 100_000
print(f"two loops at that cap: {cap ** 2:,} iterations, about {cap ** 2 / rate / 60:,.0f} minutes of one CPU at the last rate")
print(f"three loops at that cap: {cap ** 3:,} iterations, about {cap ** 3 / rate / 86400:,.0f} days of one CPU at the last rate")
python step06_limits.py
=== memory: one multiplication in a template under 40 characters
  10,000,000 characters:    3.5 ms, peak    9.5 MiB
  50,000,000 characters:   11.4 ms, peak   47.7 MiB
 100,000,000 characters:   21.6 ms, peak   95.4 MiB

=== time: two nested loops in a template under 100 characters
  300 x 300  =    90,000 iterations:      1.9 ms (48.6 million per second)
 1000 x 1000 = 1,000,000 iterations:     14.2 ms (70.4 million per second)
 2000 x 2000 = 4,000,000 iterations:     56.5 ms (70.8 million per second)

=== the one cap the sandbox has: a single range() call
OverflowError: Range too big. The sandbox blocks ranges larger than MAX_RANGE (100000).
two loops at that cap: 10,000,000,000 iterations, about 2 minutes of one CPU at the last rate
three loops at that cap: 1,000,000,000,000,000 iterations, about 163 days of one CPU at the last rate

A template of 32 characters made the process allocate about 95 MiB in a few tens of milliseconds; a bigger number would ask for correspondingly more. The loops ran at roughly 70 million iterations a second on this machine, with an empty body, which makes this a rough lower bound on the cost. The sandbox’s MAX_RANGE of 100,000 limits each range() call, not the number of calls, so two nested loops at the cap are 10 billion iterations (my arithmetic: about two minutes of one CPU) and three nested loops are a million billion (about 160 days). All of that fits in a template of about 120 characters.

So a sandbox is the second layer, not the first. For a template feature you also need to limit what syntax a template may use, and how big its input and output can be. That is Step 7.

Step 7: Build a renderer that only runs what you allow

Here is the design, in five layers. Each one covers something the sandbox does not:

  1. Plain data in, not model objects. Templates see small frozen dataclasses that contain only the fields you want users to print. There is no password hash to leak and no method to call.
  2. An allowlist of syntax. Jinja turns template text into a tree of nodes before running anything. We walk that tree and refuse any node, variable name, field name or filter that is not on our list. A blocklist of bad words has to predict every trick; an allowlist only has to name what you want to support.
  3. The sandbox, autoescape and strict undefined values. The engine is the safety net underneath the allowlist.
  4. Caps. A maximum template size, a maximum output size and a maximum loop nesting depth.
  5. One error type. Every failure becomes a TemplateRejected with a message that says which rule and which line, so the caller never has to guess which Jinja exception might escape.

Create views.py first. These classes are the whole “API” your users get to template against. frozen=True makes them read-only and customer_view copies the display fields out of a model object:

# views.py - the only objects a user-written template is allowed to see
from dataclasses import dataclass


@dataclass(frozen=True, slots=True)
class CustomerView:
    first_name: str
    last_name: str
    plan: str


@dataclass(frozen=True, slots=True)
class ItemView:
    name: str
    qty: int
    price: str


@dataclass(frozen=True, slots=True)
class OrderView:
    id: int
    total: str
    items: tuple


def customer_view(customer):
    """Copy the display fields and nothing else: no secrets, no methods."""
    return CustomerView(customer.first_name, customer.last_name, customer.plan)

Now create safe_templates.py. Read it slowly; each part is explained underneath.

# safe_templates.py - render a template that a user wrote, without giving the user Python
from jinja2 import StrictUndefined, nodes
from jinja2.exceptions import TemplateError, TemplateSyntaxError
from jinja2.sandbox import ImmutableSandboxedEnvironment

from views import CustomerView, OrderView

MAX_SOURCE = 4000   # characters of template text we accept
MAX_OUTPUT = 20000  # characters of finished text we allow
MAX_LOOP_DEPTH = 2  # loops inside loops

ALLOWED_NAMES = {"customer", "order"}
ALLOWED_ATTRS = {"first_name", "last_name", "plan", "id", "total", "items", "name", "qty", "price",
                 "index", "first", "last", "length"}
ALLOWED_FILTERS = {"upper", "lower", "title", "capitalize", "trim", "default", "length"}
ALLOWED_NODES = (nodes.Template, nodes.Output, nodes.TemplateData, nodes.Name, nodes.Const,
                 nodes.Getattr, nodes.Filter, nodes.If, nodes.For, nodes.Compare, nodes.Operand,
                 nodes.Not, nodes.And, nodes.Or)

ENV = ImmutableSandboxedEnvironment(autoescape=True, undefined=StrictUndefined)


class TemplateRejected(ValueError):
    """The template broke a rule. The message says which rule and on which line."""


def walk(node, names, depth=0):
    kind = type(node).__name__
    if not isinstance(node, ALLOWED_NODES):
        raise TemplateRejected(f"line {node.lineno}: {kind} is not allowed in these templates")
    if isinstance(node, nodes.Getattr) and node.attr not in ALLOWED_ATTRS:
        raise TemplateRejected(f"line {node.lineno}: the field '{node.attr}' is not available")
    if isinstance(node, nodes.Filter) and node.name not in ALLOWED_FILTERS:
        raise TemplateRejected(f"line {node.lineno}: the filter '{node.name}' is not allowed")
    if isinstance(node, nodes.Name) and node.name not in names:
        raise TemplateRejected(f"line {node.lineno}: the name '{node.name}' is not available")
    if isinstance(node, nodes.For):
        if not isinstance(node.target, nodes.Name):
            raise TemplateRejected(f"line {node.lineno}: a loop may use only one variable")
        if depth >= MAX_LOOP_DEPTH:
            raise TemplateRejected(f"line {node.lineno}: loops may be nested at most {MAX_LOOP_DEPTH} deep")
        walk(node.iter, names, depth)
        inner = names | {node.target.name, "loop"}
        for child in (*node.body, *node.else_, *([node.test] if node.test else [])):
            walk(child, inner, depth + 1)
        return
    for child in node.iter_child_nodes():
        walk(child, names, depth)


def render_message(source, customer, order):
    if not isinstance(customer, CustomerView) or not isinstance(order, OrderView):
        raise TypeError("pass CustomerView and OrderView objects, not model objects")
    if not isinstance(source, str) or len(source) > MAX_SOURCE:
        raise TemplateRejected(f"the template must be text of at most {MAX_SOURCE} characters")
    try:
        tree = ENV.parse(source)
        walk(tree, ALLOWED_NAMES)
    except TemplateSyntaxError as exc:
        raise TemplateRejected(f"line {exc.lineno}: {exc.message}") from None
    except RecursionError:
        raise TemplateRejected("the template is nested too deeply") from None
    pieces, size = [], 0
    try:
        for piece in ENV.from_string(tree).generate(customer=customer, order=order):  # ssti: allow (tree passed walk())
            size += len(piece)
            if size > MAX_OUTPUT:
                raise TemplateRejected(f"the result is longer than {MAX_OUTPUT} characters")
            pieces.append(piece)
    except (TemplateError, TypeError) as exc:
        raise TemplateRejected(f"could not render: {exc}") from None
    return "".join(pieces)

How the code works

The lists at the top

These lists are the allowlist. Templates may use two variable names (customer and order), thirteen field names, seven filters (Jinja’s name for the | helpers) and fourteen kinds of syntax node. The node class names are Jinja’s own: Name is a variable, Getattr is a dot lookup, Filter is a pipe, and the ones we left out include Call (parentheses), Getitem (square brackets), Mul (the star), Include and Import.

The walk function

The walk function visits every node of the parsed template and raises TemplateRejected at the first one that is not allowed. The for branch is special for three reasons: a loop may bind only one variable, that variable is added to the list of known names only inside the loop body, and loops may be nested at most two deep. I added that last rule after the first version of this tutorial’s tests passed, when I realised that an output cap does not stop a template that loops a trillion times and prints nothing. A cap on output is not a cap on time.

The render_message function

The render_message function checks that you passed view objects, checks the size of the source, parses it, walks it and only then compiles it. The line that compiles uses the same tree we validated, so what we checked is exactly what runs (the # ssti: allow comment tells the CI gate in Step 10 that this one call is deliberate). It renders with generate(), which hands back the output in pieces, so the 20,000-character cap can stop a runaway template early instead of building the whole string first. Finally it turns Jinja’s own failures, a missing field or a sandbox violation or a type error, into TemplateRejected.

Now try it. Create step07_safe.py. It sends seventeen templates through the renderer: three that should work and fourteen that should not:

# step07_safe.py - the same ideas against the safe renderer
import models
from safe_templates import TemplateRejected, render_message
from views import ItemView, OrderView, customer_view

customer = customer_view(models.demo_customer())
order = OrderView(1042, "37.50", (ItemView("Widget", 2, "10.00"), ItemView("Gadget", 1, "17.50")))
big_order = OrderView(7, "0.00", tuple(ItemView("n" * 20, 1, "1.00") for _ in range(200)))

TEMPLATES = [
    ("greeting", "Hello {{ customer.first_name }}!"),
    ("loop and filter", "{% for item in order.items %}{{ loop.index }}. {{ item.name | upper }} x{{ item.qty }}; {% endfor %}"),
    ("condition", "{% if customer.plan == 'pro' %}Thanks for going pro.{% else %}Upgrade today.{% endif %}"),
    ("arithmetic", "{{ 7 * 7 }}"),
    ("a global function", "{{ lipsum.__globals__['os'].environ['CANARY_TOKEN'] }}"),
    ("a global name", "{{ lipsum }}"),
    ("a private attribute", "{{ customer.__class__.__init__ }}"),
    ("a secret field", "{{ customer.password_hash }}"),
    ("a method call", "{{ customer.first_name.upper() }}"),
    ("a loop that never ends", "{% for i in range(100000) %}{% endfor %}"),
    ("a big string", "{{ ('x' * 50000000) | length }}"),
    ("the safe filter", "{{ customer.first_name | safe }}"),
    ("an include", "{% include 'secrets.txt' %}"),
    ("a field of the wrong object", "{{ customer.total }}"),
    ("a broken template", "{{ customer.first_name "),
    ("loops nested too deep", "{% for a in order.items %}" * 3 + "x" + "{% endfor %}" * 3),
    ("too much output", "{% for a in order.items %}{% for b in order.items %}{{ b.name }}{% endfor %}{% endfor %}"),
]
for label, source in TEMPLATES:
    shown_order = big_order if label == "too much output" else order
    try:
        print(f"{'OK':<9}{label:<30}{render_message(source, customer, shown_order)}")
    except TemplateRejected as exc:
        print(f"{'REFUSED':<9}{label:<30}{exc}")
python step07_safe.py
OK       greeting                      Hello Ada!
OK       loop and filter               1. WIDGET x2; 2. GADGET x1; 
OK       condition                     Thanks for going pro.
REFUSED  arithmetic                    line 1: Mul is not allowed in these templates
REFUSED  a global function             line 1: Getitem is not allowed in these templates
REFUSED  a global name                 line 1: the name 'lipsum' is not available
REFUSED  a private attribute           line 1: the field '__init__' is not available
REFUSED  a secret field                line 1: the field 'password_hash' is not available
REFUSED  a method call                 line 1: Call is not allowed in these templates
REFUSED  a loop that never ends        line 1: Call is not allowed in these templates
REFUSED  a big string                  line 1: Mul is not allowed in these templates
REFUSED  the safe filter               line 1: the filter 'safe' is not allowed
REFUSED  an include                    line 1: Include is not allowed in these templates
REFUSED  a field of the wrong object   could not render: 'views.CustomerView object' has no attribute 'total'
REFUSED  a broken template             line 1: unexpected end of template, expected 'end of print statement'.
REFUSED  loops nested too deep         line 1: loops may be nested at most 2 deep
REFUSED  too much output               the result is longer than 20000 characters

Reading the output: the three good templates rendered. Each refusal names the rule: arithmetic is a Mul node, the environment-variable probe died at its first square bracket (Getitem), lipsum is not on the list of names, __init__ and password_hash are not on the list of fields, and so on. “A field of the wrong object” is the one failure that happens while rendering: total is a field of an order, not a customer, so StrictUndefined raised an error instead of printing a blank. The last two rows are the caps. The loop-depth rule fires on any data. The output cap needs a big order, so the script uses one with 200 items, and two nested loops over it would have produced 800,000 characters had they not been stopped at 20,000.

Step 8: Put it behind a route

In an app, the renderer sits at the edge: it converts your model objects to views, calls render_message, and turns TemplateRejected into an HTTP 422 for the person who wrote the template. Create step08_endpoint.py:

# step08_endpoint.py - the safe renderer behind a Flask route
import models
from flask import Flask, jsonify, request
from safe_templates import TemplateRejected, render_message
from views import ItemView, OrderView, customer_view

app = Flask(__name__)
app.config["SECRET_KEY"] = "demo-flask-secret-key"


@app.post("/preview")
def preview():
    body = request.get_json(silent=True) or {}
    customer = customer_view(models.demo_customer())
    order = OrderView(1042, "37.50", (ItemView("Widget", 2, "10.00"), ItemView("Gadget", 1, "17.50")))
    try:
        return jsonify(html=render_message(body.get("template", ""), customer, order))
    except TemplateRejected as exc:
        return jsonify(error=str(exc)), 422


if __name__ == "__main__":
    client = app.test_client()
    for template in ("Hi {{ customer.first_name }}, order {{ order.id }} is on its way.",
                     "{{ config.SECRET_KEY }}",
                     "{{ lipsum.__globals__['os'].environ['CANARY_TOKEN'] }}"):
        reply = client.post("/preview", json={"template": template})
        print(template)
        print(f"  -> HTTP {reply.status_code} {reply.get_json()}")
python step08_endpoint.py
Hi {{ customer.first_name }}, order {{ order.id }} is on its way.
  -> HTTP 200 {'html': 'Hi Ada, order 1042 is on its way.'}
{{ config.SECRET_KEY }}
  -> HTTP 422 {'error': "line 1: the field 'SECRET_KEY' is not available"}
{{ lipsum.__globals__['os'].environ['CANARY_TOKEN'] }}
  -> HTTP 422 {'error': 'line 1: Getitem is not allowed in these templates'}

The first request is the feature working: a customer’s name and an order number in a friendly message. The next two are the Step 2 attacks, which now get a polite refusal that describes the rule and nothing about the server. Note that these messages tell the template author which rule failed and where, and they do not echo values. The one message that comes from the engine itself (the “field of the wrong object” row in Step 7) names a view class, so return a generic message for that kind of error if you do not want class names in a response.

Step 9: Prove it with tests, a fuzz run and planted bugs

A security rule that nobody tests quietly stops working. The test file below checks the renderer in layers on purpose. One group of tests runs the allowlist alone, another runs the sandbox engine alone, and a third runs the whole path, so a mistake in one layer cannot hide behind the other. Create test_safe_templates.py:

# test_safe_templates.py - the rules, one test each, plus a seeded fuzz run
import dataclasses
import random

import models
import pytest
import safe_templates as st
from jinja2.exceptions import SecurityError
from safe_templates import TemplateRejected, render_message
from views import CustomerView, ItemView, OrderView, customer_view

CUSTOMER = CustomerView("Ada", "Lovelace", "pro")
ORDER = OrderView(1042, "37.50", (ItemView("Widget", 2, "10.00"), ItemView("Gadget", 1, "17.50")))
SECRETS = ("canary-value-12345", "format-demo-secret-789", "pbkdf2$demo$ada-hash")


def render(source, customer=CUSTOMER, order=ORDER):
    return render_message(source, customer, order)


GOOD = [
    ("Hello {{ customer.first_name }}!", "Hello Ada!"),
    ("{{ customer.first_name | upper }} {{ customer.last_name | lower }}", "ADA lovelace"),
    ("Order {{ order.id }} total {{ order.total }}", "Order 1042 total 37.50"),
    ("{{ order.items | length }} items", "2 items"),
    ("{% for item in order.items %}{{ loop.index }}. {{ item.name }} x{{ item.qty }}; {% endfor %}",
     "1. Widget x2; 2. Gadget x1; "),
    ("{% if customer.plan == 'pro' %}pro{% else %}free{% endif %}", "pro"),
    ("{% if customer.plan != 'pro' and order.id %}a{% elif order.id %}b{% endif %}", "b"),
    ("{{ customer.first_name | default('friend') }}", "Ada"),
    ("{# a comment #}plain text", "plain text"),
    ("{% for item in order.items %}{% if loop.first %}first: {% endif %}{{ item.name }} {% endfor %}",
     "first: Widget Gadget "),
    ("{% for item in order.items if item.qty > 1 %}{{ item.name }}{% endfor %}", "Widget"),
    ("{% for a in order.items %}{% for b in order.items %}.{% endfor %}{% endfor %}", "...."),
]

# Templates the validator must refuse by itself (it runs before the engine does).
VALIDATOR_BAD = {
    "multiplication": "{{ 7 * 7 }}",
    "power": "{{ 2 ** 64 }}",
    "big string": "{{ ('x' * 50000000) | length }}",
    "dunder attribute": "{{ customer.__class__ }}",
    "dunder chain": "{{ customer.__class__.__init__.__globals__ }}",
    "global through a function": "{{ lipsum.__globals__['os'].environ['CANARY_TOKEN'] }}",
    "global name lipsum": "{{ lipsum }}",
    "global name config": "{{ config }}",
    "global name cycler": "{{ cycler }}",
    "global name range": "{% for i in order.items %}{{ range }}{% endfor %}",
    "call": "{{ customer() }}",
    "method call": "{{ customer.first_name.upper() }}",
    "range loop": "{% for i in range(100000) %}{% endfor %}",
    "square brackets": "{{ customer['first_name'] }}",
    "slice": "{{ order.items[0] }}",
    "secret field": "{{ customer.password_hash }}",
    "safe filter": "{{ customer.first_name | safe }}",
    "attr filter": "{{ customer | attr('__class__') }}",
    "replace filter": "{{ customer.first_name | replace('a', 'b') }}",
    "format filter": "{{ '%s' | format(customer) }}",
    "include": "{% include 'secrets.txt' %}",
    "import": "{% import 'os' as os %}",
    "extends": "{% extends 'base.html' %}",
    "set": "{% set x = customer %}",
    "macro": "{% macro m() %}{% endmacro %}",
    "block": "{% block b %}{% endblock %}",
    "tuple loop": "{% for a, b in order.items %}{% endfor %}",
    "three nested loops": "{% for a in order.items %}{% for b in order.items %}{% for c in order.items %}{% endfor %}{% endfor %}{% endfor %}",
    "loop variable outside the loop": "{{ item.name }}",
}
# Templates that only fail while rendering.
RUNTIME_BAD = {
    "a field the object does not have": "{{ customer.total }}",
    "iterating a number": "{% for x in order.id %}{% endfor %}",
    "syntax error": "{{ customer.first_name ",
}


@pytest.mark.parametrize("source, expected", GOOD)
def test_good_templates_render(source, expected):
    assert render(source) == expected


@pytest.mark.parametrize("source", VALIDATOR_BAD.values(), ids=VALIDATOR_BAD.keys())
def test_validator_alone_refuses(source):
    with pytest.raises(TemplateRejected):
        st.walk(st.ENV.parse(source), st.ALLOWED_NAMES)


@pytest.mark.parametrize("source", [*VALIDATOR_BAD.values(), *RUNTIME_BAD.values()],
                         ids=[*VALIDATOR_BAD.keys(), *RUNTIME_BAD.keys()])
def test_render_message_refuses(source):
    with pytest.raises(TemplateRejected):
        render(source)


@pytest.mark.parametrize("source", ["{{ customer.__class__ }}", "{{ customer.__init__.__globals__ }}",
                                    "{{ customer | attr('__class__') }}", "{{ '{0.__class__}'.format(customer) }}"])
def test_engine_alone_blocks_unsafe_attributes(source):
    with pytest.raises(SecurityError):
        st.ENV.from_string(source).render(customer=CUSTOMER)


def test_engine_alone_escapes_html():
    assert st.ENV.from_string("{{ customer.first_name }}").render(customer=CustomerView("<b>", "x", "y")) == "&lt;b&gt;"


def test_html_in_data_is_escaped():
    evil = CustomerView("<script>alert(1)</script>", "x", "pro")
    assert render("{{ customer.first_name }}", customer=evil) == "&lt;script&gt;alert(1)&lt;/script&gt;"


def test_html_the_author_typed_is_kept():
    assert render("<b>{{ customer.first_name }}</b>") == "<b>Ada</b>"


def test_source_cap():
    assert render("a" * st.MAX_SOURCE) == "a" * st.MAX_SOURCE
    with pytest.raises(TemplateRejected):
        render("a" * (st.MAX_SOURCE + 1))


def test_output_cap():
    big = OrderView(1, "0", tuple(ItemView("n" * 20, 1, "1") for _ in range(40)))
    source = "{% for a in order.items %}{% for b in order.items %}{{ b.name }}{% endfor %}{% endfor %}"
    with pytest.raises(TemplateRejected, match="longer than"):
        render(source, order=big)


def test_deep_nesting_is_refused_not_crashed():
    source = "{{ " + "(" * 1500 + "customer.first_name" + ")" * 1500 + " }}"
    with pytest.raises(TemplateRejected, match="nested too deeply"):
        render(source)


def test_model_objects_are_refused():
    with pytest.raises(TypeError):
        render_message("{{ customer.first_name }}", models.demo_customer(), ORDER)


def test_views_are_plain_data():
    assert [f.name for f in dataclasses.fields(CustomerView)] == ["first_name", "last_name", "plan"]
    assert [f.name for f in dataclasses.fields(ItemView)] == ["name", "qty", "price"]
    assert [f.name for f in dataclasses.fields(OrderView)] == ["id", "total", "items"]
    for cls in (CustomerView, ItemView, OrderView):
        assert [n for n, value in vars(cls).items() if callable(value) and not n.startswith("_")] == []


def test_customer_view_copies_only_display_fields():
    view = customer_view(models.demo_customer())
    assert view == CustomerView("Ada", "Lovelace", "pro")
    assert "pbkdf2" not in repr(view)


FRAGMENTS = ["{{ ", " }}", "{% ", " %}", "customer", "order", ".", "first_name", "total", "items", "__class__",
             "|", "upper", "safe", "for", "in", "endfor", "if", "endif", "else", "item", "loop", "range", "(", ")",
             "[", "]", "'x'", "*", "**", "7", "config", "lipsum", "__globals__", "include", "import", " ", "'",
             '"', "~", "+", "-", "=", "==", "is", "not", "and", "or", "hello ", "{# ", " #}"]


def test_fuzz_refuses_or_renders_without_secrets():
    rng = random.Random(7)
    accepted = refused = 0
    for _ in range(5000):
        source = "".join(rng.choice(FRAGMENTS) for _ in range(rng.randint(1, 24)))
        try:
            result = render(source)
        except TemplateRejected:
            refused += 1
            continue
        accepted += 1
        assert not any(secret in result for secret in SECRETS)
    assert accepted > 0 and refused > 0
python -m pytest test_safe_templates.py -q
.......................................................................................      [100%]
87 passed in 0.46s

Those 87 tests include a seeded fuzz test that builds 5,000 random templates from fragments and throws them at the renderer. Let us run the same idea at ten times the size and count the outcomes. Create step09_fuzz.py:

# step09_fuzz.py - throw random template fragments at the renderer
import random
import time

from safe_templates import TemplateRejected
from test_safe_templates import FRAGMENTS, SECRETS, render

rng = random.Random(7)
rendered = refused = leaked = 0
started = time.perf_counter()
for _ in range(50_000):
    source = "".join(rng.choice(FRAGMENTS) for _ in range(rng.randint(1, 24)))
    try:
        result = render(source)
    except TemplateRejected:
        refused += 1
        continue
    rendered += 1
    leaked += any(secret in result for secret in SECRETS)
print(f"50,000 random templates: {rendered:,} rendered, {refused:,} refused, {leaked} leaked a secret, "
      "0 other exceptions")
print(f"time: {time.perf_counter() - started:.1f} s")
python step09_fuzz.py
50,000 random templates: 26,373 rendered, 23,627 refused, 0 leaked a secret, 0 other exceptions
time: 4.0 s

Of 50,000 random templates, about half rendered and the rest were refused, none leaked a demo secret, and every failure was a TemplateRejected rather than some other exception. That is the number to watch if you change the rules later.

Do the tests notice a broken rule?

Passing tests only prove something if they would fail when the code is wrong. Mutation testing checks that: plant one bug at a time in a copy of the code, run the tests, and see whether they catch it. Create mutations.py. Each entry edits one line, such as switching autoescape off, allowing the star operator, or letting a secret into a view:

# mutations.py - plant one bug at a time in a copy of the code and check that the tests notice
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile

HERE = pathlib.Path(__file__).parent
FILES = ["models.py", "views.py", "safe_templates.py", "test_safe_templates.py"]
MUTANTS = [
    ("M01", "plain Environment instead of the sandbox", "safe_templates.py",
     [("from jinja2.sandbox import ImmutableSandboxedEnvironment", "from jinja2 import Environment as ImmutableSandboxedEnvironment")]),
    ("M02", "autoescape switched off", "safe_templates.py", [("autoescape=True", "autoescape=False")]),
    ("M03", "undefined values print as empty text", "safe_templates.py",
     [("from jinja2 import StrictUndefined, nodes", "from jinja2 import Undefined, nodes"),
      ("undefined=StrictUndefined", "undefined=Undefined")]),
    ("M04", "double-underscore attribute names allowed", "safe_templates.py",
     [('ALLOWED_ATTRS = {"first_name",', 'ALLOWED_ATTRS = {"__class__", "first_name",')]),
    ("M05", "multiplication allowed", "safe_templates.py",
     [("nodes.Not, nodes.And, nodes.Or)", "nodes.Not, nodes.And, nodes.Or, nodes.Mul)")]),
    ("M06", "calls allowed", "safe_templates.py",
     [("nodes.Not, nodes.And, nodes.Or)", "nodes.Not, nodes.And, nodes.Or, nodes.Call)")]),
    ("M07", "include tags allowed", "safe_templates.py",
     [("nodes.Not, nodes.And, nodes.Or)", "nodes.Not, nodes.And, nodes.Or, nodes.Include)")]),
    ("M08", "the safe filter allowed", "safe_templates.py",
     [('ALLOWED_FILTERS = {"upper",', 'ALLOWED_FILTERS = {"safe", "upper",')]),
    ("M09", "a global name allowed", "safe_templates.py",
     [('ALLOWED_NAMES = {"customer", "order"}', 'ALLOWED_NAMES = {"customer", "order", "lipsum"}')]),
    ("M10", "loops may unpack several variables", "safe_templates.py",
     [("if not isinstance(node.target, nodes.Name):", "if False:")]),
    ("M11", "no output cap", "safe_templates.py", [("if size > MAX_OUTPUT:", "if False:")]),
    ("M12", "no source cap", "safe_templates.py", [("len(source) > MAX_SOURCE", "False")]),
    ("M13", "model objects accepted", "safe_templates.py",
     [("if not isinstance(customer, CustomerView) or not isinstance(order, OrderView):", "if False:")]),
    ("M14", "a secret added to the customer view", "views.py",
     [("    plan: str\n", '    plan: str\n    password_hash: str = ""\n')]),
    ("M15", "deep nesting crashes instead of being refused", "safe_templates.py",
     [("except RecursionError:", "except ZeroDivisionError:")]),
    ("M16", "loops may be nested without limit", "safe_templates.py", [("if depth >= MAX_LOOP_DEPTH:", "if False:")]),
    ("M17", "a runtime TypeError escapes", "safe_templates.py",
     [("except (TemplateError, TypeError) as exc:", "except TemplateError as exc:")]),
]
ENV = dict(os.environ, PYTHONUTF8="1", PYTHONDONTWRITEBYTECODE="1", COLUMNS="170")


def run_tests(folder):
    result = subprocess.run([sys.executable, "-m", "pytest", "-x", "-q", "-p", "no:cacheprovider", "--no-header"],
                            cwd=folder, env=ENV, capture_output=True, text=True, timeout=600)
    failed = next((ln for ln in result.stdout.splitlines() if ln.startswith("FAILED")), "")
    return result.returncode, failed


def fresh_copy():
    folder = pathlib.Path(tempfile.mkdtemp(prefix="mut_"))
    for name in FILES:
        shutil.copy(HERE / name, folder / name)
    return folder


code, _ = run_tests(HERE)
print(f"control (no bug planted): {'tests pass' if code == 0 else 'TESTS FAIL'}")
caught = 0
for tag, label, filename, edits in MUTANTS:
    folder = fresh_copy()
    path = folder / filename
    text = path.read_text(encoding="utf-8")
    for old, new in edits:
        assert text.count(old) == 1, (tag, old, text.count(old))
        text = text.replace(old, new)
    path.write_text(text, encoding="utf-8", newline="\n")
    code, failed = run_tests(folder)
    shutil.rmtree(folder, ignore_errors=True)
    caught += code != 0
    first = failed.replace("FAILED test_safe_templates.py::", "").split(" - ")[0]
    print(f"{'caught' if code != 0 else 'MISSED':<7}{tag} {label:<48}{first}")
print(f"caught {caught} of {len(MUTANTS)}")
python mutations.py
control (no bug planted): tests pass
caught M01 plain Environment instead of the sandbox        test_engine_alone_blocks_unsafe_attributes[{{ customer.__class__ }}]
caught M02 autoescape switched off                         test_engine_alone_escapes_html
caught M03 undefined values print as empty text            test_render_message_refuses[a field the object does not have]
caught M04 double-underscore attribute names allowed       test_validator_alone_refuses[dunder attribute]
caught M05 multiplication allowed                          test_validator_alone_refuses[multiplication]
caught M06 calls allowed                                   test_validator_alone_refuses[call]
caught M07 include tags allowed                            test_validator_alone_refuses[include]
caught M08 the safe filter allowed                         test_validator_alone_refuses[safe filter]
caught M09 a global name allowed                           test_validator_alone_refuses[global name lipsum]
caught M10 loops may unpack several variables              test_validator_alone_refuses[tuple loop]
caught M11 no output cap                                   test_output_cap
caught M12 no source cap                                   test_source_cap
caught M13 model objects accepted                          test_model_objects_are_refused
caught M14 a secret added to the customer view             test_views_are_plain_data
caught M15 deep nesting crashes instead of being refused   test_deep_nesting_is_refused_not_crashed
caught M16 loops may be nested without limit               test_validator_alone_refuses[three nested loops]
caught M17 a runtime TypeError escapes                     test_render_message_refuses[iterating a number]
caught 17 of 17

All 17 planted bugs were caught, and the name of the first failing test tells you which layer noticed. Look at M04, which added __class__ to the allowed fields: the full renderer would still have refused that template, because the sandbox underneath caught it, so only the “validator alone” test noticed. That is the reason those layered tests exist. If your own tests miss a mutant, write the test that kills it before you trust the rule.

Step 10: Add a CI gate so the bug cannot come back

The renderer protects the code path you wrote. Nothing yet stops a teammate from adding a new render_template_string(f"...") somewhere else next month. A small static check can: it reads each Python file as a syntax tree, without running it, and flags the call shapes from this tutorial. Python’s ast module does the parsing. Create ssti_gate.py:

# ssti_gate.py - fail the build when a template, or a format string, can come from a variable
import ast
import pathlib
import sys

HARD = {
    "SSTI001": "render_template_string() with a template that is not a plain string",
    "SSTI002": "jinja2.Template() built from something that is not a plain string",
    "SSTI003": "from_string() called with something that is not a plain string",
    "SSTI004": "a Jinja2 environment created without autoescape",
}
REVIEW = {"SSTI005": "str.format() on something that is not a string literal or a CONSTANT"}


def is_text(node):
    return isinstance(node, ast.Constant) and isinstance(node.value, str)


def first_argument(call, keyword):
    if call.args:
        return call.args[0]
    return next((kw.value for kw in call.keywords if kw.arg == keyword), None)


def check_source(source):
    """Return a sorted list of (line, rule) for the text of one Python file."""
    tree = ast.parse(source)
    jinja = {}  # local name -> the name it has in jinja2
    for node in ast.walk(tree):
        if isinstance(node, ast.ImportFrom) and (node.module or "").split(".")[0] == "jinja2":
            for alias in node.names:
                jinja[alias.asname or alias.name] = alias.name
    found = []
    for node in ast.walk(tree):
        if not isinstance(node, ast.Call):
            continue
        func = node.func
        name = func.id if isinstance(func, ast.Name) else func.attr if isinstance(func, ast.Attribute) else ""
        owner = func.value.id if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name) else ""
        via_jinja = (isinstance(func, ast.Name) and name in jinja) or owner == "jinja2"
        real = jinja.get(name, name) if isinstance(func, ast.Name) else name
        if name == "render_template_string" and not is_text(first_argument(node, "source")):
            found.append((node.lineno, "SSTI001"))
        elif real == "Template" and via_jinja and not is_text(first_argument(node, "source")):
            found.append((node.lineno, "SSTI002"))
        elif name == "from_string" and isinstance(func, ast.Attribute) and not is_text(first_argument(node, "source")):
            found.append((node.lineno, "SSTI003"))
        elif real.endswith("Environment") and via_jinja:
            setting = next((kw.value for kw in node.keywords if kw.arg == "autoescape"), None)
            safe = isinstance(setting, ast.Call) or (isinstance(setting, ast.Constant) and setting.value is True)
            if not safe:
                found.append((node.lineno, "SSTI004"))
        elif name in ("format", "format_map") and isinstance(func, ast.Attribute):
            receiver = func.value
            constant = isinstance(receiver, ast.Name) and receiver.id.isupper()
            if not (is_text(receiver) or isinstance(receiver, ast.JoinedStr) or constant):
                found.append((node.lineno, "SSTI005"))
    allowed = {n for n, text in enumerate(source.splitlines(), start=1) if "# ssti: allow" in text}
    return sorted(item for item in set(found) if item[0] not in allowed)


def python_files(paths):
    for path in map(pathlib.Path, paths):
        if path.is_dir():
            yield from (p for p in sorted(path.rglob("*.py")) if ".venv" not in p.parts)
        else:
            yield path


def main(paths):
    failures = 0
    for path in python_files(paths):
        for line, rule in check_source(path.read_text(encoding="utf-8")):
            kind = "error" if rule in HARD else "review"
            print(f"{path}:{line}: {rule} {kind}: {({**HARD, **REVIEW})[rule]}")
            failures += rule in HARD
    print(f"{failures} problem(s) that fail the build")
    return 1 if failures else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:] or ["."]))

The gate has four rules that fail the build (SSTI001 to SSTI004) and one that only asks for a review (SSTI005, a .format call on something that is not a string literal or an ALL_CAPS constant, which is common and often fine). A line that is deliberately safe can carry a # ssti: allow comment, like the one in safe_templates.py.

How does it compare with Ruff?

Ruff already has security rules, so it is fair to ask whether you need your own gate. Create gate_samples.py, thirteen one-line call shapes where eight are risky and five are fine, and step10_gate.py, which asks Ruff with --select S (all of its security rules) and our gate about each line:

# gate_samples.py - thirteen call shapes, one per line: which are risky, and who notices?
import string

from flask import render_template_string, request
from jinja2 import Environment, Template, select_autoescape

GREETING = "Hi {user.name}"


def shapes(name, user, text, env):
    render_template_string(f"<h1>Hello {name}</h1>")                  # f-string template
    render_template_string("<h1>Hello " + name + "</h1>")             # concatenated template
    render_template_string(text)                                      # template from a variable
    render_template_string("<h1>Hello {{ name }}</h1>", name=name)    # constant template, data passed in
    Template(text).render()                                           # jinja2.Template from a variable
    Template("Hello {{ name }}").render(name=name)                    # jinja2.Template, constant
    env.from_string(text)                                             # from_string with a variable
    Environment()                                                     # environment without autoescape
    Environment(autoescape=select_autoescape())                       # environment with autoescape
    text.format(user=user)                                            # format string from a variable
    GREETING.format(user=user)                                        # format string is a constant
    request.args["fmt"].format(user=user)                             # format string from the request
    string.Template(text).safe_substitute(name=name)                  # string.Template, no attribute access
# step10_gate.py - what Ruff's security rules and our gate say about the thirteen call shapes
import pathlib
import re
import subprocess
import sys

import ssti_gate

SAMPLES = pathlib.Path("gate_samples.py")
lines = SAMPLES.read_text(encoding="utf-8").splitlines()
ruff = subprocess.run([sys.executable, "-m", "ruff", "check", "--isolated", "--select", "S",
                       "--output-format", "concise", str(SAMPLES)], capture_output=True, text=True)
ruff_hits = {}
for match in re.finditer(r":(\d+):\d+: (S\d+)", ruff.stdout):
    ruff_hits.setdefault(int(match.group(1)), []).append(match.group(2))
gate_hits = {}
for line, rule in ssti_gate.check_source(SAMPLES.read_text(encoding="utf-8")):
    gate_hits.setdefault(line, []).append(rule)

print(f"{'line':<6}{'shape':<46}{'Ruff S rules':<14}our gate")
for number, text in enumerate(lines, start=1):
    if "  # " in text and number > 10:
        label = text.split("  # ", 1)[1]
        print(f"{number:<6}{label:<46}{','.join(ruff_hits.get(number, [])) or '-':<14}{','.join(gate_hits.get(number, [])) or '-'}")

print()
print("=== the gate on real files")
for name in ("step02_vulnerable.py", "step03_fixed.py", "safe_templates.py", "views.py"):
    result = subprocess.run([sys.executable, "ssti_gate.py", name], capture_output=True, text=True)
    print(f"--- ssti_gate.py {name} (exit code {result.returncode})")
    print(result.stdout.strip())
python step10_gate.py
line  shape                                         Ruff S rules  our gate
11    f-string template                             -             SSTI001
12    concatenated template                         -             SSTI001
13    template from a variable                      -             SSTI001
14    constant template, data passed in             -             -
15    jinja2.Template from a variable               -             SSTI002
16    jinja2.Template, constant                     -             -
17    from_string with a variable                   -             SSTI003
18    environment without autoescape                S701          SSTI004
19    environment with autoescape                   -             -
20    format string from a variable                 -             SSTI005
21    format string is a constant                   -             -
22    format string from the request                -             SSTI005
23    string.Template, no attribute access          -             -

Ruff’s security rules flagged one of the eight risky lines: S701 on the environment without autoescape. That rule does what its documentation says: it “checks for jinja2 templates that use autoescape=False,” which is the XSS problem, not injection. Ruff 0.17.6 flagged none of the other seven: the three render_template_string shapes, jinja2.Template, from_string and the two format strings. Our gate flagged all eight: six fail the build and two (.format on a variable and on request data) are listed for review. It flagged none of the five safe lines, including string.Template, which has the same name as Jinja’s class but lives in another module. Keep Ruff for what it does well; the gate adds the specific shapes in this tutorial. Now see it on real files:

=== the gate on real files
--- ssti_gate.py step02_vulnerable.py (exit code 1)
step02_vulnerable.py:13: SSTI001 error: render_template_string() with a template that is not a plain string
1 problem(s) that fail the build
--- ssti_gate.py step03_fixed.py (exit code 0)
0 problem(s) that fail the build
--- ssti_gate.py safe_templates.py (exit code 0)
0 problem(s) that fail the build
--- ssti_gate.py views.py (exit code 0)
0 problem(s) that fail the build

The vulnerable page from Step 2 fails with exit code 1, and the fixed page and the new modules pass. Exit codes are what a CI system reads. Finally, create test_gate.py so the gate itself is tested, then run the whole suite:

# test_gate.py - the gate flags the risky shapes and leaves the safe ones alone
import pathlib

import pytest
from ssti_gate import check_source

CASES = [
    ('render_template_string(f"Hi {name}")', ["SSTI001"]),
    ('render_template_string("Hi " + name)', ["SSTI001"]),
    ("render_template_string(text)", ["SSTI001"]),
    ('render_template_string(source=text)', ["SSTI001"]),
    ('render_template_string("Hi {{ name }}", name=name)', []),
    ("jinja2.Template(text)", ["SSTI002"]),
    ("Template(text)", []),  # no jinja2 import in this snippet, so it could be string.Template
    ("env.from_string(text)", ["SSTI003"]),
    ('env.from_string("Hi {{ name }}")', []),
    ("jinja2.Environment()", ["SSTI004"]),
    ("jinja2.Environment(autoescape=False)", ["SSTI004"]),
    ("jinja2.Environment(autoescape=True)", []),
    ("jinja2.Environment(autoescape=jinja2.select_autoescape())", []),
    ("text.format(user=user)", ["SSTI005"]),
    ('"Hi {}".format(name)', []),
    ('GREETING.format(user=user)', []),
    ("request.args['f'].format(user=user)", ["SSTI005"]),
    ("string.Template(text).safe_substitute(name=name)", []),
]


@pytest.mark.parametrize("snippet, rules", CASES)
def test_shapes(snippet, rules):
    assert [rule for _, rule in check_source(snippet + "\n")] == rules


def test_import_aliases_are_followed():
    source = "from jinja2 import Template as T, Environment as E\nT(text)\nE()\n"
    assert [rule for _, rule in check_source(source)] == ["SSTI002", "SSTI004"]


def test_the_allow_comment_covers_only_its_own_line():
    source = "env.from_string(tree)  # ssti: allow (checked)\nenv.from_string(text)\n"
    assert check_source(source) == [(2, "SSTI003")]


def test_string_template_is_not_flagged():
    assert check_source("from string import Template\nTemplate(text).safe_substitute()\n") == []


@pytest.mark.parametrize("name", ["safe_templates.py", "views.py", "step03_fixed.py"])
def test_our_own_code_is_clean(name):
    assert check_source(pathlib.Path(name).read_text(encoding="utf-8")) == []


def test_the_vulnerable_demo_is_flagged():
    source = pathlib.Path("step02_vulnerable.py").read_text(encoding="utf-8")
    assert [rule for _, rule in check_source(source)] == ["SSTI001"]
python -m pytest -q
............................................................................................ [ 82%]
....................                                                                         [100%]
112 passed in 0.48s

The gate is deliberately simple, and you should know where it stops. It cannot tell a variable that came from a visitor from one that came from your own file, so it flags both, and the # ssti: allow comment is how you record a human decision. It does not follow data between functions or files. It knows Jinja2 and Flask, not other engines. Treat it as a tripwire that makes the dangerous shapes visible in review, not as proof that a codebase is clean.

Common mistakes and how to spot them

Pasting user text into a template, even “just a little”

Any of f"...", "..." + name, % or .format on a template string is the Step 2 bug. The check: the first argument of render_template_string, Template and from_string should always be a string constant, and the visitor’s text should appear only in the keyword arguments.

Trusting the sandbox with your model objects

The matrix showed a sandboxed template reading password_hash and calling delete(). Hand templates view objects built for the purpose, never the objects your database layer returns.

Catching only SecurityError

The Jinja documentation warns that “other exceptions may occur during the rendering so the caller has to ensure that all exceptions are caught.” The mutant M17 shows one: iterating a number raised a plain TypeError.

Thinking |safe is harmless

The safe filter tells autoescape to stop protecting a value. It is not on the allowlist, and a test and a mutant make sure it stays out.

Forgetting the data is also a size limit

With a loop depth of two, run time grows with the square of the list length. The renderer limits the template, not the size of the lists you pass in, so keep those bounded too.

Confirm the whole thing works end to end

You are finished when these three commands print the lines shown. The first runs all 112 tests, the second plants the 17 bugs, and the third runs the gate on the files that should pass, with exit code 0:

python -m pytest -q
python mutations.py
python ssti_gate.py step03_fixed.py step08_endpoint.py safe_templates.py views.py

Expected: 112 passed, caught 17 of 17 on the last line of the mutation output, and this from the gate:

0 problem(s) that fail the build

What to learn next

  • Add process-level limits. The Jinja documentation asks for CPU and memory limits around untrusted rendering. The portable version is to render in a worker process with a timeout and kill it when it overruns. I did not build that here.
  • Bound the data you pass in. Cap the number of items in the lists your views carry.
  • Log refusals. A burst of TemplateRejected messages for one account is worth a human glance.
  • Consider a simpler tool. If users only need {first_name}-style blanks, string.Template or the PlainFormatter from Step 4 has far less surface than a template language.
  • Read the rest of the series. The same “text from outside must stay data” rule drives our tutorials on subprocess calls, YAML, pickle, XML, regular expressions, decompression bombs and log lines.

Sources

  • Jinja documentation: Sandbox (security considerations, unsafe(), MAX_RANGE)
  • Jinja documentation: API (autoescape notes, Undefined types)
  • Jinja documentation: Template Designer Documentation (list of global functions)
  • Flask documentation: Templates (autoescaping and the standard context)
  • Python documentation: string (format string syntax, Formatter, Template)
  • PortSwigger Web Security Academy: server-side template injection
  • Ruff documentation: jinja2-autoescape-false (S701)
  • sxz.io: GitLab’s AI Gateway template flaws and its public tracking issue

Tags:

Application SecurityFlaskJinja2PythonSandboxingTemplate Injection

Share

John William Waterhouse’s 1891 painting Ulysses and the Sirens: Ulysses bound to the mast of a ship while winged sirens swoop around it and the crew rows
Previous Post

Anthropic’s Siren Turns Sandbox Escape Into a Propensity Test and Its Charts Reproduce Its Text, but WIRED’s 0.6 to 1.6 Percent Is the Narrowest of Three Measures, 81% of the Scenarios Cannot Be Finished Inside, and Auto Mode’s Block Rates Were Tuned on the Episodes They Are Scored On

A wooden house partly torn down, with its roof frame and an interior wall left open to the street
Next Post

Drupal Core’s Installer Flaw, Found by Anthropic’s OSS Scanner, Was Reported Exploited as Early as 28 Hours After the Patch and Is Now on CISA’s List, and the Rating Rose From 18 to 20 on One Factor While End-of-Life Branches Get No Fix

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest
26 Nov
How to Use Python 3.14 Deferred Annotations: Drop Quoted Forward References, Read Annotations Safely With annotationlib, and Catch the Decorator, Dataclass, and FastAPI Traps
26 Nov
Backblaze’s New Privacy Policy Drops Its Promise Not to Share E-mail Addresses for Marketing, but the Text Has Been Live Since Early November, the Scope Sentence Ars Quotes Exists Only in the Old Version, and No Ad Platform Was Contacted in a Browser Test Until Accept Was Clicked
Trending
November 26, 2026
How to Use Python 3.14 Deferred Annotations: Drop Quoted Forward References, Read Annotations Safely With annotationlib, and Catch the Decorator, Dataclass, and FastAPI Traps
November 26, 2026
Backblaze’s New Privacy Policy Drops Its Promise Not to Share E-mail Addresses for Marketing, but the Text Has Been Live Since Early November, the Scope Sentence Ars Quotes Exists Only in the Old Version, and No Ad Platform Was Contacted in a Browser Test Until Accept Was Clicked
November 26, 2026
Drupal Says Its Week-Old Installer Fix Left Some Sites Open to Takeover and Is Seeing Attacks, and in a Local Lab Upgrading the Code Alone Still Let the Visitor Who Got There First Continue the Install Until the Update Hook Ran
November 25, 2026
How to Check Whether an AI Eval Can Be Passed Without the Question: Build a Partial-Input Baseline in Python, Split by Group, and Reproduce the SNLI Hypothesis-Only Result
November 25, 2026
Google’s Fuse Turns Social Reasoning Into a 21,600-Message Benchmark, but the Code Its README Promised “Soon” Is Still Missing 71 Days Later, the Human Baseline Was Told to Focus on Facts, Not the User’s Interpretation, and a Per-Template Word Counter Gets 98.6% of the Held-Out Neutral Messages Right
November 25, 2026
CISA Lists an Exploited ASP.NET Library Flaw That Has No Patch and a Day-After-Thanksgiving Deadline, but Mandiant’s Hash List Skips the 0.9.0 Beta Build, NVD Files the Library Under a Different Vendor Name, and Default Installs Use a Form Field Called RaiseException

Related Posts

A laptop wrapped in a chain and padlock, illustrating least-privilege controls for AI agents.
Learning Hub

How to Secure Tool-Using AI Agents Before They Touch Production

June 8, 2026
Colorful sticky notes arranged on an office wall, symbolizing governance checklists and planning.
Learning Hub

AI Governance for Agentic Apps: A Practical Checklist for Builders

June 8, 2026
A technician connects green fiber optic cables at a data center, representing a private production inference endpoint.
Learning Hub

How to Deploy a Fine-Tuned LLM Behind a Private Production Inference Endpoint

June 8, 2026
Narrow aisle behind black supercomputer racks in a data center
Learning Hub

Kubernetes SELinux Volume Labeling: What Cluster Operators Should Audit Before v1.37

June 8, 2026
SXZ.io SXZ.io
  • [email protected]

Categories

Articles
Learning Hub
News

All Rights Reserved by SXZ.io ©2026