Prompt injection can cause an LLM application to ignore intended instructions, reveal sensitive context, or misuse connected tools. This guide provides a reusable testing matrix, red-team test-case template, layered mitigation checklist, and incident-response workflow for RAG systems, AI agents, and ordinary user-input flows.
Overview
Prompt injection is an instruction-conflict problem. An application combines system guidance, developer rules, retrieved content, tool results, and user input, but an attacker may place instructions inside one of those inputs and try to make the model treat them as higher-priority directions. The attempted instruction may be obvious, such as “ignore previous instructions,” or hidden in a document, web page, email, code comment, image description, or tool response.
Prompt injection prevention is not a single prompt-engineering trick. A stronger approach treats the model as one component in a larger security boundary. Prompts should clearly separate trusted instructions from untrusted data, while application code controls authorization, data access, tool permissions, output handling, and audit logging. Testing should then verify that these controls still work when the model receives adversarial or misleading content.
For every test, define the protected asset and the unacceptable outcome first. Assets might include private retrieval results, system instructions, API credentials, customer records, internal URLs, or the ability to send messages and change data. An unacceptable outcome might be disclosure, unauthorized action, instruction override, unsafe formatting, or an inability to recover after an attack.
Keep a versioned record of prompts, models, retrieval settings, tools, and test results. A prompt change, new data source, model change, or permission change can alter the risk profile. A practical LLM prompt versioning workflow makes these changes easier to compare and roll back.
Checklist by scenario
RAG prompt injection
RAG systems can retrieve documents that contain instructions unrelated to the user’s question. Treat retrieved text as reference material, not as an authority that can redefine the application’s behavior.
- Label retrieved passages as untrusted content in the prompt and in internal data structures.
- Tell the model to extract relevant facts while ignoring instructions found inside documents.
- Test direct attacks, such as a document that requests secret disclosure or a change to the response format.
- Test indirect attacks, such as a malicious instruction hidden in a support ticket, knowledge-base article, code block, metadata field, or document title.
- Check whether retrieval can expose documents the user is not authorized to access. Prompt instructions cannot replace server-side access control.
- Inspect citations and source identifiers so the application does not present attacker-controlled text as a trusted system message.
Retrieval quality and security are connected. A chunking or ranking change can surface previously hidden content. Use repeatable retrieval tests alongside security cases; the RAG chunking and retrieval tuning guide can help structure that evaluation.
AI agent and tool-use attacks
Agents introduce a second risk: an injected instruction may persuade the model to call a tool. Place authorization in application code, not only in the system prompt.
- List each tool, its permitted operations, required inputs, and possible side effects.
- Use least-privilege credentials and separate read operations from write, delete, payment, messaging, or deployment operations.
- Validate tool arguments against schemas, allowed destinations, resource ownership, and business rules.
- Require explicit confirmation or a human approval step for consequential actions where appropriate.
- Test whether untrusted text can trigger a tool call, alter an argument, bypass confirmation, or cause repeated calls.
- Set limits for tool-call count, execution time, destination, and spend where those limits apply.
- Log the user request, retrieved context, proposed action, authorization decision, and tool result without exposing secrets in logs.
Use a clear plan-and-execute boundary: the model may propose an action, but a deterministic policy layer decides whether that action is allowed. For design patterns covering permissions and recovery, see the AI agent tool-calling architecture guide.
User input and conversational flows
Direct user input can attack the instruction hierarchy, request hidden configuration, or attempt to turn the assistant into an unrestricted execution interface.
- Define what the assistant may answer, what it must refuse, and which tasks require escalation.
- Test requests to reveal system or developer instructions, credentials, private context, and internal tool details.
- Test multi-turn attacks in which a harmless conversation gradually establishes a misleading role or objective.
- Test encoded, obfuscated, multilingual, and mixed-format instructions when those inputs are accepted by the product.
- Verify that output is safely encoded before being inserted into HTML, SQL, shell commands, templates, or downstream prompts.
- Keep sensitive values out of prompts whenever possible and apply input redaction before model calls.
Prompt-level defenses work best when paired with careful data handling. Review the LLM data privacy and PII redaction guide before adding new user or enterprise data sources.
What to double-check
Use the following red-team test-case template for each attack scenario:
- Case ID: assign a stable identifier so the test can be rerun.
- Entry point: record whether the payload enters through user text, retrieved content, a file, a tool result, metadata, or conversation history.
- Attacker objective: state the intended outcome, such as secret extraction or unauthorized tool use.
- Payload: preserve the exact input, including formatting, encoding, and surrounding context.
- Expected behavior: specify the allowed response, refusal, escalation, or blocked action.
- Observed behavior: capture the model output, tool calls, retrieved sources, and policy decisions.
- Severity and evidence: describe the affected asset, reproducibility, and whether an external side effect occurred.
- Fix and regression test: record the mitigation and keep the original case in the test suite.
Double-check the boundaries around every model call. Confirm that secrets are not placed in system prompts unnecessarily, that access checks happen before retrieval, that tool results are treated as untrusted, and that the model cannot directly decide its own permissions. Also verify failure behavior: an outage, malformed tool response, timeout, or fallback model should not silently bypass safety checks. Reliability planning should remain separate from authorization; the LLM fallback and failover guide offers a useful companion review.
Finally, compare results across the model and configuration combinations you actually support. Do not assume that a mitigation tested on one model, temperature setting, context length, or tool schema behaves identically elsewhere. Record the environment with each result.
Common mistakes
- Relying on a stronger system prompt alone: a prompt can clarify intent, but it cannot enforce database permissions or prevent every model failure.
- Putting untrusted text beside trusted instructions without labels: explicit delimiters and structured fields make the intended boundary easier to preserve and test.
- Giving agents broad credentials: a successful injection becomes more damaging when one tool account can read, modify, and delete unrelated resources.
- Testing only obvious jailbreak phrases: realistic attacks may be indirect, multi-turn, encoded, or embedded in retrieved content.
- Checking only the final answer: a response may look harmless even though the agent made an unauthorized tool call or exposed data in an intermediate trace.
- Logging sensitive payloads indiscriminately: security testing can create a second data-exposure problem. Redact secrets and restrict access to test artifacts.
- Fixing a case without adding regression coverage: every confirmed issue should become a repeatable test tied to the relevant release or prompt version.
When to revisit
Run the full checklist before launch and after any meaningful change to the model, system prompt, retrieval index, document source, tool list, identity system, output format, or fallback behavior. Revisit it before seasonal planning cycles or other periods when data, permissions, traffic, and workflows change.
Schedule a lighter review whenever a new prompt version is deployed. At minimum, rerun high-severity cases, tool-authorization tests, sensitive-data tests, and representative multi-turn attacks. Review failures with both the application owner and the security or platform owner; prompt fixes and code fixes often need to be coordinated.
When an incident occurs, use this response sequence:
- Pause or restrict the affected tool, data source, or workflow if unauthorized action may still be possible.
- Preserve the relevant prompt, retrieved documents, tool traces, model configuration, and timestamps.
- Determine whether the issue caused disclosure, unauthorized access, external side effects, or only an incorrect response.
- Rotate exposed credentials and review access logs when secrets or privileged systems may be involved.
- Apply a layered fix: narrow permissions, improve input handling, clarify prompt boundaries, and add the attack to regression tests.
- Re-run the case against the affected configuration and document the residual risk before restoring normal operation.
Prompt injection defense is an ongoing prompt engineering and application-security practice. Keep the checklist beside your release process, maintain versioned evidence, and treat every new input, retrieval source, and tool permission as a reason to test again.