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
//! Bindings and utilities for creating an oauth endpoint with actix.
//!
//! Use the provided methods to use code grant methods in an asynchronous fashion, or use an
//! `AsActor<_>` to create an actor implementing endpoint functionality via messages.
#![warn(missing_docs)]

use actix::{MailboxError, Message};
use actix_web::{
    dev::{HttpResponseBuilder, Payload},
    http::{
        header::{self, HeaderMap, InvalidHeaderValue},
        StatusCode,
    },
    web::Form,
    web::Query,
    FromRequest, HttpRequest, HttpResponse, Responder, ResponseError,
};
use futures::future::{self, FutureExt, LocalBoxFuture, Ready};
use oxide_auth::{
    endpoint::{Endpoint, NormalizedParameter, OAuthError, QueryParameter, WebRequest, WebResponse},
    frontends::simple::endpoint::Error,
};
use std::{borrow::Cow, error, fmt, convert::TryFrom};
use url::Url;

mod operations;

pub use operations::{Authorize, Refresh, Resource, Token};

/// Describes an operation that can be performed in the presence of an `Endpoint`
///
/// This trait can be implemented by any type, but is very useful in Actor scenarios, where an
/// Actor can provide an endpoint to an operation sent as a message.
///
/// Here's how any Endpoint type can be turned into an Actor that responds to OAuthMessages:
/// ```rust,ignore
/// use actix::{Actor, Context, Handler};
/// use oxide_auth::endpoint::Endpoint;
/// use oxide_auth_actix::OAuthOperation;
///
/// pub struct MyEndpoint {
///     // Define your endpoint...
/// }
///
/// impl Endpoint<OAuthRequest> for MyEndpoint {
///     // Implement your endpoint...
/// }
///
/// // Implement Actor
/// impl Actor for MyEndpoint {
///     type Context = Context<Self>;
/// }
///
/// // Handle incoming OAuthMessages
/// impl<Op, Ext> Handler<OAuthMessage<Op, Ext>> for MyEndpoint
/// where
///     Op: OAuthOperation,
/// {
///     type Result = Result<Op::Item, Op::Error>;
///
///     fn handle(&mut self, msg: OAuthMessage<Op, Ext>, _: &mut Self::Context) -> Self::Result {
///         let (op, _) = msg.into_inner();
///
///         op.run(self)
///     }
/// }
/// ```
///
/// By additionally specifying a type for Extras, more advanced patterns can be used
/// ```rust,ignore
/// type Ext = Option<MyCustomSolicitor>;
///
/// // Handle incoming OAuthMessages
/// impl<Op> Handler<OAuthMessage<Op, Ext>> for MyEndpoint
/// where
///     Op: OAuthOperation,
/// {
///     type Result = Result<Op::Item, Op::Error>;
///
///     fn handle(&mut self, msg: OAuthMessage<Op, Ext>, _: &mut Self::Context) -> Self::Result {
///         let (op, ext) = msg.into_inner();
///
///         op.run(self.with_my_custom_solicitor(ext))
///     }
/// }
/// ```
pub trait OAuthOperation: Sized + 'static {
    /// The success-type produced by an OAuthOperation
    type Item: 'static;

    /// The error type produced by an OAuthOperation
    type Error: fmt::Debug + 'static;

    /// Performs the oxide operation with the provided endpoint
    fn run<E>(self, endpoint: E) -> Result<Self::Item, Self::Error>
    where
        E: Endpoint<OAuthRequest>,
        WebError: From<E::Error>;

    /// Turn an OAuthOperation into a Message to send to an actor
    fn wrap<Extras>(self, extras: Extras) -> OAuthMessage<Self, Extras> {
        OAuthMessage(self, extras)
    }
}

/// A message type to easily send `OAuthOperation`s to an actor
pub struct OAuthMessage<Operation, Extras>(Operation, Extras);

#[derive(Clone, Debug)]
/// Type implementing `WebRequest` as well as `FromRequest` for use in route handlers
///
/// This type consumes the body of the HttpRequest upon extraction, so be careful not to use it in
/// places you also expect an application payload
pub struct OAuthRequest {
    auth: Option<String>,
    query: Option<NormalizedParameter>,
    body: Option<NormalizedParameter>,
}

impl OAuthResponse {
    /// Get the headers from `OAuthResponse`
    pub fn get_headers(&self) -> HeaderMap {
        self.headers.clone()
    }

    /// Get the body from `OAuthResponse`
    pub fn get_body(&self) -> Option<String> {
        self.body.clone()
    }
}

/// Type implementing `WebRequest` as well as `FromRequest` for use in guarding resources
///
/// This is useful over [OAuthRequest] since [OAuthResource] doesn't consume the body of the
/// request upon extraction
pub struct OAuthResource {
    auth: Option<String>,
}

#[derive(Clone, Debug)]
/// Type implementing `WebResponse` and `Responder` for use in route handlers
pub struct OAuthResponse {
    status: StatusCode,
    headers: HeaderMap,
    body: Option<String>,
}

#[derive(Debug)]
/// The error type for Oxide Auth operations
pub enum WebError {
    /// Errors occuring in Endpoint operations
    Endpoint(OAuthError),

    /// Errors occuring when producing Headers
    Header(InvalidHeaderValue),

    /// Errors with the request encoding
    Encoding,

    /// Request body could not be parsed as a form
    Form,

    /// Request query was absent or could not be parsed
    Query,

    /// Request was missing a body
    Body,

    /// The Authorization header was invalid
    Authorization,

    /// Processing part of the request was canceled
    Canceled,

    /// An actor's mailbox was full
    Mailbox,

    /// General internal server error
    InternalError(Option<String>),
}

impl OAuthRequest {
    /// Create a new OAuthRequest from an HttpRequest and Payload
    pub async fn new(req: HttpRequest, mut payload: Payload) -> Result<Self, WebError> {
        let query = Query::extract(&req)
            .await
            .ok()
            .map(|q: Query<NormalizedParameter>| q.into_inner());
        let body = Form::from_request(&req, &mut payload)
            .await
            .ok()
            .map(|b: Form<NormalizedParameter>| b.into_inner());

        let mut all_auth = req.headers().get_all(header::AUTHORIZATION);
        let optional = all_auth.next();

        let auth = if all_auth.next().is_some() {
            return Err(WebError::Authorization);
        } else {
            optional.and_then(|hv| hv.to_str().ok().map(str::to_owned))
        };

        Ok(OAuthRequest { auth, query, body })
    }

    /// Fetch the authorization header from the request
    pub fn authorization_header(&self) -> Option<&str> {
        self.auth.as_deref()
    }

    /// Fetch the query for this request
    pub fn query(&self) -> Option<&NormalizedParameter> {
        self.query.as_ref()
    }

    /// Fetch the query mutably
    pub fn query_mut(&mut self) -> Option<&mut NormalizedParameter> {
        self.query.as_mut()
    }

    /// Fetch the body of the request
    pub fn body(&self) -> Option<&NormalizedParameter> {
        self.body.as_ref()
    }
}

impl OAuthResource {
    /// Create a new OAuthResource from an HttpRequest
    pub fn new(req: &HttpRequest) -> Result<Self, WebError> {
        let mut all_auth = req.headers().get_all(header::AUTHORIZATION);
        let optional = all_auth.next();

        let auth = if all_auth.next().is_some() {
            return Err(WebError::Authorization);
        } else {
            optional.and_then(|hv| hv.to_str().ok().map(str::to_owned))
        };

        Ok(OAuthResource { auth })
    }

    /// Turn this OAuthResource into an OAuthRequest for processing
    pub fn into_request(self) -> OAuthRequest {
        OAuthRequest {
            query: None,
            body: None,
            auth: self.auth,
        }
    }
}

impl OAuthResponse {
    /// Create a simple response with no body and a '200 OK' HTTP Status
    pub fn ok() -> Self {
        OAuthResponse {
            status: StatusCode::OK,
            headers: HeaderMap::new(),
            body: None,
        }
    }

    /// Set the `ContentType` header on a response
    pub fn content_type(mut self, content_type: &str) -> Result<Self, WebError> {
        self.headers
            .insert(header::CONTENT_TYPE, TryFrom::try_from(content_type)?);
        Ok(self)
    }

    /// Set the bodyfor the response
    pub fn body(mut self, body: &str) -> Self {
        self.body = Some(body.to_owned());
        self
    }
}

impl<Operation, Extras> OAuthMessage<Operation, Extras> {
    /// Produce an OAuthOperation from a wrapping OAuthMessage
    pub fn into_inner(self) -> (Operation, Extras) {
        (self.0, self.1)
    }
}

impl WebRequest for OAuthRequest {
    type Error = WebError;
    type Response = OAuthResponse;

    fn query(&mut self) -> Result<Cow<dyn QueryParameter + 'static>, Self::Error> {
        self.query
            .as_ref()
            .map(|q| Cow::Borrowed(q as &dyn QueryParameter))
            .ok_or(WebError::Query)
    }

    fn urlbody(&mut self) -> Result<Cow<dyn QueryParameter + 'static>, Self::Error> {
        self.body
            .as_ref()
            .map(|b| Cow::Borrowed(b as &dyn QueryParameter))
            .ok_or(WebError::Body)
    }

    fn authheader(&mut self) -> Result<Option<Cow<str>>, Self::Error> {
        Ok(self.auth.as_deref().map(Cow::Borrowed))
    }
}

impl WebResponse for OAuthResponse {
    type Error = WebError;

    fn ok(&mut self) -> Result<(), Self::Error> {
        self.status = StatusCode::OK;
        Ok(())
    }

    fn redirect(&mut self, url: Url) -> Result<(), Self::Error> {
        self.status = StatusCode::FOUND;
        self.headers
            .insert(header::LOCATION, TryFrom::try_from(url.into_string())?);
        Ok(())
    }

    fn client_error(&mut self) -> Result<(), Self::Error> {
        self.status = StatusCode::BAD_REQUEST;
        Ok(())
    }

    fn unauthorized(&mut self, kind: &str) -> Result<(), Self::Error> {
        self.status = StatusCode::UNAUTHORIZED;
        self.headers
            .insert(header::WWW_AUTHENTICATE, TryFrom::try_from(kind)?);
        Ok(())
    }

    fn body_text(&mut self, text: &str) -> Result<(), Self::Error> {
        self.body = Some(text.to_owned());
        self.headers
            .insert(header::CONTENT_TYPE, TryFrom::try_from("text/plain")?);
        Ok(())
    }

    fn body_json(&mut self, json: &str) -> Result<(), Self::Error> {
        self.body = Some(json.to_owned());
        self.headers
            .insert(header::CONTENT_TYPE, TryFrom::try_from("application/json")?);
        Ok(())
    }
}

impl<Operation, Extras> Message for OAuthMessage<Operation, Extras>
where
    Operation: OAuthOperation + 'static,
{
    type Result = Result<Operation::Item, Operation::Error>;
}

impl FromRequest for OAuthRequest {
    type Error = WebError;
    type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
    type Config = ();

    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
        Self::new(req.clone(), payload.take()).boxed_local()
    }
}

impl FromRequest for OAuthResource {
    type Error = WebError;
    type Future = Ready<Result<Self, Self::Error>>;
    type Config = ();

    fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
        future::ready(Self::new(req))
    }
}

impl Responder for OAuthResponse {
    type Error = WebError;
    type Future = Ready<Result<HttpResponse, Self::Error>>;

    fn respond_to(self, _: &HttpRequest) -> Self::Future {
        let mut builder = HttpResponseBuilder::new(self.status);
        for (k, v) in self.headers.into_iter() {
            builder.header(k, v.to_owned());
        }

        if let Some(body) = self.body {
            future::ok(builder.body(body))
        } else {
            future::ok(builder.finish())
        }
    }
}

impl From<OAuthResource> for OAuthRequest {
    fn from(o: OAuthResource) -> Self {
        o.into_request()
    }
}

impl Default for OAuthResponse {
    fn default() -> Self {
        OAuthResponse {
            status: StatusCode::OK,
            headers: HeaderMap::new(),
            body: None,
        }
    }
}

impl From<Error<OAuthRequest>> for WebError {
    fn from(e: Error<OAuthRequest>) -> Self {
        match e {
            Error::Web(e) => e,
            Error::OAuth(e) => e.into(),
        }
    }
}

impl From<InvalidHeaderValue> for WebError {
    fn from(e: InvalidHeaderValue) -> Self {
        WebError::Header(e)
    }
}

impl From<MailboxError> for WebError {
    fn from(e: MailboxError) -> Self {
        match e {
            MailboxError::Closed => WebError::Mailbox,
            MailboxError::Timeout => WebError::Canceled,
        }
    }
}

impl From<OAuthError> for WebError {
    fn from(e: OAuthError) -> Self {
        WebError::Endpoint(e)
    }
}

impl fmt::Display for WebError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            WebError::Endpoint(ref e) => write!(f, "Endpoint, {}", e),
            WebError::Header(ref e) => write!(f, "Couldn't set header, {}", e),
            WebError::Encoding => write!(f, "Error decoding request"),
            WebError::Form => write!(f, "Request is not a form"),
            WebError::Query => write!(f, "No query present"),
            WebError::Body => write!(f, "No body present"),
            WebError::Authorization => write!(f, "Request has invalid Authorization headers"),
            WebError::Canceled => write!(f, "Operation canceled"),
            WebError::Mailbox => write!(f, "An actor's mailbox was full"),
            WebError::InternalError(None) => write!(f, "An internal server error occured"),
            WebError::InternalError(Some(ref e)) => write!(f, "An internal server error occured: {}", e),
        }
    }
}

impl error::Error for WebError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match *self {
            WebError::Endpoint(ref e) => e.source(),
            WebError::Header(ref e) => e.source(),
            WebError::Encoding
            | WebError::Form
            | WebError::Authorization
            | WebError::Query
            | WebError::Body
            | WebError::Canceled
            | WebError::Mailbox
            | WebError::InternalError(_) => None,
        }
    }
}

impl ResponseError for WebError {
    // Default to 500 for now
}