-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerchant.rs
More file actions
218 lines (200 loc) · 7.8 KB
/
merchant.rs
File metadata and controls
218 lines (200 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// SPDX-License-Identifier: Apache-2.0
//! Merchant role: quotes carts, evaluates open checkout mandates, and
//! signs the closed `CheckoutMandate`.
use std::{collections::BTreeMap, sync::Arc};
use ap2_crypto::{JsonWebKey, Signer};
use ap2_mandate::{check_checkout_constraints, sign_merchant_authorization, MandateClient};
use ap2_types::{
v0_1_alpha as alpha,
v0_2::{Amount, CheckoutMandate, IsoCurrency, Merchant, OpenCheckoutMandate},
};
use crate::core::{
amount_from_checkout, build_checkout_from_request, canonical_token_reference,
cart_contents_from_checkout, compact_checkout_jwt, parse_currency, present_options, ActorError,
ActorResult, Clock, IntentDecision, IntentEvaluation, MerchantQuote, PurchaseRequest,
SignCheckoutRequest, SignedCheckout, SystemClock, CHECKOUT_AUD, CHECKOUT_NONCE,
CLOCK_SKEW_SECONDS, DEFAULT_TTL_SECONDS,
};
/// Operations a merchant agent must implement.
///
/// Implementations are synchronous and free of side effects beyond the
/// signing key access already mediated by the [`Signer`] interface.
pub trait MerchantAgent: Send + Sync {
/// Builds a [`MerchantQuote`] from a v0.1-alpha [`alpha::IntentMandate`].
///
/// # Errors
///
/// Returns [`ActorError::InvalidInput`] if the intent's natural
/// language description is empty.
fn quote_cart(&self, intent: &alpha::IntentMandate) -> ActorResult<MerchantQuote>;
/// Signs a v0.1-alpha cart mandate over the given [`alpha::CartContents`].
///
/// # Errors
///
/// Returns [`ActorError::Crypto`] if the underlying detached JWS
/// signature cannot be produced.
fn sign_cart_mandate(&self, contents: alpha::CartContents) -> ActorResult<alpha::CartMandate>;
/// Verifies a presented open checkout mandate and decides whether to
/// fulfil it without further user interaction.
///
/// # Errors
///
/// Returns [`ActorError::Mandate`] if the SD-JWT fails verification.
fn evaluate_intent(&self, open_checkout_mandate: &str) -> ActorResult<IntentEvaluation>;
/// Signs the closed [`SignedCheckout`] bound to a previously evaluated
/// open checkout mandate.
///
/// # Errors
///
/// Returns [`ActorError::Violations`] if the merchant's checkout
/// breaches any constraint from the open mandate.
fn sign_checkout(&self, request: &SignCheckoutRequest) -> ActorResult<SignedCheckout>;
}
/// In-memory reference implementation of [`MerchantAgent`].
#[derive(Clone)]
pub struct DefaultMerchantAgent {
merchant: Merchant,
signer: Arc<dyn Signer>,
user_public_key: JsonWebKey,
clock: Arc<dyn Clock>,
}
impl DefaultMerchantAgent {
/// Builds a merchant agent with explicit merchant identity, signer,
/// expected user public key, and clock.
#[must_use]
pub fn new(
merchant: Merchant,
signer: Arc<dyn Signer>,
user_public_key: JsonWebKey,
clock: Arc<dyn Clock>,
) -> Self {
Self {
merchant,
signer,
user_public_key,
clock,
}
}
/// Convenience constructor: uses the system wall clock.
#[must_use]
pub fn with_system_clock(
merchant: Merchant,
signer: Arc<dyn Signer>,
user_public_key: JsonWebKey,
) -> Self {
Self::new(merchant, signer, user_public_key, Arc::new(SystemClock))
}
/// Returns the public JWK derived from the configured signer.
#[must_use]
pub fn public_key(&self) -> JsonWebKey {
self.signer.public_jwk()
}
/// Returns the merchant identity this agent represents.
#[must_use]
pub const fn merchant(&self) -> &Merchant {
&self.merchant
}
}
impl MerchantAgent for DefaultMerchantAgent {
fn quote_cart(&self, intent: &alpha::IntentMandate) -> ActorResult<MerchantQuote> {
if intent.natural_language_description.trim().is_empty() {
return Err(ActorError::InvalidInput(
"intent natural language description is required".to_owned(),
));
}
let sku = intent
.skus
.as_ref()
.and_then(|skus| skus.first())
.cloned()
.unwrap_or_else(|| "demo-sku".to_owned());
let currency: IsoCurrency = parse_currency("USD")?;
let purchase = PurchaseRequest {
user_email: "buyer@example.com".to_owned(),
natural_language_description: intent.natural_language_description.clone(),
item_id: sku,
item_name: intent.natural_language_description.clone(),
quantity: 1,
price_cap: Amount {
currency,
amount: 1_999,
},
merchant: self.merchant.clone(),
ttl_seconds: DEFAULT_TTL_SECONDS,
};
let checkout = build_checkout_from_request(&purchase, self.clock.as_ref())?;
let amount = amount_from_checkout(&checkout)?;
let contents =
cart_contents_from_checkout(&checkout, &self.merchant.name, self.clock.as_ref())?;
let cart_mandate = self.sign_cart_mandate(contents)?;
Ok(MerchantQuote {
cart_mandate,
checkout,
amount,
merchant: self.merchant.clone(),
})
}
fn sign_cart_mandate(&self, contents: alpha::CartContents) -> ActorResult<alpha::CartMandate> {
let merchant_authorization = sign_merchant_authorization(&contents, self.signer.as_ref())?;
Ok(alpha::CartMandate {
contents,
merchant_authorization: Some(merchant_authorization),
extensions: BTreeMap::default(),
})
}
fn evaluate_intent(&self, open_checkout_mandate: &str) -> ActorResult<IntentEvaluation> {
let mandate = MandateClient::verify_single::<OpenCheckoutMandate>(
open_checkout_mandate,
self.user_public_key.clone(),
None,
None,
CLOCK_SKEW_SECONDS,
Some(self.clock.now_unix()),
)?;
if mandate.mandate_payload.constraints.is_empty() {
return Ok(IntentEvaluation {
decision: IntentDecision::RequireUserInSession,
reason: Some("open checkout mandate has no constraints".to_owned()),
});
}
Ok(IntentEvaluation {
decision: IntentDecision::FulfillOpenMandates,
reason: None,
})
}
fn sign_checkout(&self, request: &SignCheckoutRequest) -> ActorResult<SignedCheckout> {
let open = MandateClient::verify_single::<OpenCheckoutMandate>(
&request.open_checkout_mandate,
self.user_public_key.clone(),
None,
None,
CLOCK_SKEW_SECONDS,
Some(self.clock.now_unix()),
)?;
let violations = check_checkout_constraints(&open.mandate_payload, &request.quote.checkout);
if !violations.is_empty() {
return Err(ActorError::Violations(violations));
}
let checkout_jwt = compact_checkout_jwt(&request.quote.checkout, self.signer.as_ref())?;
let checkout_hash = canonical_token_reference(&checkout_jwt);
let checkout_mandate = CheckoutMandate {
checkout_jwt,
checkout_hash: checkout_hash.clone(),
iat: Some(self.clock.now_unix()),
exp: Some(self.clock.now_unix().saturating_add(DEFAULT_TTL_SECONDS)),
extensions: BTreeMap::default(),
};
let payload = serde_json::to_value(&checkout_mandate)?;
let checkout_mandate_sd_jwt = MandateClient::present(
self.signer.as_ref(),
&request.open_checkout_mandate,
&[payload],
present_options(CHECKOUT_AUD, CHECKOUT_NONCE, self.clock.now_unix()),
)?;
Ok(SignedCheckout {
checkout_mandate,
checkout_mandate_sd_jwt,
checkout_hash,
})
}
}