Prompt Injection Defense for LLM Apps: Threats, Tests, and a Mitigation Checklist
Prompt injection is an application-security problem, not merely a prompting problem. This guide provides a repeatable way to identify direct and indirect injection risks, limit what an LLM application can do, test its defenses, and decide when a prompt, model, tool, or retrieval change requires a new security review.
Overview
A prompt injection occurs when untrusted content influences an LLM to disregard, reinterpret, or work around the instructions that the application intended to control its behavior. The untrusted content might come directly from a user, or it might be embedded in a document, web page, email, image, support ticket, database record, or tool result.
Direct injection is visible in the conversation: a user asks the assistant to reveal hidden instructions, ignore its task, or perform an unrelated action. Indirect prompt injection is harder to notice because the attacker places instructions in content that the application later retrieves or processes. For example, a document used in a retrieval-augmented generation (RAG) workflow might contain text telling the model to disclose confidential context or call a tool.
LLMs are useful for interpreting language, but they should not be treated as an authorization system. A reliable defense therefore uses multiple controls around the model:
- Separate trusted instructions from untrusted data in the application design.
- Give tools the narrowest permissions and inputs they need.
- Validate tool arguments and model outputs in ordinary application code.
- Require human approval for sensitive or irreversible actions.
- Log security-relevant events without storing unnecessary secrets.
- Run repeatable adversarial tests whenever the application changes.
Prompt formatting and instruction hierarchy can reduce confusion, but they do not replace these controls. For background on creating reliable instructions, see How to Write Reliable AI Prompts. Security reviews should focus on the complete workflow, including retrieval, memory, tools, streaming, and downstream systems.
What to track
1. Trust boundaries and data sources
Start by listing every place text, images, files, or structured data enter the application. Mark each source as trusted, user-controlled, externally sourced, or unknown. Do not assume that content is safe because it came from a database or an internal employee. Imported content can contain attacker-controlled text, and an internal account may have been compromised.
For each source, record whether the content is sent to the model, stored in memory, included in a prompt, used to select a tool, or displayed to another user. The more decisions a source can influence, the more carefully it should be isolated and tested.
2. Instruction and data separation
Track where system-level guidance, developer rules, user requests, retrieved passages, conversation history, and tool results are assembled. Use explicit labels and structured message fields where the model interface supports them. Tell the model that retrieved content is evidence to analyze rather than authority to follow, but also enforce that distinction in code.
A useful design question is: “What happens if every retrieved passage contains an instruction to ignore the application’s task?” The safe answer should be that the application still limits the model to its approved task and capabilities.
3. Tool permissions and high-impact actions
Inventory every tool available to the model. Record its allowed operations, authentication context, data access, network access, rate limits, and whether an action can be reversed. Separate read-only tools from tools that send messages, modify records, execute code, move money, change permissions, or expose personal information.
Use server-side authorization for every tool call. A model’s statement that a user is authorized is not evidence of authorization. Validate arguments against an allowlist or schema, reject unexpected fields, and check ownership and scope outside the model.
4. Exfiltration paths
Track how sensitive information could leave the application. Potential paths include model responses, tool arguments, URLs, email bodies, logs, analytics events, error messages, generated files, and conversation memory. Test whether an attacker can cause the application to repeat secrets, place them in a tool request, or send them to an external destination.
Limit the context supplied to each task. Redact secrets before model processing where practical, and avoid putting credentials or unnecessary personal data into prompts. If a tool needs a credential, keep it in the tool service rather than exposing it to the model.
5. Output and behavior signals
Monitor more than whether the final answer sounds correct. Track blocked tool calls, rejected arguments, repeated instruction-override attempts, unusual requests for secrets, unexpected destinations, sudden changes in tool usage, and model outputs that fail a required schema. These signals can reveal attacks even when the visible answer appears harmless.
For a broader evaluation workflow, use a golden dataset and regression checks as described in the LLM Evaluation Test Suite. Security tests should be a distinct category within that suite, not an afterthought.
Control table
| Risk | Practical mitigation | Evidence to review |
|---|---|---|
| Direct instruction override | Clear task boundaries, limited context, refusal and escalation paths | Adversarial prompt results and refusal consistency |
| Indirect injection in retrieved content | Label retrieved text as untrusted evidence; filter, isolate, and test sources | RAG attack cases and retrieval-source inventory |
| Unauthorized tool use | Server-side authorization, least privilege, argument validation | Tool-call logs and denied-action tests |
| Data exfiltration | Minimize context, redact secrets, restrict destinations, review outputs | Canary-secret tests and outbound request records |
| Irreversible action | Human approval, confirmation screens, dry-run mode, rollback procedures | Approval records and recovery tests |
| Hidden state or memory abuse | Scope memory, validate writes, provide deletion and review controls | Memory mutation tests and stored-content audits |
Cadence and checkpoints
Prompt injection defense should be reviewed on a schedule and after meaningful changes. A monthly or quarterly review can cover stable applications; higher-risk systems may need more frequent checks. The goal is not to rerun every test manually, but to maintain a small, repeatable security regression suite.
Before production release
- Map all model inputs, retrieval sources, memories, tools, and external destinations.
- Confirm that permissions are enforced outside the model.
- Run direct and indirect injection cases against every relevant workflow.
- Verify that sensitive actions pause for appropriate human approval.
- Confirm that logs support investigation without exposing avoidable secrets.
Monthly or quarterly review
- Review blocked requests, unusual tool calls, and failed output validations.
- Retest a representative set of injection prompts and malicious documents.
- Check whether new data sources, tools, integrations, or memory fields were added.
- Compare results with the previous evaluation run and investigate regressions.
- Review access permissions and remove capabilities that are no longer required.
Change-based checkpoints
Run a focused review after changing the model, system prompt, routing logic, retrieval pipeline, chunking strategy, tool schema, authentication flow, memory behavior, or output parser. Also review the system after a security incident, a newly discovered attack pattern, or a change in the type of data the application handles.
Applications that stream responses should test cancellation, partial output, and errors as well as normal completion. The guidance in Streaming LLM Responses in Web Apps is relevant because a partial response or interrupted tool sequence can create a different security state from a completed request.
How to interpret changes
Do not treat a single successful or failed test as a complete security verdict. Interpret results by capability and impact. A harmless answer that says “I will ignore that instruction” is useful, but it matters more whether the application prevented an unauthorized database query, outbound request, or record change.
When a result changes, classify the cause before changing the prompt. Possible causes include a new model, altered context order, longer retrieved passages, a changed tool schema, a parser regression, a permission change, or a different temperature and routing path. This prevents teams from applying a prompt patch to what is actually an authorization or validation defect.
Prioritize findings using three questions:
- What can the attacker influence? User text alone is different from a source that can affect tools or stored memory.
- What can the application do? Read-only answers generally have a smaller impact than external side effects.
- How easily can the behavior be detected and reversed? Approval gates, audit logs, and rollback reduce consequences but do not eliminate the underlying risk.
For complex agents, maintain explicit state, checkpoints, and recovery rules rather than relying on the conversation alone. The patterns in AI Agent State Management can help teams make actions auditable and easier to stop.
When to revisit
Revisit this checklist at least monthly or quarterly, depending on the application’s risk and rate of change. A scheduled review should compare the current threat model, permissions, test results, and observed behavior with the previous review. Keep the date, version, scope, unresolved findings, and owner for each review so that security work remains traceable.
Schedule an additional review immediately when you:
- Add a retrieval source, file upload, browser connector, plugin, API, or new tool.
- Give the model access to personal, financial, confidential, or production data.
- Change a system prompt, instruction hierarchy, memory design, or agent plan.
- Replace a model, modify routing, or alter context assembly and output parsing.
- Observe unusual tool calls, data exposure, policy bypass attempts, or unexplained regressions.
- Receive a new security report that matches your application’s architecture.
For a practical next step, create a small attack-simulation file with direct override requests, malicious retrieved documents, secret-extraction attempts, unauthorized tool calls, malformed arguments, and requests for irreversible actions. Run it in staging, record expected behavior, and add every confirmed regression to the permanent suite. Combine that testing with the prompt comparison methods in the LLM Evaluation Guide. Prompt injection defense is strongest when it is treated as an ongoing engineering control: narrow permissions, validate outside the model, log carefully, test repeatedly, and revisit the review whenever the application’s capabilities change.