Module 07 · Lesson 7.2
Tool Permission Boundaries and Sandboxing
On this page
- What you will learn
- Why tools need permission boundaries
- Least privilege for each tool
- Allowlists and deny by default
- A file-reading tool with a folder allowlist in Python
- Sandboxing risky work
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
When you give a house guest a key, you do not hand over the keys to the shed, the car and the safe as well. You give the one key they need, and perhaps only for the weekend. If they lose it, the damage is small.
An AI agent should be treated like that guest. Its tools are its keys. This lesson shows how to decide which actions and resources each tool may touch, how to say "no" by default, and how to run risky work in a sandbox, an isolated space where mistakes cannot spread. Most of it needs no coding. One short Python example checks file paths.
What you will learn
- Apply least privilege to each tool, with allowlists for actions and resources.
- Explain deny by default and read-only by default in plain words.
- Describe what a sandbox is and when risky work belongs in one.
- Run a Python file-reading tool that blocks paths outside one folder.
Before you start
- Prompt Injection and Untrusted Tool Outputs and Module 3's Authentication, Secrets and Least-Privilege Access.
- No coding experience is needed for most of this lesson.
- Optional: Python 3.10 or later, if you want to run the example yourself.
Why tools need permission boundaries
The last lesson showed that you cannot always stop an agent being tricked. A permission boundary is the second line of defence. It is a limit, enforced by your code, on what a tool can do even when the model asks for more.
Picture a library card. It lets you borrow books. It does not let you reach into the cash drawer, however politely you ask. The limit is in the system, not in your good manners.
- Least privilege
- Give each tool only the access it needs for its job, and nothing more. A tool that reads orders should not be able to edit them.
- Allowlist
- A written list of what is allowed. Anything not on the list is refused. Example: the only allowed file folder is kb_files.
- Deny by default
- If a rule does not clearly say "yes", the answer is "no". New tools, new actions and new files start blocked.
- Sandbox
- A fenced-off place where risky work runs with no access to your secrets, your files or the wider network. If something goes wrong, it stays inside the fence.
Least privilege for each tool
Go through your tools one at a time and ask three questions. What can it read? What can it change? Which resources (orders, files, pages) can it reach? Write the answers in a table.
| Tool | Allowed actions | Allowed resources | Not allowed |
|---|---|---|---|
| lookup_order | Read one order | Order ids matching ^QF-[0-9]{4}$ | Editing, listing every order |
| request_return | Create a PENDING request | One order, reason damaged, wrong_size or changed_mind | Approving, refunding |
| search_help | Read help pages | Pages with audience customer, at most 3 results | Staff pages KB-14 to KB-16 |
| read_doc | Read one document | Ids matching ^RS-[0-9]{2}$ | Any other file path |
| save_report | Save a finished report | The reports folder only | Overwriting other files; runs only after approval |
Read-only by default
Start every tool as read-only. Add a write action only when the agent's job truly needs it, and then put approval in front of it, as you did in Human-in-the-Loop Approval and Escalation. A tool that cannot write cannot be tricked into writing.
Split one wide tool into narrow ones
- Avoid a general tool such as
run_query(sql). It can reach everything. - Prefer
lookup_order(order_id), which can reach one order. - Avoid a tool that accepts any web address. Prefer one that only talks to your own service.
- Give the tool its own credentials with limited rights, not an all-powerful key.
Allowlists and deny by default
There are two ways to guard a door. A blocklist says "these people may not enter". An allowlist says "only these people may enter". The blocklist always misses someone you did not think of. The allowlist is safer because new things are blocked automatically.
| Approach | Example | Weakness |
|---|---|---|
| Blocklist | Refuse paths that contain "secret" | A file named "keys.txt" gets through. |
| Allowlist | Allow only files inside kb_files that end in .txt | Very little. New files are blocked until you allow them. |
Three allowlists to write for every tool
- Actions: which operations may happen (read, create a pending request).
- Resources: which things may be touched (ids in a known format, one folder, one table).
- Values: which argument values are valid (a reason must be one of three words, not free text).
Argument checks are covered in Designing Tool Schemas and Validating Arguments. Here the idea is the same, applied to permissions: the tool checks the request against the list and refuses anything else, returning an error such as {"error": "..."}.
A file-reading tool with a folder allowlist in Python
File tools are a classic weak spot. A model asks for returns.txt. An attacker makes it ask for ../secret.txt. The two dots mean "go up one folder", so the path climbs out of the allowed folder. This trick is called path traversal.
The fix is to turn the requested path into its real, full form first (this is called resolving it), and then check that it still sits inside the allowed folder. Do not try to spot ".." in the text. Resolve first, then check.
from pathlib import Path
BASE = Path("kb_files").resolve()
def setup_demo():
BASE.mkdir(exist_ok=True)
(BASE / "returns.txt").write_text("Returns within 30 days.", encoding="utf-8")
Path("secret.txt").write_text("API_KEY=do-not-share", encoding="utf-8")
def read_file(name):
path = (BASE / name).resolve()
if not path.is_relative_to(BASE):
return {"error": "path is outside the allowed folder"}
if path.suffix != ".txt":
return {"error": "only .txt files may be read"}
if not path.is_file():
return {"error": "file not found"}
return {"text": path.read_text(encoding="utf-8")}
setup_demo()
for name in ["returns.txt", "../secret.txt", "sub/../../secret.txt", "missing.txt", "returns.md"]:
print(f"{name!r:24} -> {read_file(name)}")Runs offline with Python 3.9 or later. It creates a small demo folder next to the script.
What each part does
Path("kb_files").resolve()is the one allowed folder, written as a full path.setup_democreates the folder and two files: one inside it and one outside it, so the test has something to protect.(BASE / name).resolve()joins the requested name to the folder and works out the real location. The..parts are followed here, so a sneaky path shows its true place.path.is_relative_to(BASE)isTrueonly when the real location is inside the allowed folder. This is the boundary check.path.suffix != ".txt"is a second allowlist: only text files.path.is_file()checks the file exists. Every refusal returns a small error dictionary, like the tool errors in Module 3.- The loop tries five names, one good and four that should fail.
'returns.txt' -> {'text': 'Returns within 30 days.'}
'../secret.txt' -> {'error': 'path is outside the allowed folder'}
'sub/../../secret.txt' -> {'error': 'path is outside the allowed folder'}
'missing.txt' -> {'error': 'file not found'}
'returns.md' -> {'error': 'only .txt files may be read'}Both climbing attempts were refused, even the one hidden behind a fake sub-folder. A full path such as /etc/passwd is also refused, because joining an absolute path replaces the base and the check then fails.
Sandboxing risky work
Some tools are risky by nature. Running code the model wrote, opening unknown files or fetching web pages can all go wrong. For these, use a sandbox. Think of a chemistry lab fume cupboard: the experiment happens inside glass, and the fumes stay there.
In practice a sandbox is often a container or a virtual machine. Both are ways to run a program inside its own small, separate computer-like space. Which one to choose depends on your platform. Your security team can advise.
What a good sandbox gives you
- No secrets: the API key and other credentials are not inside it.
- No network, or a short allowlist of sites: it cannot send data out to a stranger.
- Limited files: it sees only a scratch folder that you can throw away.
- Limits on time and memory: a runaway program is stopped.
- Fresh each time: nothing carries over from one run to the next.
Conclusion and your next step
Give every tool one narrow lane. Write allowlists for actions, resources and values. Start read-only and deny by default. Check file paths after resolving them. Put risky work in a sandbox that holds no secrets.
Your next step: fill in the table from this lesson for your own agent, with one row per tool. Cross out any cell you cannot justify. Then continue to Data Privacy, Sensitive Information and Secure Logging to keep personal data out of prompts and logs.
For more on tool design, read Connecting REST APIs and Internal Services and the Agent Launch Safety Checklist.
Common errors and how to fix them
A file tool lets the agent read files outside its folder.
Why it happens: The check looked for the text ".." in the path instead of resolving the real location first.
Fix: Resolve the path, then check it is inside the allowed folder with is_relative_to.
A tool can both read and write, though the agent only needs to read.
Why it happens: One broad tool was easier to write than two narrow ones.
Fix: Split it. Give the agent the read-only version and keep writes behind approval.
The block rules keep growing and attackers still get through.
Why it happens: A blocklist names bad things, and attackers find new ones.
Fix: Switch to an allowlist so anything new is refused by default.
The sandbox still leaks data.
Why it happens: The API key was passed in, or the network was fully open.
Fix: Leave secrets outside, close the network or allow only named sites, and delete the sandbox after use.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Add a size limit and a folder check to a report tool
Quillfeather's save_report tool writes a text report. Write the boundary rules for it, and change read_file in the lesson's example so it also refuses files larger than 2000 characters.
You will need
- Reports may only be saved in a folder called reports.
- A title may contain only letters, digits, spaces and dashes.
- The tool runs only after a person approves.
- Use the lesson's read_file function as your starting point.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- Check the title with a pattern such as ^[A-Za-z0-9 -]+$ before building any path.
- After reading a file, compare len(text) with 2000.
- Fail closed: a missing approval means no save.
Show a model answer
A strong answer lists: action = save one report; folder = reports only; title values = letters, digits, spaces and dashes; approval = required, and without it the tool returns {"error": "approval required"} and writes nothing. The title check blocks slashes and dots, so the path cannot climb out of the folder. For the size limit, read the text, return {"error": "file too large"} when len(text) is above 2000, and otherwise return the text. Both checks run before the model's request has any effect, so a tricked agent still cannot save outside the folder.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. A path that looks innocent can lead outside the folder. Resolving shows where it really goes. Searching for the characters ".." is tempting, but attackers can hide the same escape in other ways.
Show the answer and explanation
Answer: B. It describes how rules are written. Safe behaviour is the starting point and every permission must be added on purpose. The first option confuses it with a very cautious agent, which is a different matter.
Show the answer and explanation
Answer: B. A sandbox contains mistakes only when it holds nothing valuable. Giving it the real key is tempting for convenience, but it removes the protection.
Frequently asked questions
What is least privilege for an AI agent?
It means each tool can do only what its job needs. A tool that checks order status reads one order and cannot edit, delete or list others. If the agent is tricked, the damage stays small.
What is a sandbox in plain words?
It is a fenced-off place where a program runs with its own limited files, no secrets and little or no network access. Like a fume cupboard in a lab, the experiment stays inside.
Is checking for "../" in a file path enough?
No. Resolve the path to its real location and check that it sits inside the allowed folder. Text checks miss other ways to climb out of a folder, such as absolute paths and shortcuts.
Do I need Docker to sandbox an agent?
Not always. Many agents only need narrow tools and never run risky code. When you do run code or open unknown files, a container or virtual machine is a common choice, and your platform team can help you pick one.
- Written by
- PromptFable Editorial
- Last updated 18 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- LLM06:2025 Excessive Agency(opens in a new tab)
OWASP Foundation · Official documentation · Explains why tools and permissions should be limited to what the agent's job needs.
- Secrets Management Cheat Sheet(opens in a new tab)
OWASP Cheat Sheet Series · Official documentation · Practical advice on keeping credentials out of code and out of reach.
- Building effective agents(opens in a new tab)
Anthropic · Official documentation
- pathlib: Object-oriented filesystem paths(opens in a new tab)
Python Software Foundation · Official documentation · Documents resolve() and is_relative_to(), used in the example.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.