Skip to main content

auth_framework/methods/
mod.rs

1//! Authentication method implementations.
2
3use crate::{
4    authentication::credentials::{Credential, CredentialMetadata},
5    errors::{AuthError, Result},
6    tokens::AuthToken,
7};
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10
11// Import the specific auth method modules
12pub mod enhanced_device;
13pub mod hardware_token;
14pub mod passkey;
15#[cfg(feature = "saml")]
16pub mod saml;
17
18// Re-export types from submodules
19#[cfg(feature = "enhanced-device-flow")]
20pub use enhanced_device::EnhancedDeviceFlowMethod;
21pub use hardware_token::HardwareToken;
22#[cfg(feature = "passkeys")]
23pub use passkey::PasskeyAuthMethod;
24#[cfg(feature = "saml")]
25pub use saml::SamlAuthMethod;
26
27/// Result of an authentication attempt.
28#[derive(Debug, Clone)]
29pub enum MethodResult {
30    /// Authentication was successful
31    Success(Box<AuthToken>),
32
33    /// Multi-factor authentication is required
34    MfaRequired(Box<MfaChallenge>),
35
36    /// Authentication failed
37    Failure { reason: String },
38}
39
40/// Multi-factor authentication challenge.
41#[derive(Clone, Serialize, Deserialize)]
42pub struct MfaChallenge {
43    /// Unique challenge ID
44    pub id: String,
45
46    /// Type of MFA required
47    pub mfa_type: MfaType,
48
49    /// User ID this challenge is for
50    pub user_id: String,
51
52    /// When the challenge expires
53    pub expires_at: chrono::DateTime<chrono::Utc>,
54
55    /// Optional message or instructions
56    pub message: Option<String>,
57
58    /// Additional challenge data
59    pub data: HashMap<String, serde_json::Value>,
60}
61
62impl std::fmt::Debug for MfaChallenge {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        let mut d = f.debug_struct("MfaChallenge");
65        d.field("id", &self.id);
66        d.field("mfa_type", &self.mfa_type);
67        d.field("user_id", &self.user_id);
68        d.field("expires_at", &self.expires_at);
69        d.field("message", &self.message);
70        d.field("data", &crate::utils::redact::redacted(&self.data));
71        d.finish()
72    }
73}
74
75/// Types of multi-factor authentication.
76#[derive(Debug, Clone, Serialize, Deserialize)]
77pub enum MfaType {
78    /// Time-based one-time password (TOTP)
79    Totp,
80
81    /// SMS verification code
82    Sms { phone_number: String },
83
84    /// Email verification code
85    Email { email_address: String },
86
87    /// Push notification
88    Push { device_id: String },
89
90    /// Hardware security key
91    SecurityKey,
92
93    /// Backup codes
94    BackupCode,
95}
96
97/// Trait for authentication methods.
98pub trait AuthMethod: Send + Sync {
99    type MethodResult: Send + Sync + 'static;
100    type AuthToken: Send + Sync + 'static;
101
102    /// Get the name of this authentication method.
103    fn name(&self) -> &str;
104
105    /// Authenticate using the provided credentials.
106    fn authenticate(
107        &self,
108        credential: Credential,
109        metadata: CredentialMetadata,
110    ) -> impl std::future::Future<Output = Result<Self::MethodResult>> + Send;
111
112    /// Validate configuration for this method.
113    fn validate_config(&self) -> Result<()>;
114
115    /// Check if this method supports refresh tokens.
116    fn supports_refresh(&self) -> bool {
117        false
118    }
119
120    /// Refresh a token if supported.
121    fn refresh_token(
122        &self,
123        _refresh_token: String,
124    ) -> impl std::future::Future<Output = Result<AuthToken, AuthError>> + Send {
125        async {
126            Err(AuthError::auth_method(
127                self.name(),
128                "Token refresh not supported by this method".to_string(),
129            ))
130        }
131    }
132}
133
134/// Basic user information.
135#[derive(Debug, Clone, Serialize, Deserialize)]
136pub struct UserInfo {
137    /// User ID
138    pub id: String,
139
140    /// Username
141    pub username: String,
142
143    /// Email address
144    pub email: Option<String>,
145
146    /// Display name
147    pub name: Option<String>,
148
149    /// User roles
150    pub roles: Vec<String>,
151
152    /// Whether the user is active
153    pub active: bool,
154
155    /// Additional user attributes
156    pub attributes: HashMap<String, serde_json::Value>,
157}
158
159/// Enum wrapper for all supported authentication methods (for registry)
160pub enum AuthMethodEnum {
161    Password(PasswordMethod),
162    Jwt(JwtMethod),
163    ApiKey(ApiKeyMethod),
164    OAuth2(OAuth2Method),
165    #[cfg(feature = "saml")]
166    Saml(SamlAuthMethod),
167    #[cfg(feature = "ldap-auth")]
168    Ldap(LdapAuthMethod),
169    HardwareToken(HardwareToken),
170    OpenIdConnect(OpenIdConnectAuthMethod),
171    AdvancedMfa(AdvancedMfaAuthMethod),
172    #[cfg(feature = "enhanced-device-flow")]
173    EnhancedDeviceFlow(Box<enhanced_device::EnhancedDeviceFlowMethod>),
174    #[cfg(feature = "passkeys")]
175    Passkey(PasskeyAuthMethod),
176}
177
178/// Simplified implementations - these would contain the full implementations
179#[derive(Debug)]
180pub struct PasswordMethod;
181
182#[derive(Debug)]
183pub struct JwtMethod;
184
185#[derive(Debug)]
186pub struct ApiKeyMethod;
187
188#[derive(Debug)]
189pub struct OAuth2Method;
190
191#[cfg(feature = "ldap-auth")]
192#[derive(Debug)]
193pub struct LdapAuthMethod;
194
195#[derive(Debug)]
196pub struct OpenIdConnectAuthMethod;
197
198#[derive(Debug)]
199pub struct AdvancedMfaAuthMethod;
200
201// Add basic constructors for test compatibility
202impl Default for PasswordMethod {
203    fn default() -> Self {
204        Self::new()
205    }
206}
207
208impl PasswordMethod {
209    pub fn new() -> Self {
210        Self
211    }
212}
213
214impl Default for JwtMethod {
215    fn default() -> Self {
216        Self::new()
217    }
218}
219
220impl JwtMethod {
221    pub fn new() -> Self {
222        Self
223    }
224
225    pub fn secret_key(self, _secret: &str) -> Self {
226        self
227    }
228
229    pub fn issuer(self, _issuer: &str) -> Self {
230        self
231    }
232
233    pub fn audience(self, _audience: &str) -> Self {
234        self
235    }
236}
237
238impl Default for ApiKeyMethod {
239    fn default() -> Self {
240        Self::new()
241    }
242}
243
244impl ApiKeyMethod {
245    pub fn new() -> Self {
246        Self
247    }
248}
249
250impl Default for OAuth2Method {
251    fn default() -> Self {
252        Self::new()
253    }
254}
255
256impl OAuth2Method {
257    pub fn new() -> Self {
258        Self
259    }
260}
261
262impl AuthMethod for AuthMethodEnum {
263    type MethodResult = MethodResult;
264    type AuthToken = AuthToken;
265
266    fn name(&self) -> &str {
267        match self {
268            AuthMethodEnum::Password(_) => "password",
269            AuthMethodEnum::Jwt(_) => "jwt",
270            AuthMethodEnum::ApiKey(_) => "api_key",
271            AuthMethodEnum::OAuth2(_) => "oauth2",
272            #[cfg(feature = "saml")]
273            AuthMethodEnum::Saml(_) => "saml",
274            #[cfg(feature = "ldap-auth")]
275            AuthMethodEnum::Ldap(_) => "ldap",
276            AuthMethodEnum::HardwareToken(_) => "hardware_token",
277            AuthMethodEnum::OpenIdConnect(_) => "openid_connect",
278            AuthMethodEnum::AdvancedMfa(_) => "advanced_mfa",
279            #[cfg(feature = "enhanced-device-flow")]
280            AuthMethodEnum::EnhancedDeviceFlow(_) => "enhanced_device_flow",
281            #[cfg(feature = "passkeys")]
282            AuthMethodEnum::Passkey(_) => "passkey",
283        }
284    }
285
286    async fn authenticate(
287        &self,
288        credential: Credential,
289        metadata: CredentialMetadata,
290    ) -> Result<Self::MethodResult> {
291        // Enhanced stub implementation with basic credential validation
292
293        // Validate credential based on type
294        match &credential {
295            Credential::Password { username, password } => {
296                if username.is_empty() || password.is_empty() {
297                    return Ok(MethodResult::Failure {
298                        reason: "Username or password cannot be empty".to_string(),
299                    });
300                }
301            }
302            Credential::Jwt { token } => {
303                if token.is_empty() {
304                    return Ok(MethodResult::Failure {
305                        reason: "JWT token cannot be empty".to_string(),
306                    });
307                }
308            }
309            Credential::ApiKey { key } if key.is_empty() => {
310                return Ok(MethodResult::Failure {
311                    reason: "API key cannot be empty".to_string(),
312                });
313            }
314            _ => {
315                // For other credential types, basic validation passed
316            }
317        }
318
319        // Check metadata for suspicious patterns
320        if let Some(ip) = &metadata.client_ip
321            && ip.starts_with("127.")
322        {
323            tracing::warn!("Authentication attempt from localhost");
324        }
325
326        // For methods that don't override this implementation, provide basic validation
327        // In a production system, this should never be reached - all auth methods should implement their own logic
328        tracing::warn!(
329            "Using default authentication method - this should not happen in production"
330        );
331
332        // Return failure by default - concrete implementations should override this
333        Ok(MethodResult::Failure {
334            reason:
335                "Authentication method not fully implemented - please use a concrete implementation"
336                    .to_string(),
337        })
338    }
339
340    fn validate_config(&self) -> Result<()> {
341        // Enhanced stub implementation with basic validation
342        Ok(())
343    }
344
345    fn supports_refresh(&self) -> bool {
346        false
347    }
348
349    async fn refresh_token(&self, _refresh_token: String) -> Result<AuthToken, AuthError> {
350        Err(AuthError::auth_method(
351            self.name(),
352            "Token refresh not supported by this method".to_string(),
353        ))
354    }
355}
356
357impl MfaChallenge {
358    /// Create a new MFA challenge.
359    pub fn new(
360        mfa_type: MfaType,
361        user_id: impl Into<String>,
362        expires_in: std::time::Duration,
363    ) -> Self {
364        Self {
365            id: uuid::Uuid::new_v4().to_string(),
366            mfa_type,
367            user_id: user_id.into(),
368            expires_at: chrono::Utc::now() + chrono::Duration::from_std(expires_in).unwrap(),
369            message: None,
370            data: HashMap::new(),
371        }
372    }
373
374    /// Get the challenge ID.
375    pub fn id(&self) -> &str {
376        &self.id
377    }
378
379    /// Check if the challenge has expired.
380    pub fn is_expired(&self) -> bool {
381        chrono::Utc::now() > self.expires_at
382    }
383
384    pub fn with_message(mut self, message: impl Into<String>) -> Self {
385        self.message = Some(message.into());
386        self
387    }
388}