Turn the Attacks into a Test Suite
Every defence in an assistant with tools was added because some attack got through. Code changes all the time, and a later change can quietly open the same hole again. This page shows how to keep each attack that once worked, together with ordinary honest requests, as automated tests that run with one command. It also covers how to check that those tests can really fail, how to measure attacks against a live model, and what a suite that passes does and does not prove.
An attack that worked once becomes a test
A regression is a bug that was fixed and then comes back. It usually returns by accident: someone refactors a function, adds a new tool, or removes a check that looked unnecessary. A security regression test is the defence against that. Each time an attack succeeds, you save it, fix the code, and keep the saved attack as a test that must pass from then on. If a later change reopens the hole, that test fails on the next run, and you learn about it before an attacker does.
A test like this needs the same verdict on every run. An attack sent to a live model is not like that, because the model may follow the injected text on one try and ignore it on the next. So the saved attack holds two things. The first is the attacker's text. The second is the script of a model that fell for it: the tool calls that model made, and replies built only from what it actually received.
When the test runs, a stand-in model follows that script in place of the live one, on a throwaway copy of the data. This model is always fooled, so the model no longer decides the outcome. Only the application's code does: whether it runs the tool call, whether it hands over the record, whether the reply leaves with a link to an attacker's server in it.
- Saved attack attacker text + script
- Stand-in model always falls for it
- Application code checks, tools, filters
- Pass or fail same on every run
- Saved attack to Stand-in model
- Stand-in model to Application code
- Application code to Pass or fail
The attacks in such a suite are aimed at your own copy of the application. Sending them to a system someone else runs is an attack on that system, and testing it needs its owner's permission.
Running the whole set with one command
The tests are only useful if running all of them is effortless. In Python the usual tool is pytest, installed into a virtual environment with pip install -U pytest. Its rules are simple. Run pytest in a folder and it searches that folder and the folders below it for files named test_*.py or *_test.py, then runs every function in them whose name starts with test. A test is an ordinary function that uses Python's assert statement: if every assert holds, the test passes, and if one is false, it fails and pytest prints the values that made it false.
One test function can cover every saved attack. The decorator @pytest.mark.parametrize runs the same function once per value in a list, and ids gives each run a readable name, so a failure names the attack that got through. The built-in tmp_path argument gives each test its own fresh temporary folder, which is where the throwaway copy of the data goes.
import json
from pathlib import Path
import pytest
from assistant.replay import run_replay
ATTACKS = sorted(Path("tests/attacks").glob("*.json"))
def test_attack_files_were_found():
assert ATTACKS, "no attack files found"
@pytest.mark.parametrize("path", ATTACKS, ids=lambda p: p.stem)
def test_attack_is_contained(path, tmp_path):
attack = json.loads(path.read_text())
result = run_replay(attack, data_dir=tmp_path)
assert result.forbidden_tools_run == []
assert attack["secret"] not in result.replyHere run_replay stands for the application's own replay function: it plays the saved script against the real code and reports which tools ran and what reply came out. The first test looks odd but earns its place. When parametrize receives an empty list, pytest skips that test by default instead of failing it, so a typo in the folder name would leave a suite that checks nothing and still looks fine. The small test that asserts the list is not empty turns that mistake into a failure.
When an attack gets through, the end of the output names it:
$ pytest
========================= short test summary info ==========================
FAILED tests/test_attacks.py::test_attack_is_contained[invoice-note-injection] - AssertionError: assert ['send_email'] == []
======================= 1 failed, 11 passed in 0.38s =======================The same command is what an automated check runs on every change. pytest ends with an exit code, a number the operating system hands back to whatever started it. A continuous integration service (a server that runs your checks each time code is pushed or a pull request is opened) reads only that number. On GitHub Actions, for example, exit code 0 marks the check as a success and any other number marks it as a failure, which can block the change from being merged.
| Exit code | What pytest is saying | Automated check |
|---|---|---|
| 0 | All tests were collected and passed | success |
| 1 | Tests ran and some of them failed | failure |
| 5 | No tests were collected | failure |
True or false?
If pytest finds no test files at all, it exits with 0, so an automated check would pass.
False. A run that collects no tests exits with code 5, and any non-zero code is a failure to the automated check. An empty parameter list inside a file that does have tests is different: it is skipped, which is why the suite asserts that attack files were found.
Developers and the automated check should run the same command, so a green result means the same thing in both places.
True. If the check ran a different set of tests, a change could pass on a laptop and fail on every push, or the reverse.
Honest requests belong in the suite too
A suite made only of attacks rewards the wrong thing. Imagine a change that makes the assistant refuse every tool call. No forbidden tool runs, no secret appears in any reply, and every attack test passes. The application is now perfectly safe and of no use to anyone.
The answer is to test what the application is for. An honest-request test replays an ordinary, allowed request (a user reading their own invoice, a refund within the limit) and asserts that it still succeeds: the tool runs, the record changes, the reply carries the information the user asked for. Research benchmarks for prompt injection report results the same way. AgentDojo, for example, reports how often the agent completes the user's task with no attack present and how often it still completes it while under attack, next to how often the attacker succeeds, because a low attack number means little on its own.
| A change that... | Attack tests | Honest tests |
|---|---|---|
| reopens a hole | fail | pass |
| refuses everything | pass | fail |
| keeps the defence and the feature | pass | pass |
HONEST = sorted(Path("tests/honest").glob("*.json"))
@pytest.mark.parametrize("path", HONEST, ids=lambda p: p.stem)
def test_honest_request_still_works(path, tmp_path):
case = json.loads(path.read_text())
result = run_replay(case, data_dir=tmp_path)
assert result.tools_run == case["expected_tools"]
assert case["expected_text"] in result.replyThe two kinds of test pull in opposite directions, and that is the point. Each attack test pushes towards refusing more; each honest test pushes towards allowing more. A defence is in the right place when both pass at the same time.
True or false?
A defence that blocks every request passes every attack test in the suite.
True. Nothing forbidden can happen if nothing happens at all. Only honest-request tests notice that the application stopped working.
A test must be able to fail
A test that passes tells you nothing until you know it would fail without the thing it protects. Tests go wrong in quiet ways: an assertion checks a field that is always empty, a replay never reaches the tool it was meant to call, the expected secret is spelled differently from the real one. Each of these produces a green test that would stay green if the defence vanished.
The check is direct. Take one defence out (comment out the argument check, let the owner check always return true, allow every link) and run the suite. At least one attack test must turn red, and it should be the one written for that hole. Then put the defence back and confirm everything is green again. Repeat for every defence.
| Defence removed | Tests that fail | Meaning |
|---|---|---|
| Refund amount check | refund-over-limit | covered |
| Record owner check | other-users-invoice | covered |
| Link allowlist on replies | image-exfiltration, link-exfiltration | covered |
| File path check | none | no test guards it |
The last row is the most valuable result of the exercise. A defence whose removal leaves every test passing is a defence no test covers: the next refactor could delete it and nobody would notice. The fix is to write the attack that this defence stops, save it, and watch it fail with the defence removed before you restore it.
This is a hand-made version of mutation testing, a general technique in which a tool changes the code in small ways on purpose (turning < into <=, for instance) and reruns the tests. Each changed copy is a mutant; if no test fails, the mutant survives, which points at code no test really checks. For security, the mutations that matter most are the ones that remove a defence, so removing each one deliberately is a short and focused version of the same idea.
True or false?
If every test passes both with and without a defence, that defence is already well protected by the suite.
False. It means the opposite: no test depends on the defence, so it could be deleted without any warning. It needs a test that fails when it is gone.
After removing a defence, it is not enough that some test fails; it should be the test written for that attack.
True. If an unrelated test fails instead, the dedicated test may be broken, and the coverage you think you have is an accident.
Measuring attacks on a live model
Replayed attacks answer one question: does the code contain this attack when the model is fooled? A different question is how often a real model gets fooled in the first place. That is answered by sending the same attack to the live model many times and counting. The result is the attack success rate:
Because a language model's output varies from one run to the next, a single attempt says little. The picture below plays a made-up attack that lands on roughly three tries in ten. Watch how the measured rate swings while the number of runs is small and only slowly settles.
- attack text
- live model
- attack landed
- attack failed
- measured rate
Real measurements show the same effect. In an evaluation by the US National Institute of Standards and Technology (NIST), the attacks were agent hijacking attacks: injected instructions that take over an agent's actions. Measured with a single attempt each, they succeeded 57% of the time on average. When each attack was attempted 25 times, the average success rate rose to 80%. The success rates of the individual attack tasks changed significantly as well.
- One attempt 57%
- 25 attempts 80%
An attack success rate is a measurement, not a verdict. It depends on how many runs you made, the exact wording of the attack, the model and its settings, and it changes when any of them changes. That makes it useful for decisions: which defence to build first, whether a prompt change made attacks rarer, how exposed a feature is. It cannot serve as a pass or fail gate the way a replayed test can. A rate of 2% still means the attack works for someone, and a run of 0 out of 20 on one day does not mean 0 out of 20 tomorrow. A replayed attack is different: it asks a question about the code that has one answer, so it can block a change. A rate tells you how worried to be.
True or false?
An attack that failed against a live model nine times out of ten can be treated as closed.
False. It succeeded once, so it works. More attempts, or a slightly reworded attack, can push the rate higher; only a defence in code turns it into a fixed result.
Attack success rates are useful for comparing defences, even though they cannot decide whether a change passes.
True. Measured over enough runs, a drop from 40% to 5% is real information about risk. It is still a sample, not a guarantee.
What a passing suite proves
When every test passes, you know something precise: each attack in the suite, replayed against a model that falls for it, is stopped by the code, and each honest request still works. That is worth knowing, and it is all the suite says. In 1972 the computer scientist Edsger Dijkstra put the limit this way: "program testing can be a very effective way to show the presence of bugs but is hopelessly inadequate for showing their absence."
For prompt injection the gap is wide. A suite of saved attacks is a fixed list, and attackers do not stay on lists. A 2025 study by researchers including Nicholas Carlini and Florian Tramèr took 12 published defences, most of which had reported near-zero attack success against fixed attack sets, and broke most of them with success rates above 90% using attacks adapted to each defence. The Prompt Injection entry of the OWASP Top 10 for LLM Applications draws the same conclusion: it advises testing against adaptive attackers who have read the deployed defence, and rejecting claims based only on static attacks.
So the suite keeps growing. Every new attack that works, whether a user reports it, a colleague finds it or a log shows it, becomes a saved attack and a new test, after it has been shown to fail with the hole still open. To find attacks faster than people can write them, automated attack tools generate hundreds of variations of known techniques and run them against an application; open-source examples include garak, PyRIT and promptfoo's red-teaming mode. They widen the search for new holes. What they find is turned into replayed tests, so that each discovery is then guarded on every change.
- New attack found by people or tools
- Saved as a test fails while open
- Defence in code test now passes
- Runs on every change one command
- New attack found to Saved as a test
- Saved as a test to Defence in code
- Defence in code to Runs on every change
- Runs on every change to New attack found: search goes on
True or false?
Once all saved attacks pass, adding more attack tests is mostly wasted effort.
False. Fixed attack sets are routinely beaten by adapted attacks. Each newly found attack is a hole the current suite does not check.
An attack found by an automated tool is most useful once it is saved as a replayed test.
True. The tool's run is a one-off search; the saved test makes sure the same hole is checked on every later change.