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
use std::borrow::BorrowMut;
use std::cmp::min;
use std::collections::hash_map::DefaultHasher;
use std::convert::From;
use std::error::Error;
use std::hash::{Hash, Hasher};
use std::iter::IntoIterator;
use std::thread::sleep;
use authenticator_delegate::{AuthenticatorDelegate, PollError, PollInformation};
use device::{GOOGLE_DEVICE_CODE_URL, DeviceFlow};
use installed::{InstalledFlow, InstalledFlowReturnMethod};
use refresh::{RefreshResult, RefreshFlow};
use std::time::Duration;
use storage::TokenStorage;
use types::{RequestError, StringError, Token, FlowType, ApplicationSecret};
use hyper;
pub struct Authenticator<D, S, C> {
flow_type: FlowType,
delegate: D,
storage: S,
client: C,
secret: ApplicationSecret,
}
pub trait GetToken {
fn token<'b, I, T>(&mut self, scopes: I) -> Result<Token, Box<Error>>
where T: AsRef<str> + Ord + 'b,
I: IntoIterator<Item = &'b T>;
fn api_key(&mut self) -> Option<String>;
}
impl<D, S, C> Authenticator<D, S, C>
where D: AuthenticatorDelegate,
S: TokenStorage,
C: BorrowMut<hyper::Client>
{
pub fn new(secret: &ApplicationSecret,
delegate: D,
client: C,
storage: S,
flow_type: Option<FlowType>)
-> Authenticator<D, S, C> {
Authenticator {
flow_type: flow_type.unwrap_or(FlowType::Device(GOOGLE_DEVICE_CODE_URL.to_string())),
delegate: delegate,
storage: storage,
client: client,
secret: secret.clone(),
}
}
fn do_installed_flow(&mut self, scopes: &Vec<&str>) -> Result<Token, Box<Error>> {
let installed_type;
match self.flow_type {
FlowType::InstalledInteractive => {
installed_type = Some(InstalledFlowReturnMethod::Interactive)
}
FlowType::InstalledRedirect(port) => {
installed_type = Some(InstalledFlowReturnMethod::HTTPRedirect(port))
}
_ => installed_type = None,
}
let mut flow = InstalledFlow::new(self.client.borrow_mut(), installed_type);
flow.obtain_token(&mut self.delegate, &self.secret, scopes.iter())
}
fn retrieve_device_token(&mut self, scopes: &Vec<&str>, code_url: String) -> Result<Token, Box<Error>> {
let mut flow = DeviceFlow::new(self.client.borrow_mut(), &self.secret, &code_url);
let pi: PollInformation;
loop {
let res = flow.request_code(scopes.iter());
pi = match res {
Err(res_err) => {
match res_err {
RequestError::HttpError(err) => {
match self.delegate.connection_error(&err) {
Retry::Abort | Retry::Skip => {
return Err(Box::new(StringError::from(&err as &Error)))
}
Retry::After(d) => sleep(d),
}
}
RequestError::InvalidClient |
RequestError::NegativeServerResponse(_, _) |
RequestError::InvalidScope(_) => {
let serr = StringError::from(res_err.to_string());
self.delegate.request_failure(res_err);
return Err(Box::new(serr));
}
};
continue;
}
Ok(pi) => {
self.delegate.present_user_code(&pi);
pi
}
};
break;
}
loop {
match flow.poll_token() {
Err(ref poll_err) => {
let pts = poll_err.to_string();
match poll_err {
&&PollError::HttpError(ref err) => {
match self.delegate.connection_error(err) {
Retry::Abort | Retry::Skip => {
return Err(Box::new(StringError::from(err as &Error)))
}
Retry::After(d) => sleep(d),
}
}
&&PollError::Expired(ref t) => {
self.delegate.expired(t);
return Err(Box::new(StringError::from(pts)));
}
&&PollError::AccessDenied => {
self.delegate.denied();
return Err(Box::new(StringError::from(pts)));
}
};
}
Ok(None) => {
match self.delegate.pending(&pi) {
Retry::Abort | Retry::Skip => {
return Err(Box::new(StringError::new("Pending authentication aborted"
.to_string(),
None)))
}
Retry::After(d) => sleep(min(d, pi.interval)),
}
}
Ok(Some(token)) => return Ok(token),
}
}
}
}
impl<D, S, C> GetToken for Authenticator<D, S, C>
where D: AuthenticatorDelegate,
S: TokenStorage,
C: BorrowMut<hyper::Client>
{
fn token<'b, I, T>(&mut self, scopes: I) -> Result<Token, Box<Error>>
where T: AsRef<str> + Ord + 'b,
I: IntoIterator<Item = &'b T>
{
let (scope_key, scopes) = {
let mut sv: Vec<&str> = scopes.into_iter()
.map(|s| s.as_ref())
.collect::<Vec<&str>>();
sv.sort();
let mut sh = DefaultHasher::new();
&sv.hash(&mut sh);
let sv = sv;
(sh.finish(), sv)
};
loop {
return match self.storage.get(scope_key, &scopes) {
Ok(Some(mut t)) => {
if t.expired() {
let mut rf = RefreshFlow::new(self.client.borrow_mut());
loop {
match *rf.refresh_token(self.flow_type.clone(),
&self.secret,
&t.refresh_token) {
RefreshResult::Error(ref err) => {
match self.delegate.connection_error(err) {
Retry::Abort|Retry::Skip =>
return Err(Box::new(StringError::new(
err.description().to_string(),
None))),
Retry::After(d) => sleep(d),
}
}
RefreshResult::RefreshError(ref err_str, ref err_description) => {
self.delegate.token_refresh_failed(&err_str, &err_description);
let storage_err = match self.storage
.set(scope_key, &scopes, None) {
Ok(_) => String::new(),
Err(err) => err.to_string(),
};
return Err(Box::new(StringError::new(storage_err + err_str,
err_description.as_ref())));
}
RefreshResult::Success(ref new_t) => {
t = new_t.clone();
loop {
if let Err(err) = self.storage
.set(scope_key, &scopes, Some(t.clone())) {
match self.delegate.token_storage_failure(true, &err) {
Retry::Skip => break,
Retry::Abort => return Err(Box::new(err)),
Retry::After(d) => {
sleep(d);
continue;
}
}
}
break;
}
break;
}
}
}
}
Ok(t)
}
Ok(None) => {
match match self.flow_type.clone() {
FlowType::Device(url) => self.retrieve_device_token(&scopes, url),
FlowType::InstalledInteractive => self.do_installed_flow(&scopes),
FlowType::InstalledRedirect(_) => self.do_installed_flow(&scopes),
} {
Ok(token) => {
loop {
if let Err(err) = self.storage
.set(scope_key, &scopes, Some(token.clone())) {
match self.delegate.token_storage_failure(true, &err) {
Retry::Skip => break,
Retry::Abort => return Err(Box::new(err)),
Retry::After(d) => {
sleep(d);
continue;
}
}
}
break;
}
Ok(token)
}
Err(err) => Err(err),
}
}
Err(err) => {
match self.delegate.token_storage_failure(false, &err) {
Retry::Abort | Retry::Skip => Err(Box::new(err)),
Retry::After(d) => {
sleep(d);
continue;
}
}
}
};
}
}
fn api_key(&mut self) -> Option<String> {
if self.secret.client_id.len() == 0 {
return None;
}
Some(self.secret.client_id.clone())
}
}
pub enum Retry {
Abort,
After(Duration),
Skip,
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::device::tests::MockGoogleAuth;
use super::super::types::tests::SECRET;
use super::super::types::ConsoleApplicationSecret;
use authenticator_delegate::DefaultAuthenticatorDelegate;
use storage::MemoryStorage;
use std::default::Default;
use hyper;
#[test]
fn flow() {
use serde_json as json;
let secret = json::from_str::<ConsoleApplicationSecret>(SECRET).unwrap().installed.unwrap();
let res = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
hyper::Client::with_connector(<MockGoogleAuth as Default>::default()),
<MemoryStorage as Default>::default(), None)
.token(&["https://www.googleapis.com/auth/youtube.upload"]);
match res {
Ok(t) => assert_eq!(t.access_token, "1/fFAGRNJru1FTz70BzhT3Zg"),
_ => panic!("Expected to retrieve token in one go"),
}
}
}