Skip to main content

adk_payments/protocol/ap2/
verification.rs

1use chrono::Utc;
2use serde::{Deserialize, Serialize};
3use serde_json::{Map, Value, json};
4
5use adk_core::Result;
6use async_trait::async_trait;
7
8use crate::protocol::ap2::error::Ap2Error;
9use crate::protocol::ap2::types::{
10    AuthorizationArtifact, CartMandate, IntentMandate, PaymentMandate,
11};
12
13/// Claim a [`MerchantAuthorizationVerifier`] sets to the merchant name bound to
14/// the verified signing key.
15///
16/// When present, `Ap2Adapter` rejects a cart whose self-reported
17/// `contents.merchant_name` differs from this value, so intent-mandate merchant
18/// allow-lists are enforced against the verified identity.
19pub const VERIFIED_MERCHANT_NAME_CLAIM: &str = "verified_merchant_name";
20
21/// Claim recording whether an authorization artifact was cryptographically verified.
22///
23/// The presence-only development verifiers set it to `false`.
24pub const CRYPTOGRAPHICALLY_VERIFIED_CLAIM: &str = "cryptographically_verified";
25
26/// Verification metadata captured after one authorization artifact passes policy.
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28#[serde(rename_all = "camelCase")]
29pub struct VerifiedAuthorization {
30    pub artifact_kind: String,
31    pub verified_at: chrono::DateTime<Utc>,
32    #[serde(default, skip_serializing_if = "Map::is_empty")]
33    pub claims: Map<String, Value>,
34}
35
36impl VerifiedAuthorization {
37    /// Creates verification metadata stamped with the current time.
38    ///
39    /// # Example
40    ///
41    /// ```
42    /// use adk_payments::protocol::ap2::{VERIFIED_MERCHANT_NAME_CLAIM, VerifiedAuthorization};
43    /// use serde_json::{Map, json};
44    ///
45    /// let mut claims = Map::new();
46    /// claims.insert(VERIFIED_MERCHANT_NAME_CLAIM.to_string(), json!("Merchant Example"));
47    /// let verified = VerifiedAuthorization::new("merchant_authorization", claims);
48    /// assert_eq!(verified.artifact_kind, "merchant_authorization");
49    /// ```
50    #[must_use]
51    pub fn new(artifact_kind: impl Into<String>, claims: Map<String, Value>) -> Self {
52        Self { artifact_kind: artifact_kind.into(), verified_at: Utc::now(), claims }
53    }
54}
55
56/// Verifies merchant authorization artifacts bound to `CartMandate`.
57///
58/// Implementations must verify the artifact cryptographically against the
59/// cart contents (for example a JWS over the canonical `contents` payload),
60/// bind the signing key to the merchant named in `contents.merchant_name`, and
61/// compare signatures or digests in constant time. Set
62/// [`VERIFIED_MERCHANT_NAME_CLAIM`] to the merchant name the key is bound to.
63#[async_trait]
64pub trait MerchantAuthorizationVerifier: Send + Sync {
65    /// Verifies `artifact` for `mandate` and returns the verified claims.
66    ///
67    /// # Errors
68    ///
69    /// Returns an error when the artifact is missing, malformed, expired, or
70    /// does not verify against the mandate contents.
71    async fn verify_cart_authorization(
72        &self,
73        mandate: &CartMandate,
74        artifact: &AuthorizationArtifact,
75    ) -> Result<VerifiedAuthorization>;
76}
77
78/// Verifies user authorization artifacts bound to intent or payment mandates.
79///
80/// Implementations must verify the artifact cryptographically against the
81/// mandate contents, check the user's key or credential binding, and compare
82/// signatures or digests in constant time.
83#[async_trait]
84pub trait UserAuthorizationVerifier: Send + Sync {
85    /// Verifies `artifact` for an intent mandate and returns the verified claims.
86    ///
87    /// # Errors
88    ///
89    /// Returns an error when the artifact does not verify against the intent.
90    async fn verify_intent_authorization(
91        &self,
92        mandate: &IntentMandate,
93        artifact: &AuthorizationArtifact,
94    ) -> Result<VerifiedAuthorization>;
95
96    /// Verifies `artifact` for a payment mandate and returns the verified claims.
97    ///
98    /// # Errors
99    ///
100    /// Returns an error when the artifact does not verify against the payment
101    /// mandate contents.
102    async fn verify_payment_authorization(
103        &self,
104        mandate: &PaymentMandate,
105        artifact: &AuthorizationArtifact,
106    ) -> Result<VerifiedAuthorization>;
107}
108
109/// Presence-only merchant check that performs **no cryptographic verification**.
110///
111/// Any non-empty value passes, including a forged one. `Ap2Adapter` uses it
112/// only after `allow_unverified_authorizations()` is called, for local
113/// development and tests. Never configure it in production.
114pub struct RequireMerchantAuthorization;
115
116#[async_trait]
117impl MerchantAuthorizationVerifier for RequireMerchantAuthorization {
118    async fn verify_cart_authorization(
119        &self,
120        mandate: &CartMandate,
121        artifact: &AuthorizationArtifact,
122    ) -> Result<VerifiedAuthorization> {
123        if artifact.value.trim().is_empty() {
124            return Err(Ap2Error::MissingMerchantAuthorization {
125                cart_id: mandate.contents.id.clone(),
126            }
127            .into());
128        }
129
130        let mut claims = Map::new();
131        claims.insert("merchant_name".to_string(), json!(mandate.contents.merchant_name));
132        claims.insert("artifact_type".to_string(), json!(artifact.artifact_type));
133        claims.insert("content_type".to_string(), json!(artifact.content_type));
134        claims.insert(CRYPTOGRAPHICALLY_VERIFIED_CLAIM.to_string(), json!(false));
135        Ok(VerifiedAuthorization::new("merchant_authorization", claims))
136    }
137}
138
139/// Presence-only user check that performs **no cryptographic verification**.
140///
141/// Any non-empty value passes, including a forged one. `Ap2Adapter` uses it
142/// only after `allow_unverified_authorizations()` is called, for local
143/// development and tests. Never configure it in production.
144pub struct RequireUserAuthorization;
145
146#[async_trait]
147impl UserAuthorizationVerifier for RequireUserAuthorization {
148    async fn verify_intent_authorization(
149        &self,
150        mandate: &IntentMandate,
151        artifact: &AuthorizationArtifact,
152    ) -> Result<VerifiedAuthorization> {
153        if artifact.value.trim().is_empty() {
154            return Err(Ap2Error::MissingIntentAuthorization {
155                transaction_id: mandate.natural_language_description.clone(),
156            }
157            .into());
158        }
159
160        let mut claims = Map::new();
161        claims.insert(
162            "user_cart_confirmation_required".to_string(),
163            json!(mandate.user_cart_confirmation_required),
164        );
165        claims.insert("artifact_type".to_string(), json!(artifact.artifact_type));
166        claims.insert("content_type".to_string(), json!(artifact.content_type));
167        claims.insert(CRYPTOGRAPHICALLY_VERIFIED_CLAIM.to_string(), json!(false));
168        Ok(VerifiedAuthorization::new("intent_authorization", claims))
169    }
170
171    async fn verify_payment_authorization(
172        &self,
173        mandate: &PaymentMandate,
174        artifact: &AuthorizationArtifact,
175    ) -> Result<VerifiedAuthorization> {
176        if artifact.value.trim().is_empty() {
177            return Err(Ap2Error::MissingUserAuthorization {
178                payment_mandate_id: mandate.payment_mandate_contents.payment_mandate_id.clone(),
179            }
180            .into());
181        }
182
183        let mut claims = Map::new();
184        claims.insert(
185            "payment_mandate_id".to_string(),
186            json!(mandate.payment_mandate_contents.payment_mandate_id),
187        );
188        claims.insert("artifact_type".to_string(), json!(artifact.artifact_type));
189        claims.insert("content_type".to_string(), json!(artifact.content_type));
190        claims.insert(CRYPTOGRAPHICALLY_VERIFIED_CLAIM.to_string(), json!(false));
191        Ok(VerifiedAuthorization::new("user_authorization", claims))
192    }
193}