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(clippy::large_enum_variant)]
168pub enum AuthMethodEnum {
169 Password(PasswordMethod),
170 Jwt(JwtMethod),
171 ApiKey(ApiKeyMethod),
172 OAuth2(OAuth2Method),
173 #[cfg(feature = "saml")]
174 Saml(Box<SamlAuthMethod>),
175 #[cfg(feature = "ldap-auth")]
176 Ldap(LdapAuthMethod),
177 HardwareOtpToken(HardwareOtpToken),
178 ClientCert(ClientCertAuthMethod),
179 OpenIdConnect(OpenIdConnectAuthMethod),
180 AdvancedMfa(AdvancedMfaAuthMethod),
181 #[cfg(feature = "enhanced-device-flow")]
182 EnhancedDeviceFlow(Box<enhanced_device::EnhancedDeviceFlowMethod>),
183 #[cfg(feature = "passkeys")]
184 Passkey(PasskeyAuthMethod),
185}
186
187#[derive(Debug)]
189pub struct PasswordMethod;
190
191#[derive(Debug)]
192pub struct JwtMethod;
193
194#[derive(Debug)]
195pub struct ApiKeyMethod;
196
197#[derive(Debug)]
198pub struct OAuth2Method;
199
200#[derive(Debug)]
201pub struct OpenIdConnectAuthMethod;
202
203#[derive(Debug)]
204pub struct AdvancedMfaAuthMethod;
205
206impl Default for PasswordMethod {
208 fn default() -> Self {
209 Self::new()
210 }
211}
212
213impl PasswordMethod {
214 pub fn new() -> Self {
215 Self
216 }
217}
218
219impl Default for JwtMethod {
220 fn default() -> Self {
221 Self::new()
222 }
223}
224
225impl JwtMethod {
226 pub fn new() -> Self {
227 Self
228 }
229
230 pub fn secret_key(self, _secret: &str) -> Self {
231 self
232 }
233
234 pub fn issuer(self, _issuer: &str) -> Self {
235 self
236 }
237
238 pub fn audience(self, _audience: &str) -> Self {
239 self
240 }
241}
242
243impl Default for ApiKeyMethod {
244 fn default() -> Self {
245 Self::new()
246 }
247}
248
249impl ApiKeyMethod {
250 pub fn new() -> Self {
251 Self
252 }
253}
254
255impl Default for OAuth2Method {
256 fn default() -> Self {
257 Self::new()
258 }
259}
260
261impl OAuth2Method {
262 pub fn new() -> Self {
263 Self
264 }
265}
266
267impl AuthMethod for AuthMethodEnum {
268 type MethodResult = MethodResult;
269 type AuthToken = AuthToken;
270
271 fn name(&self) -> &str {
272 match self {
273 AuthMethodEnum::Password(_) => "password",
274 AuthMethodEnum::Jwt(_) => "jwt",
275 AuthMethodEnum::ApiKey(_) => "api_key",
276 AuthMethodEnum::OAuth2(_) => "oauth2",
277 #[cfg(feature = "saml")]
278 AuthMethodEnum::Saml(_) => "saml",
279 #[cfg(feature = "ldap-auth")]
280 AuthMethodEnum::Ldap(_) => "ldap",
281 AuthMethodEnum::HardwareOtpToken(_) => "hardware_token",
282 AuthMethodEnum::ClientCert(_) => "client_cert",
283 AuthMethodEnum::OpenIdConnect(_) => "openid_connect",
284 AuthMethodEnum::AdvancedMfa(_) => "advanced_mfa",
285 #[cfg(feature = "enhanced-device-flow")]
286 AuthMethodEnum::EnhancedDeviceFlow(_) => "enhanced_device_flow",
287 #[cfg(feature = "passkeys")]
288 AuthMethodEnum::Passkey(_) => "passkey",
289 }
290 }
291
292 async fn authenticate(
293 &self,
294 credential: Credential,
295 metadata: CredentialMetadata,
296 ) -> Result<Self::MethodResult> {
297 let _ = &metadata;
298 match self {
299 #[cfg(feature = "saml")]
300 AuthMethodEnum::Saml(m) => return m.authenticate(credential, metadata).await,
301 #[cfg(feature = "passkeys")]
302 AuthMethodEnum::Passkey(m) => return m.authenticate(credential, metadata).await,
303 #[cfg(feature = "enhanced-device-flow")]
304 AuthMethodEnum::EnhancedDeviceFlow(m) => {
305 return m.authenticate(credential, metadata).await;
306 }
307 AuthMethodEnum::Password(_) => match credential {
308 Credential::Password { username, password } => {
309 if username.is_empty() || password.is_empty() {
310 return Self::failure("Username or password cannot be empty");
311 }
312 Self::failure(
313 "Password authentication is handled by AuthFramework's built-in storage-backed password flow",
314 )
315 }
316 _ => Self::failure("Password authentication expects Credential::password"),
317 },
318 AuthMethodEnum::Jwt(_) => match credential {
319 Credential::Jwt { token } | Credential::Bearer { token } => {
320 if token.is_empty() {
321 return Self::failure("JWT token cannot be empty");
322 }
323 Self::failure(
324 "JWT authentication must be performed through AuthFramework so the active TokenManager can validate the token signature",
325 )
326 }
327 _ => Self::failure(
328 "JWT authentication expects Credential::jwt or Credential::bearer",
329 ),
330 },
331 AuthMethodEnum::ApiKey(_) => match credential {
332 Credential::ApiKey { key } => {
333 if key.is_empty() {
334 return Self::failure("API key cannot be empty");
335 }
336 Self::failure(
337 "API key authentication must be performed through AuthFramework so the stored key can be resolved to a user and session token",
338 )
339 }
340 _ => Self::failure("API key authentication expects Credential::api_key"),
341 },
342 AuthMethodEnum::OAuth2(_) => match credential {
343 Credential::OAuth {
344 authorization_code, ..
345 } => {
346 if authorization_code.is_empty() {
347 return Self::failure("OAuth authorization code cannot be empty");
348 }
349 Self::failure(
350 "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes",
351 )
352 }
353 Credential::OAuthRefresh { refresh_token } => {
354 if refresh_token.is_empty() {
355 return Self::failure("OAuth refresh token cannot be empty");
356 }
357 Self::failure(
358 "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes",
359 )
360 }
361 Credential::Jwt { token }
362 | Credential::Bearer { token }
363 | Credential::OpenIdConnect {
364 id_token: token, ..
365 } => {
366 if token.is_empty() {
367 return Self::failure("OAuth token cannot be empty");
368 }
369 Self::failure(
370 "OAuth 2.0 token authentication must be performed through AuthFramework so token validation and auditing use the active framework state",
371 )
372 }
373 _ => Self::failure(
374 "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect",
375 ),
376 },
377 #[cfg(feature = "ldap-auth")]
378 AuthMethodEnum::Ldap(_) => {
379 return Self::failure(
380 "LDAP authentication requires a concrete LDAP integration and cannot use the generic AuthMethodEnum fallback",
381 );
382 }
383 AuthMethodEnum::HardwareOtpToken(_) => Self::failure(
384 "Hardware token authentication requires the concrete hardware token flow rather than the generic AuthMethodEnum fallback",
385 ),
386 AuthMethodEnum::ClientCert(_) => Self::failure(
387 "Client certificate authentication requires the concrete client certificate flow rather than the generic AuthMethodEnum fallback",
388 ),
389 AuthMethodEnum::OpenIdConnect(_) => Self::failure(
390 "OpenID Connect authentication should be performed through the OIDC provider or AuthFramework integrations",
391 ),
392 AuthMethodEnum::AdvancedMfa(_) => Self::failure(
393 "Advanced MFA authentication requires the concrete MFA flow rather than the generic AuthMethodEnum fallback",
394 ),
395 }
396 }
397
398 fn validate_config(&self) -> Result<()> {
399 match self {
400 AuthMethodEnum::Password(_) => Ok(()),
401 AuthMethodEnum::Jwt(_) => Ok(()),
402 AuthMethodEnum::ApiKey(_) => Ok(()),
403 AuthMethodEnum::OAuth2(_) => Ok(()),
404 #[cfg(feature = "saml")]
405 AuthMethodEnum::Saml(method) => method.validate_config(),
406 #[cfg(feature = "ldap-auth")]
407 AuthMethodEnum::Ldap(_) => Ok(()),
408 AuthMethodEnum::HardwareOtpToken(method) => {
409 if method.device_id.trim().is_empty() {
410 return Err(AuthError::config(
411 "Hardware token device_id cannot be empty",
412 ));
413 }
414 if method.token_type.trim().is_empty() {
415 return Err(AuthError::config(
416 "Hardware token token_type cannot be empty",
417 ));
418 }
419 Ok(())
420 }
421 AuthMethodEnum::ClientCert(_) => Ok(()),
422 AuthMethodEnum::OpenIdConnect(_) => Ok(()),
423 AuthMethodEnum::AdvancedMfa(_) => Ok(()),
424 #[cfg(feature = "enhanced-device-flow")]
425 AuthMethodEnum::EnhancedDeviceFlow(method) => method.validate_config(),
426 #[cfg(feature = "passkeys")]
427 AuthMethodEnum::Passkey(method) => method.validate_config(),
428 }
429 }
430
431 fn supports_refresh(&self) -> bool {
432 false
433 }
434
435 async fn refresh_token(&self, _refresh_token: String) -> Result<AuthToken, AuthError> {
436 Err(AuthError::auth_method(
437 self.name(),
438 "Token refresh not supported by this method".to_string(),
439 ))
440 }
441}
442
443impl AuthMethodEnum {
444 fn failure(reason: impl Into<String>) -> Result<MethodResult> {
445 Ok(MethodResult::Failure {
446 reason: reason.into(),
447 })
448 }
449}
450
451impl MfaChallenge {
452 pub fn new(
454 mfa_type: MfaType,
455 user_id: impl Into<String>,
456 expires_in: std::time::Duration,
457 ) -> Self {
458 Self {
459 id: uuid::Uuid::new_v4().to_string(),
460 mfa_type,
461 user_id: user_id.into(),
462 expires_at: chrono::Utc::now()
463 + chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1)),
464 created_at: chrono::Utc::now(),
465 attempts: 0,
466 max_attempts: 3,
467 code_hash: None,
468 message: None,
469 data: HashMap::new(),
470 }
471 }
472
473 pub fn id(&self) -> &str {
475 &self.id
476 }
477
478 pub fn is_expired(&self) -> bool {
480 chrono::Utc::now() > self.expires_at
481 }
482
483 pub fn with_message(mut self, message: impl Into<String>) -> Self {
484 self.message = Some(message.into());
485 self
486 }
487}