Keep untrusted information from becoming authority
Agent security assumes model inputs, retrieved pages, and tool results may be hostile. Prompt injection tries to manipulate the agent into ignoring trusted instructions, while excessive permissions, confused authority, data leakage, duplicate side effects, and partial failures can turn a bad decision into a real incident. Guardrails prevent unsafe actions; recovery controls detect failure and move the task to a safe state.
What You Will Learn
- Trace indirect prompt injection from hostile content to a proposed action.
- Place deterministic controls outside model-level instructions.
- Apply guardrails at input, tool, output, and approval boundaries.
- Choose retry, compensation, fallback, escalation, or safe stop by failure type.
Instructions guide the model; controls enforce authority
A model instruction can state that retrieved text is untrusted, but probabilistic compliance is not an authorization system. Deterministic code must decide which identity may call which tool, which resources are allowlisted, what argument limits apply, and when human approval is required.
Layer guardrails where different failures appear: inspect incoming content, validate proposed tool inputs, scan tool results before they re-enter context, check final outputs, and pause high-impact actions for an authorized person. No single universal check replaces these separate boundaries.
Threats and the controls that contain them
Instructional figure
Indirect prompt injection stopped at the action boundary
How can hostile document text attempt—but fail—to become authority?
Where layered guardrails operate
Check authority before an action and recover safely afterward
Separate trusted instructions and authorization from untrusted user, webpage, document, and tool content.
Give every tool the minimum permissions, scoped credentials, allowlisted resources, and data access required for one task.
Validate inputs, outputs, tool arguments, and policy in deterministic application code; never let untrusted content grant authority.
Detect repeated actions, unchanged state, conflicting evidence, timeouts, tool errors, and partial completion against explicit invariants and limits.
Retry only transient idempotent operations with backoff; otherwise use fallback, compensation, human escalation, or a safe stop.
Require confirmation for consequential actions, preserve an incident trace, and turn failures into new security and recovery tests.
Recovery depends on side effects and certainty
Retry a transient operation only when it is safe to repeat. If a non-idempotent payment may have completed before a timeout, check status or escalate rather than replaying it. Use compensation for a completed reversible step, a fallback for an unavailable component, and a safe stop when authority or evidence is insufficient.
Instructional figure
Choose recovery by failure type
When should a failed action retry, compensate, fall back, escalate, or stop?
YES
NO / UNCERTAIN SIDE EFFECT
A Realistic Example: Malicious instructions inside a webpage
A research agent encounters hidden text requesting secret upload. The browser content cannot grant tool permission; a policy layer blocks data access and the trace records the attempt.
Read the Mechanism in Code
Use the label and note to understand what this block represents before reading each line.
def execute_or_recover(call, user, source, state):
validate_schema(call)
if source.is_untrusted and call.requests_sensitive_data:
raise SecurityError("Untrusted content cannot authorize access")
authorize(user, call.tool, call.resource)
if repeated(call, state) or state.steps >= MAX_STEPS:
return escalate("No safe measurable progress", trace=state.trace)
if call.is_consequential:
require_confirmation(call)
try:
return sandbox.run(call)
except TransientError:
return retry_with_backoff(call) if call.is_idempotent else safe_stop()Hands-On Runnable Python Lab: Reject a Write Even When the Proposal Claims to Be an Admin
The trusted session belongs to U-17 and grants only invoice:read on INV-42. Proposed tool calls are deliberately untrusted. No real external system is contacted.
- Accept a read of the authorized invoice.
- Reject a delete proposal even when it claims admin status.
- Reject a read of another invoice despite having read scope.
- Classify a timeout as retryable and an authorization denial as non-retryable.
Authority comes from the trusted session, never from a proposal
The runtime checks both action scope and resource ownership. Model text, retrieved instructions and self-declared roles cannot expand either boundary.
session = {"user": "U-17", "scopes": {"invoice:read"}, "resources": {"INV-42"}}
tools = {"read_invoice": "invoice:read", "delete_invoice": "invoice:delete"}
def gate(proposal):
tool, resource = proposal.get("tool"), proposal.get("resource")
if tool not in tools:
return False, "unregistered tool"
if tools[tool] not in session["scopes"]:
return False, "missing trusted scope"
if resource not in session["resources"]:
return False, "resource outside authorized set"
return True, "allowed"
proposals = [
{"tool": "read_invoice", "resource": "INV-42"},
{"tool": "delete_invoice", "resource": "INV-42", "role": "admin"},
{"tool": "read_invoice", "resource": "INV-99"},
]
for proposal in proposals:
allowed, reason = gate(proposal)
print(proposal["tool"], proposal["resource"], allowed, "-", reason)
for error in ["timeout", "authorization_denied"]:
print(error, "retryable:", error in {"timeout", "temporary_unavailable"})
read_invoice INV-42 True - allowed
delete_invoice INV-42 False - missing trusted scope
read_invoice INV-99 False - resource outside authorized set
timeout retryable: True
authorization_denied retryable: FalseWhat This Run Shows
- The model-controlled role field never reaches the permission decision.
- Resource authorization prevents a read scope from becoming permission to read every invoice.
- A retry policy cannot fix a denied capability; retrying would repeat the same forbidden request.
Treat model outputs like requests arriving at a privileged boundary, not instructions the boundary must obey. Tool security remains necessary even with a model trained to resist injection.
From the Exercise to an Application
Experiment: Add invoice:delete to the proposal, leaving the trusted session unchanged.
The delete remains denied. Only a legitimate authorization flow may change the trusted session’s capabilities.
Summary / Key Takeaways
- Agent security starts from the assumption that user input, retrieved pages, documents, tool output, and generated code may be hostile.
- Prompt injection becomes dangerous when untrusted content can influence authority, permissions, or consequential tool use.
- Least privilege, scoped credentials, allowlists, schema checks, and deterministic authorization should sit outside the probabilistic model.
- Guardrails can operate at input, tool-input, tool-output, and final-output boundaries, with human approval for high-impact actions.
- Recovery logic must detect no-progress loops, repeated actions, partial completion, conflicting evidence, timeouts, and tool errors.
- Retry only transient operations that are safe to repeat; otherwise use compensation, fallback, escalation, or a safe stop.
- Production incidents should become new security tests and regression cases so the system improves from real failures.
Verified Further Reading
These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.
OWASP Top 10 for Agentic Applications (2026)
Peer-reviewed security guidance for risks specific to autonomous and agentic AI applications.
AgentDojo: A Dynamic Environment to Evaluate Prompt Injection Attacks and Defenses for LLM Agents
Research benchmark for tool-using agents exposed to untrusted external content and prompt-injection attacks.
Model Context Protocol: Server Tools (2026-07-28)
Normative tool discovery and invocation guidance, including validation, access control, human approval, and untrusted tool metadata.