1use crate::{
4 authentication::credentials::{Credential, CredentialMetadata},
5 errors::{AuthError, Result},
6 tokens::AuthToken,
7};
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10
11pub mod client_cert;
13pub mod enhanced_device;
14pub mod hardware_token;
15#[cfg(feature = "ldap-auth")]
16pub mod ldap;
17pub mod passkey;
18#[cfg(feature = "saml")]
19pub mod saml;
20
21pub use client_cert::ClientCertAuthMethod;
23#[cfg(feature = "enhanced-device-flow")]
24pub use enhanced_device::EnhancedDeviceFlowMethod;
25pub use hardware_token::HardwareOtpToken;
26#[cfg(feature = "ldap-auth")]
27pub use ldap::{LdapAuthMethod, LdapConfig};
28#[cfg(feature = "passkeys")]
29pub use passkey::PasskeyAuthMethod;
30#[cfg(feature = "saml")]
31pub use saml::SamlAuthMethod;
32
33#[derive(Debug, Clone)]
35pub enum MethodResult {
36 Success(Box<AuthToken>),
38
39 MfaRequired(Box<MfaChallenge>),
41
42 Failure { reason: String },
44}
45
46#[derive(Clone, Serialize, Deserialize)]
48pub struct MfaChallenge {
49 pub id: String,
51
52 pub mfa_type: MfaType,
54
55 pub user_id: String,
57
58 pub created_at: chrono::DateTime<chrono::Utc>,
60
61 pub expires_at: chrono::DateTime<chrono::Utc>,
63
64 pub attempts: u32,
66
67 pub max_attempts: u32,
69
70 pub code_hash: Option<String>,
73
74 pub message: Option<String>,
76
77 pub data: HashMap<String, serde_json::Value>,
79}
80
81impl std::fmt::Debug for MfaChallenge {
82 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83 let mut d = f.debug_struct("MfaChallenge");
84 d.field("id", &self.id);
85 d.field("mfa_type", &self.mfa_type);
86 d.field("user_id", &self.user_id);
87 d.field("created_at", &self.created_at);
88 d.field("expires_at", &self.expires_at);
89 d.field("attempts", &self.attempts);
90 d.field("max_attempts", &self.max_attempts);
91 d.field(
92 "code_hash",
93 &crate::utils::redact::redacted(&self.code_hash),
94 );
95 d.field("message", &self.message);
96 d.field("data", &crate::utils::redact::redacted(&self.data));
97 d.finish()
98 }
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
103pub enum MfaType {
104 Totp,
106
107 Sms { phone_number: String },
109
110 Email { email_address: String },
112
113 Push { device_id: String },
115
116 SecurityKey,
118
119 BackupCode,
121
122 MultiMethod,
124}
125
126pub trait AuthMethod: Send + Sync {
128 type MethodResult: Send + Sync + 'static;
129 type AuthToken: Send + Sync + 'static;
130
131 fn name(&self) -> &str;
133
134 fn authenticate(
136 &self,
137 credential: Credential,
138 metadata: CredentialMetadata,
139 ) -> impl std::future::Future<Output = Result<Self::MethodResult>> + Send;
140
141 fn validate_config(&self) -> Result<()>;
143
144 fn supports_refresh(&self) -> bool {
146 false
147 }
148
149 fn refresh_token(
151 &self,
152 _refresh_token: String,
153 ) -> impl std::future::Future<Output = Result<AuthToken, AuthError>> + Send {
154 async {
155 Err(AuthError::auth_method(
156 self.name(),
157 "Token refresh not supported by this method".to_string(),
158 ))
159 }
160 }
161}
162
163pub type UserInfo = crate::auth::UserInfo;
165
166#[allow(
168 clippy::large_enum_variant,
169 reason = "one value per registered method, held behind the registry; boxing would change the public variants"
170)]
171pub enum AuthMethodEnum {
172 Password(PasswordMethod),
173 Jwt(JwtMethod),
174 ApiKey(ApiKeyMethod),
175 OAuth2(OAuth2Method),
176 #[cfg(feature = "saml")]
177 Saml(Box<SamlAuthMethod>),
178 #[cfg(feature = "ldap-auth")]
179 Ldap(LdapAuthMethod),
180 HardwareOtpToken(HardwareOtpToken),
181 ClientCert(ClientCertAuthMethod),
182 OpenIdConnect(OpenIdConnectAuthMethod),
183 AdvancedMfa(AdvancedMfaAuthMethod),
184 #[cfg(feature = "enhanced-device-flow")]
185 EnhancedDeviceFlow(Box<enhanced_device::EnhancedDeviceFlowMethod>),
186 #[cfg(feature = "passkeys")]
187 Passkey(PasskeyAuthMethod),
188}
189
190#[derive(Debug)]
192pub struct PasswordMethod;
193
194#[derive(Debug)]
195pub struct JwtMethod;
196
197#[derive(Debug)]
198pub struct ApiKeyMethod;
199
200#[derive(Debug)]
201pub struct OAuth2Method;
202
203#[derive(Debug)]
204pub struct OpenIdConnectAuthMethod;
205
206#[derive(Debug)]
207pub struct AdvancedMfaAuthMethod;
208
209impl Default for PasswordMethod {
211 fn default() -> Self {
212 Self::new()
213 }
214}
215
216impl PasswordMethod {
217 pub fn new() -> Self {
218 Self
219 }
220}
221
222impl Default for JwtMethod {
223 fn default() -> Self {
224 Self::new()
225 }
226}
227
228impl JwtMethod {
229 pub fn new() -> Self {
230 Self
231 }
232
233 pub fn secret_key(self, _secret: &str) -> Self {
234 self
235 }
236
237 pub fn issuer(self, _issuer: &str) -> Self {
238 self
239 }
240
241 pub fn audience(self, _audience: &str) -> Self {
242 self
243 }
244}
245
246impl Default for ApiKeyMethod {
247 fn default() -> Self {
248 Self::new()
249 }
250}
251
252impl ApiKeyMethod {
253 pub fn new() -> Self {
254 Self
255 }
256}
257
258impl Default for OAuth2Method {
259 fn default() -> Self {
260 Self::new()
261 }
262}
263
264impl OAuth2Method {
265 pub fn new() -> Self {
266 Self
267 }
268}
269
270impl AuthMethod for AuthMethodEnum {
271 type MethodResult = MethodResult;
272 type AuthToken = AuthToken;
273
274 fn name(&self) -> &str {
275 match self {
276 AuthMethodEnum::Password(_) => "password",
277 AuthMethodEnum::Jwt(_) => "jwt",
278 AuthMethodEnum::ApiKey(_) => "api_key",
279 AuthMethodEnum::OAuth2(_) => "oauth2",
280 #[cfg(feature = "saml")]
281 AuthMethodEnum::Saml(_) => "saml",
282 #[cfg(feature = "ldap-auth")]
283 AuthMethodEnum::Ldap(_) => "ldap",
284 AuthMethodEnum::HardwareOtpToken(_) => "hardware_token",
285 AuthMethodEnum::ClientCert(_) => "client_cert",
286 AuthMethodEnum::OpenIdConnect(_) => "openid_connect",
287 AuthMethodEnum::AdvancedMfa(_) => "advanced_mfa",
288 #[cfg(feature = "enhanced-device-flow")]
289 AuthMethodEnum::EnhancedDeviceFlow(_) => "enhanced_device_flow",
290 #[cfg(feature = "passkeys")]
291 AuthMethodEnum::Passkey(_) => "passkey",
292 }
293 }
294
295 async fn authenticate(
296 &self,
297 credential: Credential,
298 metadata: CredentialMetadata,
299 ) -> Result<Self::MethodResult> {
300 let _ = &metadata;
301 match self {
302 #[cfg(feature = "saml")]
303 AuthMethodEnum::Saml(m) => return m.authenticate(credential, metadata).await,
304 #[cfg(feature = "passkeys")]
305 AuthMethodEnum::Passkey(m) => return m.authenticate(credential, metadata).await,
306 #[cfg(feature = "enhanced-device-flow")]
307 AuthMethodEnum::EnhancedDeviceFlow(m) => {
308 return m.authenticate(credential, metadata).await;
309 }
310 AuthMethodEnum::Password(_) => match credential {
311 Credential::Password { username, password } => {
312 if username.is_empty() || password.is_empty() {
313 return Self::failure("Username or password cannot be empty");
314 }
315 Self::failure(
316 "Password authentication is handled by AuthFramework's built-in storage-backed password flow",
317 )
318 }
319 _ => Self::failure("Password authentication expects Credential::password"),
320 },
321 AuthMethodEnum::Jwt(_) => match credential {
322 Credential::Jwt { token } | Credential::Bearer { token } => {
323 if token.is_empty() {
324 return Self::failure("JWT token cannot be empty");
325 }
326 Self::failure(
327 "JWT authentication must be performed through AuthFramework so the active TokenManager can validate the token signature",
328 )
329 }
330 _ => Self::failure(
331 "JWT authentication expects Credential::jwt or Credential::bearer",
332 ),
333 },
334 AuthMethodEnum::ApiKey(_) => match credential {
335 Credential::ApiKey { key } => {
336 if key.is_empty() {
337 return Self::failure("API key cannot be empty");
338 }
339 Self::failure(
340 "API key authentication must be performed through AuthFramework so the stored key can be resolved to a user and session token",
341 )
342 }
343 _ => Self::failure("API key authentication expects Credential::api_key"),
344 },
345 AuthMethodEnum::OAuth2(_) => match credential {
346 Credential::OAuth {
347 authorization_code, ..
348 } => {
349 if authorization_code.is_empty() {
350 return Self::failure("OAuth authorization code cannot be empty");
351 }
352 Self::failure(
353 "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes",
354 )
355 }
356 Credential::OAuthRefresh { refresh_token } => {
357 if refresh_token.is_empty() {
358 return Self::failure("OAuth refresh token cannot be empty");
359 }
360 Self::failure(
361 "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes",
362 )
363 }
364 Credential::Jwt { token }
365 | Credential::Bearer { token }
366 | Credential::OpenIdConnect {
367 id_token: token, ..
368 } => {
369 if token.is_empty() {
370 return Self::failure("OAuth token cannot be empty");
371 }
372 Self::failure(
373 "OAuth 2.0 token authentication must be performed through AuthFramework so token validation and auditing use the active framework state",
374 )
375 }
376 _ => Self::failure(
377 "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect",
378 ),
379 },
380 #[cfg(feature = "ldap-auth")]
381 AuthMethodEnum::Ldap(_) => Self::failure(
382 "LDAP authentication requires a concrete LDAP integration and cannot use the generic AuthMethodEnum fallback",
383 ),
384 AuthMethodEnum::HardwareOtpToken(_) => Self::failure(
385 "Hardware token authentication requires the concrete hardware token flow rather than the generic AuthMethodEnum fallback",
386 ),
387 AuthMethodEnum::ClientCert(_) => Self::failure(
388 "Client certificate authentication requires the concrete client certificate flow rather than the generic AuthMethodEnum fallback",
389 ),
390 AuthMethodEnum::OpenIdConnect(_) => Self::failure(
391 "OpenID Connect authentication should be performed through the OIDC provider or AuthFramework integrations",
392 ),
393 AuthMethodEnum::AdvancedMfa(_) => Self::failure(
394 "Advanced MFA authentication requires the concrete MFA flow rather than the generic AuthMethodEnum fallback",
395 ),
396 }
397 }
398
399 fn validate_config(&self) -> Result<()> {
400 match self {
401 AuthMethodEnum::Password(_) => Ok(()),
402 AuthMethodEnum::Jwt(_) => Ok(()),
403 AuthMethodEnum::ApiKey(_) => Ok(()),
404 AuthMethodEnum::OAuth2(_) => Ok(()),
405 #[cfg(feature = "saml")]
406 AuthMethodEnum::Saml(method) => method.validate_config(),
407 #[cfg(feature = "ldap-auth")]
408 AuthMethodEnum::Ldap(_) => Ok(()),
409 AuthMethodEnum::HardwareOtpToken(method) => {
410 if method.device_id.trim().is_empty() {
411 return Err(AuthError::config(
412 "Hardware token device_id cannot be empty",
413 ));
414 }
415 if method.token_type.trim().is_empty() {
416 return Err(AuthError::config(
417 "Hardware token token_type cannot be empty",
418 ));
419 }
420 Ok(())
421 }
422 AuthMethodEnum::ClientCert(_) => Ok(()),
423 AuthMethodEnum::OpenIdConnect(_) => Ok(()),
424 AuthMethodEnum::AdvancedMfa(_) => Ok(()),
425 #[cfg(feature = "enhanced-device-flow")]
426 AuthMethodEnum::EnhancedDeviceFlow(method) => method.validate_config(),
427 #[cfg(feature = "passkeys")]
428 AuthMethodEnum::Passkey(method) => method.validate_config(),
429 }
430 }
431
432 fn supports_refresh(&self) -> bool {
433 false
434 }
435
436 async fn refresh_token(&self, _refresh_token: String) -> Result<AuthToken, AuthError> {
437 Err(AuthError::auth_method(
438 self.name(),
439 "Token refresh not supported by this method".to_string(),
440 ))
441 }
442}
443
444impl AuthMethodEnum {
445 fn failure(reason: impl Into<String>) -> Result<MethodResult> {
446 Ok(MethodResult::Failure {
447 reason: reason.into(),
448 })
449 }
450}
451
452impl MfaChallenge {
453 pub fn new(
455 mfa_type: MfaType,
456 user_id: impl Into<String>,
457 expires_in: std::time::Duration,
458 ) -> Self {
459 Self {
460 id: uuid::Uuid::new_v4().to_string(),
461 mfa_type,
462 user_id: user_id.into(),
463 expires_at: chrono::Utc::now()
464 + chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1)),
465 created_at: chrono::Utc::now(),
466 attempts: 0,
467 max_attempts: 3,
468 code_hash: None,
469 message: None,
470 data: HashMap::new(),
471 }
472 }
473
474 pub fn id(&self) -> &str {
476 &self.id
477 }
478
479 pub fn is_expired(&self) -> bool {
481 chrono::Utc::now() > self.expires_at
482 }
483
484 pub fn with_message(mut self, message: impl Into<String>) -> Self {
485 self.message = Some(message.into());
486 self
487 }
488}