use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::principal::{ActingContext, SubjectKind, SubjectRef};
use crate::{
AdkError, ApprovalScope, ApprovalStore, Clock, DurableRunStore, ErrorCategory, ErrorComponent,
ErrorDetails, Result, SystemClock, ToolApproval, ToolConfirmationRequest, ToolOrigin,
};
pub const DEFAULT_APPROVAL_PAGE: usize = 100;
pub const APPROVAL_REAPPLY_GRACE: Duration = Duration::from_secs(60);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ApprovalAction {
Approve,
Edit,
Reject,
Respond,
}
impl ApprovalAction {
pub const ALL: [Self; 4] = [Self::Approve, Self::Edit, Self::Reject, Self::Respond];
}
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
)]
#[serde(rename_all = "camelCase")]
pub enum ApprovalRisk {
Low,
#[default]
Medium,
High,
Critical,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ApproverSelector {
Subject(SubjectRef),
Group(String),
}
impl ApproverSelector {
pub fn human(id: impl Into<String>) -> Self {
Self::Subject(SubjectRef::human(id))
}
pub fn group(group: impl Into<String>) -> Self {
Self::Group(group.into())
}
pub fn matches(&self, subject: &SubjectRef, groups: &[String]) -> bool {
match self {
Self::Subject(selected) => selected == subject,
Self::Group(group) => groups.iter().any(|member_of| member_of == group),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EscalationStep {
#[serde(rename = "afterSecs", with = "duration_secs")]
pub after: Duration,
pub to: Vec<ApproverSelector>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum ExpiryAction {
#[default]
Deny,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalPolicy {
pub approvers: Vec<ApproverSelector>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub slots: Vec<ApproverSelector>,
pub quorum: u32,
pub forbid_self_approval: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub escalation: Vec<EscalationStep>,
#[serde(default)]
pub on_expiry: ExpiryAction,
#[serde(
default,
rename = "expiresAfterSecs",
with = "option_duration_secs",
skip_serializing_if = "Option::is_none"
)]
pub expires_after: Option<Duration>,
}
impl ApprovalPolicy {
pub fn new(approvers: impl IntoIterator<Item = ApproverSelector>) -> Self {
Self {
approvers: approvers.into_iter().collect(),
slots: Vec::new(),
quorum: 1,
forbid_self_approval: true,
escalation: Vec::new(),
on_expiry: ExpiryAction::Deny,
expires_after: None,
}
}
pub fn for_slots(slots: impl IntoIterator<Item = ApproverSelector>) -> Self {
let slots: Vec<ApproverSelector> = slots.into_iter().collect();
let quorum = u32::try_from(slots.len()).unwrap_or(u32::MAX).max(1);
Self { slots, quorum, ..Self::new([]) }
}
#[must_use]
pub fn with_slots(mut self, slots: impl IntoIterator<Item = ApproverSelector>) -> Self {
self.slots.extend(slots);
self
}
#[must_use]
pub fn with_quorum(mut self, quorum: u32) -> Self {
self.quorum = quorum;
self
}
#[must_use]
pub fn allow_self_approval(mut self) -> Self {
self.forbid_self_approval = false;
self
}
#[must_use]
pub fn escalate_after(
mut self,
after: Duration,
to: impl IntoIterator<Item = ApproverSelector>,
) -> Self {
self.escalation.push(EscalationStep { after, to: to.into_iter().collect() });
self
}
#[must_use]
pub fn expires_after(mut self, ttl: Duration) -> Self {
self.expires_after = Some(ttl);
self
}
pub fn validate(&self) -> Result<()> {
if self.approvers.is_empty() && self.slots.is_empty() {
return Err(invalid(
"approval.invalid_policy",
"an approval policy needs approvers or slots",
));
}
if self.quorum == 0 {
return Err(invalid(
"approval.invalid_policy",
"an approval quorum must be at least 1",
));
}
if self.escalation.windows(2).any(|pair| pair[0].after > pair[1].after) {
return Err(invalid(
"approval.invalid_policy",
"escalation steps must be ordered by their `after` delay",
));
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ApprovalState {
Pending,
Approved,
Rejected,
Responded,
Expired,
Cancelled,
}
impl ApprovalState {
pub const ALL: [Self; 6] = [
Self::Pending,
Self::Approved,
Self::Rejected,
Self::Responded,
Self::Expired,
Self::Cancelled,
];
pub fn as_str(self) -> &'static str {
match self {
Self::Pending => "pending",
Self::Approved => "approved",
Self::Rejected => "rejected",
Self::Responded => "responded",
Self::Expired => "expired",
Self::Cancelled => "cancelled",
}
}
pub fn is_terminal(self) -> bool {
!matches!(self, Self::Pending)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalDecision {
pub approver: SubjectRef,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub approver_groups: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub via_delegation: Option<SubjectRef>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub authority_groups: Vec<String>,
pub kind: ApprovalAction,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub edited_args: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
pub decided_at: DateTime<Utc>,
}
impl ApprovalDecision {
fn new(approver: SubjectRef, kind: ApprovalAction) -> Self {
Self {
approver,
approver_groups: Vec::new(),
via_delegation: None,
authority_groups: Vec::new(),
kind,
edited_args: None,
reason: None,
decided_at: Utc::now(),
}
}
pub fn approve(approver: SubjectRef) -> Self {
Self::new(approver, ApprovalAction::Approve)
}
pub fn edit(approver: SubjectRef, args: Value) -> Self {
Self { edited_args: Some(args), ..Self::new(approver, ApprovalAction::Edit) }
}
pub fn reject(approver: SubjectRef, reason: impl Into<String>) -> Self {
Self { reason: Some(reason.into()), ..Self::new(approver, ApprovalAction::Reject) }
}
pub fn respond(approver: SubjectRef, response: impl Into<String>) -> Self {
Self { reason: Some(response.into()), ..Self::new(approver, ApprovalAction::Respond) }
}
#[must_use]
pub fn with_groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.approver_groups = groups.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn via(mut self, delegator: SubjectRef) -> Self {
self.via_delegation = Some(delegator);
self
}
#[must_use]
pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
pub fn authority(&self) -> &SubjectRef {
self.via_delegation.as_ref().unwrap_or(&self.approver)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalRequest {
pub id: String,
pub scope: ApprovalScope,
pub fingerprint: String,
pub tool_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<ToolOrigin>,
pub args_redacted: Value,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub evidence: Vec<crate::Evidence>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub acting: Option<ActingContext>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub requester: Option<SubjectRef>,
pub summary: String,
#[serde(default)]
pub risk: ApprovalRisk,
pub created_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<DateTime<Utc>>,
pub allowed_actions: Vec<ApprovalAction>,
pub policy: ApprovalPolicy,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run_id: Option<String>,
pub version: u64,
pub state: ApprovalState,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub decisions: Vec<ApprovalDecision>,
#[serde(default)]
pub escalations_fired: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolved_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
#[serde(default)]
pub outcome_applied: bool,
}
impl ApprovalRequest {
pub fn new(
id: impl Into<String>,
scope: ApprovalScope,
call: &ToolConfirmationRequest,
policy: ApprovalPolicy,
) -> Self {
Self {
id: id.into(),
scope,
fingerprint: call.fingerprint(),
tool_name: call.tool_name.clone(),
origin: call.origin.clone(),
args_redacted: call.args.clone(),
evidence: call.evidence.clone(),
acting: None,
requester: None,
summary: format!("Approve a call to '{}'", call.tool_name),
risk: ApprovalRisk::Medium,
created_at: Utc::now(),
expires_at: None,
allowed_actions: ApprovalAction::ALL.to_vec(),
policy,
run_id: None,
version: 1,
state: ApprovalState::Pending,
decisions: Vec::new(),
escalations_fired: 0,
resolved_at: None,
note: None,
outcome_applied: false,
}
}
pub fn id_for_call(
scope: &ApprovalScope,
fingerprint: &str,
held_since: DateTime<Utc>,
) -> String {
let key = serde_json::json!([
scope.app_name,
scope.user_id,
scope.session_id,
fingerprint,
held_since.timestamp_micros()
]);
let digest = crate::action_ledger::json_digest(&key);
format!("apr_{}", digest.trim_start_matches("fnv1a128:"))
}
#[must_use]
pub fn with_summary(mut self, summary: impl Into<String>) -> Self {
self.summary = summary.into();
self
}
#[must_use]
pub fn with_risk(mut self, risk: ApprovalRisk) -> Self {
self.risk = risk;
self
}
#[must_use]
pub fn with_origin(mut self, origin: ToolOrigin) -> Self {
self.origin = Some(origin);
self
}
#[must_use]
pub fn with_redacted_args(mut self, args: Value) -> Self {
self.args_redacted = args;
self
}
#[must_use]
pub fn with_evidence(mut self, evidence: impl IntoIterator<Item = crate::Evidence>) -> Self {
self.evidence.extend(evidence);
self
}
#[must_use]
pub fn with_acting(mut self, acting: ActingContext) -> Self {
if self.requester.is_none() {
self.requester = acting.on_behalf_of.clone();
}
self.acting = Some(acting);
self
}
#[must_use]
pub fn with_requester(mut self, requester: SubjectRef) -> Self {
self.requester = Some(requester);
self
}
#[must_use]
pub fn with_run_id(mut self, run_id: impl Into<String>) -> Self {
self.run_id = Some(run_id.into());
self
}
#[must_use]
pub fn with_expires_at(mut self, at: DateTime<Utc>) -> Self {
self.expires_at = Some(at);
self
}
#[must_use]
pub fn with_allowed_actions(
mut self,
actions: impl IntoIterator<Item = ApprovalAction>,
) -> Self {
self.allowed_actions = actions.into_iter().collect();
self
}
pub fn shows_call_args(&self) -> bool {
let shown = crate::tool_call_fingerprint(&self.tool_name, &self.args_redacted);
self.fingerprint.strip_suffix(shown.as_str()).is_some_and(|rest| rest.ends_with('\u{1f}'))
}
pub fn is_open(&self) -> bool {
self.state == ApprovalState::Pending || !self.outcome_applied
}
pub fn eligible_approvers(&self) -> impl Iterator<Item = &ApproverSelector> {
let fired = usize::try_from(self.escalations_fired).unwrap_or(usize::MAX);
self.policy
.approvers
.iter()
.chain(self.policy.slots.iter())
.chain(self.policy.escalation.iter().take(fired).flat_map(|step| step.to.iter()))
}
pub fn is_eligible(&self, subject: &SubjectRef, groups: &[String]) -> bool {
self.eligible_approvers().any(|selector| selector.matches(subject, groups))
}
pub fn is_self(&self, subject: &SubjectRef) -> bool {
let same_party = |other: &SubjectRef| {
other.id == subject.id
&& (other.kind == subject.kind
|| (other.kind != SubjectKind::Agent && subject.kind != SubjectKind::Agent))
};
self.requester.as_ref().is_some_and(same_party)
|| self.acting.as_ref().is_some_and(|acting| {
acting.on_behalf_of.as_ref().is_some_and(same_party)
|| SubjectRef::agent(&acting.agent.id) == *subject
})
}
pub fn quorum_progress(&self) -> (Vec<SubjectRef>, Option<Value>) {
let (counted, args) = self.counted_approvals();
(counted.into_iter().map(|decision| decision.authority().clone()).collect(), args)
}
fn counted_approvals(&self) -> (Vec<&ApprovalDecision>, Option<Value>) {
let mut approvals: Vec<&ApprovalDecision> = Vec::new();
let mut args = None;
for decision in &self.decisions {
match decision.kind {
ApprovalAction::Approve => {
if !approvals.iter().any(|held| held.authority() == decision.authority()) {
approvals.push(decision);
}
}
ApprovalAction::Edit => {
approvals.clear();
approvals.push(decision);
args = decision.edited_args.clone();
}
ApprovalAction::Reject | ApprovalAction::Respond => {}
}
}
(approvals, args)
}
pub fn open_slots(&self) -> Vec<&ApproverSelector> {
self.slot_holders()
.into_iter()
.filter(|(_, holder)| holder.is_none())
.map(|(slot, _)| slot)
.collect()
}
pub fn slot_holders(&self) -> Vec<(&ApproverSelector, Option<&ApprovalDecision>)> {
let slots = &self.policy.slots;
if slots.is_empty() {
return Vec::new();
}
let (approvals, _) = self.counted_approvals();
fn assign(
approver: usize,
approvals: &[&ApprovalDecision],
slots: &[ApproverSelector],
seen: &mut [bool],
filled_by: &mut [Option<usize>],
) -> bool {
let decision = approvals[approver];
for (slot, selector) in slots.iter().enumerate() {
if seen[slot] || !selector.matches(decision.authority(), &decision.authority_groups)
{
continue;
}
seen[slot] = true;
let free = match filled_by[slot] {
None => true,
Some(holder) => assign(holder, approvals, slots, seen, filled_by),
};
if free {
filled_by[slot] = Some(approver);
return true;
}
}
false
}
let mut filled_by: Vec<Option<usize>> = vec![None; slots.len()];
for approver in 0..approvals.len() {
let mut seen = vec![false; slots.len()];
assign(approver, &approvals, slots, &mut seen, &mut filled_by);
}
slots
.iter()
.zip(filled_by)
.map(|(slot, holder)| (slot, holder.map(|i| approvals[i])))
.collect()
}
pub fn outcome(&self) -> Option<ToolApproval> {
let last_reason = || self.decisions.last().and_then(|decision| decision.reason.clone());
match self.state {
ApprovalState::Pending => None,
ApprovalState::Approved => {
let approval = ToolApproval::approve();
Some(match self.quorum_progress().1 {
Some(args) => approval.with_edited_args(args),
None => approval,
})
}
ApprovalState::Rejected => {
Some(ToolApproval::deny().with_message(match last_reason() {
Some(reason) => format!("the approver rejected it: {reason}"),
None => "the approver rejected it".to_string(),
}))
}
ApprovalState::Responded => Some(ToolApproval::deny().with_message(format!(
"the approver responded instead: {}",
last_reason().unwrap_or_default()
))),
ApprovalState::Expired => Some(
ToolApproval::deny()
.with_message("the approval request expired before enough approvers decided"),
),
ApprovalState::Cancelled => Some(ToolApproval::deny().with_message(match &self.note {
Some(note) => format!("the approval request was cancelled: {note}"),
None => "the approval request was cancelled".to_string(),
})),
}
}
pub fn cursor(&self) -> ApprovalCursor {
ApprovalCursor { created_at: self.created_at, id: self.id.clone() }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DelegationWindow {
pub not_before: DateTime<Utc>,
pub not_after: DateTime<Utc>,
}
impl DelegationWindow {
pub fn new(not_before: DateTime<Utc>, not_after: DateTime<Utc>) -> Self {
Self { not_before, not_after }
}
pub fn contains(&self, at: DateTime<Utc>) -> bool {
self.not_before <= at && at < self.not_after
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DelegationScope {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub app_name: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tool_names: Vec<String>,
}
impl DelegationScope {
pub fn covers(&self, request: &ApprovalRequest) -> bool {
self.app_name.as_ref().is_none_or(|app| *app == request.scope.app_name)
&& (self.tool_names.is_empty() || self.tool_names.contains(&request.tool_name))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalDelegation {
pub id: String,
pub from: SubjectRef,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub from_groups: Vec<String>,
pub to: SubjectRef,
pub window: DelegationWindow,
#[serde(default)]
pub scope: DelegationScope,
pub created_at: DateTime<Utc>,
}
impl ApprovalDelegation {
pub fn new(from: SubjectRef, to: SubjectRef, window: DelegationWindow) -> Self {
Self {
id: format!("dlg_{}", uuid::Uuid::new_v4().simple()),
from,
from_groups: Vec::new(),
to,
window,
scope: DelegationScope::default(),
created_at: Utc::now(),
}
}
#[must_use]
pub fn with_from_groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.from_groups = groups.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn with_scope(mut self, scope: DelegationScope) -> Self {
self.scope = scope;
self
}
pub fn applies_to(&self, request: &ApprovalRequest, at: DateTime<Utc>) -> bool {
self.window.contains(at)
&& self.scope.covers(request)
&& request.is_eligible(&self.from, &self.from_groups)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalCursor {
pub created_at: DateTime<Utc>,
pub id: String,
}
impl ApprovalCursor {
pub fn precedes(&self, request: &ApprovalRequest) -> bool {
(request.created_at, request.id.as_str()) > (self.created_at, self.id.as_str())
}
pub fn encode(&self) -> String {
format!("{}:{}", self.created_at.timestamp_micros(), self.id)
}
pub fn decode(token: &str) -> Result<Self> {
let malformed = || invalid("approval.invalid_cursor", "malformed approval page cursor");
let (micros, id) = token.split_once(':').ok_or_else(malformed)?;
let created_at = micros
.parse::<i64>()
.ok()
.and_then(DateTime::from_timestamp_micros)
.ok_or_else(malformed)?;
Ok(Self { created_at, id: id.to_string() })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ApprovalRequestQuery {
pub states: Vec<ApprovalState>,
pub open_only: bool,
pub app_name: Option<String>,
pub user_id: Option<String>,
pub session_id: Option<String>,
pub after: Option<ApprovalCursor>,
pub limit: usize,
}
impl Default for ApprovalRequestQuery {
fn default() -> Self {
Self {
states: Vec::new(),
open_only: false,
app_name: None,
user_id: None,
session_id: None,
after: None,
limit: DEFAULT_APPROVAL_PAGE,
}
}
}
impl ApprovalRequestQuery {
#[must_use]
pub fn with_states(mut self, states: impl IntoIterator<Item = ApprovalState>) -> Self {
self.states = states.into_iter().collect();
self
}
#[must_use]
pub fn open_only(mut self) -> Self {
self.open_only = true;
self
}
#[must_use]
pub fn with_app_name(mut self, app_name: impl Into<String>) -> Self {
self.app_name = Some(app_name.into());
self
}
#[must_use]
pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
self.session_id = Some(session_id.into());
self
}
#[must_use]
pub fn with_user_id(mut self, user_id: impl Into<String>) -> Self {
self.user_id = Some(user_id.into());
self
}
#[must_use]
pub fn with_session(self, scope: &ApprovalScope) -> Self {
self.with_app_name(scope.app_name.clone())
.with_user_id(scope.user_id.clone())
.with_session_id(scope.session_id.clone())
}
#[must_use]
pub fn with_after(mut self, cursor: Option<ApprovalCursor>) -> Self {
self.after = cursor;
self
}
#[must_use]
pub fn with_limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}
pub fn matches(&self, request: &ApprovalRequest) -> bool {
(self.states.is_empty() || self.states.contains(&request.state))
&& (!self.open_only || request.is_open())
&& self.app_name.as_ref().is_none_or(|app| *app == request.scope.app_name)
&& self.user_id.as_ref().is_none_or(|user| *user == request.scope.user_id)
&& self.session_id.as_ref().is_none_or(|session| *session == request.scope.session_id)
&& self.after.as_ref().is_none_or(|cursor| cursor.precedes(request))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct InboxQuery {
pub approver: Option<SubjectRef>,
pub groups: Vec<String>,
pub states: Vec<ApprovalState>,
pub app_name: Option<String>,
pub user_id: Option<String>,
pub session_id: Option<String>,
pub cursor: Option<String>,
pub limit: usize,
}
impl Default for InboxQuery {
fn default() -> Self {
Self {
approver: None,
groups: Vec::new(),
states: Vec::new(),
app_name: None,
user_id: None,
session_id: None,
cursor: None,
limit: 50,
}
}
}
impl InboxQuery {
pub fn for_approver(
approver: SubjectRef,
groups: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
Self {
approver: Some(approver),
groups: groups.into_iter().map(Into::into).collect(),
..Self::default()
}
}
pub fn for_group(group: impl Into<String>) -> Self {
Self { groups: vec![group.into()], ..Self::default() }
}
#[must_use]
pub fn with_states(mut self, states: impl IntoIterator<Item = ApprovalState>) -> Self {
self.states = states.into_iter().collect();
self
}
#[must_use]
pub fn with_app_name(mut self, app_name: impl Into<String>) -> Self {
self.app_name = Some(app_name.into());
self
}
#[must_use]
pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
self.session_id = Some(session_id.into());
self
}
#[must_use]
pub fn with_user_id(mut self, user_id: impl Into<String>) -> Self {
self.user_id = Some(user_id.into());
self
}
#[must_use]
pub fn with_session(self, scope: &ApprovalScope) -> Self {
self.with_app_name(scope.app_name.clone())
.with_user_id(scope.user_id.clone())
.with_session_id(scope.session_id.clone())
}
#[must_use]
pub fn with_cursor(mut self, cursor: Option<String>) -> Self {
self.cursor = cursor;
self
}
#[must_use]
pub fn with_limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InboxPage {
pub items: Vec<ApprovalRequest>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum ApprovalEventKind {
Submitted,
Escalated,
Decided,
Resolved,
Expired,
Cancelled,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalNotification {
pub id: String,
pub kind: ApprovalEventKind,
pub request: ApprovalRequest,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub decision: Option<ApprovalDecision>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub escalation_step: Option<u32>,
pub at: DateTime<Utc>,
}
#[async_trait]
pub trait ApprovalNotifier: fmt::Debug + Send + Sync {
async fn notify(&self, notification: &ApprovalNotification) -> Result<()>;
}
#[async_trait]
pub trait ApprovalResolution: fmt::Debug + Send + Sync {
async fn resolving(&self, request: &ApprovalRequest, decision: &ApprovalDecision);
}
#[derive(Debug, Clone, PartialEq)]
pub struct ApprovalCall {
pub scope: ApprovalScope,
pub request: ToolConfirmationRequest,
pub reason: String,
pub agent_name: String,
pub invocation_id: String,
pub run_id: Option<String>,
pub acting: Option<ActingContext>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ApprovalRoute {
pub policy: ApprovalPolicy,
pub summary: Option<String>,
pub risk: ApprovalRisk,
pub redacted_args: Option<Value>,
pub allowed_actions: Option<Vec<ApprovalAction>>,
pub evidence: Vec<crate::Evidence>,
}
impl ApprovalRoute {
pub fn new(policy: ApprovalPolicy) -> Self {
Self {
policy,
summary: None,
risk: ApprovalRisk::default(),
redacted_args: None,
allowed_actions: None,
evidence: Vec::new(),
}
}
#[must_use]
pub fn with_summary(mut self, summary: impl Into<String>) -> Self {
self.summary = Some(summary.into());
self
}
#[must_use]
pub fn with_risk(mut self, risk: ApprovalRisk) -> Self {
self.risk = risk;
self
}
#[must_use]
pub fn with_redacted_args(mut self, args: Value) -> Self {
self.redacted_args = Some(args);
self
}
#[must_use]
pub fn with_allowed_actions(
mut self,
actions: impl IntoIterator<Item = ApprovalAction>,
) -> Self {
self.allowed_actions = Some(actions.into_iter().collect());
self
}
#[must_use]
pub fn with_evidence(mut self, evidence: impl IntoIterator<Item = crate::Evidence>) -> Self {
self.evidence.extend(evidence);
self
}
}
pub trait ApprovalRouter: Send + Sync {
fn route(&self, call: &ApprovalCall) -> Option<ApprovalRoute>;
}
impl ApprovalRouter for ApprovalPolicy {
fn route(&self, _call: &ApprovalCall) -> Option<ApprovalRoute> {
Some(ApprovalRoute::new(self.clone()))
}
}
impl<F> ApprovalRouter for F
where
F: Fn(&ApprovalCall) -> Option<ApprovalRoute> + Send + Sync,
{
fn route(&self, call: &ApprovalCall) -> Option<ApprovalRoute> {
self(call)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalTick {
pub expired: Vec<String>,
pub escalated: Vec<(String, u32)>,
pub reapplied: Vec<String>,
}
#[async_trait]
pub trait ApprovalService: fmt::Debug + Send + Sync {
async fn submit(&self, request: ApprovalRequest) -> Result<ApprovalRequest>;
async fn submit_call(&self, call: ApprovalCall) -> Result<Option<ApprovalRequest>>;
async fn get(&self, id: &str) -> Result<Option<ApprovalRequest>>;
async fn inbox(&self, query: InboxQuery) -> Result<InboxPage>;
async fn decide(
&self,
id: &str,
expected_version: u64,
decision: ApprovalDecision,
) -> Result<ApprovalRequest>;
async fn delegate(&self, delegation: ApprovalDelegation) -> Result<ApprovalDelegation>;
async fn revoke_delegation(&self, id: &str) -> Result<bool>;
async fn delegations_to(&self, to: &SubjectRef) -> Result<Vec<ApprovalDelegation>>;
async fn cancel(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest>;
async fn withdraw(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest> {
self.cancel(id, reason).await
}
async fn tick(&self, now: DateTime<Utc>) -> Result<ApprovalTick>;
fn approval_store(&self) -> Option<Arc<dyn ApprovalStore>> {
None
}
fn route_unrouted(&self, router: Arc<dyn ApprovalRouter>) -> bool {
let _ = router;
false
}
fn add_notifier(&self, notifier: Arc<dyn ApprovalNotifier>) -> bool {
let _ = notifier;
false
}
fn add_resolution(&self, hook: Arc<dyn ApprovalResolution>) -> bool {
let _ = hook;
false
}
async fn record_review(
&self,
call: ApprovalCall,
decision: ApprovalDecision,
) -> Result<Option<ApprovalRequest>> {
let _ = (call, decision);
Ok(None)
}
}
#[async_trait]
pub trait ApproverDirectory: Send + Sync {
async fn groups(&self, subject: &SubjectRef, request: &ApprovalRequest) -> Result<Vec<String>>;
fn governs(&self, group: &str) -> bool {
let _ = group;
true
}
}
pub struct StoreApprovalService {
store: Arc<dyn ApprovalStore>,
clock: Arc<dyn Clock>,
notifiers: Vec<Arc<dyn ApprovalNotifier>>,
run_store: Option<Arc<dyn DurableRunStore>>,
router: Option<Arc<dyn ApprovalRouter>>,
audit: Option<crate::audit_log::AuditTrail>,
directory: Option<Arc<dyn ApproverDirectory>>,
fallback_router: std::sync::OnceLock<Arc<dyn ApprovalRouter>>,
late_notifiers: std::sync::RwLock<Vec<Arc<dyn ApprovalNotifier>>>,
resolutions: std::sync::RwLock<Vec<Arc<dyn ApprovalResolution>>>,
}
impl fmt::Debug for StoreApprovalService {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StoreApprovalService")
.field("store", &self.store)
.field("clock", &self.clock)
.field("notifiers", &self.notifiers)
.field("run_store", &self.run_store.is_some())
.field("router", &self.router.is_some())
.field("fallback_router", &self.fallback_router.get().is_some())
.field(
"late_notifiers",
&self.late_notifiers.read().unwrap_or_else(|e| e.into_inner()).len(),
)
.field("audit", &self.audit)
.field("directory", &self.directory.is_some())
.field("resolutions", &self.resolutions.read().unwrap_or_else(|e| e.into_inner()).len())
.finish()
}
}
impl StoreApprovalService {
pub fn new(store: Arc<dyn ApprovalStore>) -> Self {
Self {
store,
clock: Arc::new(SystemClock),
notifiers: Vec::new(),
run_store: None,
router: None,
audit: None,
directory: None,
fallback_router: std::sync::OnceLock::new(),
late_notifiers: std::sync::RwLock::new(Vec::new()),
resolutions: std::sync::RwLock::new(Vec::new()),
}
}
#[must_use]
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
#[must_use]
pub fn with_notifier(mut self, notifier: Arc<dyn ApprovalNotifier>) -> Self {
self.notifiers.push(notifier);
self
}
#[must_use]
pub fn with_run_store(mut self, run_store: Arc<dyn DurableRunStore>) -> Self {
self.run_store = Some(run_store);
self
}
#[must_use]
pub fn with_router(mut self, router: impl ApprovalRouter + 'static) -> Self {
self.router = Some(Arc::new(router));
self
}
#[must_use]
pub fn with_audit(mut self, audit: crate::audit_log::AuditTrail) -> Self {
self.audit = Some(audit);
self
}
#[must_use]
pub fn with_directory(mut self, directory: Arc<dyn ApproverDirectory>) -> Self {
self.directory = Some(directory);
self
}
async fn groups_of(
&self,
subject: &SubjectRef,
asserted: &[String],
request: &ApprovalRequest,
) -> Result<Vec<String>> {
let Some(directory) = &self.directory else { return Ok(asserted.to_vec()) };
let mut groups: Vec<String> =
asserted.iter().filter(|group| !directory.governs(group)).cloned().collect();
for group in directory.groups(subject, request).await? {
if !groups.contains(&group) {
groups.push(group);
}
}
Ok(groups)
}
async fn notify(
&self,
kind: ApprovalEventKind,
request: &ApprovalRequest,
decision: Option<&ApprovalDecision>,
escalation_step: Option<u32>,
) {
let late = self.late_notifiers.read().unwrap_or_else(|e| e.into_inner()).clone();
if self.notifiers.is_empty() && late.is_empty() {
return;
}
let notification = ApprovalNotification {
id: format!("{}:{}", request.id, request.version),
kind,
request: request.clone(),
decision: decision.cloned(),
escalation_step,
at: self.clock.now(),
};
for notifier in self.notifiers.iter().chain(&late) {
if let Err(error) = notifier.notify(¬ification).await {
tracing::warn!(
approval.id = %request.id,
approval.event = ?kind,
error = %error,
"approval notifier failed"
);
}
}
}
async fn apply(&self, request: ApprovalRequest, recovering: bool) -> Result<ApprovalRequest> {
let Some(outcome) = request.outcome() else {
return Ok(request);
};
if request.outcome_applied {
return Ok(request);
}
let write = !recovering
|| self
.store
.pending(&request.scope)
.await?
.iter()
.any(|entry| entry.fingerprint == request.fingerprint);
if write {
self.store.decide(&request.scope, &request.fingerprint, outcome).await?;
}
if let Some(runs) = &self.run_store {
let mut waiting: Vec<String> = request.run_id.iter().cloned().collect();
let parked = crate::RunFilter::default()
.app_name(request.scope.app_name.clone())
.user_id(request.scope.user_id.clone())
.session_id(request.scope.session_id.clone())
.states([crate::RunState::Waiting]);
match runs.list(parked).await {
Ok(parked) => waiting.extend(
parked
.into_iter()
.filter(|run| {
matches!(
&run.checkpoint,
Some(crate::RunCheckpointRef::AwaitingApproval { fingerprints, .. })
if fingerprints.contains(&request.fingerprint)
)
})
.map(|run| run.run_id)
.filter(|run_id| request.run_id.as_ref() != Some(run_id)),
),
Err(error) => {
tracing::warn!(approval.id = %request.id, error = %error, "could not list the runs parked on an approval");
}
}
for run_id in waiting {
if let Err(error) = runs.wake(&run_id).await {
tracing::warn!(approval.id = %request.id, run.id = %run_id, error = %error, "could not wake the run waiting for an approval");
}
}
}
let mut applied = request.clone();
applied.outcome_applied = true;
applied.version = request.version + 1;
if self.store.replace_request(&applied, request.version).await? {
Ok(applied)
} else {
Ok(self.store.get_request(&request.id).await?.unwrap_or(applied))
}
}
async fn swap(&self, next: &ApprovalRequest, expected: u64) -> Result<()> {
if self.store.replace_request(next, expected).await? {
return Ok(());
}
let current = self.store.get_request(&next.id).await?;
Err(match current {
Some(current) => version_conflict(&next.id, expected, current.version),
None => not_found(&next.id),
})
}
async fn live_delegations(
&self,
to: &SubjectRef,
at: DateTime<Utc>,
) -> Result<Vec<ApprovalDelegation>> {
Ok(self
.store
.delegations_to(to)
.await?
.into_iter()
.filter(|delegation| delegation.window.contains(at))
.collect())
}
async fn authority(
&self,
request: &ApprovalRequest,
decision: &ApprovalDecision,
at: DateTime<Utc>,
) -> Result<(Option<SubjectRef>, Vec<String>)> {
let approver = &decision.approver;
if approver.kind == SubjectKind::Visitor {
return Err(forbidden(
"approval.visitor_not_allowed",
"a visitor cannot decide an approval request; approvers are identified subjects",
));
}
let forbid_self = request.policy.forbid_self_approval;
if forbid_self && request.is_self(approver) {
return Err(forbidden(
"approval.self_approval",
format!("'{}' may not approve their own call; ask another approver", approver.id),
));
}
let direct = request.is_eligible(approver, &decision.approver_groups);
if direct && decision.via_delegation.is_none() {
return Ok((None, decision.approver_groups.clone()));
}
let mut candidates: Vec<(ApprovalDelegation, Vec<String>)> = Vec::new();
for delegation in self.store.delegations_to(approver).await? {
if decision.via_delegation.as_ref().is_some_and(|from| *from != delegation.from)
|| !delegation.scope.covers(request)
{
continue;
}
let groups = self.groups_of(&delegation.from, &delegation.from_groups, request).await?;
if request.is_eligible(&delegation.from, &groups) {
candidates.push((delegation, groups));
}
}
if let Some((live, groups)) =
candidates.iter().find(|(delegation, _)| delegation.window.contains(at))
{
if forbid_self && request.is_self(&live.from) {
return Err(forbidden(
"approval.self_approval",
format!(
"'{}' may not approve on behalf of '{}', the requester",
approver.id, live.from.id
),
));
}
return Ok((Some(live.from.clone()), groups.clone()));
}
if !candidates.is_empty() {
return Err(forbidden(
"approval.delegation_inactive",
format!(
"the delegation that lets '{}' approve this request is outside its window",
approver.id
),
));
}
Err(forbidden(
"approval.not_an_approver",
format!("'{}' is not an approver of request '{}'", approver.id, request.id),
))
}
async fn in_inbox(
&self,
request: &ApprovalRequest,
query: &InboxQuery,
delegations: &[ApprovalDelegation],
at: DateTime<Utc>,
) -> Result<bool> {
let forbid_self = request.policy.forbid_self_approval;
let Some(approver) = query.approver.as_ref() else {
return Ok(query.groups.is_empty()
|| request.eligible_approvers().any(|selector| {
matches!(selector, ApproverSelector::Group(group) if query.groups.contains(group))
}));
};
if forbid_self && request.is_self(approver) {
return Ok(false);
}
let groups = self.groups_of(approver, &query.groups, request).await?;
if request.is_eligible(approver, &groups) {
return Ok(true);
}
for delegation in delegations {
if !delegation.window.contains(at)
|| !delegation.scope.covers(request)
|| (forbid_self && request.is_self(&delegation.from))
{
continue;
}
let groups = self.groups_of(&delegation.from, &delegation.from_groups, request).await?;
if request.is_eligible(&delegation.from, &groups) {
return Ok(true);
}
}
Ok(false)
}
}
#[async_trait]
impl ApprovalService for StoreApprovalService {
async fn submit(&self, mut request: ApprovalRequest) -> Result<ApprovalRequest> {
request.policy.validate()?;
if request.id.is_empty() {
return Err(invalid("approval.invalid_request", "an approval request needs an id"));
}
if request.allowed_actions.is_empty() {
return Err(invalid(
"approval.invalid_request",
"an approval request must allow at least one action",
));
}
let now = self.clock.now();
request.created_at = now;
if request.expires_at.is_none()
&& let Some(ttl) = request.policy.expires_after
{
let ttl = chrono::Duration::from_std(ttl).unwrap_or(chrono::Duration::MAX);
request.expires_at =
Some(now.checked_add_signed(ttl).unwrap_or(DateTime::<Utc>::MAX_UTC));
}
request.version = 1;
request.state = ApprovalState::Pending;
request.decisions.clear();
request.escalations_fired = 0;
request.resolved_at = None;
request.note = None;
request.outcome_applied = false;
let stored = self.store.create_request(&request).await?;
if stored == request {
tracing::info!(approval.id = %request.id, tool.name = %request.tool_name, "approval request submitted");
self.notify(ApprovalEventKind::Submitted, &stored, None, None).await;
}
Ok(stored)
}
async fn submit_call(&self, call: ApprovalCall) -> Result<Option<ApprovalRequest>> {
let router = self.router.as_ref().or_else(|| self.fallback_router.get());
let Some(route) = router.and_then(|router| router.route(&call)) else {
return Ok(None);
};
self.store.record_pending(&call.scope, &call.request).await?;
let fingerprint = call.request.fingerprint();
let Some(held) = self
.store
.pending(&call.scope)
.await?
.into_iter()
.find(|entry| entry.fingerprint == fingerprint)
else {
return Ok(None);
};
let mut open = ApprovalRequestQuery::default()
.with_session(&call.scope)
.with_states([ApprovalState::Pending]);
loop {
let batch = self.store.list_requests(&open).await?;
if let Some(existing) = batch.iter().find(|request| request.fingerprint == fingerprint)
{
return Ok(Some(existing.clone()));
}
if batch.len() < open.limit {
break;
}
open = open.with_after(batch.last().map(ApprovalRequest::cursor));
}
let id = ApprovalRequest::id_for_call(&call.scope, &fingerprint, held.requested_at);
let mut request = ApprovalRequest::new(id, call.scope.clone(), &call.request, route.policy)
.with_summary(route.summary.unwrap_or(call.reason))
.with_risk(route.risk);
if let Some(args) = route.redacted_args {
request = request.with_redacted_args(args);
}
if let Some(actions) = route.allowed_actions {
request = request.with_allowed_actions(actions);
}
request = request.with_evidence(route.evidence);
if let Some(acting) = call.acting {
request = request.with_acting(acting);
}
if request.requester.is_none() {
request = request.with_requester(SubjectRef::human(call.scope.user_id.clone()));
}
if let Some(run_id) = call.run_id {
request = request.with_run_id(run_id);
}
self.submit(request).await.map(Some)
}
async fn get(&self, id: &str) -> Result<Option<ApprovalRequest>> {
self.store.get_request(id).await
}
async fn inbox(&self, query: InboxQuery) -> Result<InboxPage> {
let now = self.clock.now();
let delegations = match &query.approver {
Some(approver) => self.live_delegations(approver, now).await?,
None => Vec::new(),
};
let states = if query.states.is_empty() {
vec![ApprovalState::Pending]
} else {
query.states.clone()
};
let limit = query.limit.max(1);
let mut after = query.cursor.as_deref().map(ApprovalCursor::decode).transpose()?;
let mut items = Vec::new();
loop {
let mut store_query = ApprovalRequestQuery::default()
.with_states(states.iter().copied())
.with_after(after.clone())
.with_limit(DEFAULT_APPROVAL_PAGE);
store_query.app_name = query.app_name.clone();
store_query.user_id = query.user_id.clone();
store_query.session_id = query.session_id.clone();
let batch = self.store.list_requests(&store_query).await?;
let exhausted = batch.len() < DEFAULT_APPROVAL_PAGE;
for request in batch {
after = Some(request.cursor());
if self.in_inbox(&request, &query, &delegations, now).await? {
items.push(request);
if items.len() == limit {
return Ok(InboxPage {
items,
next_cursor: after.map(|cursor| cursor.encode()),
});
}
}
}
if exhausted {
return Ok(InboxPage { items, next_cursor: None });
}
}
}
async fn decide(
&self,
id: &str,
expected_version: u64,
mut decision: ApprovalDecision,
) -> Result<ApprovalRequest> {
let now = self.clock.now();
let request = self.store.get_request(id).await?.ok_or_else(|| not_found(id))?;
if request.version != expected_version {
return Err(version_conflict(id, expected_version, request.version));
}
if request.state.is_terminal() {
return Err(conflict(
"approval.already_resolved",
format!("approval request '{id}' is already {}", request.state.as_str()),
));
}
if request.expires_at.is_some_and(|at| at <= now) {
return Err(conflict(
"approval.expired",
format!("approval request '{id}' expired; the call is denied"),
));
}
if !request.allowed_actions.contains(&decision.kind) {
return Err(invalid(
"approval.action_not_allowed",
format!("approval request '{id}' does not allow {:?}", decision.kind),
));
}
match decision.kind {
ApprovalAction::Edit if decision.edited_args.is_none() => {
return Err(invalid(
"approval.action_not_allowed",
"an edit must carry the edited arguments",
));
}
ApprovalAction::Respond
if decision.reason.as_deref().is_none_or(|text| text.trim().is_empty()) =>
{
return Err(invalid(
"approval.action_not_allowed",
"a response must carry the text to report to the model",
));
}
ApprovalAction::Approve | ApprovalAction::Reject => decision.edited_args = None,
ApprovalAction::Edit | ApprovalAction::Respond => {}
}
decision.approver_groups =
self.groups_of(&decision.approver, &decision.approver_groups, &request).await?;
(decision.via_delegation, decision.authority_groups) =
self.authority(&request, &decision, now).await?;
decision.decided_at = now;
if matches!(decision.kind, ApprovalAction::Approve)
&& request.quorum_progress().0.contains(decision.authority())
{
return Err(conflict(
"approval.already_decided",
format!(
"'{}' already approved request '{id}'; another approver must decide",
decision.authority().id
),
));
}
if let Some(trail) = &self.audit {
use crate::audit_log::{AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind};
let audited = match decision.kind {
ApprovalAction::Approve | ApprovalAction::Edit => AuditDecision::Approved,
ApprovalAction::Reject | ApprovalAction::Respond => AuditDecision::Rejected,
};
let mut actor = AuditActor::subject(decision.approver.clone());
actor.delegation_chain.extend(decision.via_delegation.clone());
let action = serde_json::to_value(decision.kind).unwrap_or(Value::Null);
let mut draft = AuditRecordDraft::new(AuditRecordKind::Approval, &request.tool_name)
.actor(actor)
.args_digest(trail.digest(&request.args_redacted))
.decision(audited)
.ext("source", Value::String("approval_service".to_string()))
.ext("approvalId", Value::String(id.to_string()))
.ext("approvalAction", action)
.ext("version", Value::from(expected_version + 1))
.ext("sessionId", Value::String(request.scope.session_id.clone()));
if let Some(acting) = &request.acting {
draft = draft.ext("actingAgent", Value::String(acting.agent.id.to_string()));
}
if !request.evidence.is_empty() {
let digests = request.evidence.iter().map(|item| Value::from(item.digest()));
draft = draft.ext("evidenceDigests", Value::Array(digests.collect()));
}
if let Some(edited) = &decision.edited_args {
draft = draft.ext("editedArgsDigest", Value::String(trail.digest(edited)));
}
trail.record(draft).await?;
}
let mut next = request.clone();
next.decisions.push(decision.clone());
next.version = expected_version + 1;
next.state = match decision.kind {
ApprovalAction::Reject => ApprovalState::Rejected,
ApprovalAction::Respond => ApprovalState::Responded,
ApprovalAction::Approve | ApprovalAction::Edit => {
let approvals = next.quorum_progress().0.len();
if approvals >= usize::try_from(next.policy.quorum).unwrap_or(usize::MAX)
&& next.open_slots().is_empty()
{
ApprovalState::Approved
} else {
ApprovalState::Pending
}
}
};
if next.state.is_terminal() {
next.resolved_at = Some(now);
}
self.swap(&next, expected_version).await?;
tracing::info!(
approval.id = %id,
approval.action = ?decision.kind,
approval.state = next.state.as_str(),
"approval decision recorded"
);
if !next.state.is_terminal() {
self.notify(ApprovalEventKind::Decided, &next, Some(&decision), None).await;
return Ok(next);
}
let resolutions = self.resolutions.read().unwrap_or_else(|e| e.into_inner()).clone();
for hook in resolutions {
hook.resolving(&next, &decision).await;
}
let applied = self.apply(next.clone(), false).await?;
self.notify(ApprovalEventKind::Decided, &next, Some(&decision), None).await;
self.notify(ApprovalEventKind::Resolved, &applied, None, None).await;
Ok(applied)
}
async fn delegate(&self, mut delegation: ApprovalDelegation) -> Result<ApprovalDelegation> {
if delegation.window.not_after <= delegation.window.not_before {
return Err(invalid(
"approval.invalid_delegation",
"a delegation window must end after it starts",
));
}
if delegation.from == delegation.to {
return Err(invalid(
"approval.invalid_delegation",
"a subject cannot delegate to itself",
));
}
if delegation.id.is_empty() {
return Err(invalid("approval.invalid_delegation", "a delegation needs an id"));
}
delegation.created_at = self.clock.now();
self.store.put_delegation(&delegation).await?;
tracing::info!(
delegation.id = %delegation.id,
delegation.from = %delegation.from.id,
delegation.to = %delegation.to.id,
"approval delegation granted"
);
Ok(delegation)
}
async fn revoke_delegation(&self, id: &str) -> Result<bool> {
self.store.delete_delegation(id).await
}
async fn delegations_to(&self, to: &SubjectRef) -> Result<Vec<ApprovalDelegation>> {
self.store.delegations_to(to).await
}
async fn cancel(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest> {
let request = self.store.get_request(id).await?.ok_or_else(|| not_found(id))?;
if request.state.is_terminal() {
return Err(conflict(
"approval.already_resolved",
format!("approval request '{id}' is already {}", request.state.as_str()),
));
}
let mut next = request.clone();
next.state = ApprovalState::Cancelled;
next.version = request.version + 1;
next.resolved_at = Some(self.clock.now());
next.note = reason;
self.swap(&next, request.version).await?;
let applied = self.apply(next, false).await?;
self.notify(ApprovalEventKind::Cancelled, &applied, None, None).await;
Ok(applied)
}
async fn withdraw(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest> {
let request = self.store.get_request(id).await?.ok_or_else(|| not_found(id))?;
if request.state.is_terminal() {
return Err(conflict(
"approval.already_resolved",
format!("approval request '{id}' is already {}", request.state.as_str()),
));
}
let mut next = request.clone();
next.state = ApprovalState::Cancelled;
next.version = request.version + 1;
next.resolved_at = Some(self.clock.now());
next.note = reason;
next.outcome_applied = true;
self.swap(&next, request.version).await?;
self.notify(ApprovalEventKind::Cancelled, &next, None, None).await;
Ok(next)
}
async fn tick(&self, now: DateTime<Utc>) -> Result<ApprovalTick> {
let mut report = ApprovalTick::default();
let mut after = None;
loop {
let query = ApprovalRequestQuery::default().open_only().with_after(after.clone());
let batch = self.store.list_requests(&query).await?;
let exhausted = batch.len() < query.limit;
for request in batch {
after = Some(request.cursor());
if request.state.is_terminal() {
let grace = chrono::Duration::from_std(APPROVAL_REAPPLY_GRACE)
.unwrap_or(chrono::Duration::MAX);
let settled = request
.resolved_at
.and_then(|at| at.checked_add_signed(grace))
.is_none_or(|at| at <= now);
if settled {
let applied = self.apply(request, true).await?;
report.reapplied.push(applied.id);
}
continue;
}
if request.expires_at.is_some_and(|at| at <= now) {
let mut next = request.clone();
next.state = ApprovalState::Expired;
next.version = request.version + 1;
next.resolved_at = Some(now);
if !self.store.replace_request(&next, request.version).await? {
continue;
}
tracing::info!(approval.id = %next.id, "approval request expired; denying the call");
let applied = self.apply(next, false).await?;
self.notify(ApprovalEventKind::Expired, &applied, None, None).await;
report.expired.push(applied.id);
continue;
}
let due = request
.policy
.escalation
.iter()
.take_while(|step| {
chrono::Duration::from_std(step.after)
.ok()
.and_then(|after| request.created_at.checked_add_signed(after))
.is_some_and(|at| at <= now)
})
.count();
let due = u32::try_from(due).unwrap_or(u32::MAX);
if due <= request.escalations_fired {
continue;
}
let mut next = request.clone();
next.escalations_fired = due;
next.version = request.version + 1;
if !self.store.replace_request(&next, request.version).await? {
continue;
}
for step in request.escalations_fired..due {
tracing::info!(approval.id = %next.id, approval.escalation_step = step, "approval request escalated");
self.notify(ApprovalEventKind::Escalated, &next, None, Some(step)).await;
report.escalated.push((next.id.clone(), step));
}
}
if exhausted {
return Ok(report);
}
}
}
fn approval_store(&self) -> Option<Arc<dyn ApprovalStore>> {
Some(self.store.clone())
}
async fn record_review(
&self,
call: ApprovalCall,
mut decision: ApprovalDecision,
) -> Result<Option<ApprovalRequest>> {
let router = self.router.as_ref().or_else(|| self.fallback_router.get());
let Some(route) = router.and_then(|router| router.route(&call)) else {
return Ok(None);
};
route.policy.validate()?;
let now = self.clock.now();
let fingerprint = call.request.fingerprint();
let id = ApprovalRequest::id_for_call(&call.scope, &fingerprint, now);
let mut request = ApprovalRequest::new(id, call.scope.clone(), &call.request, route.policy)
.with_summary(route.summary.unwrap_or(call.reason))
.with_risk(route.risk);
if let Some(args) = route.redacted_args {
request = request.with_redacted_args(args);
}
if let Some(actions) = route.allowed_actions {
request = request.with_allowed_actions(actions);
}
request = request.with_evidence(route.evidence);
if let Some(acting) = call.acting {
request = request.with_acting(acting);
}
if request.requester.is_none() {
request = request.with_requester(SubjectRef::human(call.scope.user_id.clone()));
}
if let Some(run_id) = call.run_id {
request = request.with_run_id(run_id);
}
decision.decided_at = now;
request.created_at = now;
request.state = match decision.kind {
ApprovalAction::Approve | ApprovalAction::Edit => ApprovalState::Approved,
ApprovalAction::Reject => ApprovalState::Rejected,
ApprovalAction::Respond => ApprovalState::Responded,
};
request.decisions = vec![decision.clone()];
request.resolved_at = Some(now);
request.outcome_applied = true;
if let Some(trail) = &self.audit {
use crate::audit_log::{AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind};
let audited = match decision.kind {
ApprovalAction::Approve | ApprovalAction::Edit => AuditDecision::Approved,
ApprovalAction::Reject | ApprovalAction::Respond => AuditDecision::Rejected,
};
let action = serde_json::to_value(decision.kind).unwrap_or(Value::Null);
let mut draft = AuditRecordDraft::new(AuditRecordKind::Approval, &request.tool_name)
.actor(AuditActor::subject(decision.approver.clone()))
.args_digest(trail.digest(&request.args_redacted))
.decision(audited)
.ext("source", Value::String(crate::REVIEW_SOURCE.to_string()))
.ext("approvalId", Value::String(request.id.clone()))
.ext("approvalAction", action)
.ext("version", Value::from(request.version))
.ext("sessionId", Value::String(request.scope.session_id.clone()));
if let Some(acting) = &request.acting {
draft = draft.ext("actingAgent", Value::String(acting.agent.id.to_string()));
}
if !request.evidence.is_empty() {
let digests = request.evidence.iter().map(|item| Value::from(item.digest()));
draft = draft.ext("evidenceDigests", Value::Array(digests.collect()));
}
trail.record(draft).await?;
}
let stored = self.store.create_request(&request).await?;
tracing::info!(
approval.id = %stored.id,
tool.name = %stored.tool_name,
approval.state = stored.state.as_str(),
reviewer.id = %decision.approver.id,
"approval request decided by a reviewer"
);
if stored == request {
self.notify(ApprovalEventKind::Decided, &stored, Some(&decision), None).await;
self.notify(ApprovalEventKind::Resolved, &stored, None, None).await;
}
Ok(Some(stored))
}
fn route_unrouted(&self, router: Arc<dyn ApprovalRouter>) -> bool {
if self.router.is_none() {
let _ = self.fallback_router.set(router);
}
true
}
fn add_notifier(&self, notifier: Arc<dyn ApprovalNotifier>) -> bool {
self.late_notifiers.write().unwrap_or_else(|e| e.into_inner()).push(notifier);
true
}
fn add_resolution(&self, hook: Arc<dyn ApprovalResolution>) -> bool {
self.resolutions.write().unwrap_or_else(|e| e.into_inner()).push(hook);
true
}
}
fn error(category: ErrorCategory, code: &'static str, message: impl Into<String>) -> AdkError {
AdkError::new(ErrorComponent::Agent, category, code, message.into())
}
fn invalid(code: &'static str, message: impl Into<String>) -> AdkError {
error(ErrorCategory::InvalidInput, code, message)
}
fn forbidden(code: &'static str, message: impl Into<String>) -> AdkError {
error(ErrorCategory::Forbidden, code, message)
}
fn conflict(code: &'static str, message: impl Into<String>) -> AdkError {
error(ErrorCategory::Conflict, code, message)
}
fn not_found(id: &str) -> AdkError {
error(ErrorCategory::NotFound, "approval.not_found", format!("no approval request '{id}'"))
}
fn version_conflict(id: &str, expected: u64, current: u64) -> AdkError {
let mut details = ErrorDetails::default();
details.metadata.insert("current_version".to_string(), current.into());
conflict(
"approval.version_conflict",
format!(
"approval request '{id}' is at version {current}, not {expected}; another decision \
landed first, so re-read the request and decide again"
),
)
.with_details(details)
}
pub(crate) fn store_unsupported(operation: &str) -> AdkError {
error(
ErrorCategory::Unsupported,
"approval.store_unsupported",
format!(
"this approval store does not implement `{operation}`, which the approval service \
needs; use a store from adk-core or adk-session, or implement the method"
),
)
}
mod duration_secs {
use serde::{Deserialize, Deserializer, Serializer};
use std::time::Duration;
pub fn serialize<S: Serializer>(value: &Duration, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_u64(value.as_secs())
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
u64::deserialize(deserializer).map(Duration::from_secs)
}
}
mod option_duration_secs {
use serde::{Deserialize, Deserializer, Serializer};
use std::time::Duration;
#[allow(clippy::ref_option)] pub fn serialize<S: Serializer>(
value: &Option<Duration>,
serializer: S,
) -> Result<S::Ok, S::Error> {
match value {
Some(duration) => serializer.serialize_some(&duration.as_secs()),
None => serializer.serialize_none(),
}
}
pub fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<Duration>, D::Error> {
Ok(Option::<u64>::deserialize(deserializer)?.map(Duration::from_secs))
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_person_and_a_service_with_one_id_are_the_same_party() {
let call = ToolConfirmationRequest::new("pay", json!({}));
let request = ApprovalRequest::new(
"req-1",
ApprovalScope::new("ap", "controller", "s"),
&call,
ApprovalPolicy::new([ApproverSelector::group("finance")]),
)
.with_acting(
ActingContext::new(crate::AgentPrincipal::derived("ap", "clerk"))
.on_behalf_of(SubjectRef::service("controller")),
);
assert!(request.is_self(&SubjectRef::human("controller")));
assert!(request.is_self(&SubjectRef::service("controller")));
assert!(!request.is_self(&SubjectRef::human("cfo")));
assert!(!request.is_self(&SubjectRef::new(SubjectKind::Agent, "controller")));
assert!(
request.is_self(&SubjectRef::agent(&crate::AgentPrincipal::derived("ap", "clerk").id))
);
}
#[test]
fn policies_serialize_in_camel_case_with_whole_seconds() {
let policy = ApprovalPolicy::new([ApproverSelector::group("finance")])
.with_quorum(2)
.escalate_after(Duration::from_secs(900), [ApproverSelector::human("cfo")])
.expires_after(Duration::from_secs(3_600));
let value = serde_json::to_value(&policy).unwrap();
assert_eq!(
value,
json!({
"approvers": [{ "group": "finance" }],
"quorum": 2,
"forbidSelfApproval": true,
"escalation": [{
"afterSecs": 900,
"to": [{ "subject": { "kind": "human", "id": "cfo" } }]
}],
"onExpiry": "deny",
"expiresAfterSecs": 3600
})
);
assert_eq!(serde_json::from_value::<ApprovalPolicy>(value).unwrap(), policy);
}
#[test]
fn cursors_round_trip_ids_containing_colons() {
let cursor = ApprovalCursor { created_at: Utc::now(), id: "a:b/ü".into() };
let decoded = ApprovalCursor::decode(&cursor.encode()).unwrap();
assert_eq!(decoded.id, cursor.id);
assert_eq!(decoded.created_at.timestamp_micros(), cursor.created_at.timestamp_micros());
assert_eq!(ApprovalCursor::decode("nope").unwrap_err().code, "approval.invalid_cursor");
}
#[test]
fn call_ids_change_with_the_hold_time() {
let scope = ApprovalScope::new("app", "u", "s");
let at = Utc::now();
let id = ApprovalRequest::id_for_call(&scope, "fp", at);
assert_eq!(id, ApprovalRequest::id_for_call(&scope, "fp", at));
assert_ne!(
id,
ApprovalRequest::id_for_call(&scope, "fp", at + chrono::Duration::seconds(1))
);
assert!(id.starts_with("apr_"));
}
#[test]
fn invalid_policies_are_refused() {
assert!(ApprovalPolicy::new([]).validate().is_err());
let zero = ApprovalPolicy::new([ApproverSelector::group("g")]).with_quorum(0);
assert_eq!(zero.validate().unwrap_err().code, "approval.invalid_policy");
let unordered = ApprovalPolicy::new([ApproverSelector::group("g")])
.escalate_after(Duration::from_secs(60), [])
.escalate_after(Duration::from_secs(30), []);
assert!(unordered.validate().is_err());
}
#[tokio::test]
async fn resolving_a_request_wakes_its_waiting_run() {
use crate::{
ApprovalStore, DurableRunStore, InMemoryApprovalStore, InMemoryRunStore, NewRun,
RunState,
};
let runs = Arc::new(InMemoryRunStore::new());
let enqueued =
runs.enqueue(NewRun::new("q", "app", "u", "agent", json!({}))).await.unwrap();
let run_id = enqueued.record().unwrap().run_id.clone();
let claimed = runs.claim("q", "worker", Duration::from_secs(60)).await.unwrap().unwrap();
runs.wait(&run_id, claimed.epoch, None).await.unwrap();
assert_eq!(runs.get(&run_id).await.unwrap().unwrap().state, RunState::Waiting);
let store = Arc::new(InMemoryApprovalStore::new());
let service = StoreApprovalService::new(store.clone()).with_run_store(runs.clone());
let call = ToolConfirmationRequest {
tool_name: "pay".into(),
function_call_id: Some("c1".into()),
args: json!({ "amount": 5 }),
origin: None,
acting: None,
evidence: Vec::new(),
};
let scope = ApprovalScope::new("app", "u", "s");
let request = service
.submit(
ApprovalRequest::new(
"req",
scope.clone(),
&call,
ApprovalPolicy::new([ApproverSelector::human("ana")]),
)
.with_run_id(run_id.clone()),
)
.await
.unwrap();
service
.decide(
&request.id,
request.version,
ApprovalDecision::approve(SubjectRef::human("ana")),
)
.await
.unwrap();
assert!(store.has_decision(&scope, &call.fingerprint()).await.unwrap());
let woken = runs.claim("q", "worker", Duration::from_secs(60)).await.unwrap();
assert_eq!(
woken.map(|claim| claim.record.run_id),
Some(run_id),
"the decision woke the run"
);
}
#[tokio::test]
async fn resolving_a_request_wakes_a_later_run_parked_on_the_call() {
use crate::{DurableRunStore, InMemoryApprovalStore, InMemoryRunStore, NewRun, RunState};
let runs = Arc::new(InMemoryRunStore::new());
let scope = ApprovalScope::new("app", "u", "s-1");
let call = ToolConfirmationRequest::new("pay", json!({ "cents": 500 }));
let park = |runs: Arc<InMemoryRunStore>| {
let fingerprint = call.fingerprint();
async move {
let new = NewRun::new("q", "app", "u", "agent", json!({})).with_session_id("s-1");
let run_id = runs.enqueue(new).await.unwrap().record().unwrap().run_id.clone();
let claim = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap().unwrap();
let checkpoint = crate::RunCheckpointRef::AwaitingApproval {
session_id: "s-1".into(),
invocation_id: None,
fingerprints: vec![fingerprint],
expires_at: None,
};
runs.set_checkpoint(&run_id, claim.epoch, checkpoint).await.unwrap();
runs.wait(&run_id, claim.epoch, None).await.unwrap();
run_id
}
};
let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
.with_run_store(runs.clone())
.with_router(ApprovalPolicy::new([ApproverSelector::human("ana")]));
let held_by = |run_id: &str| ApprovalCall {
scope: scope.clone(),
request: call.clone(),
reason: "pay".into(),
agent_name: "agent".into(),
invocation_id: "inv".into(),
run_id: Some(run_id.to_string()),
acting: None,
};
let first = park(runs.clone()).await;
let request = service.submit_call(held_by(&first)).await.unwrap().unwrap();
runs.request_cancel(&first).await.unwrap();
let second = park(runs.clone()).await;
let again = service.submit_call(held_by(&second)).await.unwrap().unwrap();
assert_eq!(again.id, request.id, "the call held again keeps its request");
service
.decide(
&request.id,
request.version,
ApprovalDecision::approve(SubjectRef::human("ana")),
)
.await
.unwrap();
assert_eq!(runs.get(&first).await.unwrap().unwrap().state, RunState::Cancelled);
let woken = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap();
assert_eq!(woken.map(|claim| claim.record.run_id), Some(second), "the later run wakes");
}
#[tokio::test]
async fn a_resolved_outcome_is_in_the_store_before_the_notifiers_run() {
use crate::{ApprovalStore, InMemoryApprovalStore};
#[derive(Debug)]
struct Witness {
store: Arc<InMemoryApprovalStore>,
seen: std::sync::Mutex<Vec<(ApprovalEventKind, bool, bool)>>,
}
#[async_trait::async_trait]
impl ApprovalNotifier for Witness {
async fn notify(&self, notification: &ApprovalNotification) -> Result<()> {
let request = ¬ification.request;
let decided = self.store.has_decision(&request.scope, &request.fingerprint).await?;
let waiting = self
.store
.pending(&request.scope)
.await?
.iter()
.any(|entry| entry.fingerprint == request.fingerprint);
self.seen.lock().unwrap().push((notification.kind, decided, waiting));
Ok(())
}
}
let store = Arc::new(InMemoryApprovalStore::new());
let witness = Arc::new(Witness { store: store.clone(), seen: Default::default() });
let service = StoreApprovalService::new(store.clone())
.with_notifier(witness.clone())
.with_router(ApprovalPolicy::new([ApproverSelector::human("ana")]));
let call = ApprovalCall {
scope: ApprovalScope::new("app", "u", "s"),
request: ToolConfirmationRequest::new("pay", json!({ "cents": 500 })),
reason: "pay".into(),
agent_name: "agent".into(),
invocation_id: "inv".into(),
run_id: None,
acting: None,
};
let request = service.submit_call(call).await.unwrap().unwrap();
service
.decide(
&request.id,
request.version,
ApprovalDecision::approve(SubjectRef::human("ana")),
)
.await
.unwrap();
assert_eq!(
*witness.seen.lock().unwrap(),
vec![
(ApprovalEventKind::Submitted, false, true),
(ApprovalEventKind::Decided, true, false),
(ApprovalEventKind::Resolved, true, false),
]
);
}
#[tokio::test]
async fn a_resolution_hook_runs_before_the_outcome_reaches_the_call_or_its_run() {
use crate::{
ApprovalStore, DurableRunStore, InMemoryApprovalStore, InMemoryRunStore, NewRun,
RunState,
};
type Seen = (ApprovalState, String, bool, Option<RunState>);
#[derive(Debug)]
struct Witness {
store: Arc<InMemoryApprovalStore>,
runs: Arc<InMemoryRunStore>,
run_id: String,
seen: std::sync::Mutex<Vec<Seen>>,
}
#[async_trait::async_trait]
impl ApprovalResolution for Witness {
async fn resolving(&self, request: &ApprovalRequest, decision: &ApprovalDecision) {
let applied =
self.store.has_decision(&request.scope, &request.fingerprint).await.unwrap();
let run = self.runs.get(&self.run_id).await.unwrap().map(|run| run.state);
self.seen.lock().unwrap().push((
request.state,
decision.approver.id.clone(),
applied,
run,
));
}
}
let store = Arc::new(InMemoryApprovalStore::new());
let runs = Arc::new(InMemoryRunStore::new());
let new = NewRun::new("q", "app", "u", "agent", json!({})).with_session_id("s");
let run_id = runs.enqueue(new).await.unwrap().record().unwrap().run_id.clone();
let claim = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap().unwrap();
let call = ToolConfirmationRequest::new("pay", json!({ "cents": 500 }));
let checkpoint = crate::RunCheckpointRef::AwaitingApproval {
session_id: "s".into(),
invocation_id: None,
fingerprints: vec![call.fingerprint()],
expires_at: None,
};
runs.set_checkpoint(&run_id, claim.epoch, checkpoint).await.unwrap();
runs.wait(&run_id, claim.epoch, None).await.unwrap();
let witness = Arc::new(Witness {
store: store.clone(),
runs: runs.clone(),
run_id: run_id.clone(),
seen: Default::default(),
});
let service = StoreApprovalService::new(store.clone())
.with_run_store(runs.clone())
.with_router(ApprovalPolicy::new([ApproverSelector::human("ana")]));
assert!(service.add_resolution(witness.clone()));
let held = ApprovalCall {
scope: ApprovalScope::new("app", "u", "s"),
request: call,
reason: "pay".into(),
agent_name: "agent".into(),
invocation_id: "inv".into(),
run_id: Some(run_id.clone()),
acting: None,
};
let request = service.submit_call(held).await.unwrap().unwrap();
service
.decide(
&request.id,
request.version,
ApprovalDecision::approve(SubjectRef::human("ana")),
)
.await
.unwrap();
assert_eq!(
*witness.seen.lock().unwrap(),
vec![(ApprovalState::Approved, "ana".to_string(), false, Some(RunState::Waiting))],
"the hook saw the recorded yes, the call not yet decided and its run still asleep"
);
assert!(store.has_decision(&request.scope, &request.fingerprint).await.unwrap());
let woken = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap();
assert_eq!(woken.map(|claim| claim.record.run_id), Some(run_id), "then the run wakes");
}
#[tokio::test]
async fn an_approver_decision_is_audited_before_it_takes_effect() {
use crate::audit_log::{
AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditRecorder,
AuditTrail, InMemoryAuditRecorder,
};
use crate::{ApprovalStore, InMemoryApprovalStore};
#[derive(Debug)]
struct Broken;
#[async_trait::async_trait]
impl AuditRecorder for Broken {
fn digest(&self, value: &Value) -> String {
crate::json_digest(value)
}
async fn record(&self, _draft: AuditRecordDraft) -> Result<()> {
Err(crate::AdkError::session("audit store down"))
}
}
let call = ToolConfirmationRequest {
tool_name: "pay".into(),
function_call_id: Some("c1".into()),
args: json!({ "to": "acct-secret", "amount": 5 }),
origin: None,
acting: None,
evidence: Vec::new(),
};
let scope = ApprovalScope::new("app", "u", "s");
let request = |id: &str| {
ApprovalRequest::new(
id,
scope.clone(),
&call,
ApprovalPolicy::new([ApproverSelector::human("ana")]),
)
};
let recorder = InMemoryAuditRecorder::new();
let store = Arc::new(InMemoryApprovalStore::new());
let service = StoreApprovalService::new(store.clone())
.with_audit(AuditTrail::new(Arc::new(recorder.clone())));
let submitted = service.submit(request("req")).await.unwrap();
service
.decide(
&submitted.id,
submitted.version,
ApprovalDecision::approve(SubjectRef::human("ana")),
)
.await
.unwrap();
assert_eq!(
recorder.records(),
vec![
AuditRecordDraft::new(AuditRecordKind::Approval, "pay")
.actor(AuditActor::subject(SubjectRef::human("ana")))
.args_digest(recorder.digest(&submitted.args_redacted))
.decision(AuditDecision::Approved)
.ext("source", json!("approval_service"))
.ext("approvalId", json!(submitted.id))
.ext("approvalAction", json!("approve"))
.ext("version", json!(submitted.version + 1))
.ext("sessionId", json!("s"))
]
);
let blocked_store = Arc::new(InMemoryApprovalStore::new());
let blocked = StoreApprovalService::new(blocked_store.clone())
.with_audit(AuditTrail::new(Arc::new(Broken)));
let submitted = blocked.submit(request("req-2")).await.unwrap();
let error = blocked
.decide(
&submitted.id,
submitted.version,
ApprovalDecision::approve(SubjectRef::human("ana")),
)
.await
.unwrap_err();
assert_eq!(error.code, "audit.record_failed");
assert!(!blocked_store.has_decision(&scope, &call.fingerprint()).await.unwrap());
assert_eq!(
blocked.get(&submitted.id).await.unwrap().unwrap().state,
ApprovalState::Pending
);
}
fn verb_origin() -> ToolOrigin {
ToolOrigin::new(
"verbs:adk-rust",
&json!({ "name": "verb_snooze", "parameters": { "type": "object" } }),
None,
)
}
#[tokio::test]
async fn a_submitted_call_keeps_its_tools_origin() {
use crate::InMemoryApprovalStore;
let policy = ApprovalPolicy::new([ApproverSelector::human("ana")]);
let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
.with_router(policy.clone());
let scope = ApprovalScope::new("adk-rust", "ana", "s-1");
let mut held = ToolConfirmationRequest::new("verb_snooze", json!({ "item": "agenda-7" }));
held.function_call_id = Some("call-1".into());
held.origin = Some(verb_origin());
let call = ApprovalCall {
scope: scope.clone(),
request: held.clone(),
reason: "Move News digest to 19:00".into(),
agent_name: "finance".into(),
invocation_id: "inv".into(),
run_id: None,
acting: None,
};
let request = service.submit_call(call).await.unwrap().unwrap();
let mut expected = ApprovalRequest::new(request.id.clone(), scope, &held, policy)
.with_summary("Move News digest to 19:00")
.with_requester(SubjectRef::human("ana"));
expected.created_at = request.created_at;
assert_eq!(request, expected);
assert_eq!(expected.origin, Some(verb_origin()));
assert_eq!(service.get(&request.id).await.unwrap(), Some(request));
}
#[test]
fn with_origin_names_the_tools_publisher() {
let call = ToolConfirmationRequest::new("pay", json!({}));
let policy = ApprovalPolicy::new([ApproverSelector::human("ana")]);
let request =
ApprovalRequest::new("apr-1", ApprovalScope::new("a", "u", "s"), &call, policy);
assert_eq!(request.origin, None);
let named = request.clone().with_origin(verb_origin());
assert_eq!(named, ApprovalRequest { origin: Some(verb_origin()), ..request });
}
#[test]
fn a_record_without_an_origin_reads_as_none() {
let call = ToolConfirmationRequest::new("pay", json!({ "cents": 500 }));
let policy = ApprovalPolicy::new([ApproverSelector::human("ana")]);
let request =
ApprovalRequest::new("apr-1", ApprovalScope::new("a", "u", "s"), &call, policy);
let written = serde_json::to_value(&request).unwrap();
assert_eq!(written.get("origin"), None);
let read: ApprovalRequest = serde_json::from_value(written).unwrap();
assert_eq!(read, request);
let named = request.with_origin(verb_origin());
let written = serde_json::to_value(&named).unwrap();
assert_eq!(
written["origin"],
json!({ "source": "verbs:adk-rust", "declarationDigest": verb_origin().declaration_digest })
);
assert_eq!(serde_json::from_value::<ApprovalRequest>(written).unwrap(), named);
}
#[tokio::test]
async fn a_host_routes_and_hears_a_service_built_without_a_router() {
use crate::InMemoryApprovalStore;
#[derive(Debug, Default)]
struct Heard(std::sync::Mutex<Vec<(ApprovalEventKind, ApprovalState)>>);
#[async_trait]
impl ApprovalNotifier for Heard {
async fn notify(&self, notification: &ApprovalNotification) -> Result<()> {
let heard = (notification.kind, notification.request.state);
self.0.lock().unwrap().push(heard);
Ok(())
}
}
let call = |args: Value| ApprovalCall {
scope: ApprovalScope::new("app", "ana", "s-1"),
request: ToolConfirmationRequest::new("bash", args),
reason: "needs approval".into(),
agent_name: "agent".into(),
invocation_id: "inv".into(),
run_id: Some("run-1".into()),
acting: None,
};
let operator = || -> Arc<dyn ApprovalRouter> {
Arc::new(
ApprovalPolicy::new([ApproverSelector::group("operator")]).allow_self_approval(),
)
};
let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()));
assert_eq!(service.submit_call(call(json!({ "command": "ls" }))).await.unwrap(), None);
let heard = Arc::new(Heard::default());
assert!(service.route_unrouted(operator()));
assert!(service.add_notifier(heard.clone()));
let filed = service.submit_call(call(json!({ "command": "date" }))).await.unwrap();
let filed = filed.expect("the host's router files the call");
assert_eq!(filed.policy.approvers, vec![ApproverSelector::group("operator")]);
let decision =
ApprovalDecision::approve(SubjectRef::human("ana")).with_groups(["operator"]);
service.decide(&filed.id, filed.version, decision).await.unwrap();
assert_eq!(
*heard.0.lock().unwrap(),
vec![
(ApprovalEventKind::Submitted, ApprovalState::Pending),
(ApprovalEventKind::Decided, ApprovalState::Approved),
(ApprovalEventKind::Resolved, ApprovalState::Approved),
]
);
let declines = |_: &ApprovalCall| -> Option<ApprovalRoute> { None };
let own =
StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new())).with_router(declines);
assert!(own.route_unrouted(operator()));
assert_eq!(own.submit_call(call(json!({ "command": "ls" }))).await.unwrap(), None);
}
}