Browse Source

Initial publish to GitHub.

tags/0.0.5
Jeb Rosen 1 year ago
commit
46991c7d4e
11 changed files with 1146 additions and 0 deletions
  1. +3
    -0
      .gitignore
  2. +29
    -0
      Cargo.toml
  3. +201
    -0
      LICENSE-APACHE
  4. +19
    -0
      LICENSE-MIT
  5. +21
    -0
      README.md
  6. +4
    -0
      examples/user_info_hyper_sync_rustls/.gitignore
  7. +14
    -0
      examples/user_info_hyper_sync_rustls/Cargo.toml
  8. +154
    -0
      examples/user_info_hyper_sync_rustls/src/main.rs
  9. +448
    -0
      src/core.rs
  10. +114
    -0
      src/hyper_sync_rustls_adapter.rs
  11. +139
    -0
      src/lib.rs

+ 3
- 0
.gitignore View File

@@ -0,0 +1,3 @@
Cargo.lock
/target
**/*.rs.bk

+ 29
- 0
Cargo.toml View File

@@ -0,0 +1,29 @@
[package]
name = "rocket_oauth2"
version = "0.0.4"
description = "OAuth2 for Rocket applications"
documentation = "https://docs.rs/rocket_oauth2/"
homepage = "https://github.com/jebrosen/rocket_oauth2"
repository = "https://github.com/jebrosen/rocket_oauth2"
authors = ["Jeb Rosen <jeb@jebrosen.com>"]
license = "MIT/Apache2.0"
edition = "2018"

[workspace]
members = ["examples/user_info_hyper_sync_rustls"]

[features]
default = ["hyper_sync_rustls_adapter"]
hyper_sync_rustls_adapter = ["hyper", "hyper-sync-rustls"]

[dependencies]
log = "0.4"
rand = "0.5"
rocket = "0.4.0-rc.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
url = "1.7"

# hyper-sync-rustls adapter
hyper = { version = "0.10", optional = true }
hyper-sync-rustls = { version = "0.3.0-rc.4", optional = true }

+ 201
- 0
LICENSE-APACHE View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.

"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and

(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and

(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and

(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

+ 19
- 0
LICENSE-MIT View File

@@ -0,0 +1,19 @@
The MIT License (MIT)
Copyright (c) 2018 Jeb Rosen

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 21
- 0
README.md View File

@@ -0,0 +1,21 @@
# rocket_oauth2

`rocket_oauth2` makes it easy to use OAuth2 in Rocket applications:

* Facilitates OAuth 2.0 client functionality to obtain authorization from users.
* Handles the authorization callback and token exchange.
* Runs an application-specific callback when a token has been successfully obtained.
* Optionally mounts a login route that redirects to the authorization endpoint.
* Supports attachment of multiple callbacks and service providers.

## Example

See the `examples` directory for more details, including the implementations
of `GitHubCallback` and `GoogleCallback`.

## License

`rocket_oauth2` is licensed under either of the following, at your option:

* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT License ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

+ 4
- 0
examples/user_info_hyper_sync_rustls/.gitignore View File

@@ -0,0 +1,4 @@
Cargo.lock
Rocket.toml
/target
**/*.rs.bk

+ 14
- 0
examples/user_info_hyper_sync_rustls/Cargo.toml View File

@@ -0,0 +1,14 @@
[package]
name = "user_info_hyper_sync_rustls"
version = "0.0.0"
authors = ["jeb <jeb@jebrosen.com>"]
publish = false
edition = "2018"

[dependencies]
hyper = "0.10"
hyper-sync-rustls = "0.3.0-rc.3"
rocket = "0.4.0-rc.1"
rocket_oauth2 = { path = "../../", features = ["hyper_sync_rustls_adapter"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

+ 154
- 0
examples/user_info_hyper_sync_rustls/src/main.rs View File

@@ -0,0 +1,154 @@
#![feature(decl_macro, proc_macro_hygiene)]

use std::io::Read;

use hyper::{
header::{qitem, Accept, Authorization, Bearer, UserAgent},
mime::Mime,
net::HttpsConnector,
Client,
};
use hyper_sync_rustls;
use rocket::http::{Cookie, Cookies, SameSite};
use rocket::request::{self, FromRequest, Request};
use rocket::response::Redirect;
use rocket::{get, routes, Outcome};
use rocket_oauth2::hyper_sync_rustls_adapter::HyperSyncRustlsAdapter;
use rocket_oauth2::{OAuth2, TokenResponse};
use serde_json::{self, Value};

struct User {
pub username: String,
}

impl<'a, 'r> FromRequest<'a, 'r> for User {
type Error = ();

fn from_request(request: &'a Request<'r>) -> request::Outcome<User, ()> {
let mut cookies = request.guard::<Cookies<'_>>().expect("request cookies");
if let Some(cookie) = cookies.get_private("username") {
return Outcome::Success(User {
username: cookie.value().to_string(),
});
}

Outcome::Forward(())
}
}

/// User information to be retrieved from the GitHub API.
#[derive(serde::Deserialize)]
struct GitHubUserInfo {
#[serde(default)]
name: String,
}

fn github_callback(
request: &Request<'_>,
token: TokenResponse,
) -> Result<Redirect, Box<dyn (::std::error::Error)>> {
let https = HttpsConnector::new(hyper_sync_rustls::TlsClient::new());
let client = Client::with_connector(https);

// Use the token to retrieve the user's GitHub account information.
let mime: Mime = "application/vnd.github.v3+json"
.parse()
.expect("parse GitHub MIME type");
let response = client
.get("https://api.github.com/user")
.header(Authorization(format!("token {}", token.access_token)))
.header(Accept(vec![qitem(mime)]))
.header(UserAgent("rocket_oauth2 demo application".into()))
.send()?;

if !response.status.is_success() {
return Err(format!("got non-success status {}", response.status).into());
}

let user_info: GitHubUserInfo = serde_json::from_reader(response.take(2 * 1024 * 1024))?;

// Set a private cookie with the user's name, and redirect to the home page.
let mut cookies = request.guard::<Cookies<'_>>().expect("request cookies");
cookies.add_private(
Cookie::build("username", user_info.name)
.same_site(SameSite::Lax)
.finish(),
);
Ok(Redirect::to("/"))
}

/// User information to be retrieved from the Google People API.
#[derive(serde::Deserialize)]
struct GoogleUserInfo {
names: Vec<Value>,
}

fn google_callback(
request: &Request<'_>,
token: TokenResponse,
) -> Result<Redirect, Box<dyn (::std::error::Error)>> {
let https = HttpsConnector::new(hyper_sync_rustls::TlsClient::new());
let client = Client::with_connector(https);

// Use the token to retrieve the user's GitHub account information.
let response = client
.get("https://people.googleapis.com/v1/people/me?personFields=names")
.header(Authorization(Bearer {
token: token.access_token,
}))
.send()?;

let user_info: GoogleUserInfo = serde_json::from_reader(response.take(2 * 1024 * 1024))?;

let real_name = user_info
.names
.first()
.and_then(|n| n.get("displayName"))
.and_then(|s| s.as_str())
.unwrap_or("");

// Set a private cookie with the user's name, and redirect to the home page.
let mut cookies = request.guard::<Cookies<'_>>().expect("request cookies");
cookies.add_private(
Cookie::build("username", real_name.to_string())
.same_site(SameSite::Lax)
.finish(),
);
Ok(Redirect::to("/"))
}

#[get("/")]
fn index(user: User) -> String {
format!("Hi, {}!", user.username)
}

#[get("/", rank = 2)]
fn index_anonymous() -> &'static str {
"Please login (/login/github or /login/google)"
}

#[get("/logout")]
fn logout(mut cookies: Cookies<'_>) -> Redirect {
cookies.remove(Cookie::named("username"));
Redirect::to("/")
}

fn main() {
rocket::ignite()
.mount("/", routes![index, index_anonymous, logout])
.attach(OAuth2::fairing(
HyperSyncRustlsAdapter,
github_callback,
"github",
"/auth/github",
Some(("/login/github", vec!["user:read"])),
))
.attach(OAuth2::fairing(
HyperSyncRustlsAdapter,
google_callback,
"google",
"/auth/google",
Some(("/login/google", vec!["profile"])),
))
.launch();
}

+ 448
- 0
src/core.rs View File

@@ -0,0 +1,448 @@
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt::Debug;
use std::path::PathBuf;

use rocket::config::{self, Config, ConfigError, Table, Value};
use rocket::fairing::{AdHoc, Fairing};
use rocket::handler;
use rocket::http::uri::Absolute;
use rocket::http::{Cookie, Cookies, Method, SameSite, Status};
use rocket::outcome::{IntoOutcome, Outcome};
use rocket::request::{FormItems, FromForm, Request};
use rocket::response::{Redirect, Responder};
use rocket::{Data, FromForm, Route, State};
use serde_json::Value as JsonValue;

const STATE_COOKIE_NAME: &str = "rocket_oauth2_state";

/// The server's response to a successful token exchange, defined in
/// in RFC 6749 §5.1.
#[derive(serde::Deserialize)]
pub struct TokenResponse {
/// The access token issued by the authorization server.
pub access_token: String,
/// The type of token, described in RFC 6749 §7.1.
pub token_type: String,
/// The lifetime in seconds of the access token, if the authorization server
/// provided one.
pub expires_in: Option<i32>,
/// The refresh token, if the server provided one.
pub refresh_token: Option<String>,
/// The (space-separated) list of scopes associated with the access token.
/// The authorization server is required to provide this if it differs from
/// the requested set of scopes.
pub scope: Option<String>,

/// Additional values returned by the authorization server, if any.
#[serde(flatten)]
pub extras: HashMap<String, JsonValue>,
}

/// An OAuth2 `Adapater` can be implemented by any type that facilitates the
/// Authorization Code Grant as described in RFC 6749 §4.1. The implementing
/// type must be able to generate an authorization URI and perform the token
/// exchange.
pub trait Adapter: Send + Sync + 'static {
/// The `Error` type returned by this `Adapter` when a URI generation or
/// token exchange fails.
type Error: Debug;

/// Generate an authorization URI and state value as described by RFC 6749 §4.1.1.
fn authorization_uri(
&self,
config: &OAuthConfig,
scopes: &[&str],
) -> Result<(Absolute<'static>, String), Self::Error>;

/// Perform the token exchange in accordance with RFC 6749 §4.1.3 given the
/// authorization code provided by the service.
fn exchange_code(&self, config: &OAuthConfig, code: &str)
-> Result<TokenResponse, Self::Error>;
}

/// An OAuth2 `Callback` implements application-specific OAuth client logic,
/// such as setting login cookies and making database and API requests. It is
/// tied to a specific `Adapter`, and will recieve an instance of the Adapter's
/// `Token` type.
pub trait Callback: Send + Sync + 'static {
// TODO: Relax 'static. Would this need GAT/ATC?
/// The callback Responder type.
type Responder: Responder<'static>;

/// This method will be called when a token exchange has successfully
/// completed and will be provided with the request and the token.
/// Implementors should perform application-specific logic here, such as
/// checking a database or setting a login cookie.
fn callback(&self, request: &Request<'_>, token: TokenResponse) -> Self::Responder;
}

impl<F, R> Callback for F
where
F: Fn(&Request<'_>, TokenResponse) -> R + Send + Sync + 'static,
R: Responder<'static>,
{
type Responder = R;

fn callback(&self, request: &Request<'_>, token: TokenResponse) -> Self::Responder {
(self)(request, token)
}
}

/// Holds configuration for an OAuth application. This consists of the [Provider]
/// details, a `client_id` and `client_secret`, and a `redirect_uri`.
pub struct OAuthConfig {
provider: Provider,
client_id: String,
client_secret: String,
redirect_uri: String,
}

fn get_config_string(table: &Table, key: &str) -> config::Result<String> {
let value = table
.get(key)
.ok_or_else(|| ConfigError::Missing(key.into()))?;

let string = value
.as_str()
.ok_or_else(|| ConfigError::BadType(key.into(), "string", value.type_str(), "".into()))?;

Ok(string.to_string())
}

impl OAuthConfig {
/// Create a new OAuthConfig.
pub fn new(
provider: Provider,
client_id: String,
client_secret: String,
redirect_uri: String,
) -> OAuthConfig {
OAuthConfig {
provider,
client_id,
client_secret,
redirect_uri,
}
}

/// Constructs a OAuthConfig from Rocket configuration
pub fn from_config(config: &Config, name: &str) -> config::Result<OAuthConfig> {
let oauth = config.get_table("oauth")?;
let conf = oauth
.get(name)
.ok_or_else(|| ConfigError::Missing(name.to_string()))?;

let table = conf.as_table().ok_or_else(|| {
ConfigError::BadType(name.into(), "table", conf.type_str(), "".into())
})?;

let provider = match conf.get("provider") {
Some(v) => Provider::from_config_value(v),
None => Err(ConfigError::Missing("provider".to_string())),
}?;

let client_id = get_config_string(table, "client_id")?;
let client_secret = get_config_string(table, "client_secret")?;
let redirect_uri = get_config_string(table, "redirect_uri")?;

Ok(OAuthConfig::new(
provider,
client_id,
client_secret,
redirect_uri,
))
}

/// Gets the [Provider] for this configuration.
pub fn provider(&self) -> &Provider {
&self.provider
}

/// Gets the client id for this configuration.
pub fn client_id(&self) -> &str {
&self.client_id
}

/// Gets the client secret for this configuration.
pub fn client_secret(&self) -> &str {
&self.client_secret
}

/// Gets the redirect URI for this configuration.
pub fn redirect_uri(&self) -> &str {
&self.redirect_uri
}
}

/// The `OAuth2` structure implements OAuth in a Rocket application by setting
/// up OAuth-related route handlers.
///
/// ## Redirect handler
/// `OAuth2` handles the redirect URI. It verifies the `state` token to prevent
/// CSRF attacks, then instructs the Adapter to perform the token exchange. The
/// resulting token is passed to the `Callback`.
///
/// ## Login handler
/// `OAuth2` optionally handles a login route, which simply redirects to the
/// authorization URI generated by the `Adapter`. Whether or not `OAuth2` is
/// handling a login URI, `get_redirect` can be used to get a `Redirect` to the
/// OAuth login flow manually.
pub struct OAuth2<A, C> {
adapter: A,
callback: C,
config: OAuthConfig,
default_scopes: Vec<String>,
}

impl<A: Adapter, C: Callback> OAuth2<A, C> {
/// Returns an OAuth2 fairing. The fairing will place an instance of
/// `OAuth2<A, C>` in managed state and mount a redirect handler. It will
/// also mount a login handler if `login` is `Some`.
pub fn fairing<CN, CU, LU, LS>(
adapter: A,
callback: C,
config_name: CN,
callback_uri: CU,
login: Option<(LU, Vec<LS>)>,
) -> impl Fairing
where
CN: Into<Cow<'static, str>>,
CU: Into<Cow<'static, str>>,
LU: Into<Cow<'static, str>>,
LS: Into<String>,
{
let config_name = config_name.into();
let callback_uri = callback_uri.into();
let mut login = login.map(|login| {
(
login.0.into(),
login.1.into_iter().map(Into::into).collect(),
)
});
AdHoc::on_attach("OAuth Init", move |rocket| {
let config = match OAuthConfig::from_config(rocket.config(), &config_name) {
Ok(c) => c,
Err(e) => {
log::error!("Invalid configuration: {:?}", e);
return Err(rocket);
}
};

let login = login
.as_mut()
.map(|l: &mut (Cow<'static, str>, Vec<String>)| {
(l.0.as_ref(), l.1.drain(..).collect())
});

Ok(rocket.attach(Self::custom(
adapter,
callback,
config,
&callback_uri,
login,
)))
})
}

/// Returns an OAuth2 fairing with custom configuration. The fairing will
/// place an instance of `OAuth2<A, C>` in managed state and mount a
/// redirect handler. It will also mount a login handler if `login` is
/// `Some`.
pub fn custom(
adapter: A,
callback: C,
config: OAuthConfig,
callback_uri: &str,
login: Option<(&str, Vec<String>)>,
) -> impl Fairing {
let mut routes = Vec::new();

routes.push(Route::new(
Method::Get,
callback_uri,
redirect_handler::<A, C>,
));

let mut default_scopes = vec![];
if let Some((login_uri, login_scopes)) = login {
routes.push(Route::new(Method::Get, login_uri, login_handler::<A, C>));
default_scopes = login_scopes;
}

let oauth2 = Self {
adapter,
callback,
config,
default_scopes,
};

AdHoc::on_attach("OAuth Mount", |rocket| {
Ok(rocket.manage(oauth2).mount("/", routes))
})
}

/// Prepare an authentication redirect. This sets a state cookie and returns
/// a `Redirect` to the provider's authorization page.
pub fn get_redirect(
&self,
cookies: &mut Cookies<'_>,
scopes: &[&str],
) -> Result<Redirect, A::Error> {
let (uri, state) = self.adapter.authorization_uri(&self.config, scopes)?;
cookies.add_private(
Cookie::build(STATE_COOKIE_NAME, state.clone())
.same_site(SameSite::Lax)
.finish(),
);
Ok(Redirect::to(uri))
}

// TODO: Decide if BadRequest is the appropriate error code.
// TODO: What do providers do if they *reject* the authorization?
/// Handle the redirect callback, delegating to the adapter and callback to
/// perform the token exchange and application-specific actions.
fn handle<'r>(&self, request: &'r Request<'_>, _data: Data) -> handler::Outcome<'r> {
// Parse the query data.
let query = request.uri().query().into_outcome(Status::BadRequest)?;

#[derive(FromForm)]
struct CallbackQuery {
code: String,
state: String,
}

let params = match CallbackQuery::from_form(&mut FormItems::from(query), false) {
Ok(p) => p,
Err(_) => return handler::Outcome::failure(Status::BadRequest),
};

{
// Verify that the given state is the same one in the cookie.
// Begin a new scope so that cookies is not kept around too long.
let mut cookies = request.guard::<Cookies<'_>>().expect("request cookies");
match cookies.get_private(STATE_COOKIE_NAME) {
Some(ref cookie) if cookie.value() == params.state => {
cookies.remove(cookie.clone());
}
_ => return handler::Outcome::failure(Status::BadRequest),
}
}

// Have the adapter perform the token exchange.
let token = match self.adapter.exchange_code(&self.config, &params.code) {
Ok(token) => token,
Err(e) => {
log::error!("Token exchange failed: {:?}", e);
return handler::Outcome::failure(Status::BadRequest);
}
};

// Run the callback.
let responder = self.callback.callback(request, token);
handler::Outcome::from(request, responder)
}
}

// These cannot be closures becuase of the lifetime parameter.
// TODO: cross-reference rust-lang/rust issues.

/// Handles the OAuth redirect route
fn redirect_handler<'r, A: Adapter, C: Callback>(
request: &'r Request<'_>,
data: Data,
) -> handler::Outcome<'r> {
let oauth = match request.guard::<State<'_, OAuth2<A, C>>>() {
Outcome::Success(oauth) => oauth,
Outcome::Failure(_) => return handler::Outcome::failure(Status::InternalServerError),
Outcome::Forward(()) => unreachable!(),
};
oauth.handle(request, data)
}

/// Handles a login route, performing a redirect
fn login_handler<'r, A: Adapter, C: Callback>(
request: &'r Request<'_>,
_data: Data,
) -> handler::Outcome<'r> {
let oauth = match request.guard::<State<'_, OAuth2<A, C>>>() {
Outcome::Success(oauth) => oauth,
Outcome::Failure(_) => return handler::Outcome::failure(Status::InternalServerError),
Outcome::Forward(()) => unreachable!(),
};
let mut cookies = request.guard::<Cookies<'_>>().expect("request cookies");
let scopes: Vec<_> = oauth.default_scopes.iter().map(String::as_str).collect();
handler::Outcome::from(request, oauth.get_redirect(&mut cookies, &scopes))
}

/// A `Provider` contains the authorization and token exchange URIs specific to
/// an OAuth service provider.
pub struct Provider {
/// The authorization URI associated with the service provider.
pub auth_uri: Cow<'static, str>,
/// The token exchange URI associated with the service provider.
pub token_uri: Cow<'static, str>,
}

impl Provider {
fn from_config_value(conf: &Value) -> Result<Provider, ConfigError> {
let type_error = || {
ConfigError::BadType(
"provider".into(),
"known provider or table",
"",
PathBuf::new(),
)
};

match conf {
Value::String(s) => Provider::from_known_name(s).ok_or_else(type_error),
Value::Table(t) => {
let auth_uri = get_config_string(t, "auth_uri")?.into();
let token_uri = get_config_string(t, "token_uri")?.into();

Ok(Provider {
auth_uri,
token_uri,
})
}
_ => Err(type_error()),
}
}
}

macro_rules! providers {
(@ $(($name:ident $docstr:expr) : $auth:expr, $token:expr),*) => {
$(
#[doc = $docstr]
#[allow(non_upper_case_globals)]
pub const $name: Provider = Provider {
auth_uri: Cow::Borrowed($auth),
token_uri: Cow::Borrowed($token),
};
)*

impl Provider {
fn from_known_name(name: &str) -> Option<Provider> {
match name {
$(
stringify!($name) => Some($name),
)*
_ => None,
}
}
}
};
($($name:ident : $auth:expr, $token:expr),* $(,)*) => {
providers!(@ $(($name concat!("A `Provider` suitable for authorizing users with ", stringify!($name), ".")) : $auth, $token),*);
};
}

providers! {
Discord: "https://discordapp.com/api/oauth2/authorize", "https://discordapp.com/api/oauth2/token",
Facebook: "https://www.facebook.com/v3.1/dialog/oauth", "https://graph.facebook.com/v3.1/oauth/access_token",
GitHub: "https://github.com/login/oauth/authorize", "https://github.com/login/oauth/access_token",
Google: "https://accounts.google.com/o/oauth2/v2/auth", "https://www.googleapis.com/oauth2/v4/token",
Reddit: "https://www.reddit.com/api/v1/authorize", "https://www.reddit.com/api/v1/access_token",
Yahoo: "https://api.login.yahoo.com/oauth2/request_auth", "https://api.login.yahoo.com/oauth2/get_token",
}

+ 114
- 0
src/hyper_sync_rustls_adapter.rs View File

@@ -0,0 +1,114 @@
//! [Adapter] implemented using [`hyper-sync-rustls`](https://github.com/SergioBenitez/hyper-sync-rustls).

use hyper;
use hyper_sync_rustls;

use std::io::Read;

use rocket::http::ext::IntoOwned;
use rocket::http::uri::{Absolute, Error as RocketUriError};
use serde_json::Error as SerdeJsonError;
use url::form_urlencoded::Serializer as UrlSerializer;
use url::ParseError;

use self::hyper::{
header::{Accept, ContentType},
net::HttpsConnector,
status::StatusCode,
Client, Error as HyperError, Url,
};
use super::{generate_state, Adapter, OAuthConfig, TokenResponse};

#[derive(Debug)]
enum ErrorKind {
/// An error in the provided authorization URI
UriError(ParseError),
/// An error in the completed authorization URI
RocketUriError(RocketUriError<'static>),
/// An error in the token exchange request
RequestError(HyperError),
/// A non-success response type
UnsuccessfulRequest(StatusCode),
/// An error in deserialization
DeserializationError(SerdeJsonError),

#[doc(hidden)]
__Nonexhaustive,
}

/// Error type for HyperSyncRustlsAdapter
#[derive(Debug)]
pub struct Error { kind: ErrorKind }

impl From<ErrorKind> for Error {
fn from(ek: ErrorKind) -> Error {
Error { kind: ek }
}
}

/// `Adapter` implementation that uses `hyper` and `rustls` to perform the token exchange.
pub struct HyperSyncRustlsAdapter;

impl Adapter for HyperSyncRustlsAdapter {
type Error = Error;

fn authorization_uri(
&self,
config: &OAuthConfig,
scopes: &[&str],
) -> Result<(Absolute<'static>, String), Self::Error> {
let state = generate_state();

let mut url = Url::parse(&config.provider().auth_uri).map_err(ErrorKind::UriError)?;
url.query_pairs_mut()
.append_pair("response_type", "code")
.append_pair("client_id", config.client_id())
.append_pair("redirect_uri", config.redirect_uri())
.append_pair("state", &state);

if !scopes.is_empty() {
url.query_pairs_mut()
.append_pair("scope", &scopes.join(" "));
}

Ok((
Absolute::parse(url.as_ref())
.map_err(|e| ErrorKind::RocketUriError(e.into_owned()))?
.into_owned(),
state,
))
}

fn exchange_code(
&self,
config: &OAuthConfig,
code: &str,
) -> Result<TokenResponse, Self::Error> {
let https = HttpsConnector::new(hyper_sync_rustls::TlsClient::new());
let client = Client::with_connector(https);

let mut ser = UrlSerializer::new(String::new());
ser.append_pair("grant_type", "authorization_code");
ser.append_pair("code", code);
ser.append_pair("redirect_uri", config.redirect_uri());
ser.append_pair("client_id", config.client_id());
ser.append_pair("client_secret", config.client_secret());

let req_str = ser.finish();

let request = client
.post(config.provider().token_uri.as_ref())
.header(Accept::json())
.header(ContentType::form_url_encoded())
.body(&req_str);

let response = request.send().map_err(ErrorKind::RequestError)?;
if !response.status.is_success() {
return Err(ErrorKind::UnsuccessfulRequest(response.status).into())
}

let token =
serde_json::from_reader(response.take(2 * 1024 * 1024)).map_err(ErrorKind::DeserializationError)?;
Ok(token)
}
}

+ 139
- 0
src/lib.rs View File

@@ -0,0 +1,139 @@
//! # rocket_oauth2
//!
//! OAuth2 ([RFC 6749](https://tools.ietf.org/html/rfc6749)) for
//! [Rocket](https://rocket.rs) applications.
//!
//! ## Requirements
//!
//! * Rocket 0.4
//!
//! ## API Stability
//!
//! `rocket_oauth2` is still in its early stages and the API is subject
//! to heavy change in the future.
//!
//! ## Features
//!
//! * Handles the Authorization Code Grant (RFC 6749, §4.1)
//! * Built-in support for a few popular OAuth2 providers
//! * Support for custom providers
//! * Support for custom adapters
//!
//! ## Not-yet-planned Features
//!
//! * Grant types other than Authorization Code.
//! * Refresh token support
//!
//! ## Design
//!
//! This crate is designed around 2 traits: [`Callback`] and [`Adapter`]. The
//! [`Adapter`] trait is implemented by types that can generate authorization
//! URLs and perform token exchanges. The [`Callback`] trait is implemented by
//! Rocket applications to perform application-specific actions when a token has
//! been exchanged successfully.
//!
//! Generally, a Rocket application will implement [`Callback`] on one type per
//! service the application will connect to. The [`OAuth2`] type registers
//! routes and handlers in the application for the OAuth2 redirect and an
//! optional login handler for convenience.
//!
//! ## Implementations
//!
//! `rocket_oauth2` currently provides only one [`Adapter`] itself:
//!
//! * `hyper_sync_rustls`: Uses [`hyper-sync-rustls`](https://github.com/SergioBenitez/hyper-sync-rustls).
//!
//! `hyper_sync_rustls` was chosen because it is already a dependency of Rocket.
//! In general, custom `Adapter`s should only be needed to work around
//! non-compliant service providers.
//!
//! ## Usage
//!
//! Add `rocket_oauth2` to your `Cargo.toml`:
//!
//! ```toml
//! rocket_oauth2 = { version = "0.0.0" }
//! ```
//!
//! Implement `Callback` for your type, or write a free function:
//!
//! ```rust
//! # extern crate rocket;
//! # extern crate rocket_oauth2;
//! # use rocket::http::{Cookie, Cookies, SameSite};
//! # use rocket::Request;
//! # use rocket::response::Redirect;
//! use rocket_oauth2::{Callback, OAuth2, TokenResponse};
//! use rocket_oauth2::hyper_sync_rustls_adapter::HyperSyncRustlsAdapter;
//!
//! fn github_callback(request: &Request, token: TokenResponse)
//! -> Result<Redirect, Box<::std::error::Error>>
//! {
//! let mut cookies = request.guard::<Cookies>().expect("request cookies");
//!
//! // Set a private cookie with the access token
//! cookies.add_private(
//! Cookie::build("token", token.access_token)
//! .same_site(SameSite::Lax)
//! .finish()
//! );
//! Ok(Redirect::to("/"))
//! }
//! ```
//!
//! Configure your OAuth client settings in `Rocket.toml`:
//! ```toml
//! [global.oauth.github]
//! provider = "GitHub"
//! client_id = "..."
//! client_secret = "..."
//! redirect_uri = "http://localhost:8000/auth/github"
//! ```
//!
//! Create and attach the [`OAuth2`] fairing:
//!
//! ```rust
//! # extern crate rocket;
//! # extern crate rocket_oauth2;
//! # use rocket::http::{Cookie, Cookies, SameSite};
//! # use rocket::Request;
//! # use rocket::response::Redirect;
//! use rocket::fairing::AdHoc;
//! use rocket_oauth2::{Callback, OAuth2, OAuthConfig, GitHub, TokenResponse};
//! use rocket_oauth2::hyper_sync_rustls_adapter::HyperSyncRustlsAdapter;
//!
//! # fn github_callback(request: &Request, token: TokenResponse)
//! # -> Result<Redirect, Box<::std::error::Error>>
//! # {
//! # unimplemented!();
//! # }
//!
//! # fn check_only() {
//! rocket::ignite()
//! .attach(OAuth2::fairing(
//! HyperSyncRustlsAdapter,
//! github_callback,
//! "github",
//!
//! // Set up a handler for the redirect uri
//! "/auth/github",
//!
//! // Set up a redirect from /login/github that will request the 'user:read' scope
//! Some(("/login/github", vec!["user:read"])),
//! ))
//! # ;
//! # }
//! ```

#![warn(future_incompatible, nonstandard_style, missing_docs)]

mod core;
pub use self::core::*;

#[cfg(feature = "hyper_sync_rustls_adapter")]
pub mod hyper_sync_rustls_adapter;

fn generate_state() -> String {
use rand::{distributions::Alphanumeric, thread_rng, Rng};
thread_rng().sample_iter(&Alphanumeric).take(20).collect()
}

Loading…
Cancel
Save