Layered Defenses, Moderation and Their Limits
Organise prompt-injection defences by where they act, see why no prompt-only defence is complete, place moderation APIs and guard models on inputs and outputs, and plan monitoring, red teaming and the residual risk you accept.
Contentsand lesson path
On this page
- Why it matters
- Where each layer acts
- Jailbreaks, moderation APIs and guard models
- Monitoring, red teaming and residual risk
- Check your understanding
- Apply it
- Review prompt
Lessons of AI Security
- Threat Modeling an LLM Application Concept · 20 min
- Lab: Injecting Your Own RAG Assistant Lab · 25 min
- Layered Defenses, Moderation and Their Limits Concept · 15 min
- Permission-Aware Retrieval and Redaction Worked example · 20 min
- Untrusted Output and Content Moderation Worked example · 25 min
- Check: Spot the Vulnerability Knowledge check · 10 questions
What you will learn
- Demonstrate direct and indirect prompt injection against your own application and apply layered mitigations.
- Screen inputs and outputs for harmful or off-policy content with a moderation API or guard model, and measure its false-positive and false-negative rates on a labelled sample.
01. Why it matters
In the lab, every layer stopped something and none stopped everything. Delimiters stopped three planted documents, encoding a fourth, and the fifth fooled the model anyway; a tool without a recipient argument and an output check then kept that fooled model from doing harm. That pattern is not an artefact of the FAKE model. It is how defence against prompt injection works in production: several partial layers, each placed where it is cheap and reliable, and none trusted on its own.
This lesson turns the lab into a map you can apply to any LLM feature. It adds two layers the lab left out, content moderation and monitoring, and it is explicit about the limits of each, because a defence whose limits you do not know gives false confidence.
02. Where each layer acts
Sort defences by the point in the request where they act. Each position has typical strengths and gaps.
where layer misses
before the model authorisation in retrieval bugs in its own rules or code
source allow-list, review at ingestion novel or slow-burn content
input screen (rules, guard model) rephrased or unseen attacks
in the prompt delimit and encode untrusted content a model that obeys anyway
policy: data is not instructions the same
around tools least privilege, fixed arguments misuse within the scope
confirmation for risky actions users who click through
after the model output encoding, link allow-list harm in plain text
output moderation subtle or new harm
over time logs, per-user signals, red teaming nothing in real timeTwo layers in this map are deterministic code: authorisation in retrieval and narrow tools. They do not depend on what the model decides, so no payload can talk its way past them; what can still fail is a wrong rule or a bug in the code. Build them first and test them like any other access control; lesson 4 does this for retrieval.
Everything that relies on the model reading something, including system-prompt policies, delimiters, and guard models, is probabilistic. It lowers the success rate; it does not remove it. There are four reasons no prompt-only defence is complete:
- One channel. Instructions and data reach the model as the same kind of tokens. Delimiters are a convention the model has learned to respect most of the time, not a boundary it must respect.
- Adaptive attackers. A fixed defence is tested once by you and thousands of times by others. Published evaluations keep finding that defences which look strong against a fixed attack set fall to attacks tuned against them.
- Change. A new model version, a reworded system prompt or a new tool can bring back an attack your tests had closed.
- Guards are models too. A guard model that reads untrusted text can be injected by that text, as any other model can.
The practical rule follows from this: assume some injections will succeed, and make sure a successful one can only reach what the user could reach anyway. That is the job of authorisation, least privilege and confirmation, and it is why OWASP lists them beside the prompt-level measures.
03. Jailbreaks, moderation APIs and guard models
A jailbreak is an attempt to make a model break its own safety training, for example through role-play or a long series of escalating requests. A prompt injection overrides the instructions of the application built on the model. They overlap, and both arrive through text, but the defences differ: the model provider's safety training mostly handles jailbreaks, while injection is your application's problem.
Content moderation screens text against a policy: harassment, hate, self-harm, sexual content, violence, and whatever your own product forbids. There are three common ways to run it:
- A hosted moderation API, such as OpenAI's moderation endpoint, which returns a flag and a score per category.
- An open guard model that you host, such as Meta's Llama Guard 4, which classifies both prompts and responses against a standard hazard taxonomy.
- A general model with your own policy, for example a small, fast Claude model asked for a structured verdict. This is the most flexible, because the policy is your text: "no promises beyond the published refund policy" is not a category any off-the-shelf API has.
Screen in both directions. On the input side, a guard catches abusive or clearly off-topic requests before you spend a model call on them. On the output side, it catches what the model produced anyway, including text that a planted document steered it into. Some providers also run their own classifiers; recent Claude models, for instance, can end a response with the stop reason refusal, which your code should handle as a blocked answer.
04. Monitoring, red teaming and residual risk
Layers that act in real time miss things; monitoring finds them afterwards. Log each moderation decision, each rejected tool call and each blocked link with a request ID and a user ID, never the raw text with personal data in it. Count per user: one blocked message is noise, twenty in an hour is someone probing your assistant, and the right response is a rate limit or a review rather than more prompt rules.
Model providers watch for abuse too, and you can help them tell your users apart. Anthropic's Messages API accepts metadata.user_id, which should be an opaque identifier, never a name, email address or phone number. A keyed hash of your internal ID is stable across requests and cannot be reversed by someone who guesses IDs:
"""A stable end-user ID for abuse monitoring that reveals nothing about the user."""
import hashlib
import hmac
import os
def opaque_user_id(user_id: str) -> str:
key = os.environ["USER_ID_KEY"].encode() # a secret: keep it out of code and logs
return hmac.new(key, user_id.encode(), hashlib.sha256).hexdigest()[:32]
request = {
"model": os.environ["ANTHROPIC_MODEL"], # for example claude-sonnet-5-5
"max_tokens": 16000, # one cap for thinking and answer text together
"metadata": {"user_id": opaque_user_id("u-ada")},
"messages": [{"role": "user", "content": "How do I export a project?"}],
}
print(request["metadata"])
print(opaque_user_id("u-ada") == opaque_user_id("u-ada")) # stable across requestsUSER_ID_KEY=practice-only-key ANTHROPIC_MODEL=claude-sonnet-5-5 python opaque_id.py{'user_id': '3afe84a77574a2dcf552fab912cd2f8c'}
TrueRed teaming is deliberate attack by your own side. Keep the results as an adversarial test set, like the seven attacks in the lab, and grow it: every incident, every new technique you read about and every attack a colleague invents becomes a case. Rerun it on every change of model, prompt, tool or data source, and compare success rates rather than single outcomes, because real models vary from run to run.
Finally, write down what is left. After all layers, the Lumen assistant can still be steered into odd wording by a planted document, and a determined user can still make it say something silly to themselves. That residual risk is acceptable only because the layers in code keep both from reaching other users' data or acting outside the user's own account. Record it in the threat register, with the person who accepted it.
05. Check your understanding
06. Apply it
For your own RAG assistant:
- Copy the layer map and fill in what you have at each position, what you plan, and what each one misses in your app.
- Add input and output screening with a moderation API or guard model, behind one function, so that lesson 5 can measure it.
- Send an opaque, keyed-hash user ID with each model request and log moderation decisions with it.
- Rerun your five planted documents with all layers on, and add the result and the residual risk to your threat register.
07. Review prompt
Without looking back:
- Which two layers in the map hold regardless of what the model decides, and why?
- Give four reasons why a prompt-only defence cannot be complete.
- Name three ways to run content moderation and one thing each is poor at.
- Why should the user ID you send to a model provider be a keyed hash rather than an email address or a plain hash?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.