Sub topic 11
Making sure the approved action is the action that runs
This chapter assumes you have read the earlier chapters on approval gates and decision types. You should be comfortable with the gate that pauses a run, the reviewer's approve, edit and reject decisions, and the saved state that lets a run resume. You should also be able to read short Python programs and JSON.
The gap between approval and execution
An approval is a statement about one specific action: "this email, to this person, with this body, may be sent." Between the moment a reviewer clicks approve and the moment the tool runs, time passes. A run may be paused for hours and resumed by a different worker process. During that time something can change the action.
If the gate records only "approved: true" for a run, it has approved a situation instead of an action. Anything that reaches the tool call afterward inherits the approval.
Three common ways the action changes:
- Re-planning on resume. The agent restarts from saved state, calls the model again, and the model produces a different tool call than the one the reviewer saw.
- Mutation in place. Code between the gate and the tool edits the arguments, for example a normalizer, a retry wrapper, or a bug.
- Replay. A stored approval is used a second time, or for a different run, so one click authorizes many actions.
Security people call the first two a time-of-check to time-of-use (TOCTOU) problem. You check the action at one moment and use it at another, and the thing you checked is no longer the thing you use. The fix is to tie the approval to the action's exact content and to verify that content immediately before execution.
Fingerprinting the action
A fingerprint is a short value computed from the action so that any change to the action changes the value. A cryptographic hash such as SHA-256 does this. You hash a canonical text form of the tool name and arguments.
import hashlib
import json
from dataclasses import dataclass
@dataclass(frozen=True)
class ToolCall:
name: str
args: dict
def fingerprint(call: ToolCall) -> str:
payload = json.dumps(
{"name": call.name, "args": call.args},
sort_keys=True,
separators=(",", ":"),
ensure_ascii=True,
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
a = ToolCall("send_email", {"to": "[email protected]", "subject": "Invoice"})
b = ToolCall("send_email", {"subject": "Invoice", "to": "[email protected]"})
c = ToolCall("send_email", {"to": "[email protected]", "subject": "Invoice"})
print(fingerprint(a) == fingerprint(b)) # True: key order does not matter
print(fingerprint(a) == fingerprint(c)) # False: recipient changedThe serialization settings matter, because the hash covers the bytes, not the meaning:
sort_keys=Truemakes{"a":1,"b":2}and{"b":2,"a":1}hash identically. Without it, a harmless reordering looks like tampering and blocks a legitimate run.- Fixed
separatorsremove whitespace differences. ensure_ascii=Trueescapes non-ASCII characters, so the output does not depend on the platform's text handling.
Each of these rules must be the same in the process that creates the fingerprint and the process that checks it. If they run different code versions, a fingerprint change after a deploy can invalidate every pending approval. Store a version label with each fingerprint, such as "fp_version": 1, so you can tell a format change from an attack.
Gotchas in what you hash
Non-JSON values
json.dumps raises TypeError on values such as datetime or bytes. Do not "fix" this with default=str without thinking. Two different objects can print as the same string, and then they would share a fingerprint. Convert such values to explicit forms (an ISO 8601 string, a base64 string) before they enter the arguments.
Floats and numbers
1 and 1.0 produce different JSON text, so they produce different hashes. That is the safe direction, since a false mismatch only asks for another approval. It still means you should keep argument types stable between the proposal and the execution.
Frozen does not mean immutable
@dataclass(frozen=True) blocks reassigning call.args, but the dictionary inside can still be changed:
call = ToolCall("delete_record", {"id": 7})
call.args["id"] = 8 # allowed: frozen only protects the attributeA fingerprint check at execution time catches this change. A better design stores the approved action itself, as a JSON string snapshot, and executes from that snapshot. Then there is no live object to mutate.
What the reviewer saw versus what you hashed
Hash exactly what you displayed. If the review screen shows a friendly summary ("Send invoice to Ana") but the hash covers the raw arguments, the reviewer approved a description and not the arguments. Render the summary from the same arguments you hash, and show the important raw values such as recipients, amounts and record ids.
Binding to more than the arguments
The arguments are not the only thing an approval should be tied to. A complete approval record also carries:
| Field | What it prevents |
|---|---|
| `fingerprint` | Running a different tool or different arguments |
| `run_id` | Using an approval from one run in another run |
| `expires_at` | Running an old approval long after the context changed |
| `used` flag | Running the same approved action twice |
| `approver` | Losing track of who accepted responsibility |
import hmac
import time
APPROVALS = {} # approval_id -> record; a database table in production
def grant(approval_id, run_id, call, approver, ttl_seconds=900):
APPROVALS[approval_id] = {
"run_id": run_id,
"fingerprint": fingerprint(call),
"approver": approver,
"expires_at": time.time() + ttl_seconds,
"used": False,
}
def execute_if_approved(call, approval_id, run_id, tools):
approval = APPROVALS.get(approval_id)
if approval is None:
raise PermissionError("No such approval")
if approval["run_id"] != run_id:
raise PermissionError("Approval belongs to a different run")
if approval["used"]:
raise PermissionError("Approval already used")
if time.time() > approval["expires_at"]:
raise PermissionError("Approval expired")
if not hmac.compare_digest(approval["fingerprint"], fingerprint(call)):
raise PermissionError("Approval does not match this action")
approval["used"] = True # consume before running
return tools[call.name](**call.args)
tools = {"delete_record": lambda id: f"deleted {id}"}
call = ToolCall("delete_record", {"id": 7})
grant("ap-1", "run-42", call, approver="sam")
print(execute_if_approved(call, "ap-1", "run-42", tools)) # deleted 7
try:
execute_if_approved(call, "ap-1", "run-42", tools)
except PermissionError as err:
print(err) # Approval already usedTwo details in this code are deliberate.
First, the approval is marked used before the tool runs. If the process crashed between running and marking, the approval would still be live and a retry could run the action twice. Marking first means a crash leaves an approval consumed but the action not done. That failure is visible and safe: a person can request a new approval. For actions that must not be lost, pair this with an idempotency key, a unique id the downstream system uses to ignore duplicate requests.
Second, hmac.compare_digest compares two strings in constant time. A plain == is fine for a hash computed from data you already hold, but the habit costs nothing and avoids timing leaks if the fingerprint ever crosses a trust boundary.
In a real database, the check-and-consume step must be one atomic operation, for example UPDATE approvals SET used = true WHERE id = ? AND used = false, then checking that one row changed. Two workers reading used = false at the same moment would otherwise both run the action.
Edits and feedback
When a reviewer edits the arguments, the approval applies to the edited call. The gate must compute the fingerprint from the edited call, not from the original proposal. A common bug is to grant the approval for the original fingerprint and then execute the edited call, which makes the check fail, or to skip the check on the edit path, which makes it meaningless.
Treat an edit as "reject the original, approve a new action." Record both in the trail. For reject and feedback decisions, no approval record is created for the action, and the agent's next proposal starts the process over with a fresh fingerprint.
Common errors
- Approving by run, not by action. A single
approvedflag on the run lets later tool calls ride along. - Re-asking the model on resume. Execute the stored approved call. Do not regenerate it.
- Hashing a summary. The hash should cover the same arguments the tool will receive.
- Silent fallback on mismatch. If the check fails, stop and ask again. Do not run a "close enough" version.
- Unbounded approvals. An approval with no expiry or no use limit becomes a standing permission.
Exercise
A reviewer approves transfer_funds with {"to": "acct-1", "amount": 100}. After a restart, the agent resumes and the model regenerates the call as {"to": "acct-1", "amount": 1000}. Using the code in this chapter, what happens when execute_if_approved runs, and what two design choices make that outcome possible?
Show answer
The fingerprint of the regenerated call differs from the stored one, so hmac.compare_digest returns false and the function raises PermissionError("Approval does not match this action"). The tool never runs. This works because (1) the approval stores a hash of the exact tool name and arguments at the time of review, and (2) the executor recomputes the hash from the call it is about to run instead of trusting an approved flag. Storing and executing the approved call snapshot, rather than regenerating it, would avoid the mismatch entirely.