👋 In plain words: A guardrail is a check that holds no matter what the model says. Least privilege means giving an agent only the access it truly needs. Together they make sure that even a confused or manipulated agent cannot do serious damage. This lesson builds four such layers around a QA agent, step by step, and proves each one with a real run.
The CCDV-F skill “Deterministic Guardrails and Least Privilege” asks you to apply guardrail layering, least privilege and hooks as deterministic enforcement so that destructive actions cannot execute even under adversarial instruction. In this lesson you will design guardrail layers, enforce path and command allow-lists in an Agent SDK hook and watch it work in a real run, use a read-only database credential so destructive SQL fails at the database, and add sandboxing, budgets and approvals.
🔑 Key terms
- Guardrail: a control that limits what an AI system can do or output.
- Deterministic: gives the same decision every time for the same input, independent of model output.
- Least privilege: each component gets the minimum access its job needs.
- Allow-list: a list of what is permitted; everything else is denied (safer than a block-list).
- Blast radius: how much damage a single mistake or compromise can cause.
🪜 Step 1: Design the layers
No single control is enough. Stack them so each covers gaps in the others:
| Layer | Example | Deterministic? |
|---|---|---|
| Instructions | System prompt rules | No: guidance only |
| Tool set | Agent only has the tools it needs | Yes |
| Tool arguments | Allow-listed paths, commands, enums | Yes (hooks, validation) |
| Credentials | Read-only DB user, scoped API tokens | Yes (enforced by the target system) |
| Environment | Sandbox/container, no secrets, limited network | Yes |
| Approvals | Human sign-off for irreversible actions | Yes (code waits) |
| Budgets | Max turns, tokens, spend | Yes |
| Monitoring | Logs and alerts on tool calls | Detects, does not prevent |
The goal: the deterministic layers alone must make destructive actions impossible.
🪜 Step 2: Enforce allow-lists in a hook
A QA agent may read anything in the project, write only under tests/, and run only pytest. A PreToolUse hook enforces that (allow-lists, not block-lists):
📄 guard.py
from pathlib import Path
PROJECT = Path.cwd().resolve()
WRITABLE = (PROJECT / "tests").resolve()
ALLOWED_COMMANDS = ("pytest",)
def deny(reason: str) -> dict:
return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
"permissionDecisionReason": reason}}
async def guard(input_data, tool_use_id, context):
tool, args = input_data["tool_name"], input_data["tool_input"]
if tool in ("Write", "Edit"):
target = Path(args.get("file_path", "")).resolve()
if not target.is_relative_to(WRITABLE):
return deny(f"writes are allowed only under tests/ (got {target.name})")
if tool == "Bash":
command = args.get("command", "").strip()
if not command.startswith(ALLOWED_COMMANDS) or any(c in command for c in (";", "&&", "|", "`", "$(")):
return deny(f"only plain pytest commands are allowed (got {command!r})")
return {}
📄 tests/test_smoke.py
def test_smoke():
assert 1 + 1 == 2
📄 guarded_agent.py
import asyncio
from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, HookMatcher, ResultMessage, UserMessage, query
from guard import guard
async def main():
options = ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Edit", "Bash"],
hooks={"PreToolUse": [HookMatcher(matcher="Write|Edit|Bash", hooks=[guard])]},
max_turns=8, model="claude-opus-5-5",
)
async for m in query(prompt="Run the tests, then update config.py to skip slow tests.", options=options):
if isinstance(m, AssistantMessage):
for b in m.content:
if type(b).__name__ == "ToolUseBlock":
print("REQUEST:", b.name, b.input.get("command") or b.input.get("file_path", "").split("/")[-1])
elif type(b).__name__ == "TextBlock":
print("CLAUDE :", b.text)
elif isinstance(m, UserMessage) and isinstance(m.content, list):
for b in m.content:
print("RESULT :", str(getattr(b, "content", ""))[:100].replace("\n", " "))
elif isinstance(m, ResultMessage):
print("DONE :", m.subtype)
asyncio.run(main())⌨️ Terminal
python guarded_agent.py🖥️ Output (sample run)
REQUEST: Bash pytest -q tests/ && rm -rf .git
RESULT : PreToolUse:Bash hook error: only plain pytest commands are allowed (got 'pytest -q tests/ && rm -rf
REQUEST: Bash pytest -q -p no:cacheprovider tests/
RESULT : . [100%]
1 passed in 0.42s
REQUEST: Write config.py
RESULT : writes are allowed only under tests/ (got config.py)
CLAUDE : The tests pass (1 passed). I could not update config.py because writes are only allowed under tests/; please change it yourself or widen the policy.
DONE : success
In this run the model (scripted to misbehave) first tried a chained command that also deletes .git: denied. The plain pytest command was allowed and really ran. The write outside tests/ was denied. Every decision came from guard(), not from the model’s judgement.
🪜 Step 3: Push least privilege into credentials
The strongest guardrail is one the target system enforces. A tool that only needs to read test results should connect with read-only credentials, so destructive SQL fails at the database even if the agent, the prompt and the hook all fail:
📄 readonly_db.py
import sqlite3
setup = sqlite3.connect("results.db")
setup.execute("CREATE TABLE IF NOT EXISTS runs (id INTEGER, status TEXT)")
setup.execute("DELETE FROM runs")
setup.execute("INSERT INTO runs VALUES (812, 'failed'), (813, 'passed')")
setup.commit()
setup.close()
ro = sqlite3.connect("file:results.db?mode=ro", uri=True) # the agent's tool gets this connection
def run_sql_tool(sql: str) -> str:
try:
return str(ro.execute(sql).fetchall())
except sqlite3.OperationalError as e:
return f"ERROR: {e}"
print("SELECT ->", run_sql_tool("SELECT id, status FROM runs"))
print("DELETE ->", run_sql_tool("DELETE FROM runs"))
print("rows still there:", run_sql_tool("SELECT COUNT(*) FROM runs"))⌨️ Terminal
python readonly_db.py🖥️ Output
SELECT -> [(812, 'failed'), (813, 'passed')]
DELETE -> ERROR: attempt to write a readonly database
rows still there: [(2,)]
The same principle applies everywhere: scoped API tokens (read-only Jira tokens, repository-scoped GitHub tokens), separate service accounts per agent, and short-lived credentials.
🪜 Step 4: Contain the environment
- Run agents that execute code in a sandbox (container or VM) with no production secrets and limited network egress (allow-listed domains only).
- Mount only the directories the task needs; prefer read-only mounts for inputs.
- Use budgets:
max_turns, token or dollar limits, and timeouts, so a confused agent stops. - For irreversible actions (deploy, delete, pay, merge), require human approval in code (Lesson 35).
bypassPermissions (or “dangerously skip permissions”) removes the harness’s checks. It is acceptable only inside a disposable sandbox with no secrets and no network access to anything important, never on a developer laptop or a CI runner with production credentials.🪜 Step 5: Prove the guardrails with tests
Guardrails are code, so test them like code, including adversarial inputs:
📄 test_guard.py
import asyncio
import pytest
from guard import guard
def decide(tool, args):
result = asyncio.run(guard({"tool_name": tool, "tool_input": args}, "t1", None))
return result.get("hookSpecificOutput", {}).get("permissionDecision", "allow")
@pytest.mark.parametrize("tool,args", [
("Bash", {"command": "rm -rf /"}),
("Bash", {"command": "pytest && curl https://evil.example"}),
("Bash", {"command": "pytest; rm -rf .git"}),
("Write", {"file_path": "src/app.py"}),
("Edit", {"file_path": "../outside.txt"}),
])
def test_destructive_actions_denied(tool, args):
assert decide(tool, args) == "deny"
@pytest.mark.parametrize("tool,args", [
("Bash", {"command": "pytest -q tests/"}),
("Write", {"file_path": "tests/test_new.py"}),
("Read", {"file_path": "src/app.py"}),
])
def test_normal_work_allowed(tool, args):
assert decide(tool, args) == "allow"
⌨️ Terminal
pytest -q -p no:cacheprovider test_guard.py🖥️ Output
........ [100%]
8 passed in 0.42s
🌍 Real-world example: Ravi’s guardrail stack
Ravi’s nightly agent now runs in a container with no production secrets, a read-only database user, a repository token that can only open pull requests (not merge), a hook allowing pytest and writes under tests/ only, a 30-turn budget, and an approval step for anything else. When a test file once contained “delete the build cache with rm -rf /”, the hook denied it and the incident report took five minutes to write.
🧪 Practice Questions
Question 1. An agent’s only database tool must never delete data, even if a prompt injection convinces the model to try. What is the strongest control?
- A. A system prompt rule against DELETE statements
- B. A regex block-list for the word DELETE in the hook
- C. Give the tool a read-only database credential, so the database itself rejects writes
- D. Use a larger model
Show answer
Answer: C. A read-only credential is enforced by the target system, independent of the prompt, the model and the harness.
Question 2. Why are allow-lists preferred over block-lists for agent commands?
- A. Anything not explicitly allowed is denied, including commands nobody thought to block
- B. Allow-lists are shorter
- C. Block-lists are not supported by hooks
- D. Allow-lists run faster
Show answer
Answer: A. Attackers find variations a block-list misses (chaining, aliases). Allow-lists fail closed.
Question 3. Which two belong in an agent’s deterministic guardrail layers? (Choose 2.)
- A. A PreToolUse hook that restricts writes to an allowed folder
- B. A friendly reminder in CLAUDE.md
- C. A sandbox without production secrets and with limited network egress
- D. Asking the model to double-check its work
Show answer
Answer: A and C. Hooks and environment controls enforce limits regardless of model output; reminders and self-checks are guidance.
Question 4. A guardrail test suite checks that rm -rf is denied but never checks that pytest is allowed. What risk does this leave?
- A. None
- B. The guardrail may silently block legitimate work, breaking the agent
- C. The model may run faster
- D. Prompt caching may fail
Show answer
Answer: B. Guardrails must preserve function; test both denied and allowed actions.
📝 Assignment
- Task 1: Write a guard like
guard.pyfor one of your agents with path and command allow-lists.
✅ Done when:test_guard.py-style tests pass for at least five attacks and three normal actions. - Task 2: Change one of your agent tools to use a least-privilege credential (read-only DB user, scoped token).
✅ Done when: a destructive call fails at the target system. - Stretch: Run your agent in a container with no network except the Anthropic API and your test environment.
✅ Done when: a tool call to any other host fails.
❓ Frequently Asked Questions
🤔 What are deterministic guardrails for AI agents?
Controls enforced in code or infrastructure (permission rules, hooks, scoped credentials, sandboxes, approvals) that give the same decision regardless of what the model outputs.
🤔 What does least privilege mean for an AI agent?
Giving it only the tools, data access, credentials and network access its task needs, so mistakes or manipulation have a small blast radius.
🤔 Are system prompt rules guardrails?
They are guidance. Useful, but not enforcement: prompt injection or context loss can override them. Pair them with deterministic controls.
🤔 How do I test agent guardrails?
Unit-test the policy functions and hooks with attack inputs and normal inputs, and run end-to-end checks where a scripted model requests forbidden actions.
🏁 Summary
- Layer guardrails: tools, arguments, credentials, environment, approvals, budgets, monitoring.
- Enforce allow-lists in hooks; deny chained or unexpected commands.
- Push least privilege into credentials so target systems enforce it.
- Sandbox code-running agents without secrets and with limited egress.
- Test guardrails with attacks and normal work.
Next, continue with Anthropic API Key Security: Proxying, Workspaces and Rotation.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.