Sub topic 13
Defense in Depth: Assume the Injection Succeeds
Prerequisites and scope
This chapter assumes you can read Python and have called a chat-style LLM API. You should also know the web security basics of untrusted input and XSS. It also assumes you have met direct and indirect prompt injection, data exfiltration, excessive agency and insecure output handling in earlier chapters. Here we pull those threats into one design approach. Later chapters cover filtering, prompt structure, least privilege, approval and testing in detail.
The design stance
An LLM reads instructions and data as one stream of text. No filter, delimiter or system prompt can guarantee that the model will ignore an instruction hidden in a document. If your design depends on the model always resisting, a single successful injection compromises everything.
Defense in depth starts from a different assumption: the injection will sometimes succeed. You then ask two questions at each step of the application:
- How do I make success less likely?
- If it succeeds anyway, what is the worst thing that can happen, and what limits it?
The second question matters more. Prompt-level defenses reduce probability. Controls outside the model reduce impact. A sound design uses both.
Why one layer is not enough
Each single defense has a known failure mode.
| Defense | What it does | How it fails |
|---|---|---|
| Input filter | Blocks known attack phrases | Paraphrase, other languages, encodings and split payloads get through |
| Prompt structure | Marks untrusted text as data | The model can still follow instructions inside the markers |
| Output filter | Removes dangerous output | Misses new exfiltration channels |
| Least privilege | Limits what tools can do | Does not stop misuse of the permissions you did grant |
| Human approval | Stops high-impact actions | Fails if reviewers approve without reading |
Because the failure modes differ, stacking layers means an attacker must defeat several different mechanisms. Layers only help if they are independent. Two filters that use the same keyword list fail together.
The layers
The diagram shows where each control sits on the path from untrusted content to impact.
Layers fall into three groups.
Reduce the likelihood
- Input and output filtering catches obvious payloads and suspicious output. It is cheap and easy to bypass.
- Prompt structure separates roles and wraps untrusted text in delimiters. It helps, but it is advice to the model, not enforcement.
Limit the impact
- Least privilege and isolation give the application only the tools, scopes and credentials its task needs. A summarizer with no tools cannot send email, whatever the document says.
- Output sanitization treats model output as untrusted. It strips remote images, restricts links and escapes HTML so rendering cannot leak data.
- Human approval puts a person in front of high-impact actions such as sending messages, spending money or deleting data.
Detect and learn
- Testing runs known payloads against the application before release and after each change.
- Logging and monitoring record prompts, tool calls and blocked actions, so you can spot attacks and respond.
Enforcement belongs outside the model
The key property of the strong layers is that code enforces them, not the model. This policy does not care what the model "decided":
READ_ONLY_TOOLS = {"search_docs", "get_order_status"}
NEEDS_APPROVAL = {"send_email", "issue_refund"}
def run_tool_call(name, args, tools, approve):
"""Run a model-requested tool call under a deny-by-default policy."""
if name in READ_ONLY_TOOLS:
return tools[name](**args)
if name in NEEDS_APPROVAL and approve(name, args):
return tools[name](**args)
raise PermissionError(f"Tool call not permitted: {name}")If an injected document convinces the model to request delete_account, the call raises an error. The injection succeeded at the model level and failed at the system level. That is the goal.
Compare this with a prompt that says "never delete accounts". The model may or may not obey it, and an attacker can argue with it. Code cannot be argued with.
Walking through an attack
Consider an assistant that summarizes incoming email and can also send email. An attacker sends a message containing hidden instructions to forward the user's recent mail to an outside address.
- The input filter does not match the attacker's unusual phrasing. Layer 1 fails.
- The prompt marks the email as untrusted, but the model follows the instruction anyway. Layer 2 fails.
- The model requests
send_emailwith the attacker's address. - The policy puts
send_emailin the approval set, so the user sees "Send 5 messages to [email protected]?" and declines. The attack is stopped. - The blocked call is logged, and monitoring flags a high-impact request that came from an email-processing session.
Two of the layers failed, and the attack still caused no harm. Step 5 also gives you a signal that this class of email is being used against you, so you can add it to your test suite.
Failure modes of the layered approach
Layering is not magic. Watch for these problems:
- Shared failure. Layers that depend on the same assumption fail together. An approval prompt that shows only the model's own summary of an action can be manipulated by the same injection.
- Approval fatigue. If users see a prompt for every action, they click through. Reserve approval for genuinely high-impact actions and show the real parameters, such as the actual recipient, not a model-written description.
- Permission creep. Tools gain scopes over time. A review of the tool list each release keeps the least-privilege layer honest.
- Untested layers. A control that is never exercised may be broken. Include tests that expect the block, such as "this call must raise
PermissionError". - Confused deputy. The application often holds more authority than the person whose request is being served. Run tools with that user's credentials, not a shared powerful account.
Applying the approach to a design
Work through these steps for any LLM feature:
- List every source of untrusted text: user input, documents, web pages, email, tool results and retrieved data.
- List every capability the model can reach: tools, APIs, data stores and rendering paths.
- For each pair, ask what an attacker gains if the model obeys text from that source.
- Remove capabilities you do not need. Add enforcement in code for the ones you keep.
- Add approval for the remainder that is high-impact or irreversible.
- Add tests and logging so you can verify the controls and see attempts.
The OWASP Top 10 for LLM Applications works well as a checklist for step 3, since it names the common risks, including prompt injection, insecure output handling and excessive agency.
Exercises
Exercise
A support bot reads customer tickets and can call issue_refund. The system prompt says "Never issue refunds unless the ticket is verified." A ticket contains hidden text telling the bot the ticket is verified. Name two controls outside the model that would limit the damage, and explain why the system prompt alone is not enough.
Show answer
Put issue_refund in an approval set so a human sees the real amount and customer before it runs, and scope the tool's credentials or limits (for example a maximum amount, or only refunds for the ticket's own customer). The system prompt alone is not enough because it is text in the same stream as the attacker's text. The model can be persuaded to treat the injected claim as true, and nothing in code checks the verification.
Exercise
Why does stacking an input keyword filter and an output keyword filter built from the same phrase list give less protection than the two layers appear to give?
Show answer
The layers share a failure mode. A payload that avoids the listed phrases, through paraphrase, translation or encoding, passes both filters. Independent layers should fail for different reasons, such as a filter, a code-enforced permission check and human approval.
Exercise
In the email-assistant walkthrough, which layer actually stopped the attack, and what does that tell you about where to invest design effort?
Show answer
The human approval step combined with the code-enforced tool policy stopped it. The filter and the prompt structure both failed. Effort should go to controls that code enforces and that limit impact, since probability-reducing controls will sometimes be bypassed.