Project Theseus: Thwart removes template injection from Java web apps
View all articlesDan Lorenc
Co-founder and CEO
Chainguard
- View all articles
John Slack
Senior Product Manager
Chainguard
Dan Lorenc Co-founder and CEO + 1 other
Today we're releasing Thwart, the second Guarded Component in Chainguard's Project Theseus. Thwart is a template engine for Spring web apps that compiles templates to Java at build time. Because nothing interprets a template at runtime, server-side template injection is impossible by construction.
Thwart is for the Java web apps that already exist: the ones on Thymeleaf, JSP, FreeMarker, or Velocity, often on Java 8, that nobody has dared touch in a decade. If you read Rebuild the planet, this is the project we called Tessera.
It is not a drop-in replacement, and that's on purpose. What makes template injection possible is part of the old engines' interface, so killing the bug class meant changing the interface. A safer library isn't useful if nobody can migrate to it, so we built the migration tooling alongside it. Thwart is AI-compatible: it ships everything a coding agent needs to move an existing app onto it, and a migration test that measures whether agents can.
In the latest round of that test, a fresh coding agent migrated 18 real open source apps, written against six different template engines, with no human help. All 18 built and passed their own test suites, and 94% of all 1,212 pages rendered identically or differed only where Thwart’s safety rules fixed an unsafe pattern on arm64. On the larger apps, the agent left a handful of pages for humans to review and finish.
The name has two meanings. A thwart is the plank that runs across a boat and braces its hull, which makes it one more plank in the Ship of Theseus. And to thwart is to stop something from happening, which is what it does to attackers.
Memory safety isn't all that matters
Earlier this month we introduced Project Theseus with challoc, a memory allocator that turns many heap bugs into crashes instead of exploits. Bugs are being found faster than anyone can patch them. Project Theseus rebuilds components so that whole classes of bugs can't happen in them.
Memory safety was the obvious place to start, but most business software already runs in memory-safe languages like Java, Python, JavaScript, and Go. Those apps still get broken into, and the bugs that let attackers in look nothing like a buffer overflow.
We see this in our own data. Athena is the coalition Chainguard started to coordinate the defense of open source against AI-discovered vulnerabilities. Across the tens of thousands of vulnerabilities it has confirmed so far in Java, Python, and JavaScript libraries:
26% are injection bugs: data that ends up treated as code, a query, markup, or an object to construct.
9% are code injection specifically, where attacker-controlled input is evaluated or used to pick the code that runs.
2% are memory-safety bugs.
That's thirteen injection bugs for every memory-safety bug.
This data is skewed toward the application layer. These are libraries written in memory-safe languages, so of course there are few memory-safety bugs in them, and the same count over C libraries would look very different. Once the memory is safe, though, this is what's left, and there is a lot of it.
A memory-safe language doesn't help with any of it, because nothing is wrong with the memory. The program does exactly what it was written to do. It takes a string and runs it. Log4Shell wasn't a memory bug: it was a lookup feature working as designed.
Template injection is one of the worst of these, because the string that gets run can reach the whole application.
Twenty-five years of the same bug
Java web apps that render pages on the server usually build them with a template engine: a component that takes data and fills in an HTML template with it.
JSP arrived in 1999, with FreeMarker and Velocity right behind it, and Thymeleaf followed in 2011. Each was nicer to work in than the last. Each kept the same design: a small language inside the template, interpreted on the server every time a page renders, that can reach the rest of the app. If an attacker's text ends up in that template code, the attacker gets to run code on your server.
In 2015, the attack got a name. James Kettle's Black Hat talk, Server-Side Template Injection, showed working exploits against FreeMarker and Velocity, including escapes from the sandboxes that were supposed to contain them. Attackers have used it ever since:
Jira, 2019 (CVE-2019-11581). The subject line of a contact form went into a Velocity template. Anyone who could reach the form could run code on the server.
Apache Solr, 2019 (CVE-2019-17558). Code execution through its Velocity response writer, later used to install cryptominers.
Confluence, 2023 (CVE-2023-22527). Template injection with no login required, scored 10.0 by Atlassian and used in ransomware campaigns.
The expression languages inside these engines have the same bug wherever they turn up. The 2017 Equifax breach, 147 million Americans' records, was an expression injected into OGNL. That's the language Thymeleaf uses outside Spring.
Every one of these engines has the same history:
Engine | Example | What happened |
|---|---|---|
JSP, with Spring's tags | Spring's JSP tags evaluated expressions twice, so data from a request could run as code | |
Velocity | Anyone who can edit a template can run arbitrary Java, past the sandbox meant to stop them. The Jira and Solr bugs above are Velocity too | |
FreeMarker | VMware Workspace ONE: one request, no login. Attackers were exploiting it within 48 hours of the patch | |
Pebble | A bypass of the method restrictions, rated 9.8. It was never fixed: the maintainers' position is that templates are trusted code | |
Thymeleaf | CVE-2021-43466, CVE-2023-38286, CVE-2026-40478, CVE-2026-41901, and nine more advisories in November 2026 | The expression sandbox has been bypassed again and again. One bypass was a single whitespace character |
None of this is a knock on the people who maintain these engines. Thymeleaf's maintainers have responded quickly to every report. But a sandbox around an interpreter is a list of things the interpreter must not do, and an attacker only needs to find one thing missing from the list.
Twenty-five years of patches haven't ended this, and the next patch won't either. As we put it in Rebuild the planet: "You don't patch a design. You replace it."
Why the design had to change
We set out to remove template injection, not to break compatibility. What we found is that everything that makes it possible is something templates are allowed to do. They are features, documented and relied on:
Templates run code at render time. An expression in a Thymeleaf template can reach any Spring bean and any static method. Thwart templates read data and nothing else: the fields and getters of the values passed in. Logic moves to Java, where the compiler and your code review already look.
Data can become template code. Thymeleaf can evaluate a value and then parse the result as another expression, and a view name built from request data gets evaluated too. Thwart has no API that takes template text at runtime.
A template can turn escaping off. Every one of the old engines has a raw-output switch in the template language. In Thwart, raw HTML is a Java type that only your Java code can create.
Inline scripts and event handlers. An
onclickattribute is code in the page, and a strict Content Security Policy has to block it. Thwart rejects it at build time and tells you where the listener goes instead.
A compatible replacement would have to keep all four, and the bugs with them.
None of these ideas are new, and that's why we trust them. Other languages moved on years ago. Scala's Twirl, C#'s Razor, and Rust's Askama compile templates into typed functions, so the compiler checks a template like any other code. Google's Closure Templates and Go's html/template pick the escaper from where a value lands in the page, and Google's safe HTML types make raw output a type that only vetted code can create. Google has written about what happened when it made the unsafe thing fail to compile across its codebase: the bug class went away. Java has compiled engines too, like JTE, Rocker, and JStachio, and for a new app they're good choices.
But there are two decades of Spring applications on Thymeleaf, JSP, FreeMarker, and Velocity, many of them on Java 8, and none of those engines offers a way to get there short of rewriting every page by hand. So those apps stay where they are, and get patched.
Thwart puts the proven ideas in one engine: it keeps Thymeleaf's syntax, runs on the Java and Spring versions those apps are stuck on, and ships with tooling to make migrating cheap.
How Thwart works
Thwart moves template code from runtime to build time. Instead of reading templates and running the code in them while serving each page, Thwart turns each template into ordinary Java when the app is built, with the same Java compiler (javac) as the rest of the app. Once the app is running, there's nothing left to interpret.
Templates are plain HTML. Thwart keeps the natural HTML style Thymeleaf made popular: extra attributes, prefixed t:, say where the data goes.
<html xmlns:t="https://thwart.chainguard.dev"
t:import="com.example.*"
t:params="Customer customer, List<Order> orders">
<body>
<h1 t:text="|Hello, ${customer.name}!|">Hello, Ann!</h1>
<p t:if="orders.isEmpty()">No orders yet.</p>
</body>
</html>
When the app is built, Thwart turns this template into a Java class that takes a customer and their orders. The controller passes in the same data as before and returns the same view name.
At runtime, no template code runs, so there's no template code to inject into. Data still comes in, but as typed values that get inserted into the page.
Runtime engines (e.g. Thymeleaf) | Thwart | |
|---|---|---|
Template code | Runs on every request | Compiled at build time |
What a template can reach | Beans, static methods, request and session | Only its declared, typed parameters |
Raw HTML output | A switch in the template | Only values marked safe in Java |
Content Security Policy | Up to the app | Strict by default |
Thwart isn't formally verified. Its HTML parsing and escaping are tested against the parsers in Chromium, Firefox, and WebKit after every merge, not formally proven. The security model says what is guaranteed and what isn't.
Thwart as a library
Killing a bug class is the reason Thwart exists. It's also a template engine we'd choose to write pages in. Most of what makes it safe also makes it nicer to use.
Mistakes are build errors. A misspelled property, a missing parameter, a fragment called with the wrong arguments, a message key that doesn't exist, a link with the wrong path variables: each one fails the build with the file, line, and column. In a runtime engine, each of those is a blank spot or a stack trace on a page somebody has to visit first.
Errors that tell you what to write. Every compiler error says what's wrong and what to do instead. Add
<button onclick="newOrder()">to the template above and the build prints:
error: customers/show.html:7:54: onclick on <button> is not allowed: inline event handlers
are not supported: a strict CSP blocks them; remove onclick and attach the listener from a
<script> with addEventListener, or mark the element with a data-* attribute and handle it
with one delegated listener
Escaping you don't have to think about. Thwart knows whether a value lands in text, an attribute, a URL, a script, or a style, and applies the right escaper or check for that spot. URLs are scheme-checked. Values in a
<script>go in as JSON.A strict Content Security Policy, on by default. Thwart puts the request's nonce on every script and style it writes, and the starter sends a strict nonce-based policy by default. Most apps never get a strict CSP working, because their templates were never written for one. Thwart's are.
Everything a Spring app expects. Form binding with validation errors, Spring Security's CSRF token added to forms for you, internationalized messages, typed links, layouts and fragments. A fragment is a typed function, so it sees only what it's passed.
Safe handling for stored HTML. When a page has to show HTML that users wrote, a built-in sanitizer turns it into a safe value in Java.
Old apps are first-class. Thwart runs on Java 8 and up, with Spring Framework 4.3 or Spring Boot 1.5 and later. Those are the apps that are hardest to keep patched, so those are the apps we built it for.
It runs beside the engine you have. Thwart's view resolver goes first, and the old engine renders whatever hasn't moved yet. You can migrate one page at a time.
It's fast. With nothing to interpret, pages render 19 to 42 times faster than Thymeleaf in our benchmarks. More on that below.
These guarantees come with tradeoffs. Thwart is stricter than what it replaces. Logic and formatting move out of templates and into Java, some markup that browsers accept gets rejected, and hot reload is a recompile that takes a few seconds. Spring WebFlux isn't supported. The comparison lists where Thwart is weaker than other engines, including other compiled ones.
AI-compatible and tested
The old rule for replacing a widely used library was "be a drop-in or lose," because asking every user to change their code was too expensive. In a decent-sized enterprise, moving off a template engine means finding and rewriting hundreds of templates, by hand, one at a time. That's the kind of migration nobody ever gets around to. It was simpler to accept the risk, or deploy the latest patch.
Agents change that math. In the challoc post, we called this AI-level compatibility: a replacement is AI compatible if an agent can move existing users onto it cheaply and safely. Instead of treating migration cost as a blocker to changing an interface, we can measure it and drive it down.
To back that up, we built a migration test. As far as we know, nobody has published one for a library before.
Thwart ships three things for agents:
A Claude Code plugin with one skill and a guide covering setup, templates, migration from Thymeleaf, JSP, FreeMarker, Velocity, Mustache, and Pebble, and known limitations.
Compiler errors written as fixes, like the one above. An agent's normal loop of edit, compile, and read the error is also how it learns Thwart.
A page-parity checker.
thwart-migrate recordsaves every page of the app as it renders today.thwart-migrate comparechecks every page of the migrated app against that recording, the way a browser builds it.
The migration test puts those three in front of a fresh agent and scores what comes out. Each run gives an agent, working alone, a real open source Spring app plus the plugin we ship, and nothing else: no web search, and nobody to ask. Then we check that the app still builds and passes its own tests, that its pages still render the way they did, and that nothing about its security got weaker along the way.
The 18 apps span all six engines, from Spring 4.3 to current Spring Boot, and eight of them run on Java 8. Six of them are a held-out set: we test on them, but never change Thwart or its guide to fit them, so they show how it handles apps it wasn't tuned for.
Migration test, Nov 24, 2026 (18 apps, 1,212 pages) | Claude Opus 5.5 | Claude Sonnet 5.5 |
Apps that build and pass all of their own tests | 18 of 18 | 18 of 18 |
Pages migrated (identical or safety-required diff only) | 91%–94% (amd64, arm64) | 88%–93% (amd64, arm64) |
Average cost per app (API equivalent) | $10.25-$11.46 | $4.97-$5.58 |
Average time per app | 27–28 min | 24 min |
Every small app migrated completely on both amd64 and arm64. On the larger apps, the remaining 6% to 9% of pages came down to a mix of Thwart's safety rules catching live-rendered markup (fixing latent XSS issues), minor agent mistakes — like a missed translation or a mistyped dialog parameter — and one known Thwart limitation around hidden PDF markup. Instead of rewriting hundreds of templates by hand, an engineering team starts with a working, passing build in under half an hour and cleans up the last few percent.
We will rerun the test as Thwart and the underlying models improve, which tells us how far future replacements can diverge from the libraries they replace.
Performance
We benchmarked Thwart against Thymeleaf—both in isolation and inside full Spring applications—to see what moving template compilation to build time buys in practice.
In pure rendering microbenchmarks (run on Nov 2, 2026, on Java 21 with Thymeleaf's template cache on), Thwart renders 19 to 42 times faster than Thymeleaf and allocates about a twentieth of the memory per page:
Page | Thwart (pages/sec) | Thymeleaf (pages/sec) | Speedup |
|---|---|---|---|
Owner table (100 rows) | 21,590 | 1,129 | 19x |
Layout page (fragments) | 179,437 | 4,245 | 42x |
The fragment-heavy page shows the bigger gap. A Thwart fragment call is a plain Java method call. Thymeleaf resolves the fragment, evaluates its selector, and binds its parameters every time one is used. Thwart also allocates about a twentieth of the memory per page, which is that much less work for the garbage collector.
Most of the gain comes from not interpreting templates at runtime, so other compiled engines should land in the same range.
Microbenchmarks only measure the template engine, though. In a real web app, the database, framework, and network do most of the work. To measure what teams actually see, we benchmarked full Spring apps (jpetstore and spring-petclinic) across Java 8, 21, and 25 on both amd64 and arm64. Here is how two representative apps compare at 32 concurrent users on amd64:
App (amd64, 32 users) | Throughput (Thwart vs. Thymeleaf) | p99 Latency | Memory Allocated / Request |
jpetstore (Java 8) | 21,042 vs. 8,383 pages/sec (2.51x) | 7.6 ms vs. 16.8 ms (-55%) | 230 KB vs. 368 KB (-38%) |
spring-petclinic (Java 25) | 1,080 vs. 1,061 pages/sec (1.01x) | 107 ms vs. 109 ms (-2%) | 1,429 KB vs. 1,543 KB (-8%) |
Across all measured apps and Java versions:
Throughput: With one user, Thwart serves 17% to 160% more pages per second. At 32 concurrent users, gains range from 2.5x on
jpetstore(where rendering is a larger share of the request) to roughly level onspring-petclinic(where database and network time dominate).Memory, startup and size: Apps hold 6% to 21% less memory after warm-up, start 3% to 15% faster and ship 3% to 8% smaller artifacts.
Tradeoffs: Because Thwart compiles every template at build time, clean builds take 16% less time to 59% more, depending on the app and Java version. Tail latency (p99 at 32 users) is 2% to 55% faster on most apps, with one exception we are still investigating: PetClinic on Spring Boot 2.7 (Java 8), where p99 latency is 23% to 62% higher even though overall throughput is ~45% faster.
End-to-end runs were measured on dedicated Google Cloud VMs (median of five alternating runs with a fixed 1 GB G1 heap); the full harness is in bench/consumers. Removing runtime interpretation doesn't cost you performance—and even when the database is the bottleneck, you get lower memory pressure and faster startup for free.
Start using Thwart
Thwart is public on GitHub at chainguard-project-theseus/thwart. It's a prototype and source-only for now, and we're working on bringing it to Chainguard Libraries. Build it from a checkout first (JDK 21 and Maven 3.9 or later):
mvn -B -ntp install -DskipTests
Then let Claude Code do the move:
claude plugin marketplace add chainguard-project-theseus/thwart
claude plugin install thwart@thwart
Ask Claude Code to migrate your app's views to Thwart, or run /thwart:thwart.
To add a page by hand:
Add the Spring Boot starter and the Thwart annotation processor to your Maven or Gradle build. The setup guide has the details.
Create an HTML template under
src/main/resources/templates, declaring the data it takes at the top witht:params, like the example above.In the Spring controller that handles the request, put that data in the model and return the template's name, as you would with your current engine. The template compiles with the rest of your app, and any mistake in it is a build error.
We want your feedback. Try it on a real app and tell us what broke, what the migration missed, and which features you rely on. File issues in our feedback repo.
How Thwart is open
Thwart is open source under the Apache 2.0 license, and all of it is public: the code, the security model, the guide and the migration test. As we wrote in Rebuild the planet, this isn't CNCF-style open source. Issues are welcome. Pull requests are not. If you and your organization are serious about joining the effort, email dlorenc@chainguard.dev.
You're welcome to ship Thwart as well, but usage is governed by our trademark policy.
What's next
Thwart is our first application-level component, and more are coming. Template injection is one of several bug classes in application libraries that a different design can remove, and where removing one means changing an interface, we'll ship the skills and the migration test alongside it, the way we did here.
As we validate each component through real-world use, we'll bring it into Chainguard's products as an opt-in. Follow along at github.com/chainguard-project-theseus.
Patching will always matter, but the way off the treadmill is software that's safer from the start, rebuilt one plank at a time.
Share this article
Related articles
productAnnouncing the Athena Partner API
productHow Chainguard’s frontier AI harness keeps your code safe
productRun GitLab-certified hardened images for GitLab Enterprise Edition with the security of Chainguard
productIntroducing Project Theseus, starting with challoc
productChainguard endpoints now handle breaking changes
productBuilding Guarded Entrypoint for Chainguard Containers