use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use chrono::Utc;
use dog_core::errors::DogError;
use dog_core::HookContext;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use uuid::Uuid;
use crate::options::{AuthOptions, TokenType};
#[cfg(feature = "jwt-aws-lc-rs")]
use crate::options::JwtAlgorithm;
pub type AuthenticationResult = Value;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConnectionEvent {
Login,
Logout,
Disconnect,
}
pub fn extract_bearer_token(headers: &HashMap<String, String>) -> Option<String> {
let v = headers
.get("authorization")
.or_else(|| headers.get("Authorization"))?;
let v = v.trim();
let prefix = "Bearer ";
if v.len() <= prefix.len() || !v.starts_with(prefix) {
return None;
}
Some(v[prefix.len()..].trim().to_string())
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct AuthenticationRequest {
pub strategy: Option<String>,
#[serde(flatten)]
pub data: Map<String, Value>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct AuthenticationParams {
pub payload: Option<Value>,
pub jwt_options: Option<JwtOverrides>,
pub auth_strategies: Option<Vec<String>>,
pub secret: Option<String>,
pub headers: HashMap<String, String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct JwtOverrides {
pub issuer: Option<String>,
pub audience: Option<Vec<String>>,
pub expires_in_seconds: Option<u64>,
pub token_type: Option<TokenType>,
}
pub trait JwtProvider: Send + Sync {
fn sign(
&self,
jwt: &crate::options::JwtOptions,
claims: Map<String, Value>,
token_type: TokenType,
) -> Result<String>;
fn verify(
&self,
jwt: &crate::options::JwtOptions,
token: &str,
overrides: Option<&JwtOverrides>,
) -> Result<Value>;
}
#[cfg(not(feature = "jwt-aws-lc-rs"))]
struct NoJwtProvider;
#[cfg(not(feature = "jwt-aws-lc-rs"))]
impl JwtProvider for NoJwtProvider {
fn sign(
&self,
_jwt: &crate::options::JwtOptions,
_claims: Map<String, Value>,
_token_type: TokenType,
) -> Result<String> {
Err(anyhow::anyhow!(
"JWT support is disabled (enable jwt-aws-lc-rs)"
))
}
fn verify(
&self,
_jwt: &crate::options::JwtOptions,
_token: &str,
_overrides: Option<&JwtOverrides>,
) -> Result<Value> {
Err(anyhow::anyhow!(
"JWT support is disabled (enable jwt-aws-lc-rs)"
))
}
}
#[cfg(feature = "jwt-aws-lc-rs")]
#[derive(Default)]
struct JsonwebtokenProvider {
encoding: std::sync::OnceLock<std::result::Result<jsonwebtoken::EncodingKey, String>>,
decoding: std::sync::OnceLock<std::result::Result<jsonwebtoken::DecodingKey, String>>,
}
#[cfg(feature = "jwt-aws-lc-rs")]
impl JsonwebtokenProvider {
fn algorithm(alg: JwtAlgorithm) -> jsonwebtoken::Algorithm {
match alg {
JwtAlgorithm::HS256 => jsonwebtoken::Algorithm::HS256,
JwtAlgorithm::HS384 => jsonwebtoken::Algorithm::HS384,
JwtAlgorithm::HS512 => jsonwebtoken::Algorithm::HS512,
JwtAlgorithm::RS256 => jsonwebtoken::Algorithm::RS256,
JwtAlgorithm::RS384 => jsonwebtoken::Algorithm::RS384,
JwtAlgorithm::RS512 => jsonwebtoken::Algorithm::RS512,
JwtAlgorithm::ES256 => jsonwebtoken::Algorithm::ES256,
JwtAlgorithm::ES384 => jsonwebtoken::Algorithm::ES384,
}
}
}
#[cfg(feature = "jwt-aws-lc-rs")]
impl JwtProvider for JsonwebtokenProvider {
fn sign(
&self,
jwt: &crate::options::JwtOptions,
claims: Map<String, Value>,
token_type: TokenType,
) -> Result<String> {
use jsonwebtoken::{encode, Header};
let key = self
.encoding
.get_or_init(|| jwt_encoding_key(jwt).map_err(|e| e.to_string()))
.as_ref()
.map_err(|e| DogError::general_error(e).into_anyhow())?;
let mut header = Header::new(Self::algorithm(jwt.algorithm.clone()));
header.typ = Some(
match token_type {
TokenType::Access => "access",
TokenType::Refresh => "refresh",
TokenType::Identity => "identity",
}
.to_string(),
);
encode(&header, &claims, key)
.map_err(|e| DogError::not_authenticated(e.to_string()).into_anyhow())
}
fn verify(
&self,
jwt: &crate::options::JwtOptions,
token: &str,
overrides: Option<&JwtOverrides>,
) -> Result<Value> {
use jsonwebtoken::{decode, Validation};
let key = self
.decoding
.get_or_init(|| jwt_decoding_key(jwt).map_err(|e| e.to_string()))
.as_ref()
.map_err(|e| DogError::general_error(e).into_anyhow())?;
let issuer = overrides
.and_then(|o| o.issuer.clone())
.unwrap_or_else(|| jwt.issuer.clone());
let audience = overrides
.and_then(|o| o.audience.clone())
.unwrap_or_else(|| jwt.audience.clone());
let alg = Self::algorithm(jwt.algorithm.clone());
let mut validation = Validation::new(alg);
validation.leeway = 0;
validation.validate_nbf = true;
validation.set_required_spec_claims(&["exp", "iss", "aud"]);
validation.set_issuer(&[issuer.as_str()]);
validation.set_audience(&audience.iter().map(|s| s.as_str()).collect::<Vec<_>>());
let decoded = decode::<Value>(token, key, &validation)
.map_err(|_| DogError::not_authenticated("Invalid token").into_anyhow())?;
let expected_type = match overrides
.and_then(|o| o.token_type.as_ref())
.unwrap_or(&TokenType::Access)
{
TokenType::Access => "access",
TokenType::Refresh => "refresh",
TokenType::Identity => "identity",
};
if decoded.header.typ.as_deref() != Some(expected_type) {
return Err(DogError::not_authenticated("Invalid token type").into_anyhow());
}
Ok(decoded.claims)
}
}
#[async_trait]
pub trait AuthenticationStrategy<P>: Send + Sync
where
P: Send + Clone + 'static,
{
async fn authenticate(
&self,
authentication: &AuthenticationRequest,
params: &AuthenticationParams,
ctx: &mut HookContext<Value, P>,
auth: &AuthenticationBase<P>,
) -> Result<AuthenticationResult>;
}
pub struct AuthenticationBuilder<P>
where
P: Send + Clone + 'static,
{
options: Arc<AuthOptions>,
strategies: HashMap<String, Arc<dyn AuthenticationStrategy<P>>>,
jwt: Arc<dyn JwtProvider>,
token_store: Option<Arc<dyn TokenStore>>,
}
impl<P> AuthenticationBuilder<P>
where
P: Send + Clone + 'static,
{
pub fn new(
builder: &mut dog_core::DogAppBuilder<Value, P>,
config_key: impl Into<String>,
options: Option<AuthOptions>,
) -> Result<Self> {
let opts = Arc::new(options.unwrap_or_default());
builder.set(config_key.into(), opts.clone());
let jwt: Arc<dyn JwtProvider> = {
#[cfg(feature = "jwt-aws-lc-rs")]
{
Arc::new(JsonwebtokenProvider::default())
}
#[cfg(not(feature = "jwt-aws-lc-rs"))]
{
Arc::new(NoJwtProvider)
}
};
Ok(Self {
options: opts,
strategies: HashMap::new(),
jwt,
token_store: None,
})
}
pub fn register(
&mut self,
name: impl Into<String>,
strategy: Arc<dyn AuthenticationStrategy<P>>,
) {
self.strategies.insert(name.into(), strategy);
}
pub fn with_token_store(mut self, store: Arc<dyn TokenStore>) -> Self {
self.token_store = Some(store);
self
}
pub fn build(self) -> AuthenticationBase<P> {
AuthenticationBase {
options: self.options,
strategies: self.strategies,
jwt: self.jwt,
token_store: self.token_store,
}
}
}
pub struct AuthenticationBase<P>
where
P: Send + Clone + 'static,
{
options: Arc<AuthOptions>,
strategies: HashMap<String, Arc<dyn AuthenticationStrategy<P>>>,
jwt: Arc<dyn JwtProvider>,
token_store: Option<Arc<dyn TokenStore>>,
}
impl<P> AuthenticationBase<P>
where
P: Send + Clone + 'static,
{
pub fn builder(
builder: &mut dog_core::DogAppBuilder<Value, P>,
config_key: impl Into<String>,
options: Option<AuthOptions>,
) -> Result<AuthenticationBuilder<P>> {
AuthenticationBuilder::new(builder, config_key, options)
}
pub fn configuration(&self) -> AuthOptions {
(*self.options).clone()
}
pub fn strategy_names(&self) -> Vec<String> {
self.strategies.keys().cloned().collect()
}
pub fn get_strategy(&self, name: &str) -> Option<Arc<dyn AuthenticationStrategy<P>>> {
self.strategies.get(name).cloned()
}
pub async fn authenticate(
&self,
authentication: &AuthenticationRequest,
params: &AuthenticationParams,
ctx: &mut HookContext<Value, P>,
allowed: &[String],
) -> Result<AuthenticationResult> {
let _strategy = authentication.strategy.as_deref().ok_or_else(|| {
DogError::not_authenticated("Invalid authentication information (no `strategy` set)")
.into_anyhow()
})?;
let strategy_name = authentication.strategy.as_deref().ok_or_else(|| {
DogError::not_authenticated("Invalid authentication information (no `strategy` set)")
.into_anyhow()
})?;
if !allowed.is_empty() && !allowed.iter().any(|s| s == strategy_name) {
return Err(DogError::not_authenticated(
"Invalid authentication information (strategy not allowed in authStrategies)",
)
.into_anyhow());
}
let strategy = self.strategies.get(strategy_name).ok_or_else(|| {
DogError::not_authenticated(format!("Unknown authentication strategy: {strategy_name}"))
.into_anyhow()
})?;
strategy
.authenticate(authentication, params, ctx, self)
.await
}
pub async fn setup(&self) {}
pub fn is_ready(&self) -> bool {
true
}
pub async fn create_access_token(
&self,
payload: Value,
overrides: Option<JwtOverrides>,
) -> Result<String> {
self.create_token(payload, overrides, TokenType::Access)
.await
}
pub async fn create_refresh_token(
&self,
payload: Value,
overrides: Option<JwtOverrides>,
) -> Result<String> {
self.create_token(payload, overrides, TokenType::Refresh)
.await
}
pub async fn verify_access_token(&self, token: &str) -> Result<Value> {
self.verify_token(token, None).await
}
pub async fn verify_refresh_token(&self, token: &str) -> Result<Value> {
self.verify_token(
token,
Some(JwtOverrides {
token_type: Some(TokenType::Refresh),
..Default::default()
}),
)
.await
}
pub async fn revoke_access_token(&self, token: &str) -> Result<()> {
let store = self.token_store.as_ref().ok_or_else(|| {
DogError::unavailable("Token revocation store is not configured").into_anyhow()
})?;
let claims = self.verify_access_token(token).await?;
let (issuer, jti, exp) = token_identity(&claims)?;
store.revoke(issuer, jti, exp).await
}
pub async fn revoke_refresh_token(&self, token: &str) -> Result<()> {
let store = self.token_store.as_ref().ok_or_else(|| {
DogError::unavailable("Token revocation store is not configured").into_anyhow()
})?;
let claims = self.verify_refresh_token(token).await?;
let (issuer, jti, exp) = token_identity(&claims)?;
store.revoke(issuer, jti, exp).await
}
pub async fn rotate_refresh_token(&self, token: &str) -> Result<TokenPair> {
let store = self.token_store.as_ref().ok_or_else(|| {
DogError::unavailable("Token revocation store is not configured").into_anyhow()
})?;
let claims = self.verify_refresh_token(token).await?;
let (issuer, jti, exp) = token_identity(&claims)?;
let mut payload = claims.clone();
if let Some(map) = payload.as_object_mut() {
for key in ["iss", "aud", "exp", "iat", "nbf", "jti"] {
map.remove(key);
}
}
let pair = TokenPair {
access_token: self.create_access_token(payload.clone(), None).await?,
refresh_token: self.create_refresh_token(payload, None).await?,
};
if !store.consume_refresh(issuer, jti, exp).await? {
return Err(DogError::not_authenticated("Refresh token already used").into_anyhow());
}
Ok(pair)
}
async fn create_token(
&self,
payload: Value,
overrides: Option<JwtOverrides>,
default_type: TokenType,
) -> Result<String> {
let cfg = self.configuration();
let jwt = cfg.jwt;
jwt.validate().map_err(anyhow::Error::msg)?;
let issuer = overrides
.as_ref()
.and_then(|o| o.issuer.clone())
.unwrap_or_else(|| jwt.issuer.clone());
let audience = overrides
.as_ref()
.and_then(|o| o.audience.clone())
.unwrap_or_else(|| jwt.audience.clone());
anyhow::ensure!(
!issuer.trim().is_empty()
&& !audience.is_empty()
&& audience.iter().all(|v| !v.trim().is_empty()),
"JWT issuer and audience must not be empty"
);
let token_type = overrides
.as_ref()
.and_then(|o| o.token_type.clone())
.unwrap_or(default_type);
let expires_in_seconds = overrides
.as_ref()
.and_then(|o| o.expires_in_seconds)
.unwrap_or(match token_type {
TokenType::Access | TokenType::Identity => jwt.access_token_expires_in.as_secs(),
TokenType::Refresh => jwt.refresh_token_expires_in.as_secs(),
});
let now = Utc::now().timestamp();
let lifetime = i64::try_from(expires_in_seconds)?;
anyhow::ensure!(lifetime > 0, "Token lifetime must be positive");
let exp = now
.checked_add(lifetime)
.ok_or_else(|| anyhow::anyhow!("Token lifetime overflow"))?;
let jti = Uuid::new_v4().to_string();
let mut claims = match payload {
Value::Object(m) => m,
other => {
let mut m = Map::new();
m.insert("payload".to_string(), other);
m
}
};
claims.insert("iss".to_string(), Value::String(issuer));
claims.insert("aud".to_string(), json!(audience));
claims.insert("iat".to_string(), Value::Number(now.into()));
claims.insert("exp".to_string(), Value::Number(exp.into()));
claims.insert("jti".to_string(), Value::String(jti));
for (k, v) in jwt.custom_claims.clone() {
claims.insert(k, v);
}
let token = self.jwt.sign(&jwt, claims, token_type)?;
anyhow::ensure!(token.len() <= 16 * 1024, "Token too large");
Ok(token)
}
async fn verify_token(&self, token: &str, overrides: Option<JwtOverrides>) -> Result<Value> {
let cfg = self.configuration();
let jwt = cfg.jwt;
jwt.validate().map_err(anyhow::Error::msg)?;
if token.len() > 16 * 1024 {
return Err(DogError::not_authenticated("Token too large").into_anyhow());
}
let claims = self.jwt.verify(&jwt, token, overrides.as_ref())?;
let (issuer, jti, _) = token_identity(&claims)?;
if let Some(store) = &self.token_store {
if store.is_revoked(issuer, jti).await? {
return Err(DogError::not_authenticated("Token revoked").into_anyhow());
}
}
Ok(claims)
}
}
#[cfg(feature = "jwt-aws-lc-rs")]
fn jwt_encoding_key(jwt: &crate::options::JwtOptions) -> Result<jsonwebtoken::EncodingKey> {
match jwt.algorithm {
JwtAlgorithm::HS256 | JwtAlgorithm::HS384 | JwtAlgorithm::HS512 => {
let secret = jwt
.secret
.as_ref()
.filter(|s| !s.is_empty())
.ok_or_else(|| anyhow::anyhow!("JWT secret is not configured"))?;
Ok(jsonwebtoken::EncodingKey::from_secret(secret.as_bytes()))
}
_ => {
#[cfg(feature = "jwt-pem")]
{
let path = jwt
.private_key_path
.as_ref()
.ok_or_else(|| anyhow::anyhow!("JWT private key is not configured"))?;
let pem = std::fs::read(path)?;
match jwt.algorithm {
JwtAlgorithm::RS256 | JwtAlgorithm::RS384 | JwtAlgorithm::RS512 => {
Ok(jsonwebtoken::EncodingKey::from_rsa_pem(&pem)?)
}
_ => Ok(jsonwebtoken::EncodingKey::from_ec_pem(&pem)?),
}
}
#[cfg(not(feature = "jwt-pem"))]
anyhow::bail!("Enable jwt-pem for RSA/ECDSA keys")
}
}
}
#[cfg(feature = "jwt-aws-lc-rs")]
fn jwt_decoding_key(jwt: &crate::options::JwtOptions) -> Result<jsonwebtoken::DecodingKey> {
match jwt.algorithm {
JwtAlgorithm::HS256 | JwtAlgorithm::HS384 | JwtAlgorithm::HS512 => {
let secret = jwt
.secret
.as_ref()
.filter(|s| !s.is_empty())
.ok_or_else(|| anyhow::anyhow!("JWT secret is not configured"))?;
Ok(jsonwebtoken::DecodingKey::from_secret(secret.as_bytes()))
}
_ => {
#[cfg(feature = "jwt-pem")]
{
let path = jwt
.public_key_path
.as_ref()
.ok_or_else(|| anyhow::anyhow!("JWT public key is not configured"))?;
let pem = std::fs::read(path)?;
match jwt.algorithm {
JwtAlgorithm::RS256 | JwtAlgorithm::RS384 | JwtAlgorithm::RS512 => {
Ok(jsonwebtoken::DecodingKey::from_rsa_pem(&pem)?)
}
_ => Ok(jsonwebtoken::DecodingKey::from_ec_pem(&pem)?),
}
}
#[cfg(not(feature = "jwt-pem"))]
anyhow::bail!("Enable jwt-pem for RSA/ECDSA keys")
}
}
}
#[async_trait]
pub trait TokenStore: Send + Sync {
async fn is_revoked(&self, issuer: &str, jti: &str) -> Result<bool>;
async fn revoke(&self, issuer: &str, jti: &str, expires_at: i64) -> Result<()>;
async fn consume_refresh(&self, issuer: &str, jti: &str, expires_at: i64) -> Result<bool>;
}
pub struct TokenPair {
pub access_token: String,
pub refresh_token: String,
}
fn token_identity(claims: &Value) -> Result<(&str, &str, i64)> {
let issuer = claims
.get("iss")
.and_then(Value::as_str)
.filter(|s| !s.is_empty());
let jti = claims
.get("jti")
.and_then(Value::as_str)
.filter(|s| !s.is_empty());
let exp = claims.get("exp").and_then(Value::as_i64);
match (issuer, jti, exp) {
(Some(issuer), Some(jti), Some(exp)) if exp > Utc::now().timestamp() => {
Ok((issuer, jti, exp))
}
_ => Err(DogError::not_authenticated("Invalid token claims").into_anyhow()),
}
}