Exposing a public endpoint wired to OpenAI or Anthropic without a defensive middleware layer is the modern equivalent of unparameterized SQL. The top risk today is Prompt Injection (direct and indirect) alongside token/quota abuse.
1. Attack Vectors to Mitigate
- Direct Injection: Users attempting to override system instructions to leak internal prompts or bypass business rules.
- Indirect Injection: Untrusted third-party text (scraped pages, user comments, emails) containing hidden instructions executed by your agent.
- Unsafe Output Handling (XSS): Rendering raw LLM HTML/Markdown without sanitization.
2. Backend Defense-in-Depth
// 1. Enforce strict input length & sanitization before calling the LLM
$userInput = mb_substr(strip_tags(trim($rawInput)), 0, 2000);
// 2. Parse strict JSON output and escape before rendering
$decoded = json_decode($llmResponse, true, 512, JSON_THROW_ON_ERROR);
$safeText = htmlspecialchars($decoded['answer'] ?? '', ENT_QUOTES, 'UTF-8');
Pair this with per-IP rate limiting and strict least-privilege permissions on any tool/function calling exposed to the model.