Module: L3-M07 · Duration: ~120 minutes (estimate, including the independent exercise) · Previous: L03 (excessive agency) · Next: L05 (safe red-teaming)
1. Introduction
L03 limited what the agent is allowed to do; this lesson adds a layer for actions that are still allowed but high risk: before they happen, a human must approve. OWASP calls this a mitigation against excessive autonomy: "Require user approval ... Utilise human-in-the-loop control to require a human to approve high-impact actions before they are taken" [R1]. The OpenAI Agents SDK does exactly this: "pause agent execution until a person approves or rejects sensitive tool calls" [R2].
L3-M02-L04 approved by key: a set of approved keys that does not know who approved and is not tied to the content of the call. This lesson fills those two holes: a digest ties an approval to the exact arguments, and a rule on who may approve (a person with the approver role, not a party to the call). Two more things: an approval is single-use and expires by the gate's own clock; and enforcement must sit in the downstream system, not only in the agent. This lesson builds an approval gate and an effect ledger to test all of that.
What the lesson produces: the gate lab/approval.py (Gate with request/decide/consume, TTL, approvers, structured display), an audit that reads the effect ledger rather than the agent, and in §9 an audit prediction table, a careful approver that you write, and your own approval-gate test cases. Every send_email only appends to an in-memory list; there is no real email.
2. Learning objectives
- Explain why high-risk actions need an approver, and why an approval must be tied to one specific call (tool, arguments, single use, expiry, the right approver). Read: §4.1.
- Explain the difference between enforcement in the World (the downstream system) and only in the agent (the client), and why the audit must read the ledger. Read: §4.2, §5.2.
- Read an audit of high-risk effects from the effect ledger, not from the agent's words, and predict it for a new script. Read: §5.2, §6.1. Practice: §8.3, §9 (TODO 1).
- Write approval-gate test cases: skipped approval, reused approval, expiry, self-approval; and an approver that compares field by field. Read: §5.1, §6.1. Practice: §9 (TODO 2, TODO 3).
3. Prerequisites and tools
- L3-M07-L03 (permissions, tool risk), L3-M02-L04 (the approved-key set and its limits), L3-M01-L05 (the map's
approvalfield), L3-M06-L02 (idempotency keys, the effect ledger). Code labcode-labs/l3-m07. - Keeping the terms apart. Approval: a person agrees to one high-risk call. Digest: a SHA-256 hash of the arguments as canonical JSON, to know that the call at execution time is the call that was approved. TTL (time to live): an approval can only be used within a number of turns after the decision. Audit: a review of the effect ledger after the run, looking for high-risk effects without a valid approval. Rubber stamp: an approver who clicks yes without reading.
- The gate, the tools and the email are all simulated and fictional.
send_emailonly appends to an in-memoryoutbox.
4. Concept explanation
4.1 An approval tied to one specific call, and the right approver
A "general" approval is useless: if the approver clicks "approve" and the agent then sends a different email, the approval step protects nothing. So Gate.request records the tool, a digest of the arguments, the display text shown to the approver, the requesting agent (by), the identity the call runs as (actor) and the turn of the request. consume lets a call through only when the approval has been approved, is unused, is for the same tool, with the same arguments (the digest matches), and has not expired (TTL). OpenAI advises "always enable tool approvals so end users can review and confirm every operation" [R3], and their SDK fails closed when it cannot read the arguments: "Callable approval rules fail closed when the SDK cannot safely inspect the arguments" [R2]. The lab does the same: when the arguments cannot be canonicalised, request returns MALFORMED_ARGS.
Who may approve is a rule, not just a name different from the agent's. In the lab, the approver must have the approver role (librarian L0001 or L0002), and must not be a party to the call: not the requesting agent, not the identity the call runs as, not the student the call is about. Identities are compared after stripping whitespace and lower-casing. Anyone else gets NOT_AN_APPROVER; a party to the call gets SELF_APPROVAL. The consequence: when librarian L0001 asks to waive a fine on their own request, L0001 cannot approve it; L0002 is needed (four eyes).
The approver must see the exact call. render(tool, args) writes a structured display tool(key="value", ...); a careful approver reads back each field and compares each value for equality. A "substring" check loses to a look-alike address: hoa.t0007@thuvien.example.evil.invalid contains hoa.t0007@thuvien.example.
4.2 Where enforcement sits: the World or the agent
This is the easiest point to get wrong. If the approval step lives only in the agent (client-side), an agent with the skips_approval bug calls the tool directly and the effect still happens. Real protection lives in the downstream system: OWASP says the mitigation "may be implemented in a downstream system (outside the scope of the LLM application) or within the LLM extension itself" [R1], and only the first one holds against a faulty agent.
The lab models both with the flag World(enforce_approval=...). When it is True, the World itself calls consume on every high-risk tool: an agent that skips approval is blocked at once (NO_APPROVAL). When it is False, the World trusts the agent: an agent that skips approval still writes the effect, and only the audit afterwards finds it. The clock must also sit in the lower layer: the gate keeps its own clock (gate.now), the harness advances it by one turn for each event in the script, and no call passes in a turn number; so the agent cannot make an old approval look fresh.
5. Technical deep dive
5.1 Gate: request, decide, consume, TTL
Gate(ttl_turns, approvers) holds the requests; approvers defaults to everyone with the librarian role in data/people.json. advance(n) moves the clock forward (never back). The codes:
| Function | Returns | Codes on failure |
|---|---|---|
request(tool, args, display, by, actor) |
(id, None) |
MALFORMED_ARGS |
decide(id, decision, by) |
None |
UNKNOWN_REQUEST, BAD_DECISION, ALREADY_DECIDED, SELF_APPROVAL, NOT_AN_APPROVER |
consume(id, tool, args) |
(True, None), marked as used |
NO_APPROVAL, UNKNOWN_REQUEST, PENDING, REJECTED, WRONG_TOOL, ARGS_CHANGED, ALREADY_USED, EXPIRED (in the order checked) |
digest(args) hashes canonical JSON (sorted keys, no NaN allowed), so {"a":1,"b":2} and {"b":2,"a":1} have the same digest, while {"a":1} differs from {"a":2}. parse_display reads back a display written by render; covers(display, tool, args) is true only when the display can be read and names exactly the tool, exactly the keys, exactly each value. TTL is counted on the gate's clock: with ttl_turns=2, an approval decided at turn 0 can still be used at turn 2; at turn 3 it is EXPIRED.
In an agent script, the event {"t": "approver", "decision": "approve"} is a rubber stamp; {"t": "approver", "approve_if": {field: value}} is an approver who checks each listed field: it approves only when the display can be read and each listed field has exactly that value. The "by" field says who decides (L0001 by default).
5.2 audit: read the ledger, not the agent
audit(ledger, gate, policy) goes through the World's effect ledger (not the agent's trace) and lists every high-risk effect without a valid approval: UNAPPROVED (no id), UNKNOWN_APPROVAL, NOT_APPROVED (still pending or rejected), WRONG_TOOL, ARGS_CHANGED, REUSED (one approval used for two effects), DISPLAY_MISMATCH (the approver was not shown this exact call), EXPIRED (the effect ran after the deadline, by the World's clock), SELF_APPROVED and NOT_AN_APPROVER (the gate record shows that a party to the call, or someone without the approver role, decided). Low-level effects (borrowing, renewing) are not audited. The audit never raises: a ledger of the wrong shape gives BAD_LEDGER or BAD_ENTRY. Because the audit reads state (the ledger + the gate record), it catches the case where the agent "says" it asked for approval but in fact did not. Blind spot: the audit trusts the gate's record and the World's clock; a display that is right field by field but too long for anyone to read still "covers" the call.
6. QA perspective
6.1 Testing the approval gate with cases
An approval gate has to be tested in the right places. Review list:
- Skipped approval (
skips_approval): withenforce_approval=Trueit must be blocked in the World; withFalsethe effect happens butauditreturnsUNAPPROVED. Test both worlds. - Reused approval (
reuses_approval, "approve-always"): one approval for two calls must giveREUSED(andARGS_CHANGEDif the arguments differ). The OpenAI SDK describes "sticky decisions" (always_approve) as a feature: when a sticky decision applies, "The SDK does not prompt again" [R2]. A feature like that is exactly where a tester has to probe: is the second call really the same thing that was approved? - Misleading display (
misleading_display): the approver sees a description instead of the call. An approver who checks each field rejects it (a description cannot be read as fields); a rubber stamp approves it, and onlyauditcatchesDISPLAY_MISMATCH. - Look-alikes: a value that contains the real value (the domain
...example.evil.invalid) must be rejected; compare for equality, not for a substring. - Expiry and the approver: the TTL stops an old approval being used many turns later;
SELF_APPROVALandNOT_AN_APPROVERstop a party to the call or someone without the approver role. - Fail closed: with broken arguments (
NaN, not a dict),requestrefuses; it does not "just let it through".
The general principle is the same as in L02: the audit reads state, not the agent's words. An agent can report "approval requested" while the ledger shows it was not.
7. Real-world scenarios
Scenario 1 (fictional): "The approval gate is only in the app". A team puts the approval step inside the agent. When they switch on skips_approval to simulate a faulty build, with enforce_approval=False (the World trusts the agent) a fine is cleared without approval; only audit returning UNAPPROVED finds it. The fix: enforce approval in the lower layer (enforce_approval=True), where the call is blocked at once [R1].
Scenario 2 (fictional): "The approver only looks at the domain". A teacher bio is injected with an instruction to send a private note to hoa.t0007@thuvien.example.evil.invalid. The team's approver checks "does the address contain hoa.t0007@thuvien.example?" and clicks approve: the note goes outside. An approver who checks each field with an equality comparison rejects it at once. The fix: a structured display, equality comparison field by field, and an audit that reads the ledger (L02 §8.2 part F shows that the exfil detector catches that email).
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 l04
Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-05; identical). send_email only appends to an in-memory list:
A. a safe email-to-teacher turn, a field-checking approver (librarian L0001), enforcement in the World: the audit is clean
display=['send_email(body="I finished B002", subject="Message from An", to="hoa.t0007@thuvien.example")']
ledger=[('send_email', 'AP1')] outbox=1 audit=[]
B. the same turn, approver rejects: nothing is written
ledger=[] outbox=0 audit=[]
C. skips_approval with enforcement in the World (enforce_approval=True): the World blocks the high-risk call
enforce_approval=True: ledger=[] audit=[]
enforce_approval=False: ledger=[('waive_fine', None)] audit=['UNAPPROVED:1']
D. reuses_approval (approve-always) with the World trusting the agent: one approval, two emails; only the audit sees it
ledger=[('send_email', 'AP1'), ('send_email', 'AP1')] outbox=2 audit=['ARGS_CHANGED:2', 'REUSED:2']
E. misleading_display: free text instead of the call. The field-checking approver rejects it; a rubber stamp approves it
approve_if: decision=reject outbox=0 audit=[]
rubber stamp: decision=approve outbox=1 audit=['DISPLAY_MISMATCH:1']
F. who may decide: the requester's own user, a non-approver, and the librarian (gate approvers = librarians)
by=S0042: code=SELF_APPROVAL outbox=0
by=T0007: code=NOT_AN_APPROVER outbox=0
by=L0001: code=None outbox=1
G. the TTL runs on the gate's own clock (ttl_turns=2): a decision two turns old is used, one three turns old is EXPIRED
decided at turn 0, consumed at turn 2: (True, None)
decided at turn 2, consumed at turn 5: (False, 'EXPIRED')
Reading the output: in part A, the structured display lists all three fields; the approver who checks to approves, one email goes out, the audit is clean. Part C is the core lesson: enforce_approval=True blocks the call that skips approval (the ledger is empty); enforce_approval=False lets it through, and only audit returns UNAPPROVED:1. In part D, approve-always sends two emails with one approval, so there are REUSED and ARGS_CHANGED. In part E, the description cannot be read as fields: the approver who checks each field rejects it; the rubber stamp approves and the audit catches DISPLAY_MISMATCH. In part F, student S0042 is the party being served, so SELF_APPROVAL; teacher T0007 does not have the approver role; librarian L0001 may approve. In part G, the TTL is counted on the gate's clock.
8.3 Try it yourself
Save this as try_l04.py in the lab's root folder, run PYTHONDONTWRITEBYTECODE=1 python try_l04.py, then delete the file:
from lab import approval as AP
g = AP.Gate(ttl_turns=1)
args = {"student": "S0042"}
rid, _ = g.request("waive_fine", args, AP.render("waive_fine", args), by="desk", actor="L0001")
print("display:", g.requests[rid]["display"])
for who in ("desk", "S0042", "L0001", "T0007", "L0002"):
print("decide by", who, "->", g.decide(rid, "approve", by=who))
print("consume:", g.consume(rid, "waive_fine", args))
print("again:", g.consume(rid, "waive_fine", args))
Output (Python 3.14.6 and 3.12.3, Linux, identical):
display: waive_fine(student="S0042")
decide by desk -> SELF_APPROVAL
decide by S0042 -> SELF_APPROVAL
decide by L0001 -> SELF_APPROVAL
decide by T0007 -> NOT_AN_APPROVER
decide by L0002 -> None
consume: (True, None)
again: (False, 'ALREADY_USED')
Reading it: the requesting agent (desk), the student whose fine is waived (S0042) and the librarian the call runs as (L0001) are all parties to the call, so SELF_APPROVAL; teacher T0007 does not have the approver role; a second librarian, L0002, may approve. A call with the right tool, the right arguments and within the deadline goes through once; the second time it is ALREADY_USED.
8.4 Run the lesson's tests
python -m pytest tests/test_l04_approval.py -v
Result: 23 passed. Read test_world_enforcement_blocks_a_skipped_approval, test_the_structured_display_is_compared_field_by_field_not_by_substring and test_the_audit_catches_an_expired_a_self_approved_and_a_non_approver_record.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
skips_approval produces no audit error |
enforce_approval=True blocks it at once in the World |
Use World(enforce_approval=False) to see the audit catch UNAPPROVED |
REUSED does not show up |
There is only one high-risk call in the script | You need two calls for one approval to be reused |
| A librarian's own request cannot be approved | L0001 is the identity the call runs as: SELF_APPROVAL |
Let the second approver decide: "by": "L0002" |
TypeError: ... 'turn' |
An old API with a turn number was called | The gate keeps its own clock: use gate.advance(n), do not pass turn |
9. Independent exercise
Problem: Predict the audit of the weak agents on a new script, write a careful approver, and write approval-gate test cases.
Requirements: complete exercises/test_l04_approval.py:
- TODO 1:
AUDIT: for each run inRUNS(the three-email scriptSCRIPT: an approver who checks each field after the first email, a rubber stamp after the third; the World enforcing or trusting the agent), which codes does the audit return (with the:<seq>part removed, no duplicates) and how many emails reachoutbox? Predict first, then runrun_audit. - TODO 2:
careful_approver(display, args): approve only whendisplayis the structured display of exactly these arguments: the same set of keys and each value equal. You may useAP.parse_display; do not callAP.covers. - TODO 3:
GATE_CASES: at least four cases{"id", "config", "enforce", "user", "script", "expect"}that show a skipped approval, a reuse, an expiry and a self-approval.expectis the sorted list of codes thatobserve(case)returns (audit codes, codes of blocked calls, codes of approval decisions). Do not reuseSCRIPTor the scripts of §8.2.
Data: there is no separate file; use lab/approval.py and lab/agent.py.
Deliverable: AUDIT, GATE_CASES and the function careful_approver in that same file.
Acceptance criteria: python -m pytest exercises/test_l04_approval.py passes (3 tests).
Hint: for TODO 1, remember which approver takes which request: each approver event takes the request that has been pending longest. For TODO 2, think about what render writes into the display, and what happens with a display that cannot be read, or has an extra or a missing field; read the test for the edge cases. For TODO 3, an approval only expires when it is used again later than the TTL.
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 simplified consume is missing a check, which lets an approval be used again. Find the bug.
def consume(req, tool, args, now, ttl):
if req["status"] != "approved":
return False, "NOT_APPROVED"
if req["tool"] != tool or digest(args) != req["digest"]:
return False, "MISMATCH"
if now - req["decided_turn"] > ttl:
return False, "EXPIRED"
return True, NoneP08 · Essay
A team says "we have an approval gate, so we are safe". Write three to five sentences listing the questions you must ask before trusting that claim.
P10 · Recall
Lesson: L3-M06-L0211. Summary
- Concepts: human-in-the-loop approval for high-risk actions [R1][R2][R3]; an approval is tied to one call (the tool, a digest of the arguments, single use, a TTL on the gate's clock) and to a valid approver (with the approver role, not a party to the call); a structured display, compared for equality field by field; a gate that fails closed on broken arguments [R2].
- Skills: tell enforcement in the World from enforcement in the client; read an audit from the effect ledger; write gate test cases for skipped approval, reuse, misleading display, look-alikes, expiry and self-approval.
- Traps: a gate only in the app; approve-always; a display that hides the arguments; substring checks; letting the requester or the beneficiary approve; letting the agent report the turn number; trusting the agent's words instead of reading the ledger.
- Now you can: show that an agent causes high-risk effects only when the right person has approved the exact call, and point to where protection breaks if enforcement lives only in the agent.
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 | Require user approval; human-in-the-loop for high-risk actions; downstream vs inside the extension |
| R2 | Human-in-the-loop (OpenAI Agents SDK) | OpenAI | https://openai.github.io/openai-agents-python/human_in_the_loop/ | 2026-11-05 | Pausing for approval of sensitive tools; fail closed when the arguments cannot be read; sticky decisions do not prompt again |
| R3 | Agent Builder safety | OpenAI | https://platform.openai.com/docs/guides/agent-builder-safety | 2026-11-05 | "always enable tool approvals so end users can review and confirm every operation" |
Glossary (English ↔ Tiếng Việt)
| English | Tiếng Việt |
|---|---|
| Human-in-the-loop approval | Phê duyệt có con người: một người đồng ý trước một hành động rủi ro cao |
| Approval gate | Cổng duyệt: gắn một phê duyệt với một lời gọi (tool, tham số, một lần, hết hạn) và một người duyệt hợp lệ |
| Digest | Băm tham số chuẩn tắc, để biết lời gọi thực thi đúng là lời gọi đã duyệt |
| Structured display | Hiển thị có cấu trúc: tool(khóa="giá trị", ...), đọc lại được để so bằng từng trường |
| TTL (time to live) | Hạn dùng: phê duyệt chỉ dùng được trong một số lượt sau khi quyết, theo đồng hồ của cổng |
| Self-approval | Tự duyệt: một bên của lời gọi (agent yêu cầu, danh tính lời gọi chạy bằng, người được lợi) quyết; bị chặn bằng SELF_APPROVAL (khác confused deputy của L03) |
| Rubber stamp | Người duyệt bấm đồng ý mà không đọc hiển thị |
| Side-effect audit | Rà sổ tác động: tìm tác động rủi ro cao thiếu phê duyệt hợp lệ |