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
//! Helper for ad-hoc authorization endpoints needs.
//!
//! Implements a simple struct with public members `Generic` that provides a common basis with an
//! `Endpoint` implementation. Tries to implement the least amount of policies and logic while
//! providing the biggest possible customizability (in that order).
use primitives::authorizer::Authorizer;
use primitives::issuer::Issuer;
use primitives::registrar::Registrar;
use primitives::scope::Scope;

use endpoint::{AccessTokenFlow, AuthorizationFlow, ResourceFlow};
use endpoint::{Endpoint, OAuthError, PreGrant, Template, Scopes};
use endpoint::{OwnerConsent, OwnerSolicitor};
use endpoint::WebRequest;

/// Errors either caused by the underlying web types or the library.
#[derive(Debug)]
pub enum Error<W: WebRequest> {
    /// An operation on a request or response failed.
    ///
    /// Typically, this should be represented as a `500–Internal Server Error`.
    Web(W::Error),

    /// Some part of the library signaled failure.
    ///
    /// No response has been generated, and in some cases doing so should be done with care or
    /// under the consideration of an attacker currently trying to abuse the system.
    OAuth(OAuthError),
}

/// A rather basic `Endpoint` implementation.
///
/// Substitue all parts that are not provided with the marker struct `Vacant`. This will at least
/// ensure that no security properties are violated. Some flows may be unavailable when some
/// primitives are missing. See `AccessTokenFlow`, `AuthorizationFlow`, `ResourceFlow` in
/// `code_grant::endpoint` for more details.
///
/// Included types are assumed to be implemented independently, with no major connections. All
/// attributes are public, so there is no inner invariant. The maintained invariants are already
/// statically encoded in the type coices.
pub struct Generic<R, A, I, S=Vacant, C=Vacant, L=Vacant> {
    /// The registrar implementation of `Vacant`.
    pub registrar: R,

    /// The authorizer implementation of `Vacant`.
    pub authorizer: A,

    /// The issuer implementation of `Vacant`.
    pub issuer: I,

    /// A solicitor implementation fit for the request types or `Vacant`.
    pub solicitor: S,
    
    /// Determine scopes for the request types or `Vacant`.
    pub scopes: C,

    /// Creates responses, may be vacant for `Default::default`.
    pub response: L,
}

/// Marker struct if some primitive is not provided.
///
/// Used in place of other primitives when those are not provided. The exact semantics depend on
/// the primitive.
///
/// ## Registrar, Authorizer, Issuer
///
/// Statically ensures to the `Generic` endpoint that no such primitive has been provided. Using
/// the endpoint for flows that need such primitives will fail during the preparation phase. This
/// returns `Option::None` in the implementations for `OptRef<T>`, `OptRegistrar`, `OptAuthorizer`,
/// `OptIssuer`.
///
/// ## OwnerSolicitor
///
/// A solicitor denying all requests. This is the 'safe' default solicitor, remember to configure
/// your own solicitor when you actually need to use it.
///
/// In contrast to the other primitives, this can not be solved as something such as
/// `OptSolicitor<W>` since there is no current stable way to deny other crates from implementing
/// `OptSolicitor<WR>` for some `WR` from that other crate. Thus, the compiler must assume that
/// `None` may in fact implement some solicitor and this makes it impossible to implement as an
/// optional reference trait for all solicitors in one way but in a different way for the `None`
/// solicitor.
///
/// ## Scopes
///
/// Returns an empty list of scopes, effictively denying all requests since at least one scope
/// needs to be fulfilled by token to gain access.
///
/// See [OwnerSolicitor](#OwnerSolicitor) for discussion on why this differs from the other
/// primitives.
pub struct Vacant;

/// A simple wrapper for functions and lambdas to be used as solicitors.
pub struct FnSolicitor<F>(pub F);

/// Use a predetermined grant and owner as solicitor.
///
/// Convenience wrapper when the owner and her/his consented to grant can be identified without
/// further inspecting the request inserted into the flow. This may be the case for `WebRequest`
/// implementations extracted from an original http request. This solicitor is obviously mostly
/// useful for one-shot endpoints.
pub struct ApprovedGrant {
    /// The owner that approves of the grant.
    pub owner: String,

    /// The exact approved grant.
    pub grant: PreGrant,
}

/// Like `AsRef<Registrar +'_>` but in a way that is expressible.
///
/// You are not supposed to need to implement this.
///
/// The difference to `AsRef` is that the `std` trait implies the trait lifetime bound be
/// independent of the lifetime of `&self`. This leads to some annoying implementation constraints,
/// similar to how you can not implement an `Iterator<&'_ mut Item>` whose items (i.e. `next`
/// method) borrow the iterator. Only in this case the lifetime trouble is hidden behind the
/// automatically inferred lifetime, as `AsRef<Trait>` actually refers to 
/// `AsRef<(Trait + 'static)`. But `as_ref` should have unsugared signature:
///
/// > `fn opt_ref<'a>(&'a self) -> Option<&'a (Trait + 'a)>`
///
/// Unfortunately, the `+ 'a` combiner can only be applied to traits, so we need a separate `OptX`
/// trait for each trait for which we want to make use of such a function, afaik. If you have
/// better ideas, I'll be grateful for opening an item on the Issue tracker.
pub trait OptRegistrar {
    /// Reference this as a `Registrar` or `Option::None`.
    fn opt_ref(&self) -> Option<&Registrar>;
}

/// Like `AsMut<Authorizer +'_>` but in a way that is expressible.
///
/// You are not supposed to need to implement this.
///
/// The difference to `AsMut` is that the `std` trait implies the trait lifetime bound be
/// independent of the lifetime of `&self`. This leads to some annoying implementation constraints,
/// similar to how you can not implement an `Iterator<&'_ mut Item>` whose items (i.e. `next`
/// method) borrow the iterator. Only in this case the lifetime trouble is hidden behind the
/// automatically inferred lifetime, as `AsMut<Trait>` actually refers to 
/// `AsMut<(Trait + 'static)`. But `opt_mut` should have unsugared signature:
///
/// > `fn opt_mut<'a>(&'a mut self) -> Option<&'a mut (Trait + 'a)>`
///
/// Unfortunately, the `+ 'a` combiner can only be applied to traits, so we need a separate `OptX`
/// trait for each trait for which we want to make use of such a function, afaik. If you have
/// better ideas, I'll be grateful for opening an item on the Issue tracker.
pub trait OptAuthorizer {
    /// Reference this mutably as an `Authorizer` or `Option::None`.
    fn opt_mut(&mut self) -> Option<&mut Authorizer>;
}

/// Like `AsMut<Issuer +'_>` but in a way that is expressible.
///
/// You are not supposed to need to implement this.
///
/// The difference to `AsMut` is that the `std` trait implies the trait lifetime bound be
/// independent of the lifetime of `&self`. This leads to some annoying implementation constraints,
/// similar to how you can not implement an `Iterator<&'_ mut Item>` whose items (i.e. `next`
/// method) borrow the iterator. Only in this case the lifetime trouble is hidden behind the
/// automatically inferred lifetime, as `AsMut<Trait>` actually refers to 
/// `AsMut<(Trait + 'static)`. But `opt_mut` should have unsugared signature:
///
/// > `fn opt_mut<'a>(&'a mut self) -> Option<&'a mut (Trait + 'a)>`
///
/// Unfortunately, the `+ 'a` combiner can only be applied to traits, so we need a separate `OptX`
/// trait for each trait for which we want to make use of such a function, afaik. If you have
/// better ideas, I'll be grateful for opening an item on the Issue tracker.
pub trait OptIssuer {
    /// Reference this mutably as an `Issuer` or `Option::None`.
    fn opt_mut(&mut self) -> Option<&mut Issuer>;
}

/// Independent component responsible for instantiating responses.
pub trait ResponseCreator<W: WebRequest> {
    /// Will only be called at most once per flow execution.
    fn create(&mut self, request: &mut W, kind: Template) -> W::Response;
}

type Authorization<'a, W> = Generic<&'a (Registrar + 'a), &'a mut(Authorizer + 'a), Vacant, &'a mut(OwnerSolicitor<W> + 'a), Vacant, Vacant>;
type AccessToken<'a> = Generic<&'a (Registrar + 'a), &'a mut(Authorizer + 'a), &'a mut(Issuer + 'a), Vacant, Vacant, Vacant>;
type Resource<'a> = Generic<Vacant, Vacant, &'a mut (Issuer + 'a), Vacant, &'a [Scope], Vacant>;

/// Create an ad-hoc authorization flow.
///
/// Since all necessary primitives are expected in the function syntax, this is guaranteed to never
/// fail or panic, compared to preparing one with `AuthorizationFlow`. 
///
/// But this is not as versatile and extensible, so it should be used with care.  The fact that it
/// only takes references is a conscious choice to maintain forwards portability while encouraging
/// the transition to custom `Endpoint` implementations instead.
pub fn authorization_flow<'a, W>(registrar: &'a Registrar, authorizer: &'a mut Authorizer, solicitor: &'a mut OwnerSolicitor<W>)
    -> AuthorizationFlow<Authorization<'a, W>, W>
    where W: WebRequest, W::Response: Default
{
    let flow = AuthorizationFlow::prepare(Generic {
        registrar,
        authorizer,
        issuer: Vacant,
        solicitor,
        scopes: Vacant,
        response: Vacant,
    });

    match flow {
        Err(_) => unreachable!(),
        Ok(flow) => flow,
    }
}

/// Create an ad-hoc access token flow.
///
/// Since all necessary primitives are expected in the function syntax, this is guaranteed to never
/// fail or panic, compared to preparing one with `AccessTokenFlow`. 
///
/// But this is not as versatile and extensible, so it should be used with care.  The fact that it
/// only takes references is a conscious choice to maintain forwards portability while encouraging
/// the transition to custom `Endpoint` implementations instead.
pub fn access_token_flow<'a, W>(registrar: &'a Registrar, authorizer: &'a mut Authorizer, issuer: &'a mut Issuer) 
    -> AccessTokenFlow<AccessToken<'a>, W>
    where W: WebRequest, W::Response: Default
{
    let flow = AccessTokenFlow::prepare(Generic {
        registrar,
        authorizer,
        issuer,
        solicitor: Vacant,
        scopes: Vacant,
        response: Vacant,
    });

    match flow {
        Err(_) => unreachable!(),
        Ok(flow) => flow,
    }
}

/// Create an ad-hoc resource flow.
///
/// Since all necessary primitives are expected in the function syntax, this is guaranteed to never
/// fail or panic, compared to preparing one with `ResourceFlow`. 
///
/// But this is not as versatile and extensible, so it should be used with care.  The fact that it
/// only takes references is a conscious choice to maintain forwards portability while encouraging
/// the transition to custom `Endpoint` implementations instead.
pub fn resource_flow<'a, W>(issuer: &'a mut Issuer, scopes: &'a [Scope])
    -> ResourceFlow<Resource<'a>, W>
    where W: WebRequest, W::Response: Default
{
    let flow = ResourceFlow::prepare(Generic {
        registrar: Vacant,
        authorizer: Vacant,
        issuer,
        solicitor: Vacant,
        scopes,
        response: Vacant,
    });

    match flow {
        Err(_) => unreachable!(),
        Ok(flow) => flow,
    }
}

impl<R, A, I, O, C, L> Generic<R, A, I, O, C, L> {
    /// Change the used solicitor.
    pub fn with_solicitor<N>(self, new_solicitor: N) -> Generic<R, A, I, N, C, L> {
        Generic {
            registrar: self.registrar,
            authorizer: self.authorizer,
            issuer: self.issuer,
            solicitor: new_solicitor,
            scopes: self.scopes,
            response: self.response,
        }
    }

    /// Change the used scopes.
    pub fn with_scopes<S>(self, new_scopes: S) -> Generic<R, A, I, O, S, L> {
        Generic {
            registrar: self.registrar,
            authorizer: self.authorizer,
            issuer: self.issuer,
            solicitor: self.solicitor,
            scopes: new_scopes,
            response: self.response,
        }
    }

    /// Create an authorizer flow.
    ///
    /// Opposed to `AuthorizationFlow::prepare` this statically ensures that the construction
    /// succeeds.
    pub fn to_authorization<W: WebRequest>(self) -> AuthorizationFlow<Self, W>
    where
        Self: Endpoint<W>,
        R: Registrar,
        A: Authorizer,
    {
        match AuthorizationFlow::prepare(self) {
            Ok(flow) => flow,
            Err(_) => unreachable!(),
        }
    }

    /// Create an access token flow.
    ///
    /// Opposed to `AccessTokenFlow::prepare` this statically ensures that the construction
    /// succeeds.
    pub fn to_access_token<W: WebRequest>(self) -> AccessTokenFlow<Self, W>
    where
        Self: Endpoint<W>,
        R: Registrar,
        A: Authorizer,
        I: Issuer,
    {
        match AccessTokenFlow::prepare(self) {
            Ok(flow) => flow,
            Err(_) => unreachable!(),
        }
    }

    /// Create a resource access flow.
    ///
    /// Opposed to `ResourceFlow::prepare` this statically ensures that the construction
    /// succeeds.
    pub fn to_resource<W: WebRequest>(self) -> ResourceFlow<Self, W>
    where
        Self: Endpoint<W>,
        I: Issuer,
    {
        match ResourceFlow::prepare(self) {
            Ok(flow) => flow,
            Err(_) => unreachable!(),
        }
    }

    /// Check, statically, that this is an endpoint for some request.
    ///
    /// This is mainly a utility method intended for compilation and integration tests.
    pub fn assert<W: WebRequest>(self) -> Self where Self: Endpoint<W> {
        self
    }
}

impl<W: WebRequest> Error<W> {
    /// Convert into a single error type.
    ///
    /// Note that the additional information whether the error occurred in the web components or
    /// during the flow needs to be implicitely contained in the types. Otherwise, this information
    /// is lost and you should use or provide a `From<Error<W>>` implementation instead. This
    /// method is still useful for frontends providing a standard error type that interacts with
    /// their web server library.
    pub fn pack<P>(self) -> P
        where OAuthError: Into<P>, W::Error: Into<P>,
    {
        match self {
            Error::Web(err) => err.into(),
            Error::OAuth(oauth) => oauth.into(),
        }
    }
}

impl<W, R, A, I, O, C, L> Endpoint<W> for Generic<R, A, I, O, C, L>
where 
    W: WebRequest, 
    R: OptRegistrar,
    A: OptAuthorizer,
    I: OptIssuer,
    O: OwnerSolicitor<W>,
    C: Scopes<W>,
    L: ResponseCreator<W>,
{
    type Error = Error<W>;

    fn registrar(&self) -> Option<&Registrar> {
        self.registrar.opt_ref()
    }

    fn authorizer_mut(&mut self) -> Option<&mut Authorizer> {
        self.authorizer.opt_mut()
    }

    fn issuer_mut(&mut self) -> Option<&mut Issuer> {
        self.issuer.opt_mut()
    }

    fn owner_solicitor(&mut self) -> Option<&mut OwnerSolicitor<W>> {
        Some(&mut self.solicitor)
    }

    fn scopes(&mut self) -> Option<&mut Scopes<W>> {
        Some(&mut self.scopes)
    }

    fn response(&mut self, request: &mut W, kind: Template) -> Result<W::Response, Self::Error> {
        Ok(self.response.create(request, kind))
    }

    fn error(&mut self, err: OAuthError) -> Error<W> {
        Error::OAuth(err)
    }

    fn web_error(&mut self, err: W::Error) -> Error<W> {
        Error::Web(err)
    }
}

impl<T: Registrar> OptRegistrar for T {
    fn opt_ref(&self) -> Option<&Registrar> {
        Some(self)
    }
}

impl<T: Authorizer> OptAuthorizer for T {
    fn opt_mut(&mut self) -> Option<&mut Authorizer> {
        Some(self)
    }
}

impl<T: Issuer> OptIssuer for T {
    fn opt_mut(&mut self) -> Option<&mut Issuer> {
        Some(self)
    }
}

impl OptRegistrar for Vacant {
    fn opt_ref(&self) -> Option<&Registrar> {
        Option::None
    }
}

impl OptAuthorizer for Vacant {
    fn opt_mut(&mut self) -> Option<&mut Authorizer> {
        Option::None
    }
}

impl OptIssuer for Vacant {
    fn opt_mut(&mut self) -> Option<&mut Issuer> {
        Option::None
    }
}

impl<W: WebRequest> OwnerSolicitor<W> for Vacant {
    fn check_consent(&mut self, _: &mut W, _: &PreGrant) -> OwnerConsent<W::Response> {
        OwnerConsent::Denied
    }
}

impl<W: WebRequest> Scopes<W> for Vacant {
    fn scopes(&mut self, _: &mut W) -> &[Scope] {
        const NO_SCOPES: [Scope; 0] = [];
        &NO_SCOPES
    }
}

impl<W, F> OwnerSolicitor<W> for FnSolicitor<F>
where
    W: WebRequest,
    F: FnMut(&mut W, &PreGrant) -> OwnerConsent<W::Response>
{
    fn check_consent(&mut self, request: &mut W, grant: &PreGrant)
        -> OwnerConsent<W::Response> 
    {
        (self.0)(request, grant)
    }
}

impl<W: WebRequest> OwnerSolicitor<W> for ApprovedGrant {
    /// Approve if the grant matches *exactly*.
    ///
    /// That is, `client_id`, `redirect_uri`, and `scope` of the pre-grant are all equivalent. In
    /// particular, the requested scope must match exactly not only be a subset of the approved
    /// scope.
    fn check_consent(&mut self, _: &mut W, grant: &PreGrant) -> OwnerConsent<W::Response> {
        if &self.grant == grant { 
            OwnerConsent::Authorized(self.owner.clone()) 
        } else {
            OwnerConsent::Denied
        }
    }
}

impl<W: WebRequest> ResponseCreator<W> for Vacant where W::Response: Default {
    fn create(&mut self, _: &mut W, _: Template) -> W::Response {
        Default::default()
    }
}

impl<W: WebRequest, F> ResponseCreator<W> for F where F: FnMut() -> W::Response {
    fn create(&mut self, _: &mut W, _: Template) -> W::Response {
        self()
    }
}