apisdk 0.0.6

An easy-to-use API toolkit for writing HTTP API Clients for Rust.
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
use std::{any::type_name, num::ParseIntError, string::FromUtf8Error, sync::Arc, time::SystemTime};

use async_trait::async_trait;
use base64::DecodeError;
use reqwest::{
    header::{HeaderName, HeaderValue, AUTHORIZATION},
    Request, Response,
};
use reqwest_middleware::Next;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{
    digest::{self, decode_base64},
    Extensions, Middleware,
};

/// This middleware is used to sign the request
#[derive(Default)]
pub(crate) struct SignatureMiddleware;

#[async_trait]
impl Middleware for SignatureMiddleware {
    async fn handle(
        &self,
        req: Request,
        extensions: &mut Extensions,
        next: Next<'_>,
    ) -> Result<Response, reqwest_middleware::Error> {
        let mut req = req;

        // Sign the request by using ApiSignature
        if let Some(signatue) = extensions.get::<Arc<dyn ApiSignature>>() {
            req = signatue.sign(req, extensions).await?;
        }

        next.run(req, extensions).await
    }
}

/// This trait is used to generate token
#[async_trait]
pub trait TokenProvider: 'static + Send + Sync {
    /// Generate a new token
    async fn generate_token(&self, req: &Request) -> Result<String, reqwest_middleware::Error>;
}

#[async_trait]
impl<F, T> TokenProvider for F
where
    F: 'static + Send + Sync,
    F: Fn() -> Result<T, reqwest_middleware::Error>,
    T: ToString,
{
    async fn generate_token(&self, _req: &Request) -> Result<String, reqwest_middleware::Error> {
        self().map(|t| t.to_string())
    }
}

/// This trait is used to sign request
#[async_trait]
pub trait ApiSignature: TokenProvider {
    /// Get type_name, used in Debug
    fn type_name(&self) -> &str {
        type_name::<Self>()
    }

    /// Get `Carrier`
    fn get_carrier(&self) -> &Carrier {
        &Carrier::BearerAuth
    }

    /// Sign request
    /// - req: HTTP request
    /// - extensions: Extensions
    async fn sign(
        &self,
        req: Request,
        _extensions: &Extensions,
    ) -> Result<Request, reqwest_middleware::Error> {
        let token = self.generate_token(&req).await?;
        Ok(self.get_carrier().apply(req, token))
    }
}

#[async_trait]
impl TokenProvider for Box<dyn ApiSignature> {
    async fn generate_token(&self, req: &Request) -> Result<String, reqwest_middleware::Error> {
        self.as_ref().generate_token(req).await
    }
}

#[async_trait]
impl ApiSignature for Box<dyn ApiSignature> {
    fn get_carrier(&self) -> &Carrier {
        self.as_ref().get_carrier()
    }

    async fn sign(
        &self,
        req: Request,
        extensions: &Extensions,
    ) -> Result<Request, reqwest_middleware::Error> {
        self.as_ref().sign(req, extensions).await
    }
}

/// This trait is used to update signature
pub trait SignatureTrait {
    /// Update signature to use `Carrier`
    fn with_carrier(self, carrier: Carrier) -> Self;

    /// Update signature to use `Header`
    /// - name: the name of header
    fn with_header_name(self, name: impl ToString) -> Self;

    /// Update signature to use `QueryParam`
    /// - name: the name of query param
    fn with_query_param(self, name: impl ToString) -> Self;
}

/// This enum represents the position of request to carry token.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub enum Carrier {
    /// Standard `Authorization` header, with `Bearer` auth-scheme
    #[default]
    BearerAuth,
    /// Standard `Authorization` header, without any auth-scheme
    SchemelessAuth,
    /// Customized header
    Header(String),
    /// Customized query param
    QueryParam(String),
}

impl Carrier {
    /// Apply the changes to request
    pub fn apply(&self, req: Request, token: impl ToString) -> Request {
        let mut req = req;
        let token = token.to_string();
        match self {
            Carrier::BearerAuth => {
                req.headers_mut().insert(
                    AUTHORIZATION,
                    HeaderValue::try_from(format!("Bearer {}", token)).unwrap(),
                );
            }
            Carrier::SchemelessAuth => {
                req.headers_mut()
                    .insert(AUTHORIZATION, HeaderValue::try_from(token).unwrap());
            }
            Carrier::Header(name) => {
                req.headers_mut().append(
                    HeaderName::try_from(name.as_str()).unwrap(),
                    HeaderValue::try_from(token).unwrap(),
                );
            }
            Carrier::QueryParam(name) => {
                req.url_mut()
                    .query_pairs_mut()
                    .append_pair(name.as_str(), &token);
            }
        }
        req
    }
}

/// This enum holds `access_token`, which used to sign request
pub enum AccessToken {
    /// Immutable token
    Fixed(String),
    /// Dynamic token, which will be retrieved from provider
    Dynamic(Arc<dyn TokenProvider>),
}

impl std::fmt::Debug for AccessToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Fixed(_) => f.debug_tuple("Fixed").finish(),
            Self::Dynamic(_) => f.debug_tuple("Dynamic").finish(),
        }
    }
}

/// This struct is used to sign request by using `access_token`
#[derive(Debug)]
pub struct AccessTokenSignature {
    access_token: AccessToken,
    carrier: Carrier,
}

impl AccessTokenSignature {
    /// Build for immutable token
    pub fn new(access_token: impl ToString) -> Self {
        Self {
            access_token: AccessToken::Fixed(access_token.to_string()),
            carrier: Carrier::default(),
        }
    }

    /// Build for dynamic token
    pub fn new_dynamic(provider: impl TokenProvider) -> Self {
        Self {
            access_token: AccessToken::Dynamic(Arc::new(provider)),
            carrier: Carrier::default(),
        }
    }
}

#[async_trait]
impl ApiSignature for AccessTokenSignature {
    fn get_carrier(&self) -> &Carrier {
        &self.carrier
    }
}

#[async_trait]
impl TokenProvider for AccessTokenSignature {
    async fn generate_token(&self, req: &Request) -> Result<String, reqwest_middleware::Error> {
        match &self.access_token {
            AccessToken::Fixed(token) => Ok(token.clone()),
            AccessToken::Dynamic(provider) => provider.generate_token(req).await,
        }
    }
}

impl SignatureTrait for AccessTokenSignature {
    fn with_carrier(self, carrier: Carrier) -> Self {
        Self { carrier, ..self }
    }

    fn with_header_name(self, name: impl ToString) -> Self {
        Self {
            carrier: Carrier::Header(name.to_string()),
            ..self
        }
    }

    fn with_query_param(self, name: impl ToString) -> Self {
        Self {
            carrier: Carrier::QueryParam(name.to_string()),
            ..self
        }
    }
}

/// Hash algorithm
#[derive(Debug)]
pub enum HashAlgorithm {
    Md5,
    Sha1,
    Sha256,
}

impl HashAlgorithm {
    /// Calc hash value
    pub fn apply(&self, input: impl AsRef<[u8]>) -> String {
        match self {
            Self::Md5 => digest::md5(input),
            Self::Sha1 => digest::sha1(input),
            Self::Sha256 => digest::sha256(input),
        }
    }
}

impl From<String> for HashAlgorithm {
    fn from(s: String) -> Self {
        s.as_str().into()
    }
}

impl From<&str> for HashAlgorithm {
    fn from(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "sha1" => Self::Sha1,
            "md5" => Self::Md5,
            "sha256" => Self::Sha256,
            _ => Self::Sha1,
        }
    }
}

/// This struct is used to sign request by hashed token.
///
/// # Generate token algorithm
///
/// ```
/// hash = md5 | sha1(default) | sha256
/// timestamp = UNIX_TIMESTAMP (in second)
/// sign = hash($app_id + $app_secret + $timestamp)
/// token = base64($client_id + "," + $app_id + "," + $timestamp + "," + $sign)
///       = (or) base64($app_id + "," + $timestamp + "," + $sign)
/// ```
///
/// # Parse token
///
/// ```rust
/// let token = "xxx";
/// let parsed_token = ParsedHashedToken::parse(token)?;
/// if parsed_token.is_expired(60 * 5, None) {
///     // Expired Token
/// } else if parsed_token.is_signed("my-secret-key", HashAlgorithm::MD5) {
///     // Invalid Token
/// }
/// ```
#[derive(Debug)]
pub struct HashedTokenSignature {
    client_id: Option<String>,
    app_id: String,
    app_secret: String,
    algorithm: HashAlgorithm,
    carrier: Carrier,
}

impl HashedTokenSignature {
    pub fn new<S: ToString>(app_id: S, app_secret: S) -> Self {
        Self::new_with_algorithm(app_id, app_secret, HashAlgorithm::Sha1)
    }

    pub fn new_with_algorithm<S: ToString>(
        app_id: S,
        app_secret: S,
        algorithm: HashAlgorithm,
    ) -> Self {
        Self {
            client_id: None,
            app_id: app_id.to_string(),
            app_secret: app_secret.to_string(),
            algorithm,
            carrier: Carrier::default(),
        }
    }

    pub fn new_with_client_id<S: ToString>(
        client_id: S,
        app_id: S,
        app_secret: S,
        algorithm: HashAlgorithm,
    ) -> Self {
        Self {
            client_id: match client_id.to_string() {
                id if id.is_empty() => None,
                id => Some(id),
            },
            app_id: app_id.to_string(),
            app_secret: app_secret.to_string(),
            algorithm,
            carrier: Carrier::default(),
        }
    }

    /// Generate token
    fn generate_token_at(&self, timestamp: u64) -> String {
        // Hash
        let plain = format!("{}{}{}", &self.app_id, &self.app_secret, timestamp);
        let sign = self.algorithm.apply(plain);

        // Compose
        let compose = match &self.client_id {
            Some(client_id) => format!("{},{},{},{}", client_id, &self.app_id, timestamp, sign),
            None => format!("{},{},{}", &self.app_id, timestamp, sign),
        };
        digest::encode_base64(compose)
    }
}

#[async_trait]
impl ApiSignature for HashedTokenSignature {
    fn get_carrier(&self) -> &Carrier {
        &self.carrier
    }
}

#[async_trait]
impl TokenProvider for HashedTokenSignature {
    async fn generate_token(&self, _req: &Request) -> Result<String, reqwest_middleware::Error> {
        let timestamp = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        Ok(self.generate_token_at(timestamp))
    }
}

impl SignatureTrait for HashedTokenSignature {
    fn with_carrier(self, carrier: Carrier) -> Self {
        Self { carrier, ..self }
    }

    fn with_header_name(self, name: impl ToString) -> Self {
        Self {
            carrier: Carrier::Header(name.to_string()),
            ..self
        }
    }

    fn with_query_param(self, name: impl ToString) -> Self {
        Self {
            carrier: Carrier::QueryParam(name.to_string()),
            ..self
        }
    }
}

/// Token Error
#[derive(Debug, Error)]
pub enum TokenError {
    /// Base64 decode error
    #[error("{0}")]
    Base64(#[from] DecodeError),
    /// Utf8 decode error
    #[error("{0}")]
    Utf8(#[from] FromUtf8Error),
    /// Invalid format
    #[error("Invalid format")]
    Format,
    /// Invalid timestamp
    #[error("{0}")]
    Timestamp(#[from] ParseIntError),
}

/// This struct is used to parse token
#[derive(Debug)]
pub struct ParsedHashedToken {
    /// client_id
    pub client_id: Option<String>,
    /// app_id
    pub app_id: String,
    /// timestamp, in second
    pub timestamp: u64,
    /// sign
    pub sign: String,
}

impl ParsedHashedToken {
    /// Parse the token
    pub fn parse(token: impl AsRef<[u8]>) -> Result<Self, TokenError> {
        let token = token.as_ref();
        if token.is_empty() {
            return Err(TokenError::Format);
        }

        let composed = decode_base64(token)
            .map_err(|e| TokenError::Base64(e))
            .and_then(|b| String::from_utf8(b).map_err(|e| TokenError::Utf8(e)))?;
        let terms: Vec<&str> = composed.split(',').collect();
        let mut iter = terms.iter();
        match terms.len() {
            4 => Ok(Self {
                client_id: Some(iter.next().unwrap().to_string()),
                app_id: iter.next().unwrap().to_string(),
                timestamp: iter
                    .next()
                    .unwrap()
                    .parse()
                    .map_err(|e| TokenError::Timestamp(e))?,
                sign: iter.next().unwrap().to_string(),
            }),
            3 => Ok(Self {
                client_id: None,
                app_id: iter.next().unwrap().to_string(),
                timestamp: iter
                    .next()
                    .unwrap()
                    .parse()
                    .map_err(|e| TokenError::Timestamp(e))?,
                sign: iter.next().unwrap().to_string(),
            }),
            _ => Err(TokenError::Format),
        }
    }

    /// Check the token is expired or not
    /// - deviation: 1 min as default
    pub fn is_expired(&self, expires_in_secs: u64, deviation: Option<u64>) -> bool {
        let deviation = deviation.unwrap_or(60) as i64;
        let now = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let diff = now as i64 - self.timestamp as i64;
        diff < -deviation || diff > expires_in_secs as i64 + deviation
    }

    /// Check the token is signed or not
    pub fn is_signed<S, A>(&self, app_secret: S, algorithm: A) -> bool
    where
        S: std::fmt::Display,
        A: Into<HashAlgorithm>,
    {
        // Sign
        let plain = format!("{}{}{}", self.app_id, app_secret, self.timestamp);
        let algorithm: HashAlgorithm = algorithm.into();
        let sign = algorithm.apply(plain);

        sign == self.sign
    }
}

impl TryFrom<&str> for ParsedHashedToken {
    type Error = TokenError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl TryFrom<String> for ParsedHashedToken {
    type Error = TokenError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}