1use std::fmt;
67use std::sync::Arc;
68use std::time::Duration;
69
70use async_trait::async_trait;
71use chrono::{DateTime, Utc};
72use serde::{Deserialize, Serialize};
73use serde_json::Value;
74
75use crate::principal::{ActingContext, SubjectKind, SubjectRef};
76use crate::{
77 AdkError, ApprovalScope, ApprovalStore, Clock, DurableRunStore, ErrorCategory, ErrorComponent,
78 ErrorDetails, Result, SystemClock, ToolApproval, ToolConfirmationRequest, ToolOrigin,
79};
80
81pub const DEFAULT_APPROVAL_PAGE: usize = 100;
83
84pub const APPROVAL_REAPPLY_GRACE: Duration = Duration::from_secs(60);
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase")]
103pub enum ApprovalAction {
104 Approve,
106 Edit,
108 Reject,
110 Respond,
112}
113
114impl ApprovalAction {
115 pub const ALL: [Self; 4] = [Self::Approve, Self::Edit, Self::Reject, Self::Respond];
117}
118
119#[derive(
121 Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
122)]
123#[serde(rename_all = "camelCase")]
124pub enum ApprovalRisk {
125 Low,
127 #[default]
129 Medium,
130 High,
132 Critical,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
154#[serde(rename_all = "camelCase")]
155pub enum ApproverSelector {
156 Subject(SubjectRef),
158 Group(String),
160}
161
162impl ApproverSelector {
163 pub fn human(id: impl Into<String>) -> Self {
165 Self::Subject(SubjectRef::human(id))
166 }
167
168 pub fn group(group: impl Into<String>) -> Self {
170 Self::Group(group.into())
171 }
172
173 pub fn matches(&self, subject: &SubjectRef, groups: &[String]) -> bool {
175 match self {
176 Self::Subject(selected) => selected == subject,
177 Self::Group(group) => groups.iter().any(|member_of| member_of == group),
178 }
179 }
180}
181
182#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
185#[serde(rename_all = "camelCase")]
186pub struct EscalationStep {
187 #[serde(rename = "afterSecs", with = "duration_secs")]
189 pub after: Duration,
190 pub to: Vec<ApproverSelector>,
192}
193
194#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
196#[serde(rename_all = "camelCase")]
197#[non_exhaustive]
198pub enum ExpiryAction {
199 #[default]
201 Deny,
202}
203
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233#[serde(rename_all = "camelCase")]
234pub struct ApprovalPolicy {
235 pub approvers: Vec<ApproverSelector>,
237 #[serde(default, skip_serializing_if = "Vec::is_empty")]
241 pub slots: Vec<ApproverSelector>,
242 pub quorum: u32,
245 pub forbid_self_approval: bool,
248 #[serde(default, skip_serializing_if = "Vec::is_empty")]
250 pub escalation: Vec<EscalationStep>,
251 #[serde(default)]
253 pub on_expiry: ExpiryAction,
254 #[serde(
256 default,
257 rename = "expiresAfterSecs",
258 with = "option_duration_secs",
259 skip_serializing_if = "Option::is_none"
260 )]
261 pub expires_after: Option<Duration>,
262}
263
264impl ApprovalPolicy {
265 pub fn new(approvers: impl IntoIterator<Item = ApproverSelector>) -> Self {
268 Self {
269 approvers: approvers.into_iter().collect(),
270 slots: Vec::new(),
271 quorum: 1,
272 forbid_self_approval: true,
273 escalation: Vec::new(),
274 on_expiry: ExpiryAction::Deny,
275 expires_after: None,
276 }
277 }
278
279 pub fn for_slots(slots: impl IntoIterator<Item = ApproverSelector>) -> Self {
295 let slots: Vec<ApproverSelector> = slots.into_iter().collect();
296 let quorum = u32::try_from(slots.len()).unwrap_or(u32::MAX).max(1);
297 Self { slots, quorum, ..Self::new([]) }
298 }
299
300 #[must_use]
302 pub fn with_slots(mut self, slots: impl IntoIterator<Item = ApproverSelector>) -> Self {
303 self.slots.extend(slots);
304 self
305 }
306
307 #[must_use]
309 pub fn with_quorum(mut self, quorum: u32) -> Self {
310 self.quorum = quorum;
311 self
312 }
313
314 #[must_use]
316 pub fn allow_self_approval(mut self) -> Self {
317 self.forbid_self_approval = false;
318 self
319 }
320
321 #[must_use]
323 pub fn escalate_after(
324 mut self,
325 after: Duration,
326 to: impl IntoIterator<Item = ApproverSelector>,
327 ) -> Self {
328 self.escalation.push(EscalationStep { after, to: to.into_iter().collect() });
329 self
330 }
331
332 #[must_use]
334 pub fn expires_after(mut self, ttl: Duration) -> Self {
335 self.expires_after = Some(ttl);
336 self
337 }
338
339 pub fn validate(&self) -> Result<()> {
346 if self.approvers.is_empty() && self.slots.is_empty() {
347 return Err(invalid(
348 "approval.invalid_policy",
349 "an approval policy needs approvers or slots",
350 ));
351 }
352 if self.quorum == 0 {
353 return Err(invalid(
354 "approval.invalid_policy",
355 "an approval quorum must be at least 1",
356 ));
357 }
358 if self.escalation.windows(2).any(|pair| pair[0].after > pair[1].after) {
359 return Err(invalid(
360 "approval.invalid_policy",
361 "escalation steps must be ordered by their `after` delay",
362 ));
363 }
364 Ok(())
365 }
366}
367
368#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
374#[serde(rename_all = "camelCase")]
375pub enum ApprovalState {
376 Pending,
378 Approved,
380 Rejected,
382 Responded,
384 Expired,
386 Cancelled,
388}
389
390impl ApprovalState {
391 pub const ALL: [Self; 6] = [
393 Self::Pending,
394 Self::Approved,
395 Self::Rejected,
396 Self::Responded,
397 Self::Expired,
398 Self::Cancelled,
399 ];
400
401 pub fn as_str(self) -> &'static str {
403 match self {
404 Self::Pending => "pending",
405 Self::Approved => "approved",
406 Self::Rejected => "rejected",
407 Self::Responded => "responded",
408 Self::Expired => "expired",
409 Self::Cancelled => "cancelled",
410 }
411 }
412
413 pub fn is_terminal(self) -> bool {
415 !matches!(self, Self::Pending)
416 }
417}
418
419#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
435#[serde(rename_all = "camelCase")]
436pub struct ApprovalDecision {
437 pub approver: SubjectRef,
439 #[serde(default, skip_serializing_if = "Vec::is_empty")]
442 pub approver_groups: Vec<String>,
443 #[serde(default, skip_serializing_if = "Option::is_none")]
445 pub via_delegation: Option<SubjectRef>,
446 #[serde(default, skip_serializing_if = "Vec::is_empty")]
450 pub authority_groups: Vec<String>,
451 pub kind: ApprovalAction,
453 #[serde(default, skip_serializing_if = "Option::is_none")]
455 pub edited_args: Option<Value>,
456 #[serde(default, skip_serializing_if = "Option::is_none")]
458 pub reason: Option<String>,
459 pub decided_at: DateTime<Utc>,
461}
462
463impl ApprovalDecision {
464 fn new(approver: SubjectRef, kind: ApprovalAction) -> Self {
465 Self {
466 approver,
467 approver_groups: Vec::new(),
468 via_delegation: None,
469 authority_groups: Vec::new(),
470 kind,
471 edited_args: None,
472 reason: None,
473 decided_at: Utc::now(),
474 }
475 }
476
477 pub fn approve(approver: SubjectRef) -> Self {
479 Self::new(approver, ApprovalAction::Approve)
480 }
481
482 pub fn edit(approver: SubjectRef, args: Value) -> Self {
484 Self { edited_args: Some(args), ..Self::new(approver, ApprovalAction::Edit) }
485 }
486
487 pub fn reject(approver: SubjectRef, reason: impl Into<String>) -> Self {
489 Self { reason: Some(reason.into()), ..Self::new(approver, ApprovalAction::Reject) }
490 }
491
492 pub fn respond(approver: SubjectRef, response: impl Into<String>) -> Self {
494 Self { reason: Some(response.into()), ..Self::new(approver, ApprovalAction::Respond) }
495 }
496
497 #[must_use]
499 pub fn with_groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
500 self.approver_groups = groups.into_iter().map(Into::into).collect();
501 self
502 }
503
504 #[must_use]
506 pub fn via(mut self, delegator: SubjectRef) -> Self {
507 self.via_delegation = Some(delegator);
508 self
509 }
510
511 #[must_use]
513 pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
514 self.reason = Some(reason.into());
515 self
516 }
517
518 pub fn authority(&self) -> &SubjectRef {
520 self.via_delegation.as_ref().unwrap_or(&self.approver)
521 }
522}
523
524#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
554#[serde(rename_all = "camelCase")]
555pub struct ApprovalRequest {
556 pub id: String,
558 pub scope: ApprovalScope,
560 pub fingerprint: String,
562 pub tool_name: String,
564 #[serde(default, skip_serializing_if = "Option::is_none")]
568 pub origin: Option<ToolOrigin>,
569 pub args_redacted: Value,
571 #[serde(default, skip_serializing_if = "Vec::is_empty")]
577 pub evidence: Vec<crate::Evidence>,
578 #[serde(default, skip_serializing_if = "Option::is_none")]
580 pub acting: Option<ActingContext>,
581 #[serde(default, skip_serializing_if = "Option::is_none")]
584 pub requester: Option<SubjectRef>,
585 pub summary: String,
587 #[serde(default)]
589 pub risk: ApprovalRisk,
590 pub created_at: DateTime<Utc>,
592 #[serde(default, skip_serializing_if = "Option::is_none")]
594 pub expires_at: Option<DateTime<Utc>>,
595 pub allowed_actions: Vec<ApprovalAction>,
597 pub policy: ApprovalPolicy,
599 #[serde(default, skip_serializing_if = "Option::is_none")]
601 pub run_id: Option<String>,
602 pub version: u64,
604 pub state: ApprovalState,
606 #[serde(default, skip_serializing_if = "Vec::is_empty")]
608 pub decisions: Vec<ApprovalDecision>,
609 #[serde(default)]
611 pub escalations_fired: u32,
612 #[serde(default, skip_serializing_if = "Option::is_none")]
614 pub resolved_at: Option<DateTime<Utc>>,
615 #[serde(default, skip_serializing_if = "Option::is_none")]
617 pub note: Option<String>,
618 #[serde(default)]
620 pub outcome_applied: bool,
621}
622
623impl ApprovalRequest {
624 pub fn new(
627 id: impl Into<String>,
628 scope: ApprovalScope,
629 call: &ToolConfirmationRequest,
630 policy: ApprovalPolicy,
631 ) -> Self {
632 Self {
633 id: id.into(),
634 scope,
635 fingerprint: call.fingerprint(),
636 tool_name: call.tool_name.clone(),
637 origin: call.origin.clone(),
638 args_redacted: call.args.clone(),
639 evidence: call.evidence.clone(),
640 acting: None,
641 requester: None,
642 summary: format!("Approve a call to '{}'", call.tool_name),
643 risk: ApprovalRisk::Medium,
644 created_at: Utc::now(),
645 expires_at: None,
646 allowed_actions: ApprovalAction::ALL.to_vec(),
647 policy,
648 run_id: None,
649 version: 1,
650 state: ApprovalState::Pending,
651 decisions: Vec::new(),
652 escalations_fired: 0,
653 resolved_at: None,
654 note: None,
655 outcome_applied: false,
656 }
657 }
658
659 pub fn id_for_call(
666 scope: &ApprovalScope,
667 fingerprint: &str,
668 held_since: DateTime<Utc>,
669 ) -> String {
670 let key = serde_json::json!([
671 scope.app_name,
672 scope.user_id,
673 scope.session_id,
674 fingerprint,
675 held_since.timestamp_micros()
676 ]);
677 let digest = crate::action_ledger::json_digest(&key);
678 format!("apr_{}", digest.trim_start_matches("fnv1a128:"))
679 }
680
681 #[must_use]
683 pub fn with_summary(mut self, summary: impl Into<String>) -> Self {
684 self.summary = summary.into();
685 self
686 }
687
688 #[must_use]
690 pub fn with_risk(mut self, risk: ApprovalRisk) -> Self {
691 self.risk = risk;
692 self
693 }
694
695 #[must_use]
716 pub fn with_origin(mut self, origin: ToolOrigin) -> Self {
717 self.origin = Some(origin);
718 self
719 }
720
721 #[must_use]
723 pub fn with_redacted_args(mut self, args: Value) -> Self {
724 self.args_redacted = args;
725 self
726 }
727
728 #[must_use]
764 pub fn with_evidence(mut self, evidence: impl IntoIterator<Item = crate::Evidence>) -> Self {
765 self.evidence.extend(evidence);
766 self
767 }
768
769 #[must_use]
772 pub fn with_acting(mut self, acting: ActingContext) -> Self {
773 if self.requester.is_none() {
774 self.requester = acting.on_behalf_of.clone();
775 }
776 self.acting = Some(acting);
777 self
778 }
779
780 #[must_use]
782 pub fn with_requester(mut self, requester: SubjectRef) -> Self {
783 self.requester = Some(requester);
784 self
785 }
786
787 #[must_use]
789 pub fn with_run_id(mut self, run_id: impl Into<String>) -> Self {
790 self.run_id = Some(run_id.into());
791 self
792 }
793
794 #[must_use]
796 pub fn with_expires_at(mut self, at: DateTime<Utc>) -> Self {
797 self.expires_at = Some(at);
798 self
799 }
800
801 #[must_use]
803 pub fn with_allowed_actions(
804 mut self,
805 actions: impl IntoIterator<Item = ApprovalAction>,
806 ) -> Self {
807 self.allowed_actions = actions.into_iter().collect();
808 self
809 }
810
811 pub fn shows_call_args(&self) -> bool {
836 let shown = crate::tool_call_fingerprint(&self.tool_name, &self.args_redacted);
837 self.fingerprint.strip_suffix(shown.as_str()).is_some_and(|rest| rest.ends_with('\u{1f}'))
838 }
839
840 pub fn is_open(&self) -> bool {
842 self.state == ApprovalState::Pending || !self.outcome_applied
843 }
844
845 pub fn eligible_approvers(&self) -> impl Iterator<Item = &ApproverSelector> {
848 let fired = usize::try_from(self.escalations_fired).unwrap_or(usize::MAX);
849 self.policy
850 .approvers
851 .iter()
852 .chain(self.policy.slots.iter())
853 .chain(self.policy.escalation.iter().take(fired).flat_map(|step| step.to.iter()))
854 }
855
856 pub fn is_eligible(&self, subject: &SubjectRef, groups: &[String]) -> bool {
859 self.eligible_approvers().any(|selector| selector.matches(subject, groups))
860 }
861
862 pub fn is_self(&self, subject: &SubjectRef) -> bool {
867 let same_party = |other: &SubjectRef| {
868 other.id == subject.id
869 && (other.kind == subject.kind
870 || (other.kind != SubjectKind::Agent && subject.kind != SubjectKind::Agent))
871 };
872 self.requester.as_ref().is_some_and(same_party)
873 || self.acting.as_ref().is_some_and(|acting| {
874 acting.on_behalf_of.as_ref().is_some_and(same_party)
875 || SubjectRef::agent(&acting.agent.id) == *subject
876 })
877 }
878
879 pub fn quorum_progress(&self) -> (Vec<SubjectRef>, Option<Value>) {
884 let (counted, args) = self.counted_approvals();
885 (counted.into_iter().map(|decision| decision.authority().clone()).collect(), args)
886 }
887
888 fn counted_approvals(&self) -> (Vec<&ApprovalDecision>, Option<Value>) {
891 let mut approvals: Vec<&ApprovalDecision> = Vec::new();
892 let mut args = None;
893 for decision in &self.decisions {
894 match decision.kind {
895 ApprovalAction::Approve => {
896 if !approvals.iter().any(|held| held.authority() == decision.authority()) {
897 approvals.push(decision);
898 }
899 }
900 ApprovalAction::Edit => {
901 approvals.clear();
902 approvals.push(decision);
903 args = decision.edited_args.clone();
904 }
905 ApprovalAction::Reject | ApprovalAction::Respond => {}
906 }
907 }
908 (approvals, args)
909 }
910
911 pub fn open_slots(&self) -> Vec<&ApproverSelector> {
937 self.slot_holders()
938 .into_iter()
939 .filter(|(_, holder)| holder.is_none())
940 .map(|(slot, _)| slot)
941 .collect()
942 }
943
944 pub fn slot_holders(&self) -> Vec<(&ApproverSelector, Option<&ApprovalDecision>)> {
979 let slots = &self.policy.slots;
980 if slots.is_empty() {
981 return Vec::new();
982 }
983 let (approvals, _) = self.counted_approvals();
984 fn assign(
987 approver: usize,
988 approvals: &[&ApprovalDecision],
989 slots: &[ApproverSelector],
990 seen: &mut [bool],
991 filled_by: &mut [Option<usize>],
992 ) -> bool {
993 let decision = approvals[approver];
994 for (slot, selector) in slots.iter().enumerate() {
995 if seen[slot] || !selector.matches(decision.authority(), &decision.authority_groups)
996 {
997 continue;
998 }
999 seen[slot] = true;
1000 let free = match filled_by[slot] {
1001 None => true,
1002 Some(holder) => assign(holder, approvals, slots, seen, filled_by),
1003 };
1004 if free {
1005 filled_by[slot] = Some(approver);
1006 return true;
1007 }
1008 }
1009 false
1010 }
1011 let mut filled_by: Vec<Option<usize>> = vec![None; slots.len()];
1012 for approver in 0..approvals.len() {
1013 let mut seen = vec![false; slots.len()];
1014 assign(approver, &approvals, slots, &mut seen, &mut filled_by);
1015 }
1016 slots
1017 .iter()
1018 .zip(filled_by)
1019 .map(|(slot, holder)| (slot, holder.map(|i| approvals[i])))
1020 .collect()
1021 }
1022
1023 pub fn outcome(&self) -> Option<ToolApproval> {
1026 let last_reason = || self.decisions.last().and_then(|decision| decision.reason.clone());
1027 match self.state {
1028 ApprovalState::Pending => None,
1029 ApprovalState::Approved => {
1030 let approval = ToolApproval::approve();
1031 Some(match self.quorum_progress().1 {
1032 Some(args) => approval.with_edited_args(args),
1033 None => approval,
1034 })
1035 }
1036 ApprovalState::Rejected => {
1037 Some(ToolApproval::deny().with_message(match last_reason() {
1038 Some(reason) => format!("the approver rejected it: {reason}"),
1039 None => "the approver rejected it".to_string(),
1040 }))
1041 }
1042 ApprovalState::Responded => Some(ToolApproval::deny().with_message(format!(
1043 "the approver responded instead: {}",
1044 last_reason().unwrap_or_default()
1045 ))),
1046 ApprovalState::Expired => Some(
1047 ToolApproval::deny()
1048 .with_message("the approval request expired before enough approvers decided"),
1049 ),
1050 ApprovalState::Cancelled => Some(ToolApproval::deny().with_message(match &self.note {
1051 Some(note) => format!("the approval request was cancelled: {note}"),
1052 None => "the approval request was cancelled".to_string(),
1053 })),
1054 }
1055 }
1056
1057 pub fn cursor(&self) -> ApprovalCursor {
1059 ApprovalCursor { created_at: self.created_at, id: self.id.clone() }
1060 }
1061}
1062
1063#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1069#[serde(rename_all = "camelCase")]
1070pub struct DelegationWindow {
1071 pub not_before: DateTime<Utc>,
1073 pub not_after: DateTime<Utc>,
1075}
1076
1077impl DelegationWindow {
1078 pub fn new(not_before: DateTime<Utc>, not_after: DateTime<Utc>) -> Self {
1080 Self { not_before, not_after }
1081 }
1082
1083 pub fn contains(&self, at: DateTime<Utc>) -> bool {
1085 self.not_before <= at && at < self.not_after
1086 }
1087}
1088
1089#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1091#[serde(rename_all = "camelCase")]
1092pub struct DelegationScope {
1093 #[serde(default, skip_serializing_if = "Option::is_none")]
1095 pub app_name: Option<String>,
1096 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1098 pub tool_names: Vec<String>,
1099}
1100
1101impl DelegationScope {
1102 pub fn covers(&self, request: &ApprovalRequest) -> bool {
1104 self.app_name.as_ref().is_none_or(|app| *app == request.scope.app_name)
1105 && (self.tool_names.is_empty() || self.tool_names.contains(&request.tool_name))
1106 }
1107}
1108
1109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1128#[serde(rename_all = "camelCase")]
1129pub struct ApprovalDelegation {
1130 pub id: String,
1132 pub from: SubjectRef,
1134 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1137 pub from_groups: Vec<String>,
1138 pub to: SubjectRef,
1140 pub window: DelegationWindow,
1142 #[serde(default)]
1144 pub scope: DelegationScope,
1145 pub created_at: DateTime<Utc>,
1147}
1148
1149impl ApprovalDelegation {
1150 pub fn new(from: SubjectRef, to: SubjectRef, window: DelegationWindow) -> Self {
1152 Self {
1153 id: format!("dlg_{}", uuid::Uuid::new_v4().simple()),
1154 from,
1155 from_groups: Vec::new(),
1156 to,
1157 window,
1158 scope: DelegationScope::default(),
1159 created_at: Utc::now(),
1160 }
1161 }
1162
1163 #[must_use]
1165 pub fn with_from_groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
1166 self.from_groups = groups.into_iter().map(Into::into).collect();
1167 self
1168 }
1169
1170 #[must_use]
1172 pub fn with_scope(mut self, scope: DelegationScope) -> Self {
1173 self.scope = scope;
1174 self
1175 }
1176
1177 pub fn applies_to(&self, request: &ApprovalRequest, at: DateTime<Utc>) -> bool {
1179 self.window.contains(at)
1180 && self.scope.covers(request)
1181 && request.is_eligible(&self.from, &self.from_groups)
1182 }
1183}
1184
1185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1191#[serde(rename_all = "camelCase")]
1192pub struct ApprovalCursor {
1193 pub created_at: DateTime<Utc>,
1195 pub id: String,
1197}
1198
1199impl ApprovalCursor {
1200 pub fn precedes(&self, request: &ApprovalRequest) -> bool {
1202 (request.created_at, request.id.as_str()) > (self.created_at, self.id.as_str())
1203 }
1204
1205 pub fn encode(&self) -> String {
1207 format!("{}:{}", self.created_at.timestamp_micros(), self.id)
1208 }
1209
1210 pub fn decode(token: &str) -> Result<Self> {
1216 let malformed = || invalid("approval.invalid_cursor", "malformed approval page cursor");
1217 let (micros, id) = token.split_once(':').ok_or_else(malformed)?;
1218 let created_at = micros
1219 .parse::<i64>()
1220 .ok()
1221 .and_then(DateTime::from_timestamp_micros)
1222 .ok_or_else(malformed)?;
1223 Ok(Self { created_at, id: id.to_string() })
1224 }
1225}
1226
1227#[derive(Debug, Clone, PartialEq, Eq)]
1242#[non_exhaustive]
1243pub struct ApprovalRequestQuery {
1244 pub states: Vec<ApprovalState>,
1246 pub open_only: bool,
1248 pub app_name: Option<String>,
1250 pub user_id: Option<String>,
1252 pub session_id: Option<String>,
1257 pub after: Option<ApprovalCursor>,
1259 pub limit: usize,
1261}
1262
1263impl Default for ApprovalRequestQuery {
1264 fn default() -> Self {
1265 Self {
1266 states: Vec::new(),
1267 open_only: false,
1268 app_name: None,
1269 user_id: None,
1270 session_id: None,
1271 after: None,
1272 limit: DEFAULT_APPROVAL_PAGE,
1273 }
1274 }
1275}
1276
1277impl ApprovalRequestQuery {
1278 #[must_use]
1280 pub fn with_states(mut self, states: impl IntoIterator<Item = ApprovalState>) -> Self {
1281 self.states = states.into_iter().collect();
1282 self
1283 }
1284
1285 #[must_use]
1287 pub fn open_only(mut self) -> Self {
1288 self.open_only = true;
1289 self
1290 }
1291
1292 #[must_use]
1294 pub fn with_app_name(mut self, app_name: impl Into<String>) -> Self {
1295 self.app_name = Some(app_name.into());
1296 self
1297 }
1298
1299 #[must_use]
1311 pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
1312 self.session_id = Some(session_id.into());
1313 self
1314 }
1315
1316 #[must_use]
1327 pub fn with_user_id(mut self, user_id: impl Into<String>) -> Self {
1328 self.user_id = Some(user_id.into());
1329 self
1330 }
1331
1332 #[must_use]
1348 pub fn with_session(self, scope: &ApprovalScope) -> Self {
1349 self.with_app_name(scope.app_name.clone())
1350 .with_user_id(scope.user_id.clone())
1351 .with_session_id(scope.session_id.clone())
1352 }
1353
1354 #[must_use]
1356 pub fn with_after(mut self, cursor: Option<ApprovalCursor>) -> Self {
1357 self.after = cursor;
1358 self
1359 }
1360
1361 #[must_use]
1363 pub fn with_limit(mut self, limit: usize) -> Self {
1364 self.limit = limit;
1365 self
1366 }
1367
1368 pub fn matches(&self, request: &ApprovalRequest) -> bool {
1370 (self.states.is_empty() || self.states.contains(&request.state))
1371 && (!self.open_only || request.is_open())
1372 && self.app_name.as_ref().is_none_or(|app| *app == request.scope.app_name)
1373 && self.user_id.as_ref().is_none_or(|user| *user == request.scope.user_id)
1374 && self.session_id.as_ref().is_none_or(|session| *session == request.scope.session_id)
1375 && self.after.as_ref().is_none_or(|cursor| cursor.precedes(request))
1376 }
1377}
1378
1379#[derive(Debug, Clone, PartialEq, Eq)]
1400#[non_exhaustive]
1401pub struct InboxQuery {
1402 pub approver: Option<SubjectRef>,
1404 pub groups: Vec<String>,
1406 pub states: Vec<ApprovalState>,
1408 pub app_name: Option<String>,
1410 pub user_id: Option<String>,
1412 pub session_id: Option<String>,
1417 pub cursor: Option<String>,
1419 pub limit: usize,
1421}
1422
1423impl Default for InboxQuery {
1424 fn default() -> Self {
1425 Self {
1426 approver: None,
1427 groups: Vec::new(),
1428 states: Vec::new(),
1429 app_name: None,
1430 user_id: None,
1431 session_id: None,
1432 cursor: None,
1433 limit: 50,
1434 }
1435 }
1436}
1437
1438impl InboxQuery {
1439 pub fn for_approver(
1441 approver: SubjectRef,
1442 groups: impl IntoIterator<Item = impl Into<String>>,
1443 ) -> Self {
1444 Self {
1445 approver: Some(approver),
1446 groups: groups.into_iter().map(Into::into).collect(),
1447 ..Self::default()
1448 }
1449 }
1450
1451 pub fn for_group(group: impl Into<String>) -> Self {
1453 Self { groups: vec![group.into()], ..Self::default() }
1454 }
1455
1456 #[must_use]
1458 pub fn with_states(mut self, states: impl IntoIterator<Item = ApprovalState>) -> Self {
1459 self.states = states.into_iter().collect();
1460 self
1461 }
1462
1463 #[must_use]
1465 pub fn with_app_name(mut self, app_name: impl Into<String>) -> Self {
1466 self.app_name = Some(app_name.into());
1467 self
1468 }
1469
1470 #[must_use]
1486 pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
1487 self.session_id = Some(session_id.into());
1488 self
1489 }
1490
1491 #[must_use]
1493 pub fn with_user_id(mut self, user_id: impl Into<String>) -> Self {
1494 self.user_id = Some(user_id.into());
1495 self
1496 }
1497
1498 #[must_use]
1512 pub fn with_session(self, scope: &ApprovalScope) -> Self {
1513 self.with_app_name(scope.app_name.clone())
1514 .with_user_id(scope.user_id.clone())
1515 .with_session_id(scope.session_id.clone())
1516 }
1517
1518 #[must_use]
1520 pub fn with_cursor(mut self, cursor: Option<String>) -> Self {
1521 self.cursor = cursor;
1522 self
1523 }
1524
1525 #[must_use]
1527 pub fn with_limit(mut self, limit: usize) -> Self {
1528 self.limit = limit;
1529 self
1530 }
1531}
1532
1533#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1535#[serde(rename_all = "camelCase")]
1536pub struct InboxPage {
1537 pub items: Vec<ApprovalRequest>,
1539 #[serde(default, skip_serializing_if = "Option::is_none")]
1541 pub next_cursor: Option<String>,
1542}
1543
1544#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1550#[serde(rename_all = "camelCase")]
1551#[non_exhaustive]
1552pub enum ApprovalEventKind {
1553 Submitted,
1555 Escalated,
1557 Decided,
1559 Resolved,
1561 Expired,
1563 Cancelled,
1565}
1566
1567#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1569#[serde(rename_all = "camelCase")]
1570pub struct ApprovalNotification {
1571 pub id: String,
1574 pub kind: ApprovalEventKind,
1576 pub request: ApprovalRequest,
1578 #[serde(default, skip_serializing_if = "Option::is_none")]
1580 pub decision: Option<ApprovalDecision>,
1581 #[serde(default, skip_serializing_if = "Option::is_none")]
1583 pub escalation_step: Option<u32>,
1584 pub at: DateTime<Utc>,
1586}
1587
1588#[async_trait]
1613pub trait ApprovalNotifier: fmt::Debug + Send + Sync {
1614 async fn notify(&self, notification: &ApprovalNotification) -> Result<()>;
1616}
1617
1618#[async_trait]
1646pub trait ApprovalResolution: fmt::Debug + Send + Sync {
1647 async fn resolving(&self, request: &ApprovalRequest, decision: &ApprovalDecision);
1649}
1650
1651#[derive(Debug, Clone, PartialEq)]
1658pub struct ApprovalCall {
1659 pub scope: ApprovalScope,
1661 pub request: ToolConfirmationRequest,
1663 pub reason: String,
1665 pub agent_name: String,
1667 pub invocation_id: String,
1669 pub run_id: Option<String>,
1671 pub acting: Option<ActingContext>,
1673}
1674
1675#[derive(Debug, Clone, PartialEq)]
1677pub struct ApprovalRoute {
1678 pub policy: ApprovalPolicy,
1680 pub summary: Option<String>,
1682 pub risk: ApprovalRisk,
1684 pub redacted_args: Option<Value>,
1686 pub allowed_actions: Option<Vec<ApprovalAction>>,
1688 pub evidence: Vec<crate::Evidence>,
1692}
1693
1694impl ApprovalRoute {
1695 pub fn new(policy: ApprovalPolicy) -> Self {
1697 Self {
1698 policy,
1699 summary: None,
1700 risk: ApprovalRisk::default(),
1701 redacted_args: None,
1702 allowed_actions: None,
1703 evidence: Vec::new(),
1704 }
1705 }
1706
1707 #[must_use]
1709 pub fn with_summary(mut self, summary: impl Into<String>) -> Self {
1710 self.summary = Some(summary.into());
1711 self
1712 }
1713
1714 #[must_use]
1716 pub fn with_risk(mut self, risk: ApprovalRisk) -> Self {
1717 self.risk = risk;
1718 self
1719 }
1720
1721 #[must_use]
1723 pub fn with_redacted_args(mut self, args: Value) -> Self {
1724 self.redacted_args = Some(args);
1725 self
1726 }
1727
1728 #[must_use]
1730 pub fn with_allowed_actions(
1731 mut self,
1732 actions: impl IntoIterator<Item = ApprovalAction>,
1733 ) -> Self {
1734 self.allowed_actions = Some(actions.into_iter().collect());
1735 self
1736 }
1737
1738 #[must_use]
1740 pub fn with_evidence(mut self, evidence: impl IntoIterator<Item = crate::Evidence>) -> Self {
1741 self.evidence.extend(evidence);
1742 self
1743 }
1744}
1745
1746pub trait ApprovalRouter: Send + Sync {
1768 fn route(&self, call: &ApprovalCall) -> Option<ApprovalRoute>;
1770}
1771
1772impl ApprovalRouter for ApprovalPolicy {
1773 fn route(&self, _call: &ApprovalCall) -> Option<ApprovalRoute> {
1774 Some(ApprovalRoute::new(self.clone()))
1775 }
1776}
1777
1778impl<F> ApprovalRouter for F
1779where
1780 F: Fn(&ApprovalCall) -> Option<ApprovalRoute> + Send + Sync,
1781{
1782 fn route(&self, call: &ApprovalCall) -> Option<ApprovalRoute> {
1783 self(call)
1784 }
1785}
1786
1787#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1793#[serde(rename_all = "camelCase")]
1794pub struct ApprovalTick {
1795 pub expired: Vec<String>,
1797 pub escalated: Vec<(String, u32)>,
1799 pub reapplied: Vec<String>,
1801}
1802
1803#[async_trait]
1808pub trait ApprovalService: fmt::Debug + Send + Sync {
1809 async fn submit(&self, request: ApprovalRequest) -> Result<ApprovalRequest>;
1817
1818 async fn submit_call(&self, call: ApprovalCall) -> Result<Option<ApprovalRequest>>;
1828
1829 async fn get(&self, id: &str) -> Result<Option<ApprovalRequest>>;
1835
1836 async fn inbox(&self, query: InboxQuery) -> Result<InboxPage>;
1842
1843 async fn decide(
1860 &self,
1861 id: &str,
1862 expected_version: u64,
1863 decision: ApprovalDecision,
1864 ) -> Result<ApprovalRequest>;
1865
1866 async fn delegate(&self, delegation: ApprovalDelegation) -> Result<ApprovalDelegation>;
1873
1874 async fn revoke_delegation(&self, id: &str) -> Result<bool>;
1880
1881 async fn delegations_to(&self, to: &SubjectRef) -> Result<Vec<ApprovalDelegation>>;
1887
1888 async fn cancel(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest>;
1895
1896 async fn withdraw(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest> {
1909 self.cancel(id, reason).await
1910 }
1911
1912 async fn tick(&self, now: DateTime<Utc>) -> Result<ApprovalTick>;
1922
1923 fn approval_store(&self) -> Option<Arc<dyn ApprovalStore>> {
1925 None
1926 }
1927
1928 fn route_unrouted(&self, router: Arc<dyn ApprovalRouter>) -> bool {
1950 let _ = router;
1951 false
1952 }
1953
1954 fn add_notifier(&self, notifier: Arc<dyn ApprovalNotifier>) -> bool {
1985 let _ = notifier;
1986 false
1987 }
1988
1989 fn add_resolution(&self, hook: Arc<dyn ApprovalResolution>) -> bool {
2019 let _ = hook;
2020 false
2021 }
2022
2023 async fn record_review(
2075 &self,
2076 call: ApprovalCall,
2077 decision: ApprovalDecision,
2078 ) -> Result<Option<ApprovalRequest>> {
2079 let _ = (call, decision);
2080 Ok(None)
2081 }
2082}
2083
2084#[async_trait]
2122pub trait ApproverDirectory: Send + Sync {
2123 async fn groups(&self, subject: &SubjectRef, request: &ApprovalRequest) -> Result<Vec<String>>;
2129
2130 fn governs(&self, group: &str) -> bool {
2133 let _ = group;
2134 true
2135 }
2136}
2137
2138pub struct StoreApprovalService {
2158 store: Arc<dyn ApprovalStore>,
2159 clock: Arc<dyn Clock>,
2160 notifiers: Vec<Arc<dyn ApprovalNotifier>>,
2161 run_store: Option<Arc<dyn DurableRunStore>>,
2162 router: Option<Arc<dyn ApprovalRouter>>,
2163 audit: Option<crate::audit_log::AuditTrail>,
2164 directory: Option<Arc<dyn ApproverDirectory>>,
2165 fallback_router: std::sync::OnceLock<Arc<dyn ApprovalRouter>>,
2167 late_notifiers: std::sync::RwLock<Vec<Arc<dyn ApprovalNotifier>>>,
2169 resolutions: std::sync::RwLock<Vec<Arc<dyn ApprovalResolution>>>,
2171}
2172
2173impl fmt::Debug for StoreApprovalService {
2174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2175 f.debug_struct("StoreApprovalService")
2176 .field("store", &self.store)
2177 .field("clock", &self.clock)
2178 .field("notifiers", &self.notifiers)
2179 .field("run_store", &self.run_store.is_some())
2180 .field("router", &self.router.is_some())
2181 .field("fallback_router", &self.fallback_router.get().is_some())
2182 .field(
2183 "late_notifiers",
2184 &self.late_notifiers.read().unwrap_or_else(|e| e.into_inner()).len(),
2185 )
2186 .field("audit", &self.audit)
2187 .field("directory", &self.directory.is_some())
2188 .field("resolutions", &self.resolutions.read().unwrap_or_else(|e| e.into_inner()).len())
2189 .finish()
2190 }
2191}
2192
2193impl StoreApprovalService {
2194 pub fn new(store: Arc<dyn ApprovalStore>) -> Self {
2198 Self {
2199 store,
2200 clock: Arc::new(SystemClock),
2201 notifiers: Vec::new(),
2202 run_store: None,
2203 router: None,
2204 audit: None,
2205 directory: None,
2206 fallback_router: std::sync::OnceLock::new(),
2207 late_notifiers: std::sync::RwLock::new(Vec::new()),
2208 resolutions: std::sync::RwLock::new(Vec::new()),
2209 }
2210 }
2211
2212 #[must_use]
2214 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
2215 self.clock = clock;
2216 self
2217 }
2218
2219 #[must_use]
2221 pub fn with_notifier(mut self, notifier: Arc<dyn ApprovalNotifier>) -> Self {
2222 self.notifiers.push(notifier);
2223 self
2224 }
2225
2226 #[must_use]
2231 pub fn with_run_store(mut self, run_store: Arc<dyn DurableRunStore>) -> Self {
2232 self.run_store = Some(run_store);
2233 self
2234 }
2235
2236 #[must_use]
2238 pub fn with_router(mut self, router: impl ApprovalRouter + 'static) -> Self {
2239 self.router = Some(Arc::new(router));
2240 self
2241 }
2242
2243 #[must_use]
2263 pub fn with_audit(mut self, audit: crate::audit_log::AuditTrail) -> Self {
2264 self.audit = Some(audit);
2265 self
2266 }
2267
2268 #[must_use]
2271 pub fn with_directory(mut self, directory: Arc<dyn ApproverDirectory>) -> Self {
2272 self.directory = Some(directory);
2273 self
2274 }
2275
2276 async fn groups_of(
2279 &self,
2280 subject: &SubjectRef,
2281 asserted: &[String],
2282 request: &ApprovalRequest,
2283 ) -> Result<Vec<String>> {
2284 let Some(directory) = &self.directory else { return Ok(asserted.to_vec()) };
2285 let mut groups: Vec<String> =
2286 asserted.iter().filter(|group| !directory.governs(group)).cloned().collect();
2287 for group in directory.groups(subject, request).await? {
2288 if !groups.contains(&group) {
2289 groups.push(group);
2290 }
2291 }
2292 Ok(groups)
2293 }
2294
2295 async fn notify(
2296 &self,
2297 kind: ApprovalEventKind,
2298 request: &ApprovalRequest,
2299 decision: Option<&ApprovalDecision>,
2300 escalation_step: Option<u32>,
2301 ) {
2302 let late = self.late_notifiers.read().unwrap_or_else(|e| e.into_inner()).clone();
2303 if self.notifiers.is_empty() && late.is_empty() {
2304 return;
2305 }
2306 let notification = ApprovalNotification {
2307 id: format!("{}:{}", request.id, request.version),
2308 kind,
2309 request: request.clone(),
2310 decision: decision.cloned(),
2311 escalation_step,
2312 at: self.clock.now(),
2313 };
2314 for notifier in self.notifiers.iter().chain(&late) {
2315 if let Err(error) = notifier.notify(¬ification).await {
2316 tracing::warn!(
2317 approval.id = %request.id,
2318 approval.event = ?kind,
2319 error = %error,
2320 "approval notifier failed"
2321 );
2322 }
2323 }
2324 }
2325
2326 async fn apply(&self, request: ApprovalRequest, recovering: bool) -> Result<ApprovalRequest> {
2334 let Some(outcome) = request.outcome() else {
2335 return Ok(request);
2336 };
2337 if request.outcome_applied {
2338 return Ok(request);
2339 }
2340 let write = !recovering
2341 || self
2342 .store
2343 .pending(&request.scope)
2344 .await?
2345 .iter()
2346 .any(|entry| entry.fingerprint == request.fingerprint);
2347 if write {
2348 self.store.decide(&request.scope, &request.fingerprint, outcome).await?;
2349 }
2350 if let Some(runs) = &self.run_store {
2351 let mut waiting: Vec<String> = request.run_id.iter().cloned().collect();
2355 let parked = crate::RunFilter::default()
2356 .app_name(request.scope.app_name.clone())
2357 .user_id(request.scope.user_id.clone())
2358 .session_id(request.scope.session_id.clone())
2359 .states([crate::RunState::Waiting]);
2360 match runs.list(parked).await {
2361 Ok(parked) => waiting.extend(
2362 parked
2363 .into_iter()
2364 .filter(|run| {
2365 matches!(
2366 &run.checkpoint,
2367 Some(crate::RunCheckpointRef::AwaitingApproval { fingerprints, .. })
2368 if fingerprints.contains(&request.fingerprint)
2369 )
2370 })
2371 .map(|run| run.run_id)
2372 .filter(|run_id| request.run_id.as_ref() != Some(run_id)),
2373 ),
2374 Err(error) => {
2375 tracing::warn!(approval.id = %request.id, error = %error, "could not list the runs parked on an approval");
2376 }
2377 }
2378 for run_id in waiting {
2379 if let Err(error) = runs.wake(&run_id).await {
2380 tracing::warn!(approval.id = %request.id, run.id = %run_id, error = %error, "could not wake the run waiting for an approval");
2382 }
2383 }
2384 }
2385 let mut applied = request.clone();
2386 applied.outcome_applied = true;
2387 applied.version = request.version + 1;
2388 if self.store.replace_request(&applied, request.version).await? {
2389 Ok(applied)
2390 } else {
2391 Ok(self.store.get_request(&request.id).await?.unwrap_or(applied))
2393 }
2394 }
2395
2396 async fn swap(&self, next: &ApprovalRequest, expected: u64) -> Result<()> {
2398 if self.store.replace_request(next, expected).await? {
2399 return Ok(());
2400 }
2401 let current = self.store.get_request(&next.id).await?;
2402 Err(match current {
2403 Some(current) => version_conflict(&next.id, expected, current.version),
2404 None => not_found(&next.id),
2405 })
2406 }
2407
2408 async fn live_delegations(
2409 &self,
2410 to: &SubjectRef,
2411 at: DateTime<Utc>,
2412 ) -> Result<Vec<ApprovalDelegation>> {
2413 Ok(self
2414 .store
2415 .delegations_to(to)
2416 .await?
2417 .into_iter()
2418 .filter(|delegation| delegation.window.contains(at))
2419 .collect())
2420 }
2421
2422 async fn authority(
2425 &self,
2426 request: &ApprovalRequest,
2427 decision: &ApprovalDecision,
2428 at: DateTime<Utc>,
2429 ) -> Result<(Option<SubjectRef>, Vec<String>)> {
2430 let approver = &decision.approver;
2431 if approver.kind == SubjectKind::Visitor {
2432 return Err(forbidden(
2433 "approval.visitor_not_allowed",
2434 "a visitor cannot decide an approval request; approvers are identified subjects",
2435 ));
2436 }
2437 let forbid_self = request.policy.forbid_self_approval;
2438 if forbid_self && request.is_self(approver) {
2439 return Err(forbidden(
2440 "approval.self_approval",
2441 format!("'{}' may not approve their own call; ask another approver", approver.id),
2442 ));
2443 }
2444 let direct = request.is_eligible(approver, &decision.approver_groups);
2445 if direct && decision.via_delegation.is_none() {
2446 return Ok((None, decision.approver_groups.clone()));
2447 }
2448 let mut candidates: Vec<(ApprovalDelegation, Vec<String>)> = Vec::new();
2449 for delegation in self.store.delegations_to(approver).await? {
2450 if decision.via_delegation.as_ref().is_some_and(|from| *from != delegation.from)
2451 || !delegation.scope.covers(request)
2452 {
2453 continue;
2454 }
2455 let groups = self.groups_of(&delegation.from, &delegation.from_groups, request).await?;
2456 if request.is_eligible(&delegation.from, &groups) {
2457 candidates.push((delegation, groups));
2458 }
2459 }
2460 if let Some((live, groups)) =
2461 candidates.iter().find(|(delegation, _)| delegation.window.contains(at))
2462 {
2463 if forbid_self && request.is_self(&live.from) {
2464 return Err(forbidden(
2465 "approval.self_approval",
2466 format!(
2467 "'{}' may not approve on behalf of '{}', the requester",
2468 approver.id, live.from.id
2469 ),
2470 ));
2471 }
2472 return Ok((Some(live.from.clone()), groups.clone()));
2473 }
2474 if !candidates.is_empty() {
2475 return Err(forbidden(
2476 "approval.delegation_inactive",
2477 format!(
2478 "the delegation that lets '{}' approve this request is outside its window",
2479 approver.id
2480 ),
2481 ));
2482 }
2483 Err(forbidden(
2484 "approval.not_an_approver",
2485 format!("'{}' is not an approver of request '{}'", approver.id, request.id),
2486 ))
2487 }
2488
2489 async fn in_inbox(
2492 &self,
2493 request: &ApprovalRequest,
2494 query: &InboxQuery,
2495 delegations: &[ApprovalDelegation],
2496 at: DateTime<Utc>,
2497 ) -> Result<bool> {
2498 let forbid_self = request.policy.forbid_self_approval;
2499 let Some(approver) = query.approver.as_ref() else {
2500 return Ok(query.groups.is_empty()
2501 || request.eligible_approvers().any(|selector| {
2502 matches!(selector, ApproverSelector::Group(group) if query.groups.contains(group))
2503 }));
2504 };
2505 if forbid_self && request.is_self(approver) {
2506 return Ok(false);
2507 }
2508 let groups = self.groups_of(approver, &query.groups, request).await?;
2509 if request.is_eligible(approver, &groups) {
2510 return Ok(true);
2511 }
2512 for delegation in delegations {
2513 if !delegation.window.contains(at)
2514 || !delegation.scope.covers(request)
2515 || (forbid_self && request.is_self(&delegation.from))
2516 {
2517 continue;
2518 }
2519 let groups = self.groups_of(&delegation.from, &delegation.from_groups, request).await?;
2520 if request.is_eligible(&delegation.from, &groups) {
2521 return Ok(true);
2522 }
2523 }
2524 Ok(false)
2525 }
2526}
2527
2528#[async_trait]
2529impl ApprovalService for StoreApprovalService {
2530 async fn submit(&self, mut request: ApprovalRequest) -> Result<ApprovalRequest> {
2531 request.policy.validate()?;
2532 if request.id.is_empty() {
2533 return Err(invalid("approval.invalid_request", "an approval request needs an id"));
2534 }
2535 if request.allowed_actions.is_empty() {
2536 return Err(invalid(
2537 "approval.invalid_request",
2538 "an approval request must allow at least one action",
2539 ));
2540 }
2541 let now = self.clock.now();
2542 request.created_at = now;
2543 if request.expires_at.is_none()
2544 && let Some(ttl) = request.policy.expires_after
2545 {
2546 let ttl = chrono::Duration::from_std(ttl).unwrap_or(chrono::Duration::MAX);
2547 request.expires_at =
2548 Some(now.checked_add_signed(ttl).unwrap_or(DateTime::<Utc>::MAX_UTC));
2549 }
2550 request.version = 1;
2551 request.state = ApprovalState::Pending;
2552 request.decisions.clear();
2553 request.escalations_fired = 0;
2554 request.resolved_at = None;
2555 request.note = None;
2556 request.outcome_applied = false;
2557 let stored = self.store.create_request(&request).await?;
2558 if stored == request {
2559 tracing::info!(approval.id = %request.id, tool.name = %request.tool_name, "approval request submitted");
2560 self.notify(ApprovalEventKind::Submitted, &stored, None, None).await;
2561 }
2562 Ok(stored)
2563 }
2564
2565 async fn submit_call(&self, call: ApprovalCall) -> Result<Option<ApprovalRequest>> {
2566 let router = self.router.as_ref().or_else(|| self.fallback_router.get());
2567 let Some(route) = router.and_then(|router| router.route(&call)) else {
2568 return Ok(None);
2569 };
2570 self.store.record_pending(&call.scope, &call.request).await?;
2571 let fingerprint = call.request.fingerprint();
2572 let Some(held) = self
2573 .store
2574 .pending(&call.scope)
2575 .await?
2576 .into_iter()
2577 .find(|entry| entry.fingerprint == fingerprint)
2578 else {
2579 return Ok(None);
2581 };
2582 let mut open = ApprovalRequestQuery::default()
2585 .with_session(&call.scope)
2586 .with_states([ApprovalState::Pending]);
2587 loop {
2588 let batch = self.store.list_requests(&open).await?;
2589 if let Some(existing) = batch.iter().find(|request| request.fingerprint == fingerprint)
2590 {
2591 return Ok(Some(existing.clone()));
2592 }
2593 if batch.len() < open.limit {
2594 break;
2595 }
2596 open = open.with_after(batch.last().map(ApprovalRequest::cursor));
2597 }
2598 let id = ApprovalRequest::id_for_call(&call.scope, &fingerprint, held.requested_at);
2599 let mut request = ApprovalRequest::new(id, call.scope.clone(), &call.request, route.policy)
2600 .with_summary(route.summary.unwrap_or(call.reason))
2601 .with_risk(route.risk);
2602 if let Some(args) = route.redacted_args {
2603 request = request.with_redacted_args(args);
2604 }
2605 if let Some(actions) = route.allowed_actions {
2606 request = request.with_allowed_actions(actions);
2607 }
2608 request = request.with_evidence(route.evidence);
2609 if let Some(acting) = call.acting {
2610 request = request.with_acting(acting);
2611 }
2612 if request.requester.is_none() {
2613 request = request.with_requester(SubjectRef::human(call.scope.user_id.clone()));
2614 }
2615 if let Some(run_id) = call.run_id {
2616 request = request.with_run_id(run_id);
2617 }
2618 self.submit(request).await.map(Some)
2619 }
2620
2621 async fn get(&self, id: &str) -> Result<Option<ApprovalRequest>> {
2622 self.store.get_request(id).await
2623 }
2624
2625 async fn inbox(&self, query: InboxQuery) -> Result<InboxPage> {
2626 let now = self.clock.now();
2627 let delegations = match &query.approver {
2628 Some(approver) => self.live_delegations(approver, now).await?,
2629 None => Vec::new(),
2630 };
2631 let states = if query.states.is_empty() {
2632 vec![ApprovalState::Pending]
2633 } else {
2634 query.states.clone()
2635 };
2636 let limit = query.limit.max(1);
2637 let mut after = query.cursor.as_deref().map(ApprovalCursor::decode).transpose()?;
2638 let mut items = Vec::new();
2639 loop {
2640 let mut store_query = ApprovalRequestQuery::default()
2641 .with_states(states.iter().copied())
2642 .with_after(after.clone())
2643 .with_limit(DEFAULT_APPROVAL_PAGE);
2644 store_query.app_name = query.app_name.clone();
2645 store_query.user_id = query.user_id.clone();
2646 store_query.session_id = query.session_id.clone();
2647 let batch = self.store.list_requests(&store_query).await?;
2648 let exhausted = batch.len() < DEFAULT_APPROVAL_PAGE;
2649 for request in batch {
2650 after = Some(request.cursor());
2651 if self.in_inbox(&request, &query, &delegations, now).await? {
2652 items.push(request);
2653 if items.len() == limit {
2654 return Ok(InboxPage {
2655 items,
2656 next_cursor: after.map(|cursor| cursor.encode()),
2657 });
2658 }
2659 }
2660 }
2661 if exhausted {
2662 return Ok(InboxPage { items, next_cursor: None });
2663 }
2664 }
2665 }
2666
2667 async fn decide(
2668 &self,
2669 id: &str,
2670 expected_version: u64,
2671 mut decision: ApprovalDecision,
2672 ) -> Result<ApprovalRequest> {
2673 let now = self.clock.now();
2674 let request = self.store.get_request(id).await?.ok_or_else(|| not_found(id))?;
2675 if request.version != expected_version {
2676 return Err(version_conflict(id, expected_version, request.version));
2677 }
2678 if request.state.is_terminal() {
2679 return Err(conflict(
2680 "approval.already_resolved",
2681 format!("approval request '{id}' is already {}", request.state.as_str()),
2682 ));
2683 }
2684 if request.expires_at.is_some_and(|at| at <= now) {
2685 return Err(conflict(
2686 "approval.expired",
2687 format!("approval request '{id}' expired; the call is denied"),
2688 ));
2689 }
2690 if !request.allowed_actions.contains(&decision.kind) {
2691 return Err(invalid(
2692 "approval.action_not_allowed",
2693 format!("approval request '{id}' does not allow {:?}", decision.kind),
2694 ));
2695 }
2696 match decision.kind {
2697 ApprovalAction::Edit if decision.edited_args.is_none() => {
2698 return Err(invalid(
2699 "approval.action_not_allowed",
2700 "an edit must carry the edited arguments",
2701 ));
2702 }
2703 ApprovalAction::Respond
2704 if decision.reason.as_deref().is_none_or(|text| text.trim().is_empty()) =>
2705 {
2706 return Err(invalid(
2707 "approval.action_not_allowed",
2708 "a response must carry the text to report to the model",
2709 ));
2710 }
2711 ApprovalAction::Approve | ApprovalAction::Reject => decision.edited_args = None,
2712 ApprovalAction::Edit | ApprovalAction::Respond => {}
2713 }
2714 decision.approver_groups =
2715 self.groups_of(&decision.approver, &decision.approver_groups, &request).await?;
2716 (decision.via_delegation, decision.authority_groups) =
2717 self.authority(&request, &decision, now).await?;
2718 decision.decided_at = now;
2719 if matches!(decision.kind, ApprovalAction::Approve)
2720 && request.quorum_progress().0.contains(decision.authority())
2721 {
2722 return Err(conflict(
2723 "approval.already_decided",
2724 format!(
2725 "'{}' already approved request '{id}'; another approver must decide",
2726 decision.authority().id
2727 ),
2728 ));
2729 }
2730
2731 if let Some(trail) = &self.audit {
2732 use crate::audit_log::{AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind};
2733 let audited = match decision.kind {
2734 ApprovalAction::Approve | ApprovalAction::Edit => AuditDecision::Approved,
2735 ApprovalAction::Reject | ApprovalAction::Respond => AuditDecision::Rejected,
2736 };
2737 let mut actor = AuditActor::subject(decision.approver.clone());
2738 actor.delegation_chain.extend(decision.via_delegation.clone());
2739 let action = serde_json::to_value(decision.kind).unwrap_or(Value::Null);
2740 let mut draft = AuditRecordDraft::new(AuditRecordKind::Approval, &request.tool_name)
2741 .actor(actor)
2742 .args_digest(trail.digest(&request.args_redacted))
2743 .decision(audited)
2744 .ext("source", Value::String("approval_service".to_string()))
2745 .ext("approvalId", Value::String(id.to_string()))
2746 .ext("approvalAction", action)
2747 .ext("version", Value::from(expected_version + 1))
2748 .ext("sessionId", Value::String(request.scope.session_id.clone()));
2749 if let Some(acting) = &request.acting {
2750 draft = draft.ext("actingAgent", Value::String(acting.agent.id.to_string()));
2751 }
2752 if !request.evidence.is_empty() {
2754 let digests = request.evidence.iter().map(|item| Value::from(item.digest()));
2755 draft = draft.ext("evidenceDigests", Value::Array(digests.collect()));
2756 }
2757 if let Some(edited) = &decision.edited_args {
2758 draft = draft.ext("editedArgsDigest", Value::String(trail.digest(edited)));
2759 }
2760 trail.record(draft).await?;
2761 }
2762
2763 let mut next = request.clone();
2764 next.decisions.push(decision.clone());
2765 next.version = expected_version + 1;
2766 next.state = match decision.kind {
2767 ApprovalAction::Reject => ApprovalState::Rejected,
2768 ApprovalAction::Respond => ApprovalState::Responded,
2769 ApprovalAction::Approve | ApprovalAction::Edit => {
2770 let approvals = next.quorum_progress().0.len();
2771 if approvals >= usize::try_from(next.policy.quorum).unwrap_or(usize::MAX)
2772 && next.open_slots().is_empty()
2773 {
2774 ApprovalState::Approved
2775 } else {
2776 ApprovalState::Pending
2777 }
2778 }
2779 };
2780 if next.state.is_terminal() {
2781 next.resolved_at = Some(now);
2782 }
2783 self.swap(&next, expected_version).await?;
2784 tracing::info!(
2785 approval.id = %id,
2786 approval.action = ?decision.kind,
2787 approval.state = next.state.as_str(),
2788 "approval decision recorded"
2789 );
2790 if !next.state.is_terminal() {
2791 self.notify(ApprovalEventKind::Decided, &next, Some(&decision), None).await;
2792 return Ok(next);
2793 }
2794 let resolutions = self.resolutions.read().unwrap_or_else(|e| e.into_inner()).clone();
2797 for hook in resolutions {
2798 hook.resolving(&next, &decision).await;
2799 }
2800 let applied = self.apply(next.clone(), false).await?;
2803 self.notify(ApprovalEventKind::Decided, &next, Some(&decision), None).await;
2804 self.notify(ApprovalEventKind::Resolved, &applied, None, None).await;
2805 Ok(applied)
2806 }
2807
2808 async fn delegate(&self, mut delegation: ApprovalDelegation) -> Result<ApprovalDelegation> {
2809 if delegation.window.not_after <= delegation.window.not_before {
2810 return Err(invalid(
2811 "approval.invalid_delegation",
2812 "a delegation window must end after it starts",
2813 ));
2814 }
2815 if delegation.from == delegation.to {
2816 return Err(invalid(
2817 "approval.invalid_delegation",
2818 "a subject cannot delegate to itself",
2819 ));
2820 }
2821 if delegation.id.is_empty() {
2822 return Err(invalid("approval.invalid_delegation", "a delegation needs an id"));
2823 }
2824 delegation.created_at = self.clock.now();
2825 self.store.put_delegation(&delegation).await?;
2826 tracing::info!(
2827 delegation.id = %delegation.id,
2828 delegation.from = %delegation.from.id,
2829 delegation.to = %delegation.to.id,
2830 "approval delegation granted"
2831 );
2832 Ok(delegation)
2833 }
2834
2835 async fn revoke_delegation(&self, id: &str) -> Result<bool> {
2836 self.store.delete_delegation(id).await
2837 }
2838
2839 async fn delegations_to(&self, to: &SubjectRef) -> Result<Vec<ApprovalDelegation>> {
2840 self.store.delegations_to(to).await
2841 }
2842
2843 async fn cancel(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest> {
2844 let request = self.store.get_request(id).await?.ok_or_else(|| not_found(id))?;
2845 if request.state.is_terminal() {
2846 return Err(conflict(
2847 "approval.already_resolved",
2848 format!("approval request '{id}' is already {}", request.state.as_str()),
2849 ));
2850 }
2851 let mut next = request.clone();
2852 next.state = ApprovalState::Cancelled;
2853 next.version = request.version + 1;
2854 next.resolved_at = Some(self.clock.now());
2855 next.note = reason;
2856 self.swap(&next, request.version).await?;
2857 let applied = self.apply(next, false).await?;
2858 self.notify(ApprovalEventKind::Cancelled, &applied, None, None).await;
2859 Ok(applied)
2860 }
2861
2862 async fn withdraw(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest> {
2863 let request = self.store.get_request(id).await?.ok_or_else(|| not_found(id))?;
2864 if request.state.is_terminal() {
2865 return Err(conflict(
2866 "approval.already_resolved",
2867 format!("approval request '{id}' is already {}", request.state.as_str()),
2868 ));
2869 }
2870 let mut next = request.clone();
2871 next.state = ApprovalState::Cancelled;
2872 next.version = request.version + 1;
2873 next.resolved_at = Some(self.clock.now());
2874 next.note = reason;
2875 next.outcome_applied = true;
2877 self.swap(&next, request.version).await?;
2878 self.notify(ApprovalEventKind::Cancelled, &next, None, None).await;
2879 Ok(next)
2880 }
2881
2882 async fn tick(&self, now: DateTime<Utc>) -> Result<ApprovalTick> {
2883 let mut report = ApprovalTick::default();
2884 let mut after = None;
2885 loop {
2886 let query = ApprovalRequestQuery::default().open_only().with_after(after.clone());
2887 let batch = self.store.list_requests(&query).await?;
2888 let exhausted = batch.len() < query.limit;
2889 for request in batch {
2890 after = Some(request.cursor());
2891 if request.state.is_terminal() {
2892 let grace = chrono::Duration::from_std(APPROVAL_REAPPLY_GRACE)
2893 .unwrap_or(chrono::Duration::MAX);
2894 let settled = request
2895 .resolved_at
2896 .and_then(|at| at.checked_add_signed(grace))
2897 .is_none_or(|at| at <= now);
2898 if settled {
2899 let applied = self.apply(request, true).await?;
2900 report.reapplied.push(applied.id);
2901 }
2902 continue;
2903 }
2904 if request.expires_at.is_some_and(|at| at <= now) {
2905 let mut next = request.clone();
2906 next.state = ApprovalState::Expired;
2907 next.version = request.version + 1;
2908 next.resolved_at = Some(now);
2909 if !self.store.replace_request(&next, request.version).await? {
2910 continue;
2911 }
2912 tracing::info!(approval.id = %next.id, "approval request expired; denying the call");
2913 let applied = self.apply(next, false).await?;
2914 self.notify(ApprovalEventKind::Expired, &applied, None, None).await;
2915 report.expired.push(applied.id);
2916 continue;
2917 }
2918 let due = request
2919 .policy
2920 .escalation
2921 .iter()
2922 .take_while(|step| {
2923 chrono::Duration::from_std(step.after)
2924 .ok()
2925 .and_then(|after| request.created_at.checked_add_signed(after))
2926 .is_some_and(|at| at <= now)
2927 })
2928 .count();
2929 let due = u32::try_from(due).unwrap_or(u32::MAX);
2930 if due <= request.escalations_fired {
2931 continue;
2932 }
2933 let mut next = request.clone();
2934 next.escalations_fired = due;
2935 next.version = request.version + 1;
2936 if !self.store.replace_request(&next, request.version).await? {
2937 continue;
2938 }
2939 for step in request.escalations_fired..due {
2940 tracing::info!(approval.id = %next.id, approval.escalation_step = step, "approval request escalated");
2941 self.notify(ApprovalEventKind::Escalated, &next, None, Some(step)).await;
2942 report.escalated.push((next.id.clone(), step));
2943 }
2944 }
2945 if exhausted {
2946 return Ok(report);
2947 }
2948 }
2949 }
2950
2951 fn approval_store(&self) -> Option<Arc<dyn ApprovalStore>> {
2952 Some(self.store.clone())
2953 }
2954
2955 async fn record_review(
2956 &self,
2957 call: ApprovalCall,
2958 mut decision: ApprovalDecision,
2959 ) -> Result<Option<ApprovalRequest>> {
2960 let router = self.router.as_ref().or_else(|| self.fallback_router.get());
2961 let Some(route) = router.and_then(|router| router.route(&call)) else {
2962 return Ok(None);
2963 };
2964 route.policy.validate()?;
2965 let now = self.clock.now();
2966 let fingerprint = call.request.fingerprint();
2967 let id = ApprovalRequest::id_for_call(&call.scope, &fingerprint, now);
2968 let mut request = ApprovalRequest::new(id, call.scope.clone(), &call.request, route.policy)
2969 .with_summary(route.summary.unwrap_or(call.reason))
2970 .with_risk(route.risk);
2971 if let Some(args) = route.redacted_args {
2972 request = request.with_redacted_args(args);
2973 }
2974 if let Some(actions) = route.allowed_actions {
2975 request = request.with_allowed_actions(actions);
2976 }
2977 request = request.with_evidence(route.evidence);
2978 if let Some(acting) = call.acting {
2979 request = request.with_acting(acting);
2980 }
2981 if request.requester.is_none() {
2982 request = request.with_requester(SubjectRef::human(call.scope.user_id.clone()));
2983 }
2984 if let Some(run_id) = call.run_id {
2985 request = request.with_run_id(run_id);
2986 }
2987 decision.decided_at = now;
2988 request.created_at = now;
2989 request.state = match decision.kind {
2990 ApprovalAction::Approve | ApprovalAction::Edit => ApprovalState::Approved,
2991 ApprovalAction::Reject => ApprovalState::Rejected,
2992 ApprovalAction::Respond => ApprovalState::Responded,
2993 };
2994 request.decisions = vec![decision.clone()];
2995 request.resolved_at = Some(now);
2996 request.outcome_applied = true;
2998
2999 if let Some(trail) = &self.audit {
3000 use crate::audit_log::{AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind};
3001 let audited = match decision.kind {
3002 ApprovalAction::Approve | ApprovalAction::Edit => AuditDecision::Approved,
3003 ApprovalAction::Reject | ApprovalAction::Respond => AuditDecision::Rejected,
3004 };
3005 let action = serde_json::to_value(decision.kind).unwrap_or(Value::Null);
3006 let mut draft = AuditRecordDraft::new(AuditRecordKind::Approval, &request.tool_name)
3007 .actor(AuditActor::subject(decision.approver.clone()))
3008 .args_digest(trail.digest(&request.args_redacted))
3009 .decision(audited)
3010 .ext("source", Value::String(crate::REVIEW_SOURCE.to_string()))
3011 .ext("approvalId", Value::String(request.id.clone()))
3012 .ext("approvalAction", action)
3013 .ext("version", Value::from(request.version))
3014 .ext("sessionId", Value::String(request.scope.session_id.clone()));
3015 if let Some(acting) = &request.acting {
3016 draft = draft.ext("actingAgent", Value::String(acting.agent.id.to_string()));
3017 }
3018 if !request.evidence.is_empty() {
3020 let digests = request.evidence.iter().map(|item| Value::from(item.digest()));
3021 draft = draft.ext("evidenceDigests", Value::Array(digests.collect()));
3022 }
3023 trail.record(draft).await?;
3024 }
3025
3026 let stored = self.store.create_request(&request).await?;
3027 tracing::info!(
3028 approval.id = %stored.id,
3029 tool.name = %stored.tool_name,
3030 approval.state = stored.state.as_str(),
3031 reviewer.id = %decision.approver.id,
3032 "approval request decided by a reviewer"
3033 );
3034 if stored == request {
3035 self.notify(ApprovalEventKind::Decided, &stored, Some(&decision), None).await;
3036 self.notify(ApprovalEventKind::Resolved, &stored, None, None).await;
3037 }
3038 Ok(Some(stored))
3039 }
3040
3041 fn route_unrouted(&self, router: Arc<dyn ApprovalRouter>) -> bool {
3042 if self.router.is_none() {
3043 let _ = self.fallback_router.set(router);
3045 }
3046 true
3047 }
3048
3049 fn add_notifier(&self, notifier: Arc<dyn ApprovalNotifier>) -> bool {
3050 self.late_notifiers.write().unwrap_or_else(|e| e.into_inner()).push(notifier);
3051 true
3052 }
3053
3054 fn add_resolution(&self, hook: Arc<dyn ApprovalResolution>) -> bool {
3055 self.resolutions.write().unwrap_or_else(|e| e.into_inner()).push(hook);
3056 true
3057 }
3058}
3059
3060fn error(category: ErrorCategory, code: &'static str, message: impl Into<String>) -> AdkError {
3065 AdkError::new(ErrorComponent::Agent, category, code, message.into())
3066}
3067
3068fn invalid(code: &'static str, message: impl Into<String>) -> AdkError {
3069 error(ErrorCategory::InvalidInput, code, message)
3070}
3071
3072fn forbidden(code: &'static str, message: impl Into<String>) -> AdkError {
3073 error(ErrorCategory::Forbidden, code, message)
3074}
3075
3076fn conflict(code: &'static str, message: impl Into<String>) -> AdkError {
3077 error(ErrorCategory::Conflict, code, message)
3078}
3079
3080fn not_found(id: &str) -> AdkError {
3081 error(ErrorCategory::NotFound, "approval.not_found", format!("no approval request '{id}'"))
3082}
3083
3084fn version_conflict(id: &str, expected: u64, current: u64) -> AdkError {
3085 let mut details = ErrorDetails::default();
3086 details.metadata.insert("current_version".to_string(), current.into());
3087 conflict(
3088 "approval.version_conflict",
3089 format!(
3090 "approval request '{id}' is at version {current}, not {expected}; another decision \
3091 landed first, so re-read the request and decide again"
3092 ),
3093 )
3094 .with_details(details)
3095}
3096
3097pub(crate) fn store_unsupported(operation: &str) -> AdkError {
3099 error(
3100 ErrorCategory::Unsupported,
3101 "approval.store_unsupported",
3102 format!(
3103 "this approval store does not implement `{operation}`, which the approval service \
3104 needs; use a store from adk-core or adk-session, or implement the method"
3105 ),
3106 )
3107}
3108
3109mod duration_secs {
3110 use serde::{Deserialize, Deserializer, Serializer};
3111 use std::time::Duration;
3112
3113 pub fn serialize<S: Serializer>(value: &Duration, serializer: S) -> Result<S::Ok, S::Error> {
3114 serializer.serialize_u64(value.as_secs())
3115 }
3116
3117 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
3118 u64::deserialize(deserializer).map(Duration::from_secs)
3119 }
3120}
3121
3122mod option_duration_secs {
3123 use serde::{Deserialize, Deserializer, Serializer};
3124 use std::time::Duration;
3125
3126 #[allow(clippy::ref_option)] pub fn serialize<S: Serializer>(
3128 value: &Option<Duration>,
3129 serializer: S,
3130 ) -> Result<S::Ok, S::Error> {
3131 match value {
3132 Some(duration) => serializer.serialize_some(&duration.as_secs()),
3133 None => serializer.serialize_none(),
3134 }
3135 }
3136
3137 pub fn deserialize<'de, D: Deserializer<'de>>(
3138 deserializer: D,
3139 ) -> Result<Option<Duration>, D::Error> {
3140 Ok(Option::<u64>::deserialize(deserializer)?.map(Duration::from_secs))
3141 }
3142}
3143
3144#[cfg(test)]
3145mod tests {
3146 use super::*;
3147 use serde_json::json;
3148
3149 #[test]
3150 fn a_person_and_a_service_with_one_id_are_the_same_party() {
3151 let call = ToolConfirmationRequest::new("pay", json!({}));
3152 let request = ApprovalRequest::new(
3153 "req-1",
3154 ApprovalScope::new("ap", "controller", "s"),
3155 &call,
3156 ApprovalPolicy::new([ApproverSelector::group("finance")]),
3157 )
3158 .with_acting(
3159 ActingContext::new(crate::AgentPrincipal::derived("ap", "clerk"))
3160 .on_behalf_of(SubjectRef::service("controller")),
3161 );
3162 assert!(request.is_self(&SubjectRef::human("controller")));
3163 assert!(request.is_self(&SubjectRef::service("controller")));
3164 assert!(!request.is_self(&SubjectRef::human("cfo")));
3165 assert!(!request.is_self(&SubjectRef::new(SubjectKind::Agent, "controller")));
3166 assert!(
3167 request.is_self(&SubjectRef::agent(&crate::AgentPrincipal::derived("ap", "clerk").id))
3168 );
3169 }
3170
3171 #[test]
3172 fn policies_serialize_in_camel_case_with_whole_seconds() {
3173 let policy = ApprovalPolicy::new([ApproverSelector::group("finance")])
3174 .with_quorum(2)
3175 .escalate_after(Duration::from_secs(900), [ApproverSelector::human("cfo")])
3176 .expires_after(Duration::from_secs(3_600));
3177 let value = serde_json::to_value(&policy).unwrap();
3178 assert_eq!(
3179 value,
3180 json!({
3181 "approvers": [{ "group": "finance" }],
3182 "quorum": 2,
3183 "forbidSelfApproval": true,
3184 "escalation": [{
3185 "afterSecs": 900,
3186 "to": [{ "subject": { "kind": "human", "id": "cfo" } }]
3187 }],
3188 "onExpiry": "deny",
3189 "expiresAfterSecs": 3600
3190 })
3191 );
3192 assert_eq!(serde_json::from_value::<ApprovalPolicy>(value).unwrap(), policy);
3193 }
3194
3195 #[test]
3196 fn cursors_round_trip_ids_containing_colons() {
3197 let cursor = ApprovalCursor { created_at: Utc::now(), id: "a:b/ü".into() };
3198 let decoded = ApprovalCursor::decode(&cursor.encode()).unwrap();
3199 assert_eq!(decoded.id, cursor.id);
3200 assert_eq!(decoded.created_at.timestamp_micros(), cursor.created_at.timestamp_micros());
3201 assert_eq!(ApprovalCursor::decode("nope").unwrap_err().code, "approval.invalid_cursor");
3202 }
3203
3204 #[test]
3205 fn call_ids_change_with_the_hold_time() {
3206 let scope = ApprovalScope::new("app", "u", "s");
3207 let at = Utc::now();
3208 let id = ApprovalRequest::id_for_call(&scope, "fp", at);
3209 assert_eq!(id, ApprovalRequest::id_for_call(&scope, "fp", at));
3210 assert_ne!(
3211 id,
3212 ApprovalRequest::id_for_call(&scope, "fp", at + chrono::Duration::seconds(1))
3213 );
3214 assert!(id.starts_with("apr_"));
3215 }
3216
3217 #[test]
3218 fn invalid_policies_are_refused() {
3219 assert!(ApprovalPolicy::new([]).validate().is_err());
3220 let zero = ApprovalPolicy::new([ApproverSelector::group("g")]).with_quorum(0);
3221 assert_eq!(zero.validate().unwrap_err().code, "approval.invalid_policy");
3222 let unordered = ApprovalPolicy::new([ApproverSelector::group("g")])
3223 .escalate_after(Duration::from_secs(60), [])
3224 .escalate_after(Duration::from_secs(30), []);
3225 assert!(unordered.validate().is_err());
3226 }
3227
3228 #[tokio::test]
3229 async fn resolving_a_request_wakes_its_waiting_run() {
3230 use crate::{
3231 ApprovalStore, DurableRunStore, InMemoryApprovalStore, InMemoryRunStore, NewRun,
3232 RunState,
3233 };
3234
3235 let runs = Arc::new(InMemoryRunStore::new());
3236 let enqueued =
3237 runs.enqueue(NewRun::new("q", "app", "u", "agent", json!({}))).await.unwrap();
3238 let run_id = enqueued.record().unwrap().run_id.clone();
3239 let claimed = runs.claim("q", "worker", Duration::from_secs(60)).await.unwrap().unwrap();
3240 runs.wait(&run_id, claimed.epoch, None).await.unwrap();
3242 assert_eq!(runs.get(&run_id).await.unwrap().unwrap().state, RunState::Waiting);
3243
3244 let store = Arc::new(InMemoryApprovalStore::new());
3245 let service = StoreApprovalService::new(store.clone()).with_run_store(runs.clone());
3246 let call = ToolConfirmationRequest {
3247 tool_name: "pay".into(),
3248 function_call_id: Some("c1".into()),
3249 args: json!({ "amount": 5 }),
3250 origin: None,
3251 acting: None,
3252 evidence: Vec::new(),
3253 };
3254 let scope = ApprovalScope::new("app", "u", "s");
3255 let request = service
3256 .submit(
3257 ApprovalRequest::new(
3258 "req",
3259 scope.clone(),
3260 &call,
3261 ApprovalPolicy::new([ApproverSelector::human("ana")]),
3262 )
3263 .with_run_id(run_id.clone()),
3264 )
3265 .await
3266 .unwrap();
3267 service
3268 .decide(
3269 &request.id,
3270 request.version,
3271 ApprovalDecision::approve(SubjectRef::human("ana")),
3272 )
3273 .await
3274 .unwrap();
3275
3276 assert!(store.has_decision(&scope, &call.fingerprint()).await.unwrap());
3277 let woken = runs.claim("q", "worker", Duration::from_secs(60)).await.unwrap();
3278 assert_eq!(
3279 woken.map(|claim| claim.record.run_id),
3280 Some(run_id),
3281 "the decision woke the run"
3282 );
3283 }
3284
3285 #[tokio::test]
3289 async fn resolving_a_request_wakes_a_later_run_parked_on_the_call() {
3290 use crate::{DurableRunStore, InMemoryApprovalStore, InMemoryRunStore, NewRun, RunState};
3291
3292 let runs = Arc::new(InMemoryRunStore::new());
3293 let scope = ApprovalScope::new("app", "u", "s-1");
3294 let call = ToolConfirmationRequest::new("pay", json!({ "cents": 500 }));
3295 let park = |runs: Arc<InMemoryRunStore>| {
3296 let fingerprint = call.fingerprint();
3297 async move {
3298 let new = NewRun::new("q", "app", "u", "agent", json!({})).with_session_id("s-1");
3299 let run_id = runs.enqueue(new).await.unwrap().record().unwrap().run_id.clone();
3300 let claim = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap().unwrap();
3301 let checkpoint = crate::RunCheckpointRef::AwaitingApproval {
3302 session_id: "s-1".into(),
3303 invocation_id: None,
3304 fingerprints: vec![fingerprint],
3305 expires_at: None,
3306 };
3307 runs.set_checkpoint(&run_id, claim.epoch, checkpoint).await.unwrap();
3308 runs.wait(&run_id, claim.epoch, None).await.unwrap();
3309 run_id
3310 }
3311 };
3312 let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
3313 .with_run_store(runs.clone())
3314 .with_router(ApprovalPolicy::new([ApproverSelector::human("ana")]));
3315 let held_by = |run_id: &str| ApprovalCall {
3316 scope: scope.clone(),
3317 request: call.clone(),
3318 reason: "pay".into(),
3319 agent_name: "agent".into(),
3320 invocation_id: "inv".into(),
3321 run_id: Some(run_id.to_string()),
3322 acting: None,
3323 };
3324
3325 let first = park(runs.clone()).await;
3326 let request = service.submit_call(held_by(&first)).await.unwrap().unwrap();
3327 runs.request_cancel(&first).await.unwrap();
3328 let second = park(runs.clone()).await;
3329 let again = service.submit_call(held_by(&second)).await.unwrap().unwrap();
3330 assert_eq!(again.id, request.id, "the call held again keeps its request");
3331
3332 service
3333 .decide(
3334 &request.id,
3335 request.version,
3336 ApprovalDecision::approve(SubjectRef::human("ana")),
3337 )
3338 .await
3339 .unwrap();
3340 assert_eq!(runs.get(&first).await.unwrap().unwrap().state, RunState::Cancelled);
3341 let woken = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap();
3342 assert_eq!(woken.map(|claim| claim.record.run_id), Some(second), "the later run wakes");
3343 }
3344
3345 #[tokio::test]
3349 async fn a_resolved_outcome_is_in_the_store_before_the_notifiers_run() {
3350 use crate::{ApprovalStore, InMemoryApprovalStore};
3351
3352 #[derive(Debug)]
3353 struct Witness {
3354 store: Arc<InMemoryApprovalStore>,
3355 seen: std::sync::Mutex<Vec<(ApprovalEventKind, bool, bool)>>,
3356 }
3357 #[async_trait::async_trait]
3358 impl ApprovalNotifier for Witness {
3359 async fn notify(&self, notification: &ApprovalNotification) -> Result<()> {
3360 let request = ¬ification.request;
3361 let decided = self.store.has_decision(&request.scope, &request.fingerprint).await?;
3362 let waiting = self
3363 .store
3364 .pending(&request.scope)
3365 .await?
3366 .iter()
3367 .any(|entry| entry.fingerprint == request.fingerprint);
3368 self.seen.lock().unwrap().push((notification.kind, decided, waiting));
3369 Ok(())
3370 }
3371 }
3372
3373 let store = Arc::new(InMemoryApprovalStore::new());
3374 let witness = Arc::new(Witness { store: store.clone(), seen: Default::default() });
3375 let service = StoreApprovalService::new(store.clone())
3376 .with_notifier(witness.clone())
3377 .with_router(ApprovalPolicy::new([ApproverSelector::human("ana")]));
3378 let call = ApprovalCall {
3379 scope: ApprovalScope::new("app", "u", "s"),
3380 request: ToolConfirmationRequest::new("pay", json!({ "cents": 500 })),
3381 reason: "pay".into(),
3382 agent_name: "agent".into(),
3383 invocation_id: "inv".into(),
3384 run_id: None,
3385 acting: None,
3386 };
3387 let request = service.submit_call(call).await.unwrap().unwrap();
3388 service
3389 .decide(
3390 &request.id,
3391 request.version,
3392 ApprovalDecision::approve(SubjectRef::human("ana")),
3393 )
3394 .await
3395 .unwrap();
3396 assert_eq!(
3397 *witness.seen.lock().unwrap(),
3398 vec![
3399 (ApprovalEventKind::Submitted, false, true),
3400 (ApprovalEventKind::Decided, true, false),
3401 (ApprovalEventKind::Resolved, true, false),
3402 ]
3403 );
3404 }
3405
3406 #[tokio::test]
3410 async fn a_resolution_hook_runs_before_the_outcome_reaches_the_call_or_its_run() {
3411 use crate::{
3412 ApprovalStore, DurableRunStore, InMemoryApprovalStore, InMemoryRunStore, NewRun,
3413 RunState,
3414 };
3415
3416 type Seen = (ApprovalState, String, bool, Option<RunState>);
3418
3419 #[derive(Debug)]
3420 struct Witness {
3421 store: Arc<InMemoryApprovalStore>,
3422 runs: Arc<InMemoryRunStore>,
3423 run_id: String,
3424 seen: std::sync::Mutex<Vec<Seen>>,
3425 }
3426 #[async_trait::async_trait]
3427 impl ApprovalResolution for Witness {
3428 async fn resolving(&self, request: &ApprovalRequest, decision: &ApprovalDecision) {
3429 let applied =
3430 self.store.has_decision(&request.scope, &request.fingerprint).await.unwrap();
3431 let run = self.runs.get(&self.run_id).await.unwrap().map(|run| run.state);
3432 self.seen.lock().unwrap().push((
3433 request.state,
3434 decision.approver.id.clone(),
3435 applied,
3436 run,
3437 ));
3438 }
3439 }
3440
3441 let store = Arc::new(InMemoryApprovalStore::new());
3442 let runs = Arc::new(InMemoryRunStore::new());
3443 let new = NewRun::new("q", "app", "u", "agent", json!({})).with_session_id("s");
3444 let run_id = runs.enqueue(new).await.unwrap().record().unwrap().run_id.clone();
3445 let claim = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap().unwrap();
3446 let call = ToolConfirmationRequest::new("pay", json!({ "cents": 500 }));
3447 let checkpoint = crate::RunCheckpointRef::AwaitingApproval {
3448 session_id: "s".into(),
3449 invocation_id: None,
3450 fingerprints: vec![call.fingerprint()],
3451 expires_at: None,
3452 };
3453 runs.set_checkpoint(&run_id, claim.epoch, checkpoint).await.unwrap();
3454 runs.wait(&run_id, claim.epoch, None).await.unwrap();
3455 let witness = Arc::new(Witness {
3456 store: store.clone(),
3457 runs: runs.clone(),
3458 run_id: run_id.clone(),
3459 seen: Default::default(),
3460 });
3461 let service = StoreApprovalService::new(store.clone())
3462 .with_run_store(runs.clone())
3463 .with_router(ApprovalPolicy::new([ApproverSelector::human("ana")]));
3464 assert!(service.add_resolution(witness.clone()));
3465 let held = ApprovalCall {
3466 scope: ApprovalScope::new("app", "u", "s"),
3467 request: call,
3468 reason: "pay".into(),
3469 agent_name: "agent".into(),
3470 invocation_id: "inv".into(),
3471 run_id: Some(run_id.clone()),
3472 acting: None,
3473 };
3474 let request = service.submit_call(held).await.unwrap().unwrap();
3475 service
3476 .decide(
3477 &request.id,
3478 request.version,
3479 ApprovalDecision::approve(SubjectRef::human("ana")),
3480 )
3481 .await
3482 .unwrap();
3483
3484 assert_eq!(
3485 *witness.seen.lock().unwrap(),
3486 vec![(ApprovalState::Approved, "ana".to_string(), false, Some(RunState::Waiting))],
3487 "the hook saw the recorded yes, the call not yet decided and its run still asleep"
3488 );
3489 assert!(store.has_decision(&request.scope, &request.fingerprint).await.unwrap());
3490 let woken = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap();
3491 assert_eq!(woken.map(|claim| claim.record.run_id), Some(run_id), "then the run wakes");
3492 }
3493
3494 #[tokio::test]
3495 async fn an_approver_decision_is_audited_before_it_takes_effect() {
3496 use crate::audit_log::{
3497 AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditRecorder,
3498 AuditTrail, InMemoryAuditRecorder,
3499 };
3500 use crate::{ApprovalStore, InMemoryApprovalStore};
3501
3502 #[derive(Debug)]
3503 struct Broken;
3504 #[async_trait::async_trait]
3505 impl AuditRecorder for Broken {
3506 fn digest(&self, value: &Value) -> String {
3507 crate::json_digest(value)
3508 }
3509 async fn record(&self, _draft: AuditRecordDraft) -> Result<()> {
3510 Err(crate::AdkError::session("audit store down"))
3511 }
3512 }
3513
3514 let call = ToolConfirmationRequest {
3515 tool_name: "pay".into(),
3516 function_call_id: Some("c1".into()),
3517 args: json!({ "to": "acct-secret", "amount": 5 }),
3518 origin: None,
3519 acting: None,
3520 evidence: Vec::new(),
3521 };
3522 let scope = ApprovalScope::new("app", "u", "s");
3523 let request = |id: &str| {
3524 ApprovalRequest::new(
3525 id,
3526 scope.clone(),
3527 &call,
3528 ApprovalPolicy::new([ApproverSelector::human("ana")]),
3529 )
3530 };
3531
3532 let recorder = InMemoryAuditRecorder::new();
3533 let store = Arc::new(InMemoryApprovalStore::new());
3534 let service = StoreApprovalService::new(store.clone())
3535 .with_audit(AuditTrail::new(Arc::new(recorder.clone())));
3536 let submitted = service.submit(request("req")).await.unwrap();
3537 service
3538 .decide(
3539 &submitted.id,
3540 submitted.version,
3541 ApprovalDecision::approve(SubjectRef::human("ana")),
3542 )
3543 .await
3544 .unwrap();
3545 assert_eq!(
3546 recorder.records(),
3547 vec![
3548 AuditRecordDraft::new(AuditRecordKind::Approval, "pay")
3549 .actor(AuditActor::subject(SubjectRef::human("ana")))
3550 .args_digest(recorder.digest(&submitted.args_redacted))
3551 .decision(AuditDecision::Approved)
3552 .ext("source", json!("approval_service"))
3553 .ext("approvalId", json!(submitted.id))
3554 .ext("approvalAction", json!("approve"))
3555 .ext("version", json!(submitted.version + 1))
3556 .ext("sessionId", json!("s"))
3557 ]
3558 );
3559
3560 let blocked_store = Arc::new(InMemoryApprovalStore::new());
3561 let blocked = StoreApprovalService::new(blocked_store.clone())
3562 .with_audit(AuditTrail::new(Arc::new(Broken)));
3563 let submitted = blocked.submit(request("req-2")).await.unwrap();
3564 let error = blocked
3565 .decide(
3566 &submitted.id,
3567 submitted.version,
3568 ApprovalDecision::approve(SubjectRef::human("ana")),
3569 )
3570 .await
3571 .unwrap_err();
3572 assert_eq!(error.code, "audit.record_failed");
3573 assert!(!blocked_store.has_decision(&scope, &call.fingerprint()).await.unwrap());
3574 assert_eq!(
3575 blocked.get(&submitted.id).await.unwrap().unwrap().state,
3576 ApprovalState::Pending
3577 );
3578 }
3579
3580 fn verb_origin() -> ToolOrigin {
3581 ToolOrigin::new(
3582 "verbs:adk-rust",
3583 &json!({ "name": "verb_snooze", "parameters": { "type": "object" } }),
3584 None,
3585 )
3586 }
3587
3588 #[tokio::test]
3591 async fn a_submitted_call_keeps_its_tools_origin() {
3592 use crate::InMemoryApprovalStore;
3593
3594 let policy = ApprovalPolicy::new([ApproverSelector::human("ana")]);
3595 let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
3596 .with_router(policy.clone());
3597 let scope = ApprovalScope::new("adk-rust", "ana", "s-1");
3598 let mut held = ToolConfirmationRequest::new("verb_snooze", json!({ "item": "agenda-7" }));
3599 held.function_call_id = Some("call-1".into());
3600 held.origin = Some(verb_origin());
3601 let call = ApprovalCall {
3602 scope: scope.clone(),
3603 request: held.clone(),
3604 reason: "Move News digest to 19:00".into(),
3605 agent_name: "finance".into(),
3606 invocation_id: "inv".into(),
3607 run_id: None,
3608 acting: None,
3609 };
3610
3611 let request = service.submit_call(call).await.unwrap().unwrap();
3612 let mut expected = ApprovalRequest::new(request.id.clone(), scope, &held, policy)
3613 .with_summary("Move News digest to 19:00")
3614 .with_requester(SubjectRef::human("ana"));
3615 expected.created_at = request.created_at;
3616 assert_eq!(request, expected);
3617 assert_eq!(expected.origin, Some(verb_origin()));
3618 assert_eq!(service.get(&request.id).await.unwrap(), Some(request));
3619 }
3620
3621 #[test]
3622 fn with_origin_names_the_tools_publisher() {
3623 let call = ToolConfirmationRequest::new("pay", json!({}));
3624 let policy = ApprovalPolicy::new([ApproverSelector::human("ana")]);
3625 let request =
3626 ApprovalRequest::new("apr-1", ApprovalScope::new("a", "u", "s"), &call, policy);
3627 assert_eq!(request.origin, None);
3628 let named = request.clone().with_origin(verb_origin());
3629 assert_eq!(named, ApprovalRequest { origin: Some(verb_origin()), ..request });
3630 }
3631
3632 #[test]
3635 fn a_record_without_an_origin_reads_as_none() {
3636 let call = ToolConfirmationRequest::new("pay", json!({ "cents": 500 }));
3637 let policy = ApprovalPolicy::new([ApproverSelector::human("ana")]);
3638 let request =
3639 ApprovalRequest::new("apr-1", ApprovalScope::new("a", "u", "s"), &call, policy);
3640 let written = serde_json::to_value(&request).unwrap();
3641 assert_eq!(written.get("origin"), None);
3642 let read: ApprovalRequest = serde_json::from_value(written).unwrap();
3643 assert_eq!(read, request);
3644
3645 let named = request.with_origin(verb_origin());
3646 let written = serde_json::to_value(&named).unwrap();
3647 assert_eq!(
3648 written["origin"],
3649 json!({ "source": "verbs:adk-rust", "declarationDigest": verb_origin().declaration_digest })
3650 );
3651 assert_eq!(serde_json::from_value::<ApprovalRequest>(written).unwrap(), named);
3652 }
3653
3654 #[tokio::test]
3657 async fn a_host_routes_and_hears_a_service_built_without_a_router() {
3658 use crate::InMemoryApprovalStore;
3659
3660 #[derive(Debug, Default)]
3661 struct Heard(std::sync::Mutex<Vec<(ApprovalEventKind, ApprovalState)>>);
3662
3663 #[async_trait]
3664 impl ApprovalNotifier for Heard {
3665 async fn notify(&self, notification: &ApprovalNotification) -> Result<()> {
3666 let heard = (notification.kind, notification.request.state);
3667 self.0.lock().unwrap().push(heard);
3668 Ok(())
3669 }
3670 }
3671
3672 let call = |args: Value| ApprovalCall {
3673 scope: ApprovalScope::new("app", "ana", "s-1"),
3674 request: ToolConfirmationRequest::new("bash", args),
3675 reason: "needs approval".into(),
3676 agent_name: "agent".into(),
3677 invocation_id: "inv".into(),
3678 run_id: Some("run-1".into()),
3679 acting: None,
3680 };
3681 let operator = || -> Arc<dyn ApprovalRouter> {
3682 Arc::new(
3683 ApprovalPolicy::new([ApproverSelector::group("operator")]).allow_self_approval(),
3684 )
3685 };
3686
3687 let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()));
3688 assert_eq!(service.submit_call(call(json!({ "command": "ls" }))).await.unwrap(), None);
3689 let heard = Arc::new(Heard::default());
3690 assert!(service.route_unrouted(operator()));
3691 assert!(service.add_notifier(heard.clone()));
3692 let filed = service.submit_call(call(json!({ "command": "date" }))).await.unwrap();
3693 let filed = filed.expect("the host's router files the call");
3694 assert_eq!(filed.policy.approvers, vec![ApproverSelector::group("operator")]);
3695 let decision =
3696 ApprovalDecision::approve(SubjectRef::human("ana")).with_groups(["operator"]);
3697 service.decide(&filed.id, filed.version, decision).await.unwrap();
3698 assert_eq!(
3699 *heard.0.lock().unwrap(),
3700 vec![
3701 (ApprovalEventKind::Submitted, ApprovalState::Pending),
3702 (ApprovalEventKind::Decided, ApprovalState::Approved),
3703 (ApprovalEventKind::Resolved, ApprovalState::Approved),
3704 ]
3705 );
3706
3707 let declines = |_: &ApprovalCall| -> Option<ApprovalRoute> { None };
3710 let own =
3711 StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new())).with_router(declines);
3712 assert!(own.route_unrouted(operator()));
3713 assert_eq!(own.submit_call(call(json!({ "command": "ls" }))).await.unwrap(), None);
3714 }
3715}