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
#![allow(non_upper_case_globals)]

use std::ops::Add;
use std::sync::Arc;
use std::time::{Duration, Instant};
use lazy_static::lazy_static;
use log::debug;
use async_rwlock::RwLock;
use crate::{DEFAULT_TIMEOUT, Error, GOOGLE_OAUTH_V3_USER_INFO_API, GOOGLE_SA_CERTS_URL, GoogleAccessTokenPayload, GooglePayload, IDTokenClientIDNotFoundError, MyResult, utils};
use crate::certs::{Cert, Certs};
use crate::jwt_parser::JwtParser;
use crate::validate::id_token;

lazy_static! {
    static ref ca: reqwest::Client = reqwest::Client::new();
}

/// AsyncClient is an async client to do verification.
#[derive(Debug, Clone)]
pub struct AsyncClient {
    client_ids: Arc<RwLock<Vec<String>>>,
    timeout: Duration,
    cached_certs: Arc<RwLock<Certs>>,
}

impl AsyncClient {
    /// Create a new async client.
    pub fn new<S: ToString>(client_id: S) -> Self {
        let client_id = client_id.to_string();
        Self::new_with_vec([client_id])
    }

    /// Create a new async client, with multiple client ids.
    pub fn new_with_vec<T, V>(client_ids: T) -> Self
        where
            T: AsRef<[V]>,
            V: AsRef<str>,
    {
        Self {
            client_ids: Arc::new(RwLock::new(
                client_ids
                    .as_ref()
                    .iter()
                    .map(|c| c.as_ref())
                    .filter(|c| !c.is_empty())
                    .map(|c| c.to_string())
                    .collect()
            )),
            timeout: Duration::from_secs(DEFAULT_TIMEOUT),
            cached_certs: Arc::default(),
        }
    }

    /// Add a new client_id for future validating.
    ///
    /// Note: this function is thread safe.
    pub async fn add_client_id<T: ToString>(&mut self, client_id: T) {
        let client_id = client_id.to_string();

        if !client_id.is_empty() {
            self.client_ids.write().await.push(client_id)
        }
    }

    /// Remove a client_id, if it exists.
    ///
    /// Note: this function is thread safe.
    pub async fn remove_client_id<T: AsRef<str>>(&mut self, client_id: T) {
        let to_delete = client_id.as_ref();

        if !to_delete.is_empty() {
            let mut client_ids = self.client_ids.write().await;
            client_ids.retain(|id| id != to_delete)
        }
    }

    /// Set the timeout (used in fetching google certs).
    /// Default timeout is 5 seconds. Zero timeout will be ignored.
    pub fn timeout(mut self, d: Duration) -> Self {
        if d.as_nanos() != 0 {
            self.timeout = d;
        }

        self
    }

    /// Do verification with `id_token`. If succeed, return the user data.
    pub async fn validate_id_token<S>(&self, token: S) -> MyResult<GooglePayload>
        where S: AsRef<str>
    {
        // fast check:
        // if there is no given client id, simple return without communicating with Google server.

        let client_ids = self.client_ids.read().await;

        if client_ids.is_empty() {
            return Err(Error::IDTokenClientIDNotFoundError(IDTokenClientIDNotFoundError {
                get: token.as_ref().to_string(),
                expected: Default::default(),
            }))
        }

        let token = token.as_ref();

        let parser: JwtParser<GooglePayload> = JwtParser::parse(token)?;

        id_token::validate_info(&*client_ids, &parser)?;

        let cert = self.get_cert(parser.header.alg.as_str(), parser.header.kid.as_str()).await?;

        id_token::do_validate(&cert, &parser)?;

        Ok(parser.payload)
    }

    async fn get_cert(&self, alg: &str, kid: &str) -> MyResult<Cert> {
        {
            let cached_certs = self.cached_certs.read().await;
            if !cached_certs.need_refresh() {
                debug!("certs: use cache");
                return cached_certs.find_cert(alg, kid);
            }
        }

        debug!("certs: try to fetch new certs");

        let mut cached_certs = self.cached_certs.write().await;

        // refresh certs here...
        let resp = ca.get(GOOGLE_SA_CERTS_URL)
            .timeout(self.timeout)
            .send()
            .await?;

        // parse the response header `age` and `max-age`.
        let max_age = utils::parse_max_age_from_async_resp(&resp);

        let text = resp.text().await?;
        *cached_certs = serde_json::from_str(&text)?;

        cached_certs.set_cache_until(
            Instant::now().add(Duration::from_secs(max_age))
        );

        cached_certs.find_cert(alg, kid)
    }

    /// Try to validate access token. If succeed, return the user info.
    pub async fn validate_access_token<S>(&self, token: S) -> MyResult<GoogleAccessTokenPayload>
        where S: AsRef<str>
    {
        let token = token.as_ref();

        let info = ca.get(format!("{}?access_token={}", GOOGLE_OAUTH_V3_USER_INFO_API, token))
            .timeout(self.timeout)
            .send()
            .await?
            .text()
            .await?;

        let payload = serde_json::from_str(&info)?;

        Ok(payload)
    }
}

impl Default for AsyncClient {
    fn default() -> Self {
        Self::new_with_vec::<&[_; 0], &'static str>(&[])
    }
}