Sub topic 14
Reviewing and testing an agent's permissions
This chapter assumes you have read the earlier chapters on tool scoping, deterministic enforcement, argument constraints, scoped credentials, and approval. You should be able to read short Python and JSON snippets and run pytest. Everything so far was about building limits. This chapter covers how to check that the limits exist, still hold, and fail closed.
Why permissions need review and tests
An agent's permissions drift. Someone adds a tool for a demo and never removes it. A credential gets widened to fix a failing job. A new model version starts calling tools in different ways. A prompt edit changes which tools the agent tries to use.
Two kinds of checks cover this:
- Review is a human reading the agent's permissions and asking whether each one is still needed.
- Testing is code that tries to break the limits and fails the build when it succeeds.
Review catches excess that nobody noticed. Tests catch regressions and prove that the enforcement layer behaves as designed. You need both.
Step 1: Build a permission inventory
You cannot review what you have not listed. For each agent, write down every way it can affect the world. Use one row per permission:
| Layer | Question to answer | Example finding |
|---|---|---|
| Tools | Which tools are registered, and which does this task allow? | `send_email` is registered but the task never sends mail |
| Arguments | What does each tool accept? | `read_file` takes any string, validated only by a path check |
| Credentials | Which identity does each tool use, and how long does it live? | One long-lived admin key shared by all tools |
| Data | What private data can the agent read? | Whole bucket instead of one prefix |
| Egress | Where can output or network traffic go? | Unrestricted outbound HTTP from the sandbox |
| Autonomy | Which actions run without a person? | `delete_record` runs unattended |
Keep the inventory in the repository, next to the agent's code, so changes to it appear in code review. A short machine-readable form works well, because a test can compare it with reality.
{
"agent": "docs-answerer",
"allowed_tools": ["search_docs", "read_file"],
"high_risk_tools": [],
"credentials": [
{
"tool": "read_file",
"identity": "docs-reader",
"scope": "read-only, /srv/agent/workspace",
"max_lifetime_minutes": 15
}
],
"egress": "none"
}Step 2: Review against the task, not against the current setup
The common review mistake is asking "is anything here dangerous?" The better question is "would the task fail if I removed this?" Go through the inventory and apply these checks:
- Tools. For each allowed tool, name the task step that needs it. If you cannot, remove it.
- Permissions. Compare each credential's policy with what the tool actually does. An IAM policy that allows
s3:*for a tool that only callsGetObjectis excess. Use your cloud provider's access-analysis features, such as AWS IAM Access Analyzer's unused-access findings, to see which granted actions were never used. - The three-way combination. Check whether any single agent run can combine private data, untrusted input, and an outbound channel. If it can, one injected instruction can leak data.
- Autonomy. For each action without approval, ask what happens if the model chooses it with attacker-supplied arguments.
- Limits and logs. Confirm that rate limits, budgets, and audit logging exist for every tool, including the low-risk ones.
Review again whenever a tool, credential, model, or system prompt changes. Also review on a calendar, for example every quarter, to catch permissions that were never touched but are no longer needed.
Step 3: Deterministic tests for the enforcement layer
The enforcement code is ordinary code, so test it like ordinary code. These tests do not involve a model. They check the allowlist, the path check, and the approval gate directly.
The following file contains the tools from earlier chapters and the tests. Save it as test_permissions.py and run pytest. It needs Python 3.9 or later.
from pathlib import Path
import pytest
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()
def search_docs(query: str) -> str:
return f"results for {query}"
TOOLS = {"read_file": read_file, "search_docs": search_docs}
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)
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)}
@pytest.fixture
def workspace(tmp_path, monkeypatch):
root = (tmp_path / "workspace").resolve()
root.mkdir()
(root / "guide.txt").write_text("rotate keys monthly")
(tmp_path / "secret.txt").write_text("top secret")
monkeypatch.setitem(globals(), "ALLOWED_ROOT", root)
return root
def test_unlisted_tool_is_refused():
with pytest.raises(PermissionError):
run_tool_call("send_email", {"to": "[email protected]"}, allowed={"search_docs"})
def test_listed_tool_runs():
assert run_tool_call("search_docs", {"query": "x"}, {"search_docs"}) == "results for x"
def test_file_inside_workspace_is_readable(workspace):
assert read_file("guide.txt") == "rotate keys monthly"
@pytest.mark.parametrize("bad", ["../secret.txt", "/etc/passwd", "a/../../secret.txt"])
def test_paths_outside_workspace_are_refused(workspace, bad):
with pytest.raises(PermissionError):
read_file(bad)
def test_symlink_escape_is_refused(workspace):
(workspace / "link.txt").symlink_to(workspace.parent / "secret.txt")
with pytest.raises(PermissionError):
read_file("link.txt")
def test_denied_approval_never_runs_the_tool():
calls = []
tools = {"delete_record": lambda record_id: calls.append(record_id)}
out = execute_with_approval("delete_record", {"record_id": 7}, tools, lambda n, a: False)
assert out == {"status": "denied", "tool": "delete_record"}
assert calls == []Three details matter here:
- The tests include refusals, not only successes. A permission test that only checks the happy path proves nothing about limits.
- The symlink test checks an edge case. The
resolve()call follows links, so the escape is caught. A check based on string prefixes would miss it. - The last test asserts that the tool function was never called. Checking the returned status alone would not catch a bug that runs the action and then reports denial.
Step 4: Adversarial tests that simulate a compromised model
Deterministic tests show that the gate works when called. Adversarial tests show that the whole loop holds when the model misbehaves. The key idea: you do not need a real model to test enforcement. Replace it with a script that issues the worst calls an injection could cause, and check that the runtime refuses them.
def run_script(calls, allowed):
"""Run scripted model tool requests; return the outcome of each."""
outcomes = []
for name, args in calls:
try:
run_tool_call(name, args, allowed)
outcomes.append("ok")
except (PermissionError, KeyError, TypeError):
outcomes.append("refused")
return outcomes
def test_injected_instructions_cannot_widen_the_tool_set():
poisoned_doc_says = [
("search_docs", {"query": "keys"}),
("send_email", {"to": "[email protected]", "body": "contents"}),
("read_file", {"path": "../../etc/shadow"}),
]
outcomes = run_script(poisoned_doc_says, allowed={"search_docs"})
assert outcomes == ["ok", "refused", "refused"]Add to this suite over time. Good test cases come from:
- Known injection patterns, such as instructions hidden in a retrieved web page, a PDF, or a tool result.
- Argument abuse: traversal paths, oversized inputs, wildcard values, and extra unexpected parameters.
- Past incidents and near-misses from your audit logs.
- Cross-user cases: user A's session asking for user B's record.
Also run end-to-end exercises with the real model and a staged environment. Plant a canary, a fake secret such as a unique token in a file the agent should not read. Feed the agent poisoned input that asks it to find and send the token. If the canary ever appears in an outbound request or a log, you have found a gap. These runs are non-deterministic, so repeat them and track the failure rate. They complement the scripted tests and do not replace them.
Step 5: Test the credential layer separately
Code-level checks do not prove that the cloud policy is narrow. Test it with the credentials the tool really uses. For the S3 policy from earlier, which allows only s3:GetObject on public-summaries/*, check that:
- Reading an object under
public-summaries/succeeds. - Reading an object elsewhere in the bucket returns
AccessDenied. - Listing the bucket, writing, and deleting each return
AccessDenied. - An expired token stops working after its lifetime ends.
These checks catch the case where a second, broader policy is also attached to the same role. The effective permission is the union of all attached policies, so reading the one policy file is not enough.
Step 6: Use audit logs as a test oracle
Audit logs record what the agent did. Compare them with the inventory. Look for these signals:
- Tool calls that were refused. A steady stream of refusals suggests injection attempts or a prompt that encourages wrong tool use.
- Calls to tools not in the task's allowlist, which would mean enforcement is missing somewhere.
- Allowed permissions that never appear in the logs. These are candidates for removal.
- Approval requests that are always approved within seconds. The reviewer may be clicking through, which makes the gate decorative.
Common errors
| Mistake | Why it hurts | Fix |
|---|---|---|
| Testing only that allowed calls work | Limits can be missing and no test fails | Add a refusal test for each limit |
| Testing with the real model only | Results vary, so a pass proves little | Script the model for enforcement tests |
| Reading one policy and calling it reviewed | Attached policies combine | Check the effective permissions |
| Reviewing once at launch | Permissions drift | Review on every change and on a schedule |
| Treating a refusal as a bug | Refusal is the control working | Alert on refusals, but do not remove the check |
Exercise
Your agent summarizes support tickets and has three tools: read_ticket, search_docs, and send_email. The task never sends mail. Name two checks you would run, one review step and one automated test, and say what result each should produce.
Show answer
Review step: ask which task step needs send_email. None does, so remove it from the allowlist and from the tool registry, and drop any mail-sending credential. Automated test: script a model that requests send_email with an attacker address, run it through the runtime with allowed={"read_ticket", "search_docs"}, and assert the outcome is a PermissionError refusal and that the email function was never called.
Exercise
A teammate says the path-restricted read_file tool is safe because a test confirms guide.txt can be read. What is missing, and name one input you would add?
Show answer
The test covers only the permitted case. It needs refusal tests for paths outside the workspace, for example ../secret.txt, an absolute path like /etc/passwd, and a symlink inside the workspace that points outside it. Each must raise PermissionError.