mod endpoints;
mod keys;
mod model;
pub mod verify;
use std::future::Future;
use std::pin::Pin;
use fastauth_core::plugin_prelude::*;
use fastauth_core::routes::GetSession;
use http::header::ACCESS_CONTROL_EXPOSE_HEADERS;
use http::{HeaderName, HeaderValue};
use serde_json::{Map, Value};
pub use endpoints::{
GetJwks, GetToken, Jwks, RotateKeys, RotatedKey, SignJwt, SignJwtInput, TokenOutput, VerifyJwt,
VerifyJwtInput, VerifyJwtOutput,
};
pub use jsonwebtoken;
pub use model::JsonWebKey;
pub use verify::{JwksVerifier, VerifyError};
pub const SET_AUTH_JWT: &str = "set-auth-jwt";
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum JwtAlgorithm {
#[default]
EdDSA,
ES256,
RS256,
}
impl JwtAlgorithm {
pub fn name(self) -> &'static str {
match self {
JwtAlgorithm::EdDSA => "EdDSA",
JwtAlgorithm::ES256 => "ES256",
JwtAlgorithm::RS256 => "RS256",
}
}
}
type Claims = Map<String, Value>;
type DefinePayload = Arc<
dyn Fn(SessionView) -> Pin<Box<dyn Future<Output = Result<Claims, AuthError>> + Send>>
+ Send
+ Sync,
>;
#[derive(Clone)]
pub struct Jwt {
alg: JwtAlgorithm,
issuer: Option<String>,
audience: Option<String>,
expiration_time: Duration,
rotation_interval: Option<Duration>,
grace_period: Duration,
set_jwt_header: bool,
define_payload: Option<DefinePayload>,
}
impl std::fmt::Debug for Jwt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Jwt")
.field("alg", &self.alg)
.field("issuer", &self.issuer)
.field("audience", &self.audience)
.field("expiration_time", &self.expiration_time)
.field("rotation_interval", &self.rotation_interval)
.field("grace_period", &self.grace_period)
.finish_non_exhaustive()
}
}
impl Default for Jwt {
fn default() -> Self {
Self {
alg: JwtAlgorithm::EdDSA,
issuer: None,
audience: None,
expiration_time: Duration::minutes(15),
rotation_interval: None,
grace_period: Duration::days(30),
set_jwt_header: true,
define_payload: None,
}
}
}
impl Jwt {
pub fn new() -> Self {
Self::default()
}
pub fn algorithm(mut self, alg: JwtAlgorithm) -> Self {
self.alg = alg;
self
}
pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
self.issuer = Some(issuer.into());
self
}
pub fn audience(mut self, audience: impl Into<String>) -> Self {
self.audience = Some(audience.into());
self
}
pub fn expiration_time(mut self, ttl: Duration) -> Self {
self.expiration_time = ttl;
self
}
pub fn rotation_interval(mut self, interval: Duration) -> Self {
self.rotation_interval = Some(interval);
self
}
pub fn grace_period(mut self, grace: Duration) -> Self {
self.grace_period = grace;
self
}
pub fn disable_jwt_header(mut self) -> Self {
self.set_jwt_header = false;
self
}
pub fn define_payload<F, Fut>(mut self, define: F) -> Self
where
F: Fn(SessionView) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Map<String, Value>, AuthError>> + Send + 'static,
{
self.define_payload = Some(Arc::new(move |session| Box::pin(define(session))));
self
}
}
impl Plugin for Jwt {
const ID: &'static str = "jwt";
type Requires = ();
type UserFields = ();
type SessionFields = ();
fn schema(&self, schema: &mut SchemaBuilder) {
schema.model::<JsonWebKey>();
}
fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
app.endpoint(GetJwks)
.endpoint(GetToken)
.server_endpoint::<SignJwt>()
.server_endpoint::<VerifyJwt>()
.server_endpoint::<RotateKeys>();
if self.set_jwt_header {
app.hook::<GetSession>().after(set_jwt_header);
}
}
}
async fn set_jwt_header<D: Adapter>(
ctx: HookCtx<D>,
output: Option<Value>,
) -> Result<After<Option<Value>>, AuthError> {
if let Some(session) = ctx.session() {
let token = keys::session_token(&ctx, ctx.plugin::<Jwt>(), session).await?;
let value = HeaderValue::from_str(&token).map_err(AuthError::internal)?;
ctx.set_header(HeaderName::from_static(SET_AUTH_JWT), value);
ctx.set_header(
ACCESS_CONTROL_EXPOSE_HEADERS,
HeaderValue::from_static(SET_AUTH_JWT),
);
}
Ok(After::Continue(output))
}
pub trait JwtExt: AuthInstance + Sized {
fn jwt<I>(&self) -> JwtApi<'_, Self>
where
Self: HasPlugin<Jwt, I>,
{
JwtApi {
auth: self,
headers: HeaderMap::new(),
}
}
}
impl<A: AuthInstance> JwtExt for A {}
pub struct JwtApi<'a, A> {
auth: &'a A,
headers: HeaderMap,
}
impl<A> std::fmt::Debug for JwtApi<'_, A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("JwtApi")
}
}
impl<A: AuthInstance> JwtApi<'_, A> {
pub fn headers(mut self, headers: &HeaderMap) -> Self {
self.headers = headers.clone();
self
}
async fn call<E: Endpoint<A::Db>>(
&self,
endpoint: &E,
input: E::Input,
) -> Result<E::Output, AuthError> {
Ok(self
.auth
.api()
.headers(&self.headers)
.call(endpoint, input)
.await?
.data)
}
pub async fn token(&self) -> Result<String, AuthError> {
Ok(self.call(&GetToken, Map::new()).await?.token)
}
pub async fn sign(&self, claims: Map<String, Value>) -> Result<String, AuthError> {
Ok(self
.call(&SignJwt, SignJwtInput { payload: claims })
.await?
.token)
}
pub async fn verify(&self, token: &str) -> Result<Option<Map<String, Value>>, AuthError> {
let input = VerifyJwtInput {
token: token.to_owned(),
issuer: None,
};
Ok(self.call(&VerifyJwt, input).await?.payload)
}
pub async fn jwks(&self) -> Result<Jwks, AuthError> {
self.call(&GetJwks, Map::new()).await
}
pub async fn rotate(&self) -> Result<Id, AuthError> {
Ok(self.call(&RotateKeys, Empty {}).await?.kid)
}
}