AI systems are attack surfaces. Every prompt is potential input injection. Every model response is potential data leakage. Every tool call is potential privilege escalation. If you're building AI applications without security as a foundational concern, you're building a breach waiting to happen.
Here's how to do it right.
The AI Security Threat Model
Traditional applications have well-understood threat models. AI applications introduce new attack vectors:
| Attack Vector | Traditional App | AI Application |
|---|---|---|
| Input injection | SQL injection | Prompt injection |
| Data leakage | Database exposure | Training data extraction |
| Privilege escalation | Auth bypass | Tool permission abuse |
| Denial of service | Resource exhaustion | Infinite loops, token bombing |
Layer 1: Input Sanitization
Every input to an AI system must be validated and sanitized:
class SecureInputHandler {
async processUserInput(input: string): Promise<SafeInput> {
// Check for obvious injection attempts
if (this.containsInjectionPatterns(input)) {
throw new SecurityError('Potential injection detected')
}
// Limit input length
const truncated = input.slice(0, MAX_INPUT_LENGTH)
// Encode special characters
const encoded = this.encodeSpecialChars(truncated)
// Add input boundary markers
return {
content: `<user_input>${encoded}</user_input>`,
originalLength: input.length,
sanitized: true
}
}
private containsInjectionPatterns(input: string): boolean {
const patterns = [
/ignore (all )?(previous|above) instructions/i,
/you are now/i,
/system prompt/i,
/\[INST\]/i,
/<\|im_start\|>/i
]
return patterns.some(p => p.test(input))
}
}
This isn't foolproof—prompt injection is fundamentally hard to prevent—but it raises the bar significantly.
Layer 2: Output Validation
Never trust model outputs. Validate everything before acting on it:
class SecureOutputHandler {
async processModelOutput(output: ModelOutput): Promise<SafeOutput> {
// Parse structured output (don't trust raw strings)
const parsed = this.parseStructuredOutput(output)
// Validate against schema
const validated = await this.validateSchema(parsed)
// Check for data leakage
if (await this.containsSensitiveData(validated)) {
return this.redactSensitiveData(validated)
}
// Verify any tool calls
if (validated.toolCalls) {
await this.validateToolCalls(validated.toolCalls)
}
return validated
}
private async containsSensitiveData(output: unknown): Promise<boolean> {
const sensitivePatterns = [
/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/, // Email
/\b\d{3}-\d{2}-\d{4}\b/, // SSN
/\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14})\b/, // Credit card
// Add patterns for API keys, internal URLs, etc.
]
const str = JSON.stringify(output)
return sensitivePatterns.some(p => p.test(str))
}
}
Layer 3: Tool Permission System
AI agents with tools are especially dangerous. Implement strict permission controls:
interface ToolPermission {
tool: string
actions: string[]
resourcePatterns: RegExp[]
rateLimit: RateLimit
requiresApproval: boolean
}
class ToolPermissionSystem {
private permissions: Map<string, ToolPermission[]>
async checkPermission(
agentId: string,
tool: string,
action: string,
resource: string
): Promise<PermissionResult> {
const agentPerms = this.permissions.get(agentId) || []
const toolPerm = agentPerms.find(p => p.tool === tool)
if (!toolPerm) {
return { allowed: false, reason: 'Tool not permitted' }
}
if (!toolPerm.actions.includes(action)) {
return { allowed: false, reason: 'Action not permitted' }
}
if (!toolPerm.resourcePatterns.some(p => p.test(resource))) {
return { allowed: false, reason: 'Resource not permitted' }
}
if (await this.isRateLimited(agentId, tool)) {
return { allowed: false, reason: 'Rate limit exceeded' }
}
if (toolPerm.requiresApproval) {
return { allowed: false, reason: 'Requires human approval', needsApproval: true }
}
return { allowed: true }
}
}
Key principles:
- Deny by default: Agents have no permissions until explicitly granted
- Least privilege: Grant minimum permissions needed
- Human in the loop: Require approval for sensitive operations
Layer 4: Model Isolation
Run models in isolated environments:
class IsolatedModelRunner {
async runModel(
model: Model,
input: SafeInput,
context: ExecutionContext
): Promise<ModelOutput> {
// Create isolated sandbox
const sandbox = await this.createSandbox({
memoryLimit: '4GB',
cpuLimit: '2 cores',
networkAccess: false,
filesystemAccess: 'none',
timeout: 30000
})
try {
// Run model in sandbox
const output = await sandbox.execute(async () => {
return model.generate(input, context)
})
return output
} finally {
// Always destroy sandbox
await sandbox.destroy()
}
}
}
This prevents:
- Models accessing unauthorized resources
- Infinite loops consuming unbounded resources
- Side-channel attacks through filesystem/network
Layer 5: Audit Logging
Log everything for forensic analysis:
interface SecurityAuditLog {
timestamp: Date
eventType: SecurityEventType
agentId: string
userId?: string
input: {
raw: string
sanitized: string
injectionDetected: boolean
}
output: {
raw: string
redactionsApplied: string[]
leakageDetected: boolean
}
toolCalls: {
tool: string
action: string
resource: string
permitted: boolean
result: 'success' | 'denied' | 'error'
}[]
riskScore: number
}
Use these logs for:
- Real-time threat detection
- Post-incident forensics
- Compliance reporting
- Model behavior analysis
Defense in Depth
No single layer is sufficient. Stack them:
User Input
│
▼
┌───────────────────────┐
│ Input Sanitization │ ← Layer 1
└───────────────────────┘
│
▼
┌───────────────────────┐
│ Model Isolation │ ← Layer 4
└───────────────────────┘
│
▼
┌───────────────────────┐
│ Output Validation │ ← Layer 2
└───────────────────────┘
│
▼
┌───────────────────────┐
│ Tool Permissions │ ← Layer 3
└───────────────────────┘
│
▼
┌───────────────────────┐
│ Audit Logging │ ← Layer 5
└───────────────────────┘
│
▼
Safe Output
The Hard Truth
Perfect security is impossible. Prompt injection, in particular, is an unsolved problem—there's no foolproof way to distinguish "data" from "instructions" when everything is natural language.
But "hard" doesn't mean "don't try." These layers dramatically reduce your attack surface and make successful attacks much harder and more detectable.
Build AI systems like you're building banking software. Because increasingly, you are.