Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gate dependencies behind feature flags #177

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
8 changes: 4 additions & 4 deletions .cirrus.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ stable_task:
- CRATE: oxide-auth-db
OXIDE_AUTH_SKIP_REDIS: yes
- CRATE: db-example
build_script: cargo build -p "$CRATE" --examples
test_script: cargo test -p "$CRATE"
build_script: cargo build -p "$CRATE" --examples --all-features
test_script: cargo test -p "$CRATE" --all-features
before_cache_script: rm -rf $CARGO_HOME/registry/index

nightly_task:
Expand All @@ -37,8 +37,8 @@ nightly_task:
- CRATE: oxide-auth-db
OXIDE_AUTH_SKIP_REDIS: yes
- CRATE: db-example
build_script: cargo build -p "$CRATE" --examples
test_script: cargo test -p "$CRATE"
build_script: cargo build -p "$CRATE" --examples --all-features
test_script: cargo test -p "$CRATE" --all-features
before_cache_script: rm -rf $CARGO_HOME/registry/index

release_task:
Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
[workspace]
resolver = "2"
members = [
"oxide-auth",
"oxide-auth-async",
Expand Down
59 changes: 48 additions & 11 deletions examples/support/iron.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ use iron::{headers, modifiers, IronResult, Request, Response};
use iron::middleware::Handler;
use iron::status::Status;
use reqwest::header;
use oxide_auth::primitives::generator::{Encoder, DataRepr};

pub struct RmpTokenEncoder;

impl Encoder for RmpTokenEncoder {
fn encode(&self, value: DataRepr) -> Result<Vec<u8>, ()> {
rmp_serde::to_vec(&value).map_err(|_| ())
}

fn decode(&self, value: &[u8]) -> Result<DataRepr, ()> {
rmp_serde::from_slice(value).map_err(|_| ())
}
}

/// Rough client function mirroring core functionality of an oauth client. This is not actually
/// needed in your implementation but merely exists to provide an interactive example. It will
Expand All @@ -29,17 +42,23 @@ pub fn dummy_client() -> impl Handler + 'static {
let get_state = Arc::new(State::default());
let endpoint_state = get_state.clone();
let mut router = router::Router::new();
router.get("/endpoint", move |request: &mut Request| endpoint(get_state.clone(), request), "endpoint");
router.get("/", move |request: &mut Request| view(endpoint_state.clone(), request), "view");
router.get(
"/endpoint",
move |request: &mut Request| endpoint(get_state.clone(), request),
"endpoint",
);
router.get(
"/",
move |request: &mut Request| view(endpoint_state.clone(), request),
"view",
);
router
}

/// Receive the authorization codes at 'http://localhost:8021/endpoint'.
fn endpoint(state: Arc<State>, req: &mut Request) -> IronResult<Response> {
// Check the received parameters in the input
let query = req.url.as_ref()
.query_pairs()
.collect::<HashMap<_, _>>();
let query = req.url.as_ref().query_pairs().collect::<HashMap<_, _>>();

if let Some(error) = query.get("error") {
let message = format!("Error during owner authorization: {}", error.as_ref());
Expand All @@ -48,7 +67,7 @@ fn endpoint(state: Arc<State>, req: &mut Request) -> IronResult<Response> {

let code = match query.get("code") {
None => return Ok(Response::with((Status::BadRequest, "Missing code"))),
Some(v) => v.clone()
Some(v) => v.clone(),
};

// Construct a request against http://localhost:8020/token, the access token endpoint
Expand All @@ -60,17 +79,29 @@ fn endpoint(state: Arc<State>, req: &mut Request) -> IronResult<Response> {
params.insert("redirect_uri", "http://localhost:8021/endpoint");
let access_token_request = client
.post("http://localhost:8020/token")
.form(&params).build().unwrap();
.form(&params)
.build()
.unwrap();
let mut token_response = match client.execute(access_token_request) {
Ok(response) => response,
Err(_) => return Ok(Response::with((Status::InternalServerError, "Could not fetch bearer token"))),
Err(_) => {
return Ok(Response::with((
Status::InternalServerError,
"Could not fetch bearer token",
)))
}
};

let mut token = String::new();
token_response.read_to_string(&mut token).unwrap();
let token_map: HashMap<String, String> = match serde_json::from_str(&token) {
Ok(response) => response,
Err(err) => return Ok(Response::with((Status::BadRequest, format!("Could not parse token response {:?}", err)))),
Err(err) => {
return Ok(Response::with((
Status::BadRequest,
format!("Could not parse token response {:?}", err),
)))
}
};

if token_map.get("error").is_some() {
Expand Down Expand Up @@ -111,11 +142,17 @@ fn view(state: Arc<State>, _: &mut Request) -> IronResult<Response> {
let page_request = client
.get("http://localhost:8020/")
.header(header::AUTHORIZATION, format!("Bearer {}", token))
.build().unwrap();
.build()
.unwrap();

let mut page_response = match client.execute(page_request) {
Ok(response) => response,
Err(_) => return Ok(Response::with((Status::BadRequest, "Could not access protected resource"))),
Err(_) => {
return Ok(Response::with((
Status::BadRequest,
"Could not access protected resource",
)))
}
};

let mut protected_page = String::new();
Expand Down
4 changes: 3 additions & 1 deletion oxide-auth-actix/examples/actix-example/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ actix = "0.13"
actix-web = "4.2.1"
env_logger = "0.9"
futures = "0.3"
oxide-auth = { version = "0.5.0", path = "./../../../oxide-auth" }
oxide-auth = { version = "0.5.0", path = "./../../../oxide-auth", features = [
"argon2",
] }
oxide-auth-actix = { version = "0.2.0", path = "./../../" }
reqwest = { version = "0.11.10", features = ["blocking"] }
serde = "1.0"
Expand Down
28 changes: 16 additions & 12 deletions oxide-auth-actix/examples/actix-example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ use actix_web::{
use oxide_auth::{
endpoint::{Endpoint, OwnerConsent, OwnerSolicitor, Solicitation, QueryParameter},
frontends::simple::endpoint::{ErrorInto, FnSolicitor, Generic, Vacant},
primitives::prelude::{AuthMap, Client, ClientMap, RandomGenerator, Scope, TokenMap},
primitives::{
prelude::{AuthMap, Client, ClientMap, RandomGenerator, Scope, TokenMap},
registrar::Argon2,
},
};
use oxide_auth_actix::{
Authorize, OAuthMessage, OAuthOperation, OAuthRequest, OAuthResource, OAuthResponse, Refresh,
Expand Down Expand Up @@ -140,20 +143,21 @@ pub async fn main() -> std::io::Result<()> {

impl State {
pub fn preconfigured() -> Self {
let mut registrar = ClientMap::new(Argon2::default());
registrar.extend([Client::confidential(
"LocalClient",
"http://localhost:8021/endpoint"
.parse::<url::Url>()
.unwrap()
.into(),
"default-scope".parse().unwrap(),
"SecretSecret".as_bytes(),
)]);

State {
endpoint: Generic {
// A registrar with one pre-registered client
registrar: vec![Client::confidential(
"LocalClient",
"http://localhost:8021/endpoint"
.parse::<url::Url>()
.unwrap()
.into(),
"default-scope".parse().unwrap(),
"SecretSecret".as_bytes(),
)]
.into_iter()
.collect(),
registrar,
// Authorization tokens are 16 byte random keys to a memory hash map.
authorizer: AuthMap::new(RandomGenerator::new(16)),
// Bearer tokens are also random generated but 256-bit tokens, since they live longer
Expand Down
8 changes: 5 additions & 3 deletions oxide-auth-async/src/tests/access_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ use std::collections::HashMap;

use chrono::{Utc, Duration};

use super::{Body, CraftedRequest, CraftedResponse, Status, TestGenerator, ToSingleValueQuery};
use super::{
Body, CraftedRequest, CraftedResponse, Status, TestGenerator, ToSingleValueQuery, NoopPasswordPolicy,
};
use super::defaults::*;

struct AccessTokenSetup {
Expand Down Expand Up @@ -82,7 +84,7 @@ impl<'a> Endpoint<CraftedRequest> for AccessTokenEndpoint<'a> {

impl AccessTokenSetup {
fn private_client() -> Self {
let mut registrar = ClientMap::new();
let mut registrar = ClientMap::new(NoopPasswordPolicy);
let mut authorizer = AuthMap::new(TestGenerator("AuthToken".to_string()));
let issuer = TokenMap::new(TestGenerator("AccessToken".to_string()));

Expand Down Expand Up @@ -118,7 +120,7 @@ impl AccessTokenSetup {
}

fn public_client() -> Self {
let mut registrar = ClientMap::new();
let mut registrar = ClientMap::new(NoopPasswordPolicy);
let mut authorizer = AuthMap::new(TestGenerator("AuthToken".to_string()));
let issuer = TokenMap::new(TestGenerator("AccessToken".to_string()));

Expand Down
4 changes: 2 additions & 2 deletions oxide-auth-async/src/tests/authorization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use oxide_auth::{

use crate::endpoint::{Endpoint, OwnerSolicitor, authorization::AuthorizationFlow};

use super::{CraftedRequest, Status, TestGenerator, ToSingleValueQuery};
use super::{CraftedRequest, Status, TestGenerator, ToSingleValueQuery, NoopPasswordPolicy};
use super::{Allow, Deny};
use super::defaults::*;

Expand Down Expand Up @@ -70,7 +70,7 @@ struct AuthorizationSetup {

impl AuthorizationSetup {
fn new() -> AuthorizationSetup {
let mut registrar = ClientMap::new();
let mut registrar = ClientMap::new(NoopPasswordPolicy);
let authorizer = AuthMap::new(TestGenerator("AuthToken".to_string()));

let client = Client::confidential(
Expand Down
6 changes: 3 additions & 3 deletions oxide-auth-async/src/tests/client_credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
endpoint::{client_credentials::ClientCredentialsFlow, Endpoint, OwnerSolicitor},
};

use super::{CraftedRequest, Status, TestGenerator, ToSingleValueQuery};
use super::{CraftedRequest, Status, TestGenerator, ToSingleValueQuery, NoopPasswordPolicy};
use super::{Allow, Deny};
use super::defaults::*;

Expand Down Expand Up @@ -74,7 +74,7 @@ struct ClientCredentialsSetup {

impl ClientCredentialsSetup {
fn new() -> ClientCredentialsSetup {
let mut registrar = ClientMap::new();
let mut registrar = ClientMap::new(NoopPasswordPolicy);
let authorizer = AuthMap::new(TestGenerator("AuthToken".to_string()));
let issuer = TokenMap::new(TestGenerator("AuthToken".to_owned()));

Expand All @@ -97,7 +97,7 @@ impl ClientCredentialsSetup {
}

fn public_client() -> Self {
let mut registrar = ClientMap::new();
let mut registrar = ClientMap::new(NoopPasswordPolicy);
let authorizer = AuthMap::new(TestGenerator("AuthToken".to_string()));
let issuer = TokenMap::new(TestGenerator("AccessToken".to_owned()));

Expand Down
20 changes: 19 additions & 1 deletion oxide-auth-async/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,32 @@ use std::borrow::Cow;
use std::collections::HashMap;

use oxide_auth::{
primitives::generator::TagGrant,
primitives::{
generator::TagGrant,
registrar::{PasswordPolicy, RegistrarError},
},
endpoint::{WebRequest, WebResponse, OwnerConsent, QueryParameter, Solicitation},
primitives::grant::Grant,
};
use url::Url;

use crate::endpoint::OwnerSolicitor;

struct NoopPasswordPolicy;

impl PasswordPolicy for NoopPasswordPolicy {
fn check(&self, client_id: &str, passphrase: &[u8], stored: &[u8]) -> Result<(), RegistrarError> {
let other = self.store(client_id, passphrase);
(other == stored).then_some(()).ok_or(RegistrarError::Unspecified)
}

fn store(&self, client_id: &str, passphrase: &[u8]) -> Vec<u8> {
let mut acc = client_id.as_bytes().to_vec();
acc.extend_from_slice(passphrase);
acc
}
}

/// Open and simple implementation of `WebRequest`.
#[derive(Clone, Debug, Default)]
struct CraftedRequest {
Expand Down
5 changes: 3 additions & 2 deletions oxide-auth-async/src/tests/refresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use oxide_auth::{
frontends::simple::endpoint::Error,
};

use crate::tests::NoopPasswordPolicy;
use crate::{
endpoint::{refresh::RefreshFlow, Endpoint, resource::ResourceFlow},
primitives::{Issuer},
Expand Down Expand Up @@ -76,7 +77,7 @@ struct RefreshTokenSetup {

impl RefreshTokenSetup {
fn private_client() -> Self {
let mut registrar = ClientMap::new();
let mut registrar = ClientMap::new(NoopPasswordPolicy);
let mut issuer = TokenMap::new(RandomGenerator::new(16));

let client = Client::confidential(
Expand Down Expand Up @@ -114,7 +115,7 @@ impl RefreshTokenSetup {
}

fn public_client() -> Self {
let mut registrar = ClientMap::new();
let mut registrar = ClientMap::new(NoopPasswordPolicy);
let mut issuer = TokenMap::new(RandomGenerator::new(16));

let client = Client::public(
Expand Down
6 changes: 4 additions & 2 deletions oxide-auth-db/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ license = "MIT OR Apache-2.0"
edition = "2018"

[dependencies]
oxide-auth = { version = "0.5.1", path = "../oxide-auth" }
oxide-auth = { version = "0.5.1", path = "../oxide-auth", features = [
"argon2",
] }
once_cell = "1.3.1"
serde = { version = "1.0.101", features = ["derive"] }
serde_json = "1.0"
r2d2_redis = {version = "0.14", optional = true }
r2d2_redis = { version = "0.14", optional = true }
url = "2"
anyhow = "1.0"
log = "0.4.8"
Expand Down
8 changes: 4 additions & 4 deletions oxide-auth-db/src/primitives/db_registrar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl Extend<Client> for DBRegistrar {
I: IntoIterator<Item = Client>,
{
iter.into_iter().for_each(|client| {
self.register_client(client);
let _ = self.register_client(client);
})
}
}
Expand Down Expand Up @@ -196,7 +196,7 @@ mod tests {
"client:".parse().unwrap(),
)
.unwrap();
db_registrar.register_client(client);
let _ = db_registrar.register_client(client);

assert_eq!(
db_registrar
Expand Down Expand Up @@ -256,7 +256,7 @@ mod tests {
"default".parse().unwrap(),
);

oauth_service.register_client(public_client);
let _ = oauth_service.register_client(public_client);
oauth_service
.check(public_id, None)
.expect("Authorization of public client has changed");
Expand All @@ -272,7 +272,7 @@ mod tests {
private_passphrase,
);

oauth_service.register_client(private_client);
let _ = oauth_service.register_client(private_client);

oauth_service
.check(private_id, Some(private_passphrase))
Expand Down
6 changes: 5 additions & 1 deletion oxide-auth-iron/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ serde_urlencoded = "0.7"
url = "2"

[dev-dependencies]
oxide-auth = { version = "0.5.0", path = "../oxide-auth", features = [
"argon2",
] }
reqwest = { version = "0.11.10", features = ["blocking"] }
rmp-serde = "1.1.2"
router = "0.6.0"
serde = { version = "1.0", features = ["derive"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Loading