Blog/Quality Assurance

Prompt Injection Testing for Chatbots and AI Agents: A Practical Guide

QA engineer pointing to a computer screen displaying code

Summarize with:

Prompt injection testing checks whether a chatbot or AI agent can be manipulated, through a user's message or through content it reads, into ignoring its rules, revealing hidden instructions, exposing private data, or taking actions it should not. It matters because prompt injection is the first risk in the OWASP Top 10 for LLM Applications (LLM01:2025), and the stakes rise quickly once chatbots turn into agents that can read inboxes, search documents, and call APIs. 

This guide covers what prompt injection testing involves, why it calls for a different mindset than traditional security testing, how to test chatbots and agents step by step, and how to reduce the risk with layered defenses.

What prompt injection looks like in practice

Picture a customer support chatbot on an online store. It answers questions about deliveries, walks customers through returns, and, to take some pressure off the support team, has access to order history and a tool that can issue refunds. One evening, someone opens the chat window and types a few polite sentences in plain English. There is no malware attached, no suspicious link, and no unusual traffic for a firewall to flag. A few messages later, the bot has described the internal rules it was given, shared details from an order that does not belong to the person asking, and approved a refund that its own policy should have blocked.

Nothing in that conversation resembles a cyberattack in the way most security teams are trained to recognize one, and yet that is exactly what happened. The risk grows once chatbots become agents. In June 2025, researchers at Aim Security disclosed EchoLeak (CVE-2025-32711), a vulnerability in Microsoft 365 Copilot that could have allowed an attacker to extract sensitive data from a user's Copilot context through a single crafted email, without the user clicking anything. Microsoft rated it critical, with a CVSS score of 9.3, and fixed it on the server side.

Direct and indirect prompt injection

OWASP describes a prompt injection vulnerability as one where prompts change a model's behavior or output in ways the developers never intended. It comes in two forms: 

Direct prompt injection, which happens when the instruction sits in the user's own message, typed straight into the chat. 

Example of a direct prompt injection, created using Claude Design.
Example of a direct prompt injection, created using Claude Design.

Indirect prompt injection happens when the instruction is hidden in external content the model reads later, such as a web page, a PDF, an email, or a document pulled in through retrieval-augmented generation (RAG). 

Example of hidden instructions in the file of an indirect prompt injection, created using Claude Design.
Example of hidden instructions in the file of an indirect prompt injection, created using Claude Design.
Example of an indirect prompt injection, created using Claude Design.
Example of an indirect prompt injection, created using Claude Design.

Both forms can be intentional or accidental, and the instructions don't even need to be visible to a human, as long as the model reads them.

Prompt injection examples

Type Example What can go wrong
Direct, role override A message telling the bot to ignore its previous instructions and act as an unrestricted assistant The bot drops its policy and answers off-topic or unsafe requests
Direct, prompt extraction A normal delivery question, plus a request to explain which rules the bot follows and how it was set up The system prompt leaks and shows an attacker which rules to work around
Direct, authority claim A message claiming to be the store manager and asking for a refund The bot performs a restricted action on an unverified claim
Indirect, document Hidden text in a PDF or product review that tells an assistant to ignore its rules An agent follows instructions planted in content it was only meant to summarize
Indirect, email A crafted email that an assistant reads when asked to summarize an inbox Data leaves the system without the user noticing, as in EchoLeak

Prompt injection vs. jailbreaking

You'll often hear "jailbreaking" used in the same breath. Jailbreaking is generally treated as a type of prompt injection, specifically the kind aimed at getting a model to drop its safety rules entirely. Prompt injection is the broader category, and for a business deploying a chatbot it tends to matter more, because attempts usually go after the bot's specific instructions, data, and permissions rather than the model's general safety training.

What prompt injection testing covers

Prompt injection testing, then, checks whether a message or a piece of content can push a chatbot or agent into doing any of the following:

  • Abandoning its role or policy. Aanswering off-topic requests, waiving business rules, or changing its persona mid-conversation
  • Revealing its hidden instructions. The system prompt, internal guidelines, or configuration details
  • Misusing its context. Treating retrieved documents, conversation history, or tool output as commands rather than information
  • Exposing private data. Another customer's details, internal documents, or credentials
  • Taking actions it shouldn't. Sending emails, issuing refunds, or calling APIs beyond what the user is allowed to do

One more thing worth settling early is how the results get written up. Internal teams may need exact reproduction steps to fix a finding, but reports shared with clients, stakeholders, or the public should focus on the risk, the evidence, and the safer behavior expected from the bot, so that the report itself doesn't turn into a ready-made attack script.

Why prompt injection slips past traditional security testing

QA engineer doing prompt injection testing

Traditional security testing has a lot of signals to work with: scanners look for known exploit signatures, malformed requests, injection syntax, suspicious domains, or traffic coming from places it shouldn't. A prompt injection attempt usually has none of these. It arrives as ordinary text through the same chat window every legitimate customer uses, written in the same language, and often phrased just as politely.

The comparison to SQL injections is tempting, yet the UK's National Cyber Security Centre has argued that it's also misleading. SQL injections can be properly mitigated with parameterized queries, because databases can enforce a strict line between instructions and data. Current LLMs don't enforce that line inside a prompt; everything in the context window is text the model may treat as something to act on. The NCSC suggests thinking of an LLM as an "inherently confusable deputy" and warns that prompt injection may never be fully mitigated in the way SQL injection has been.

That leads to three practical differences for testers:

  • Anyone can do it. Exploiting prompt injection doesn't require specialist tools, a VPN, or deep technical knowledge. A curious customer, a frustrated user trying to get a refund, a competitor, or someone who saw a trick on social media can all attempt it, and many of them won't think of what they're doing as an attack.
  • The person carrying the attack may not know about it. CrowdStrike, which maintains a taxonomy of more than 200 prompt injection techniques, describes a method where a user is tricked into adding malicious instructions to their own workspace, for example by pasting a "customer note" into a CRM record. The user's later request to the AI assistant (something as harmless as "summarize this account") is perfectly legitimate, while the hidden instruction rides along inside the data the assistant reads.
  • Results aren't deterministic. The same prompt can succeed once and fail the next three times, because model output varies with settings like temperature, and because guardrails are often language models themselves. The OWASP AI Testing Guide recommends repeating every request multiple times for exactly this reason, since a single clean run proves very little. Our guide to testing LLM-based apps covers more of the challenges that non-deterministic output creates.

It also helps to separate prompt injection testing from general chatbot QA. Functional chatbot testing checks whether answers are accurate, whether handoffs to human agents work, and whether the tone fits the brand. A bot can pass all of that and still be talked out of its rules within five messages. Prompt injection testing belongs inside chatbot QA, in the same way that negative testing belongs inside functional testing: it deals with the ways real users deviate from the path the designers had in mind.

How to test chatbots and agents for prompt injection

Before writing a single test, two pieces of groundwork make everything else more effective. 

First, learn what the bot is supposed to do, including its system prompt, the policies it enforces, and the topics it should decline. You can't judge a deviation without knowing the intended behavior. 

Second, map every place where text can enter the model's context. For a simple chatbot, that may only be the chat input. For an agent, CrowdStrike's list is a useful reminder of how wide it can get: prompts, uploaded files, RAG pipelines, agent memory, API responses, tool outputs, browser content, emails, and data from connected SaaS tools. Our guide to how to test AI agents covers the wider testing picture for agents.

Step 1: Learn to recognize the obvious attempts

Some injection attempts announce themselves. Phrases like "ignore all previous instructions," "system override," "you are now in debug mode," or requests to act as an unrestricted persona (the well-known "DAN," short for "Do Anything Now," is the classic example) have circulated widely for years. The DAN family evolved through community forums, with new versions appearing each time model providers patched the previous one, and most public LLMs have since been hardened against these prompts.

Your bot should handle these gracefully, and testing them is a reasonable baseline. The catch is that recognizable phrasing is the easiest part of the problem. Attackers routinely rework them into variants that use synonyms, deliberate typos, odd capitalization, encoded text, other languages, or instructions split across several messages, all designed to slip past filters that look for specific wording. CrowdStrike makes a similar point: prompt injection is no longer just about obvious jailbreaks. A test suite built only around famous phrases will mostly tell you that your bot recognizes famous phrases.

Step 2: Probe for hidden instructions while a real task is in play

A direct request for the system prompt is easy to refuse. A more realistic test combines that request with a legitimate need. For example, a customer asks about the status of their delivery and, in the same message, asks the bot to explain which rules it follows and how it was set up. The expected behavior is that the bot answers the delivery question and declines to describe its internal configuration, without becoming unhelpful or confused.

Vary the framing from there: ask in a different language, ask for the information as a formatted export, or ask for it piece by piece across several turns. System prompt leakage deserves this attention because a leaked prompt shows an attacker exactly which rules to work around next.

Step 3: Mix legitimate requests with policy pressure

Many chatbots are scoped to a specific purpose, and testers often check scope by asking off-topic questions. The more revealing test pairs an allowed request with a disallowed one. Imagine a store with a 30-day return policy. A customer asks to return an item bought 45 days ago and adds a request for the bot to skip the date check "just this once," because they're a loyal customer.

The safer behavior is clear: the bot applies the policy, explains it politely, and offers a route to a human agent if exceptions are possible. What you're watching for is the bot granting the exception itself, inventing a policy that doesn't exist, or partially complying (for example, generating a return label "for reference").

Step 4: Apply role-play, authority, and urgency

People rarely say "I am attacking you." They say they're the store manager testing the system, that their account was hacked and they urgently need access, or that the conversation is "just a story" in which the bot plays a character with no restrictions. These framings work on people too, which is why they're effective against models trained on human conversation.

Test each of them against your bot's sensitive actions. The expected behavior is that the bot treats identity and authority claims made in chat as unverified and routes the person to an authenticated flow. This is also a design check: if the only thing standing between a user and a restricted action is the model's judgment of whether someone sounds legitimate, the authorization belongs in code.

Step 5: Follow the conversation across many turns

Single-message tests miss a whole class of problems. Multi-turn techniques work by steering a conversation gradually, with each message looking harmless on its own, until the model ends up somewhere it would have refused to go if asked directly. CrowdStrike describes a related pattern it calls trigger-activated rule addition, where an instruction planted early stays dormant until a later keyword or event wakes it up, which makes it easy to miss during review.

To test for persistence, plant an instruction, let the bot refuse it, then carry on with a normal customer conversation for several turns and check whether the earlier instruction resurfaces. Repeat the test in a fresh session to confirm nothing carries over between conversations, and remember to run each scenario several times, since a single pass can't tell you much about a non-deterministic system.

Step 6: Test data boundaries and indirect injection

Privacy tests check whether the bot can be persuaded to share data the current user shouldn't see: another customer's order, internal documentation, pricing rules, or anything stored in its knowledge base that wasn't meant for customers. Try plausible-looking order numbers, ask about "the previous customer," or request internal procedures under a support-related pretext.

For agents and RAG-based systems, indirect injection deserves its own test cycle. In a test environment, place instructions inside the content your agent processes (a support ticket, a product review, a shared document, an email, or a web page it browses) and observe whether the agent follows them when a user makes an ordinary request. EchoLeak showed how much damage this can do when an assistant has access to sensitive data and a way to send it somewhere.

Pay particular attention to tool use: check that the agent can't do more than the user it's acting for is allowed to do, since every tool an agent can call widens the impact of a successful injection. We've written about how much oversight agentic systems need when they act on their own, and the same reasoning applies when the agent is your product rather than your testing tool.

Step 7: Tie every serious finding to the expected safer behavior

A finding that says "the bot leaked its prompt" is hard to act on. A useful finding includes the transcript as evidence, the business impact (privacy exposure, policy bypass, financial loss, reputational harm), a severity rating, the expected safer behavior, and who owns the fix. 

Defining the safer behavior matters more than it seems, because simply making the bot refuse more often tends to create new problems: a bot that refuses every message containing the word "instructions" will frustrate real customers asking for assembly instructions. The goal is a bot that declines the unsafe part of a request and still helps with the legitimate part.

Also decide early how findings get written up. Internal teams may need exact reproduction steps to fix an issue, but reports shared with clients, stakeholders, or the public should focus on the risk, the evidence, and the safer behavior expected from the bot, so the report doesn't turn into a ready-made attack script.

Step 8: Retest after every change

Prompt injection resistance can regress without a single line of application code changing. Updating the system prompt, switching to a new model version, adjusting guardrail settings, adding documents to the retrieval index, or connecting a new tool can all change how the bot responds to pressure. After any of these, rerun the original findings, nearby variants of them, and a set of ordinary customer journeys, so you can confirm that the fix didn't break useful behavior along the way.

Keeping those tests in a maintained set, like a golden dataset, makes the rerun quick. The same logic as regression testing applies here, and our guide to automated regression testing explains how to run such checks on every release.

Factors that can warrant retesting of agents and chatbots, created using Claude Design.
Factors that can warrant retesting of agents and chatbots, created using Claude Design.

Automation helps with the repeatable part. Open-source tools such as Garak, Promptfoo, and Prompt Security's Fuzzer can run adversarial prompts at scale. Automated runs are good at regression and volume, while human testers remain better at the creative, context-specific attempts that real users come up with, so most teams benefit from both. In our own AI chatbot testing work, red-team prompts sit alongside answer quality and performance checks, because a bot that's safe yet slow or inaccurate still fails its users.

Find out what your chatbot can be talked into before your users do

TestDevLab's QA engineers red-team chatbots and AI agents for prompt injection, data leaks, and tool misuse, then help your team fix what they find. Our ISTQB-certified engineers combine automated adversarial testing with human creativity, so you see the attacks real users would try.

How to prevent prompt injection: Defense layers

Once testing has shown where a bot is vulnerable, the next question is how to limit what a successful injection can achieve. The NCSC's position is a helpful anchor here: prompt injection is a residual risk that no single product can eliminate, so the goal is to reduce not only the likelihood, but also the impact of an attack, if it does occur. It also advises caution with any vendor claiming to "stop" prompt injection completely. 

With that in mind, here are the main layers, along with their trade-offs.

Input sanitization

Filtering known dangerous phrases and restricting the length and format of user input is cheap to implement and filters out a fair share of low-effort, copy-pasted attempts. Length limits also shrink the room for long persona scripts.

The limitations are significant, though. Word-based filters are exactly what synonyms, typos, encodings, and translations are designed to get around. Filters can also misfire on legitimate users, such as a customer who types "please ignore my previous message, I meant the blue one." Treat sanitization as a first layer and test it for both missed attacks and false blocks.

Strong prompt design and input separation

A well-structured system prompt gives the model a clear role, scope, and set of limits, including an explicit instruction to ignore attempts to change its core rules. Our guide to prompt engineering covers how to structure prompts. Two further practices make a real difference. 

Keep anything sensitive (API keys, credentials, internal URLs) out of the system prompt entirely, since you should assume it can leak. And separate untrusted content from instructions using strict templates, delimiters, or data marking, so the model can tell what came from your application and what came from a user or an external document. The NCSC discusses this kind of data marking as one of the techniques that make injected instructions harder for a model to act on.

The trade-off is that separation reduces confusion without removing it. CrowdStrike describes a technique called special token injection, in which attackers imitate the very markers applications use to separate roles and content, aiming to get untrusted text treated as a system-level instruction; delimiters help, and they also need additional testing.

Guardrails and monitoring

Guardrails check what goes into and comes out of the model. On the output side, that means defining sensitive categories and filtering responses for them, as well as specifying expected output formats and validating them with deterministic code rather than trusting the model to comply. If your model provider supports settings that give system-level instructions priority over user messages, enabling them adds one more layer. For wrong or invented answers, see our guide to spotting and preventing AI hallucinations.

Monitoring covers what happens after launch. CrowdStrike highlights the need for runtime visibility into prompts and responses: which models and agents are involved, what's being exchanged, and whether sensitive data or unsafe instructions appear in the traffic. The limitation is that guardrails built on language models share some of the same weaknesses as the models they protect, and they can block the same request one time and let it through the next. For that reason, guardrails should be included in the scope of your prompt injection testing alongside the bot itself.

Least privilege and human approval

If an injection gets past every other layer, permissions decide how bad things get. For agents that can send emails, edit records, or move money, we treat this as the layer you can’t skip. OWASP recommends giving the model only the access it needs for its intended task, handling privileged functions in application code, and requiring human approval for high-risk actions. The NCSC puts the stakes plainly: once a model can call tools or APIs, a successful injection can do whatever an attacker with direct access to those tools could do.

In practice, that means read-only access wherever writing isn't essential, caps on refunds or transactions the bot can approve on its own, confirmation steps before emails are sent or records are changed, and authorization checks enforced by the backend rather than the model. The trade-off is some friction for users and some added work for support teams, which is usually a fair price for actions with real financial or privacy consequences. It also connects to broader security testing, since the APIs and permissions behind an agent need the same scrutiny as any other part of the system.

Training and fine-tuning data hygiene

For teams that fine-tune their own models, the training data is an attack surface of its own. Research on data poisoning has shown that a small number of poisoned fine-tuning examples paired with a trigger word can teach a model to comply with unsafe requests whenever that trigger appears. Vetting and sanitizing training and fine-tuning data, and including examples of correct refusals, reduces that risk. Like the rest of the defenses here, it needs revisiting whenever training data or safety requirements change.

Most teams building on hosted models don't train them at all, but they do curate the documents their bot retrieves. An attacker who can modify a document in a RAG repository can change the bot's answers for every user whose question retrieves it. Applying the same hygiene to your knowledge base (who can edit it, how content is reviewed, and how changes are tracked) is the hosted-model equivalent.

Defense layer What it helps with Where it falls short
Input sanitization Low-effort, copy-pasted attempts; overly long persona scripts Synonyms, typos, encodings, and other languages; false blocks on legitimate users
Prompt design and separation Role confusion; untrusted content being read as instructions Attackers imitating delimiters 
and role markers
Guardrails and monitoring Sensitive data in outputs; visibility into live traffic LLM-based guardrails can behave inconsistently
Least privilege and human approval Limiting the damage of any successful injection Added friction for users and support teams
Data hygiene Poisoned fine-tuning data and knowledge base content Requires ongoing review rather than a one-time cleanup

Closing the chat 

Prompt injection is hidden in plain sight, so anyone who can type into a chat window or influence the content a bot reads can attempt it, often without looking like an attacker at all. Because current models can’t reliably separate instructions from data, no single filter, prompt, or guardrail will catch every attempt, and the more tools and data a chatbot or agent can reach, the more a successful attempt can do.

That puts the weight on how teams test and design these systems. Start by defining what the bot should and shouldn’t do, then map every channel that feeds text into its context, including documents, emails, and tool outputs. Test the way real users and real attackers behave, across many turns, with authority claims, urgency, mixed requests, and instructions hidden in content, and repeat each test several times. Report every finding with the safer behavior you expect, layer your defenses, and keep the bot’s permissions as narrow as its job allows. Finally, treat prompt injection testing as a regular part of your release cycle and rerun it whenever the system prompt, the model, the guardrails, the knowledge base, or the connected tools change.

To go further, read our guides to testing AI chatbots, testing LLM apps, and testing AI agents. If you would rather work with a partner, compare options in our roundup of the best AI application testing companies.

FAQ

Most common questions

What is prompt injection testing?

Prompt injection testing checks whether a message or a piece of content can push a chatbot or AI agent into ignoring its rules, revealing hidden instructions, exposing private data, or taking actions it should not. It covers both direct attacks typed into the chat and indirect ones hidden in content the model reads.

What is the difference between direct and indirect prompt injection?

In direct prompt injection, the instruction sits in the user's own message. In indirect prompt injection, the instruction is hidden in external content the model reads later, such as a web page, an email, a PDF, or a document retrieved through RAG. The user making the request may not know the content contains an instruction.

Is prompt injection the same as jailbreaking?

Jailbreaking is generally treated as a type of prompt injection, aimed at getting a model to drop its safety rules entirely. Prompt injection is the broader category, and attempts often target a bot's specific instructions, data, and permissions instead.

Can prompt injection be fully prevented?

Not with current models. They cannot reliably separate instructions from data, so the UK's NCSC advises reducing both the likelihood and the impact of an attack, using layered defenses such as input checks, prompt design, guardrails, monitoring, and least privilege.

How often should you test for prompt injection?

Test before release, and retest whenever the system prompt, the model version, the guardrail settings, the knowledge base, or the connected tools change. Run automated checks on every release, and add human red-team sessions periodically, since people come up with attempts that scripts do not.

Don't let a polite chat message become a security incident

TestDevLab's QA engineers test your chatbots and AI agents for prompt injection, map where untrusted text enters your system, and report findings with the safer behavior your bot should show. Tell us what your bot can access, and we'll recommend where to start.

Summarize with:

QA engineer having a video call with 5-start rating graphic displayed above

Save your team from late-night firefighting

Stop scrambling for fixes. Prevent unexpected bugs and keep your releases smooth with our comprehensive QA services.

Explore our services