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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
use crate::prelude::*;
use anyhow::anyhow;
use base64::prelude::*;
use http::header::InvalidHeaderValue;
use paste::paste;
use routex_api::collect_payment::DebtorAccountReference;
use routex_api::info::{ConnectionInfo, SearchFilter};
use routex_api::{
AccountReference, ConfirmationContext, ConfirmationData, ConnectionId, InputContext,
ResponseData, ServiceRequest,
};
pub use routex_api::{Error as ServiceError, ServiceId};
use routex_client_common::{
DEFAULT_URL, HttpClient, RoutexClientCore, handle_not_found, json_decode,
};
pub use routex_client_common::{Error, Response, Result, SearchRequest};
use url::Url;
use uuid::Uuid;
pub mod prelude {
pub use super::RoutexClient;
pub use routex_api::accounts::{AccountField, Service as AccountsService};
pub use routex_api::balances::{
Balance, BalanceType, Balances, Decimal, Service as BalancesService,
};
pub use routex_api::collect_payment::{PaymentInitiation, Service as CollectPaymentService};
pub use routex_api::info::{
ConnectionInfo, ConnectionType, CountryCode, Details, SearchFilter,
};
pub use routex_api::transactions::Service as TransactionsService;
pub use routex_api::transfer::{
ChargeBearer, CreditorAddress, ISODateTimeOrDate, PaymentProduct,
Service as TransferService, TransferDetails,
};
pub use routex_api::{
Account, AccountIdentifier, AccountReference, AccountStatus, AccountType, Amount,
Authenticated, ConfirmationContext, ConnectionData, ConnectionId, Credentials,
CredentialsModel, Dialog, DialogContext, DialogInput, DialogOption, Filter, Image,
InputContext, InputType, OBResponse, OBResult, PaymentErrorCode, ProviderErrorCode,
Redirect, RedirectHandle, SecrecyLevel, Service, ServiceBlockedCode, Session,
SupportedService, Ticket, TicketErrorCode, UnsupportedProductReason,
};
pub use url::Url;
}
#[must_use]
#[derive(Clone, Debug)]
pub struct RoutexClient<T> {
core: RoutexClientCore<T>,
recurring_consents: bool,
}
#[cfg(feature = "reqwest")]
impl Default for RoutexClient<routex_client_common::reqwest::Client> {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "reqwest")]
impl RoutexClient<routex_client_common::reqwest::Client> {
#[allow(clippy::needless_pass_by_value, clippy::missing_panics_doc)]
/// Create a new client
pub fn new() -> Self {
Self::with_url(DEFAULT_URL.parse().expect("valid URL"))
}
/// Create a new client with a custom URL
pub fn with_url(url: Url) -> Self {
Self::with_url_and_client(url, routex_client_common::reqwest::Client::new())
}
/// Create a new client from environment variables
///
/// Expected variables:
///
/// * `ROUTEX_URL`
///
/// # Panics
///
/// Panics if one of the variables is not set or if `ROUTEX_URL` is not a valid URL.
pub fn from_env() -> Self {
Self::with_url(
std::env::var("ROUTEX_URL")
.expect("ROUTEX_URL not set")
.parse()
.expect("Proxy URL should be valid"),
)
}
}
impl<T> RoutexClient<T>
where
T: HttpClient + Clone,
{
#[allow(clippy::missing_panics_doc)]
/// Create a new client
pub fn with_client(http_client: T) -> Self {
Self::with_url_and_client(DEFAULT_URL.parse().expect("valid URL"), http_client)
}
/// Create a new client with a custom URL
pub fn with_url_and_client(url: Url, http_client: T) -> Self {
Self::for_distribution("Rust", env!("CARGO_PKG_VERSION"), url, http_client)
}
/// Create a new client for a versioned distribution and with a custom URL
pub fn for_distribution(distribution: &str, version: &str, url: Url, http_client: T) -> Self {
Self {
core: RoutexClientCore::for_distribution(distribution, version, url, http_client),
recurring_consents: false,
}
}
/// Run a key settlement with the routex service, verifying the attestation report.
///
/// Stores a new random secret key and announces its public key to routex.
/// In return, routex responds with its own public key and an attestation report.
/// The attestation report allows verifying that routex created its corresponding secret key within the TEE
/// and that its creation happened in response to our client public key (freshness).
///
/// # Errors
///
/// Returns an error if the key settlement request fails or the attestation report fails verification.
pub async fn settle_key<S: routex_api::Service>(
&self,
ticket: &Authenticated<Ticket<S>>,
) -> Result<()> {
self.core.settle_key(ticket).await
}
/// System version for the established session
pub async fn system_version(&self, ticket_id: Uuid) -> Option<String> {
self.core.system_version(ticket_id).await
}
}
// Traces
impl<T> RoutexClient<T>
where
T: HttpClient + Clone,
{
/// Trace identifier returned with the last request
///
/// # Panics
///
/// Panics of the internal lock is poisoned.
pub fn trace_id(&self) -> Option<Vec<u8>> {
self.core.trace_id()
}
/// Retrieve trace data
///
/// # Errors
///
/// * [`Error::RequestError`] if the request fails.
/// * [`Error::NotFound`] if the trace is not available.
pub async fn trace<S: routex_api::Service>(
&self,
ticket: &Authenticated<Ticket<S>>,
trace_id: &[u8],
) -> Result<String> {
let ticket_id = ticket.to_data().id;
let trace_id = BASE64_URL_SAFE.encode(
self.core
.with_key_settlement(ticket_id, async |keys| {
keys.seal(trace_id, &ticket_id).await
})
.await
.map_err(Error::RequestError)?,
);
self.core
.execute(
ticket,
self.core
.get(&routex_api::traces::path(&trace_id).to_url(self.core.url())),
)
.await
.map_err(handle_not_found)
.and_then(|res| {
String::from_utf8(res.to_vec()).map_err(|err| Error::RequestError(anyhow!(err)))
})
}
}
// Redirects
impl<T> RoutexClient<T>
where
T: HttpClient + Clone,
{
/// Set a redirect URI for subsequent service requests.
///
/// Redirects will eventually forward to that URI.
/// It can be used to redirect back to a web application or to jump
/// back into the context of a desktop or mobile application.
///
/// If no redirect URI is set, [`RedirectHandle`]s will get returned instead of [`Redirect`]s.
///
/// # Errors
///
/// Fails if the URI is not a valid header value (probably lacks proper percent encoding).
pub fn set_redirect_uri(
&mut self,
redirect_uri: &str,
) -> std::result::Result<(), InvalidHeaderValue> {
self.core.set_redirect_uri(redirect_uri)
}
pub fn set_recurring_consents(&mut self, enabled: bool) {
self.recurring_consents = enabled;
}
/// Register a redirect URI for a given redirect handle.
///
/// Returns the URL that the user is meant to get sent to.
///
/// # Errors
///
/// Fails if the request fails or the response data cannot get parsed as expected.
pub async fn register_redirect_uri<S: routex_api::Service>(
&self,
ticket: &Authenticated<Ticket<S>>,
handle: impl Into<String>,
redirect_uri: impl Into<String>,
) -> Result<Url> {
Ok(json_decode::<routex_api::redirects::Response>(
&self
.core
.execute(
ticket,
self.core.post(
&routex_api::redirects::path().to_url(self.core.url()),
&routex_api::redirects::Request {
handle: handle.into(),
redirect_uri: redirect_uri.into(),
},
),
)
.await?,
)?
.redirect_url)
}
}
// Info
impl<T> RoutexClient<T>
where
T: HttpClient + Clone,
{
/// Search for service connections (banks and other providers)
///
/// The result is a list of connections that match all the [`SearchFilter`]s.
///
/// # Errors
///
/// Fails if the request fails.
///
/// # Example
///
/// ```no_run
/// # tokio_test::block_on(async {
/// # let client = RoutexClient::from_env();
/// # let user_input = "my bank";
/// # let ticket: Authenticated<Ticket<AccountsService>> = unimplemented!();
/// use routex_client::prelude::*;
///
/// // Split input at whitespace for improved name matching
/// let mut filters: Vec<_> = user_input
/// .split_whitespace()
/// .map(|term| SearchFilter::Term(term.to_string()))
/// .collect();
///
/// filters.push(SearchFilter::Types(vec![ConnectionType::Production]));
///
/// let connection_infos = client
/// .search(ticket, filters)
/// .iban_detection(true)
/// .limit(20)
/// .send()
/// .await?;
/// # Ok::<_, routex_client::Error>(())
/// # });
/// ```
pub fn search<S: routex_api::Service>(
&self,
ticket: Authenticated<Ticket<S>>,
filters: impl IntoIterator<Item = SearchFilter>,
) -> SearchRequest<S, T> {
self.core.search(ticket, filters)
}
/// Get information for a service connection
///
/// # Errors
///
/// * [`Error::RequestError`] if the request fails.
/// * [`Error::NotFound`] if the connection ID is not known.
///
/// # Examples
///
/// ```no_run
/// # tokio_test::block_on(async {
/// # use routex_client::prelude::*;
/// # let client = RoutexClient::from_env();
/// # let ticket: &Authenticated<Ticket<AccountsService>> = unimplemented!();
/// # let connection_id = unimplemented!();
/// let connection_info = client.info(ticket, connection_id).await?;
/// # Ok::<_, routex_client::Error>(())
/// # });
/// ```
pub async fn info<S: routex_api::Service>(
&self,
ticket: &Authenticated<Ticket<S>>,
connection_id: ConnectionId,
) -> Result<ConnectionInfo> {
self.core.info(ticket, connection_id).await
}
}
#[must_use]
pub struct Request<S, C>
where
S: Service,
{
inner: ServiceRequest<S>,
ticket: Authenticated<Ticket<S>>,
client: RoutexClientCore<C>,
}
impl<S, C> Request<S, C>
where
S: Service,
C: HttpClient + Clone,
{
/// Set a session to use
pub fn session(mut self, session: Session) -> Self {
self.inner.session = Some(session);
self
}
/// Enable the use of recurring consenst
pub fn recurring_consents(mut self, enabled: bool) -> Self {
self.inner.recurring_consents = enabled;
self
}
/// Send the request.
///
/// # Errors
///
/// Fails if the request fails.
pub async fn send(self) -> Result<OBResponse<S>> {
json_decode(
&self
.client
.execute(
&self.ticket,
self.client.post(
&<S as Service>::path().to_url(self.client.url()),
&self.inner,
),
)
.await
.map_err(handle_not_found)?,
)
}
}
macro_rules! service {
{
$(#[$meta:meta])+
$service:ident
$(($arg:ident: $($type:tt)+))*
$({$($values:tt)*})?
} => {
paste! {
impl<T> RoutexClient<T>
where
T: HttpClient + Clone,
{
$(#[$meta])+
pub fn [<$service:snake>](
&self,
credentials: Credentials,
ticket: &Authenticated<Ticket<[<$service Service>]>>,
$($arg: $($type)+,)*
) -> Request<[<$service Service>], T> {
Request {
inner: ServiceRequest::<[<$service Service>]> {
credentials,
session: None,
recurring_consents: self.recurring_consents,
data: routex_api::[<$service:snake>]::RequestData {
$($($values)*)?
},
},
ticket: ticket.clone(),
client: self.core.clone(),
}
}
#[doc = "Respond to [`Dialog`] returned by [`" $service:snake "`](Self::" $service:snake "), [`respond_" $service:snake "`](Self::respond_" $service:snake "), or [`confirm_" $service:snake "`](Self::confirm_" $service:snake ")"]
///
/// # Errors
///
/// Fails if the request fails.
pub async fn [<respond_$service:snake>](
&self,
ticket: &Authenticated<Ticket<[<$service Service>]>>,
context: InputContext<[<$service Service>]>,
response: impl Into<String>,
) -> Result<OBResponse<[<$service Service>]>> {
json_decode(
&self.core
.execute(
ticket,
self.core
.post(
&[<$service Service>]::response_path().to_url(self.core.url()),
&ResponseData { context, response: response.into() },
),
)
.await
.map_err(handle_not_found)?
)
}
#[doc = "Confirm [`Dialog`] or [`Redirect`] returned by [`" $service:snake "`](Self::" $service:snake "), [`respond_" $service:snake "`](Self::respond_" $service:snake "), or [`confirm_" $service:snake "`](Self::confirm_" $service:snake ")"]
///
/// # Errors
///
/// Fails if the request fails.
pub async fn [<confirm_$service:snake>](
&self,
ticket: &Authenticated<Ticket<[<$service Service>]>>,
context: ConfirmationContext<[<$service Service>]>,
) -> Result<OBResponse<[<$service Service>]>> {
json_decode(
&self.core
.execute(
ticket,
self.core
.post(
&[<$service Service>]::confirmation_path().to_url(self.core.url()),
&ConfirmationData { context },
),
)
.await
.map_err(handle_not_found)?
)
}
}
}
}
}
service! {
/// [Accounts service](https://docs.yaxi.tech/accounts.html)
///
/// # Example
///
/// ```no_run
/// # tokio_test::block_on(async {
/// # use routex_client::prelude::*;
/// # let client = RoutexClient::from_env();
/// # let connection_id = unimplemented!();
/// # let user_id = None;
/// # let password = None;
/// # let connection_data = None;
/// # let accounts_ticket = unimplemented!();
/// let credentials = Credentials {
/// connection_id,
/// user_id,
/// password,
/// connection_data,
/// };
///
/// let response = client
/// .accounts(
/// credentials,
/// accounts_ticket,
/// [
/// AccountField::Iban,
/// AccountField::Bic,
/// AccountField::Name,
/// AccountField::DisplayName,
/// AccountField::OwnerName,
/// AccountField::Currency,
/// ],
/// Some(
/// AccountField::IBAN.not_eq(None)
/// .and(
/// AccountField::TYPE.eq(Some(AccountType::Current))
/// .or(AccountField::TYPE.eq(None))
/// )
/// .and(Account::supports(SupportedService::CollectPayment)),
/// ),
/// )
/// .send()
/// .await?;
///
/// let OBResponse::Result(result, session, connection_data) = response else {
/// todo!("Handle interrupts");
/// };
/// # Ok::<_, routex_client::Error>(())
/// # });
/// ```
Accounts
(fields: impl IntoIterator<Item = AccountField>)
(filter: Option<Filter<AccountField>>)
{
fields: fields.into_iter().collect(),
filter,
}
}
service! {
/// [Balances service](https://docs.yaxi.tech/balances.html)
///
/// # Errors
///
/// Fails if the request fails.
Balances
(accounts: impl IntoIterator<Item = AccountReference>)
{
accounts: accounts.into_iter().collect(),
}
}
service! {
/// [Transactions service](https://docs.yaxi.tech/transactions.html)
Transactions
}
service! {
/// [Collect Payment service](https://docs.yaxi.tech/collect-payment.html)
///
/// # Example
///
/// ```no_run
/// # tokio_test::block_on(async {
/// # use routex_client::prelude::*;
/// # use routex_api::collect_payment::DebtorAccountIdentifier as AccountIdentifier;
/// # use routex_api::collect_payment::DebtorAccountReference as AccountReference;
/// # let client = RoutexClient::from_env();
/// # let credentials = unimplemented!();
/// # let session = vec![].into();
/// # let payment_ticket = unimplemented!();
/// # let selected_iban = String::new();
/// let response = client
/// .collect_payment(
/// credentials,
/// payment_ticket,
/// Some(AccountReference {
/// id: AccountIdentifier::Iban(selected_iban),
/// currency: None,
/// }),
/// )
/// .session(session)
/// .send()
/// .await?;
/// # Ok::<_, routex_client::Error>(())
/// # });
/// ```
CollectPayment
(account: Option<DebtorAccountReference>)
{
account
}
}
service! {
#[allow(clippy::too_many_arguments)]
/// [Transfer service](https://docs.yaxi.tech/transfer.html)
Transfer
(product: PaymentProduct)
(debtor_account: Option<AccountReference>)
(debtor_name: Option<String>)
(requested_execution_date: Option<ISODateTimeOrDate>)
(details: impl IntoIterator<Item = TransferDetails>)
{
product,
debtor_account,
debtor_name,
requested_execution_date,
details: details.into_iter().collect(),
}
}