Skip to main content

adk_payments/kernel/
governed.rs

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
28/// Error code returned when a payment policy denies a checkout.
29pub const PAYMENT_POLICY_DENIED_CODE: &str = "payments.policy.denied";
30/// Error code returned when a payment policy escalated a checkout and no approval arrived.
31pub const PAYMENT_APPROVAL_REQUIRED_CODE: &str = "payments.policy.approval_required";
32/// Error code returned when an escalated checkout was explicitly refused.
33pub const PAYMENT_APPROVAL_DENIED_CODE: &str = "payments.policy.approval_denied";
34/// Error code returned when an approver approved an escalated operation with substituted
35/// arguments: the operation did not run as proposed, and the error's `editedArgs` detail
36/// carries the arguments to re-issue it with. The payment tools re-issue the call
37/// themselves (spec 3.1 §10 C3).
38pub const PAYMENT_APPROVAL_EDITED_CODE: &str = "payments.policy.approval_edited";
39
40/// Outcome of asking for approval of an escalated payment.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum PaymentApproval {
43    /// The payment may proceed.
44    Approved,
45    /// The payment must not proceed.
46    Denied,
47    /// No decision is available yet; the payment does not proceed now.
48    Pending,
49}
50
51/// What an approver decided about an escalated payment: the approval, the arguments it
52/// substituted for the call's own, and what it said (spec 3.1 §10 C3).
53///
54/// # Example
55///
56/// ```
57/// use adk_payments::kernel::{PaymentApproval, PaymentDecision};
58/// use serde_json::json;
59///
60/// let decision = PaymentDecision::new(PaymentApproval::Approved)
61///     .with_edited_args(json!({ "amount": 40 }))
62///     .with_message("approved at 40");
63/// assert_eq!(decision.approval, PaymentApproval::Approved);
64/// assert_eq!(decision.message.as_deref(), Some("approved at 40"));
65/// ```
66#[derive(Debug, Clone, PartialEq)]
67#[non_exhaustive]
68pub struct PaymentDecision {
69    /// Whether the payment may proceed.
70    pub approval: PaymentApproval,
71    /// Arguments the approver substituted for the call's own. An approved payment with
72    /// edited arguments is not made as proposed: the governed service returns
73    /// [`PAYMENT_APPROVAL_EDITED_CODE`] and the caller re-issues it with these arguments.
74    pub edited_args: Option<Value>,
75    /// What the approver said: a reason for a refusal, or a note on an approval. It is
76    /// recorded with the decision and reported with a refusal.
77    pub message: Option<String>,
78}
79
80impl PaymentDecision {
81    /// A decision with no edited arguments and no message.
82    pub fn new(approval: PaymentApproval) -> Self {
83        Self { approval, edited_args: None, message: None }
84    }
85
86    /// Sets the arguments the approver substituted. See
87    /// [`edited_args`](Self::edited_args).
88    #[must_use]
89    pub fn with_edited_args(mut self, args: Value) -> Self {
90        self.edited_args = Some(args);
91        self
92    }
93
94    /// Sets what the approver said. See [`message`](Self::message).
95    #[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/// Decides payments that a policy escalated.
109///
110/// The payment tools supply an approver that decides through
111/// [`adk_core::confirm_tool_call`] — call-ID decisions, fingerprint approvals, the
112/// approval store, and the confirmation handler — so an escalation reaches the same
113/// approval flow as any tool that requires confirmation, and a held escalation resumes
114/// once an approver decides it.
115#[async_trait]
116pub trait PaymentApprover: Send + Sync {
117    /// Approves, refuses, or defers `record`, which the policies escalated with `findings`.
118    async fn approve(
119        &self,
120        record: &TransactionRecord,
121        findings: &[PaymentPolicyFinding],
122    ) -> Result<PaymentApproval>;
123
124    /// Decides `record` as [`approve`](Self::approve) does, and may substitute arguments
125    /// or add a message (spec 3.1 §10 C3). The default wraps `approve`.
126    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/// Who is paying, and how escalations are decided, for one governed operation.
136///
137/// # Example
138///
139/// ```
140/// use adk_payments::kernel::PaymentCaller;
141///
142/// let caller = PaymentCaller::new().with_org("store").with_agent("shopper");
143/// # let _ = caller;
144/// ```
145#[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    /// Creates a caller with no attribution, no ledger, and no approver.
156    #[must_use]
157    pub fn new() -> Self {
158        Self::default()
159    }
160
161    /// Attributes spend to `org`.
162    #[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    /// Attributes spend to `agent`.
169    #[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    /// Uses `ledger` for this call when the service has no ledger of its own.
176    #[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    /// Asks `approver` about escalated payments. Without one, an escalation is refused
183    /// with [`PAYMENT_APPROVAL_REQUIRED_CODE`].
184    #[must_use]
185    pub fn with_approver(mut self, approver: Arc<dyn PaymentApprover>) -> Self {
186        self.approver = Some(approver);
187        self
188    }
189
190    /// Records every governed decision for this caller in `trail`, naming `actor` as
191    /// acting, ahead of and alongside any [`PaymentAuditor`] of the service.
192    ///
193    /// An allowed payment whose record cannot be written does not run when the trail is
194    /// in [`AuditFailureMode::Block`](adk_core::audit_log::AuditFailureMode::Block). The
195    /// payment tools set this from the run's `RunConfig::audit`.
196    ///
197    /// # Example
198    ///
199    /// ```
200    /// use std::sync::Arc;
201    /// use adk_core::audit_log::{AuditActor, AuditTrail, InMemoryAuditRecorder};
202    /// use adk_payments::kernel::PaymentCaller;
203    ///
204    /// let trail = AuditTrail::new(Arc::new(InMemoryAuditRecorder::new()));
205    /// let actor = AuditActor::for_invocation("store", "shopper", "alice", "inv-1");
206    /// let caller = PaymentCaller::new().with_audit(trail, actor);
207    /// # let _ = caller;
208    /// ```
209    #[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
224/// The caller's audit record for `operation` on `record`: the cart's digest, the
225/// merchant, the total, and the guardrails that spoke. Cart lines stay out of the record.
226fn 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
256/// A policy refusal naming the guardrails that spoke, with `extra` metadata beside them.
257fn 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
281/// Adds [`SpendLimitGuardrail::when_configured`] unless `policies` already limit spend,
282/// so a ledger on the caller or the service caps payments without further setup.
283pub(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
291/// How a governed operation's spend holds settle once it returns.
292pub(crate) enum Settlement {
293    /// Commit every hold, at this amount when known.
294    Commit(Option<u64>),
295    /// Release every hold: no money moved.
296    #[cfg(feature = "ap2")]
297    Release,
298}
299
300/// Payment policies, spend ledger, and audit trail shared by every governed payment path:
301/// [`GovernedCheckoutService`] for checkouts and the AP2 adapter for payment mandates.
302#[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    /// Runs `run` only after the policies allow `operation` on `record` for `caller` and,
332    /// when an auditor is configured, the decision is recorded.
333    ///
334    /// Spend holds the policies took are settled by `settle` when `run` succeeds and
335    /// released when it fails or never starts.
336    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                // The payment is refused either way, so a failed write is logged by the trail.
378                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                // What the approver said and substituted travels with the decision's record.
399                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                    // Approved, but not as proposed: the caller re-issues the operation.
424                    (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                        // An approval with edited arguments is recorded as approved, and as
463                        // not run, since the operation as proposed never runs.
464                        let draft =
465                            approver_exts(draft, &trail).outcome(AuditRecordOutcome::NotRun);
466                        let _ = trail.record(draft).await;
467                    }
468                    // An approval with edited arguments refuses nothing: the operation runs
469                    // when the caller re-issues it, and that run is audited.
470                    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        // An unrecorded decision must not move money: the audit write precedes the call.
493        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        // The operation has already happened, so the outcome record cannot refuse it.
513        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    /// Records a refused payment. The payment is already refused, so a failed write is
542    /// logged rather than returned.
543    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
578/// The audited identity: the session's user when known, else the paying agent.
579fn 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
602/// A [`MerchantCheckoutService`] that evaluates a [`PaymentPolicySet`] before every
603/// checkout creation and completion.
604///
605/// | Policy outcome | Effect |
606/// |----------------|--------|
607/// | Allow | The operation runs; spend holds are committed on success and released on failure |
608/// | Escalate | The caller's [`PaymentApprover`] decides; without one the call fails with [`PAYMENT_APPROVAL_REQUIRED_CODE`] |
609/// | Deny | The call fails with [`PAYMENT_POLICY_DENIED_CODE`]; the backend is not reached |
610///
611/// Completion is evaluated against the stored checkout, so a cart changed after creation
612/// is judged as it will be paid. A checkout the backend cannot return is refused.
613/// Updates, lookups, cancellations, and order updates pass through. With an auditor
614/// ([`with_auditor`](Self::with_auditor)), every allowed operation is recorded before the
615/// backend is reached, and an operation whose record cannot be written is refused.
616///
617/// Wrap a backend with this service before handing it to the ACP adapter so protocol
618/// traffic is governed too; the payment tools wrap theirs automatically, and the AP2
619/// adapter governs its own checkouts and payment mandates.
620///
621/// # Example
622///
623/// ```rust,ignore
624/// use adk_payments::guardrail::{AmountThresholdGuardrail, MerchantAllowlistGuardrail, PaymentPolicySet};
625/// use adk_payments::kernel::GovernedCheckoutService;
626/// use std::sync::Arc;
627///
628/// let governed = GovernedCheckoutService::new(
629///     backend,
630///     PaymentPolicySet::new()
631///         .with(AmountThresholdGuardrail::new(Some(5_000), Some(10_000)).with_currency("USD", 2))
632///         .with(MerchantAllowlistGuardrail::new(["merchant-1"])),
633/// );
634/// let service: Arc<dyn adk_payments::kernel::MerchantCheckoutService> = Arc::new(governed);
635/// ```
636pub struct GovernedCheckoutService {
637    inner: Arc<dyn MerchantCheckoutService>,
638    governor: PaymentGovernor,
639}
640
641impl GovernedCheckoutService {
642    /// Governs `inner` with `policies`.
643    #[must_use]
644    pub fn new(inner: Arc<dyn MerchantCheckoutService>, policies: PaymentPolicySet) -> Self {
645        Self { inner, governor: PaymentGovernor::new(policies) }
646    }
647
648    /// Gives policies `ledger`, ahead of any ledger the caller supplies.
649    #[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    /// Records every governed decision with `auditor`, refusing an operation whose
656    /// allowed decision cannot be recorded.
657    ///
658    /// # Example
659    ///
660    /// ```rust,ignore
661    /// use adk_auth::FileAuditSink;
662    /// use adk_payments::auth::PaymentAuditor;
663    ///
664    /// let governed = governed.with_auditor(PaymentAuditor::new(Arc::new(
665    ///     FileAuditSink::new("payments-audit.jsonl")?,
666    /// )));
667    /// ```
668    #[must_use]
669    pub fn with_auditor(mut self, auditor: PaymentAuditor) -> Self {
670        self.governor.set_auditor(auditor);
671        self
672    }
673
674    /// Returns the policies this service enforces.
675    #[must_use]
676    pub fn policies(&self) -> &PaymentPolicySet {
677        self.governor.policies()
678    }
679
680    /// Creates a checkout after the policies allow it for `caller`.
681    ///
682    /// # Errors
683    ///
684    /// Returns [`PAYMENT_POLICY_DENIED_CODE`], [`PAYMENT_APPROVAL_REQUIRED_CODE`], or
685    /// [`PAYMENT_APPROVAL_DENIED_CODE`] when the policies stop the checkout,
686    /// `payments.auth.audit_failed` when the decision cannot be recorded, or the
687    /// backend's error.
688    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    /// Completes a checkout after the policies allow the stored checkout for `caller`.
718    ///
719    /// # Errors
720    ///
721    /// Returns `payments.policy.checkout_not_found` when the backend has no such
722    /// checkout, a policy error code when the policies stop the payment,
723    /// `payments.auth.audit_failed` when the decision cannot be recorded, or the
724    /// backend's error.
725    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
759/// A checkout that returned commits its holds at the returned total.
760pub(crate) fn checkout_settlement(record: &TransactionRecord) -> Settlement {
761    Settlement::Commit(usd_micro_amount(&record.cart.total).ok())
762}
763
764/// Builds the caller a protocol adapter supplies: the session's app and the acting actor.
765pub(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}