Module: L3-M07 · Duration: ~120 minutes (estimate, including the independent exercise) · Previous: L02 (injection through data) · Next: L04 (the approval gate)
1. Introduction
L02 showed that an instruction in data can make an agent want to do something bad. This lesson asks the next question: when the agent wants to do it, how far is it allowed to go? L3-M01-L01 and L3-M01-L05 introduced excessive agency with OWASP's three root causes: excessive functionality, excessive permissions, excessive autonomy, and mapped them onto the architecture map. This lesson tests the second root cause, excessive permissions, with a runnable matrix; the third root cause, excessive autonomy, is the topic of L04.
The test is a permission matrix: for each role × tool × resource class, does the policy allow or block it? We compare that matrix with a spec written beforehand, run each cell in a sandbox environment, and list every excess permission compared with what is needed: the principle of least privilege. OWASP advises "Implement authorization in downstream systems rather than relying on an LLM to decide if an action is allowed or not" (complete mediation) [R1]; the lab does exactly that: the environment checks permissions on every call, without asking the model.
What the lesson produces: the policy data/policy.json, the checker lab/policy.py with check_matrix, excess and a gate that checks every role of the policy, the spec data/permission_spec.json, and in §9 a policy you fix, spec rows you write from a user story, and a measurement of a confused-deputy bug.
2. Learning objectives
- Recall the three root causes of excessive agency (L3-M01) and explain least privilege and complete mediation. Read: §4.1.
- Determine the resource class of a call (self/class/other, public/class/self/other, internal/external) from the caller's role. Read: §4.2, §5.1.
- Write spec rows from a user story, then run and read a permission matrix against the spec and a list of excess permissions. Read: §5.2, §6.1. Practice: §8.3, §9 (TODO 1-3).
- Analyse and measure a "confused deputy" bug: the same call run with the user's identity and with the service identity. Read: §4.2, §8.2 part D. Practice: §9 (TODO 4).
3. Prerequisites and tools
- L3-M01-L01 and L3-M01-L05 (excessive agency, the three root causes, the
permissionfield), L3-M02-L03 (authorisation belongs to downstream systems, not to the model), L3-M07-L02 (violating actions). Code labcode-labs/l3-m07. - Keeping the terms apart. Role: student, teacher, librarian, service. Resource class: the relation between the target of a call and the caller:
self(oneself),class(the same school class),other(someone else); for documents it ispublic/class/self/other; for email it isinternal(the internal domain) /external. Note: "resource class" is a kind of relation; its valueclassmeans "the same school class". Grant: one (role, tool, class) that is allowed. Confused deputy: a high-privilege component used to act on behalf of a low-privilege party. - The users, permissions and email domains are all simulated and fictional. There is no real system and no network.
4. Concept explanation
4.1 Recap: excessive agency and least privilege
OWASP LLM06 defines Excessive Agency as the vulnerability "that enables damaging actions to be performed in response to unexpected, ambiguous or manipulated outputs from an LLM" [R1]; the three root causes were covered in L3-M01-L05 §4.2. This lesson uses only the second root cause: a tool has permissions on downstream systems wider than it needs [R1].
Three OWASP mitigations that this lesson tests: Minimize extension permissions (grant only the minimum permissions), Execute extensions in user's context (an action on behalf of a person runs with that person's own identity), and Complete mediation: "Implement authorization in downstream systems rather than relying on an LLM ... Enforce the complete mediation principle so that all requests ... are validated against security policies" [R1]. OpenAI says the same thing differently: limit the surface with "structured outputs and isolation", and "it's important to understand these risks and use caution in what access you give agents" [R2].
4.2 The permission matrix and the confused deputy
A policy assigns grants to each role. To test it, we spread the whole cross product role × tool × resource class into a matrix, then ask of each cell: does the policy allow or block it? Compared with a spec written beforehand (the cells that should be allowed), every differing cell is a finding.
The resource class depends on the caller, not only on the target. The same student S0042 is self to himself, class to a classmate in 7A, and other to a student in another class. An email to @thuvien.example is internal, to another domain it is external. So a permission bug only shows up when we try the right (role, target) combination.
A confused deputy is a separate bug: the agent calls tools with a shared, high-privilege service identity instead of the identity of the user it is serving. In the lab, the weakness acts_as_service makes the agent call every tool as SVC, the identity used for background jobs (due-date reminders, record clean-up), which therefore has wide permissions. Then the rule "a student may only view their own record" is bypassed even though the policy is correct. OWASP names exactly this scenario, "an extension ... accesses downstream systems with a generic high-privileged identity" [R1], and advises running in the user's context.
5. Technical deep dive
5.1 authorize, resource_class, and complete mediation in the World
lab/policy.py has resource_class(policy, people, documents, actor, tool, args), which returns the resource class (or None when the target does not exist), and authorize(...), which returns (True, class) or (False, code) with code UNKNOWN_ACTOR, UNKNOWN_TOOL, NOT_FOUND, FORBIDDEN. An email address must match in full (a newline at the end of the address is NOT_FOUND). The key point: lab/world.py calls authorize on every tool call, for every caller: that is how the lab stands in for complete mediation in the downstream system, not in the model.
validate_policy checks shape, not wisdom: a tool must have a valid kind/risk/resource, a grant must point to an existing tool, the class must be one of that tool's classes, no duplicate classes. A grant that is unnecessary but well-formed still passes validate_policy; what catches it is the matrix and excess.
5.2 check_matrix, the "n/a" cells, excess and the gate
matrix_cases(policy, fixtures) turns each cell into a concrete call on fixture data (data/permission_spec.json: one caller for each role, one target for each class). check_matrix(spec_allow, policy, fixtures, lambda pl: World(pl)) runs each cell in a fresh World (the last parameter builds a World for the policy under test) and compares "allowed" with the spec. The functions and codes you need:
| Function / code | Meaning | Example in the demo |
|---|---|---|
| an "allowed" cell | Every status except blocked with FORBIDDEN/NOT_FOUND/UNKNOWN_ACTOR/UNKNOWN_TOOL |
43 cells (part B) |
an n/a cell |
The fixtures have no target for that class; it must be in the spec's expected_na, with a reason |
the librarian's class class: 15 cells (part B) |
excess(policy, needs) |
Every grant (of every role) that no user story needs | part C |
MISMATCH |
A cell that differs from the spec, with the expected direction | parts C, E |
UNCHECKED_ROLE |
The policy has a role for which the fixtures have no caller | role admin (part E) |
TOOL_SPEC_MISMATCH |
A tool's kind/risk/resource differs from the spec (for example send_email downgraded to low risk, which skips the approval step of L04) |
part E |
NA_MISMATCH / NA_CELL_ALLOWED |
A cell with no fixture that the spec does not declare (a fixture was deleted) / an n/a cell that is granted |
part E |
gate(spec_allow, policy, fixtures, world_factory, needs) HOLDs on any of the codes above, when the policy is malformed, or when the spec names a cell the policy does not have. It does not only check the roles that have fixtures: the service role also has a caller (SVC) and spec rows, and has needs that record the reason (background jobs), so every change on that role is seen too.
6. QA perspective
6.1 Write the spec first, read the matrix and the excess permissions
The core principle: the spec is decided by people; the matrix is what is enforced. The tester writes spec_allow (the cells that should be allowed) and needs (the grants each user story really needs) before reading the policy; then lets the matrix and excess point out the differences. Review list:
- Every role is checked: each role of the policy has a fixture caller of that role; a new role with no fixture makes the gate HOLD.
- Cover every class: every cell is either run or listed in
expected_nawith a written reason; no cell is skipped silently, and non/acell is granted. - Try the right combination: to catch "a student views another student's record", the
classfixture must be a different student in the same class, not the caller themselves. - A business-rule error is not a permission error:
NONE_LEFT/LIMITmeans blocked by a business rule (as in L3-M06-L02), so authorisation already passed; onlyFORBIDDEN/NOT_FOUND/UNKNOWN_ACTOR/UNKNOWN_TOOLmeans blocked by authorisation. - A tool's risk is part of the spec: downgrading a tool to low risk skips the approval step; the spec records each tool's
risk. - Confused deputy: run the same call with the user's identity and with the service identity, and check that the call with the user's identity is blocked.
7. Real-world scenarios
Scenario 1 (fictional): "Permission to send outside". A team grants the teacher role send_email to external as well, "so teachers can email parents". The matrix differs from the spec in the cell teacher.send_email.external, and excess lists exactly that cell. The risk: combined with an exfil injection (L02), a malicious document can make the agent send data outside on the teacher's behalf. The fix: teacher.send_email keeps only internal, or a new user story is recorded in needs together with an approver (L04).
Scenario 2 (fictional): "One identity for everything". For convenience, the agent calls tools with the service identity instead of the student's identity. get_student(S0518) run as S0042 is FORBIDDEN, but run as SVC it is ok: the boundary "view only your own record" disappears. The policy's matrix is still clean, because the bug lies in the identity the agent uses, not in the policy; only a measurement on the real call (§9 TODO 4) shows it.
8. Hands-on tutorial
8.1 Setup
cd academy-content/code-labs/l3-m07
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest # 154 passed
8.2 Run the demo
python -m lab.demo l03
Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-05; identical). Every run is simulated:
A. validate_policy on the shipped policy and on structurally broken ones (shape, not wisdom)
shipped: []
a class name the model does not define: ['UNKNOWN_CLASS:student.borrow_book']
a grant on a tool that does not exist: ['UNKNOWN_TOOL:teacher.fly_book']
B. the permission matrix of all four roles: cells, mismatches with the spec, and declared cells with no fixture (n/a)
cells run = 85, mismatches = 0, n/a = 15 (declared: 15)
allowed = 43, denied = 42
C. a policy with two excess grants: the matrix mismatches and the least-privilege excess list
mismatches: [(('student', 'get_student', 'other'), 'allowed'), (('teacher', 'send_email', 'external'), 'allowed')]
excess vs needs: [('student', 'get_student', 'other'), ('teacher', 'send_email', 'external')]
D. the confused deputy: a student's call run as the service identity reaches another student's record
get_student(S0518) as the student (S0042): blocked FORBIDDEN
get_student(S0518) as the service identity (SVC): ok None
E. the gate: shipped policy, the excess policy, and three changes a fixture-only check would miss
shipped: {'decision': 'READY_FOR_REVIEW', 'reasons': []}
excess: {'decision': 'HOLD', 'reasons': ['MISMATCH:student.get_student.other:expected=deny', 'MISMATCH:teacher.send_email.external:expected=deny', 'EXCESS:student.get_student.other', 'EXCESS:teacher.send_email.external']}
a new role 'admin': ['UNCHECKED_ROLE:admin', 'EXCESS:admin.delete_record.other']
send_email downgraded to low risk: ['TOOL_SPEC_MISMATCH:send_email']
a fixture nulled: ['NA_MISMATCH:student.send_email.external']
Reading the output: in part A, validate_policy catches only shape errors (an unknown class, an unknown tool). In part B, the matrix of all four roles (including service) runs 85 cells, the 15 n/a cells are exactly as many as the spec declares (for example the class class for the librarian, who belongs to no school class), and no cell differs from the spec; 43 cells are allowed, 42 are blocked. In part C, the two excess permissions are both cells that differ from the spec and entries in excess. Part D is the confused deputy. In part E, three changes that a gate looking only at the roles with fixtures would miss: a new role, a tool downgraded in risk, a deleted fixture; all three HOLD.
8.3 Try it yourself
Save this as try_l03.py in the lab's root folder, run PYTHONDONTWRITEBYTECODE=1 python try_l03.py, then delete the file:
from lab import policy as P, data
pol = data.policy()
people = {p["id"]: p for p in data.people()}
docs = {d["id"]: d for d in data.documents()}
for actor, tool, args in [("S0042", "get_student", {"student": "S0042"}),
("S0042", "get_student", {"student": "S0518"}),
("S0042", "send_email", {"to": "x@thuvien.example", "subject": "s", "body": "b"}),
("S0042", "send_email", {"to": "x@out.invalid", "subject": "s", "body": "b"})]:
print(actor, tool, args.get("student") or args.get("to"), "->", P.authorize(pol, people, docs, actor, tool, args))
Output (Python 3.14.6 and 3.12.3, Linux, identical):
S0042 get_student S0042 -> (True, 'self')
S0042 get_student S0518 -> (False, 'FORBIDDEN')
S0042 send_email x@thuvien.example -> (True, 'internal')
S0042 send_email x@out.invalid -> (False, 'FORBIDDEN')
Reading it: S0042 can view his own record (self) but not S0518's (FORBIDDEN); sending an internal email is allowed (internal), but sending outside is blocked by authorisation. The resource class decides, and it depends on the caller.
8.4 Run the lesson's tests
python -m pytest tests/test_l03_permissions.py -v
Result: 26 passed. Read test_the_matrix_matches_the_spec_and_lists_na_cells, test_the_gate_checks_roles_that_have_no_fixture and test_the_confused_deputy_a_service_identity_reaches_another_students_record.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
The self and class cells get mixed up |
The class fixture uses the caller themselves |
The class fixture must be a different person in the same class (S0730 for 7A) |
| A business-rule error is counted as "blocked" | NONE_LEFT/LIMIT mistaken for a permission error |
Only FORBIDDEN/NOT_FOUND/UNKNOWN_ACTOR/UNKNOWN_TOOL means blocked by authorisation |
NA_MISMATCH |
A fixture target was deleted, or expected_na declares a cell that has a fixture |
Put the fixture back, or declare that cell with a reason |
UNCHECKED_ROLE |
The policy has a role for which the spec has no caller | Add a fixture caller, spec rows and needs for that role |
9. Independent exercise
Problem: Fix an over-broad policy, list the excess permissions, write the spec for next term's user story, and measure the confused-deputy gap.
Requirements: complete exercises/test_l03_permissions.py:
- TODO 1:
POLICY: the proposed policy (EX["proposed"]) with three grants fixed so thatP.gateisREADY_FOR_REVIEW. Do not copydata/policy.json. - TODO 2:
EXCESS: the sorted list of (role, tool, class) that the original policy (EX["proposed"]) grants beyondneeds. - TODO 3:
MY_SPEC_ROWS: thespec_allowrows ("teacher <tool> <class>") for the teacher role, written from the storyEX["teacher_story"](below). The test compares a fingerprint, so the answer is not in the test file; a second test runs your rows againstEX["teacher_v2"], the draft policy for that story. - TODO 4:
deputy_gap(user, target): callget_studentwith{"student": target}in a freshWorld(), once asuserand once asSVC, and return the two statuses.
The story (the Vietnamese version of EX["teacher_story"]): next term, a teacher may search the catalogue, view a book and look up the teacher of a class; read their own record and the records of students in their own class; read public documents and their own class's documents; borrow books on behalf of, and renew books for, a student in their own class; and send email to people in the school. Nothing else.
Data: exercises/ex_permissions_l03.json, data/permission_spec.json.
Deliverable: POLICY, EXCESS, MY_SPEC_ROWS and the function deputy_gap in that same file.
Acceptance criteria: python -m pytest exercises/test_l03_permissions.py passes (5 tests).
Hint: for TODO 1, run the proposed policy's matrix against the spec and read the differing cells; each differing cell points to a grant to fix. For TODO 2, remember that excess compares with needs, not with the spec. For TODO 3, go through the story clause by clause and ask: which tool, which resource class (§3); which email class is "people in the school"?
10. Knowledge check
0/10 done · Results are kept in this browser only.
P02 · True or false
P03 · Fill in the blank
P04 · Multiple choice
P05 · Put in order
P06 · Select all that apply
P07 · Spot the bug
This fixture setup for the matrix mixes up two resource classes. Find the bug.
fixtures = {"roles": {"student": "S0042"},
"targets": {"student": {"student": {"self": "S0042", "class": "S0042", "other": "S0518"}}}}P08 · Essay
Why does the lesson say authorisation should be enforced in the "downstream system" rather than left to the model to decide? Write two to four sentences.
P10 · Recall
Lesson: L3-M07-L0211. Summary
- Concepts: excessive agency with its three root causes (L3-M01) [R1]; this lesson tests excessive permissions; least privilege and complete mediation in downstream systems, not in the model [R1][R2]; the resource class depends on the caller; the confused deputy.
- Skills: write a permission spec from user stories; read the role × tool × class matrix against the spec; list and deal with excess permissions; use a gate that checks every role, tool risks and
n/acells; measure a confused-deputy bug. - Traps:
validate_policyonly catches shape; mixing upselfandclass; treating a business-rule error as a permission error; checking only the roles that have fixtures; lettingn/acells pass silently;needsso broad thatexcessis empty; letting the agent decide permissions. - Now you can: test an agent's permission policy, point out the excess permissions, and reproduce a confused deputy.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | LLM06:2025 Excessive Agency | OWASP Gen AI Security Project | https://genai.owasp.org/llmrisk/llm062025-excessive-agency/ | 2026-11-05 | Definition; minimize permissions; execute in user's context; complete mediation; generic high-privileged identity |
| R2 | Agent Builder safety | OpenAI | https://platform.openai.com/docs/guides/agent-builder-safety | 2026-11-05 | Limiting the surface; caution with the access given to agents; structured outputs and isolation |
Glossary (English ↔ Tiếng Việt)
| English | Tiếng Việt |
|---|---|
| Excessive agency | Quyền tự quyết thừa (glossary L3-M01-L01); bài này kiểm gốc rễ quyền thừa |
| Excessive permissions | Quyền thừa: tool có quyền trên hệ thống phía dưới rộng hơn mức cần |
| Least privilege | Đặc quyền tối thiểu: chỉ cấp quyền đúng mức cần |
| Permission matrix | Ma trận phân quyền: vai × tool × lớp tài nguyên |
| Resource class | Lớp tài nguyên: quan hệ giữa mục tiêu và người gọi (self/class/other, internal/external...) |
| Expected n/a cell | Ô n/a đã khai: ô không có dữ liệu mẫu, ghi trong spec kèm lý do |
| Complete mediation | Cưỡng chế đầy đủ: kiểm quyền ở hệ thống phía dưới trên mọi lời gọi, không giao cho model |
| Confused deputy | Đại biểu bị lừa: dùng một danh tính quyền cao để làm thay một bên quyền thấp |