use fastauth_core::plugin_prelude::*;
use jsonwebtoken::jwk::JwkSet;
use serde_json::{Map, Value};
use crate::verify::JwksVerifier;
use crate::{Jwt, keys};
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Jwks {
pub keys: Vec<Map<String, Value>>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct GetJwks;
impl<D: Adapter> Endpoint<D> for GetJwks {
const METHOD: Method = Method::GET;
const PATH: &'static str = "/jwks";
type Access = Public;
type Input = Map<String, Value>;
type Output = Jwks;
async fn call(&self, ctx: Ctx<D>, _: Map<String, Value>) -> Result<Jwks, AuthError> {
let jwt = ctx.plugin::<Jwt>();
keys::current(&ctx, jwt).await?;
let all = keys::all(&ctx).await?;
let keys = keys::published(&all, jwt, ctx.now())
.into_iter()
.map(|key| keys::public_jwk(key, jwt))
.collect::<Result<_, _>>()?;
Ok(Jwks { keys })
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenOutput {
pub token: String,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct GetToken;
impl<D: Adapter> Endpoint<D> for GetToken {
const METHOD: Method = Method::GET;
const PATH: &'static str = "/token";
type Access = Authenticated;
type Input = Map<String, Value>;
type Output = TokenOutput;
async fn call(
&self,
ctx: Ctx<D, Authenticated>,
_: Map<String, Value>,
) -> Result<TokenOutput, AuthError> {
let token = keys::session_token(&ctx, ctx.plugin::<Jwt>(), ctx.session()).await?;
Ok(TokenOutput { token })
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SignJwtInput {
pub payload: Map<String, Value>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct SignJwt;
impl<D: Adapter> Endpoint<D> for SignJwt {
const METHOD: Method = Method::POST;
const PATH: &'static str = "/sign-jwt";
type Access = Public;
type Input = SignJwtInput;
type Output = TokenOutput;
async fn call(&self, ctx: Ctx<D>, input: SignJwtInput) -> Result<TokenOutput, AuthError> {
let token = keys::sign(&ctx, ctx.plugin::<Jwt>(), input.payload).await?;
Ok(TokenOutput { token })
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct VerifyJwtInput {
pub token: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub issuer: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct VerifyJwtOutput {
pub payload: Option<Map<String, Value>>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct VerifyJwt;
impl<D: Adapter> Endpoint<D> for VerifyJwt {
const METHOD: Method = Method::POST;
const PATH: &'static str = "/verify-jwt";
type Access = Public;
type Input = VerifyJwtInput;
type Output = VerifyJwtOutput;
async fn call(&self, ctx: Ctx<D>, input: VerifyJwtInput) -> Result<VerifyJwtOutput, AuthError> {
let jwt = ctx.plugin::<Jwt>();
let keys = keys::all(&ctx)
.await?
.iter()
.map(|key| keys::public_jwk(key, jwt))
.collect::<Result<Vec<_>, _>>()?;
let jwks: JwkSet = serde_json::from_value(serde_json::json!({ "keys": keys }))
.map_err(AuthError::internal)?;
let base_url = ctx
.config()
.base_url
.as_str()
.trim_end_matches('/')
.to_owned();
let issuer = input
.issuer
.or_else(|| jwt.issuer.clone())
.unwrap_or_else(|| base_url.clone());
let audience = jwt.audience.clone().unwrap_or(base_url);
let payload = JwksVerifier::new(jwks, issuer, audience)
.verify(&input.token)
.ok();
Ok(VerifyJwtOutput { payload })
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RotatedKey {
pub kid: Id,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct RotateKeys;
impl<D: Adapter> Endpoint<D> for RotateKeys {
const METHOD: Method = Method::POST;
const PATH: &'static str = "/jwks/rotate";
type Access = Public;
type Input = Empty;
type Output = RotatedKey;
async fn call(&self, ctx: Ctx<D>, _: Empty) -> Result<RotatedKey, AuthError> {
let key = keys::rotate(&ctx, ctx.plugin::<Jwt>()).await?;
Ok(RotatedKey { kid: key.id })
}
}