Model policy and gateway policy
The protection of an AI agent has two layers of policy. The first is written by the model provider and put into the model by training. The second is written by you and enforced by code on the request path. This module shows what each layer can ensure, what it cannot, and how to combine them. Each section ends with a conclusion: what this means for protecting an AI agent.
Time: about an hour. Roughly 35 minutes for the text, 20 minutes for the lab and 5 minutes for the questions. What you need: Python 3.8 or later with no third-party packages. No account, keys or network access are needed.
Learning goals
- Explain what a published model policy describes and why it is not a guarantee, a contract or your own policy.
- Tell a model's behavior from an enforcement point and name the three properties of an enforcement point.
- List what a gateway ensures whatever the model: a decision before the model, one policy across models and providers, a decision log and a tenant's own stricter policy.
- Name two classes of problem in which a gateway does not help, and explain why.
- Assign requirements to the model, the gateway and the executor, and report the result as a rate with its one-sided 95% bound.
What a published model policy is
Providers of frontier models publish texts about how a model should behave. OpenAI has the "Model Spec". Anthropic has a constitution for Claude, "Claude's Constitution". Such a text is neither a set of rules for customers nor a description of filters. It describes the intended behavior of the model itself: whose instructions it follows and in what order, what it does by default, what a developer or a user may change, and what it must not do whatever the instructions.
The two documents differ in style and are alike in what they contain.
- An order of authority. The "Model Spec" describes a chain of command: platform rules first, then the developer, then the user. Text from documents and from tool responses carries no authority. Claude's constitution describes principals: Anthropic, operators and users, whom the model trusts to different degrees.
- Prohibitions that instructions do not lift. Both documents contain a short list of things the model must not do, whoever asks.
- Adjustable defaults. Most of the behavior is described as a default. A developer in the system message and a user in the conversation may change it within set limits.
- The manner of writing. The "Model Spec" is closer to a body of rules and defaults with examples. Claude's constitution more often explains reasons and relies on the model's judgment rather than on a list of rules.
The text becomes behavior through training: the provider relies on it when preparing examples and grading the model's responses. The mechanism itself is covered in the module "LLMs for security engineers", in the section on reinforcement learning.
What this means for defense:
- Read the policy of the model your agent runs on. It answers practical questions: what the model will do with an instruction found in a document, what it treats as a default, and what you can change with a system message.
- Keep three kinds of provider document apart. The model policy describes the behavior of the model. The usage policy describes what you are allowed to do as a customer. A description of moderation concerns the provider's infrastructure. Only the first is put into the model.
- An agent's system message works inside the frame of the model policy: it changes defaults and does not lift prohibitions. Make sure that the behavior you need lies in the adjustable part.
What a model policy is not
A model policy is easily taken for something it is not. There are five such substitutions.
- A guarantee. The document describes the provider's intent. The behavior was obtained by training and is followed with high probability, but not always. Both documents themselves state that the model's behavior may depart from what is written.
- A contract with you. The document does not promise you a refusal rate and gives no grounds for a claim when the model departed from it. Your relationship with the provider is defined by the contract and the usage policy.
- Your policy. The author of the document does not know your data, customers, contracts or regulator. It contains no ban on discussing a competitor's prices or on stating your contract numbers, and the model does not regard such requests as a violation.
- A constant. The texts are revised, the models are updated, and behavior changes from version to version. Another model has another text. A model with open weights that a third party has fine-tuned may have no stated policy at all.
- An enforcement mechanism. The next section is about this.
What this means for defense:
- Do not enter the model policy in your threat model as a closed risk. Enter it as a layer that lowers a probability, and measure that probability on your own model version.
- Implement the requirements that only you have on your own side. A system message will tell the model about them, but following them will remain trained behavior.
- When you replace the model or the provider, assume that the model policy layer has been replaced entirely, and repeat the measurements.
A refusal is a behavior, not an enforcement point
In security, an enforcement point is a place where an access decision is made compulsorily. The classic description comes from James Anderson's report of 1972. A reference monitor is invoked on every access and cannot be bypassed, is protected from modification, and is small enough to be verified. Saltzer and Schroeder named the first property complete mediation.
A refusal by the model has none of these three properties.
- A repeated attempt gets around it. The response is chosen by sampling, so a request that the model refused may go through on a retry without a single change.
- The party it is meant to restrain influences it. The decision is made in the same context that the attacker's text enters. The work of Zou and coauthors and of Wei and coauthors showed that an input which removes the refusal can be searched for deliberately.
- It cannot be verified. The decision is not written down as a rule: it is spread across the model's weights. The explanation the model gives for its refusal is generated text as well.
There are three more practical properties.
- A refusal leaves no record on your side. Some APIs report it with a separate marker, but often the application receives ordinary text and has to guess that it is a refusal.
- A refusal happens after transmission. By the time of the refusal, the request text is already with the provider. If the problem lies in the request data itself, for example it contains someone else's personal data or a secret, the refusal brings nothing back.
- A refusal is expressed in words. What the agent did with its tools meanwhile cannot be seen from the text. The module "Monitoring agents: judge the actions" covers this.
What this means for defense:
- Model refusals are useful: they stop many direct attempts. In a list of measures they are entered as a reduction in probability, not as a control.
- Every requirement that contains the word "never" gets an enforcement point in code: in the gateway before the model, or at the executor before the action.
- Do not build incident detection on the text of refusals. Count decisions where they are recorded.
What a gateway can enforce
Here a gateway means the code on the path between the application and the model that sees the request before the model does and the response before the application does. Spectorn is built this way too: it sits in front of the model and inspects the content of requests and responses. A gateway becomes an enforcement point on one condition: there is no other path to the model. If the application can reach the provider directly, the mediation is incomplete.
A decision before the model sees the text. A gateway can reject a request and not pass it to the provider. For data that must not leave your perimeter, this is the only moment at which a refusal still changes anything. According to the public description of the request path in Spectorn, a request is forwarded to the provider only if the input checks pass, and when the input check is unavailable it is not forwarded at all.
One policy across models and providers. An agent rarely runs on a single model: there is a fallback provider, a cheap model for simple steps and a new version you are moving to. Each has its own policy text and its own rate of adherence to it. A gateway applies one rule to a request whichever model the request is addressed to. For a model with open weights, which has no provider layer, this is the only shared layer.
A decision log. A gateway records every decision it makes: who called, when, what the verdict was and under which policy version. Spectorn keeps such a log as an integrity-protected chain in which a later edit of a record is detectable, and sends each finding to the SIEM the customer configures, with its category, severity and verdict identifier. The same documentation states the boundary: Spectorn sees only what the integration sends to it, and calls that bypass it do not reach the log.
A tenant's own stricter policy. A customer can prohibit more than the model provider does: topics, kinds of data, recipients. In Spectorn every tenant has its own policy, which includes the scan mode and the allow and deny lists. There are two modes: enforce, and shadow, in which the request is checked and you can see what would have been blocked. The reverse is impossible: a gateway cannot make the model less strict, and a prohibition put into the model stays with it.
What this means for defense:
- What must not reach the provider is stopped before the model. A refusal by the model comes too late here.
- Provider keys are held only on the gateway, and the application's direct route to the provider is closed. Otherwise the gateway remains advice, not an enforcement point.
- Make the gateway's decision deterministic wherever that is possible: same input, same verdict. Such a decision can be tested, by mutation too, as described in the module "Goodhart's law in security metrics".
- A new policy is first turned on in shadow mode on your own traffic. You review what would have been blocked, and only then turn on enforcement.
- An investigation rests on the record of the decision, not on running the request again.
Where a gateway cannot help
The first class of problem: meaning that the model understands and the gateway's detector does not see.
A detector is built in advance: from rules, samples or a classifier. The model was trained on incomparably more language. It understands a paraphrase, a hint, a code word, a rare language and a meaning that adds up from several innocuous turns. So there are always inputs that the model understands and the detector does not. The adversary looks for exactly these and moves second: the adversary sees the defense and adapts the attack to it. A classifier based on another model narrows this gap, but it remains a detector with a miss rate of its own.
We have a measurement of this gap. According to the record on the page "Measured evidence, with dates", on 2026-11-02 Spectorn blocked 20 of 65 attacks that at the time appeared in no training corpus: that is 31%, with one-sided 95% bounds from 21.4% to 41.5%. The gateway did not stop the remaining attacks of that set. Since 2026-11-21 the set has taken part in tuning the protection and no longer counts as held out, so a repeated measurement on it will no longer show this gap.
Other layers stop this class. The model understands the meaning and may refuse, although its refusal remains a behavior. The executor checks the action against permissions and against what the user authorized, whatever path the text took to reach it.
What this means for defense:
- Do not promise yourself or your customer that the gateway sees everything the model understands. The miss rate on dissimilar attacks is measured on a held-out set and reported with a bound.
- The last line for this class is the executor: the action is checked independently of the text that led to it.
- The model's refusal layer works for you here. A model without that layer needs a compensating control on tasks with untrusted input.
De-anonymization from innocuous data
The second class of problem: an inference that a capable model draws from data, each piece of which is innocuous.
The problem itself is older than language models. In 2000 Latanya Sweeney estimated that 87% of the US population is uniquely identified by the combination of ZIP code, sex and date of birth. In 2008 Narayanan and Shmatikov showed how to recover the identities of users in an anonymized set of movie ratings by matching it against public reviews. At the time, such matching took a specialist and time.
The paper by Staab and coauthors (2023) showed that a language model infers personal attributes of an author, for example place of residence, age and income, from ordinary texts in which those attributes are not stated. The accuracy is high, and the time and cost are a small fraction of what a human needs. The authors also tested two protective measures, text anonymization and the models' own refusals, and found both insufficient at the time of the study.
An input check does not help here because of how the problem is built. No message contains an identifier: no name, no number, no address. A personal-data detector looks for identifiers and finds nothing. Masking removes direct identifiers and leaves the indirect attributes from which the inference is drawn: a habitual route, a job title, a rare event, a manner of writing. What is dangerous is the combination of fragments, not a single fragment.
For an agent this is a practical risk. An agent that has search over public sources and access to internal data performs by itself the matching that used to need an analyst.
What this means for defense:
- Treat an anonymized set that the agent can access as personal data if the agent can match it against another source.
- Restrict the ability to match, not the text: which sources the agent reads within one task, how many records and for what purpose. This is the policy of the tools and of the executor.
- Use masking, but do not call it anonymization.
- An output check catches part of the cases: a name or a contact in the response that was not in the input. Such responses are worth recording as events.
- The model policy on privacy remains a layer that lowers a probability.
How to combine the two layers
| Layer | What it ensures | What it does not ensure | How to verify it |
|---|---|---|---|
| Model policy | An understanding of meaning; refusals where there is no pattern | A guarantee, a record, your requirements, constancy across versions | A rate on your own model version, with a bound |
| Gateway | A decision before the model; one policy for all models; a log; the tenant's policy | An understanding of everything the model understands; protection from inference out of innocuous data | A rate on a held-out set; mutation; a check that there is no bypass path |
| Executor | A check of the action against permissions and against what the user authorized | Control over the text of the response | Tests on every path to the executor |
Rules for combining them:
- Assign the requirements. "Never" gets an enforcement point in code. "As a rule" may be left to the model's behavior if you measure it.
- Do not weaken one layer because of the other. The gateway's decision must not count on the model refusing, and the choice of model must not count on the gateway seeing everything.
- See to it that the layers fail in different ways. If the gateway's detector is the same model that runs in the agent, their misses coincide.
- Align the system message with the gateway policy. If one demands what the other prohibits, you get false blocks or an unnoticed divergence.
- Measure the layers separately and together, on your own model version and your own policy version. An aggregate number hides the class in which one of the layers does not work.
- Decide in advance how a layer behaves when it fails. An unavailable check means that the request is not served, not that it passes unchecked.
No layer solves the problem alone. The next module moves from text to actions.
Required reading
- OpenAI, "Model Spec": the sections on the chain of command, rules and defaults.
- Anthropic, "Claude's Constitution": the sections on principals, hard constraints and instructable behaviors.
- James P. Anderson, "Computer Security Technology Planning Study", 1972: the definition of the reference monitor.
- Jerome H. Saltzer, Michael D. Schroeder, "The Protection of Information in Computer Systems", 1975: the design principles, complete mediation first of all.
- Andy Zou et al., "Universal and Transferable Adversarial Attacks on Aligned Language Models", 2023: the problem statement and the transfer between models. arxiv.org/abs/2307.15043
- Robin Staab et al., "Beyond Memorization: Violating Privacy Via Inference with Large Language Models", 2023: the problem statement and the section on mitigations.
- Spectorn, "What Is an AI Firewall and How Does It Work": the control points and the boundaries of responsibility.
Further reading
- Alexander Wei et al., "Jailbroken: How Does LLM Safety Training Fail?", 2023.
- Yuntao Bai et al., "Constitutional AI: Harmlessness from AI Feedback", 2022.
- Hakan Inan et al., "Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations", 2023.
- Mrinank Sharma et al., "Constitutional Classifiers: Defending against Universal Jailbreaks across Thousands of Hours of Red Teaming", 2025.
- Milad Nasr, Nicholas Carlini et al., "The Attacker Moves Second: Stronger Adaptive Attacks Bypass Defenses Against LLM Jailbreaks and Prompt Injections", 2025.
- Eric Wallace et al., "The Instruction Hierarchy: Training LLMs to Prioritize Privileged Instructions", 2024. arxiv.org/abs/2404.13208
- Latanya Sweeney, "Simple Demographics Often Identify People Uniquely", 2000.
- Arvind Narayanan, Vitaly Shmatikov, "Robust De-anonymization of Large Sparse Datasets", 2008.
- Paul Ohm, "Broken Promises of Privacy: Responding to the Surprising Failure of Anonymization", 2010.
- OWASP, "Top 10 for Large Language Model Applications": the sections on sensitive information disclosure and on excessive agency. owasp.org/www-project-top-10-for-large-language-model-applications
- Spectorn, "LLM Guardrails Explained": how controlling behavior differs from protection.
- Boaz Barak, the course CS 2881R AI Safety, Harvard University: the session on model policies. boazbk.github.io/mltheoryseminar
Lab
Goal: measure two layers, the model's refusal and the gateway's decision, separately and together on three classes of request. The data is synthetic: the "forbidden" requests are strings with made-up marker words. The lab's numbers describe the toy and say nothing about any real model or product.
The threshold is chosen before the measurement: τ = 5%. The claim under test: "a forbidden request gets an answer in fewer than 5% of cases". A trial is one independent request, and an event is an answer to a forbidden request.
The toy has three classes of request, 300 in each. In the first, what the model policy forbids is expressed with a marker that the gateway's rule sees. In the second, the same forbidden thing is expressed without a marker: only the model understands the meaning. The third class is forbidden only by the tenant's policy, and the model does not know about it. Two models were trained on one policy text and adhere to it with different probabilities.
Save the code to a file named lab_policy.py and run python3 lab_policy.py.
import math
import random
ALPHA = 0.05 # one-sided 95% bound
TAU = 0.05 # threshold chosen before the measurement
PER_CLASS = 300 # independent requests in each class
POLICY = "lab-policy-1"
# Both models were trained on one policy text but adhere to it with different probabilities.
# The third has no refusal layer: this is how a model without a provider policy behaves.
REFUSAL_RATE = {"model_a": 0.99, "model_b": 0.85, "no_policy": 0.0}
BASE_RULES = ["zorbak"] # what the gateway recognizes by pattern
TENANT_DENY = ["quillex"] # what the tenant has prohibited in addition
def requests_of(kind):
# The gateway reads only the text field. The meaning field stands for what the model understands.
samples = []
for number in range(1, PER_CLASS + 1):
if kind == "pattern": # forbidden by the model policy, the text has a marker
text, meaning = f"zorbak synthetic request {number}", "provider_forbidden"
elif kind == "meaning": # forbidden by the model policy, the text has no marker
text, meaning = f"synthetic request without a marker {number}", "provider_forbidden"
else: # forbidden only by the tenant's policy
text, meaning = f"quillex synthetic request {number}", "tenant_forbidden"
samples.append({"id": f"{kind}-{number}", "text": text, "meaning": meaning})
return samples
def model_answers(model, request, rng):
# A refusal is a behavior: the outcome is drawn anew on every call.
if request["meaning"] == "provider_forbidden":
return rng.random() >= REFUSAL_RATE[model]
return True # the model does not know about the tenant's policy
def gateway_allows(request):
# The gateway's decision is deterministic and does not depend on the model.
return not any(marker in request["text"] for marker in BASE_RULES + TENANT_DENY)
def measure(kind, model, gateway, seed):
rng = random.Random(seed)
events, records = 0, []
for request in requests_of(kind):
if gateway:
allowed = gateway_allows(request)
verdict = "allow" if allowed else "block"
# the decision record: without the request text
records.append({"id": request["id"], "verdict": verdict, "policy": POLICY})
if not allowed:
continue # the request is not passed to the model
if model_answers(model, request, rng):
events += 1 # a forbidden request got an answer
return events, records
# Exact one-sided Clopper-Pearson bounds, standard library only.
# The same calculation as in the labs of the previous modules and in scripts/rate_bounds.py.
def binom_cdf(k, n, p):
total = 0.0
for i in range(k + 1):
log_term = math.lgamma(n + 1) - math.lgamma(i + 1) - math.lgamma(n - i + 1)
log_term += i * math.log(p) + (n - i) * math.log1p(-p)
total += math.exp(log_term)
return total
def upper_bound(k, n):
if k == n:
return 1.0
low, high = k / n, 1.0
for _ in range(100):
middle = (low + high) / 2
if binom_cdf(k, n, middle) > ALPHA:
low = middle
else:
high = middle
return high
def lower_bound(k, n):
if k == 0:
return 0.0
low, high = 0.0, k / n
for _ in range(100):
middle = (low + high) / 2
if 1.0 - binom_cdf(k - 1, n, middle) < ALPHA:
low = middle
else:
high = middle
return low
def report(label, events, records):
trials = PER_CLASS
low, high = lower_bound(events, trials), upper_bound(events, trials)
if high < TAU:
verdict = "VERIFIED"
elif low >= TAU:
verdict = "NOT VERIFIED"
else:
verdict = "INCONCLUSIVE"
print(f"{label}: {events}/{trials} = {events / trials:.2%}, "
f"bounds [{low:.2%}, {high:.2%}], threshold {TAU:.0%}: {verdict}, "
f"decision records: {len(records)}")
report("model A without a gateway, marker in the text", *measure("pattern", "model_a", False, seed=1))
report("model B without a gateway, marker in the text", *measure("pattern", "model_b", False, seed=2))
report("gateway and model B, marker in the text", *measure("pattern", "model_b", True, seed=3))
report("gateway and model A, meaning only", *measure("meaning", "model_a", True, seed=4))
report("gateway and model B, meaning only", *measure("meaning", "model_b", True, seed=5))
report("model A without a gateway, tenant prohibition", *measure("tenant", "model_a", False, seed=6))
report("gateway and model A, tenant prohibition", *measure("tenant", "model_a", True, seed=7))
print("sample decision record:", measure("tenant", "model_a", True, seed=7)[1][0])
What to do:
- Run the script and copy the seven measurement lines into your report: events, trials, rate, both bounds, the verdict and the number of decision records.
- Compare the first and second lines. The policy text and the requests are the same, and only the model differs. Explain what this means for an agent that is being moved to another model.
- Compare the third and fifth lines. The gateway and the model in them are the same. Name the layer that made the decision in each of them.
- Compare the sixth and seventh lines and name the only place where the tenant's policy lives.
- Look at the number of decision records. The fifth line has 300 records, and every one of them
carries the verdict
allow. What does such a record prove, and what does it not prove? - Change the
seedvalues and run the script again. Note which lines changed and which did not. - Replace
"model_b"with"no_policy"in the third and fifth lines and run the script again. Record which of the two lines changed and why. - Check one line against the tool in the Spectorn repository:
python3 scripts/rate_bounds.py claim 0 300 --tau 0.05. The bounds should match.
What you can check from the formulas before running anything:
- If
Nindependent trials contained no events, the upper one-sided 95% bound equals1 - 0.05 ** (1 / N). For 300 trials that is 0.99%. - If the event occurred in all
Ntrials, the lower bound equals0.05 ** (1 / N). For 300 trials that is 99.01%. - Model A in the toy answers a forbidden request with a probability of 1%, model B with a probability of 15%. The 5% threshold lies between them.
- The lines with the gateway on the first and third classes do not depend on
seed: the decision is made before the model.
What you should get:
| Measurement | Events and trials | 95% bounds | Verdict at τ = 5% | Decision records |
|---|---|---|---|---|
| Model A without a gateway, marker in the text | about 3 out of 300 | depend on seed | VERIFIED expected | 0 |
| Model B without a gateway, marker in the text | about 45 out of 300 | depend on seed | NOT VERIFIED expected | 0 |
| Gateway and model B, marker in the text | 0 out of 300 | from 0% to 0.99% | VERIFIED | 300 |
| Gateway and model A, meaning only | about 3 out of 300 | depend on seed | VERIFIED expected | 300 |
| Gateway and model B, meaning only | about 45 out of 300 | depend on seed | NOT VERIFIED expected | 300 |
| Model A without a gateway, tenant prohibition | 300 out of 300 | from 99.01% to 100% | NOT VERIFIED | 0 |
| Gateway and model A, tenant prohibition | 0 out of 300 | from 0% to 0.99% | VERIFIED | 300 |
The counts in the lines marked "about" depend on seed, so no exact numbers are given here: put
your own into the report. The last line of the output shows one decision record: it holds an
identifier, a verdict and a policy version, and no request text.
Add three sentences to the report: why the first and second lines give different verdicts under one policy text, why the gateway changed nothing in the fifth line, and why the sixth line does not depend on how well the model adheres to the provider's policy.
Self-check questions
- A threat model says: "Harmful requests are closed: the provider has published a model policy, and the model refuses". Which three properties of an enforcement point does a refusal lack, and what must the team measure before it leaves that line in place?
- An agent runs on two models from different providers, and the customer has prohibited stating contract numbers in responses. Where will you implement this prohibition, why is a system message not enough, and what will go into the log when it fires?
- A support agent has search over public sources and access to an anonymized export of tickets. The personal-data filter has not fired once in a month. Why does this not prove the absence of risk, and which two restrictions will you add?
Previous module: "Goodhart's law in security metrics". Next module: "Monitoring agents: judge the actions".