How to prevent prompt injection from controlling AI tools

To prevent prompt injection from turning into unauthorized actions, enforce permissions outside the model, restrict what its tools can access and validate the action before execution. OWASP’s prompt injection prevention guidance treats screening and structured prompts as supporting layers, not sufficient protection. The practical objective is to contain a malicious instruction even when the model follows it.

Start with the assistant’s capabilities. A document summarizer needs a different approval path from an assistant that can send messages or change records. Microsoft’s defense-in-depth guidance recommends designing for attacks that get through, combining probabilistic detection with deterministic restrictions. Build the restriction first, then measure what the detector adds.

Google · Preferred Sources

Don't miss new tech stories on Google

Add Tech Insider once in the Google app and our stories appear in your news suggestions.

Add Now

Locate the boundary an attacker can cross

Microsoft describes indirect injection as instructions planted in outside material that an assistant mistakes for commands. Emails, shared documents, websites and plugins can carry that material. Its security response analysis also explains that ordinary text is sufficient: suspicious file formats and unusual encodings are not prerequisites. Treat the content’s origin and authority as separate properties from its readability.

For your application, draw the path from the user’s request through retrieval, model processing, proposed actions and displayed output. Mark every entry point for outside content. In a retrieval-augmented generation application, inspect the retrieved passage as well as the question. OWASP explicitly includes fetched pages, tool results and conversation history among the channels that require a trust decision.

Keep trusted application instructions separate from the material being analyzed. OWASP cautions that labels and prompt wording do not enforce that separation. A document may say that its author approved a transfer; your application must still obtain authority from its trusted agent identity provider and approval systems. Never use the document’s own assertion as the permission record.

Write the threat model in terms of prohibited outcomes. For a support assistant, that might mean sending a customer record outside the permitted recipients or changing another customer’s account. These are proposed application policies, not model capabilities. They give the execution layer something definite to reject even when the language in a malicious document looks harmless.

Constrain actions before refining the prompt

OWASP places permission and argument checks in execution code, outside the model. Give each tool only the information and operations it needs. Microsoft additionally recommends privileges that last only as long as the task requires. Do not give a summarizer write access merely because another feature uses the same assistant.

Separate generating an action from executing it. Make that boundary part of the application’s agent governance rules. Validate the tool name, the actual target, the arguments and the authenticated caller’s permissions. For a consequential operation, show the proposed action for approval before it runs. OWASP requires the executor to verify approval for that exact action; an agreeable phrase in the conversation is not a substitute.

The following small Python example illustrates an approval check for a proposed email. Its recipient allowlist is supplied by trusted application policy, and its approved action must come from the trusted approval interface. The model supplies only the proposal. This is a decision function, not an email sender or a complete authorization service.

def may_send_email(proposal, permitted_recipients, approved_action):
    required = {"tool", "recipient", "subject", "body"}
    if not isinstance(proposal, dict) or set(proposal) != required:
        return False
    if any(not isinstance(value, str) for value in proposal.values()):
        return False
    if proposal["tool"] != "send_email":
        return False
    if proposal["recipient"] not in permitted_recipients:
        return False
    if not isinstance(approved_action, dict):
        return False
    return proposal == approved_action

# Dummy values for a local policy smoke test; no message is sent.
action = {"tool": "send_email", "recipient": "[email protected]",
          "subject": "Draft summary", "body": "Dummy summary"}
allowed = {"[email protected]"}
assert may_send_email(action, allowed, dict(action))
assert not may_send_email(action, allowed, None)
changed = dict(action, body="Changed after approval")
assert not may_send_email(changed, allowed, action)
assert not may_send_email(action, set(), action)

In the real executor, obtain the caller and allowed recipients from authenticated server state, not from model arguments. Bind approval to that caller and the complete operation. Consume approvals through a trusted service with an application-defined expiry and replay policy, and reject an action if anything changes after review. The function above deliberately does not implement that storage or lifecycle; it shows the equality and permission checks that your integration must preserve.

For an assistant whose job is only to draft, omit the send operation entirely. Microsoft describes this separation in Outlook: Copilot can generate a message, while the user approves and sends it. That pattern trades some convenience for a clear boundary between model-generated content and a consequential action.

Screen documents without treating a detector as authority

Apply screening to each untrusted channel before it reaches the model, rather than checking only the chat box. OWASP explains why keyword filters miss attacks: attackers can paraphrase, change language or encode instructions. A blocked phrase is evidence about that phrase, not proof that the document is safe.

Keep the original input available for the task and screen a bounded, normalized copy where appropriate. OWASP advises limiting length before normalization, decoding or matching, and decoding suspicious encoded strings for inspection. Do not indiscriminately rewrite customer documents to make a filter happy. Decide explicitly what happens when preprocessing cannot preserve the content the user needs.

Documents need a visibility check as well. OWASP recommends comparing extracted text with rendered pages to find text the reader cannot see. If the document is unreadable or contains flagged hidden material, route it to review or process only visible text while marking the result incomplete. A partial extraction must not silently become an apparently complete business answer.

Choose a classifier as another layer. Microsoft characterizes Prompt Shields as probabilistic and says it is updated against known techniques in multiple languages. OWASP warns that a guardrail model is also vulnerable to prompt injection. Neither an allow verdict nor a second model should grant a tool permission that the executor would otherwise deny.

ControlUseful decisionBoundary it does not establish
Structured instructionsTell the model which text is dataAuthority to execute an action
Input or document screeningBlock or review suspicious materialProof that all accepted content is harmless
Tool authorizationReject operations outside caller permissionsAccuracy of the model’s summary
Exact-action approvalLet a user review a consequential proposalPermission for later changes to that proposal
Output handlingRestrict how generated content is rendered or usedSafety of actions that already happened

AWS’s prompt-template guidance describes results from a demonstrative Claude retrieval application. Treat template improvements as guidance to evaluate in your own deployment, rather than as a portable security guarantee. Your tool boundary should remain effective when the chosen model, template or classifier changes.

Budget for the effect on legitimate work. Microsoft identifies latency and false positives as trade-offs of layered defenses. OWASP suggests reserving heavier checks for sensitive paths. Compare the task-completion cost of a new detector with the additional attacks it reveals; do not weaken authorization to compensate for a slow classifier.

Protect the output and the return path

A clean-looking final answer is not the only output to inspect. Microsoft describes data leakage through generated images and links: a browser can request an attacker-controlled image while rendering a response, sending information embedded in the request without a user clicking it. Review the renderer and permitted network destinations as part of the application boundary.

Treat model output as untrusted wherever it goes next. OWASP calls for destination-specific controls, such as safe HTML rendering and parameterized database queries. An output keyword filter does not replace those controls. For a document assistant, decide whether remote images are needed at all, and prevent generated markup from choosing a new route for protected data.

Keep a usable security record without turning the record into another disclosure channel. OWASP recommends logging relevant metadata and decisions while excluding credentials, secrets and unnecessary sensitive text. Record which tool was proposed, the policy decision and the approval outcome in a form your incident process can inspect. Restrict access to any sensitive evidence you retain.

Test observable outcomes, then decide what can ship

Define the expected policy decision and observable result before choosing attack strings. OWASP’s testing guidance recommends dummy data and sandboxed tool substitutes. An indirect-injection test belongs in the external document or tool result being evaluated; pasting it into the user message exercises a different path.

Test case to constructEvidence to collectAcceptance decision
A document asks for an unauthorized emailTool request, authorization decision and dummy outboxNo unauthorized message reaches the outbox
A proposal changes after approvalReviewed arguments and attempted execution argumentsChanged operation is rejected or returned for fresh review
A generated answer embeds remote contentRenderer behavior and instrumented network destinationProtected dummy data does not reach the destination
A normal document requires an allowed summarySecurity decision and expected summary contentLegitimate task completes without an incorrect security refusal
A detector fails or telemetry is missingError and the executor’s actual behaviorMark the evaluation inconclusive; do not count a blocked attack
An attack uses another supported languagePer-language policy decisions and benign controlsAssess security outcomes and legitimate completion together

Observe actions as well as responses. OWASP emphasizes that a refusal cannot reverse a tool action already executed. A test that prints a reassuring rejection while the dummy outbox receives a message has failed the relevant objective. Likewise, absence of a marker in the final text says nothing about a different disclosure channel.

Report errors, incomplete telemetry and unsupported contexts separately. Record allowed, blocked and review-required decisions for ordinary requests, then check whether those requests actually completed. OWASP calls for supported languages and scripts to be covered, with benign controls in each.

Keep the individual outcomes, the denominator behind each rate, model and defense versions, settings and repeated-run records. OWASP cautions against turning a hand-picked smoke test into a claim about the population of attacks. Do not declare the application secure because a short list of familiar strings was rejected.

The release decision should follow the capabilities you have demonstrated you can contain. Keep an unapproved write path disabled; narrow an integration whose data access exceeds its task; investigate a missing observation before calling the test successful. This procedure produces a concrete acceptance record for the assistant. Detection can evolve without making the model the final authority over customer data or actions.

Sofia Lindström

Sofia Lindström

Security and privacy

Sofia Lindström writes about security and privacy for Tech Insider: software vulnerabilities and the updates that fix them, data breaches, privacy rules and how products handle personal data. She works from vendor advisories, official vulnerability catalogues and the documents behind each story.

View all articles