OWASP Top 10 for LLMs: Hardening AI Agents Against Prompt Injection and Exfiltration
Practical AppSec engineering for production AI agents: defending against direct and indirect prompt injection, enforcing least-privilege tool calling, structured output validation, and full audit trails.
The moment you wire a large language model to real tools—SQL queries, CRM APIs, outbound email, or order creation—you are no longer running a text generator; you are operating a probabilistic interpreter with side effects. The OWASP Top 10 for LLM Applications maps the exact failure modes that surface in production: Prompt Injection (LLM01), Sensitive Information Disclosure (LLM02), Improper Output Handling (LLM05), and Excessive Agency (LLM06).
Because language models cannot natively distinguish trusted system instructions from untrusted user text or retrieved RAG documents, prompt-only defenses inevitably fail. In this note, I document the deterministic security boundaries we build around production AI agents at Artag Dev to enforce least privilege, stop data exfiltration, and keep every tool call auditable.
Direct vs. indirect prompt injection—and why prompt-only defenses fail
Direct prompt injection happens when a user attempts to override system rules directly in chat. Indirect prompt injection is subtler and far more dangerous: an attacker hides adversarial instructions inside a PDF, web page, or product description indexed by your RAG pipeline. When the agent retrieves that chunk, the model may follow the embedded instruction as if it came from your backend.
No system prompt provides a mathematical security guarantee against injection. Therefore, we treat the LLM as untrusted compute enclosed inside deterministic boundaries: explicit data delimiters for external text, server-enforced authorization outside the model, and strict validation on every tool input and model output.
- Structural delimiting: wrap external content (RAG chunks, user messages) inside explicit untrusted-data blocks.
- Input hygiene: normalize invisible Unicode control characters, cap input length, and screen known exfiltration payloads ahead of inference.
- Assume compromise: design tool permissions and database RLS so that even a fully hijacked prompt cannot cross tenant boundaries or execute destructive actions.
Controlling Excessive Agency (OWASP LLM06) with least-privilege tool calling
The strongest defense against a hijacked agent is restricting what tools exist and which arguments the model is allowed to supply. We never expose `tenantId`, `userId`, `role`, or raw SQL strings in an LLM tool's JSON Schema. Those identity attributes are injected strictly from the authenticated server session context.
We also tier every tool by blast radius: scoped `read`, reversible `write_safe`, and high-impact `write_critical` (refunds, permission changes, bulk outbound messages). High-impact tools never auto-execute; they return a structured proposal requiring explicit out-of-band human approval.
import { z } from "zod";
export type ToolRiskLevel = "read" | "write_safe" | "write_critical";
export interface AuthContext {
tenantId: string;
userId: string;
allowedTools: ReadonlySet<string>;
}
export interface SafeToolDefinition<TInput extends z.ZodTypeAny> {
name: string;
risk: ToolRiskLevel;
schema: TInput;
execute: (args: z.infer<TInput>, ctx: AuthContext) => Promise<unknown>;
}
export async function invokeToolSafely<TInput extends z.ZodTypeAny>(
tool: SafeToolDefinition<TInput>,
rawArgs: unknown,
ctx: AuthContext
): Promise<{ status: "ok" | "requires_approval" | "denied"; data?: unknown; reason?: string }> {
// 1. Enforce explicit session-level tool allowlist
if (!ctx.allowedTools.has(tool.name)) {
return { status: "denied", reason: `Tool ${tool.name} not permitted for current session` };
}
// 2. Strictly validate LLM-supplied arguments with Zod
const parsed = tool.schema.safeParse(rawArgs);
if (!parsed.success) {
return { status: "denied", reason: "Invalid tool arguments schema" };
}
// 3. Require human-in-the-loop approval for critical mutations
if (tool.risk === "write_critical") {
return {
status: "requires_approval",
data: { tool: tool.name, proposedArgs: parsed.data, requestedBy: ctx.userId },
};
}
// 4. Execute with server-authenticated context (never LLM-supplied)
const result = await tool.execute(parsed.data, ctx);
return { status: "ok", data: result };
}Blocking data exfiltration and validating structured outputs
A classic exfiltration technique against chat UIs that render Markdown is instructing the model to embed stolen secrets inside an image URL (``), causing the user's browser to fire a GET request to the attacker's server the instant the message renders. Another risk is accidental leakage of API keys, internal tokens, or unauthorized PII in plain text.
We neutralize both classes deterministically before any response leaves the backend: strict JSON schema validation whenever UI components expect structured payloads, Markdown sanitization that blocks external images outside an explicit host allowlist, and a lightweight DLP scanner that redacts secret patterns.
const SECRET_PATTERNS: RegExp[] = [
/sk-[a-zA-Z0-9]{20,}/g, // OpenAI-style API keys
/ghp_[a-zA-Z0-9]{30,}/g, // GitHub personal tokens
/-----BEGIN [A-Z ]+ PRIVATE KEY-----/g, // PEM private keys
];
const EXTERNAL_MD_IMAGE = /!\[[^\]]*\]\((https?:\/\/[^)]+)\)/gi;
export function sanitizeAgentOutput(rawText: string, allowedHosts: ReadonlySet<string>): string {
let clean = rawText;
// 1. Stop Markdown image exfiltration to non-allowlisted hosts
clean = clean.replace(EXTERNAL_MD_IMAGE, (_match, url: string) => {
try {
const host = new URL(url).hostname;
return allowedHosts.has(host) ? _match : "[external image blocked by security policy]";
} catch {
return "[link blocked]";
}
});
// 2. Redact accidental credential or secret patterns
for (const pattern of SECRET_PATTERNS) {
clean = clean.replace(pattern, "[REDACTED]");
}
return clean;
}Trace auditing, step budgets, and continuous CI red teaming
Every production agent turn writes an immutable audit record containing the session ID, tenant ID, prompt version, requested tool calls, authorization verdicts, and output-guard events. We also cap execution depth (`maxSteps <= 4`) and per-turn token budgets to mitigate Denial-of-Wallet abuse and runaway tool loops.
Structured traces make post-incident forensics fast: if a customer reports unexpected agent behavior, engineers can reconstruct the exact retrieved RAG chunks, tool arguments, authorization decisions, and sanitized output without guessing what the model saw.
Ahead of every release, an automated adversarial test suite runs in CI against direct injection strings, poisoned RAG chunks, Markdown exfiltration attempts, and unauthorized tool-call attempts. If any test succeeds in invoking a disallowed tool or leaking a canary token, the build fails immediately.
Closing thoughts: deterministic security around probabilistic models
Hardening production AI agents is not about writing longer system prompts—it is about wrapping probabilistic models in proven software security controls: least privilege, database-enforced isolation, schema validation, and auditability. When every tool boundary enforces Zod validation, every database query runs inside a tenant-scoped PostgreSQL RLS transaction, and every outbound message passes through a deterministic output guard, prompt injection ceases to be a single point of failure.
If your engineering team is preparing an AI agent, multi-tenant RAG platform, or critical B2B API for enterprise security review, explore our Application Security, API Hardening & DevSecOps Engineering service for concrete deliverables and security architecture reviews.
Next architectural step
Application Security, API Hardening & DevSecOps Engineering
Want to apply this architecture in your stack? Reach out at info@artagdev.com.co or review the full deliverables of our dedicated service.