use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum AuthStrategy {
Jwt,
OAuth,
ApiKey,
Basic,
Custom(String),
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum JwtAlgorithm {
#[default]
HS256,
HS384,
HS512,
RS256,
RS384,
RS512,
ES256,
ES384,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum TokenType {
#[default]
Access,
Refresh,
Identity,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct AuthOptions {
pub strategies: Vec<AuthStrategy>,
pub entity: Option<String>,
pub service: Option<String>,
pub entity_id_claim: Option<String>,
pub jwt: JwtOptions,
pub oauth_providers: HashMap<String, OAuthProvider>,
pub api_key: ApiKeyOptions,
}
impl Default for AuthOptions {
fn default() -> Self {
Self {
strategies: vec![AuthStrategy::Jwt],
entity: None,
service: None,
entity_id_claim: None,
jwt: JwtOptions::default(),
oauth_providers: HashMap::new(),
api_key: ApiKeyOptions::default(),
}
}
}
impl AuthOptions {
pub fn validate(&self) -> Result<(), String> {
if self.strategies.is_empty() {
return Err("At least one authentication strategy must be enabled".to_string());
}
if self.entity.is_some() && self.service.as_deref().unwrap_or("").trim().is_empty() {
return Err("Entity is configured but service is missing".to_string());
}
if self.strategies.contains(&AuthStrategy::Jwt) {
self.jwt
.validate()
.map_err(|e| format!("JWT validation failed: {}", e))?;
}
if self.strategies.contains(&AuthStrategy::OAuth) {
if self.oauth_providers.is_empty() {
return Err(
"OAuth strategy is enabled but no OAuth providers are configured".to_string(),
);
}
for (provider_name, provider) in &self.oauth_providers {
provider.validate().map_err(|e| {
format!(
"OAuth provider '{}' validation failed: {}",
provider_name, e
)
})?;
}
}
if self.strategies.contains(&AuthStrategy::ApiKey) {
self.api_key
.validate()
.map_err(|e| format!("API key validation failed: {}", e))?;
}
let mut custom_strategies = Vec::new();
for strategy in &self.strategies {
if let AuthStrategy::Custom(name) = strategy {
if custom_strategies.contains(name) {
return Err(format!(
"Duplicate custom authentication strategy: '{}'",
name
));
}
custom_strategies.push(name.clone());
}
}
Ok(())
}
pub fn builder() -> AuthOptionsBuilder {
AuthOptionsBuilder::new()
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct JwtOptions {
pub algorithm: JwtAlgorithm,
pub issuer: String,
pub audience: Vec<String>,
#[serde(with = "humantime_serde")]
pub access_token_expires_in: Duration,
#[serde(with = "humantime_serde")]
pub refresh_token_expires_in: Duration,
pub token_type: TokenType,
pub custom_claims: HashMap<String, serde_json::Value>,
pub secret: Option<String>,
pub private_key_path: Option<String>,
pub public_key_path: Option<String>,
}
impl Default for JwtOptions {
fn default() -> Self {
Self {
algorithm: JwtAlgorithm::default(),
issuer: "dogrs-auth".to_string(),
audience: vec!["dogrs-api".to_string()],
access_token_expires_in: Duration::from_secs(3600), refresh_token_expires_in: Duration::from_secs(604800), token_type: TokenType::default(),
custom_claims: HashMap::new(),
secret: None,
private_key_path: None,
public_key_path: None,
}
}
}
impl JwtOptions {
pub fn validate(&self) -> Result<(), String> {
if self.issuer.trim().is_empty() {
return Err("JWT issuer cannot be empty".to_string());
}
if self.audience.is_empty() || self.audience.iter().any(|v| v.trim().is_empty()) {
return Err("JWT audience cannot be empty".to_string());
}
match self.algorithm {
JwtAlgorithm::HS256 | JwtAlgorithm::HS384 | JwtAlgorithm::HS512 => {
if self.secret.as_ref().is_none_or(|s| s.len() < 32) {
return Err("HMAC algorithms require a secret of at least 32 bytes".to_string());
}
}
JwtAlgorithm::RS256
| JwtAlgorithm::RS384
| JwtAlgorithm::RS512
| JwtAlgorithm::ES256
| JwtAlgorithm::ES384 => {
if self.private_key_path.is_none() && self.public_key_path.is_none() {
return Err("RSA/ECDSA algorithms require key files".to_string());
}
}
}
for key in ["iss", "aud", "exp", "iat", "nbf", "jti"] {
if self.custom_claims.contains_key(key) {
return Err(format!("Reserved JWT claim cannot be overridden: {key}"));
}
}
if self.access_token_expires_in.as_secs() > i64::MAX as u64
|| self.refresh_token_expires_in.as_secs() > i64::MAX as u64
{
return Err("Token lifetime is too large".into());
}
if self.access_token_expires_in.as_secs() == 0 {
return Err("Access token expiration must be greater than 0".to_string());
}
if self.refresh_token_expires_in.as_secs() == 0 {
return Err("Refresh token expiration must be greater than 0".to_string());
}
Ok(())
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct OAuthProvider {
pub name: String,
pub client_id: String,
pub client_secret: String,
pub auth_url: String,
pub token_url: String,
pub redirect_uri: String,
pub user_info_url: Option<String>,
pub scopes: Vec<String>,
}
impl OAuthProvider {
pub fn validate(&self) -> Result<(), String> {
if self.name.is_empty() {
return Err("OAuth provider name cannot be empty".to_string());
}
if self.client_id.is_empty() {
return Err("OAuth client ID cannot be empty".to_string());
}
if self.client_secret.is_empty() {
return Err("OAuth client secret cannot be empty".to_string());
}
if self.auth_url.is_empty() {
return Err("OAuth authorization URL cannot be empty".to_string());
}
if self.token_url.is_empty() {
return Err("OAuth token URL cannot be empty".to_string());
}
if self.redirect_uri.is_empty() {
return Err("OAuth redirect URI cannot be empty".to_string());
}
if !self.auth_url.starts_with("http://") && !self.auth_url.starts_with("https://") {
return Err("OAuth authorization URL must be a valid HTTP/HTTPS URL".to_string());
}
if !self.token_url.starts_with("http://") && !self.token_url.starts_with("https://") {
return Err("OAuth token URL must be a valid HTTP/HTTPS URL".to_string());
}
if let Some(ref user_info_url) = self.user_info_url {
if !user_info_url.starts_with("http://") && !user_info_url.starts_with("https://") {
return Err("OAuth user info URL must be a valid HTTP/HTTPS URL".to_string());
}
}
Ok(())
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ApiKeyOptions {
pub header_name: String,
pub query_param: Option<String>,
pub required: bool,
}
impl Default for ApiKeyOptions {
fn default() -> Self {
Self {
header_name: "X-API-Key".to_string(),
query_param: Some("api_key".to_string()),
required: false,
}
}
}
impl ApiKeyOptions {
pub fn validate(&self) -> Result<(), String> {
if self.header_name.is_empty() {
return Err("API key header name cannot be empty".to_string());
}
if !self
.header_name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
{
return Err("API key header name must contain only alphanumeric characters, hyphens, and underscores".to_string());
}
if let Some(ref query_param) = self.query_param {
if query_param.is_empty() {
return Err("API key query parameter cannot be empty if specified".to_string());
}
if !query_param
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_')
{
return Err("API key query parameter must contain only alphanumeric characters and underscores".to_string());
}
}
Ok(())
}
}
#[derive(Clone, Debug, Default)]
pub struct AuthOptionsBuilder {
strategies: Vec<AuthStrategy>,
jwt: Option<JwtOptions>,
oauth_providers: HashMap<String, OAuthProvider>,
api_key: Option<ApiKeyOptions>,
}
impl AuthOptionsBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn strategy(mut self, strategy: AuthStrategy) -> Self {
self.strategies.push(strategy);
self
}
pub fn strategies(mut self, strategies: Vec<AuthStrategy>) -> Self {
self.strategies = strategies;
self
}
pub fn jwt(mut self, jwt_options: JwtOptions) -> Self {
self.jwt = Some(jwt_options);
self
}
pub fn oauth_provider(mut self, name: String, provider: OAuthProvider) -> Self {
self.oauth_providers.insert(name, provider);
self
}
pub fn api_key(mut self, api_key_options: ApiKeyOptions) -> Self {
self.api_key = Some(api_key_options);
self
}
pub fn build(self) -> AuthOptions {
AuthOptions {
strategies: if self.strategies.is_empty() {
vec![AuthStrategy::Jwt]
} else {
self.strategies
},
entity: None,
service: None,
entity_id_claim: None,
jwt: self.jwt.unwrap_or_default(),
oauth_providers: self.oauth_providers,
api_key: self.api_key.unwrap_or_default(),
}
}
pub fn build_validated(self) -> Result<AuthOptions, String> {
let options = self.build();
options.validate()?;
Ok(options)
}
}