1use std::sync::Arc;
2
3use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, SpendLedger};
4use chrono::{DateTime, Utc};
5use serde::de::DeserializeOwned;
6use serde_json::json;
7
8use crate::auth::PaymentAuditor;
9use crate::domain::{
10 CommerceMode, EvidenceReference, InterventionKind, InterventionState, InterventionStatus,
11 ProtocolEnvelopeDigest, ProtocolExtensions, ProtocolReference, TransactionRecord,
12 TransactionState,
13};
14#[cfg(doc)]
15use crate::guardrail::SpendLimitGuardrail;
16use crate::guardrail::{PaymentOperation, PaymentPolicySet, usd_micro_amount};
17use crate::kernel::governed::{
18 PaymentGovernor, Settlement, caller_from, checkout_settlement, with_spend_limit,
19};
20use crate::kernel::{
21 BeginInterventionCommand, CommerceContext, CreateCheckoutCommand, EvidenceLookup,
22 EvidenceStore, InterventionService, MerchantCheckoutService, PaymentCaller,
23 PaymentExecutionOutcome, PaymentExecutionResult, PaymentExecutionService, ProtocolCorrelator,
24 ProtocolRefKind, StoreEvidenceCommand, StoredEvidence, TransactionLookup, TransactionStore,
25 UpdateCheckoutCommand,
26};
27use crate::protocol::ap2::error::Ap2Error;
28use crate::protocol::ap2::ledger::{InMemoryPaymentMandateLedger, PaymentMandateLedger};
29use crate::protocol::ap2::mapper::{
30 ap2_descriptor, cart_amount_scale, cart_from_cart_mandate, execute_payment_command,
31 fulfillment_from_cart_mandate, intent_create_checkout_command, merge_extensions,
32 payment_amount, sync_payment_outcome_command, update_record_extensions,
33 update_record_state_from_receipt,
34};
35use crate::protocol::ap2::types::{
36 AuthorizationArtifact, CartMandate, IntentMandate, PaymentMandate, PaymentReceipt,
37 PaymentStatusEnvelope,
38};
39use crate::protocol::ap2::verification::{
40 MerchantAuthorizationVerifier, RequireMerchantAuthorization, RequireUserAuthorization,
41 UserAuthorizationVerifier, VERIFIED_MERCHANT_NAME_CLAIM, VerifiedAuthorization,
42};
43
44const EXECUTED_PAYMENT_MANDATE_REF_KIND: &str = "ap2_executed_payment_mandate_id";
47
48const IDEMPOTENCY_KEY_FIELD: &str = "idempotency_key";
50
51fn context_idempotency_key(context: &CommerceContext) -> Option<String> {
53 context.extensions.as_slice().iter().find_map(|envelope| {
54 envelope
55 .fields
56 .get(IDEMPOTENCY_KEY_FIELD)
57 .and_then(|value| value.as_str())
58 .map(str::to_string)
59 })
60}
61
62struct StoredArtifactSet {
63 envelope: crate::domain::ProtocolExtensionEnvelope,
64 evidence: Vec<StoredEvidence>,
65}
66
67#[derive(Default)]
68struct ProtocolRefUpdate {
69 intent_ref: Option<String>,
70 cart_ref: Option<String>,
71 payment_ref: Option<String>,
72 executed_payment_ref: Option<String>,
73 receipt_ref: Option<String>,
74}
75
76pub struct Ap2Adapter {
102 checkout_service: Arc<dyn MerchantCheckoutService>,
103 payment_service: Arc<dyn PaymentExecutionService>,
104 transaction_store: Arc<dyn TransactionStore>,
105 evidence_store: Arc<dyn EvidenceStore>,
106 merchant_verifier: Option<Arc<dyn MerchantAuthorizationVerifier>>,
107 user_verifier: Option<Arc<dyn UserAuthorizationVerifier>>,
108 allow_unverified_authorizations: bool,
109 payment_mandate_ledger: Arc<dyn PaymentMandateLedger>,
110 intervention_service: Option<Arc<dyn InterventionService>>,
111 governor: PaymentGovernor,
112}
113
114impl Ap2Adapter {
115 #[must_use]
127 pub fn new(
128 checkout_service: Arc<dyn MerchantCheckoutService>,
129 payment_service: Arc<dyn PaymentExecutionService>,
130 transaction_store: Arc<dyn TransactionStore>,
131 evidence_store: Arc<dyn EvidenceStore>,
132 ) -> Self {
133 Self {
134 checkout_service,
135 payment_service,
136 transaction_store,
137 evidence_store,
138 merchant_verifier: None,
139 user_verifier: None,
140 allow_unverified_authorizations: false,
141 payment_mandate_ledger: Arc::new(InMemoryPaymentMandateLedger::new()),
142 intervention_service: None,
143 governor: PaymentGovernor::new(with_spend_limit(PaymentPolicySet::new())),
144 }
145 }
146
147 #[must_use]
165 pub fn with_payment_policies(mut self, policies: PaymentPolicySet) -> Self {
166 self.governor.set_policies(with_spend_limit(policies));
167 self
168 }
169
170 #[must_use]
172 pub fn with_spend_ledger(mut self, ledger: Arc<dyn SpendLedger>) -> Self {
173 self.governor.set_spend_ledger(ledger);
174 self
175 }
176
177 #[must_use]
180 pub fn with_payment_auditor(mut self, auditor: PaymentAuditor) -> Self {
181 self.governor.set_auditor(auditor);
182 self
183 }
184
185 #[must_use]
187 pub fn with_merchant_authorization_verifier(
188 mut self,
189 verifier: Arc<dyn MerchantAuthorizationVerifier>,
190 ) -> Self {
191 self.merchant_verifier = Some(verifier);
192 self
193 }
194
195 #[must_use]
197 pub fn with_user_authorization_verifier(
198 mut self,
199 verifier: Arc<dyn UserAuthorizationVerifier>,
200 ) -> Self {
201 self.user_verifier = Some(verifier);
202 self
203 }
204
205 #[must_use]
213 pub fn allow_unverified_authorizations(mut self) -> Self {
214 tracing::warn!(
215 merchant_verifier.configured = self.merchant_verifier.is_some(),
216 user_verifier.configured = self.user_verifier.is_some(),
217 "ap2 adapter accepts unverified authorization artifacts; this is unsafe outside local development"
218 );
219 self.allow_unverified_authorizations = true;
220 self
221 }
222
223 #[must_use]
228 pub fn with_payment_mandate_ledger(mut self, ledger: Arc<dyn PaymentMandateLedger>) -> Self {
229 self.payment_mandate_ledger = ledger;
230 self
231 }
232
233 #[must_use]
235 pub fn with_intervention_service(
236 mut self,
237 intervention_service: Arc<dyn InterventionService>,
238 ) -> Self {
239 self.intervention_service = Some(intervention_service);
240 self
241 }
242
243 pub async fn submit_intent_mandate(
251 &self,
252 context: CommerceContext,
253 intent_mandate: IntentMandate,
254 authorization_artifact: Option<AuthorizationArtifact>,
255 ) -> Result<TransactionRecord> {
256 self.validate_intent_mandate(&context, &intent_mandate, authorization_artifact.as_ref())?;
257 let verification = if let Some(artifact) = authorization_artifact.as_ref() {
258 Some(self.verify_intent_authorization(&intent_mandate, artifact).await?)
259 } else {
260 None
261 };
262
263 let context = self.normalize_context(context, ProtocolExtensions::default());
264 let artifacts = self
265 .store_intent_artifacts(
266 &context,
267 &intent_mandate,
268 authorization_artifact.as_ref(),
269 verification.as_ref(),
270 )
271 .await?;
272 let intent_ref = artifacts.evidence.first().and_then(|stored| {
273 stored
274 .evidence_ref
275 .digest
276 .clone()
277 .or_else(|| Some(stored.evidence_ref.evidence_id.clone()))
278 });
279 let command = intent_create_checkout_command(&intent_mandate, context.clone());
280 let record = self.checkout_service.create_checkout(command).await?;
281
282 self.finalize_record(
283 &context,
284 record,
285 artifacts,
286 ProtocolRefUpdate { intent_ref, ..ProtocolRefUpdate::default() },
287 )
288 .await
289 }
290
291 pub async fn submit_cart_mandate(
300 &self,
301 context: CommerceContext,
302 cart_mandate: CartMandate,
303 ) -> Result<TransactionRecord> {
304 self.validate_not_expired("cart_expiry", &cart_mandate.contents.cart_expiry)?;
305 let context = self.normalize_context(context, ProtocolExtensions::default());
306
307 let merchant_authorization = cart_mandate
308 .merchant_authorization
309 .clone()
310 .map(|value| AuthorizationArtifact::new("merchant_authorization", value, "text/plain"))
311 .ok_or_else(|| {
312 AdkError::from(Ap2Error::MissingMerchantAuthorization {
313 cart_id: cart_mandate.contents.id.clone(),
314 })
315 })?;
316 let verification =
317 self.verify_cart_authorization(&cart_mandate, &merchant_authorization).await?;
318 if let Some(verified) =
319 verification.claims.get(VERIFIED_MERCHANT_NAME_CLAIM).and_then(|name| name.as_str())
320 && !verified.eq_ignore_ascii_case(&cart_mandate.contents.merchant_name)
321 {
322 return Err(Ap2Error::MerchantIdentityMismatch {
323 claimed: cart_mandate.contents.merchant_name.clone(),
324 verified: verified.to_string(),
325 }
326 .into());
327 }
328
329 let existing = self.lookup(&context).await?;
330 if let Some(record) = existing.as_ref() {
331 self.validate_intent_constraints(&context, record, &cart_mandate).await?;
332 }
333 let cart = cart_from_cart_mandate(&cart_mandate)?;
334 let fulfillment = fulfillment_from_cart_mandate(&cart_mandate)?;
335
336 let artifacts = self
337 .store_cart_artifacts(&context, &cart_mandate, &merchant_authorization, &verification)
338 .await?;
339
340 let record = if existing.is_some() {
341 self.checkout_service
342 .update_checkout(UpdateCheckoutCommand {
343 context: context.clone(),
344 cart: Some(cart),
345 fulfillment,
346 })
347 .await?
348 } else {
349 let mut proposed = TransactionRecord::new(
350 context.transaction_id.clone(),
351 context.actor.clone(),
352 context.merchant_of_record.clone(),
353 context.mode,
354 cart.clone(),
355 Utc::now(),
356 );
357 proposed.session_identity = context.session_identity.clone();
358 proposed.payment_processor = context.payment_processor.clone();
359 let command = CreateCheckoutCommand { context: context.clone(), cart, fulfillment };
360 self.governor
361 .govern(
362 PaymentOperation::CreateCheckout,
363 &proposed,
364 &context.protocol,
365 &caller_from(&context),
366 || self.checkout_service.create_checkout(command),
367 checkout_settlement,
368 )
369 .await?
370 };
371
372 self.finalize_record(
373 &context,
374 record,
375 artifacts,
376 ProtocolRefUpdate {
377 cart_ref: Some(cart_mandate.contents.id.clone()),
378 ..ProtocolRefUpdate::default()
379 },
380 )
381 .await
382 }
383
384 pub async fn submit_payment_mandate(
393 &self,
394 context: CommerceContext,
395 payment_mandate: PaymentMandate,
396 ) -> Result<PaymentExecutionResult> {
397 let caller = caller_from(&context);
398 self.submit_payment_mandate_as(context, payment_mandate, &caller).await
399 }
400
401 pub async fn submit_payment_mandate_as(
429 &self,
430 context: CommerceContext,
431 payment_mandate: PaymentMandate,
432 caller: &PaymentCaller,
433 ) -> Result<PaymentExecutionResult> {
434 let mut context = self.normalize_context(context, ProtocolExtensions::default());
435 let existing = self.lookup(&context).await?.ok_or_else(|| {
436 AdkError::from(Ap2Error::TransactionNotFound {
437 transaction_id: context.transaction_id.as_str().to_string(),
438 })
439 })?;
440 self.ensure_payment_mandate_admissible(&existing, &payment_mandate)?;
441 let cart_mandate: CartMandate =
442 self.load_latest_json(&context, &existing, "cart_mandate").await?.ok_or_else(|| {
443 AdkError::from(Ap2Error::TransactionNotFound {
444 transaction_id: context.transaction_id.as_str().to_string(),
445 })
446 })?;
447 self.validate_payment_mandate_against_cart(&payment_mandate, &cart_mandate)?;
448 let amount_scale = cart_amount_scale(&cart_mandate)?;
449 if context.merchant_of_record.merchant_id.is_empty() {
450 context.merchant_of_record = existing.merchant_of_record.clone();
451 }
452
453 let authorization = match payment_mandate.user_authorization.clone() {
454 Some(user_authorization) => {
455 let artifact = AuthorizationArtifact::new(
456 "user_authorization",
457 user_authorization,
458 "text/plain",
459 );
460 let verification =
461 self.verify_payment_authorization(&payment_mandate, &artifact).await?;
462 Some((artifact, verification))
463 }
464 None => {
465 if !self.evaluate_autonomous_authority(&context, &existing, &cart_mandate).await? {
466 let artifacts = self
467 .store_payment_artifacts(&context, &payment_mandate, None, None)
468 .await?;
469 return self
470 .begin_user_reconfirmation(
471 context,
472 existing,
473 cart_mandate,
474 payment_mandate,
475 artifacts.envelope,
476 artifacts.evidence,
477 )
478 .await;
479 }
480 None
481 }
482 };
483
484 let payment_mandate_id =
485 payment_mandate.payment_mandate_contents.payment_mandate_id.clone();
486 let amount = payment_amount(&payment_mandate, amount_scale)?;
487 let mut judged = existing.clone();
489 judged.cart.total = amount.clone();
490 let idempotency_key = context_idempotency_key(&context)
491 .unwrap_or_else(|| format!("ap2:payment_mandate:{payment_mandate_id}"));
492 let committed_amount = usd_micro_amount(&amount).ok();
493
494 let (result, payment_envelope, evidence) = self
495 .governor
496 .govern(
497 PaymentOperation::ExecutePayment,
498 &judged,
499 &context.protocol,
500 caller,
501 || async {
502 if let Some(previous) = self
503 .payment_mandate_ledger
504 .consume(&payment_mandate_id, &context.transaction_id)
505 .await?
506 {
507 return Err(Ap2Error::PaymentMandateReplayed {
508 payment_mandate_id: payment_mandate_id.clone(),
509 transaction_id: previous.as_str().to_string(),
510 }
511 .into());
512 }
513
514 let artifacts = self
515 .store_payment_artifacts(
516 &context,
517 &payment_mandate,
518 authorization.as_ref().map(|(artifact, _)| artifact),
519 authorization.as_ref().map(|(_, verification)| verification),
520 )
521 .await?;
522 let evidence = artifacts.evidence;
523 let supporting_evidence_refs = self.ap2_evidence_refs(&existing, &evidence);
524 let payment_envelope = self
525 .payment_envelope(
526 &payment_mandate,
527 authorization.as_ref().map(|(_, verification)| verification),
528 &evidence,
529 )
530 .with_field(IDEMPOTENCY_KEY_FIELD, json!(idempotency_key));
531 let mut command = execute_payment_command(
532 &payment_mandate,
533 amount_scale,
534 self.normalize_context(
535 context.clone(),
536 ProtocolExtensions::from(vec![payment_envelope.clone()]),
537 ),
538 supporting_evidence_refs,
539 )?;
540 command.extensions = ProtocolExtensions::from(vec![payment_envelope.clone()]);
541
542 let result = self.payment_service.execute_payment(command).await?;
543 Ok((result, payment_envelope, evidence))
544 },
545 |(result, _, _)| match result.outcome {
546 PaymentExecutionOutcome::Authorized | PaymentExecutionOutcome::Completed => {
547 Settlement::Commit(committed_amount)
548 }
549 PaymentExecutionOutcome::InterventionRequired
550 | PaymentExecutionOutcome::Failed => Settlement::Release,
551 },
552 )
553 .await?;
554 let transaction = self
555 .finalize_record(
556 &context,
557 result.transaction.clone(),
558 StoredArtifactSet { envelope: payment_envelope, evidence: evidence.clone() },
559 ProtocolRefUpdate {
560 payment_ref: Some(payment_mandate_id.clone()),
561 executed_payment_ref: Some(payment_mandate_id),
562 ..ProtocolRefUpdate::default()
563 },
564 )
565 .await?;
566
567 let mut generated_evidence_refs = result.generated_evidence_refs;
568 for stored in evidence {
569 if !generated_evidence_refs.contains(&stored.evidence_ref) {
570 generated_evidence_refs.push(stored.evidence_ref);
571 }
572 }
573
574 Ok(PaymentExecutionResult {
575 outcome: result.outcome,
576 transaction,
577 order: result.order,
578 intervention: result.intervention,
579 generated_evidence_refs,
580 })
581 }
582
583 pub async fn apply_payment_receipt(
591 &self,
592 context: CommerceContext,
593 payment_receipt: PaymentReceipt,
594 ) -> Result<TransactionRecord> {
595 let context = self.normalize_context(context, ProtocolExtensions::default());
596 let existing = self.lookup(&context).await?;
597 if let Some(bound) = existing
598 .as_ref()
599 .and_then(|record| record.protocol_refs.ap2_payment_mandate_id.as_deref())
600 && bound != payment_receipt.payment_mandate_id
601 {
602 return Err(Ap2Error::PaymentMandateMismatch {
603 payment_mandate_id: payment_receipt.payment_mandate_id.clone(),
604 field: "payment_receipt.payment_mandate_id".to_string(),
605 }
606 .into());
607 }
608 let artifacts = self.store_receipt_artifacts(&context, &payment_receipt).await?;
609 let mut command =
610 sync_payment_outcome_command(existing.as_ref(), &payment_receipt, context.clone());
611 command.generated_evidence_refs =
612 artifacts.evidence.iter().map(|stored| stored.evidence_ref.clone()).collect();
613 command.context.extensions = merge_extensions(
614 command.context.extensions,
615 ProtocolExtensions::from(vec![artifacts.envelope.clone()]),
616 );
617
618 let mut record = self.payment_service.sync_payment_outcome(command).await?;
619 update_record_state_from_receipt(&mut record, &payment_receipt);
620 self.finalize_record(
621 &context,
622 record,
623 artifacts,
624 ProtocolRefUpdate {
625 payment_ref: Some(payment_receipt.payment_mandate_id.clone()),
626 receipt_ref: Some(payment_receipt.payment_id.clone()),
627 ..ProtocolRefUpdate::default()
628 },
629 )
630 .await
631 }
632
633 async fn verify_cart_authorization(
634 &self,
635 mandate: &CartMandate,
636 artifact: &AuthorizationArtifact,
637 ) -> Result<VerifiedAuthorization> {
638 match (&self.merchant_verifier, self.allow_unverified_authorizations) {
639 (Some(verifier), _) => verifier.verify_cart_authorization(mandate, artifact).await,
640 (None, true) => {
641 RequireMerchantAuthorization.verify_cart_authorization(mandate, artifact).await
642 }
643 (None, false) => Err(Ap2Error::AuthorizationVerifierNotConfigured {
644 artifact_kind: "merchant_authorization".to_string(),
645 }
646 .into()),
647 }
648 }
649
650 async fn verify_intent_authorization(
651 &self,
652 mandate: &IntentMandate,
653 artifact: &AuthorizationArtifact,
654 ) -> Result<VerifiedAuthorization> {
655 match (&self.user_verifier, self.allow_unverified_authorizations) {
656 (Some(verifier), _) => verifier.verify_intent_authorization(mandate, artifact).await,
657 (None, true) => {
658 RequireUserAuthorization.verify_intent_authorization(mandate, artifact).await
659 }
660 (None, false) => Err(Ap2Error::AuthorizationVerifierNotConfigured {
661 artifact_kind: "intent_authorization".to_string(),
662 }
663 .into()),
664 }
665 }
666
667 async fn verify_payment_authorization(
668 &self,
669 mandate: &PaymentMandate,
670 artifact: &AuthorizationArtifact,
671 ) -> Result<VerifiedAuthorization> {
672 match (&self.user_verifier, self.allow_unverified_authorizations) {
673 (Some(verifier), _) => verifier.verify_payment_authorization(mandate, artifact).await,
674 (None, true) => {
675 RequireUserAuthorization.verify_payment_authorization(mandate, artifact).await
676 }
677 (None, false) => Err(Ap2Error::AuthorizationVerifierNotConfigured {
678 artifact_kind: "user_authorization".to_string(),
679 }
680 .into()),
681 }
682 }
683
684 fn ensure_payment_mandate_admissible(
687 &self,
688 record: &TransactionRecord,
689 payment_mandate: &PaymentMandate,
690 ) -> Result<()> {
691 let transaction_id = record.transaction_id.as_str().to_string();
692 let payment_mandate_id = &payment_mandate.payment_mandate_contents.payment_mandate_id;
693 if let Some(executed) = record
694 .protocol_refs
695 .additional
696 .iter()
697 .find(|reference| reference.reference_kind == EXECUTED_PAYMENT_MANDATE_REF_KIND)
698 {
699 return Err(if &executed.reference_value == payment_mandate_id {
700 Ap2Error::PaymentMandateReplayed {
701 payment_mandate_id: payment_mandate_id.clone(),
702 transaction_id,
703 }
704 } else {
705 Ap2Error::TransactionAlreadyPaid {
706 transaction_id,
707 executed_payment_mandate_id: executed.reference_value.clone(),
708 }
709 }
710 .into());
711 }
712 match &record.state {
713 TransactionState::Authorized
714 | TransactionState::Completed
715 | TransactionState::Canceled
716 | TransactionState::Failed => {
717 return Err(Ap2Error::TransactionNotPayable {
718 transaction_id,
719 state: format!("{:?}", record.state.tag()),
720 }
721 .into());
722 }
723 TransactionState::Draft
724 | TransactionState::Negotiating
725 | TransactionState::AwaitingUserAuthorization
726 | TransactionState::AwaitingPaymentMethod
727 | TransactionState::InterventionRequired(_) => {}
728 }
729 if let Some(bound) = record.protocol_refs.ap2_payment_mandate_id.as_deref()
730 && bound != payment_mandate_id
731 {
732 return Err(Ap2Error::PaymentMandateRebind {
733 transaction_id,
734 bound_payment_mandate_id: bound.to_string(),
735 payment_mandate_id: payment_mandate_id.clone(),
736 }
737 .into());
738 }
739 Ok(())
740 }
741
742 async fn begin_user_reconfirmation(
743 &self,
744 context: CommerceContext,
745 existing: TransactionRecord,
746 cart_mandate: CartMandate,
747 payment_mandate: PaymentMandate,
748 envelope: crate::domain::ProtocolExtensionEnvelope,
749 evidence: Vec<StoredEvidence>,
750 ) -> Result<PaymentExecutionResult> {
751 let intervention_service = self.intervention_service.as_ref().ok_or_else(|| {
752 AdkError::from(Ap2Error::InterventionServiceRequired {
753 transaction_id: context.transaction_id.as_str().to_string(),
754 })
755 })?;
756 let expires_at = self
757 .load_latest_json::<IntentMandate>(&context, &existing, "intent_mandate")
758 .await?
759 .map(|intent| self.parse_timestamp("intent_expiry", &intent.intent_expiry))
760 .transpose()?
761 .or_else(|| {
762 self.parse_timestamp("cart_expiry", &cart_mandate.contents.cart_expiry).ok()
763 });
764 let intervention = InterventionState {
765 intervention_id: format!("ap2-reconfirm-{}", context.transaction_id.as_str()),
766 kind: InterventionKind::BuyerReconfirmation,
767 status: InterventionStatus::Pending,
768 instructions: Some(
769 "return to the user for explicit AP2 cart or payment confirmation".to_string(),
770 ),
771 continuation_token: Some(format!("ap2:return:{}", context.transaction_id.as_str())),
772 requested_by: Some(context.actor.clone()),
773 expires_at,
774 extensions: ProtocolExtensions::default(),
775 };
776 let record = intervention_service
777 .begin_intervention(BeginInterventionCommand {
778 context: context.clone(),
779 intervention: intervention.clone(),
780 })
781 .await?;
782 let transaction = self
783 .finalize_record(
784 &context,
785 record,
786 StoredArtifactSet { envelope, evidence: evidence.clone() },
787 ProtocolRefUpdate {
788 payment_ref: Some(payment_mandate.payment_mandate_contents.payment_mandate_id),
789 ..ProtocolRefUpdate::default()
790 },
791 )
792 .await?;
793
794 Ok(PaymentExecutionResult {
795 outcome: PaymentExecutionOutcome::InterventionRequired,
796 order: transaction.order.clone(),
797 transaction,
798 intervention: Some(intervention),
799 generated_evidence_refs: evidence
800 .into_iter()
801 .map(|stored| stored.evidence_ref)
802 .collect(),
803 })
804 }
805
806 fn normalize_context(
807 &self,
808 mut context: CommerceContext,
809 extensions: ProtocolExtensions,
810 ) -> CommerceContext {
811 context.protocol = ap2_descriptor();
812 context.extensions = merge_extensions(context.extensions, extensions);
813 context
814 }
815
816 async fn lookup(&self, context: &CommerceContext) -> Result<Option<TransactionRecord>> {
817 self.transaction_store
818 .get(TransactionLookup {
819 transaction_id: context.transaction_id.clone(),
820 session_identity: context.session_identity.clone(),
821 })
822 .await
823 }
824
825 fn validate_intent_mandate(
826 &self,
827 context: &CommerceContext,
828 intent_mandate: &IntentMandate,
829 authorization_artifact: Option<&AuthorizationArtifact>,
830 ) -> Result<()> {
831 self.validate_not_expired("intent_expiry", &intent_mandate.intent_expiry)?;
832 if context.mode == CommerceMode::HumanNotPresent {
833 if authorization_artifact.is_none() {
834 return Err(Ap2Error::MissingIntentAuthorization {
835 transaction_id: context.transaction_id.as_str().to_string(),
836 }
837 .into());
838 }
839 if !self.has_authority_constraints(intent_mandate) {
840 return Err(Ap2Error::MissingAuthorityConstraints {
841 transaction_id: context.transaction_id.as_str().to_string(),
842 }
843 .into());
844 }
845 }
846 Ok(())
847 }
848
849 fn has_authority_constraints(&self, intent_mandate: &IntentMandate) -> bool {
854 intent_mandate.merchants.as_ref().is_some_and(|merchants| !merchants.is_empty())
855 || intent_mandate.skus.as_ref().is_some_and(|skus| !skus.is_empty())
856 }
857
858 async fn validate_intent_constraints(
867 &self,
868 context: &CommerceContext,
869 existing: &TransactionRecord,
870 cart_mandate: &CartMandate,
871 ) -> Result<()> {
872 if context.mode != CommerceMode::HumanNotPresent {
873 return Ok(());
874 }
875 let Some(intent_mandate) =
876 self.load_latest_json::<IntentMandate>(context, existing, "intent_mandate").await?
877 else {
878 return Ok(());
879 };
880 self.validate_not_expired("intent_expiry", &intent_mandate.intent_expiry)?;
881 if let Some(merchants) =
882 intent_mandate.merchants.as_ref().filter(|merchants| !merchants.is_empty())
883 {
884 let merchant_name = cart_mandate.contents.merchant_name.to_ascii_lowercase();
885 let allowed =
886 merchants.iter().map(|merchant| merchant.to_ascii_lowercase()).collect::<Vec<_>>();
887 if !allowed.iter().any(|merchant| merchant == &merchant_name) {
888 return Err(Ap2Error::MerchantNotAuthorized {
889 merchant_name: cart_mandate.contents.merchant_name.clone(),
890 }
891 .into());
892 }
893 }
894
895 if intent_mandate.skus.as_ref().is_some_and(|skus| !skus.is_empty()) {
896 return Err(Ap2Error::SkuConstraintUnverifiable.into());
897 }
898
899 if intent_mandate.requires_refundability {
900 let all_refundable = cart_mandate
901 .contents
902 .payment_request
903 .details
904 .display_items
905 .iter()
906 .all(|item| item.refund_period > 0);
907 if !all_refundable {
908 return Err(Ap2Error::RefundabilityRequired.into());
909 }
910 }
911
912 Ok(())
913 }
914
915 fn validate_payment_mandate_against_cart(
916 &self,
917 payment_mandate: &PaymentMandate,
918 cart_mandate: &CartMandate,
919 ) -> Result<()> {
920 let payment_details_id = &payment_mandate.payment_mandate_contents.payment_details_id;
921 if payment_details_id != &cart_mandate.contents.payment_request.details.id {
922 return Err(Ap2Error::PaymentMandateMismatch {
923 payment_mandate_id: payment_mandate
924 .payment_mandate_contents
925 .payment_mandate_id
926 .clone(),
927 field: "payment_details_id".to_string(),
928 }
929 .into());
930 }
931 if payment_mandate.payment_mandate_contents.payment_response.request_id
932 != cart_mandate.contents.payment_request.details.id
933 {
934 return Err(Ap2Error::PaymentMandateMismatch {
935 payment_mandate_id: payment_mandate
936 .payment_mandate_contents
937 .payment_mandate_id
938 .clone(),
939 field: "payment_response.request_id".to_string(),
940 }
941 .into());
942 }
943 if payment_mandate.payment_mandate_contents.payment_details_total
944 != cart_mandate.contents.payment_request.details.total
945 {
946 return Err(Ap2Error::PaymentMandateMismatch {
947 payment_mandate_id: payment_mandate
948 .payment_mandate_contents
949 .payment_mandate_id
950 .clone(),
951 field: "payment_details_total".to_string(),
952 }
953 .into());
954 }
955 self.validate_not_expired("cart_expiry", &cart_mandate.contents.cart_expiry)
956 }
957
958 async fn evaluate_autonomous_authority(
959 &self,
960 context: &CommerceContext,
961 existing: &TransactionRecord,
962 cart_mandate: &CartMandate,
963 ) -> Result<bool> {
964 if context.mode != CommerceMode::HumanNotPresent {
965 return Err(Ap2Error::MissingUserAuthorization {
966 payment_mandate_id: context.transaction_id.as_str().to_string(),
967 }
968 .into());
969 }
970 let Some(intent_mandate) =
971 self.load_latest_json::<IntentMandate>(context, existing, "intent_mandate").await?
972 else {
973 return Err(Ap2Error::MissingIntentAuthorization {
974 transaction_id: context.transaction_id.as_str().to_string(),
975 }
976 .into());
977 };
978 if !existing.evidence_refs.iter().any(|evidence_ref| {
981 evidence_ref.protocol.name == "ap2"
982 && evidence_ref.artifact_kind == "intent_authorization"
983 }) {
984 return Err(Ap2Error::MissingIntentAuthorization {
985 transaction_id: context.transaction_id.as_str().to_string(),
986 }
987 .into());
988 }
989 self.validate_intent_constraints(context, existing, cart_mandate).await?;
990 if intent_mandate.user_cart_confirmation_required
991 || cart_mandate.contents.user_cart_confirmation_required
992 {
993 return Ok(false);
994 }
995 Ok(true)
996 }
997
998 fn parse_timestamp(&self, field: &str, value: &str) -> Result<DateTime<Utc>> {
999 DateTime::parse_from_rfc3339(value).map(|timestamp| timestamp.with_timezone(&Utc)).map_err(
1000 |_| {
1001 AdkError::from(Ap2Error::InvalidTimestamp {
1002 field: field.to_string(),
1003 value: value.to_string(),
1004 })
1005 },
1006 )
1007 }
1008
1009 fn validate_not_expired(&self, field: &str, value: &str) -> Result<()> {
1010 let timestamp = self.parse_timestamp(field, value)?;
1011 if timestamp < Utc::now() {
1012 return Err(Ap2Error::ExpiredArtifact {
1013 field: field.to_string(),
1014 expires_at: timestamp.to_rfc3339(),
1015 }
1016 .into());
1017 }
1018 Ok(())
1019 }
1020
1021 async fn store_json(
1022 &self,
1023 context: &CommerceContext,
1024 artifact_kind: &str,
1025 unique_id: &str,
1026 payload: &impl serde::Serialize,
1027 ) -> Result<StoredEvidence> {
1028 self.evidence_store
1029 .store(StoreEvidenceCommand {
1030 transaction_id: context.transaction_id.clone(),
1031 session_identity: context.session_identity.clone(),
1032 evidence_ref: EvidenceReference {
1033 evidence_id: format!("{artifact_kind}:{unique_id}"),
1034 protocol: ap2_descriptor(),
1035 artifact_kind: artifact_kind.to_string(),
1036 digest: None,
1037 },
1038 body: serde_json::to_vec(payload).map_err(|err| {
1039 AdkError::new(
1040 ErrorComponent::Server,
1041 ErrorCategory::InvalidInput,
1042 "payments.ap2.serialize_failed",
1043 format!("failed to serialize AP2 evidence: {err}"),
1044 )
1045 })?,
1046 content_type: "application/json".to_string(),
1047 })
1048 .await
1049 }
1050
1051 async fn store_inline_artifact(
1052 &self,
1053 context: &CommerceContext,
1054 artifact_kind: &str,
1055 unique_id: &str,
1056 artifact: &AuthorizationArtifact,
1057 ) -> Result<StoredEvidence> {
1058 self.evidence_store
1059 .store(StoreEvidenceCommand {
1060 transaction_id: context.transaction_id.clone(),
1061 session_identity: context.session_identity.clone(),
1062 evidence_ref: EvidenceReference {
1063 evidence_id: format!("{artifact_kind}:{unique_id}"),
1064 protocol: ap2_descriptor(),
1065 artifact_kind: artifact_kind.to_string(),
1066 digest: None,
1067 },
1068 body: artifact.value.as_bytes().to_vec(),
1069 content_type: artifact.content_type.clone(),
1070 })
1071 .await
1072 }
1073
1074 async fn load_latest_json<T>(
1075 &self,
1076 context: &CommerceContext,
1077 record: &TransactionRecord,
1078 artifact_kind: &str,
1079 ) -> Result<Option<T>>
1080 where
1081 T: DeserializeOwned,
1082 {
1083 let Some(evidence_ref) = record
1084 .evidence_refs
1085 .iter()
1086 .rev()
1087 .find(|evidence_ref| {
1088 evidence_ref.protocol.name == "ap2" && evidence_ref.artifact_kind == artifact_kind
1089 })
1090 .cloned()
1091 else {
1092 return Ok(None);
1093 };
1094
1095 let Some(stored) = self
1096 .evidence_store
1097 .load(EvidenceLookup {
1098 evidence_ref,
1099 session_identity: context.session_identity.clone(),
1100 })
1101 .await?
1102 else {
1103 return Ok(None);
1104 };
1105
1106 serde_json::from_slice(&stored.body).map(Some).map_err(|err| {
1107 AdkError::new(
1108 ErrorComponent::Artifact,
1109 ErrorCategory::Internal,
1110 "payments.ap2.evidence_decode_failed",
1111 format!(
1112 "failed to decode stored AP2 `{artifact_kind}` evidence for transaction `{}`: {err}",
1113 context.transaction_id
1114 ),
1115 )
1116 })
1117 }
1118
1119 async fn store_intent_artifacts(
1120 &self,
1121 context: &CommerceContext,
1122 intent_mandate: &IntentMandate,
1123 authorization_artifact: Option<&AuthorizationArtifact>,
1124 verification: Option<&VerifiedAuthorization>,
1125 ) -> Result<StoredArtifactSet> {
1126 let mandate = self
1127 .store_json(context, "intent_mandate", context.transaction_id.as_str(), intent_mandate)
1128 .await?;
1129 let mut envelope = crate::domain::ProtocolExtensionEnvelope::new(ap2_descriptor())
1130 .with_field("artifact_kind", json!("intent_mandate"))
1131 .with_field("intent_expiry", json!(intent_mandate.intent_expiry))
1132 .with_field(
1133 "user_cart_confirmation_required",
1134 json!(intent_mandate.user_cart_confirmation_required),
1135 )
1136 .with_field(
1137 "has_merchant_constraints",
1138 json!(
1139 intent_mandate
1140 .merchants
1141 .as_ref()
1142 .is_some_and(|merchants| !merchants.is_empty())
1143 ),
1144 )
1145 .with_field(
1146 "has_sku_constraints",
1147 json!(intent_mandate.skus.as_ref().is_some_and(|skus| !skus.is_empty())),
1148 )
1149 .with_field("requires_refundability", json!(intent_mandate.requires_refundability));
1150 let mut evidence = vec![mandate.clone()];
1151 envelope.evidence_refs.push(mandate.evidence_ref.clone());
1152
1153 if let Some(artifact) = authorization_artifact {
1154 let stored = self
1155 .store_inline_artifact(
1156 context,
1157 "intent_authorization",
1158 context.transaction_id.as_str(),
1159 artifact,
1160 )
1161 .await?;
1162 envelope.evidence_refs.push(stored.evidence_ref.clone());
1163 envelope.fields.insert(
1164 "intent_authorization_artifact".to_string(),
1165 json!({
1166 "artifactType": artifact.artifact_type,
1167 "contentType": artifact.content_type,
1168 }),
1169 );
1170 evidence.push(stored);
1171 }
1172 if let Some(verification) = verification {
1173 envelope
1174 .fields
1175 .insert("intent_authorization_verification".to_string(), json!(verification));
1176 }
1177
1178 Ok(StoredArtifactSet { envelope, evidence })
1179 }
1180
1181 async fn store_cart_artifacts(
1182 &self,
1183 context: &CommerceContext,
1184 cart_mandate: &CartMandate,
1185 merchant_authorization: &AuthorizationArtifact,
1186 verification: &VerifiedAuthorization,
1187 ) -> Result<StoredArtifactSet> {
1188 let mandate = self
1189 .store_json(context, "cart_mandate", &cart_mandate.contents.id, cart_mandate)
1190 .await?;
1191 let authorization = self
1192 .store_inline_artifact(
1193 context,
1194 "merchant_authorization",
1195 &cart_mandate.contents.id,
1196 merchant_authorization,
1197 )
1198 .await?;
1199 let all_items_refundable = cart_mandate
1200 .contents
1201 .payment_request
1202 .details
1203 .display_items
1204 .iter()
1205 .all(|item| item.refund_period > 0);
1206 let mut envelope = crate::domain::ProtocolExtensionEnvelope::new(ap2_descriptor())
1207 .with_field("artifact_kind", json!("cart_mandate"))
1208 .with_field("cart_id", json!(cart_mandate.contents.id))
1209 .with_field(
1210 "payment_details_id",
1211 json!(cart_mandate.contents.payment_request.details.id),
1212 )
1213 .with_field("cart_expiry", json!(cart_mandate.contents.cart_expiry))
1214 .with_field("merchant_name", json!(cart_mandate.contents.merchant_name))
1215 .with_field(
1216 "user_cart_confirmation_required",
1217 json!(cart_mandate.contents.user_cart_confirmation_required),
1218 )
1219 .with_field("total", json!(cart_mandate.contents.payment_request.details.total))
1220 .with_field("all_items_refundable", json!(all_items_refundable));
1221 envelope.evidence_refs.push(mandate.evidence_ref.clone());
1222 envelope.evidence_refs.push(authorization.evidence_ref.clone());
1223 envelope
1224 .fields
1225 .insert("merchant_authorization_verification".to_string(), json!(verification));
1226 Ok(StoredArtifactSet { envelope, evidence: vec![mandate, authorization] })
1227 }
1228
1229 async fn store_payment_artifacts(
1230 &self,
1231 context: &CommerceContext,
1232 payment_mandate: &PaymentMandate,
1233 user_authorization: Option<&AuthorizationArtifact>,
1234 verification: Option<&VerifiedAuthorization>,
1235 ) -> Result<StoredArtifactSet> {
1236 let mandate = self
1237 .store_json(
1238 context,
1239 "payment_mandate",
1240 &payment_mandate.payment_mandate_contents.payment_mandate_id,
1241 payment_mandate,
1242 )
1243 .await?;
1244 let mut envelope =
1245 self.payment_envelope(payment_mandate, verification, std::slice::from_ref(&mandate));
1246 let mut evidence = vec![mandate];
1247 if let Some(user_authorization) = user_authorization {
1248 let authorization = self
1249 .store_inline_artifact(
1250 context,
1251 "user_authorization",
1252 &payment_mandate.payment_mandate_contents.payment_mandate_id,
1253 user_authorization,
1254 )
1255 .await?;
1256 envelope.evidence_refs.push(authorization.evidence_ref.clone());
1257 evidence.push(authorization);
1258 }
1259
1260 Ok(StoredArtifactSet { envelope, evidence })
1261 }
1262
1263 async fn store_receipt_artifacts(
1264 &self,
1265 context: &CommerceContext,
1266 payment_receipt: &PaymentReceipt,
1267 ) -> Result<StoredArtifactSet> {
1268 let receipt = self
1269 .store_json(context, "payment_receipt", &payment_receipt.payment_id, payment_receipt)
1270 .await?;
1271 let status = match payment_receipt.payment_status {
1272 PaymentStatusEnvelope::Success(_) => "success",
1273 PaymentStatusEnvelope::Error(_) => "error",
1274 PaymentStatusEnvelope::Failure(_) => "failure",
1275 };
1276 let method_name = payment_receipt
1277 .payment_method_details
1278 .as_ref()
1279 .and_then(|details| details.get("method_name"))
1280 .and_then(serde_json::Value::as_str);
1281 let mut envelope = crate::domain::ProtocolExtensionEnvelope::new(ap2_descriptor())
1282 .with_field("artifact_kind", json!("payment_receipt"))
1283 .with_field("payment_mandate_id", json!(payment_receipt.payment_mandate_id))
1284 .with_field("timestamp", json!(payment_receipt.timestamp))
1285 .with_field("payment_id", json!(payment_receipt.payment_id))
1286 .with_field("amount", json!(payment_receipt.amount))
1287 .with_field("status", json!(status));
1288 if let Some(method_name) = method_name {
1289 envelope = envelope.with_field("method_name", json!(method_name));
1290 }
1291 envelope.evidence_refs.push(receipt.evidence_ref.clone());
1292 Ok(StoredArtifactSet { envelope, evidence: vec![receipt] })
1293 }
1294
1295 fn payment_envelope(
1296 &self,
1297 payment_mandate: &PaymentMandate,
1298 verification: Option<&VerifiedAuthorization>,
1299 evidence: &[StoredEvidence],
1300 ) -> crate::domain::ProtocolExtensionEnvelope {
1301 let mut envelope = crate::domain::ProtocolExtensionEnvelope::new(ap2_descriptor())
1302 .with_field("artifact_kind", json!("payment_mandate"))
1303 .with_field(
1304 "payment_mandate_id",
1305 json!(payment_mandate.payment_mandate_contents.payment_mandate_id),
1306 )
1307 .with_field(
1308 "payment_details_id",
1309 json!(payment_mandate.payment_mandate_contents.payment_details_id),
1310 )
1311 .with_field(
1312 "payment_request_id",
1313 json!(payment_mandate.payment_mandate_contents.payment_response.request_id),
1314 )
1315 .with_field(
1316 "payment_details_total",
1317 json!(payment_mandate.payment_mandate_contents.payment_details_total),
1318 )
1319 .with_field(
1320 "method_name",
1321 json!(payment_mandate.payment_mandate_contents.payment_response.method_name),
1322 )
1323 .with_field(
1324 "merchant_agent",
1325 json!(payment_mandate.payment_mandate_contents.merchant_agent),
1326 )
1327 .with_field("timestamp", json!(payment_mandate.payment_mandate_contents.timestamp))
1328 .with_field(
1329 "user_authorization_present",
1330 json!(payment_mandate.user_authorization.is_some()),
1331 );
1332 envelope.evidence_refs.extend(evidence.iter().map(|stored| stored.evidence_ref.clone()));
1333 if let Some(verification) = verification {
1334 envelope
1335 .fields
1336 .insert("user_authorization_verification".to_string(), json!(verification));
1337 }
1338 envelope
1339 }
1340
1341 fn ap2_evidence_refs(
1342 &self,
1343 existing: &TransactionRecord,
1344 new_evidence: &[StoredEvidence],
1345 ) -> Vec<EvidenceReference> {
1346 let mut refs = existing
1347 .evidence_refs
1348 .iter()
1349 .filter(|evidence_ref| evidence_ref.protocol.name == "ap2")
1350 .cloned()
1351 .collect::<Vec<_>>();
1352 for stored in new_evidence {
1353 if !refs.contains(&stored.evidence_ref) {
1354 refs.push(stored.evidence_ref.clone());
1355 }
1356 }
1357 refs
1358 }
1359
1360 async fn finalize_record(
1361 &self,
1362 context: &CommerceContext,
1363 mut record: TransactionRecord,
1364 artifacts: StoredArtifactSet,
1365 refs: ProtocolRefUpdate,
1366 ) -> Result<TransactionRecord> {
1367 if let Some(existing) = self.lookup(context).await? {
1368 self.merge_existing(&mut record, existing);
1369 }
1370 record.session_identity = context.session_identity.clone();
1371 update_record_extensions(&mut record, artifacts.envelope);
1372 for stored in artifacts.evidence {
1373 if !record.evidence_refs.contains(&stored.evidence_ref) {
1374 record.attach_evidence_ref(stored.evidence_ref.clone());
1375 }
1376 if !record
1377 .evidence_digests
1378 .iter()
1379 .any(|digest| digest.evidence_ref == stored.evidence_ref)
1380 {
1381 record.attach_evidence_digest(ProtocolEnvelopeDigest::new(
1382 stored.evidence_ref.clone(),
1383 Utc::now(),
1384 ));
1385 }
1386 }
1387 if let Some(intent_ref) = refs.intent_ref {
1388 record.protocol_refs.ap2_intent_mandate_id = Some(intent_ref);
1389 }
1390 if let Some(cart_ref) = refs.cart_ref {
1391 record.protocol_refs.ap2_cart_mandate_id = Some(cart_ref);
1392 }
1393 if let Some(payment_ref) = refs.payment_ref {
1394 ProtocolCorrelator::attach_protocol_ref(
1395 &mut record,
1396 ProtocolRefKind::Ap2PaymentMandateId,
1397 payment_ref,
1398 )
1399 .map_err(AdkError::from)?;
1400 }
1401 if let Some(executed) = refs.executed_payment_ref {
1402 let marker = ProtocolReference {
1403 protocol: ap2_descriptor(),
1404 reference_kind: EXECUTED_PAYMENT_MANDATE_REF_KIND.to_string(),
1405 reference_value: executed,
1406 };
1407 if !record.protocol_refs.additional.contains(&marker) {
1408 record.protocol_refs.additional.push(marker);
1409 }
1410 }
1411 if let Some(receipt_ref) = refs.receipt_ref {
1412 record.protocol_refs.ap2_payment_receipt_id = Some(receipt_ref);
1413 }
1414 record.recompute_safe_summary();
1415 self.transaction_store.upsert(record.clone()).await?;
1416 Ok(record)
1417 }
1418
1419 fn merge_existing(&self, record: &mut TransactionRecord, existing: TransactionRecord) {
1420 if record.fulfillment.is_none() {
1421 record.fulfillment = existing.fulfillment;
1422 }
1423 if record.order.is_none() {
1424 record.order = existing.order;
1425 }
1426 if record.payment_processor.is_none() {
1427 record.payment_processor = existing.payment_processor;
1428 }
1429 if record.protocol_refs.ap2_intent_mandate_id.is_none() {
1430 record.protocol_refs.ap2_intent_mandate_id =
1431 existing.protocol_refs.ap2_intent_mandate_id;
1432 }
1433 if record.protocol_refs.ap2_cart_mandate_id.is_none() {
1434 record.protocol_refs.ap2_cart_mandate_id = existing.protocol_refs.ap2_cart_mandate_id;
1435 }
1436 if record.protocol_refs.ap2_payment_mandate_id.is_none() {
1437 record.protocol_refs.ap2_payment_mandate_id =
1438 existing.protocol_refs.ap2_payment_mandate_id;
1439 }
1440 if record.protocol_refs.ap2_payment_receipt_id.is_none() {
1441 record.protocol_refs.ap2_payment_receipt_id =
1442 existing.protocol_refs.ap2_payment_receipt_id;
1443 }
1444 for reference in existing.protocol_refs.additional {
1445 if !record.protocol_refs.additional.contains(&reference) {
1446 record.protocol_refs.additional.push(reference);
1447 }
1448 }
1449 for envelope in existing.extensions.0 {
1450 if !record.extensions.as_slice().contains(&envelope) {
1451 record.attach_extension(envelope);
1452 }
1453 }
1454 for evidence_ref in existing.evidence_refs {
1455 if !record.evidence_refs.contains(&evidence_ref) {
1456 record.attach_evidence_ref(evidence_ref);
1457 }
1458 }
1459 for digest in existing.evidence_digests {
1460 if !record.evidence_digests.contains(&digest) {
1461 record.attach_evidence_digest(digest);
1462 }
1463 }
1464 }
1465}