AI

AI Agent Permissions and Human Approval

Separate read, draft and send permissions. Run a mock email workflow with exact-action approval, changed arguments, expiry, reuse checks and audit records.

An AI agent should be able to propose an email without being able to send it. The application must decide which operations are allowed and whether a person has approved the exact message. This guide shows that separation for developers who know basic programming and are adding actions to an AI application.

Quick answer

Give the agent only the permissions needed for its task, and deny everything else. For a consequential action such as sending email, require a separate approval tied to the actor, task and exact action details. Recheck permission and approval immediately before execution; a prompt saying “ask first” is not enforcement.

Permission and approval answer different questions

Authentication establishes who is acting. Authorization, or permission checking, decides what that actor may do. Approval records a decision about a particular proposed operation. Logging in does not approve a message, and approving a message does not grant a missing send permission.

The OWASP authorization guide recommends least privilege, denying access by default and checking permissions on every request. Least privilege means giving a component only the access required for its work. In an agent application, those checks belong in the host and tool service, where credentials and execution are controlled.

An actor is the application identity doing the work. It might be a service acting on behalf of a user. The host must establish that identity; a model-generated actor field cannot authenticate it. If the surrounding loop is new to you, start with what an AI agent is.

Follow a draft-email workflow

Imagine a support assistant answering a fictional customer’s upload-limit question. The application has three narrow operations: read one ticket, prepare an email draft and send a reviewed message. Preparing text should not silently acquire the ability to deliver it.

Operation Drafter identity Sender identity Additional boundary
Read the fixture ticket Allowed Allowed Exact permitted ticket ID
Prepare a local draft Allowed Allowed Exact fields and bounded strings
Send Denied Allowed by policy Matching, unexpired, unused approval

The sender is a separate host-configured identity, not a role the model can choose to assume. The table distinguishes standing permission from approval of one action.

An email proposal splits into read/draft and send paths. The host checks permissions on both; sending also requires review of the exact message and a final actor, task, expiry and reuse check before a mock send.

The draft path ends locally. The send path checks standing permission before review and again at execution; denied, changed or expired requests stop.

Review the action that will actually execute

Show the recipient, subject and full body in the approval interface, including any attachments or other delivery options your application supports. Store the decision with the proposed action, actor and task. If relevant details change, ask for a new decision rather than applying an old “yes” to a new operation.

OWASP’s transaction-authorization guidance supports server-side enforcement, review of significant operation data and protection against modification and reuse. A short expiry reduces the window for using an old decision; it does not replace one-use handling.

An agent library can help pause and resume a run, but your application still owns identity and storage. The OpenAI Agents SDK human-in-the-loop guide warns that restoring serialized run state does not authenticate it. Its server-side guidance requires authenticating the reviewer, authorizing their decision and consuming pending state safely. The example below illustrates the boundary without installing that SDK.

Run a mock email example

Save this as approval_demo.py and run python approval_demo.py. The complete listing uses the standard library and was executed with Python 3.8.20. It needs no packages, account, credentials or network connection.

This is a single-process fixture, not an AI model or email service. The host supplies trusted actor/task identifiers and integer clock values. approve() stands in for a decision received after human review; its fixed reviewer-1 audit label is synthetic. The code does not authenticate a reviewer or expose that method as a model tool.

import copy
import json

POLICY = {"drafter": {"read", "draft"}, "sender": {"read", "draft", "send"}}
EMAIL = {"to": "customer@example.test", "subject": "Upload limit",
         "body": "The fictional upload limit is 25 MB."}
SEND = {"op": "send", "args": EMAIL}


def validated(action):
    if not isinstance(action, dict) or set(action) != {"op", "args"}:
        raise ValueError("invalid_action")
    op, args = action["op"], action["args"]
    if not isinstance(op, str) or op not in {"read", "draft", "send"}:
        raise ValueError("unknown_operation")
    if not isinstance(args, dict):
        raise ValueError("invalid_arguments")
    if op == "read":
        if args != {"ticket_id": "T-17"}:
            raise ValueError("invalid_arguments")
    else:
        if set(args) != {"to", "subject", "body"}:
            raise ValueError("invalid_arguments")
        for key, value in args.items():
            limit = 2000 if key == "body" else 200
            if not isinstance(value, str) or not value.strip() or len(value) > limit:
                raise ValueError("invalid_arguments")
            if key != "body" and ("\r" in value or "\n" in value):
                raise ValueError("invalid_arguments")
    return copy.deepcopy(action)


def check_time(now):
    if type(now) is not int or now < 0:
        raise ValueError("invalid_time")


class MailDemo:
    def __init__(self):
        self.permissions = copy.deepcopy(POLICY)
        self.approvals, self.audit, self.sent = {}, [], []

    def log(self, actor, task, op, reason, now, reviewer=None, approval_id=None):
        self.audit.append({"actor": actor, "task": task, "op": op,
                           "reason": reason, "at": now, "reviewer": reviewer,
                           "approval_id": approval_id})
        return reason

    def approve(self, actor, task, action, now, ttl=10):
        # Trusted host callback after human review; never exposed as a model tool.
        check_time(now)
        action = validated(action)
        if type(ttl) is not int or not 1 <= ttl <= 300:
            raise ValueError("invalid_ttl")
        if action["op"] != "send" or "send" not in self.permissions.get(actor, set()):
            raise ValueError("permission_denied")
        key = "approval-" + str(len(self.approvals) + 1)
        self.approvals[key] = {"actor": actor, "task": task, "action": action,
                               "issued": now, "expires": now + ttl, "used": False}
        self.log(actor, task, "send", "approval_recorded", now,
                 reviewer="reviewer-1", approval_id=key)
        return key

    def execute(self, actor, task, action, now, approval_id=None):
        check_time(now)
        try:
            action = validated(action)
        except ValueError as error:
            return self.log(actor, task, "invalid", str(error), now)
        op = action["op"]
        if op not in self.permissions.get(actor, set()):
            return self.log(actor, task, op, "permission_denied", now)
        if op == "read":
            # Fixed fictional ticket; no mailbox or network access.
            self.log(actor, task, op, "read_ready", now)
            return {"ticket_id": "T-17", "question": "What is the upload limit?"}
        if op == "draft":
            self.log(actor, task, op, "draft_ready", now)
            return copy.deepcopy(action["args"])
        record = self.approvals.get(approval_id) if isinstance(approval_id, str) else None
        if record is None:
            reason = "approval_required"
        elif (record["actor"], record["task"], record["action"]) != (actor, task, action):
            reason = "approval_mismatch"
        elif now < record["issued"] or now >= record["expires"]:
            reason = "approval_expired"
        elif record["used"]:
            reason = "approval_used"
        else:
            record["used"] = True
            self.sent.append(copy.deepcopy(action["args"]))  # Mock effect only.
            reason = "mock_sent"
        return self.log(actor, task, op, reason, now,
                        approval_id=approval_id if isinstance(approval_id, str) else None)


if __name__ == "__main__":
    demo, task = MailDemo(), "job-17"
    print("read:", demo.execute("drafter", task,
          {"op": "read", "args": {"ticket_id": "T-17"}}, 100)["ticket_id"])
    print("draft:", demo.execute("drafter", task,
          {"op": "draft", "args": EMAIL}, 100)["subject"])
    print("drafter send:", demo.execute("drafter", task, SEND, 100))
    print("sender without approval:", demo.execute("sender", task, SEND, 100))
    first = demo.approve("sender", task, SEND, 100)
    changed = copy.deepcopy(SEND)
    changed["args"]["body"] = "A different message."
    print("changed body:", demo.execute("sender", task, changed, 101, first))
    print("at expiry:", demo.execute("sender", task, SEND, 110, first))
    fresh = demo.approve("sender", task, SEND, 110)
    print("approved send:", demo.execute("sender", task, SEND, 111, fresh))
    print("reuse:", demo.execute("sender", task, SEND, 112, fresh))
    assert demo.sent == [EMAIL]
    print("audit reasons:", json.dumps([row["reason"] for row in demo.audit]))
    print("mock sends:", len(demo.sent))

Expected output:

read: T-17
draft: Upload limit
drafter send: permission_denied
sender without approval: approval_required
changed body: approval_mismatch
at expiry: approval_expired
approved send: mock_sent
reuse: approval_used
audit reasons: ["read_ready", "draft_ready", "permission_denied", "approval_required", "approval_recorded", "approval_mismatch", "approval_expired", "approval_recorded", "mock_sent", "approval_used"]
mock sends: 1

What each stop tells you

The drafter can read T-17 and prepare text, but its send attempt is denied. A sender has standing send permission, yet still cannot send without a recorded decision. Permission and approval are separate checks.

The first approval is issued at fixture time 100 and expires at 110. Changing the body at 101 fails the action comparison. At exactly 110, the original message fails the expiry check: approval is valid only while issued <= now < expires. Changing the recipient or subject also requires another decision.

A fresh approval permits one mock send at 111. Reusing it at 112 fails. The only effect is an append to demo.sent, an in-memory list. No email is delivered. A successful draft returns email data to its caller; approval details stay in host-owned state.

The final trace reports reasons in execution order. Each audit record also contains the actor, task, operation, fixture time, an approval lookup key for the send path and a synthetic reviewer label for approval creation. It omits the recipient, subject and message body. Real logs need a privacy policy too: even identity and task identifiers can be sensitive.

Where the fixture stops

The approval IDs are predictable lookup keys in a trusted in-memory dictionary. They are not credentials, cryptographic signatures or evidence that a reviewer authenticated. Keep real approval state on the server, accept decisions only through an authenticated and authorized route, and never let model output replace that state.

The validator bounds strings and rejects extra fields and header newlines. It is not a complete email-address parser, content-safety check or system for enforcing access across customer accounts. Real tools need resource ownership, destination and data-disclosure rules as well. A permission to read one support ticket should not become permission to read any mailbox.

The execution method rechecks current permission even after approval is created. Its one-use flag prevents sequential reuse within this process. It does not provide shared storage, thread/process synchronization, crash recovery or a single indivisible operation covering approval and external email delivery. Restarting loses all approvals and audit records. A production design must coordinate the approval check and consumption so two workers cannot both act on the same decision.

External delivery adds another problem: a send may succeed while the response is lost. A local used flag cannot guarantee exactly-once delivery. Use the provider’s supported duplicate-request handling where available and define how operators reconcile uncertain outcomes before retrying. Do not turn a delivery timeout into permission to send again.

Choose how much autonomy the workflow needs

Design When it fits Tradeoff
Draft-only assistant A person will send the final message manually No automatic delivery; more manual work
Narrow automatic action Low-impact operations with clear, enforceable policy Faster flow; policy and output checks must cover the allowed scope
Per-action approval Messages or changes that need review of exact details Adds delay and review work; vague previews can lead to mistaken approval

A person approving every harmless step can become tired and stop reading. Put review where the consequence warrants it, and make rejection easy. For the email example, keeping all delivery outside the agent is often the simplest starting point. Enable sending only when the host can enforce the additional boundary.

The same pattern can apply to a proposed calendar invitation or a proposed infrastructure change. The significant fields differ: attendees and time in one case, target environment and exact change in the other. Treat those as separate policies rather than reusing a generic approval Boolean.

Test permission changes and stale decisions

Exercise the checks through the same tool path used by the agent. Test unknown actors, unknown operations, extra fields, a different task, a different message, expiry boundaries and reuse. Revoke send permission after recording approval and confirm execution still fails. Verify that a rejected action leaves the mock-send list unchanged.

Check useful behavior too: the drafter should still read the permitted ticket and return a draft. A system that blocks everything has not met the task. Keep model-quality evaluations separate from these deterministic host tests; a model asking nicely or choosing a valid tool does not prove authorization works.

Keep audit records useful enough to investigate a decision without storing unnecessary message content. In production, record who reviewed what action version, when it expired and what execution outcome followed. Protect those records against unauthorized modification and set retention rules. The fixture’s editable list only illustrates the record shape.

Start with a draft, then add controlled actions

Keep read, draft and send permissions separate. Before adding delivery, make the host bind approval to the exact actor, task and message, reject changed or expired decisions and recheck current permission. Run the failure cases before connecting a real service, and design recovery for uncertain delivery outcomes. The model proposes the action; the application remains responsible for whether it happens.

Topics: AI agents, authorization, least privilege, human approval, audit logs, Python

References