routex-client-common 0.0.2

Common logic shared by different routex clients.
Documentation
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
#![allow(clippy::missing_errors_doc, clippy::missing_panics_doc)]

use std::collections::HashMap;
use std::sync::{Arc, RwLock};

use anyhow::anyhow;
use base64::prelude::*;
use bytes::Bytes;
use futures::lock::Mutex;
use reqwest::header::{CONTENT_LENGTH, HeaderMap, InvalidHeaderValue};
use reqwest::{
    Client,
    header::{ACCEPT, HeaderValue},
};
use reqwest::{ClientBuilder, RequestBuilder, StatusCode};
use routex_api::{Authenticated, Error as ServiceError, ServiceId};
#[cfg(feature = "error")]
use routex_api::{
    PaymentErrorCode, ProviderErrorCode, ServiceBlockedCode, TicketErrorCode,
    UnsupportedProductReason,
};
use routex_settlement::KeySettlement;
use serde::Deserialize;
use url::Url;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error(transparent)]
    RequestError(anyhow::Error),
    #[error("Service error")]
    ServiceError(ServiceError),
    #[error("Error response")]
    ResponseError(Box<Response>),
    #[error("Resource not found")]
    NotFound,
}

#[derive(Clone, Debug)]
pub struct Response {
    pub url: Url,
    pub status: StatusCode,
    pub headers: HeaderMap,
    pub body: Bytes,
}

pub fn json_decode<T: for<'de> Deserialize<'de>>(body: &[u8]) -> Result<T> {
    serde_json::from_slice(body).map_err(|err| Error::RequestError(err.into()))
}

impl From<Response> for Error {
    fn from(response: Response) -> Error {
        match serde_json::from_slice::<ServiceError>(&response.body) {
            Ok(payload) => Error::ServiceError(payload),
            Err(_) => Error::ResponseError(Box::new(response)),
        }
    }
}

impl From<reqwest::Error> for Error {
    fn from(err: reqwest::Error) -> Self {
        Self::RequestError(anyhow!(err))
    }
}

pub type Result<T> = std::result::Result<T, Error>;

#[must_use]
#[derive(Clone, Debug)]
pub struct RoutexClientCore {
    url: Url,
    client: Client,
    keys: Arc<Mutex<HashMap<String, KeySettlement<sealed::RoutexKeySettlementEndpoint>>>>,
    redirect_uri: Option<HeaderValue>,
    trace_id: Arc<RwLock<Option<Vec<u8>>>>,
}

mod sealed {
    use reqwest::{Client, header::ACCEPT};
    use routex_settlement::KeySettlementCore;
    use url::Url;

    use super::{Error, Response};

    #[derive(Debug)]
    pub struct RoutexKeySettlementEndpoint {
        pub(super) url: Url,
        pub(super) client: Client,
    }

    impl KeySettlementCore for RoutexKeySettlementEndpoint {
        type Data = str;

        async fn request(
            &self,
            public_key: [u8; 32],
            ticket_id: &Self::Data,
        ) -> anyhow::Result<routex_api::keys::Response> {
            let response = self
                .client
                .post(self.url.clone())
                .header(&routex_api::headers::TICKET_ID, ticket_id)
                .header(ACCEPT, routex_api::CURRENT_MEDIA_TYPE)
                .json(&routex_api::keys::Request { public_key })
                .send()
                .await?;

            if response.status().is_client_error() || response.status().is_server_error() {
                Err(Error::from(Response {
                    url: response.url().clone(),
                    status: response.status(),
                    headers: response.headers().clone(),
                    body: response.bytes().await?,
                })
                .into())
            } else {
                Ok(response.json().await?)
            }
        }
    }
}

pub const DEFAULT_URL: &str = "https://api.yaxi.tech/";

impl RoutexClientCore {
    /// Create a new client for a versioned distribution and with a custom URL
    ///
    /// # Panics
    ///
    /// Panics if it fails to build the [`reqwest::Client`].
    pub fn for_distribution(distribution: &str, version: &str, url: Url) -> Self {
        let client = ClientBuilder::new()
            .user_agent(format!(
                "RoutexClient/{} ({})",
                version,
                [distribution, std::env::consts::OS, std::env::consts::ARCH]
                    .into_iter()
                    .filter(|s| !s.is_empty())
                    .collect::<Vec<_>>()
                    .join("; "),
            ))
            .build()
            .unwrap();

        Self {
            url,
            client,
            keys: Arc::default(),
            redirect_uri: None,
            trace_id: Arc::default(),
        }
    }

    /// 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<routex_api::Ticket<S>>,
    ) -> Result<()> {
        let ticket_id = ticket.to_data().id;

        self.with_key_settlement(&ticket_id, async |keys| {
            keys.settle(&ticket_id).await.map_err(Error::RequestError)
        })
        .await
    }

    pub async fn with_key_settlement<U>(
        &self,
        ticket_id: impl Into<String>,
        f: impl AsyncFnOnce(&mut KeySettlement<sealed::RoutexKeySettlementEndpoint>) -> U,
    ) -> U {
        f(self
            .keys
            .lock()
            .await
            .entry(ticket_id.into())
            .or_insert_with(|| {
                KeySettlement::new(sealed::RoutexKeySettlementEndpoint {
                    url: routex_api::keys::settlement_path().to_url(&self.url),
                    client: self.client.clone(),
                })
            }))
        .await
    }

    pub async fn system_version(&self, ticket_id: impl Into<String>) -> Option<String> {
        self.with_key_settlement(ticket_id, async |keys| keys.system_version().cloned())
            .await
            .map(|v| serde_json::to_string(&v).expect("serialization should work"))
    }

    pub async fn execute<S: routex_api::Service>(
        &self,
        ticket: &Authenticated<routex_api::Ticket<S>>,
        request: RequestBuilder,
    ) -> Result<Bytes> {
        let ticket_id = ticket.to_data().id;

        self.with_key_settlement(&ticket_id, async |keys| {
            let mut request = request
                .header(&routex_api::headers::TICKET_ID, &ticket_id)
                .header(
                    &routex_api::headers::TICKET,
                    BASE64_STANDARD.encode(
                        keys.seal(ticket.as_str().as_bytes(), &ticket_id)
                            .await
                            .map_err(Error::RequestError)?,
                    ),
                )
                .header(ACCEPT, routex_api::CURRENT_MEDIA_TYPE)
                .build()
                .expect("build should work");

            if let Some(value) = self.redirect_uri.clone() {
                request
                    .headers_mut()
                    .insert(&routex_api::headers::REDIRECT_URI, value);
            }

            if let Some(body) = request.body_mut() {
                *body = keys
                    .seal(
                        body.as_bytes().expect("Body should be reusable"),
                        &ticket_id,
                    )
                    .await
                    .map_err(Error::RequestError)?
                    .into();
            }

            request.headers_mut().insert(
                &routex_api::headers::SESSION_ID,
                keys.session_id(&ticket_id)
                    .await
                    .map_err(Error::RequestError)?
                    .clone(),
            );

            request.headers_mut().remove(&CONTENT_LENGTH);

            let response = self.client.execute(request).await?;

            *self.trace_id.write().expect("poisoned") = response
                .headers()
                .get(&routex_api::headers::TRACE_ID)
                .and_then(|v| v.to_str().ok())
                .and_then(|v| BASE64_STANDARD.decode(v).ok())
                .and_then(|v| keys.unseal(&v).ok());

            if response.status().is_client_error() || response.status().is_server_error() {
                let url = response.url().clone();
                let status = response.status();
                let headers = response.headers().clone();
                let body = response.bytes().await?;
                Err(Error::from(Response {
                    url,
                    status,
                    headers,
                    body: keys.unseal(&body).map_or(body, Into::into),
                }))
            } else {
                let body = response.bytes().await?;
                Ok(if body.is_empty() {
                    body
                } else {
                    keys.unseal(&body)
                        .map_err(|err| Error::RequestError(anyhow!(err)))?
                        .into()
                })
            }
        })
        .await
    }

    pub fn client(&self) -> &Client {
        &self.client
    }

    pub fn url(&self) -> &Url {
        &self.url
    }

    /// Trace identifier returned with the last request
    ///
    /// # Panics
    ///
    /// Panics of the internal lock is poisoned.
    pub fn trace_id(&self) -> Option<Vec<u8>> {
        self.trace_id.read().expect("poisoned").clone()
    }

    pub fn set_redirect_uri(
        &mut self,
        redirect_uri: &str,
    ) -> std::result::Result<(), InvalidHeaderValue> {
        self.redirect_uri = Some(redirect_uri.try_into()?);
        Ok(())
    }
}

#[must_use]
pub fn handle_not_found(err: Error) -> Error {
    if let Error::ResponseError(response) = &err
        && response.status == StatusCode::NOT_FOUND
    {
        Error::NotFound
    } else {
        err
    }
}

/// A ticket that contains only the service, but no other data.
#[derive(serde::Deserialize, Clone)]
pub struct ServiceOnlyTicket {
    pub service: ServiceId,
}

#[macro_export]
macro_rules! with_any_service {
    ($ticket:expr, $authenticated:ident, $block:block) => {
        match $ticket.parse::<routex_api::Authenticated<routex_client_common::ServiceOnlyTicket>>()
        {
            Ok($authenticated) => match $authenticated.to_data().service {
                routex_api::ServiceId::Accounts { .. } => {
                    with_any_service!(
                        $ticket,
                        $authenticated,
                        $block,
                        routex_api::accounts::Service
                    )
                }
                routex_api::ServiceId::CollectPayment { .. } => {
                    with_any_service!(
                        $ticket,
                        $authenticated,
                        $block,
                        routex_api::collect_payment::Service
                    )
                }
                routex_api::ServiceId::Balances { .. } => {
                    with_any_service!(
                        $ticket,
                        $authenticated,
                        $block,
                        routex_api::balances::Service
                    )
                }
                routex_api::ServiceId::Transactions { .. } => {
                    with_any_service!(
                        $ticket,
                        $authenticated,
                        $block,
                        routex_api::transactions::Service
                    )
                }
                routex_api::ServiceId::Transfer { .. } => {
                    with_any_service!(
                        $ticket,
                        $authenticated,
                        $block,
                        routex_api::transfer::Service
                    )
                }
            },
            Err(err) => Err(err.into()),
        }
    };
    ($ticket:expr, $authenticated:ident, $block:block, $service:ty) => {
        match $ticket.parse::<routex_api::Authenticated<routex_api::Ticket<$service>>>() {
            Ok($authenticated) => $block.map_err(Into::into),
            Err(err) => Err(err.into()),
        }
    };
}

#[cfg(feature = "uniffi")]
::uniffi::setup_scaffolding!();

#[cfg(feature = "error")]
#[allow(clippy::enum_variant_names)]
#[derive(thiserror::Error, Debug)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]
pub enum RoutexClientError {
    #[error("Invalid redirect URI")]
    InvalidRedirectUri,

    #[error("Request error")]
    RequestError { error: String },

    #[error("Unexpected service error")]
    UnexpectedError { user_message: Option<String> },

    #[error("Canceled")]
    Canceled,

    #[error("Invalid credentials")]
    InvalidCredentials { user_message: Option<String> },

    #[error("Service blocked")]
    ServiceBlocked {
        user_message: Option<String>,
        code: Option<ServiceBlockedCode>,
    },

    #[error("Unauthorized")]
    Unauthorized { user_message: Option<String> },

    #[error("Consent expired")]
    ConsentExpired { user_message: Option<String> },

    #[error("Access exceeded")]
    AccessExceeded { user_message: Option<String> },

    #[error("Period out of bounds")]
    PeriodOutOfBounds { user_message: Option<String> },

    #[error("Unsupported product")]
    UnsupportedProduct {
        reason: Option<UnsupportedProductReason>,
        user_message: Option<String>,
    },

    #[error("Payment canceled or rejected")]
    PaymentFailed {
        code: Option<PaymentErrorCode>,
        user_message: Option<String>,
    },

    #[error("Unexpected value")]
    UnexpectedValue { error: String },

    #[error("{error}")]
    TicketError {
        error: String,
        code: TicketErrorCode,
    },

    #[error("The account-servicing provider indicated a technical error")]
    ProviderError {
        code: Option<ProviderErrorCode>,
        user_message: Option<String>,
    },

    #[error("Error response")]
    ResponseError { response: String },

    #[error("Resource not found")]
    NotFound,

    #[error("The transaction is not possible without user interaction")]
    InterruptError,
}

#[cfg(feature = "error")]
impl From<Error> for RoutexClientError {
    fn from(error: Error) -> Self {
        match error {
            Error::RequestError(error) => Self::RequestError {
                error: error.to_string(),
            },
            Error::ServiceError(ServiceError::UnexpectedError { user_message, .. }) => {
                Self::UnexpectedError { user_message }
            }
            Error::ServiceError(ServiceError::Canceled { .. }) => Self::Canceled,
            Error::ServiceError(ServiceError::InvalidCredentials { user_message, .. }) => {
                Self::InvalidCredentials { user_message }
            }
            Error::ServiceError(ServiceError::ServiceBlocked {
                user_message, code, ..
            }) => Self::ServiceBlocked { user_message, code },
            Error::ServiceError(ServiceError::Unauthorized { user_message, .. }) => {
                Self::Unauthorized { user_message }
            }
            Error::ServiceError(ServiceError::ConsentExpired { user_message, .. }) => {
                Self::ConsentExpired { user_message }
            }
            Error::ServiceError(ServiceError::AccessExceeded { user_message, .. }) => {
                Self::AccessExceeded { user_message }
            }
            Error::ServiceError(ServiceError::PeriodOutOfBounds { user_message, .. }) => {
                Self::PeriodOutOfBounds { user_message }
            }
            Error::ServiceError(ServiceError::UnsupportedProduct {
                reason,
                user_message,
                ..
            }) => Self::UnsupportedProduct {
                reason,
                user_message,
            },
            Error::ServiceError(ServiceError::PaymentFailed {
                code, user_message, ..
            }) => Self::PaymentFailed { code, user_message },
            Error::ServiceError(ServiceError::UnexpectedValue { error, .. }) => {
                Self::UnexpectedValue { error }
            }
            Error::ServiceError(ServiceError::TicketError { error, code, .. }) => {
                Self::TicketError { error, code }
            }
            Error::ServiceError(ServiceError::ProviderError {
                code, user_message, ..
            }) => Self::ProviderError { code, user_message },
            Error::ServiceError(ServiceError::InterruptError { .. }) => Self::InterruptError,
            Error::ResponseError(response) => Self::ResponseError {
                response: format!("{response:?}"),
            },
            Error::NotFound => Self::NotFound,
        }
    }
}

#[cfg(feature = "error")]
impl From<jsonwebtoken::errors::Error> for RoutexClientError {
    fn from(err: jsonwebtoken::errors::Error) -> Self {
        RoutexClientError::TicketError {
            error: err.to_string(),
            code: routex_api::TicketErrorCode::Invalid,
        }
    }
}

#[cfg(feature = "uniffi")]
pub struct Ticket(String);

#[cfg(feature = "uniffi")]
impl Ticket {
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[cfg(feature = "uniffi")]
uniffi::custom_newtype!(Ticket, String);

#[cfg(feature = "uniffi")]
uniffi::custom_type!(Url, String, {
    remote,
    try_lift: |val| Ok(val.parse()?),
    lower: |obj| obj.into(),
});