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
use crate::code_grant::authorization::{
    authorization_code, Error as AuthorizationError, Extension, Endpoint as AuthorizationEndpoint,
    Request as AuthorizationRequest, Pending,
};

use super::*;

/// All relevant methods for handling authorization code requests.
pub struct AuthorizationFlow<E, R>
where
    E: Endpoint<R>,
    R: WebRequest,
{
    endpoint: WrappedAuthorization<E, R>,
}

struct WrappedAuthorization<E: Endpoint<R>, R: WebRequest> {
    inner: E,
    extension_fallback: (),
    r_type: PhantomData<R>,
}

struct WrappedRequest<'a, R: WebRequest + 'a> {
    /// Original request.
    request: PhantomData<R>,

    /// The query in the url.
    query: Cow<'a, dyn QueryParameter + 'static>,

    /// An error if one occurred.
    error: Option<R::Error>,
}

struct AuthorizationPending<'a, E: 'a, R: 'a>
where
    E: Endpoint<R>,
    R: WebRequest,
{
    endpoint: &'a mut WrappedAuthorization<E, R>,
    pending: Pending,
    request: R,
}

/// A processed authentication request that may be waiting for authorization by the resource owner.
///
/// Note that this borrows from the `AuthorizationFlow` used to create it. You can `finish` the
/// authorization flow for this request to produce a response or an error.
struct AuthorizationPartial<'a, E: 'a, R: 'a>
where
    E: Endpoint<R>,
    R: WebRequest,
{
    inner: AuthorizationPartialInner<'a, E, R>,
}

/// Result type from processing an authentication request.
enum AuthorizationPartialInner<'a, E: 'a, R: 'a>
where
    E: Endpoint<R>,
    R: WebRequest,
{
    /// No error happened during processing and the resource owner can decide over the grant.
    Pending {
        /// A utility struct with which the request can be decided.
        pending: AuthorizationPending<'a, E, R>,
    },

    /// The request was faulty, e.g. wrong client data, but there is a well defined response.
    Failed {
        /// The request passed in.
        request: R,

        /// Final response to the client.
        ///
        /// This should be forwarded unaltered to the client. Modifications and amendments risk
        /// deviating from the OAuth2 rfc, enabling DoS, or even leaking secrets. Modify with care.
        response: R::Response,
    },

    /// An internal error happened during the request.
    Error {
        /// The request passed in.
        request: R,

        /// Error that happened while handling the request.
        error: E::Error,
    },
}

impl<E, R> AuthorizationFlow<E, R>
where
    E: Endpoint<R>,
    R: WebRequest,
{
    /// Check that the endpoint supports the necessary operations for handling requests.
    ///
    /// Binds the endpoint to a particular type of request that it supports, for many
    /// implementations this is probably single type anyways.
    ///
    /// ## Panics
    ///
    /// Indirectly `execute` may panic when this flow is instantiated with an inconsistent
    /// endpoint, for details see the documentation of `Endpoint`. For consistent endpoints,
    /// the panic is instead caught as an error here.
    pub fn prepare(mut endpoint: E) -> Result<Self, E::Error> {
        if endpoint.registrar().is_none() {
            return Err(endpoint.error(OAuthError::PrimitiveError));
        }

        if endpoint.authorizer_mut().is_none() {
            return Err(endpoint.error(OAuthError::PrimitiveError));
        }

        Ok(AuthorizationFlow {
            endpoint: WrappedAuthorization {
                inner: endpoint,
                extension_fallback: (),
                r_type: PhantomData,
            },
        })
    }

    /// Use the checked endpoint to execute the authorization flow for a request.
    ///
    /// In almost all cases this is followed by executing `finish` on the result but some users may
    /// instead want to inspect the partial result.
    ///
    /// ## Panics
    ///
    /// When the registrar or the authorizer returned by the endpoint is suddenly `None` when
    /// previously it was `Some(_)`.
    pub fn execute(&mut self, mut request: R) -> Result<R::Response, E::Error> {
        let negotiated = authorization_code(&mut self.endpoint, &WrappedRequest::new(&mut request));

        let inner = match negotiated {
            Err(err) => match authorization_error(&mut self.endpoint.inner, &mut request, err) {
                Ok(response) => AuthorizationPartialInner::Failed { request, response },
                Err(error) => AuthorizationPartialInner::Error { request, error },
            },
            Ok(negotiated) => AuthorizationPartialInner::Pending {
                pending: AuthorizationPending {
                    endpoint: &mut self.endpoint,
                    pending: negotiated,
                    request,
                },
            },
        };

        let partial = AuthorizationPartial { inner };

        partial.finish()
    }
}

impl<'a, E: Endpoint<R>, R: WebRequest> AuthorizationPartial<'a, E, R> {
    /// Finish the authentication step.
    ///
    /// If authorization has not yet produced a hard error or an explicit response, executes the
    /// owner solicitor of the endpoint to determine owner consent.
    pub fn finish(self) -> Result<R::Response, E::Error> {
        let (_request, result) = match self.inner {
            AuthorizationPartialInner::Pending { pending } => pending.finish(),
            AuthorizationPartialInner::Failed { request, response } => (request, Ok(response)),
            AuthorizationPartialInner::Error { request, error } => (request, Err(error)),
        };

        result
    }
}

fn authorization_error<E: Endpoint<R>, R: WebRequest>(
    endpoint: &mut E, request: &mut R, error: AuthorizationError,
) -> Result<R::Response, E::Error> {
    match error {
        AuthorizationError::Ignore => Err(endpoint.error(OAuthError::DenySilently)),
        AuthorizationError::Redirect(mut target) => {
            let mut response = endpoint.response(
                request,
                InnerTemplate::Redirect {
                    authorization_error: Some(target.description()),
                }
                .into(),
            )?;
            response
                .redirect(target.into())
                .map_err(|err| endpoint.web_error(err))?;
            Ok(response)
        }
        AuthorizationError::PrimitiveError => Err(endpoint.error(OAuthError::PrimitiveError)),
    }
}

impl<'a, E: Endpoint<R>, R: WebRequest> AuthorizationPending<'a, E, R> {
    /// Resolve the pending status using the endpoint to query owner consent.
    fn finish(mut self) -> (R, Result<R::Response, E::Error>) {
        let checked = self
            .endpoint
            .owner_solicitor()
            .check_consent(&mut self.request, self.pending.as_solicitation());

        match checked {
            OwnerConsent::Denied => self.deny(),
            OwnerConsent::InProgress(resp) => self.in_progress(resp),
            OwnerConsent::Authorized(who) => self.authorize(who),
            OwnerConsent::Error(err) => (self.request, Err(self.endpoint.inner.web_error(err))),
        }
    }

    /// Postpones the decision over the request, to display data to the resource owner.
    ///
    /// This should happen at least once for each request unless the resource owner has already
    /// acknowledged and pre-approved a specific grant.  The response can also be used to determine
    /// the resource owner, if no login has been detected or if multiple accounts are allowed to be
    /// logged in at the same time.
    fn in_progress(self, response: R::Response) -> (R, Result<R::Response, E::Error>) {
        (self.request, Ok(response))
    }

    /// Denies the request, the client is not allowed access.
    fn deny(mut self) -> (R, Result<R::Response, E::Error>) {
        let result = self.pending.deny();
        let result = Self::convert_result(result, &mut self.endpoint.inner, &mut self.request);

        (self.request, result)
    }

    /// Tells the system that the resource owner with the given id has approved the grant.
    fn authorize(mut self, who: String) -> (R, Result<R::Response, E::Error>) {
        let result = self.pending.authorize(self.endpoint, who.into());
        let result = Self::convert_result(result, &mut self.endpoint.inner, &mut self.request);

        (self.request, result)
    }

    fn convert_result(
        result: Result<Url, AuthorizationError>, endpoint: &mut E, request: &mut R,
    ) -> Result<R::Response, E::Error> {
        match result {
            Ok(url) => {
                let mut response = endpoint.response(
                    request,
                    InnerTemplate::Redirect {
                        authorization_error: None,
                    }
                    .into(),
                )?;
                response.redirect(url).map_err(|err| endpoint.web_error(err))?;
                Ok(response)
            }
            Err(err) => authorization_error(endpoint, request, err),
        }
    }
}

impl<E: Endpoint<R>, R: WebRequest> WrappedAuthorization<E, R> {
    fn owner_solicitor(&mut self) -> &mut dyn OwnerSolicitor<R> {
        self.inner.owner_solicitor().unwrap()
    }
}

impl<E: Endpoint<R>, R: WebRequest> AuthorizationEndpoint for WrappedAuthorization<E, R> {
    fn registrar(&self) -> &dyn Registrar {
        self.inner.registrar().unwrap()
    }

    fn authorizer(&mut self) -> &mut dyn Authorizer {
        self.inner.authorizer_mut().unwrap()
    }

    fn extension(&mut self) -> &mut dyn Extension {
        self.inner
            .extension()
            .and_then(super::Extension::authorization)
            .unwrap_or(&mut self.extension_fallback)
    }
}

impl<'a, R: WebRequest + 'a> WrappedRequest<'a, R> {
    pub fn new(request: &'a mut R) -> Self {
        Self::new_or_fail(request).unwrap_or_else(Self::from_err)
    }

    fn new_or_fail(request: &'a mut R) -> Result<Self, R::Error> {
        Ok(WrappedRequest {
            request: PhantomData,
            query: request.query()?,
            error: None,
        })
    }

    fn from_err(err: R::Error) -> Self {
        WrappedRequest {
            request: PhantomData,
            query: Cow::Owned(Default::default()),
            error: Some(err),
        }
    }
}

impl<'a, R: WebRequest + 'a> AuthorizationRequest for WrappedRequest<'a, R> {
    fn valid(&self) -> bool {
        self.error.is_none()
    }

    fn client_id(&self) -> Option<Cow<str>> {
        self.query.unique_value("client_id")
    }

    fn scope(&self) -> Option<Cow<str>> {
        self.query.unique_value("scope")
    }

    fn redirect_uri(&self) -> Option<Cow<str>> {
        self.query.unique_value("redirect_uri")
    }

    fn state(&self) -> Option<Cow<str>> {
        self.query.unique_value("state")
    }

    fn response_type(&self) -> Option<Cow<str>> {
        self.query.unique_value("response_type")
    }

    fn extension(&self, key: &str) -> Option<Cow<str>> {
        self.query.unique_value(key)
    }
}