Skip to content
/ POST · CHAT AGENTS

How to Prevent Prompt Injection in a Chatbot: 7 Design Steps

OWASP knows no fool-proof fix for prompt injection. These 7 design steps limit what an injected customer chatbot can read, change or send.

Author · HarryNovember 15, 202610 min read

You cannot fully prevent prompt injection: OWASP's 2025 guidance says it is unclear whether fool-proof prevention exists. What you can control is how much damage an injected chatbot can do. SwiftBiz's 7-step design checklist for customer-facing chatbots shrinks that damage: map what the bot touches, remove authority, gate actions, fix the output, distrust outside content, filter, then test.

The steps map OWASP's seven LLM01 mitigations and Action 1 of the Canadian Centre for Cyber Security's May 2026 AI security primer to a small-business chatbot, and the worked example is SwiftBiz's own website chatbot, described from its source code. Sources checked on November 15, 2026.

Can you prevent prompt injection completely?

No. Prompt injection is an attack where text a chatbot reads, typed by a visitor or hidden in a document, changes what the bot does. OWASP's LLM01:2025 Prompt Injection defines it as user prompts that "alter the LLM's behavior or output in unintended ways" and says: "it is unclear if there are fool-proof methods of prevention for prompt injection." Its seven measures "mitigate the impact."

The UK's National Cyber Security Centre goes further. In its 8 December 2025 blog post Prompt injection is not SQL injection (it may be worse), it explains that a language model makes no inherent distinction between data and instructions, so "prompt injection attacks may never be totally mitigated in the way that SQL injection attacks can be." Its advice is to focus on "deterministic (non-LLM) safeguards that constrain the actions of the system."

So ask a different question: if someone does inject my bot, what is the worst it can do?

What are the 7 steps, and where do they come from?

Each step pairs an OWASP mitigation with the matching line from Action 1 of the Cyber Centre's Top 10 artificial intelligence security actions: A primer (ITSAP.10.049, May 2026), where prompt injection defence is Action 1 of 10.

StepWhat you doOWASP LLM01 mitigationCyber Centre wording
1Map what the bot can read, write and send(groundwork for all seven)"Reduce access to private data by AI models"
2Remove authority the bot does not need4. Enforce privilege control and least privilege access"Restrict high risk tools and agents via role based access and identity controls"
3Put a person or a code check before every irreversible action5. Require human approval for high-risk actions"Validate downstream actions (files, code and tools) before execution"; Action 9, human-in-the-loop
4Make the output a fixed shape that code validates2. Define and validate expected output formats"Apply output filtering and policy gating"
5Treat documents, pages and emails the bot reads as untrusted6. Segregate and identify external content"Limit exposure to untrusted content"
6Filter what goes in and what comes out3. Implement input and output filtering"Sanitize inputs"; markdown image URLs
7Write the rules into the system prompt, then test1. Constrain model behavior; 7. Adversarial testing"Isolate system prompts and protect prompt history"

Steps 1 to 4 limit what a successful injection can achieve. Steps 5 to 7 make success less likely, and they are the weaker layers.

Step 1: What can your chatbot read, write and send?

The blast-radius map is a one-page table that lists each capability a chatbot has and what an attacker could do with it, so you can remove or gate the dangerous rows before launch.

CapabilityExampleIf an attacker controls itKeep, gate or remove?
Reads your knowledge basePolicy pages, FAQsCan make the bot quote it out of contextKeep
Reads customer recordsOrder status lookupCan try to pull another customer's dataGate: look up only the verified customer's record
Writes to systemsCreate a booking, update a CRM fieldCan create junk or change recordsGate: code validates every field
Sends messagesEmail, SMS, webhookCan send spam or leak data outwardGate or remove
Commits moneyRefunds, discounts, price quotesCan give away money or promise a priceRemove
Shows links and imagesMarkdown in repliesCan smuggle conversation data out in a URLRestrict

Step 2: Which permissions should you take away?

Take away every permission the bot's one-sentence job does not need, starting with anything that commits money. A support bot should have no refund authority, no discount codes and no ability to quote a price that is not on your price list. OWASP's mitigation 4 says to "handle these functions in code rather than providing them to the model" and to restrict access "to the minimum necessary."

  • Read-only by default. An order-lookup bot gets a read-only account that sees one order by number, not a database login.
  • Scoped credentials. A rule of thumb the NCSC quotes from Simon Willison and Baibhav Bista is that "when an LLM processes information from a party, the privileges it has drops to that of the party." A bot talking to anonymous visitors should hold no privileges worth stealing.
  • No wildcard access. If your bot uses tools through the Model Context Protocol, the MCP security best practices call for "a progressive, least-privilege scope model" and list "wildcard or omnibus scopes (*, all, full-access)" as a common mistake.

The Five Eyes guidance on careful adoption of agentic AI, co-authored by the Cyber Centre, says never to grant AI agents "broad or unrestricted access, especially to sensitive data or critical systems."

Step 3: Which actions need a person to approve them?

Any action you cannot undo cheaply needs a person, or a plain-code rule, between the bot and the result: refunds, cancellations, outbound emails to new addresses, record deletions and anything over a dollar threshold. OWASP's mitigation 5 is "Implement human-in-the-loop controls for privileged operations," and the Cyber Centre's Action 9 asks for "human checkpoints in automated and multi-agent workflows."

The bot drafts the refund; a staff member approves it. Our guide to human-in-the-loop AI workflows covers where to put the checkpoint. If your bot takes real actions in other systems, test those actions with the AI agent actions checklist.

Step 4: How do you make the bot's output something code can check?

Wherever the bot's reply feeds another system, require a fixed format and check it in code before anything happens. OWASP's mitigation 2 is to "use deterministic code to validate adherence to these formats." A field that must be an email address, a date in your hours, or one of five service names is easy to verify; free text is not. Keep business decisions, such as whether a lead qualifies or a discount applies, in rules your developer wrote, not in the model's judgment.

Step 5: How do you handle documents, web pages and emails the bot reads?

Treat anything the bot reads from outside as untrusted, because indirect injection hides instructions in exactly that content. OWASP's second example scenario is a web page "containing hidden instructions" that make the model insert an image linking to a URL, which leaks the private conversation. Its fourth is a modified document in the knowledge base.

What to do:

  • Control the knowledge base. Load only documents your staff wrote or reviewed. Do not let the bot index customer uploads or the open web unless that is its job.
  • Label outside content. OWASP's mitigation 6 says to "Separate and clearly denote untrusted content." Your developer can wrap retrieved text in clear markers and tell the model it is reference material, never instructions.
  • Do not trust the browser. Chat history, page URLs and hidden form fields sent from the visitor's browser can be edited by the visitor.

Step 6: What should you filter going in and coming out?

Filter inputs for size and rate, and outputs for anything that could carry data out. Cap message length and messages per session, escape any bot text you put into an email or web page, and restrict links and images in replies. The Cyber Centre specifically names reducing "the ability for AI systems to communicate externally (such as embedded data in markdown image URLs)."

If your chat window displays markdown images, an injected bot can write an image whose web address contains the visitor's details, and the browser sends them to the attacker's server by loading it. The strongest fix is to configure your chat renderer not to display images at all. As a first layer, a one-line filter can strip inline markdown images before display:

// Replace inline markdown images with a placeholder before rendering.
// The placeholder has no square brackets, so it cannot join nearby text into a new image.
const stripImages = (reply) => reply.replace(/!\[[^\]]*\]\([^)]*\)/g, "(image removed)");

What it catches: inline images, including ones with an empty description, a title, a data URI, an address in angle brackets, several in one reply, or an image inside a link. Ordinary links are left alone. A web address containing parentheses is cut short, which leaves stray text but no image. What it misses: reference-style images (![x][1] with the address defined elsewhere in the reply), raw HTML image tags, and images whose description itself contains square brackets. It is a backstop, not the fix.

Do not rely on phrase blocklists. The NCSC warns against blocking text like "ignore previous instructions" because "there are infinite ways to rephrase an attack."

Step 7: What belongs in the system prompt, and what doesn't?

Put the bot's role, topics and refusals in the system prompt, and assume visitors can read it. OWASP's mitigation 1 is to give the model "specific instructions about the model's role, capabilities, and limitations," and its LLM07:2025 System Prompt Leakage entry adds that "the system prompt should not be considered a secret, nor should it be used as a security control." Never put passwords, API keys, internal margins or customer data in it.

Then test. OWASP's mitigation 7 is adversarial testing, "treating the model as an untrusted user." Run the injection gate in our 9-gate chatbot test before launch, and for a bot already live, follow the OWASP-mapped red-team plan. This guide designs the defences; those two check them.

How is SwiftBiz's own website chatbot built?

The chat assistant on swiftbiz.ai is a sales and support bot. Here is its blast-radius map, taken from our code, not from a test run:

CapabilityHow it is builtWorst case if injected
Tools and actionsNone. The model receives its instructions and the conversation and returns textIt cannot book, refund, email or look anything up
KnowledgeA knowledge file written by us, in the code; no web browsing, no uploadsPlanted documents are not a path in
Lead detailsA separate call that must return JSON matching a fixed 9-field schema (name, email, company, services, budget, timeline, pain points, company size, industry), no extra fields allowedJunk values in one lead record
Lead decisionsPlain code scores the lead and decides when to notify our team; fields are HTML-escaped in the emailA junk lead saved to our CRM and an unwanted notification to our own inbox
InputMessage and history sizes are capped, roles are limited to visitor and assistant, and each conversation is rate-limitedOversized or malformed requests are rejected
Page contextThe page address is matched against a fixed list of site routes; only our own labels reach the promptA crafted URL cannot write into the prompt
DisplayHTML is sanitised, scripts, frames and forms are removed, and links are limited to web and email addressesScripts, frames and forms in a reply do not run

Two limits remain by design. The system prompt's security section is the last layer, not the defence. The conversation history arrives from the visitor's browser, so it is capped and checked, never trusted.

If you want the same map drawn for your bot, start with an AI Readiness Audit ($3,500, credited toward your retainer), or see how we build AI chat agents. All SwiftBiz prices are in Canadian dollars (CAD).

How do you know the defences are working?

You know when injection tests fail to produce a harmful result and your logs would show an attempt if one happened. Three checks:

  • Every "remove" row in the blast-radius map is gone. Ask to see the bot's credentials and tool list.
  • Injection cases pass three runs out of three in the pre-launch test, because a model can answer the same prompt differently each time.
  • You log inputs, outputs and tool calls. The NCSC notes that "detecting and responding to failed tool calls or API calls could identify earlier stages of an attack." A spike in refused or failed actions is worth an alert.

When is this more design than you need, and what doesn't it cover?

  • A menu-only bot that shows fixed answers and links cannot be injected in this sense. Ordinary functional testing is enough.
  • A text-only FAQ bot with no tools and no customer data needs steps 1, 6 and 7. Its worst case is an embarrassing reply, which still matters; you are responsible for what it tells customers.
  • A bot that reads email, browses the web or takes actions needs all seven, and the NCSC's warning applies: "If the system's security cannot tolerate the remaining risk, it may not be a good use case for LLMs."

Hallucinated answers and privacy compliance need their own controls, and no design here makes a bot injection-proof. SwiftBiz builds and tests these systems; we do not certify them as secure.

What do owners ask about prompt injection?

Can a good system prompt stop prompt injection?
No. Instructions in the system prompt make injection harder, but OWASP's LLM07:2025 entry says the system prompt should not be considered a secret or used as a security control. Assume a determined visitor can read it and talk the model around it. Put the real limits in code and permissions: what the bot can access, which actions need approval, and what output formats your systems accept.
What is the difference between direct and indirect prompt injection?
Direct injection is typed by the person chatting with the bot, such as telling it to ignore its rules. Indirect injection is hidden in content the bot reads: a web page, an email, an uploaded file or a document in its knowledge base. OWASP lists both under LLM01:2025. Indirect injection is more dangerous for bots that read outside content, because the attacker never has to talk to the bot.
Do prompt injection filters and guardrail products work?
They reduce risk; none removes it. The UK NCSC advises buyers to beware any product that claims it can stop prompt injection and to prefer vendors who explain how they reduce it. Phrase blocklists are especially weak, because an attack can be reworded endlessly. Use a filter as one layer on top of least privilege, approval steps and validated output formats, not instead of them.
Is a chatbot with no tools safe from prompt injection?
Safer, not safe. Without tools or customer data, an injected bot cannot refund money, send email or leak records, so the worst case shrinks to what it says in that one chat. That can still mean an off-brand reply, a revealed system prompt or a wrong promise to a customer, so keep output filtering and testing in place.
What does SwiftBiz charge to review a chatbot's defences?
SwiftBiz's red-teaming / safety audit is $5k per engagement, and the AI Readiness Audit is $3,500, credited toward your retainer. The AI Chatbot Starter, a standalone chatbot trained on your data, is $8,000 one-time. All prices are in Canadian dollars.

Which controls should you put in first?

  • If your bot can move money or change records, do steps 2 and 3 before anything else: remove the authority or add an approval step.
  • If your bot reads outside content (email, web pages, uploads), do step 5 next and switch off images in the chat window.
  • If your bot only answers questions from your own documents, steps 6 and 7 plus a pre-launch injection test are the right size.
  • If a vendor tells you their product stops prompt injection, ask what the bot can still do when it fails. The answer is your blast radius.

Want this running for your business?

Start with a free strategy call. We'll map your workflow, flag the highest-ROI automation, and tell you honestly whether we're the right fit.