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
use hyper;
use hyper::client::*;
use hyper::Uri;
use hyper::Body;
use hyper::Method;
use hyper::header::{Authorization, Bearer, ContentLength};
use std::str::FromStr;
use futures::future::Future;
use futures::{future, Stream};
use time::*;
use std::sync::{RwLock, Arc};
use cogs::*;
use std::convert::From;
const TOKEN_EXPIRES_IN_MINS: i64 = 9;
lazy_static! {
static ref ISSUE_TOKEN_URI: Uri = {
Uri::from_str("https://api.cognitive.microsoft.com/sts/v1.0/issueToken").unwrap()
};
}
header! {
(SubscriptionKeyHeader, "Ocp-Apim-Subscription-Key") => [String]
}
pub struct Engine<Connector>
where Connector: Connect + Service
{
credentials: Arc<RwLock<Credentials>>,
client: Arc<Client<Connector>>,
}
impl<Connector> Engine<Connector>
where Connector: Connect,
Connector: Service
{
pub fn new(credentials: Credentials, client: Client<Connector>) -> Self {
Engine {
credentials: Arc::new(RwLock::new(credentials)),
client: Arc::new(client),
}
}
pub fn run<A>(&self, cog: A) -> Box<Future<Item = <A as Cog>::Item, Error = <A as Cog>::Error>>
where A: Cog
{
let mut req: Request = cog.into();
let client_ref = self.client.clone();
let f = self.renew_token().then(move |engine_result| {
let inner_f: Box<Future<Item = <A as Cog>::Item, Error = <A as Cog>::Error>> =
match engine_result {
Ok(AccessToken { token, .. }) => {
{
let mut headers = req.headers_mut();
headers.set(Authorization(Bearer { token: token.clone() }));
}
Box::new(client_ref.request(req)
.map_err(|e| Error::HyperError(e))
.then(|r| <A as Cog>::Output::from(r)))
}
Err(e) => Box::new(<A as Cog>::Output::from(Err(e))),
};
inner_f
});
Box::new(f)
}
fn renew_token(&self) -> Box<Future<Item = AccessToken, Error = Error>> {
let retrieve_token_sync: Option<AccessToken> = {
let read_lock = self.credentials.read();
match read_lock {
Ok(ref creds) => {
if creds.should_renew_token() {
None
} else {
creds.access_token.clone()
}
}
_ => None,
}
};
match retrieve_token_sync {
Some(t) => future::ok(t).boxed(),
None => {
let write_lock_sync = self.credentials.write();
match write_lock_sync {
Ok(mut creds) => {
if creds.should_renew_token() {
if creds.renewing_token {
self.renew_token()
} else {
let mut req: Request<Body> = Request::new(Method::Post,
ISSUE_TOKEN_URI.clone());
{
let headers = req.headers_mut();
headers.set(SubscriptionKeyHeader(creds
.subscription_key
.0
.clone()));
headers.set(ContentLength(0));
}
creds.renewing_token = true;
let req_f = self.client
.request(req)
.map_err(|e| Error::HyperError(e));
let creds_ref_err = self.credentials.clone();
let creds_ref = self.credentials.clone();
let f = req_f.and_then(|r| {
read_to_string(r).and_then(move |t| {
let r = {
let creds_write_lock = creds_ref.write();
creds_write_lock
.map_err(|_| Error::LockPoisonedError)
.map(|mut creds| {
let access = AccessToken {
token: t,
expires_at: now() + Duration::minutes(TOKEN_EXPIRES_IN_MINS),
};
creds.renewing_token = false;
creds.update_token(access.clone());
access
})
};
r
})
}).map_err(move |e| {
let creds_err_lock = creds_ref_err.write();
match creds_err_lock {
Ok(mut creds) => {
creds.renewing_token = false;
e
}
_ => Error::LockPoisonedError
}
});
Box::new(f)
}
} else {
let t = creds.access_token.clone().unwrap();
future::ok(t).boxed()
}
}
_ => future::err(Error::LockPoisonedError).boxed(),
}
}
}
}
}
pub fn read_to_string(resp: Response) -> Box<Future<Item = String, Error = Error>> {
Box::new(read_to_bytes(resp).and_then(|b| {
String::from_utf8(b).map_err(|_| Error::FromUtf8Error)
}))
}
pub fn read_to_bytes(resp: Response) -> Box<Future<Item = Vec<u8>, Error = Error>> {
let vec = if let Some(len) = resp.headers().get::<ContentLength>() {
Vec::with_capacity(**len as usize)
} else {
vec![]
};
Box::new(resp.body()
.map_err(|e| Error::HyperError(e))
.fold(vec, |mut acc, chunk| {
acc.extend_from_slice(chunk.as_ref());
Ok::<_, Error>(acc)
}))
}
#[derive(Debug)]
pub enum Error {
CouldNotRetrieveToken,
FromUtf8Error,
LockPoisonedError,
HyperError(hyper::Error),
}
pub struct Credentials {
pub subscription_key: SubscriptionKey,
#[doc(hidden)]
access_token: Option<AccessToken>,
#[doc(hidden)]
renewing_token: bool,
}
impl Credentials {
pub fn new(key: SubscriptionKey) -> Credentials {
Credentials {
subscription_key: key,
access_token: None,
renewing_token: false,
}
}
pub fn should_renew_token(&self) -> bool {
let now = now();
match self.token_expires_at() {
Some(expires) => now >= *expires,
_ => true,
}
}
fn update_token(&mut self, token: AccessToken) {
self.access_token = Some(token);
}
fn token_expires_at(&self) -> Option<&Tm> {
match self.access_token {
Some(ref tm) => Some(&tm.expires_at),
_ => None,
}
}
}
pub struct SubscriptionKey(String);
impl SubscriptionKey {
pub fn new<S: ToString>(key: S) -> SubscriptionKey {
SubscriptionKey(key.to_string())
}
pub fn value(&self) -> &str {
&self.0[..]
}
}
#[derive(Clone)]
struct AccessToken {
token: String,
expires_at: Tm,
}
#[cfg(test)]
mod tests {
use super::*;
use tokio_core;
use std::env;
use hyper_tls;
fn subscription_key() -> String {
env::var("AZURE_SUBSCRIPTION_KEY").unwrap()
}
#[test]
fn renew_token_test() {
let mut core = tokio_core::reactor::Core::new().unwrap();
let handle = core.handle();
let client = Client::configure()
.connector(hyper_tls::HttpsConnector::new(4, &handle).unwrap())
.build(&handle);
let sub_key = SubscriptionKey::new(subscription_key());
let credentials = Credentials::new(sub_key);
let engine = Engine::new(credentials, client);
let work = engine.renew_token();
assert!(core.run(work).is_ok())
}
}