posemesh-domain-http 1.5.3

HTTP client library for interacting with AukiLabs domain data services, supporting both native and WebAssembly targets.
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
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
use base64::{Engine as _, engine::general_purpose};
use futures::lock::Mutex;
use reqwest::Client;
use serde::{Deserialize, Serialize};

use posemesh_utils::now_unix_secs;
use std::sync::Arc;

use crate::errors::{AukiErrorResponse, AuthError, DomainError};

#[derive(Debug, Clone)]
pub struct AuthClient {
    pub api_url: String,
    client: Client,
    dds_token_cache: Arc<Mutex<Option<DdsTokenCache>>>,
    user_token_cache: Arc<Mutex<Option<UserTokenCache>>>,
    pub client_id: String,
    app_key: Option<String>,
    app_secret: Option<String>,
}

#[derive(Debug, Clone)]
pub struct UserTokenCache {
    refresh_token: String,
    access_token: String,
    expires_at: u64,
}

impl TokenCache for UserTokenCache {
    fn get_access_token(&self) -> String {
        self.access_token.clone()
    }

    fn get_expires_at(&self) -> u64 {
        self.expires_at
    }
}

#[derive(Debug, Clone)]
pub(crate) struct DdsTokenCache {
    // DDS access token
    access_token: String,
    claim: JwtClaim,
}

impl TokenCache for DdsTokenCache {
    fn get_access_token(&self) -> String {
        self.access_token.clone()
    }

    fn get_expires_at(&self) -> u64 {
        self.claim.exp
    }
}

impl Default for DdsTokenCache {
    fn default() -> Self {
        Self {
            access_token: "".to_string(),
            claim: JwtClaim { exp: 0, org: None },
        }
    }
}
pub(crate) trait TokenCache {
    fn get_access_token(&self) -> String;
    fn get_expires_at(&self) -> u64;
}

#[derive(Debug, Serialize)]
pub struct UserCredentials {
    pub email: String,
    pub password: String,
}

#[derive(Debug, Deserialize)]
pub struct UserTokenResponse {
    pub access_token: String,
    pub refresh_token: String,
}

#[derive(Debug, Deserialize)]
pub struct DdsTokenResponse {
    pub access_token: String,
}

impl AuthClient {
    pub fn new(api_url: &str, client_id: &str) -> Self {
        Self {
            api_url: api_url.to_string(),
            client: Client::new(),
            dds_token_cache: Arc::new(Mutex::new(None)),
            user_token_cache: Arc::new(Mutex::new(None)),
            client_id: client_id.to_string(),
            app_key: None,
            app_secret: None,
        }
    }

    /// Get the expiration time of the user refresh token or DDS access token
    pub async fn get_expires_at(&self) -> Result<u64, DomainError> {
        let token_cache = {
            let cache = self.user_token_cache.lock().await;
            cache.clone()
        };
        if token_cache.is_none() {
            let dds_token_cache = {
                let cache = self.dds_token_cache.lock().await;
                cache.clone()
            };
            if dds_token_cache.is_none() {
                return Err(DomainError::AuthError(AuthError::Unauthorized(
                    "No token found",
                )));
            }
            return Ok(dds_token_cache.unwrap().claim.exp);
        }
        Ok(parse_jwt(&token_cache.unwrap().refresh_token)?.exp)
    }

    pub async fn sign_in_with_app_credentials(
        &mut self,
        app_key: &str,
        app_secret: &str,
    ) -> Result<String, DomainError> {
        self.app_key = Some(app_key.to_string());
        self.app_secret = Some(app_secret.to_string());
        *self.dds_token_cache.lock().await = None;
        *self.user_token_cache.lock().await = None;

        self.get_dds_app_access_token().await
    }

    // Get DDS access token with either app credentials or user access token or oidc_access_token, it checks the cache first, if found and not about to expire, return the cached token
    // if not found or about to expire, it fetches a new token with app credentials or user access token or oidc_access_token and sets the cache.
    // If user access token is about to expire, it refreshes the user access token with refresh token first and sets the cache.
    // It clears all caches if there is an error.
    pub async fn get_dds_access_token(
        &self,
        oidc_access_token: Option<&str>,
    ) -> Result<String, DomainError> {
        let result = if let Some(oidc_access_token) = oidc_access_token {
            self.get_dds_access_token_with_oidc_access_token(oidc_access_token)
                .await
        } else if self.app_key.is_some() {
            self.get_dds_app_access_token().await
        } else {
            self.get_dds_user_access_token().await
        };

        if result.is_err() {
            *self.dds_token_cache.lock().await = None;
            *self.user_token_cache.lock().await = None;
        }

        result
    }

    // Get DDS access token with OIDC access token, doesn't cache
    async fn get_dds_access_token_with_oidc_access_token(
        &self,
        oidc_access_token: &str,
    ) -> Result<String, DomainError> {
        // Clear all caches before proceeding
        *self.dds_token_cache.lock().await = None;
        *self.user_token_cache.lock().await = None;

        let response = self.get_dds_token_by_token(oidc_access_token).await?;
        {
            let mut cache = self.dds_token_cache.lock().await;
            *cache = Some(DdsTokenCache {
                access_token: response.access_token.clone(),
                claim: parse_jwt(&response.access_token)?,
            });
        }
        Ok(response.access_token)
    }

    // Get DDS access token with app credentials, it checks the cache first, if found and not about to expire, return the cached token
    // if not found or about to expire, fetch a new token with app credentials and sets the cache.
    async fn get_dds_app_access_token(&self) -> Result<String, DomainError> {
        let token_cache = {
            let cache = self.dds_token_cache.lock().await;
            cache.clone()
        };

        let app_key = self
            .app_key
            .clone()
            .ok_or(AuthError::Unauthorized("App key is not set"))?;
        let app_secret = self
            .app_secret
            .clone()
            .ok_or(AuthError::Unauthorized("App secret is not set"))?;

        let token_cache = get_cached_or_fresh_token(
            &token_cache.unwrap_or(DdsTokenCache {
                access_token: "".to_string(),
                claim: JwtClaim { exp: 0, org: None },
            }),
            || {
                let app_key = app_key.to_string();
                let app_secret = app_secret.to_string();
                let client = self.client.clone();
                let api_url = self.api_url.clone();
                let client_id = self.client_id.clone();
                async move {
                    let response = client
                        .post(format!("{}/service/domains-access-token", api_url))
                        .basic_auth(app_key, Some(app_secret))
                        .header("Content-Type", "application/json")
                        .header("posemesh-client-id", client_id)
                        .send()
                        .await?;

                    if response.status().is_success() {
                        let token_response: DdsTokenResponse = response.json().await?;
                        Ok(DdsTokenCache {
                            access_token: token_response.access_token.clone(),
                            claim: parse_jwt(&token_response.access_token)?,
                        })
                    } else {
                        let status = response.status();
                        let text = response
                            .text()
                            .await
                            .unwrap_or_else(|_| "Unknown error".to_string());
                        Err(AukiErrorResponse {
                            status,
                            error: format!("Failed to get DDS access token. {}", text),
                        }
                        .into())
                    }
                }
            },
        )
        .await?;

        {
            let mut cache = self.dds_token_cache.lock().await;
            *cache = Some(token_cache.clone());
        }

        Ok(token_cache.access_token)
    }

    // Get DDS access token with user credentials, it checks the cache first, if found and not about to expire, return the cached token
    // if not found or about to expire, it fetches a new token with user access token and sets the cache.
    // If user access token is about to expire, it refreshes the user access token with refresh token first and sets the cache.
    async fn get_dds_user_access_token(&self) -> Result<String, DomainError> {
        let token_cache = {
            let cache = self.dds_token_cache.lock().await;
            cache.clone()
        };

        if token_cache.is_none() {
            return Err(AuthError::Unauthorized("No user access token found").into());
        }

        let user_token_cache = {
            let cache = self.user_token_cache.lock().await;
            cache.clone()
        };

        if user_token_cache.is_none() {
            return Err(AuthError::Unauthorized("Login first").into());
        }

        let token_cache = get_cached_or_fresh_token(&token_cache.unwrap(), || {
            let client = self.client.clone();
            let api_url = self.api_url.clone();
            let client_id = self.client_id.clone();

            async move {
                let client_clone = client.clone();
                let api_url_clone = api_url.clone();
                let client_id_clone = client_id.clone();
                let refresh_token = user_token_cache.clone().unwrap().refresh_token;
                let user_token_cache =
                    get_cached_or_fresh_token(&user_token_cache.unwrap(), || async move {
                        let response = client_clone
                            .post(format!("{}/user/refresh", api_url_clone))
                            .header("Content-Type", "application/json")
                            .header("posemesh-client-id", client_id_clone)
                            .header("Authorization", format!("Bearer {}", refresh_token))
                            .send()
                            .await
                            .expect("Failed to refresh token");

                        if response.status().is_success() {
                            let token_response: UserTokenResponse = response.json().await?;
                            Ok(UserTokenCache {
                                refresh_token: token_response.refresh_token.clone(),
                                access_token: token_response.access_token.clone(),
                                expires_at: parse_jwt(&token_response.access_token)?.exp,
                            })
                        } else {
                            let status = response.status();
                            let text = response
                                .text()
                                .await
                                .unwrap_or_else(|_| "Unknown error".to_string());
                            Err(AukiErrorResponse {
                                status,
                                error: format!("Failed to refresh token. {}", text),
                            }
                            .into())
                        }
                    })
                    .await?;

                {
                    let mut cache = self.user_token_cache.lock().await;
                    *cache = Some(user_token_cache.clone());
                }

                let dds_token_response = self
                    .get_dds_token_by_token(&user_token_cache.access_token)
                    .await?;

                let dds_cache = DdsTokenCache {
                    access_token: dds_token_response.access_token.clone(),
                    claim: parse_jwt(&dds_token_response.access_token)?,
                };
                {
                    let mut cache = self.dds_token_cache.lock().await;
                    *cache = Some(dds_cache.clone());
                }
                Ok(dds_cache)
            }
        })
        .await?;

        {
            let mut cache = self.dds_token_cache.lock().await;
            *cache = Some(token_cache.clone());
        }

        Ok(token_cache.access_token)
    }

    // Login with user credentials, return DDS access token. It clears all caches and sets the app credentials to none.
    pub async fn user_login(&mut self, email: &str, password: &str) -> Result<String, DomainError> {
        self.app_key = None;
        self.app_secret = None;

        let credentials = UserCredentials {
            email: email.to_string(),
            password: password.to_string(),
        };

        let response = self
            .client
            .post(format!("{}/user/login", &self.api_url))
            .header("Content-Type", "application/json")
            .header("posemesh-client-id", &self.client_id)
            .json(&credentials)
            .send()
            .await?;

        if response.status().is_success() {
            let token_response: UserTokenResponse = response.json().await?;
            {
                let mut cache = self.user_token_cache.lock().await;
                *cache = Some(UserTokenCache {
                    refresh_token: token_response.refresh_token.clone(),
                    access_token: token_response.access_token.clone(),
                    expires_at: parse_jwt(&token_response.access_token)?.exp,
                });
            }

            let dds_token_response = self
                .get_dds_token_by_token(&token_response.access_token)
                .await?;
            let mut cache = self.dds_token_cache.lock().await;
            let token_cache = DdsTokenCache {
                access_token: dds_token_response.access_token.clone(),
                claim: parse_jwt(&dds_token_response.access_token)?,
            };
            *cache = Some(token_cache.clone());
            Ok(token_cache.access_token)
        } else {
            let status = response.status();
            let text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());

            Err(AukiErrorResponse {
                status,
                error: format!("Failed to login. {}", text),
            }
            .into())
        }
    }

    // Get DDS access token with either user access token or oidc_access_token, doesn't cache
    async fn get_dds_token_by_token(&self, token: &str) -> Result<DdsTokenResponse, DomainError> {
        let dds_response = self
            .client
            .post(format!("{}/service/domains-access-token", &self.api_url))
            .header("Authorization", format!("Bearer {}", token))
            .header("Content-Type", "application/json")
            .header("posemesh-client-id", &self.client_id)
            .send()
            .await?;

        if dds_response.status().is_success() {
            dds_response
                .json::<DdsTokenResponse>()
                .await
                .map_err(|e| e.into())
        } else {
            let status = dds_response.status();
            let text = dds_response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            Err(AukiErrorResponse {
                status,
                error: format!("Failed to get DDS access token. {}", text),
            }
            .into())
        }
    }
}

pub const REFRESH_CACHE_TIME: u64 = 60; // 1 minute

pub(crate) async fn get_cached_or_fresh_token<R, F, Fut>(
    cache: &R,
    token_fetcher: F,
) -> Result<R, DomainError>
where
    F: FnOnce() -> Fut,
    R: TokenCache + Clone,
    Fut: std::future::Future<Output = Result<R, DomainError>>,
{
    // Check if we have a valid cached token
    let expires_at = cache.get_expires_at();
    let current_time = now_unix_secs();
    // If token expires in more than REFRESH_CACHE_TIME seconds, return cached token
    if expires_at > current_time && expires_at - current_time > REFRESH_CACHE_TIME {
        return Ok(cache.clone());
    }

    // Fetch new token
    token_fetcher().await
}

#[derive(Debug, Deserialize, Clone)]
pub struct JwtClaim {
    pub exp: u64,
    pub org: Option<String>,
}

pub fn parse_jwt(token: &str) -> Result<JwtClaim, AuthError> {
    let parts = token.split('.').collect::<Vec<&str>>();
    if parts.len() != 3 {
        return Err(AuthError::Unauthorized("Invalid JWT token"));
    }
    let payload = parts[1];
    let decoded = general_purpose::URL_SAFE_NO_PAD.decode(payload)?;
    let claims: JwtClaim = serde_json::from_slice(&decoded)?;
    Ok(claims)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::time::{SystemTime, UNIX_EPOCH};
    use tokio::sync::Mutex;

    #[derive(Clone, Debug)]
    struct DummyTokenCache {
        access_token: String,
        expires_at: u64,
    }

    impl TokenCache for DummyTokenCache {
        fn get_access_token(&self) -> String {
            self.access_token.clone()
        }
        fn get_expires_at(&self) -> u64 {
            self.expires_at
        }
    }

    fn now_unix_secs() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
    }

    fn make_jwt(exp: u64) -> String {
        // Header: {"alg":"HS256","typ":"JWT"}
        // Payload: {"exp":exp}
        let header = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .encode(r#"{"alg":"HS256","typ":"JWT"}"#);
        let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .encode(format!(r#"{{"exp":{}}}"#, exp));
        format!("{}.{}.sig", header, payload)
    }

    #[tokio::test]
    async fn test_ddstoken_about_to_expire_should_refetch() {
        // Token expires in 2 seconds (less than REFRESH_CACHE_TIME)
        let now = now_unix_secs();
        let expiring_soon = now + 2;
        let cache = DummyTokenCache {
            access_token: make_jwt(expiring_soon),
            expires_at: expiring_soon,
        };

        let fetch_called = Arc::new(Mutex::new(false));
        let fetch_called_clone = fetch_called.clone();

        let new_exp = now + 1000;
        let token_fetcher = move || {
            let fetch_called_clone = fetch_called_clone.clone();
            async move {
                *fetch_called_clone.lock().await = true;
                let token = DummyTokenCache {
                    access_token: make_jwt(new_exp),
                    expires_at: new_exp,
                };
                // set_expires_at will be called by get_cached_or_fresh_token
                Ok(token)
            }
        };

        let result = get_cached_or_fresh_token(&cache, token_fetcher)
            .await
            .unwrap();
        // Should have called fetcher
        assert!(
            *fetch_called.lock().await,
            "Fetcher should have been called"
        );
        // Should have new expiration
        assert_eq!(result.expires_at, new_exp);
    }

    #[tokio::test]
    async fn test_ddstoken_not_expiring_should_use_cache() {
        // Token expires in 100 seconds (more than REFRESH_CACHE_TIME)
        let now = now_unix_secs();
        let not_expiring = now + 100;
        let cache = DummyTokenCache {
            access_token: make_jwt(not_expiring),
            expires_at: not_expiring,
        };

        let fetch_called = Arc::new(Mutex::new(false));
        let fetch_called_clone = fetch_called.clone();

        let cache_clone = cache.clone();
        let token_fetcher = move || {
            let fetch_called_clone = fetch_called_clone.clone();
            async move {
                *fetch_called_clone.lock().await = true;
                Ok(cache_clone.clone())
            }
        };

        let result = get_cached_or_fresh_token(&cache, token_fetcher)
            .await
            .unwrap();
        // Should NOT have called fetcher
        assert!(
            !*fetch_called.lock().await,
            "Fetcher should NOT have been called"
        );
        // Should have same expiration
        assert_eq!(result.expires_at, not_expiring);
    }
}