a2a_protocol_server/tool_loop/audited.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! A tool call is on the audit record before it runs
5//! (adversarial review A3, 2026-11-12).
6//!
7//! A [required](crate::audit::AuditLog::require_record) log makes sure a call
8//! is recorded as it starts and keeps the record of how it ended. A tool call
9//! inside a run is a finer action than the RPC that carries it, and may be the
10//! irreversible one: sending the message, moving the money. [`AuditedPolicy`]
11//! is the fail-closed boundary for it: it writes a `tool.action` record to the
12//! tenant's chain, and **an allowed call whose record the log cannot write is
13//! not run**.
14
15use std::future::Future;
16use std::pin::Pin;
17use std::sync::Arc;
18
19use a2a_protocol_types::audit::{Actor, AuditRecord, digest_of, kind};
20
21use super::policy::{PolicyDecision, PolicyRequest, ToolPolicy};
22use crate::audit::AuditLog;
23use crate::store::tenant::TenantContext;
24
25/// What the model is told when an action cannot be put on the record.
26const NOT_RECORDED: &str = "this action was not run: it could not be recorded in the audit log";
27
28/// A [`ToolPolicy`] that records every call before it runs.
29///
30/// It asks the policy it wraps first (every call is allowed when it wraps none),
31/// then writes a `tool.action` record: the tool, the call's id, whether it is
32/// read-only or was recovered from text, the decision, the authenticated caller,
33/// the task, and a SHA-256 digest of the arguments, never the arguments. The
34/// record goes to the chain of the request's tenant, with the call's other
35/// records.
36///
37/// `detail.decision` is one of:
38///
39/// * `allow`: the call is allowed and runs once this record is in the store,
40/// written before the call, not spooled for later: if the store refuses it,
41/// the call is answered as an error the model can read and is not run.
42/// * `deny`: it is not run. A record the store refuses is kept as any other
43/// record of a required log is; the call was not going to run.
44/// * `approval_required`: the wrapped policy sent it to a person, and it does
45/// not run now. Kept like a denial: nothing runs on it. Written again when the
46/// run resumes, since the policy is asked again.
47/// * `approved`: a person approved exactly this call (`detail.approvedBy`, the
48/// identity the approval gate verified, which [`AuditPrivacy`] seals) and it
49/// is about to run. Written durably like `allow`, immediately before the
50/// call ([`ToolPolicy::approved`]): **an approved call whose record the store
51/// refuses is not run** (adversarial review N02, 2026-11-13; until then an
52/// approved call ran with no record of running, and a healthy store said
53/// `deny` for it).
54///
55/// Install it with [`ToolLoop::with_policy`](super::ToolLoop::with_policy).
56/// Records are written by the loop's own task, in the tenant of the request,
57/// which is what [`ToolLoopExecutor`](super::ToolLoopExecutor) sets.
58///
59/// [`AuditPrivacy`]: crate::audit::AuditPrivacy
60pub struct AuditedPolicy {
61 log: Arc<AuditLog>,
62 inner: Option<Box<dyn ToolPolicy>>,
63}
64
65impl std::fmt::Debug for AuditedPolicy {
66 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67 f.debug_struct("AuditedPolicy")
68 .field("log", &self.log)
69 .field("wraps_a_policy", &self.inner.is_some())
70 .finish()
71 }
72}
73
74impl AuditedPolicy {
75 /// Records every call to `log` and decides nothing else: each is allowed
76 /// that the log can record.
77 #[must_use]
78 pub fn new(log: Arc<AuditLog>) -> Self {
79 Self { log, inner: None }
80 }
81
82 /// Asks `inner` first. A call it denies is recorded as denied and not run;
83 /// one it allows is recorded and then run.
84 #[must_use]
85 pub fn wrapping(mut self, inner: impl ToolPolicy) -> Self {
86 self.inner = Some(Box::new(inner));
87 self
88 }
89
90 /// The record of `request` and what was decided, or `None` if its
91 /// arguments cannot be digested.
92 fn record(request: &PolicyRequest<'_>, decision: &str) -> Option<AuditRecord> {
93 let mut r = AuditRecord::new(TenantContext::current(), kind::TOOL_ACTION);
94 r.actor = request.principal.map(|p| Actor::new(p, None));
95 r.task_id = request.task.map(str::to_owned);
96 r.digests
97 .insert("arguments".to_owned(), digest_of(request.arguments).ok()?);
98 for (key, value) in [
99 ("tool", request.tool.into()),
100 ("toolCallId", request.call_id.into()),
101 ("decision", decision.into()),
102 ("readOnly", request.read_only.into()),
103 ("recoveredFromText", request.recovered_from_text.into()),
104 ] {
105 r.detail.insert(key.to_owned(), value);
106 }
107 Some(r)
108 }
109
110 /// Writes a record a call that runs depends on: now, not spooled. `Err`
111 /// is what the model is told instead of the call running.
112 async fn before_running(&self, record: Option<AuditRecord>) -> Result<(), String> {
113 let Some(record) = record else {
114 return Err(NOT_RECORDED.to_owned());
115 };
116 // Written here and now: an action must not run on the promise of a
117 // record that a later retry might write.
118 match self.log.append(record).await {
119 Ok(_) => Ok(()),
120 Err(_error) => {
121 trace_error!(error = %_error, "audit: a tool action could not be recorded, so it was not run");
122 self.log.note_failure();
123 Err(NOT_RECORDED.to_owned())
124 }
125 }
126 }
127
128 /// Writes a record of a call that does not run: kept by a required log
129 /// when the store refuses it, and waited on by nothing.
130 async fn not_running(&self, record: AuditRecord) {
131 if self.log.is_required() {
132 let _ = self.log.append_required(record).await;
133 } else {
134 let _ = self.log.append(record).await;
135 }
136 }
137}
138
139impl ToolPolicy for AuditedPolicy {
140 fn authorize<'a>(
141 &'a self,
142 request: &'a PolicyRequest<'a>,
143 ) -> Pin<Box<dyn Future<Output = PolicyDecision> + Send + 'a>> {
144 Box::pin(async move {
145 let decision = match &self.inner {
146 Some(inner) => inner.authorize(request).await,
147 None => PolicyDecision::Allow,
148 };
149 let word = match &decision {
150 PolicyDecision::Allow => "allow",
151 PolicyDecision::RequireApproval(_) => "approval_required",
152 _ => "deny",
153 };
154 let record = Self::record(request, word);
155 if matches!(decision, PolicyDecision::Allow) {
156 return match self.before_running(record).await {
157 Ok(()) => decision,
158 Err(why) => PolicyDecision::Deny(why),
159 };
160 }
161 // Not going to run now: the record is kept, and nothing waits on it.
162 let Some(record) = record else {
163 return PolicyDecision::Deny(NOT_RECORDED.to_owned());
164 };
165 self.not_running(record).await;
166 decision
167 })
168 }
169
170 fn approved<'a>(
171 &'a self,
172 request: &'a PolicyRequest<'a>,
173 approver: &'a str,
174 ) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'a>> {
175 Box::pin(async move {
176 if let Some(inner) = &self.inner {
177 inner.approved(request, approver).await?;
178 }
179 let record = Self::record(request, "approved").map(|mut r| {
180 r.detail
181 .insert("approvedBy".to_owned(), serde_json::json!([approver]));
182 r
183 });
184 self.before_running(record).await
185 })
186 }
187}