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
//! Different implementations

use std::env;
use std::io::Read;
use std::str;
use std::sync::Arc;
use std::time::Duration;

use backoff::{Error as BackoffError, ExponentialBackoff, Operation};
use failure::ResultExt;
use reqwest::{Client, Response, StatusCode, Url, UrlError};

use parsers::*;
use {AccessToken, InitializationError, InitializationResult, TokenInfo};
use {TokenInfoError, TokenInfoErrorKind, TokenInfoResult, TokenInfoService};

#[cfg(feature = "async")]
use async_client::AsyncTokenInfoServiceClient;
#[cfg(feature = "async")]
use futures::future::{Executor, Future};
#[cfg(feature = "metrix")]
use metrics::metrix::MetrixCollector;
#[cfg(feature = "async")]
use metrics::{DevNullMetricsCollector, MetricsCollector};
#[cfg(feature = "metrix")]
use metrix::processor::{AggregatesProcessors, ProcessorMount};

/// A builder for a `TokenInfoServiceClient`
///
/// # Features
///
/// * `async` enables
///     * `build_async`
///     * `build_async_with_metrics`
/// * `async` + `metrix` enables
///     * `build_async_with_metrix`
pub struct TokenInfoServiceClientBuilder<P: TokenInfoParser> {
    pub parser: Option<P>,
    pub endpoint: Option<String>,
    pub query_parameter: Option<String>,
    pub fallback_endpoint: Option<String>,
}

impl<P> TokenInfoServiceClientBuilder<P>
where
    P: TokenInfoParser + Sync + Send + 'static,
{
    /// Create a new `TokenInfoServiceClientBuilder` with the given
    /// `TokenInfoParser` already set.
    pub fn new(parser: P) -> Self {
        let mut builder = Self::default();
        builder.with_parser(parser);
        builder
    }

    /// Sets the `TokenInfoParser`. The `TokenInfoParser` is mandatory.
    pub fn with_parser(&mut self, parser: P) -> &mut Self {
        self.parser = Some(parser);
        self
    }

    /// Sets the introspection endpoint. The introspection endpoint is
    /// mandatory.
    pub fn with_endpoint<T: Into<String>>(&mut self, endpoint: T) -> &mut Self {
        self.endpoint = Some(endpoint.into());
        self
    }

    /// Sets a fallback for the introspection endpoint. The fallback is
    /// optional.
    pub fn with_fallback_endpoint<T: Into<String>>(&mut self, endpoint: T) -> &mut Self {
        self.fallback_endpoint = Some(endpoint.into());
        self
    }

    /// Sets the query parameter for the access token.
    /// If ommitted the access token will be part of the URL.
    pub fn with_query_parameter<T: Into<String>>(&mut self, parameter: T) -> &mut Self {
        self.query_parameter = Some(parameter.into());
        self
    }

    /// Build the `TokenInfoServiceClient`. Fails if not all mandatory fields
    /// are set.
    pub fn build(self) -> InitializationResult<TokenInfoServiceClient> {
        let parser = if let Some(parser) = self.parser {
            parser
        } else {
            return Err(InitializationError("No token info parser.".into()));
        };

        let endpoint = if let Some(endpoint) = self.endpoint {
            endpoint
        } else {
            return Err(InitializationError("No endpoint.".into()));
        };

        TokenInfoServiceClient::new::<P>(
            &endpoint,
            self.query_parameter.as_ref().map(|s| &**s),
            self.fallback_endpoint.as_ref().map(|s| &**s),
            parser,
        )
    }

    /// Build the `TokenInfoServiceClient`. Fails if not all mandatory fields
    /// are set.
    #[cfg(feature = "async")]
    pub fn build_async<E>(self, executor: E) -> InitializationResult<AsyncTokenInfoServiceClient>
    where
        E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sync + 'static,
    {
        self.build_async_with_metrics(executor, DevNullMetricsCollector)
    }

    /// Build the `TokenInfoServiceClient`. Fails if not all mandatory fields
    /// are set.
    #[cfg(feature = "async")]
    pub fn build_async_with_metrics<E, M>(
        self,
        executor: E,
        metrics_collector: M,
    ) -> InitializationResult<AsyncTokenInfoServiceClient>
    where
        E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sync + 'static,
        M: MetricsCollector + 'static,
    {
        let parser = if let Some(parser) = self.parser {
            parser
        } else {
            return Err(InitializationError("No token info parser.".into()));
        };

        let endpoint = if let Some(endpoint) = self.endpoint {
            endpoint
        } else {
            return Err(InitializationError("No endpoint.".into()));
        };

        AsyncTokenInfoServiceClient::with_metrics::<P, E, M>(
            &endpoint,
            self.query_parameter.as_ref().map(|s| &**s),
            self.fallback_endpoint.as_ref().map(|s| &**s),
            parser,
            executor,
            metrics_collector,
        )
    }

    /// Build the `TokenInfoServiceClient`. Fails if not all mandatory fields
    /// are set.
    ///
    /// If `group_name` is defined a new group with the given
    /// name will be created. Otherwise the metrics of the
    /// client will be directly added to `takes_metrics`.
    #[cfg(all(feature = "async", feature = "metrix"))]
    pub fn build_async_with_metrix<E, M, T>(
        self,
        executor: E,
        takes_metrics: &mut M,
        group_name: Option<T>,
    ) -> InitializationResult<AsyncTokenInfoServiceClient>
    where
        E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sync + 'static,
        M: AggregatesProcessors,
        T: Into<String>,
    {
        let metrics_collector = if let Some(group) = group_name {
            let mut mount = ProcessorMount::new(group);
            let collector = MetrixCollector::new(&mut mount);
            takes_metrics.add_processor(mount);
            collector
        } else {
            MetrixCollector::new(takes_metrics)
        };

        self.build_async_with_metrics(executor, metrics_collector)
    }

    /// Creates a new `TokenInfoServiceClientBuilder` from environment
    /// parameters.
    ///
    /// The following variables used to identify the field in a token info
    /// response:
    ///
    /// * `TOKKIT_TOKEN_INTROSPECTION_ENDPOINT`(mandatory): The endpoint of the
    /// service * `TOKKIT_TOKEN_INTROSPECTION_QUERY_PARAMETER`(optional):
    /// The request parameter
    /// * `TOKKIT_TOKEN_INTROSPECTION_FALLBACK_ENDPOINT`(optional): A fallback
    /// endpoint
    ///
    /// If `TOKKIT_TOKEN_INTROSPECTION_QUERY_PARAMETER` is ommitted the access
    /// token will be part of the URL.
    pub fn from_env() -> InitializationResult<Self> {
        let endpoint = env::var("TOKKIT_TOKEN_INTROSPECTION_ENDPOINT").map_err(|err| {
            InitializationError(format!("'TOKKIT_TOKEN_INTROSPECTION_ENDPOINT': {}", err))
        })?;
        let query_parameter = match env::var("TOKKIT_TOKEN_INTROSPECTION_QUERY_PARAMETER") {
            Ok(v) => Some(v),
            Err(env::VarError::NotPresent) => None,
            Err(err) => {
                return Err(InitializationError(format!(
                    "'TOKKIT_TOKEN_INTROSPECTION_QUERY_PARAMETER': {}",
                    err
                )))
            }
        };
        let fallback_endpoint = match env::var("TOKKIT_TOKEN_INTROSPECTION_FALLBACK_ENDPOINT") {
            Ok(v) => Some(v),
            Err(env::VarError::NotPresent) => None,
            Err(err) => {
                return Err(InitializationError(format!(
                    "'TOKKIT_TOKEN_INTROSPECTION_FALLBACK_ENDPOINT': {}",
                    err
                )))
            }
        };
        Ok(TokenInfoServiceClientBuilder {
            parser: Default::default(),
            endpoint: Some(endpoint),
            query_parameter: query_parameter,
            fallback_endpoint: fallback_endpoint,
        })
    }
}

impl TokenInfoServiceClientBuilder<PlanBTokenInfoParser> {
    /// Create a new `TokenInfoServiceClient` with prepared settings.
    ///
    /// [More information](http://planb.readthedocs.io/en/latest/intro.html#token-info)
    pub fn plan_b(endpoint: String) -> TokenInfoServiceClientBuilder<PlanBTokenInfoParser> {
        let mut builder = Self::default();
        builder.with_parser(PlanBTokenInfoParser);
        builder.with_endpoint(endpoint);
        builder.with_query_parameter("access_token");
        builder
    }

    /// Create a new `TokenInfoServiceClient` with prepared settings from
    /// environment variables.
    ///
    /// `TOKKIT_TOKEN_INTROSPECTION_ENDPOINT` and
    /// `TOKKIT_TOKEN_INTROSPECTION_FALLBACK_ENDPOINT` will be used and
    /// `TOKKIT_TOKEN_INTROSPECTION_QUERY_PARAMETER` will have no effect.
    ///
    /// [More information](http://planb.readthedocs.io/en/latest/intro.html#token-info)
    pub fn plan_b_from_env(
) -> InitializationResult<TokenInfoServiceClientBuilder<PlanBTokenInfoParser>> {
        let mut builder = Self::from_env()?;
        builder.with_parser(PlanBTokenInfoParser);
        builder.with_query_parameter("access_token");
        Ok(builder)
    }
}

impl TokenInfoServiceClientBuilder<GoogleV3TokenInfoParser> {
    /// Create a new `TokenInfoServiceClient` with prepared settings.
    ///
    /// [More information](https://developers.google.
    /// com/identity/protocols/OAuth2UserAgent#validatetoken)
    pub fn google_v3() -> TokenInfoServiceClientBuilder<GoogleV3TokenInfoParser> {
        let mut builder = Self::default();
        builder.with_parser(GoogleV3TokenInfoParser);
        builder.with_endpoint("https://www.googleapis.com/oauth2/v3/tokeninfo");
        builder.with_query_parameter("access_token");
        builder
    }
}

impl TokenInfoServiceClientBuilder<AmazonTokenInfoParser> {
    /// Create a new `TokenInfoServiceClient` with prepared settings.
    ///
    /// [More information](https://images-na.ssl-images-amazon.
    /// com/images/G/01/lwa/dev/docs/website-developer-guide._TTH_.pdf)
    pub fn amazon() -> TokenInfoServiceClientBuilder<AmazonTokenInfoParser> {
        let mut builder = Self::default();
        builder.with_parser(AmazonTokenInfoParser);
        builder.with_endpoint("https://api.amazon.com/auth/O2/tokeninfo");
        builder.with_query_parameter("access_token");
        builder
    }
}

impl<P: TokenInfoParser> Default for TokenInfoServiceClientBuilder<P> {
    fn default() -> Self {
        TokenInfoServiceClientBuilder {
            parser: Default::default(),
            endpoint: Default::default(),
            query_parameter: Default::default(),
            fallback_endpoint: Default::default(),
        }
    }
}

/// Introspects an `AccessToken` remotely.
///
/// Returns the result as a `TokenInfo`.
///
/// The `TokenInfoServiceClient` will do retries on failures and if possible
/// call a fallback.
pub struct TokenInfoServiceClient {
    url_prefix: Arc<String>,
    fallback_url_prefix: Option<Arc<String>>,
    http_client: Client,
    parser: Arc<TokenInfoParser + Sync + Send + 'static>,
}

impl TokenInfoServiceClient {
    /// Creates a new `TokenInfoServiceClient`. Fails if one of the given
    /// endpoints is invalid.
    pub fn new<P>(
        endpoint: &str,
        query_parameter: Option<&str>,
        fallback_endpoint: Option<&str>,
        parser: P,
    ) -> InitializationResult<TokenInfoServiceClient>
    where
        P: TokenInfoParser + Sync + Send + 'static,
    {
        let url_prefix = assemble_url_prefix(endpoint, &query_parameter)
            .map_err(|err| InitializationError(err))?;

        let fallback_url_prefix = if let Some(fallback_endpoint_address) = fallback_endpoint {
            Some(
                assemble_url_prefix(fallback_endpoint_address, &query_parameter)
                    .map_err(|err| InitializationError(err))?,
            )
        } else {
            None
        };

        let client = Client::new();
        Ok(TokenInfoServiceClient {
            url_prefix: Arc::new(url_prefix),
            fallback_url_prefix: fallback_url_prefix.map(|fb| Arc::new(fb)),
            http_client: client,
            parser: Arc::new(parser),
        })
    }
}

pub(crate) fn assemble_url_prefix(
    endpoint: &str,
    query_parameter: &Option<&str>,
) -> ::std::result::Result<String, String> {
    let mut url_prefix = String::from(endpoint);
    if let &Some(query_parameter) = query_parameter {
        if url_prefix.ends_with('/') {
            url_prefix.pop();
        }
        url_prefix.push_str(&format!("?{}=", query_parameter));
    } else {
        if !url_prefix.ends_with('/') {
            url_prefix.push('/');
        }
    }
    let test_url = format!("{}test_token", url_prefix);
    let _ = test_url
        .parse::<Url>()
        .map_err(|err| format!("Invalid URL: {}", err))?;
    Ok(url_prefix)
}

impl TokenInfoService for TokenInfoServiceClient {
    fn introspect(&self, token: &AccessToken) -> TokenInfoResult<TokenInfo> {
        let url: Url = complete_url(&self.url_prefix, token)?;
        let fallback_url = match self.fallback_url_prefix {
            Some(ref fb_url_prefix) => Some(complete_url(fb_url_prefix, token)?),
            None => None,
        };
        get_with_fallback(url, fallback_url, &self.http_client, &*self.parser)
    }
}

impl Clone for TokenInfoServiceClient {
    fn clone(&self) -> Self {
        TokenInfoServiceClient {
            url_prefix: self.url_prefix.clone(),
            fallback_url_prefix: self.fallback_url_prefix.clone(),
            http_client: self.http_client.clone(),
            parser: self.parser.clone(),
        }
    }
}

fn complete_url(url_prefix: &str, token: &AccessToken) -> TokenInfoResult<Url> {
    let mut url_str = url_prefix.to_string();
    url_str.push_str(token.0.as_ref());
    let url = url_str.parse()?;
    Ok(url)
}

fn get_with_fallback(
    url: Url,
    fallback_url: Option<Url>,
    client: &Client,
    parser: &TokenInfoParser,
) -> TokenInfoResult<TokenInfo> {
    get_from_remote(url, client, parser).or_else(|err| match *err.kind() {
        TokenInfoErrorKind::Client(_) => Err(err),
        _ => fallback_url
            .map(|url| get_from_remote(url, client, parser))
            .unwrap_or(Err(err)),
    })
}

fn get_from_remote(
    url: Url,
    http_client: &Client,
    parser: &TokenInfoParser,
) -> TokenInfoResult<TokenInfo> {
    let mut op = || match get_from_remote_no_retry(url.clone(), http_client, parser) {
        Ok(token_info) => Ok(token_info),
        Err(err) => match *err.kind() {
            TokenInfoErrorKind::InvalidResponseContent(_) => Err(BackoffError::Permanent(err)),
            TokenInfoErrorKind::UrlError(_) => Err(BackoffError::Permanent(err)),
            TokenInfoErrorKind::NotAuthenticated(_) => Err(BackoffError::Permanent(err)),
            TokenInfoErrorKind::Client(_) => Err(BackoffError::Permanent(err)),
            _ => Err(BackoffError::Transient(err)),
        },
    };

    let mut backoff = ExponentialBackoff::default();
    backoff.max_elapsed_time = Some(Duration::from_millis(200));
    backoff.initial_interval = Duration::from_millis(10);
    backoff.multiplier = 1.5;

    let notify = |err, _| {
        warn!("Retry on token info service: {}", err);
    };

    let retry_result = op.retry_notify(&mut backoff, notify);

    match retry_result {
        Ok(token_info) => Ok(token_info),
        Err(BackoffError::Transient(err)) => Err(err),
        Err(BackoffError::Permanent(err)) => Err(err),
    }
}

fn get_from_remote_no_retry(
    url: Url,
    http_client: &Client,
    parser: &TokenInfoParser,
) -> TokenInfoResult<TokenInfo> {
    let mut request_builder = http_client.get(url);
    match request_builder.send() {
        Ok(ref mut response) => process_response(response, parser),
        Err(err) => Err(TokenInfoErrorKind::Connection(err.to_string()).into()),
    }
}

fn process_response(
    response: &mut Response,
    parser: &TokenInfoParser,
) -> TokenInfoResult<TokenInfo> {
    let mut body = Vec::new();
    response
        .read_to_end(&mut body)
        .context(TokenInfoErrorKind::Io(
            "Could not read response bode".to_string(),
        ))?;
    if response.status() == StatusCode::Ok {
        let result: TokenInfo = match parser.parse(&body) {
            Ok(info) => info,
            Err(msg) => {
                return Err(TokenInfoErrorKind::InvalidResponseContent(msg.to_string()).into())
            }
        };
        Ok(result)
    } else if response.status() == StatusCode::Unauthorized {
        let msg = str::from_utf8(&body)?;
        return Err(TokenInfoErrorKind::NotAuthenticated(format!(
            "The server refused the token: {}",
            msg
        )).into());
    } else if response.status().is_client_error() {
        let msg = str::from_utf8(&body)?;
        return Err(TokenInfoErrorKind::Client(msg.to_string()).into());
    } else if response.status().is_server_error() {
        let msg = str::from_utf8(&body)?;
        return Err(TokenInfoErrorKind::Server(msg.to_string()).into());
    } else {
        let msg = str::from_utf8(&body)?;
        return Err(TokenInfoErrorKind::Other(msg.to_string()).into());
    }
}

impl From<UrlError> for TokenInfoError {
    fn from(what: UrlError) -> Self {
        TokenInfoErrorKind::UrlError(what.to_string()).into()
    }
}

impl From<str::Utf8Error> for TokenInfoError {
    fn from(what: str::Utf8Error) -> Self {
        TokenInfoErrorKind::InvalidResponseContent(what.to_string()).into()
    }
}