Sub topic 6
Enforcing authorization in code, not in the prompt
This chapter assumes you know how LLM tool calling works, can read short Python and JSON snippets, and understand basic access control terms such as roles and permissions. It also assumes you have read the earlier chapters on the threat model and on tool scoping.
Why a prompt is not a control
A system prompt can say "never delete records" or "only read files in the workspace." That text is an instruction to a model. It is not a rule that the system enforces. The model reads it as one more piece of context, and it can fail to follow it in several ways:
- Prompt injection: untrusted content such as a web page or an email tells the model to ignore its earlier instructions.
- Ordinary mistakes: the model misreads a request, picks the wrong tool, or fills in a wrong argument.
- Long context: an early instruction gets less weight as the conversation grows.
- Model changes: a new model version follows the same prompt a little differently.
A control is something that holds even when the model is wrong or hostile. For that reason, authorization has to run in ordinary code that sits between the model's output and the tool. This is called deterministic enforcement. "Deterministic" means the same request always gets the same decision, and no model output can talk the code into a different one.
Prompts still have a role. A good prompt reduces how often the model attempts something forbidden, which saves tokens and avoids noisy refusals. Treat the prompt as guidance and the code as the guarantee.
Where the enforcement point sits
The model never runs a tool. It produces a structured request, such as a tool name and a JSON object of arguments. Your runtime decides what happens next. That gap is where you place the checks.
Notice that a denial goes back to the model as an error message. The model can then try something else, but each new attempt faces the same checks. The checks are the same no matter how persuasive the model's request is.
Check 1: the per-task allowlist
The first check asks whether this task is allowed to call this tool at all. The runtime keeps a registry of every tool it knows about, and each task supplies its own set of permitted names.
def read_file(path: str) -> str:
return f"contents of {path}"
def search_docs(query: str) -> str:
return f"results for {query}"
def send_email(to: str, body: str) -> str:
return f"sent to {to}"
TOOLS = {
"read_file": read_file,
"search_docs": search_docs,
"send_email": send_email,
}
def run_tool_call(name: str, args: dict, allowed: set[str]):
if name not in allowed:
raise PermissionError(f"tool {name!r} is not allowed for this task")
return TOOLS[name](**args)
# A documentation-answering task gets read-only tools only.
result = run_tool_call(
"search_docs",
{"query": "rotate API keys"},
allowed={"search_docs", "read_file"},
)
print(result)If the model asks for send_email in this task, run_tool_call raises PermissionError. The model cannot add a name to allowed, because allowed is chosen by your code when the task starts, not by the model.
Two details matter here:
- Decide the allowlist from the task and the user, not from the conversation. If the allowlist can change in response to model output, the model can change it.
- Fail closed. An unknown tool name or a missing allowlist should produce a denial. Use
name not in allowed, never a check that only blocks names on a denylist.
Check 2: argument constraints inside the tool
An allowed tool can still be dangerous with the wrong arguments. A file reader is safe in one directory and a leak in another. So the tool itself, or a wrapper around it, must validate what it receives.
from pathlib import Path
ALLOWED_ROOT = Path("/srv/agent/workspace").resolve()
def read_file(path: str) -> str:
target = (ALLOWED_ROOT / path).resolve()
if not target.is_relative_to(ALLOWED_ROOT):
raise PermissionError("path is outside the workspace")
return target.read_text()This code does three things that a prompt cannot:
- It joins the requested path to a fixed root. An absolute path such as
/etc/passwdreplaces the root when joined with/inpathlib, but the next step catches it. - It calls
resolve(), which collapses..segments and follows symbolic links, so../../etc/passwdis turned into its real location before the check. - It compares the resolved path to the root with
is_relative_to. This is more reliable than checking whether the string starts with the root, because a string check would wrongly accept/srv/agent/workspace-secrets.
The same pattern applies to other argument types. Prefer rules that describe what is allowed over rules that describe what is forbidden:
| Argument type | Weak check | Stronger check |
|---|---|---|
| File path | Reject strings containing `..` | Resolve, then require the result to be inside one root |
| Email recipient | Trust the model's address | Require the domain to be in an allowed set |
| SQL | Ask the model for "safe" SQL | Offer fixed parameterized queries; the model supplies only the parameter values |
| URL | Block a few bad hosts | Allow only listed hosts, and check again after redirects |
| Record ID | Accept any ID | Check the record belongs to the current user |
The last row deserves attention. Authorization depends on who the agent is acting for. A tool that fetches an order by ID must confirm that the order belongs to the requesting user, using the user's identity from your session and not an identity the model supplies in an argument.
Check 3: identity comes from the session, not the model
A common bug is a tool with a user_id parameter that the model fills in. An injected instruction can then say "use user_id 1" and read someone else's data. The fix is to take identity from the runtime context and keep it out of the tool schema.
from dataclasses import dataclass
@dataclass(frozen=True)
class Context:
user_id: str
allowed_tools: frozenset[str]
ORDERS = {
"o-1": {"owner": "alice", "total": 40},
"o-2": {"owner": "bob", "total": 15},
}
def get_order(ctx: Context, order_id: str) -> dict:
order = ORDERS.get(order_id)
if order is None or order["owner"] != ctx.user_id:
# Same error for "missing" and "not yours" avoids revealing which IDs exist.
raise PermissionError("order not found")
return order
alice = Context(user_id="alice", allowed_tools=frozenset({"get_order"}))
print(get_order(alice, "o-1")) # works
# get_order(alice, "o-2") # raises PermissionErrorThe model chooses order_id. It never chooses ctx. Using the same error for a missing record and a forbidden one stops the model, or an attacker steering it, from probing which IDs exist.
Check 4: approval for high-risk tools
Some actions are hard to undo or affect other people. For those, the runtime pauses and asks an approval callback, such as a person in a UI, before running the tool. Chapter coverage of when to require approval comes later. Here the point is where the check lives: in code, outside the model.
HIGH_RISK = {"send_email", "delete_record"}
def execute_with_approval(name, args, tools, approve):
if name in HIGH_RISK and not approve(name, args):
return {"status": "denied", "tool": name}
return {"status": "ok", "result": tools[name](**args)}The approver sees the exact arguments. If the human approves one set of arguments and the code runs another, the approval means nothing, so execute precisely what was shown.
Putting the checks together
Combine the checks into one function so no tool call can reach a tool without passing all of them. Keep this function small and test it directly.
def authorize_and_run(ctx, name, args, tools, approve, validators):
if name not in ctx.allowed_tools:
return {"status": "denied", "reason": "tool not allowed"}
validate = validators.get(name)
if validate is None:
return {"status": "denied", "reason": "no validator registered"}
try:
clean = validate(ctx, args)
except (PermissionError, ValueError) as exc:
return {"status": "denied", "reason": str(exc)}
if name in HIGH_RISK and not approve(name, clean):
return {"status": "denied", "reason": "approval refused"}
return {"status": "ok", "result": tools[name](ctx, **clean)}Two design choices keep this safe. A tool with no registered validator is denied, so adding a new tool without constraints fails closed instead of silently running. And the tool runs with clean, the validated copy of the arguments, not the original dictionary the model produced.
Credentials as a second layer
Code checks can have bugs. A second layer limits what a tool can do even if a check is wrong. Give the tool credentials that permit only its job. For an AWS-backed tool that reads published summaries, this policy allows one action on one prefix:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::example-reports-bucket/public-summaries/*"
}
]
}If a path check fails to catch something, the credential still cannot read other buckets, write objects, or list anything. The later chapter on scoped credentials covers short-lived and per-user tokens in detail.
Common errors
- Putting rules in the prompt only. The model can ignore them, so they do not count as enforcement.
- Letting the model pass identity. Fields like
user_idorrolein a tool schema let the model act as someone else. - Denylists. Blocking a list of bad values always misses one. Allow known good values.
- Checking before normalizing. Paths, URLs, and encodings must be canonical before you compare them.
- Trusting tool output as policy. Text returned by a tool is untrusted data and must not change the allowlist.
- Checks that fail open. Wrap them so an exception or a missing rule results in denial.
- Different code paths. If one entry point skips the policy function, an attacker will use that one.
Exercises
Exercise
A system prompt says "Only read files inside /srv/agent/workspace." The agent also has a read_file tool that opens any path it receives. Why is this not an adequate control, and what is the smallest code change that fixes it?
Show answer
The sentence is guidance to the model, and prompt injection or a plain mistake can lead the model to request another path, which the tool would open. Fix it in the tool: resolve the joined path with Path.resolve() and raise PermissionError unless isrelativeto(ALLOWED_ROOT) is true.
Exercise
A getorder tool takes both orderid and user_id as model-supplied arguments and returns the order if the two match. What attack does this allow, and how do you redesign it?
Show answer
An injected instruction can make the model supply another user's userid along with a matching orderid, so the match check passes for the wrong person. Remove user_id from the tool schema, read the identity from the runtime context created by your authentication layer, and compare the order's owner to that identity.
Exercise
In authorizeandrun, why is a tool with no registered validator denied instead of allowed?
Show answer
The check fails closed. A newly added tool without constraints cannot run until someone writes its validator, so forgetting a rule produces a visible denial and not a silent gap in protection.