SECURITY & COMPLIANCE18 min read

Prompt Injection in AI Agents: Security Setup

A practical security setup for isolating agent tools, containing untrusted content and limiting data exfiltration.

P
PADISO teamPublished 28 Nov 2026

Prompt injection in ai agents is a security problem because an agent can turn malicious instructions in an email, web page or document into tool actions. You cannot solve it with a stronger system prompt alone. You need controls outside the model that limit what it can read, which actions it can take and where data can go.

This guide gives you a step-by-step setup for production systems. It draws on the OWASP guidance on prompt injection, the Australian Cyber Security Centre guidance on agentic AI services, and patterns we use when designing AI agents and automation. The aim is not to make a model perfectly resistant. It is to make a successful attack less able to cause harm.

What prompt injection in AI agents can do

Prompt injection happens when content supplied to an AI system contains instructions intended to change how it behaves. A direct attack comes from a user who asks the model to ignore its rules. An indirect attack hides instructions in content the model is asked to process, such as an email, an uploaded file, a retrieved knowledge-base passage or a web page.

In an agent, the model may have tools. It could search files, update a customer record, send email, run code or call an internal API. If hostile content changes the agent's decisions, the result may be an unauthorised action rather than an inappropriate answer. OWASP identifies prompt injection as a key risk for large language model applications, including systems that use external content and tools, as detailed in frameworks assessing the OWASP Top 10 for LLMs.

This creates a confused-deputy problem, particularly evident in action-capable copilot and agent architectures. A deputy is a system with legitimate authority that is tricked into using that authority for someone else's purpose. The agent's credentials may be valid, but the action may not be authorised by the user, the organisation or the policy that should govern the task. The ACSC's joint guidance on agentic AI adoption emphasises controlling agent authority and keeping security decisions outside the agent's own reasoning.

A secure design assumes that any untrusted content might contain an attack. It also assumes a classifier, model or prompt may miss one. The design question is therefore not just, “Can the model detect this text?” It is, “If the model follows it, what can it reach, change, send or remember?”

What do you need before you change the agent?

Start with an inventory, not a new prompt. Record the agent's business purpose, the data it can access, the tools it can call, the identities it uses, the external content it processes and the side effects it can trigger. Include supporting systems such as retrieval indexes, memory stores, MCP servers, logs and scheduled jobs.

For each tool, identify its owner and the consequences of misuse. A read-only search tool has a different risk from a tool that can send a customer email or change permissions. “Internal” does not mean safe: an internal API can still expose sensitive data or make a consequential change.

Before implementation, make these decisions:

  • Which actions can the agent perform without approval?
  • Which actions need a person to approve them, and through which independent channel?
  • Which data classes may the agent read, and which may it return?
  • Which network destinations must it contact to do its job?
  • How will you revoke its access, stop a running task and investigate an incident?
  • Where can you test safely with synthetic data and non-production credentials?

Document the intended boundary for each action. For example, an agent might draft an email but not send it, search a defined set of documents but not browse the wider drive, or prepare an account update but require a person to commit it. These boundaries will become testable policy, not merely text in the system prompt.

If your team is still deciding whether to build an agent or how much authority to give it, start with a scoped AI strategy and solutioning assessment. The security design should follow the business task, data sensitivity and acceptable risk, not the other way around.

Step 1: Map trust boundaries and reduce the agent's job

Draw the path from input to action, applying established principles of AI agent security to isolate components. Include the user interface, model, retrieval system, agent runtime, tools, identity provider, network egress and people who approve actions. Mark every place where data crosses from a less trusted area to a more trusted one.

Typical untrusted inputs include:

  • Email and chat messages from outside the organisation.
  • Uploaded documents, spreadsheets, PDFs and code repositories.
  • Web pages, search results and vendor documentation.
  • Retrieved passages whose authorship or integrity is uncertain.
  • Tool outputs that contain text originally supplied by an external user.
  • Long-term memory written by previous sessions or workflows.

Treat tool output as untrusted unless its source and meaning are controlled. A database result may include a user-entered field. A ticketing API response can contain an attacker-authored description. Putting such text inside a trusted-looking JSON object does not make it trustworthy.

Then remove capabilities the agent does not need. An agent that summarises invoices might need read access to a designated folder and a way to return a draft summary. It probably does not need a shell, arbitrary web access, permission to send email or access to every shared drive. Start with no permissions and add a specific capability only when the task requires it.

Write down the allowed workflow in plain language and as a system boundary. Specify permitted inputs, tools, data, destinations and actions. Split separate jobs into separate agents or workflows when they need different authority. A single general-purpose agent with access to many tools is harder to constrain and audit than a narrow agent with a small, clear task.

Tip: Build a tool inventory with fields for tool name, purpose, read or write access, data scope, identity, network destination, approval requirement and owner. Use it as the basis for reviews and tests.

Mistake to avoid: Do not grant broad access because the model might need it later. “Just in case” privileges make an injection more consequential and make it harder to explain what the agent is allowed to do.

Step 2: Separate untrusted reading from privileged tool use

A useful design pattern is the dual-LLM pattern described by Simon Willison. It separates the model that reads hostile material from the component that can take actions. The first model has no tools and no network access. It reads the source and returns a constrained representation. The privileged planner receives only the representation it needs, not the raw document.

For example, a document-reading component could return fields such as supplier name, invoice date, amount, currency and a short factual summary. It should not be able to send payments or update the accounting system. A separate workflow can check those fields against business rules and present a proposed action for approval.

A practical pipeline looks like this:

  1. Fetch external content in a restricted ingestion service.
  2. Remove or flag content that is not required for the task.
  3. Send the remaining content to a reader with no tools, no secrets and no outbound network access.
  4. Require the reader to return a strict schema, such as a JSON object with known fields and types.
  5. Validate the structure, field lengths, allowed values and source references in ordinary application code.
  6. Pass validated fields to the planner or business workflow, not the original content.
  7. Have an independent policy service decide whether a proposed action is allowed.

The separation is about capabilities, not just using two model calls. If the reader and planner share the same broad credentials, tools or writable memory, the boundary is weak. Ideally they run with separate identities and network policies. The reader should not be able to reach the execution service, and the planner should not retrieve the raw untrusted document as a convenient fallback.

Structured output reduces the space in which instructions can travel, but it does not prove that the information is safe. A malicious document might cause the reader to put attacker-controlled text in a summary field. Restrict free-text fields, impose length limits and validate values against trusted sources where possible. For high-impact actions, require a human to inspect the source or a clear evidence trail.

Use a single model with tools only if the business case justifies the residual risk and you have strong external controls. A dual-model pattern is not a guarantee against prompt injection. It is a way to reduce direct exposure of the action-taking component to raw hostile instructions.

Step 3: Put authorisation outside the model

The model may suggest a tool call. It must not be the authority that decides whether the call is permitted. Enforce authorisation in the application layer, API gateway or a separate policy decision point. A policy decision point evaluates whether an action is allowed. A policy enforcement point blocks or permits the actual request.

For every tool call, check at least:

  • Identity: Which user or workload identity is acting?
  • Action: Is this a read, create, update, delete, send or execute operation?
  • Resource: Which exact record, file, account or service is affected?
  • Scope: Is the resource within the task's allowed boundary?
  • Context: Is the request expected for this workflow and session?
  • Approval: Is an independent approval required before execution?

Validate tool parameters against a strict schema. Reject unknown fields, unsupported operations, unexpected recipients, out-of-scope record identifiers and malformed values. Where possible, give the tool a narrow operation such as “read invoice status” rather than a general-purpose database query or shell command. Use allowlisted values and resource identifiers instead of letting the model construct arbitrary commands.

The tool should check policy again when it receives the request. Do not assume that a check made earlier in the conversation still applies after the agent has read new content or changed tasks. Bind authorisation to the actual action, resource and session. If a user changes scope or a workflow changes identity, re-evaluate permission.

For example, a support agent might be allowed to draft a response for a ticket assigned to the current team. The gateway should verify the ticket ID and team assignment before returning data. A separate send operation should check the recipient and require approval if the message goes outside the organisation. A prompt instruction such as “only send approved messages” is not a substitute for those checks.

For systems built with MCP servers, review the client, server and each exposed tool as separate trust boundaries. Do not give a local MCP process administrator or shell access by default. Scope tokens to the session and required operations, validate JSON-RPC payloads, and run local servers in isolated environments. The agent should not be able to use a tool to escape the intended boundary and gain broader access to the host.

Tip: Keep the policy decision and enforcement logs. Record the requesting identity, proposed operation, resource, policy result, approval and final outcome. Avoid logging secrets or unnecessary sensitive content.

Mistake to avoid: Do not make a tool an unrestricted proxy to an internal API. If the agent can pass through arbitrary paths, query strings or commands, your policy layer may only be cosmetic.

Step 4: Contain untrusted content in the context

A language model processes instructions and data within the same context window. There is no hardware-style wall between the system prompt and text copied from an email. Delimiters and labelling help the model understand the source, but they do not create a security boundary on their own.

Keep the system instructions separate from user and retrieved content in the application representation. Label untrusted sections clearly and tell the model to treat them as data to analyse, not instructions to follow. Some implementations use unique XML-style tags around retrieved passages. This can improve clarity, but attackers may still write text that conflicts with the instruction. Never rely on tags as the only protection.

Before content enters a prompt, use ordinary code to apply controls appropriate to its type:

  • Normalise Unicode and remove control characters that are not needed.
  • Detect or flag hidden text, such as visually concealed content in HTML or documents.
  • Escape or remove markup that could be interpreted by downstream renderers.
  • Enforce size limits and discard irrelevant sections where possible.
  • Preserve source identifiers so you can trace a claim back to its origin.
  • Separate fields by provenance, such as user input, retrieved text and trusted application metadata.

Be careful with “sanitisation”. Removing suspicious phrases cannot reliably make a document safe. Attackers can reword instructions, split them across passages or hide them in formats that your parser does not understand. Sanitisation should reduce avoidable ambiguity and rendering risks. The core controls remain limited capabilities, policy enforcement and restricted egress.

If you retrieve content from a vector database, preserve provenance and access controls. Do not retrieve a document simply because it is semantically similar if the requesting user cannot access it. Keep retrieved text bounded to the task, and avoid passing entire documents when selected passages are sufficient. Treat content from previous agent turns as untrusted too, especially if it was derived from external sources.

Tip: Test the entire path from file ingestion to retrieval to model prompt. Hidden characters may be removed by one component but reintroduced by another conversion or extraction step.

Mistake to avoid: Do not assume that an antivirus scan or a prompt-injection classifier makes retrieved content trustworthy. A detector can flag known patterns, but the agent still needs to be safe when the detector misses an attack.

Step 5: Limit where the agent can send data

Data exfiltration means moving information to a place where it should not go. The obvious path is an agent with unrestricted internet access. Less obvious paths include a webhook tool, a shared storage bucket, an external email, an internal service that syncs elsewhere, a rendered image URL or a memory store that another workflow later reads.

Apply network egress controls outside the model runtime. Deny outbound connections by default, then allow only the destinations and ports required for the task. Where practical, route calls through an egress proxy that checks hostnames, records destinations and blocks unknown targets. Do not let a model create a URL and have the runtime fetch it without validation.

Review every tool as a possible egress channel. A “write note” operation may write to a shared location. A document export might expose content to a third-party service. A search tool may allow crafted queries to leak data. Restrict the data fields each tool returns and the places it can write. Apply data loss prevention rules at the API gateway or destination where possible.

Treat output rendering as part of the security boundary. If an agent response is displayed as Markdown or HTML, escape or remove active content that could make the browser contact an external host. In particular, validate links and do not allow untrusted output to trigger background requests or embedded content automatically. If the user needs to follow a link, show it safely and make the destination clear.

Never place raw API keys, database passwords or long-lived credentials in model context. Use a gateway or tool service to hold credentials and make calls on the agent's behalf. Give each workload an identity with the minimum permissions required, use short-lived or session-scoped tokens where supported, and revoke them when a session ends or an incident occurs.

If the agent has no direct internet access, do not assume exfiltration is impossible. An attacker may still exploit an allowed internal tool, shared drive, email integration or memory store as a path to move or stage data. Test the actual set of channels available to the agent, including indirect ones.

Step 6: Make consequential actions pause for approval

Require human approval before actions that are difficult to reverse or have material impact. Examples include sending messages to external recipients, changing access rights, deleting records, moving funds, publishing content and making changes to production systems.

The approval should happen outside the model's control. The agent can prepare a proposed action and explain its evidence. A person should receive a clear summary of what will happen, which records or recipients are affected, what data will be shared and why the action is being proposed. The approval interface should let the person reject or modify it, and the system should enforce that decision before the tool executes.

Avoid approval prompts that ask only, “Proceed?” Show the specific action and destination. If the agent's proposal changes after approval, require a new approval. Bind the approval to the exact payload, identity and expiry so it cannot be reused for a different request.

Use risk-based approval rather than asking a person to approve every harmless step. Excessive interruptions encourage people to approve mechanically. Keep low-risk, reversible actions within a defined scope, and escalate when an action crosses a threshold or involves a sensitive resource. Record both the approval and the final execution result.

For Australian financial institutions, map these controls into existing information-security and operational-risk processes rather than treating agent security as a separate policy island. Review APRA's CPS 234 information security standard alongside our guidance on APRA CPS 234 AI controls, and assess the agent, its providers and its dependencies against the organisation's obligations. Confirm applicable notification, third-party and resilience requirements with your compliance and legal teams. Do not treat a general AI control checklist as a substitute for interpreting the standards that apply to your organisation.

Step 7: Protect memory and session state

Long-term memory can turn a one-time injection into a persistent problem. A malicious document might persuade an agent to save an instruction or preference that changes later behaviour. Johann Rehberger's research, tracked in discussions around prompt injection vulnerabilities and persistent memory exploits and SpAIware and persistent memory injection, describes how attacker-controlled content can affect stored state. Understanding these attack paths requires clear agent memory forensics to identify how state corruption propagates across sessions.

Treat memory writes as privileged actions. Define which fields the agent may store, who can change them, how long they persist and which workflows can read them. Prefer structured facts with a source and timestamp over free-form instructions. Separate user preferences from system policy, and never let a memory entry override authorisation rules.

Apply these controls:

  • Do not write arbitrary text from an external document directly into persistent memory.
  • Validate memory updates against an explicit schema and allowed field list.
  • Keep provenance, including the source and identity that created the entry.
  • Require approval for changes to sensitive profile or workflow settings.
  • Scope memory by user, tenant and purpose, and enforce access checks on reads.
  • Provide a way to inspect, correct and delete stored memory.
  • Expire or revalidate information when its purpose or source is no longer valid.

Keep session state isolated where practical. A user should not inherit another user's conversation, tool results or memory simply because the application reuses a runtime. At the end of a session, revoke temporary credentials and clear state that is not meant to persist.

Step 8: Test the system as an attacker would

A secure design needs repeatable tests. Reference practical technical guides covering prompt injection attacks and defenses to structure realistic scenarios. Build a test set from the inputs the agent actually processes: email, tickets, retrieved documents, webpages, code, file attachments and tool responses. Include direct instructions, indirect instructions, hidden text, attempts to change the task, requests to reveal secrets, requests to call tools and attempts to write persistent memory.

Test the controls as well as the model's response. For each case, ask:

  • Did the agent identify or ignore the injected instruction?
  • Did any unauthorised tool call reach the gateway?
  • Did the gateway deny the call for the right reason?
  • Could the agent send data to an unapproved destination?
  • Did the output renderer make an external request?
  • Was sensitive information included in a log, response or memory entry?
  • Could a user or workflow read data outside its access scope?
  • Did a human approval bind to the exact action that was executed?

Use harmless synthetic secrets and non-production tools. For example, seed a test document with a fake credential and an instruction to include it in an email to a controlled test recipient. The expected result is not merely that the model says no. The system should lack a permitted route to send the secret, the policy gateway should deny out-of-scope actions, and logs should show the attempted action without exposing the credential.

Test multi-step attacks too. An agent may fail to execute a suspicious request immediately but store it in memory, pass it to another agent or use a sequence of low-risk calls to reach the same result. Include tool outputs and retrieved passages in the test set because the attack may arrive through a source that your team considers internal.

A classifier or guardrail can add a useful detection layer. For example, AWS Bedrock Guardrails documentation describes configurable controls for model inputs and outputs. Use such capabilities according to the current product documentation and test them against your own attack cases. A detector can reduce exposure or provide a signal for review, but it should not replace isolation, least privilege or policy enforcement.

Run tests after changes to prompts, models, tools, retrieval logic, identity configuration, renderers and memory handling. Keep a record of the test version, expected outcome, observed result and remediation. Track blocked policy violations as well as successful model responses. A model can appear helpful in a demo while the execution boundary is still too permissive.

A practical rollout checklist

Use this checklist before connecting an agent to production data or actions.

Control area Minimum setup Evidence to keep
Scope One defined job, minimal data and a named owner Approved use case and data map
Tools Narrow operations, strict schemas and no default admin access Tool inventory and permission review
Identity Separate workload identity and least-privilege access Token scope and access logs
Untrusted content Provenance labels, bounded context and safe parsing Ingestion tests and source traceability
Policy Independent checks for each consequential tool call Policy rules and deny logs
Egress Default deny with explicit destinations Firewall or proxy configuration and tests
Output Escaped rendering and validated links Rendering tests
Human review Approval for high-impact or irreversible actions Approval record tied to action payload
Memory Schema-constrained writes and access controls Memory policy and lifecycle tests
Operations Monitoring, stop procedure and incident owner Runbook, alerts and exercise results

Treat each row as a launch gate, not a one-off form. If a control is not in place, reduce the agent's authority until it is. Start with read-only or draft-only workflows, observe where they fail, and expand capability in measured steps after the controls and tests pass.

Common security mistakes to avoid

Relying on a stronger system prompt. Clear instructions help, but the model reads hostile instructions in the same context. A prompt cannot replace a permission check in code.

Giving the agent a shared administrator identity. Broad credentials increase the consequences of a compromised workflow and make it harder to determine which user authorised an action. Use a distinct identity with narrow permissions.

Treating retrieved text as trusted because it came from an internal system. Internal records can contain external submissions, copied messages or stale content. Track provenance and enforce the user's access rights at retrieval time.

Trusting JSON as a security boundary. A schema can restrict shape, not guarantee truth or intent. Validate values, restrict free text and check the source before a consequential action.

Allowing unrestricted network access for convenience. An agent does not need general internet access merely because one tool calls a third-party service. Route necessary calls through an allowlisted gateway.

Approving vague actions. A person cannot make an informed decision if the approval screen hides the recipient, resource or payload. Show exactly what will happen and require renewed approval if the action changes.

Stopping at a successful demo. Demo content rarely represents the full range of hostile inputs, permission boundaries or side effects in production. Test the deployed path, including the tools, identity, network and memory systems around the model.

Where PADISO fits

PADISO helps teams design and build agent workflows with clear tool boundaries, external policy enforcement, identity controls and production testing. Our AI automation team can review the agent architecture, while our platform engineering team can help implement the runtime, integration and operating controls.

Wrap-up: make the boundary enforceable

Prompt injection is difficult to prevent reliably at the language level. Make the system safe by limiting the agent's authority, keeping raw hostile content away from privileged execution where possible, and enforcing every important decision outside the model. Then test what happens when detection fails.

Your next step is to map one agent's tools, data and outbound paths, then identify the highest-impact action it can take. If you want help turning that map into an implementation plan, talk to PADISO about securing your AI agent.

WANT TO TALK THROUGH YOUR SITUATION?

Talk it through with us. Thirty minutes, no slides.

P
Written by the PADISO TeamSydney-based technology leaders who build what they advise on. Seven years of fractional CTO, architecture and AI work for enterprise, government and private equity.

Keep reading

All posts →

Let's talk.

Tell us what you are weighing up, whether it is a build, a roadmap or a deal. You will leave the call knowing your next step.

Book a 30-min callhi@padiso.co