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 enhanced_device;
13pub mod hardware_token;
14pub mod passkey;
15#[cfg(feature = "saml")]
16pub mod saml;
17
18#[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#[derive(Debug, Clone)]
29pub enum MethodResult {
30 Success(Box<AuthToken>),
32
33 MfaRequired(Box<MfaChallenge>),
35
36 Failure { reason: String },
38}
39
40#[derive(Clone, Serialize, Deserialize)]
42pub struct MfaChallenge {
43 pub id: String,
45
46 pub mfa_type: MfaType,
48
49 pub user_id: String,
51
52 pub expires_at: chrono::DateTime<chrono::Utc>,
54
55 pub message: Option<String>,
57
58 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#[derive(Debug, Clone, Serialize, Deserialize)]
77pub enum MfaType {
78 Totp,
80
81 Sms { phone_number: String },
83
84 Email { email_address: String },
86
87 Push { device_id: String },
89
90 SecurityKey,
92
93 BackupCode,
95}
96
97pub trait AuthMethod: Send + Sync {
99 type MethodResult: Send + Sync + 'static;
100 type AuthToken: Send + Sync + 'static;
101
102 fn name(&self) -> &str;
104
105 fn authenticate(
107 &self,
108 credential: Credential,
109 metadata: CredentialMetadata,
110 ) -> impl std::future::Future<Output = Result<Self::MethodResult>> + Send;
111
112 fn validate_config(&self) -> Result<()>;
114
115 fn supports_refresh(&self) -> bool {
117 false
118 }
119
120 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#[derive(Debug, Clone, Serialize, Deserialize)]
136pub struct UserInfo {
137 pub id: String,
139
140 pub username: String,
142
143 pub email: Option<String>,
145
146 pub name: Option<String>,
148
149 pub roles: Vec<String>,
151
152 pub active: bool,
154
155 pub attributes: HashMap<String, serde_json::Value>,
157}
158
159pub 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#[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
201impl 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 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 }
317 }
318
319 if let Some(ip) = &metadata.client_ip
321 && ip.starts_with("127.")
322 {
323 tracing::warn!("Authentication attempt from localhost");
324 }
325
326 tracing::warn!(
329 "Using default authentication method - this should not happen in production"
330 );
331
332 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 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 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 pub fn id(&self) -> &str {
376 &self.id
377 }
378
379 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}