AI Gateway · Exercise 05

Block bad prompts

Stop prompt injections and sensitive data at the gateway with Guardrails and DLP before they ever reach a model.

Block bad prompts

Blocking prompt injection and sensitive data at the gateway before a request reaches the model. Direct video link

When users can type into your AI application, you don’t control what they paste. Customers accidentally paste credit card numbers into support chats, and attackers intentionally send prompt injections to hijack what your assistant does. If you try to build security checks into every application separately, one service eventually forgets — and if you rely on the model itself to refuse an injection, your security changes every time you swap models in a route. Putting those checks in AI Gateway applies one policy to every request before it ever reaches a model, with zero application code changes.

What you’ll build

Prompt-injection protection on your gateway using Guardrails. You’ll send both a normal prompt and a prompt-injection attempt through your Worker, and confirm in the gateway logs that the attack is stopped before it ever reaches a model.

Prerequisites

DLP looks for data, Guardrails looks for intent

AI Gateway gives you two complementary controls on the request and response path:

  • Data Loss Prevention (DLP): scans text against detection profiles, such as Financial Information (credit card numbers) or National Identifier Numbers, and either Flags or Blocks a match before it leaves Cloudflare for a model provider.
  • Guardrails: evaluates prompts and responses with dedicated safety models on Workers AI — Prompt Guard (P1) for prompt injection and jailbreak attempts, and Llama Guard (S1–S14) for harmful content categories — and either Flags or Blocks matching requests.

When Guardrails blocks a prompt injection, your route never resolves and the upstream model is never called: the gateway returns HTTP 424 (Prompt blocked due to security configurations), and the upstream model uses 0 tokens. The Guardrails check itself runs on Workers AI and is billed as Workers AI inference.

With DLP and Guardrails in place, here is the complete five-stage AI Gateway pipeline you built across this course:

prompt + metadataBlocked (P1 / PII)AllowedHitMissOverUnderinternsescalationsYour Worker5. DLP & GuardrailsHTTP 4240 model tokens1. Logs2. Cache?~20ms · $03. Limits?HTTP 4294. Route: supportGranite / GemmaLlama 3.3 70B ──► GPT-OSS 120B

If your app handles regulated data that shouldn’t be stored in gateway logs, you have two logging options. The cf-aig-collect-log-payload: false header keeps who sent the request, the model, tokens, and cost without storing what was sent. collectLog: false on the binding (or the cf-aig-collect-log: false header) skips the log entry entirely, metadata included.