跪拜 Guibai
← Back to the summary

Build the Agent Permission Gate Before Plugging In Tools

Series: AI Application Production Handbook Article 21 (of 30) | Companion open-source project: https://github.com/ChenYingbo/ai-prod-demo This article advances the handling of the P5 item "permissions / proxy" from the S01 threat model, the one that "starts low now, jumps high after tools are connected", moving it earlier.

一、Look at the problem first: the gate must be built before tools are connected

In the S01 threat model, LLM08/09 (permissions / over-proxy) is rated "low", but that "low" has a precondition: the demo currently has no tool calling. Once RAG or Agent is connected, letting the model "query the database" "modify records" "send emails", this item immediately jumps to the highest risk level — if "delete the database" and "look up information" have the same permissions, that's a disaster.

When it actually lands, three obstacles are unavoidable:

  1. "Thinking about permissions when tools are connected" = an accident waiting to happen — when developing features, you rush for speed, then plan to add permissions later, but "later" never comes.
  2. Relying on the model's "self-discipline" not to overstep is unreliable — which tool the model selects is probabilistic; writing "please don't overstep" in the prompt is useless. Permissions must be enforced by the system.
  3. Sensitive operations have no brake — operations like deletion, money transfer, and external sending should have a human confirmation, not be executed by the model with a single click.

Solution: permission framework first. Tools declare their least-privilege role plus sensitive markers; all calls go through a unified entry (permission check → sensitive confirmation → execution). Before connecting the first real tool, the gate is already there.

Core insight: permissions are "system enforcement", not "model self-discipline". Least privilege = every tool declares who can call it; HITL (human-in-the-loop) = sensitive operations must have human confirmation. Without this framework before tool integration, you are giving the Agent a master key.

二、Principle

2.1 Least privilege: write permissions into tool definitions, not scattered in code

In the companion project, app/tools.py does only one thing — declares for each tool "what role it needs, whether it's sensitive":

search_kb     → minimum role user      (read-only, freely callable)
update_record → minimum role operator + sensitive  (write, needs confirmation)
delete_record → minimum role admin     + sensitive  (dangerous, needs confirmation)

Role hierarchy: user(1) < operator(2) < admin(3)

Three design points:

  1. Declarative: permissions are written in the tool definition. A new tool must declare them; if not declared, it is not callable by default (unknown tool → denied).
  2. Unified entry: all tool calls go through execute_guarded(), no second entry — bypassing the entry means bypassing permissions.
  3. Denials leave traces: every permission_denied is logged; denied attempts themselves are attack signals (can be wired into the O module for alerts).

2.2 HITL for sensitive operations: humans guard dangerous actions

operator calls update_record
   ↓
execute_guarded → permission okay → is it a sensitive operation?
   ↓ yes
request_confirmation → generate confirmation_id → enter pending queue
   ↓
human decision: approve → execute / deny → terminate (both leave traces)

Four disciplines of HITL:

Point Approach
What counts as sensitive Write / delete / external send / spend money — declared in tool definition, not guessed at runtime
Confirmation must be recorded Who, when, approved or denied — audit must be traceable
Must have a timeout Pending confirmation requests cannot hang forever; timeout defaults to deny (A04 will deepen this)
Denial is also an event deny is not "didn't happen", it's "was blocked" — must be visible in audit

2.3 Permission framework ≠ sandbox (honest boundaries)

This section must be clear, to avoid clickbait:

In one sentence: the framework governs "whether it can be called", the sandbox governs "where it runs", production needs both.

三、Hands-on: five scenarios run the permission matrix + HITL

The companion project runs without a key.

3.1 Sandbox demo (covers all five scenarios)

cd demo && source .venv/bin/activate
python scripts/sandbox_demo.py

Actual output:

===== S03 Permission and Sandbox Demo =====

[Scenario 1] user calls read-only tool search_kb
  → (True, executed) expected: direct execution

[Scenario 2] user calls write tool update_record (over-permission)
  → (False, permission-denied) expected: permission-denied

[Scenario 3] operator calls update_record (sensitive → needs human confirmation)
  → (True, confirmation-required:08d48f7d667b) expected: confirmation-required:xxx
  [HITL] human approves 08d48f7d667b →
  → decision result: True (confirmation record kept, then executed)

[Scenario 4] operator calls delete_record (insufficient role)
  → (False, permission-denied) expected: permission-denied

[Scenario 5] admin calls delete_record (sensitive → confirmation → denial terminates)
  → (True, confirmation-required:27153d614b46) expected: confirmation-required
  [HITL] human denies 27153d614b46 →
  → decision result: True (operation not executed, record kept)

[Summary] Permission matrix: read=user / write=operator(sensitive confirmation) / delete=admin(sensitive confirmation)

The five scenarios exactly cover the three boundaries of the permission matrix and the two branches of HITL: read-only passes, over-permission denied, sensitive requires confirmation, approval enables execution, denial terminates. Note the denial in scenario 5 — decide(cid, approve_=False) returns True only to mean "the decision action was successfully recorded", not "the operation was executed"; the state is set to denied, and the caller is supposed to not execute based on that. This distinction will be explicitly tested later.

3.2 Unit verification

python -m pytest tests/test_permissions.py -q
# 7 passed in 0.01s

7 items cover: role matrix (including unknown-role and nonexistent tools are denied), sensitive markers, read-only direct execution, over-permission denial, HITL approval (and a repeated decision must fail on the second call), state denied after denial, unknown tool denial. Run full regression: 128 passed.

3.3 Audit log: denials and confirmations are events

The permission framework logs every action in structured form. This is the data source for the O-module alerting ("sharp increase in permission denials = possible attack"):

python -c "..."   # trigger three types of flows: user over-permission / operator approval / admin denial

Actual log (excerpt):

event=permission_denied       request_id=-
event=confirmation_requested  request_id=-
event=confirmation_approved   request_id=-
event=confirmation_requested  request_id=-
event=confirmation_denied     request_id=-

There is a real, small pitfall worth writing out: permission_denied in the code clearly passes tool=, role=, but the log shows only event and request_id — because O01's structured logging has a field whitelist (that batch of model/in_tokens/latency_ms); tool, role, confirmation_id, approver are not in the list, and the formatter drops them. The audit event can see "what type of event happened", but the key context — "which tool, who approved" — is not persisted — which is insufficient for security auditing. The fix is simple: add these fields to the whitelist. The completeness of security logs depends on whether you are willing to write a few extra fields.

3.4 Rehearsal before connecting real tools (worth doing once)

Suppose the demo is to connect "check weather" (read-only) and "send email" (external sending):

  1. In app/tools.py, declare the role + sensitive marker for these two tools;
  2. Think clearly first: who is allowed to check weather? Who can send email? Is sending email sensitive (external sending usually is)?
  3. Run through execute_guarded and confirm the permission matrix matches expectations;
  4. Experience: when tools are integrated, permissions are "declare first, then use", not "patch after going live".

四、Real pitfalls

  1. Permissions scattered in code — each tool judges permissions on its own; bypassing one spot leaks. Must converge to a unified entry execute_guarded.
  2. Letting the model decide permissions — writing "don't overstep" in the prompt; the model is probabilistic and can still be hijacked by injection. Permissions must be system-enforced.
  3. Sensitive operations without confirmation — deletion executes directly; dangerous operations must go through HITL, and denial must leave a trace.
  4. Confirmation without timeout — a pending confirmation request hangs forever, which is a stuck approval; timeout must default to deny.
  5. Treating the permission framework as a sandbox — the framework governs "whether it can be called", the sandbox governs "where it is called", real tools need both (this article only did the former).
  6. Forgetting to declare new tools — not declaring defaults to deny is the safe direction; never be lazy and change it to "default allow".
  7. Being lazy with audit fields — like in 3.3, the log whitelist omitted tool/role/approver, and when something happens you can't trace back "who approved, which record was changed".

五、Takeaways from this article

Next (S04): Output Security and Data Privacy — PII detection and automatic masking, log masking, compliance self-checks. S02 stops "malicious input that comes in", S04 guards "sensitive data that leaks out". Save + follow; one per day, 30 days to bring AI applications to production.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

沉着宇宙

A very solid production-grade breakdown! The points about "permissions being enforced by the system, not by the model's good conscience" and unifying everything through execute_guarded(), with undeclared tools rejected by default, are especially critical. The pitfall in section 3.3 where the audit log whitelist dropped the tool/approver fields is painfully real. At Spark Workshop, when organizing Agent Skills, we increasingly emphasize marking read-only/write boundaries and human-confirmation nodes directly in the tool definitions, rather than relying on prompt-based caution to enforce safety boundaries.