1use std::future::Future;
2use std::sync::Arc;
3
4use adk_auth::AuditOutcome;
5use adk_core::audit_log::{
6 AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome, AuditTrail,
7};
8use adk_core::{AdkError, ErrorCategory, ErrorComponent, ErrorDetails, Result, SpendLedger};
9use async_trait::async_trait;
10use chrono::Utc;
11use serde_json::Value;
12
13use crate::auth::{
14 AuthenticatedPaymentRequest, PaymentAuditor, PaymentOperation as AuditPaymentOperation,
15};
16
17use crate::domain::{ProtocolDescriptor, TransactionRecord};
18use crate::guardrail::{
19 PaymentOperation, PaymentPolicyContext, PaymentPolicyDecision, PaymentPolicyFinding,
20 PaymentPolicyGuardrail, PaymentPolicySet, SpendLimitGuardrail, usd_micro_amount,
21};
22use crate::kernel::commands::{
23 CancelCheckoutCommand, CompleteCheckoutCommand, CreateCheckoutCommand, OrderUpdateCommand,
24 TransactionLookup, UpdateCheckoutCommand,
25};
26use crate::kernel::service::MerchantCheckoutService;
27
28pub const PAYMENT_POLICY_DENIED_CODE: &str = "payments.policy.denied";
30pub const PAYMENT_APPROVAL_REQUIRED_CODE: &str = "payments.policy.approval_required";
32pub const PAYMENT_APPROVAL_DENIED_CODE: &str = "payments.policy.approval_denied";
34pub const PAYMENT_APPROVAL_EDITED_CODE: &str = "payments.policy.approval_edited";
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum PaymentApproval {
43 Approved,
45 Denied,
47 Pending,
49}
50
51#[derive(Debug, Clone, PartialEq)]
67#[non_exhaustive]
68pub struct PaymentDecision {
69 pub approval: PaymentApproval,
71 pub edited_args: Option<Value>,
75 pub message: Option<String>,
78}
79
80impl PaymentDecision {
81 pub fn new(approval: PaymentApproval) -> Self {
83 Self { approval, edited_args: None, message: None }
84 }
85
86 #[must_use]
89 pub fn with_edited_args(mut self, args: Value) -> Self {
90 self.edited_args = Some(args);
91 self
92 }
93
94 #[must_use]
96 pub fn with_message(mut self, message: impl Into<String>) -> Self {
97 self.message = Some(message.into());
98 self
99 }
100}
101
102impl From<PaymentApproval> for PaymentDecision {
103 fn from(approval: PaymentApproval) -> Self {
104 Self::new(approval)
105 }
106}
107
108#[async_trait]
116pub trait PaymentApprover: Send + Sync {
117 async fn approve(
119 &self,
120 record: &TransactionRecord,
121 findings: &[PaymentPolicyFinding],
122 ) -> Result<PaymentApproval>;
123
124 async fn decide(
127 &self,
128 record: &TransactionRecord,
129 findings: &[PaymentPolicyFinding],
130 ) -> Result<PaymentDecision> {
131 Ok(PaymentDecision::new(self.approve(record, findings).await?))
132 }
133}
134
135#[derive(Clone, Default)]
146pub struct PaymentCaller {
147 org: Option<String>,
148 agent: Option<String>,
149 spend_ledger: Option<Arc<dyn SpendLedger>>,
150 approver: Option<Arc<dyn PaymentApprover>>,
151 audit: Option<(AuditTrail, AuditActor)>,
152}
153
154impl PaymentCaller {
155 #[must_use]
157 pub fn new() -> Self {
158 Self::default()
159 }
160
161 #[must_use]
163 pub fn with_org(mut self, org: impl Into<String>) -> Self {
164 self.org = Some(org.into());
165 self
166 }
167
168 #[must_use]
170 pub fn with_agent(mut self, agent: impl Into<String>) -> Self {
171 self.agent = Some(agent.into());
172 self
173 }
174
175 #[must_use]
177 pub fn with_spend_ledger(mut self, ledger: Arc<dyn SpendLedger>) -> Self {
178 self.spend_ledger = Some(ledger);
179 self
180 }
181
182 #[must_use]
185 pub fn with_approver(mut self, approver: Arc<dyn PaymentApprover>) -> Self {
186 self.approver = Some(approver);
187 self
188 }
189
190 #[must_use]
210 pub fn with_audit(mut self, trail: AuditTrail, actor: AuditActor) -> Self {
211 self.audit = Some((trail, actor));
212 self
213 }
214}
215
216const fn operation_action(operation: PaymentOperation) -> &'static str {
217 match operation {
218 PaymentOperation::CreateCheckout => "payment.create_checkout",
219 PaymentOperation::CompleteCheckout => "payment.complete_checkout",
220 PaymentOperation::ExecutePayment => "payment.execute_payment",
221 }
222}
223
224fn payment_draft(
227 trail: &AuditTrail,
228 actor: &AuditActor,
229 operation: PaymentOperation,
230 record: &TransactionRecord,
231 protocol: &ProtocolDescriptor,
232 findings: &[PaymentPolicyFinding],
233) -> AuditRecordDraft {
234 let cart = serde_json::to_value(&record.cart).unwrap_or(Value::Null);
235 let guardrails: Vec<Value> =
236 findings.iter().map(|finding| Value::String(finding.guardrail.clone())).collect();
237 let mut draft = AuditRecordDraft::new(AuditRecordKind::Payment, operation_action(operation))
238 .actor(actor.clone())
239 .args_digest(trail.digest(&cart))
240 .policy_ref("payment_policy")
241 .ext("transactionId", Value::String(record.transaction_id.as_str().to_string()))
242 .ext("merchantId", Value::String(record.merchant_of_record.merchant_id.clone()))
243 .ext("currency", Value::String(record.cart.total.currency.clone()))
244 .ext("amountMinor", Value::from(record.cart.total.amount_minor))
245 .ext("scale", Value::from(record.cart.total.scale))
246 .ext("protocol", Value::String(protocol.name.clone()));
247 if !guardrails.is_empty() {
248 draft = draft.ext("guardrails", Value::Array(guardrails));
249 }
250 if let Some(identity) = &record.session_identity {
251 draft = draft.ext("sessionId", Value::String(identity.session_id.to_string()));
252 }
253 draft
254}
255
256fn policy_error(
258 code: &'static str,
259 summary: &str,
260 findings: &[PaymentPolicyFinding],
261 extra: &[(&str, Value)],
262) -> AdkError {
263 let reasons: Vec<String> = findings
264 .iter()
265 .map(|finding| format!("{}: {}", finding.guardrail, finding.reason))
266 .collect();
267 let mut details = ErrorDetails::default();
268 details.metadata.insert("findings".to_string(), reasons.clone().into());
269 for (key, value) in extra {
270 details.metadata.insert((*key).to_string(), value.clone());
271 }
272 AdkError::new(
273 ErrorComponent::Guardrail,
274 ErrorCategory::Forbidden,
275 code,
276 format!("{summary}: {}", reasons.join("; ")),
277 )
278 .with_details(details)
279}
280
281pub(crate) fn with_spend_limit(policies: PaymentPolicySet) -> PaymentPolicySet {
284 if policies.contains(SpendLimitGuardrail::new().name()) {
285 policies
286 } else {
287 policies.with(SpendLimitGuardrail::when_configured())
288 }
289}
290
291pub(crate) enum Settlement {
293 Commit(Option<u64>),
295 #[cfg(feature = "ap2")]
297 Release,
298}
299
300#[derive(Clone)]
303pub(crate) struct PaymentGovernor {
304 policies: PaymentPolicySet,
305 spend_ledger: Option<Arc<dyn SpendLedger>>,
306 auditor: Option<PaymentAuditor>,
307}
308
309impl PaymentGovernor {
310 pub(crate) fn new(policies: PaymentPolicySet) -> Self {
311 Self { policies, spend_ledger: None, auditor: None }
312 }
313
314 pub(crate) fn policies(&self) -> &PaymentPolicySet {
315 &self.policies
316 }
317
318 #[cfg(feature = "ap2")]
319 pub(crate) fn set_policies(&mut self, policies: PaymentPolicySet) {
320 self.policies = policies;
321 }
322
323 pub(crate) fn set_spend_ledger(&mut self, ledger: Arc<dyn SpendLedger>) {
324 self.spend_ledger = Some(ledger);
325 }
326
327 pub(crate) fn set_auditor(&mut self, auditor: PaymentAuditor) {
328 self.auditor = Some(auditor);
329 }
330
331 pub(crate) async fn govern<T, F, Fut, S>(
337 &self,
338 operation: PaymentOperation,
339 record: &TransactionRecord,
340 protocol: &ProtocolDescriptor,
341 caller: &PaymentCaller,
342 run: F,
343 settle: S,
344 ) -> Result<T>
345 where
346 F: FnOnce() -> Fut,
347 Fut: Future<Output = Result<T>>,
348 S: FnOnce(&T) -> Settlement,
349 {
350 let mut context = PaymentPolicyContext::new(operation);
351 if let Some(ledger) = self.spend_ledger.clone().or_else(|| caller.spend_ledger.clone()) {
352 context = context.with_spend_ledger(ledger);
353 }
354 if let Some(org) = &caller.org {
355 context = context.with_org(org);
356 }
357 if let Some(agent) = &caller.agent {
358 context = context.with_agent(agent);
359 }
360
361 let caller_record = |decision: AuditDecision, findings: &[PaymentPolicyFinding]| {
362 caller.audit.as_ref().map(|(trail, actor)| {
363 let draft = payment_draft(trail, actor, operation, record, protocol, findings)
364 .decision(decision);
365 let draft = if matches!(decision, AuditDecision::Allowed | AuditDecision::Approved)
366 {
367 draft
368 } else {
369 draft.outcome(AuditRecordOutcome::NotRun)
370 };
371 (trail.clone(), draft)
372 })
373 };
374 let escalated = match self.policies.evaluate(record, protocol, &context).await {
375 PaymentPolicyDecision::Allow => false,
376 PaymentPolicyDecision::Deny { findings } => {
377 if let Some((trail, draft)) = caller_record(AuditDecision::Denied, &findings) {
379 let _ = trail.record(draft).await;
380 }
381 self.audit_refusal(operation, record, protocol, caller).await;
382 return Err(policy_error(
383 PAYMENT_POLICY_DENIED_CODE,
384 "payment refused by policy",
385 &findings,
386 &[],
387 ));
388 }
389 PaymentPolicyDecision::Escalate { findings } => {
390 let decided = match &caller.approver {
391 Some(approver) => approver.decide(record, &findings).await,
392 None => Ok(PaymentDecision::new(PaymentApproval::Pending)),
393 };
394 let (approval, edited, message) = match decided {
395 Ok(decision) => (Ok(decision.approval), decision.edited_args, decision.message),
396 Err(error) => (Err(error), None, None),
397 };
398 let approver_exts = |draft: AuditRecordDraft, trail: &AuditTrail| {
400 let draft = match &message {
401 Some(message) => {
402 draft.ext("approverMessage", Value::String(message.clone()))
403 }
404 None => draft,
405 };
406 match &edited {
407 Some(edited) => {
408 draft.ext("editedArgsDigest", Value::String(trail.digest(edited)))
409 }
410 None => draft,
411 }
412 };
413 let message_ext = || {
414 message
415 .as_ref()
416 .map(|message| ("approverMessage", Value::String(message.clone())))
417 .into_iter()
418 .collect::<Vec<_>>()
419 };
420 let refused_as = match (&approval, &edited) {
421 (Ok(PaymentApproval::Denied), _) => AuditDecision::Rejected,
422 (Ok(PaymentApproval::Pending), _) => AuditDecision::ApprovalRequired,
423 (Ok(PaymentApproval::Approved), Some(_)) => AuditDecision::Approved,
425 (Ok(PaymentApproval::Approved), None) | (Err(_), _) => AuditDecision::Denied,
426 };
427 let refusal = match (approval, &edited) {
428 (Ok(PaymentApproval::Approved), None) => None,
429 (Ok(PaymentApproval::Approved), Some(edited)) => {
430 let mut extra = message_ext();
431 extra.push(("editedArgs", edited.clone()));
432 Some(policy_error(
433 PAYMENT_APPROVAL_EDITED_CODE,
434 "payment approved with edited arguments; re-issue it with them",
435 &findings,
436 &extra,
437 ))
438 }
439 (Ok(PaymentApproval::Denied), _) => {
440 let summary = match &message {
441 Some(message) => format!("payment approval was denied ({message})"),
442 None => "payment approval was denied".to_string(),
443 };
444 Some(policy_error(
445 PAYMENT_APPROVAL_DENIED_CODE,
446 &summary,
447 &findings,
448 &message_ext(),
449 ))
450 }
451 (Ok(PaymentApproval::Pending), _) => Some(policy_error(
452 PAYMENT_APPROVAL_REQUIRED_CODE,
453 "payment requires approval",
454 &findings,
455 &[],
456 )),
457 (Err(error), _) => Some(error),
458 };
459 if let Some(error) = refusal {
460 context.release_holds().await;
461 if let Some((trail, draft)) = caller_record(refused_as, &findings) {
462 let draft =
465 approver_exts(draft, &trail).outcome(AuditRecordOutcome::NotRun);
466 let _ = trail.record(draft).await;
467 }
468 if error.code != PAYMENT_APPROVAL_EDITED_CODE {
471 self.audit_refusal(operation, record, protocol, caller).await;
472 }
473 return Err(error);
474 }
475 if let Some((trail, draft)) = caller_record(AuditDecision::Approved, &findings)
476 && let Err(error) = trail.record(approver_exts(draft, &trail)).await
477 {
478 context.release_holds().await;
479 return Err(error);
480 }
481 true
482 }
483 };
484 if !escalated
485 && let Some((trail, draft)) = caller_record(AuditDecision::Allowed, &[])
486 && let Err(error) = trail.record(draft).await
487 {
488 context.release_holds().await;
489 return Err(error);
490 }
491
492 if let Some(auditor) = &self.auditor {
494 let request = audit_request(record, caller);
495 if let Err(error) = auditor
496 .record_operation(
497 &request,
498 record,
499 protocol,
500 audit_operation(operation),
501 AuditOutcome::Allowed,
502 escalated,
503 )
504 .await
505 {
506 context.release_holds().await;
507 return Err(error.into());
508 }
509 }
510
511 let result = run().await;
512 if let Some((trail, actor)) = &caller.audit {
514 let outcome = if result.is_ok() {
515 AuditRecordOutcome::Succeeded
516 } else {
517 AuditRecordOutcome::Failed
518 };
519 let draft =
520 payment_draft(trail, actor, operation, record, protocol, &[]).outcome(outcome);
521 if let Err(error) = trail.recorder().record(draft).await {
522 tracing::error!(error = %error, "payment outcome could not be audited");
523 }
524 }
525 match result {
526 Ok(result) => {
527 match settle(&result) {
528 Settlement::Commit(actual) => context.commit_holds(actual).await,
529 #[cfg(feature = "ap2")]
530 Settlement::Release => context.release_holds().await,
531 }
532 Ok(result)
533 }
534 Err(error) => {
535 context.release_holds().await;
536 Err(error)
537 }
538 }
539 }
540
541 async fn audit_refusal(
544 &self,
545 operation: PaymentOperation,
546 record: &TransactionRecord,
547 protocol: &ProtocolDescriptor,
548 caller: &PaymentCaller,
549 ) {
550 let Some(auditor) = &self.auditor else {
551 return;
552 };
553 let request = audit_request(record, caller);
554 if let Err(error) = auditor
555 .record_operation(
556 &request,
557 record,
558 protocol,
559 audit_operation(operation),
560 AuditOutcome::Denied,
561 false,
562 )
563 .await
564 {
565 tracing::warn!(error = %error, "failed to record a refused payment");
566 }
567 }
568}
569
570const fn audit_operation(operation: PaymentOperation) -> AuditPaymentOperation {
571 match operation {
572 PaymentOperation::CreateCheckout => AuditPaymentOperation::CreateCheckout,
573 PaymentOperation::CompleteCheckout => AuditPaymentOperation::CompleteCheckout,
574 PaymentOperation::ExecutePayment => AuditPaymentOperation::ExecutePayment,
575 }
576}
577
578fn audit_request(
580 record: &TransactionRecord,
581 caller: &PaymentCaller,
582) -> AuthenticatedPaymentRequest {
583 let user = record
584 .session_identity
585 .as_ref()
586 .map(|identity| identity.user_id.to_string())
587 .or_else(|| caller.agent.clone())
588 .unwrap_or_else(|| record.initiated_by.actor_id.clone());
589 let mut request = AuthenticatedPaymentRequest::new(user);
590 if let Some(identity) = &record.session_identity {
591 request = request.with_session_id(identity.session_id.to_string());
592 }
593 if let Some(org) = &caller.org {
594 request = request.with_metadata("org", Value::String(org.clone()));
595 }
596 if let Some(agent) = &caller.agent {
597 request = request.with_metadata("agent", Value::String(agent.clone()));
598 }
599 request
600}
601
602pub struct GovernedCheckoutService {
637 inner: Arc<dyn MerchantCheckoutService>,
638 governor: PaymentGovernor,
639}
640
641impl GovernedCheckoutService {
642 #[must_use]
644 pub fn new(inner: Arc<dyn MerchantCheckoutService>, policies: PaymentPolicySet) -> Self {
645 Self { inner, governor: PaymentGovernor::new(policies) }
646 }
647
648 #[must_use]
650 pub fn with_spend_ledger(mut self, ledger: Arc<dyn SpendLedger>) -> Self {
651 self.governor.set_spend_ledger(ledger);
652 self
653 }
654
655 #[must_use]
669 pub fn with_auditor(mut self, auditor: PaymentAuditor) -> Self {
670 self.governor.set_auditor(auditor);
671 self
672 }
673
674 #[must_use]
676 pub fn policies(&self) -> &PaymentPolicySet {
677 self.governor.policies()
678 }
679
680 pub async fn create_checkout_as(
689 &self,
690 command: CreateCheckoutCommand,
691 caller: &PaymentCaller,
692 ) -> Result<TransactionRecord> {
693 let context = &command.context;
694 let mut record = TransactionRecord::new(
695 context.transaction_id.clone(),
696 context.actor.clone(),
697 context.merchant_of_record.clone(),
698 context.mode,
699 command.cart.clone(),
700 Utc::now(),
701 );
702 record.session_identity = context.session_identity.clone();
703 record.payment_processor = context.payment_processor.clone();
704 let protocol = context.protocol.clone();
705 self.governor
706 .govern(
707 PaymentOperation::CreateCheckout,
708 &record,
709 &protocol,
710 caller,
711 || self.inner.create_checkout(command),
712 checkout_settlement,
713 )
714 .await
715 }
716
717 pub async fn complete_checkout_as(
726 &self,
727 command: CompleteCheckoutCommand,
728 caller: &PaymentCaller,
729 ) -> Result<TransactionRecord> {
730 let lookup = TransactionLookup {
731 transaction_id: command.context.transaction_id.clone(),
732 session_identity: command.context.session_identity.clone(),
733 };
734 let Some(record) = self.inner.get_checkout(lookup).await? else {
735 return Err(AdkError::new(
736 ErrorComponent::Guardrail,
737 ErrorCategory::NotFound,
738 "payments.policy.checkout_not_found",
739 format!(
740 "checkout `{}` was not found, so its payment policies cannot be evaluated",
741 command.context.transaction_id.as_str()
742 ),
743 ));
744 };
745 let protocol = command.context.protocol.clone();
746 self.governor
747 .govern(
748 PaymentOperation::CompleteCheckout,
749 &record,
750 &protocol,
751 caller,
752 || self.inner.complete_checkout(command),
753 checkout_settlement,
754 )
755 .await
756 }
757}
758
759pub(crate) fn checkout_settlement(record: &TransactionRecord) -> Settlement {
761 Settlement::Commit(usd_micro_amount(&record.cart.total).ok())
762}
763
764pub(crate) fn caller_from(context: &crate::kernel::commands::CommerceContext) -> PaymentCaller {
766 let mut caller = PaymentCaller::new().with_agent(&context.actor.actor_id);
767 if let Some(identity) = &context.session_identity {
768 caller = caller.with_org(identity.app_name.as_str());
769 }
770 caller
771}
772
773#[async_trait]
774impl MerchantCheckoutService for GovernedCheckoutService {
775 async fn create_checkout(&self, command: CreateCheckoutCommand) -> Result<TransactionRecord> {
776 let caller = caller_from(&command.context);
777 self.create_checkout_as(command, &caller).await
778 }
779
780 async fn update_checkout(&self, command: UpdateCheckoutCommand) -> Result<TransactionRecord> {
781 self.inner.update_checkout(command).await
782 }
783
784 async fn get_checkout(&self, lookup: TransactionLookup) -> Result<Option<TransactionRecord>> {
785 self.inner.get_checkout(lookup).await
786 }
787
788 async fn complete_checkout(
789 &self,
790 command: CompleteCheckoutCommand,
791 ) -> Result<TransactionRecord> {
792 let caller = caller_from(&command.context);
793 self.complete_checkout_as(command, &caller).await
794 }
795
796 async fn cancel_checkout(&self, command: CancelCheckoutCommand) -> Result<TransactionRecord> {
797 self.inner.cancel_checkout(command).await
798 }
799
800 async fn apply_order_update(&self, command: OrderUpdateCommand) -> Result<TransactionRecord> {
801 self.inner.apply_order_update(command).await
802 }
803}