When the agent can write: securing write access
An agent that changes data needs declared write operations, an approval that shows the change in plain text, and a tamper-evident log. The server enforces all of this; the prompt does not.
My analysis, written up with AI.
As long as an agent only reads, the worst outcome is usually a data leak. That is serious, but it is limited by what the agent is allowed to see. If the same agent can write, a wrong access changes the state of your system, often unnoticed and often with consequences in downstream systems: a delivery goes to the wrong address, a contract gets canceled, a record disappears.
This text describes the pattern I use to secure agents’ write access in production systems I have built. The example is deliberately plain: an agent that processes orders. The full code is a single Python script without dependencies, and the excerpts below come from it. It runs with python3 3.10 or later. The script uses German identifiers and messages; the excerpts below translate them.
1. Reading and writing are separate problems
For read access, the question is: what may this agent see on behalf of this person? The answer lives in the permission and retrieval layer. For write access, three more questions come up. Is this change permitted in this state at all? Has a human understood what will happen before it happens? And can you show afterwards, without gaps, who triggered, saw and approved what?
The OWASP Top 10 for Agentic Applications 2026 name these risks. ASI02 Tool Misuse and Exploitation describes the case where an agent uses a legitimate tool unsafely within its permissions, explicitly including the example of deleting valuable data. ASI03 Identity and Privilege Abuse applies as soon as the agent has more permissions than the person it acts for. ASI09 Human-Agent Trust Exploitation describes how people approve actions they have not checked because the agent sounds convincing (OWASP GenAI Security Project 2025).
The cause is often prompt injection rather than a bug in the code. An agent that sees private data, reads untrusted content and can communicate externally combines what Simon Willison calls the “lethal trifecta” (Willison 2025). With write access, the attack needs even less: it no longer has to get anything out; it is enough if it changes something. Meta took this up in its “Agents Rule of Two”. There, the ability to change state sits next to external communication. Within a session, an agent should have no more than two of three properties: processing untrustworthy inputs, access to sensitive systems or private data, and changing state or communicating externally. If it needs all three, it should not run autonomously but at a minimum under supervision, for example with human-in-the-loop approval (Meta 2025). This text is about exactly that case. A crafted document in the context can be enough for the agent to propose a plausible but wrong change. That is why the model must never be the one to decide whether a change is permitted.
2. Declared write operations
The agent does not get a generic “update record” tool. It gets a small set of named write operations, and each one is declared: which entity, which fields, which permission, which preconditions and how high the impact is.
Precondition = Callable[[dict, dict], str | None] # (current, changes) -> error or None
@dataclass(frozen=True)
class WriteOperation:
name: str
entity: str
permission: str
fields: frozenset[str]
preconditions: tuple[Precondition, ...] = ()
high_impact: bool = False
batchable: bool = True
WriteOperation(
name="change_shipping_address",
entity="order",
permission="order.edit",
fields=frozenset({"street", "postcode", "city"}),
preconditions=(status_is("open", "in_review"),),
)
Three properties matter here.
The check runs on the server. The declaration is code that the server runs before every change. It is not a description for the model. What the system prompt says (“only change open orders”) is a hint at best. It is enforced here:
def _check(self, operation: str, target: str, changes: dict, actor: str):
c = OPERATIONS.get(operation)
if c is None:
raise Denied(f"no operation '{operation}'")
if c.permission not in self.grants.get(actor, set()):
raise Denied(f"{actor} lacks {c.permission}")
extra = set(changes) - c.fields
if extra:
raise Denied(f"fields outside the operation: {sorted(extra)}")
current = self.store.get(target)
if current is None or current["entity"] != c.entity:
raise Denied(f"target {target} does not match {c.entity}")
for pre in c.preconditions:
if (err := pre(current, changes)) is not None:
raise Denied(err)
return c, current
The agent acts with the person’s permissions. In the example, the actor is called agent:mia and has exactly Mia’s permissions, with no service account behind it. This part addresses ASI03. An agent that runs with admin rights and is supposed to “be careful” moves the permission check into the model.
Preconditions check the state as well as the input. An address change is permitted for an open order and not for a shipped one. A cancellation is only allowed as a transition from open to canceled. These rules usually already exist somewhere in the business logic. The declaration makes them binding for the agent’s write path and visible in one place.
The side effect is an inventory. If you list the declared operations, you know what the agent can change at all. That is the basis for every review and for the evals further down.
3. The approval has to show what will happen
Many approval dialogs I have seen show a sentence like “The agent wants to update the order. Allow?”. That does not tell the person what changes. Others show the model’s reasoning, which is exactly the text an attack can influence most easily. Under ASI09, OWASP explicitly recommends a plain-language risk summary, “not model-generated rationales”, and under ASI02 a dry run or diff before high-impact actions (OWASP GenAI Security Project 2025).
In this pattern, the server therefore generates the diff, from the stored state and the requested fields. The model writes none of it.
def render_diff(c: WriteOperation, target: str, current: dict, changes: dict) -> list[str]:
lines = [f"{c.name} on {target} (version {current['version']})"]
for k in sorted(changes):
old, new = current.get(k), changes[k]
if old != new:
lines.append(f" {LABELS.get(k, k)}: {old!r} -> {new!r}")
return lines
The output in the demo run:
change_shipping_address on B-1 (version 1)
City: 'München' -> 'Augsburg'
Postcode: '80331' -> '86150'
Two details matter here.
First, the approval is bound to exactly what was shown. When the proposal is made, the server computes a hash over target, version, operation and changes. The interface sends this hash back with the approval. If it does not match, nothing is written. That way, nothing can be swapped between display and click.
Second, the server checks everything again at approval time, against the current state. Minutes or hours can pass between proposal and click, and the order may have changed in that time. The version number catches this:
for p in items: # re-check against current state, not the state at proposal time
c, current = self._check(p.operation, p.target, p.changes, approver)
if current["version"] != p.version:
raise Denied(f"{p.target} was changed since the proposal")
The approval has its own actor. The server checks the permissions of the approving person, independent of the agent that made the proposal. For high-impact operations, in the example the cancellation, nobody may approve their own proposal. For the demo, that is enough as a four-eyes rule. In a real system, this is where you add the distinction of whether the proposal came from the agent on the person’s behalf or from the person directly.
4. Batch approvals without rubber-stamping
As soon as an agent is useful, it proposes many changes at once. Twenty separate dialogs reliably lead to nobody reading by the fifth. A batch approval makes sense, but only with rules that keep it readable. In the systems I have built, these have proven themselves:
- One operation per batch. Twenty address changes can be read as a table; twenty mixed operations cannot.
- High impact is never batchable. Cancellations, deletions, payments and permission changes are approved one at a time. In the declaration this is
batchable=False. - An upper limit. Anything above it is split. The limit depends on what one person can review with focus.
- One hash over the whole batch. The approval applies to exactly the entries shown. If one of them changes between display and click, the entire batch fails.
def _check_batch(self, items: list[Pending], approver: str, shown_digest: str) -> None:
if len(items) > 1:
operations = {p.operation for p in items}
if len(operations) != 1:
raise Denied("batch approval only for a single operation")
if not OPERATIONS[operations.pop()].batchable:
raise Denied("operation does not allow batch approval")
if len(items) > self.max_batch:
raise Denied(f"more than {self.max_batch} entries")
if batch_digest(items) != shown_digest:
raise Denied("approval does not match the change shown")
In the demo run, the agent proposes three address changes. While the batch is displayed, another process changes one of the orders. The approval is refused: “B-4 was changed since the proposal”. Writing all or nothing is deliberate. Whoever approves a batch has an overall state in mind. Half executed, it matches no state that was ever shown.
The interface follows one more rule: the batch shows every line of the diff in addition to any summary, and highlights entries that deviate from the pattern of the others. If nineteen addresses move within Munich and one moves overseas, that one should stand out.
The most effective measure is to ask less often. The CaMeL paper by researchers at Google, Google DeepMind and ETH Zurich calls the problem “user fatigue”: users become desensitized to security prompts and may end up approving malicious actions (Debenedetti et al. 2025). There, policies decide when to ask. An email does not violate the policy if the recipients come directly from the user. If an address comes from untrusted content, the action is not blocked but runs only after confirmation. Applied to the declaration, every operation gets one of three levels: it runs without approval, it needs approval, or it is not offered to the agent at all. Only operations with low impact whose values come entirely from a trusted source run without approval. The example script only implements the last two levels.
5. Fail-closed: what applies when the check itself fails
Preconditions often depend on other services: inventory, customer status, contract data. These services go down, time out or return something unexpected. If the write path does not know the answer, only one reaction is defensible: do not write.
Code often violates this. A try/except that simply carries on when the check errors, a feature flag that defaults to “allowed” on failure, a default value for a missing role: each of these lets the write through exactly when the check fails. OWASP states this directly for ambiguous tool resolution: “Fail closed on ambiguous resolution” (OWASP GenAI Security Project 2025).
In the pattern, this is one place with two branches:
try:
c, current = self._check(operation, target, changes, actor)
except Denied as e:
self.log.append("denied", cid, operation=operation, target=target, actor=actor, reason=str(e))
raise
except Exception as e: # fail closed: a broken check is a denial
self.log.append("denied", cid, operation=operation, target=target, actor=actor,
reason=f"check failed: {type(e).__name__}")
raise Denied("check not possible") from e
A business rejection and a technically failed check both end as a denial, but they are logged separately. The distinction matters for operations. If technical denials pile up, a service is degraded, and an alert should say so before confused users reach support.
Fail-closed means the agent can do less during outages. That is fine as long as it is visible. The agent should tell the person that the change is not possible right now, instead of silently retrying.
6. Audit log and monitoring
An audit log for agents’ write access has to do more than an application log. It has to show who asked, what the agent proposed, which diff was shown, who approved it and what was written in the end. And it has to be built so that later changes are noticed. Under ASI02, OWASP calls for “immutable logs of all tool invocations and parameter changes”, and under ASI09 for “tamper-proof records” (OWASP GenAI Security Project 2025).
Correlation IDs. Every user request gets an ID that travels through all steps: model call, tool call, proposal, approval, database write. In the example it is req-7f3a. With this ID, a single operation can be reconstructed from the question to the changed row. Without it, you are left with separate logs from separate services that you piece together by hand using timestamps.
Hash chaining. Every entry contains the hash of its predecessor. Changing an entry afterwards breaks the chain from that point on.
def append(self, event: str, correlation_id: str, **data) -> dict:
prev = self._entries[-1]["hash"] if self._entries else "0" * 64
entry = {
"seq": len(self._entries),
"ts": datetime.now(timezone.utc).isoformat(),
"event": event,
"correlation_id": correlation_id,
"data": data,
"prev": prev,
}
entry["hash"] = _digest(entry)
self._entries.append(entry)
return entry
In the demo run, the approving person in one entry is swapped after the last step. verify() then returns False. A hash chain alone does not protect against rewriting the entire log. That needs a second location: regularly write the latest hash to a system with its own permissions, for example an object store with a retention lock. The chain shows whether the log is internally consistent. Comparing it with the externally stored hash shows whether it was rewritten.
Alerts. The audit log is also the data source for monitoring. Two patterns have proven useful: repeated denials per actor, and approvals where the proposing and approving identity are the same. Repeated denials almost always mean one of two things: the agent has been manipulated and is probing, or it is poorly calibrated and offers things that are not possible.
def alerts(log: AuditLog, max_denials: int = 3) -> list[str]:
out, denials = [], {}
for e in log.entries():
if e["event"] in ("denied", "approval_refused"):
actor = e["data"].get("actor") or e["data"].get("approver")
denials[actor] = denials.get(actor, 0) + 1
if denials[actor] == max_denials:
out.append(f"{actor}: {max_denials} denied write attempts")
if e["event"] == "executed" and e["data"]["approver"] == e["data"]["proposed_by"]:
out.append(f"{e['correlation_id']}: self-approval by {e['data']['approver']}")
return out
In the demo run, the rule fires after three denials: a shipped order, one that does not exist, and a check that could not run because of a timeout.
7. Evals for write paths
Most evals for agents measure whether the answer is good. For write paths, a different question matters more: does the agent only offer what the person is actually allowed to do? An agent that regularly proposes cancellations that then fail on the server produces denials, noise in monitoring and users who learn to click away error messages.
The first level is deterministic and belongs in CI: for every operation and the roles the agent acts for, it checks that what is offered to the agent matches the server-side check.
cases = [
("agent:mia", "change_shipping_address", "B-2", {"city": "Köln"}, True),
("agent:mia", "cancel_order", "B-2", {"status": "canceled"}, False),
("agent:mia", "change_shipping_address", "B-3", {"city": "Köln"}, False),
("agent:mia", "change_shipping_address", "B-2", {"price": 0}, False),
("agent:mia", "delete_order", "B-2", {}, False),
]
These cases cover the four boundaries that matter: missing permission, wrong state, fields outside the operation and an operation that does not exist. On top of that comes the condition that the agent is only offered the operations the person is authorized for. In the example, offered_operations("agent:mia") returns only change_shipping_address. The cancellation tool is not visible to Mia’s agent at all.
The second level tests the model itself. You run realistic requests, including some with crafted content in the context, and count how often the agent makes a proposal that the server rejects. This number should be close to zero and should be measured again on every change of model, prompt or tool list. If it rises, that is a finding, even if not a single wrong write got through. The safeguards worked in that case, while the agent’s behavior shifted.
What the pattern does not do
Declared write operations do not prevent changes that are wrong in substance but satisfy every rule. If the agent takes a plausible address from a crafted document and the order is open, the proposal passes every check. The diff is then the last line of defense, and it only helps if it is short and clear enough for a human to spot the one wrong line. The pattern also does not replace database transactions. In the example everything is in memory. In a real system, the check and the write with version check belong in the same transaction.
Nor does it replace a test from the outside. It limits, in the architecture, what a successful attack can reach.
What I check here
For an agent with write access, I first check whether there is a closed list of write operations, and I read it. Then: whether preconditions and permissions are enforced on the server or only stated in the prompt; whose identity is used for writing; whether the approval shows a server-generated diff and is bound to exactly that diff; which rules apply to batch approvals; what happens in the code when a check throws an exception; whether a single operation can be traced from the question to the write through a correlation ID, and whether the audit log makes tampering detectable; which alerts exist; and whether evals measure how often the agent offers things it is not allowed to do. Every finding comes with a concrete proposal for the change.
Sources
- Debenedetti, E. et al. (2025): Defeating Prompt Injections by Design. https://arxiv.org/abs/2503.18813
- Meta (2025): Agents Rule of Two: A Practical Approach to AI Agent Security. https://ai.meta.com/blog/practical-ai-agent-security/
- OWASP GenAI Security Project (2025): OWASP Top 10 for Agentic Applications for 2026. https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/
- Willison, S. (2025): The lethal trifecta for AI agents: private data, untrusted content, and external communication. https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/