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
use crate::authenticator_delegate::{AuthenticatorDelegate, Retry};
use crate::refresh::RefreshFlow;
use crate::storage::{hash_scopes, DiskTokenStorage, MemoryStorage, TokenStorage};
use crate::types::{ApplicationSecret, GetToken, RefreshResult, RequestError, Token};

use futures::{future, prelude::*};
use tokio_timer;

use std::error::Error;
use std::io;
use std::sync::{Arc, Mutex};

/// Authenticator abstracts different `GetToken` implementations behind one type and handles
/// caching received tokens. It's important to use it (instead of the flows directly) because
/// otherwise the user needs to be asked for new authorization every time a token is generated.
///
/// `ServiceAccountAccess` does not need (and does not work) with `Authenticator`, given that it
/// does not require interaction and implements its own caching. Use it directly.
///
/// NOTE: It is recommended to use a client constructed like this in order to prevent functions
/// like `hyper::run()` from hanging: `let client = hyper::Client::builder().keep_alive(false);`.
/// Due to token requests being rare, this should not result in a too bad performance problem.
pub struct Authenticator<
    T: GetToken,
    S: TokenStorage,
    AD: AuthenticatorDelegate,
    C: hyper::client::connect::Connect,
> {
    client: hyper::Client<C>,
    inner: Arc<Mutex<T>>,
    store: Arc<Mutex<S>>,
    delegate: AD,
}

impl<T: GetToken, AD: AuthenticatorDelegate, C: hyper::client::connect::Connect>
    Authenticator<T, MemoryStorage, AD, C>
{
    /// Create an Authenticator caching tokens for the duration of this authenticator.
    pub fn new(
        client: hyper::Client<C>,
        inner: T,
        delegate: AD,
    ) -> Authenticator<T, MemoryStorage, AD, C> {
        Authenticator {
            client: client,
            inner: Arc::new(Mutex::new(inner)),
            store: Arc::new(Mutex::new(MemoryStorage::new())),
            delegate: delegate,
        }
    }
}

impl<T: GetToken, AD: AuthenticatorDelegate, C: hyper::client::connect::Connect>
    Authenticator<T, DiskTokenStorage, AD, C>
{
    /// Create an Authenticator using the store at `path`.
    pub fn new_disk<P: AsRef<str>>(
        client: hyper::Client<C>,
        inner: T,
        delegate: AD,
        token_storage_path: P,
    ) -> io::Result<Authenticator<T, DiskTokenStorage, AD, C>> {
        Ok(Authenticator {
            client: client,
            inner: Arc::new(Mutex::new(inner)),
            store: Arc::new(Mutex::new(DiskTokenStorage::new(token_storage_path)?)),
            delegate: delegate,
        })
    }
}

impl<
        GT: 'static + GetToken + Send,
        S: 'static + TokenStorage + Send,
        AD: 'static + AuthenticatorDelegate + Send,
        C: 'static + hyper::client::connect::Connect + Clone + Send,
    > GetToken for Authenticator<GT, S, AD, C>
{
    /// Returns the API Key of the inner flow.
    fn api_key(&mut self) -> Option<String> {
        self.inner.lock().unwrap().api_key()
    }
    /// Returns the application secret of the inner flow.
    fn application_secret(&self) -> ApplicationSecret {
        self.inner.lock().unwrap().application_secret()
    }

    fn token<I, T>(
        &mut self,
        scopes: I,
    ) -> Box<dyn Future<Item = Token, Error = RequestError> + Send>
    where
        T: Into<String>,
        I: IntoIterator<Item = T>,
    {
        let (scope_key, scopes) = hash_scopes(scopes);
        let store = self.store.clone();
        let mut delegate = self.delegate.clone();
        let client = self.client.clone();
        let appsecret = self.inner.lock().unwrap().application_secret();
        let gettoken = self.inner.clone();
        let loopfn = move |()| -> Box<
            dyn Future<Item = future::Loop<Token, ()>, Error = RequestError> + Send,
        > {
            // How well does this work with tokio?
            match store.lock().unwrap().get(
                scope_key.clone(),
                &scopes.iter().map(|s| s.as_str()).collect(),
            ) {
                Ok(Some(t)) => {
                    if !t.expired() {
                        return Box::new(Ok(future::Loop::Break(t)).into_future());
                    }
                    // Implement refresh flow.
                    let refresh_token = t.refresh_token.clone();
                    let mut delegate = delegate.clone();
                    let store = store.clone();
                    let scopes = scopes.clone();
                    let refresh_fut = RefreshFlow::refresh_token(
                        client.clone(),
                        appsecret.clone(),
                        refresh_token,
                    )
                        .and_then(move |rr| -> Box<dyn Future<Item=future::Loop<Token, ()>, Error=RequestError> + Send> {
                            match rr {
                                RefreshResult::Error(ref e) => {
                                    delegate.token_refresh_failed(
                                        format!("{}", e.description().to_string()),
                                        &Some("the request has likely timed out".to_string()),
                                        );
                                    Box::new(Err(RequestError::Refresh(rr)).into_future())
                                }
                                RefreshResult::RefreshError(ref s, ref ss) => {
                                    delegate.token_refresh_failed(
                                        format!("{} {}", s, ss.clone().map(|s| format!("({})", s)).unwrap_or("".to_string())),
                                        &Some("the refresh token is likely invalid and your authorization has been revoked".to_string()),
                                        );
                                    Box::new(Err(RequestError::Refresh(rr)).into_future())
                                }
                                RefreshResult::Success(t) => {
                                    if let Err(e) = store.lock().unwrap().set(scope_key, &scopes.iter().map(|s| s.as_str()).collect(), Some(t.clone())) {
                                        match delegate.token_storage_failure(true, &e) {
                                            Retry::Skip => Box::new(Ok(future::Loop::Break(t)).into_future()),
                                            Retry::Abort => Box::new(Err(RequestError::Cache(Box::new(e))).into_future()),
                                            Retry::After(d) => Box::new(
                                                tokio_timer::sleep(d)
                                                .then(|_| Ok(future::Loop::Continue(()))),
                                                )
                                                as Box<
                                                dyn Future<
                                                Item = future::Loop<Token, ()>,
                                                Error = RequestError> + Send>,
                                        }
                                    } else {
                                        Box::new(Ok(future::Loop::Break(t)).into_future())
                                    }
                                },
                            }
                        });
                    Box::new(refresh_fut)
                }
                Ok(None) => {
                    let store = store.clone();
                    let scopes = scopes.clone();
                    let mut delegate = delegate.clone();
                    Box::new(
                        gettoken
                            .lock()
                            .unwrap()
                            .token(scopes.clone())
                            .and_then(move |t| {
                                if let Err(e) = store.lock().unwrap().set(
                                    scope_key,
                                    &scopes.iter().map(|s| s.as_str()).collect(),
                                    Some(t.clone()),
                                ) {
                                    match delegate.token_storage_failure(true, &e) {
                                        Retry::Skip => {
                                            Box::new(Ok(future::Loop::Break(t)).into_future())
                                        }
                                        Retry::Abort => Box::new(
                                            Err(RequestError::Cache(Box::new(e))).into_future(),
                                        ),
                                        Retry::After(d) => Box::new(
                                            tokio_timer::sleep(d)
                                                .then(|_| Ok(future::Loop::Continue(()))),
                                        )
                                            as Box<
                                                dyn Future<
                                                        Item = future::Loop<Token, ()>,
                                                        Error = RequestError,
                                                    > + Send,
                                            >,
                                    }
                                } else {
                                    Box::new(Ok(future::Loop::Break(t)).into_future())
                                }
                            }),
                    )
                }
                Err(err) => match delegate.token_storage_failure(false, &err) {
                    Retry::Abort | Retry::Skip => {
                        return Box::new(Err(RequestError::Cache(Box::new(err))).into_future())
                    }
                    Retry::After(d) => {
                        return Box::new(
                            tokio_timer::sleep(d).then(|_| Ok(future::Loop::Continue(()))),
                        )
                    }
                },
            }
        };
        Box::new(future::loop_fn((), loopfn))
    }
}