Skip to content

Commit

Permalink
Feature: Tutorial updates and Auth Imports Reorg (#67)
Browse files Browse the repository at this point in the history
  • Loading branch information
bkonkle authored Dec 5, 2023
1 parent d98663b commit b79ea27
Show file tree
Hide file tree
Showing 14 changed files with 161 additions and 139 deletions.
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.16.0]

### Added

- `tutorial`: More revisions to the tutorial documentation.

### Changed

- `nakago-axum`: Renamed the `auth::subject::Provide` provider for `Validator` - which didn't make sense - to `validator::Provide`.

## [0.15.0]

### Removed
Expand Down Expand Up @@ -228,6 +238,7 @@ Expect major changes to the Application and Lifecycle systems going forward, bui
- Injection Providers
- Documentation

[0.16.0]: https://github.com/bkonkle/nakago/compare/0.15.0...0.16.0
[0.15.0]: https://github.com/bkonkle/nakago/compare/0.14.1...0.15.0
[0.14.1]: https://github.com/bkonkle/nakago/compare/0.14.0...0.14.1
[0.14.0]: https://github.com/bkonkle/nakago/compare/0.13.0...0.14.0
Expand Down
2 changes: 1 addition & 1 deletion examples/async-graphql/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ futures = "0.3"
hyper = "0.14"
log = "0.4"
nakago = "0.14"
nakago-axum = "0.14"
nakago-axum = "0.16"
nakago-derive = "0.8"
nakago-sea-orm = "0.14"
nakago-async-graphql = "0.15"
Expand Down
4 changes: 2 additions & 2 deletions examples/async-graphql/src/init.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use nakago::{inject, EventType};
use nakago_axum::{
auth::{self, jwks, Validator, JWKS},
auth::{jwks, validator, Validator, JWKS},
AxumApplication,
};

Expand All @@ -21,7 +21,7 @@ pub async fn app() -> inject::Result<AxumApplication<Config>> {
app.provide(&JWKS, jwks::Provide::default().with_config_tag(&CONFIG))
.await?;

app.provide_type::<Validator>(auth::subject::Provide::default())
app.provide_type::<Validator>(validator::Provide::default())
.await?;

app.provide(
Expand Down
4 changes: 2 additions & 2 deletions examples/async-graphql/tests/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use anyhow::Result;
use axum::http::HeaderValue;
use fake::{Fake, Faker};
use futures_util::{stream::SplitStream, Future, SinkExt, StreamExt};
use nakago_axum::auth::{self, Validator};
use nakago_axum::auth::{validator, Validator};
use serde::Deserialize;
use tokio::{net::TcpStream, time::timeout};
use tokio_tungstenite::{
Expand Down Expand Up @@ -40,7 +40,7 @@ impl Utils {
pub async fn init() -> Result<Self> {
let app = init::app().await?;

app.replace_type_with::<Validator>(auth::subject::ProvideUnverified::default())
app.replace_type_with::<Validator>(validator::ProvideUnverified::default())
.await?;

let config_path = std::env::var("CONFIG_PATH_ASYNC_GRAPHQL")
Expand Down
2 changes: 1 addition & 1 deletion examples/simple/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ futures = "0.3"
hyper = "0.14"
log = "0.4"
nakago = "0.14"
nakago-axum = "0.14"
nakago-axum = "0.16"
nakago-derive = "0.8"
pico-args = "0.5.0"
pretty_env_logger = "0.5"
Expand Down
4 changes: 2 additions & 2 deletions examples/simple/src/init.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use nakago::{inject, EventType};
use nakago_axum::{
auth::{self, jwks, Validator, JWKS},
auth::{jwks, validator, Validator, JWKS},
config, AxumApplication,
};

Expand All @@ -18,7 +18,7 @@ pub async fn app() -> inject::Result<AxumApplication<Config>> {
app.provide(&JWKS, jwks::Provide::default().with_config_tag(&CONFIG))
.await?;

app.provide_type::<Validator>(auth::subject::Provide::default())
app.provide_type::<Validator>(validator::Provide::default())
.await?;

// Loading
Expand Down
4 changes: 2 additions & 2 deletions examples/simple/tests/utils.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::ops::Deref;

use anyhow::Result;
use nakago_axum::auth::{self, Validator};
use nakago_axum::auth::{validator, Validator};

use nakago_examples_simple::{init, Config};

Expand All @@ -19,7 +19,7 @@ impl TestUtils {
pub async fn init() -> Result<Self> {
let app = init::app().await?;

app.replace_type_with::<Validator>(auth::subject::ProvideUnverified::default())
app.replace_type_with::<Validator>(validator::ProvideUnverified::default())
.await?;

let config_path = std::env::var("CONFIG_PATH_SIMPLE")
Expand Down
2 changes: 1 addition & 1 deletion nakago_async_graphql/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ figment = { version = "0.10", features = ["env"] }
hyper = "0.14"
log = "0.4"
nakago = "0.14"
nakago-axum = "0.14"
nakago-axum = "0.16"
nakago-derive = "0.8"
pretty_env_logger = "0.5"
rand = "0.8"
Expand Down
2 changes: 1 addition & 1 deletion nakago_axum/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "nakago-axum"
version = "0.14.1"
version = "0.16.0"
authors = ["Brandon Konkle <[email protected]>"]
edition = "2021"
description = "An Axum HTTP routes integration for Nakago"
Expand Down
60 changes: 3 additions & 57 deletions nakago_axum/src/auth/jwks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,17 @@ use std::{marker::PhantomData, sync::Arc};
use async_trait::async_trait;
use axum::extract::FromRef;
use biscuit::{
jwa::SignatureAlgorithm,
jwk::{AlgorithmParameters, JWKSet, JWK},
jws::{Header, Secret},
ClaimsSet, Empty, JWT,
jws::Secret,
Empty,
};
use hyper::{self, body::to_bytes, client::HttpConnector, Body, Method, Request};
use hyper_tls::HttpsConnector;
use nakago::{self, inject, Inject, Provider, Tag};
use nakago_derive::Provider;
use thiserror::Error;

use super::{Config, Error};
use super::Config;

/// The JWKS Tag
pub const JWKS: Tag<JWKSet<Empty>> = Tag::new("auth::JWKS");
Expand Down Expand Up @@ -88,59 +87,6 @@ pub fn get_secret(jwk: JWK<Empty>) -> Result<Secret, ClientError> {
Ok(secret)
}

/// A validator for JWTs that uses a JWKS key set to validate the token
#[derive(Clone)]
pub enum Validator {
/// A validator that uses a JWKS key set to validate the token
KeySet(Arc<JWKSet<Empty>>),

/// A validator that does not validate the token, used for testing
Unverified,
}

impl Validator {
/// Get a validated payload from a JWT string
pub fn get_payload(&self, jwt: &str) -> Result<ClaimsSet<Empty>, Error> {
match self {
Validator::KeySet(jwks) => {
// First extract without verifying the header to locate the key-id (kid)
let token = JWT::<Empty, Empty>::new_encoded(jwt);

let header: Header<Empty> = token.unverified_header().map_err(Error::JWTToken)?;

let key_id = header.registered.key_id.ok_or(Error::JWKSVerification)?;

debug!("Fetching signing key for '{:?}'", key_id);

// Now that we have the key, construct our RSA public key secret
let secret = get_secret_from_key_set(jwks, &key_id)
.map_err(|_err| Error::JWKSVerification)?;

// Now fully verify and extract the token
let token = token
.into_decoded(&secret, SignatureAlgorithm::RS256)
.map_err(Error::JWTToken)?;

let payload = token.payload().map_err(Error::JWTToken)?;

debug!(
"Successfully verified token with subject: {:?}",
payload.registered.subject
);

Ok(payload.clone())
}
Validator::Unverified => {
let token = JWT::<Empty, Empty>::new_encoded(jwt);

let payload = &token.unverified_payload().map_err(Error::JWTToken)?;

Ok(payload.clone())
}
}
}
}

/// Possible errors during jwks retrieval
#[derive(Debug, Error)]
pub enum ClientError {
Expand Down
6 changes: 5 additions & 1 deletion nakago_axum/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ pub mod jwks;
/// JWT authentication
pub mod subject;

/// Validation
pub mod validator;

pub use config::Config;
pub use errors::Error;
pub use jwks::{Validator, JWKS};
pub use jwks::JWKS;
pub use subject::Subject;
pub use validator::Validator;
57 changes: 2 additions & 55 deletions nakago_axum/src/auth/subject.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,12 @@
#![allow(unused_imports)]
use std::sync::Arc;

use async_trait::async_trait;
use axum::{
extract::{FromRef, FromRequestParts},
Extension,
};
use biscuit::{
jwa::SignatureAlgorithm,
jwk::JWKSet,
jws::{Compact, Header},
ClaimsSet, Empty, JWT,
};
use axum::extract::FromRequestParts;
use http::{header::AUTHORIZATION, request::Parts, HeaderMap, HeaderValue};
use nakago::{inject, Dependency, Inject, Provider, Tag};
use nakago_derive::Provider;

use crate::State;

use super::{
jwks::{get_secret_from_key_set, Validator, JWKS},
Error::{self, InvalidAuthHeader, MissingValidator},
Validator,
};

const BEARER: &str = "Bearer ";
Expand Down Expand Up @@ -83,42 +69,3 @@ pub fn jwt_from_header(headers: &HeaderMap<HeaderValue>) -> Result<Option<&str>,

Ok(Some(auth_header.trim_start_matches(BEARER)))
}

/// Provide the State needed in order to use the `Subject` extractor in an Axum handler
///
/// **Provides:** `Validator`
///
/// **Depends on:**
/// - `Tag(auth::JWKS)`
#[derive(Default)]
pub struct Provide {}

#[Provider]
#[async_trait]
impl Provider<Validator> for Provide {
async fn provide(self: Arc<Self>, i: Inject) -> inject::Result<Arc<Validator>> {
let jwks = i.get(&JWKS).await?;

let validator = Validator::KeySet(jwks);

Ok(Arc::new(validator))
}
}

/// Provide the test ***unverified*** AuthState used in testing, which trusts any token given to it
///
/// **WARNING: This is insecure and should only be used in testing**
///
/// **Provides:** `Validator`
#[derive(Default)]
pub struct ProvideUnverified {}

#[Provider]
#[async_trait]
impl Provider<Validator> for ProvideUnverified {
async fn provide(self: Arc<Self>, _i: Inject) -> inject::Result<Arc<Validator>> {
let validator = Validator::Unverified;

Ok(Arc::new(validator))
}
}
Loading

0 comments on commit b79ea27

Please sign in to comment.