oxirs-fuseki 0.2.4

SPARQL 1.1/1.2 HTTP protocol server with Fuseki-compatible configuration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! Comprehensive authentication and authorization system
//!
//! This module provides a modular authentication system with support for:
//! - Username/password authentication
//! - X.509 certificate authentication  
//! - Multi-factor authentication (TOTP, SMS, Hardware tokens)
//! - LDAP/Active Directory integration
//! - OAuth2/OIDC support
//! - SAML 2.0 authentication
//! - JWT token management
//! - Session management
//! - Role-based access control

use crate::config::{JwtConfig, LdapConfig, SecurityConfig, UserConfig};
use crate::error::{FusekiError, FusekiResult};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, info};

// Module declarations
pub mod api_key_service; // API key management with rotation and revocation
pub mod certificate;
pub mod graph_acl; // Graph-level ACL on top of dataset RBAC (v1.0 LTS)
pub mod graph_auth; // Graph-level authorization (ReBAC-based, Phase 2)
pub mod http_auth; // Simplified HTTP auth middleware (ApiKey, Basic, Bearer, None)
pub mod jwt; // JWT token generation and validation
pub mod jwt_validation; // JWT validation and JWK management
pub mod ldap;
pub mod oauth;
pub mod oauth_providers; // Provider-specific OAuth2 implementations
pub mod password;
pub mod permissions;
pub mod policy_engine; // ๐Ÿ†• Unified Policy Engine (RBAC + ReBAC)
pub mod query_filter; // ๐Ÿ†• SPARQL query result filtering (Phase 2)
pub mod rbac; // Enhanced Role-Based Access Control
pub mod rdf_rebac; // ๐Ÿ†• RDF-native ReBAC implementation (Phase 4)
pub mod rebac; // ๐Ÿ†• Relationship-Based Access Control
pub mod rebac_migration; // ๐Ÿ†• ReBAC migration tools (Export/Import/Migrate)
pub mod refresh_token; // OAuth 2.0 Refresh Token Rotation (RFC 6749 ยง10.4)
#[cfg(feature = "saml")]
pub mod saml;
pub mod session;
pub mod token_management; // Token introspection and revocation (RFC 7662, RFC 7009)
pub mod types;

// Re-export key types for easy access
pub use certificate::CertificateAuthService as CertificateAuthenticator;
pub use session::SessionManager;
pub use types::*;

/// Main authentication service that coordinates all authentication methods
#[derive(Clone)]
pub struct AuthService {
    config: Arc<SecurityConfig>,
    users: Arc<RwLock<HashMap<String, UserConfig>>>,
    session_manager: Arc<SessionManager>,
    certificate_auth: Arc<CertificateAuthenticator>,
    oauth2_service: Option<oauth::OAuth2Service>,
    ldap_service: Option<ldap::LdapService>,
    #[cfg(feature = "saml")]
    saml_provider: Option<Arc<saml::SamlProvider>>,
    /// Storage for MFA challenges
    mfa_challenges: Arc<RwLock<HashMap<String, MfaChallenge>>>,
}

impl AuthService {
    /// Create a new authentication service
    pub async fn new(config: SecurityConfig) -> FusekiResult<Self> {
        let users = config.users.clone();
        let config_arc = Arc::new(config);

        // Initialize session manager
        let session_manager = Arc::new(SessionManager::new(config_arc.session.timeout_secs as i64));

        // Initialize certificate authenticator
        let certificate_auth = Arc::new(CertificateAuthenticator::new(config_arc.clone()));

        // Initialize OAuth2 service if configured
        let oauth2_service = config_arc
            .oauth
            .as_ref()
            .map(|oauth_config| oauth::OAuth2Service::new(oauth_config.clone()));

        // Initialize LDAP service if configured
        let ldap_service = if let Some(ldap_config) = config_arc.ldap.as_ref() {
            Some(ldap::LdapService::new(ldap_config.clone()).await?)
        } else {
            None
        };

        // Initialize SAML provider if configured
        #[cfg(feature = "saml")]
        let saml_provider = if let Some(saml_config) = config_arc.saml.as_ref() {
            if saml_config.enabled {
                use url::Url;
                let saml_internal_config = saml::SamlConfig {
                    sp: saml::ServiceProviderConfig {
                        entity_id: saml_config.sp_entity_id.clone(),
                        acs_url: Url::parse(&saml_config.acs_url).map_err(|e| {
                            FusekiError::configuration(format!("Invalid SAML ACS URL: {}", e))
                        })?,
                        sls_url: saml_config
                            .slo_url
                            .as_ref()
                            .and_then(|url| Url::parse(url).ok()),
                        certificate: None, // Load from file path if needed
                        private_key: None, // Load from file path if needed
                    },
                    idp: saml::IdentityProviderConfig {
                        entity_id: saml_config.idp.entity_id.clone(),
                        sso_url: Url::parse(&saml_config.idp.sso_url).map_err(|e| {
                            FusekiError::configuration(format!("Invalid SAML SSO URL: {}", e))
                        })?,
                        slo_url: saml_config
                            .idp
                            .slo_url
                            .as_ref()
                            .and_then(|url| Url::parse(url).ok()),
                        certificate: String::new(), // Load from cert_path if needed
                        metadata_url: saml_config
                            .idp
                            .metadata_url
                            .as_ref()
                            .and_then(|url| Url::parse(url).ok()),
                    },
                    attribute_mapping: saml::AttributeMapping {
                        username: saml_config.attribute_mappings.username_attribute.clone(),
                        email: saml_config.attribute_mappings.email_attribute.clone(),
                        display_name: saml_config.attribute_mappings.name_attribute.clone(),
                        groups: saml_config.attribute_mappings.groups_attribute.clone(),
                        custom: std::collections::HashMap::new(),
                    },
                    session: saml::SessionConfig {
                        timeout: std::time::Duration::from_secs(saml_config.session_timeout_secs),
                        allow_idp_initiated: false,
                        force_authn: false,
                        track_session_index: true,
                    },
                };
                Some(Arc::new(saml::SamlProvider::new(saml_internal_config)))
            } else {
                None
            }
        } else {
            None
        };

        Ok(Self {
            config: config_arc,
            users: Arc::new(RwLock::new(users)),
            session_manager,
            certificate_auth,
            oauth2_service,
            ldap_service,
            #[cfg(feature = "saml")]
            saml_provider,
            mfa_challenges: Arc::new(RwLock::new(HashMap::new())),
        })
    }

    /// Authenticate user with username/password
    pub async fn authenticate_user(
        &self,
        username: &str,
        password: &str,
    ) -> FusekiResult<AuthResult> {
        let users = self.users.read().await;

        // Try local user authentication first
        if let Some(user_config) = users.get(username) {
            // Check if user is enabled
            if !user_config.enabled {
                info!("Login attempt for disabled user: {}", username);
                return Ok(AuthResult::Forbidden);
            }

            // Verify password using password module
            if password::PasswordUtils::verify_password(password, &user_config.password_hash)? {
                debug!("Successful local authentication for user: {}", username);

                // Create user object with permissions
                let permissions =
                    permissions::PermissionChecker::compute_user_permissions(user_config);
                let user = User {
                    username: username.to_string(),
                    roles: user_config.roles.clone(),
                    email: user_config.email.clone(),
                    full_name: user_config.full_name.clone(),
                    last_login: user_config.last_login,
                    permissions,
                };

                return Ok(AuthResult::Authenticated(user));
            }
        }

        // If local authentication failed, try LDAP if enabled
        if let Some(ldap_service) = &self.ldap_service {
            debug!("Trying LDAP authentication for user: {}", username);
            return ldap_service
                .authenticate_ldap_user(username, password)
                .await;
        }

        Ok(AuthResult::Unauthenticated)
    }

    /// Authenticate using X.509 certificate
    pub async fn authenticate_certificate(&self, cert_data: &[u8]) -> FusekiResult<AuthResult> {
        self.certificate_auth
            .authenticate_certificate(cert_data)
            .await
    }

    /// Create a new session for authenticated user
    pub async fn create_session(&self, user: User) -> FusekiResult<String> {
        self.session_manager.create_session(user).await
    }

    /// Validate an existing session
    pub async fn validate_session(&self, session_id: &str) -> FusekiResult<Option<User>> {
        match self.session_manager.validate_session(session_id).await? {
            AuthResult::Authenticated(user) => Ok(Some(user)),
            _ => Ok(None),
        }
    }

    /// Logout a session
    pub async fn logout(&self, session_id: &str) -> FusekiResult<bool> {
        self.session_manager
            .invalidate_session(session_id)
            .await
            .map(|_| true)
    }

    /// Create JWT token for user
    pub fn create_jwt_token(&self, user: &User) -> FusekiResult<String> {
        self.session_manager.create_jwt_token(user)
    }

    /// Validate JWT token
    pub fn validate_jwt_token(&self, token: &str) -> FusekiResult<TokenValidation> {
        self.session_manager.validate_jwt_token(token)
    }

    /// OAuth2 authentication URL
    pub fn get_oauth2_auth_url(&self, state: &str) -> FusekiResult<String> {
        self.oauth2_service
            .as_ref()
            .ok_or_else(|| FusekiError::configuration("OAuth2 not configured"))?
            .get_auth_url(state)
    }

    /// Complete OAuth2 authentication
    pub async fn complete_oauth2_authentication(
        &self,
        code: &str,
        state: &str,
        redirect_uri: &str,
    ) -> FusekiResult<AuthResult> {
        let oauth2_service = self
            .oauth2_service
            .as_ref()
            .ok_or_else(|| FusekiError::configuration("OAuth2 not configured"))?;

        // Exchange authorization code for access token
        let token = oauth2_service
            .exchange_code_for_token(code, state, redirect_uri)
            .await?;

        // Get user information using the access token
        let user_info = oauth2_service.get_user_info(&token.access_token).await?;

        // Extract user details from OAuth2 user info
        let username = user_info.sub.clone();
        let email = user_info.email.clone();
        let full_name = user_info.name.clone();

        // Create user object with default permissions
        // In a real implementation, you might want to map OAuth2 groups/roles to internal roles
        let roles = vec!["user".to_string()]; // Default role for OAuth2 users

        // Compute permissions for the roles
        let mut permissions = std::collections::HashSet::new();
        for role in &roles {
            if let Some(role_permissions) =
                permissions::PermissionChecker::get_role_permissions(role)
            {
                permissions.extend(role_permissions);
            }
        }
        let permissions: Vec<_> = permissions.into_iter().collect();

        let user = User {
            username: username.clone(),
            roles,
            email,
            full_name,
            last_login: Some(chrono::Utc::now()),
            permissions,
        };

        debug!("Successful OAuth2 authentication for user: {}", username);
        Ok(AuthResult::Authenticated(user))
    }

    /// Check if OAuth2 authentication is enabled
    pub fn is_oauth2_enabled(&self) -> bool {
        self.oauth2_service.is_some()
    }

    /// Generate OAuth2 authorization URL (delegating to OAuth2Service)
    pub async fn generate_oauth2_auth_url(
        &self,
        redirect_uri: &str,
        scopes: &[String],
        use_pkce: bool,
    ) -> FusekiResult<(String, String)> {
        self.oauth2_service
            .as_ref()
            .ok_or_else(|| FusekiError::configuration("OAuth2 not configured"))?
            .generate_authorization_url(redirect_uri, scopes, use_pkce)
            .await
    }

    /// Validate OAuth2 access token (delegating to OAuth2Service)
    pub async fn validate_access_token(&self, access_token: &str) -> FusekiResult<bool> {
        self.oauth2_service
            .as_ref()
            .ok_or_else(|| FusekiError::configuration("OAuth2 not configured"))?
            .validate_access_token(access_token)
            .await
    }

    /// Get OAuth configuration for discovery endpoint
    pub fn get_oauth_config(&self) -> Option<&crate::config::OAuthConfig> {
        self.config.oauth.as_ref()
    }

    /// Get OAuth2 user information (delegating to OAuth2Service)
    pub async fn get_oauth2_user_info(
        &self,
        access_token: &str,
    ) -> FusekiResult<oauth::OIDCUserInfo> {
        self.oauth2_service
            .as_ref()
            .ok_or_else(|| FusekiError::configuration("OAuth2 not configured"))?
            .get_user_info(access_token)
            .await
    }

    /// Refresh OAuth2 access token (delegating to OAuth2Service)
    pub async fn refresh_oauth2_token(
        &self,
        refresh_token: &str,
    ) -> FusekiResult<oauth::OAuth2Token> {
        self.oauth2_service
            .as_ref()
            .ok_or_else(|| FusekiError::configuration("OAuth2 not configured"))?
            .refresh_token(refresh_token)
            .await
    }

    /// SAML authentication methods
    #[cfg(feature = "saml")]
    pub async fn generate_saml_auth_request(
        &self,
        relay_state: Option<String>,
    ) -> FusekiResult<String> {
        if let Some(saml_provider) = &self.saml_provider {
            let url = saml_provider.generate_login_url(relay_state).await?;
            Ok(url.to_string())
        } else {
            Err(FusekiError::configuration("SAML not configured"))
        }
    }

    /// Check if SAML authentication is enabled
    #[cfg(feature = "saml")]
    pub fn is_saml_enabled(&self) -> bool {
        self.saml_provider.is_some()
    }

    /// Complete SAML authentication after receiving response from IdP
    #[cfg(feature = "saml")]
    pub async fn complete_saml_authentication(
        &self,
        saml_response: &str,
        relay_state: Option<&str>,
    ) -> FusekiResult<AuthResult> {
        let saml_provider = self
            .saml_provider
            .as_ref()
            .ok_or_else(|| FusekiError::configuration("SAML not configured"))?;

        // Process SAML response and extract user information
        let user = saml_provider
            .process_response(saml_response, relay_state)
            .await?;

        debug!("Successful SAML authentication for user: {}", user.username);
        Ok(AuthResult::Authenticated(user))
    }

    /// Logout user by SAML session index
    #[cfg(feature = "saml")]
    pub async fn logout_by_session_index(&self, session_index: &str) -> FusekiResult<bool> {
        let saml_provider = self
            .saml_provider
            .as_ref()
            .ok_or_else(|| FusekiError::configuration("SAML not configured"))?;

        // Find session by SAML session index
        if let Some(session_id) = saml_provider.get_session_by_index(session_index).await? {
            // Invalidate the session
            self.session_manager.invalidate_session(&session_id).await?;
            debug!("Logged out session with SAML index: {}", session_index);
            Ok(true)
        } else {
            debug!("No session found for SAML index: {}", session_index);
            Ok(false)
        }
    }

    /// Get SAML Service Provider configuration
    #[cfg(feature = "saml")]
    pub fn get_saml_sp_config(&self) -> FusekiResult<saml::ServiceProviderConfig> {
        self.saml_provider
            .as_ref()
            .map(|provider| provider.config.sp.clone())
            .ok_or_else(|| FusekiError::configuration("SAML not configured"))
    }

    /// Get SAML attribute mapping configuration
    #[cfg(feature = "saml")]
    pub fn get_saml_attribute_mapping(&self) -> FusekiResult<saml::AttributeMapping> {
        self.saml_provider
            .as_ref()
            .map(|provider| provider.config.attribute_mapping.clone())
            .ok_or_else(|| FusekiError::configuration("SAML not configured"))
    }

    /// Generate SAML logout request
    #[cfg(feature = "saml")]
    pub async fn generate_saml_logout_request(
        &self,
        session_index: &str,
        name_id: &str,
    ) -> FusekiResult<String> {
        let saml_provider = self
            .saml_provider
            .as_ref()
            .ok_or_else(|| FusekiError::configuration("SAML not configured"))?;

        saml_provider
            .generate_logout_request(session_index, name_id)
            .await
    }

    /// Get SAML metadata
    #[cfg(feature = "saml")]
    pub fn get_saml_metadata(&self) -> FusekiResult<String> {
        let saml_provider = self
            .saml_provider
            .as_ref()
            .ok_or_else(|| FusekiError::configuration("SAML not configured"))?;

        Ok(saml_provider.get_metadata())
    }

    /// Get configuration reference
    pub fn config(&self) -> &SecurityConfig {
        &self.config
    }

    /// Get session manager reference
    pub fn session_manager(&self) -> &SessionManager {
        &self.session_manager
    }

    /// Get user configuration by username
    pub async fn get_user(&self, username: &str) -> Option<UserConfig> {
        let users = self.users.read().await;
        users.get(username).cloned()
    }

    /// Hash a password using bcrypt
    pub fn hash_password(&self, password: &str) -> FusekiResult<String> {
        #[cfg(feature = "auth")]
        {
            use bcrypt::{hash, DEFAULT_COST};
            hash(password, DEFAULT_COST)
                .map_err(|e| FusekiError::authentication(format!("Failed to hash password: {e}")))
        }
        #[cfg(not(feature = "auth"))]
        {
            use std::collections::hash_map::DefaultHasher;
            use std::hash::{Hash, Hasher};

            let mut hasher = DefaultHasher::new();
            password.hash(&mut hasher);
            Ok(format!("hash_{:x}", hasher.finish()))
        }
    }

    /// Verify password against bcrypt hash
    pub fn verify_password(&self, password: &str, hash: &str) -> FusekiResult<bool> {
        #[cfg(feature = "auth")]
        {
            use bcrypt::verify;
            verify(password, hash)
                .map_err(|e| FusekiError::authentication(format!("Failed to verify password: {e}")))
        }
        #[cfg(not(feature = "auth"))]
        {
            let computed_hash = self.hash_password(password)?;
            Ok(computed_hash == hash)
        }
    }

    /// Add or update user
    pub async fn upsert_user(&self, username: String, config: UserConfig) -> FusekiResult<()> {
        let mut users = self.users.write().await;
        users.insert(username, config);
        Ok(())
    }

    /// Remove user by username
    pub async fn remove_user(&self, username: &str) -> FusekiResult<bool> {
        let mut users = self.users.write().await;
        Ok(users.remove(username).is_some())
    }

    /// Check if LDAP authentication is enabled
    pub fn is_ldap_enabled(&self) -> bool {
        self.ldap_service.is_some()
    }

    /// Authenticate user against LDAP
    pub async fn authenticate_ldap(
        &self,
        username: &str,
        password: &str,
    ) -> FusekiResult<AuthResult> {
        if let Some(ref ldap_service) = self.ldap_service {
            ldap_service
                .authenticate_ldap_user(username, password)
                .await
        } else {
            Err(FusekiError::configuration("LDAP not configured"))
        }
    }

    /// Get JWT configuration
    pub fn jwt_config(&self) -> Option<&JwtConfig> {
        self.config.jwt.as_ref()
    }

    /// Generate JWT token for user
    pub async fn generate_jwt_token(&self, user: &User) -> FusekiResult<String> {
        self.create_jwt_token(user)
    }

    /// Test LDAP connection
    pub async fn test_ldap_connection(&self) -> FusekiResult<bool> {
        if let Some(ref ldap_service) = self.ldap_service {
            ldap_service.test_connection().await
        } else {
            Err(FusekiError::configuration("LDAP not configured"))
        }
    }

    /// Get LDAP configuration
    pub fn ldap_config(&self) -> Option<&LdapConfig> {
        self.config.ldap.as_ref()
    }

    /// Get user LDAP groups
    pub async fn get_ldap_user_groups(&self, username: &str) -> FusekiResult<Vec<String>> {
        if let Some(ref ldap_service) = self.ldap_service {
            let groups = ldap_service.get_user_groups(username).await?;
            Ok(groups.into_iter().map(|group| group.cn).collect())
        } else {
            Err(FusekiError::configuration("LDAP not configured"))
        }
    }

    /// Store MFA challenge
    pub async fn store_mfa_challenge(
        &self,
        challenge_id: &str,
        challenge: MfaChallenge,
    ) -> FusekiResult<()> {
        let mut challenges = self.mfa_challenges.write().await;
        challenges.insert(challenge_id.to_string(), challenge);
        debug!("Stored MFA challenge: {}", challenge_id);
        Ok(())
    }

    /// Get MFA challenge
    pub async fn get_mfa_challenge(
        &self,
        challenge_id: &str,
    ) -> FusekiResult<Option<MfaChallenge>> {
        let challenges = self.mfa_challenges.read().await;
        Ok(challenges.get(challenge_id).cloned())
    }

    /// Remove MFA challenge
    pub async fn remove_mfa_challenge(&self, challenge_id: &str) -> FusekiResult<bool> {
        let mut challenges = self.mfa_challenges.write().await;
        let removed = challenges.remove(challenge_id).is_some();
        if removed {
            debug!("Removed MFA challenge: {}", challenge_id);
        }
        Ok(removed)
    }

    /// Store MFA email for user
    pub async fn store_mfa_email(&self, username: &str, _email: &str) -> FusekiResult<()> {
        // TODO: Implement MFA email storage in user profile
        info!("Storing MFA email for user: {}", username);
        Ok(())
    }

    /// Get user's SMS phone number
    pub async fn get_user_sms_phone(&self, _username: &str) -> FusekiResult<Option<String>> {
        // TODO: Implement SMS phone retrieval from user profile
        Ok(Some("+1-555-0123".to_string())) // Placeholder
    }

    /// Get user's MFA email
    pub async fn get_user_mfa_email(&self, _username: &str) -> FusekiResult<Option<String>> {
        // TODO: Implement MFA email retrieval from user profile
        Ok(Some("user@example.com".to_string())) // Placeholder
    }

    /// Store WebAuthn challenge
    pub async fn store_webauthn_challenge(
        &self,
        username: &str,
        _challenge: &str,
    ) -> FusekiResult<()> {
        // TODO: Implement WebAuthn challenge storage
        info!("Storing WebAuthn challenge for user: {}", username);
        Ok(())
    }

    /// Store SMS phone number for user
    pub async fn store_sms_phone(&self, username: &str, _phone: &str) -> FusekiResult<()> {
        // TODO: Implement SMS phone storage in user profile
        info!("Storing SMS phone for user: {}", username);
        Ok(())
    }

    /// Update MFA challenge (placeholder)
    pub async fn update_mfa_challenge(
        &self,
        challenge_id: &str,
        challenge: MfaChallenge,
    ) -> FusekiResult<()> {
        let mut challenges = self.mfa_challenges.write().await;
        challenges.insert(challenge_id.to_string(), challenge);
        debug!("Updated MFA challenge: {}", challenge_id);
        Ok(())
    }

    /// Get user MFA status (placeholder)
    pub async fn get_user_mfa_status(&self, _username: &str) -> FusekiResult<MfaStatus> {
        // TODO: Implement MFA status retrieval
        Ok(MfaStatus {
            enabled: false,
            enrolled_methods: vec![],
            backup_codes_remaining: 0,
            last_used: None,
            expires_at: None,
            message: "MFA disabled".to_string(),
        })
    }

    /// Disable MFA method (placeholder)
    pub async fn disable_mfa_method(
        &self,
        _username: &str,
        _method: MfaMethod,
    ) -> FusekiResult<()> {
        // TODO: Implement MFA method disabling
        Ok(())
    }

    /// Store backup codes (placeholder)
    pub async fn store_backup_codes(
        &self,
        _username: &str,
        _codes: Vec<String>,
    ) -> FusekiResult<()> {
        // TODO: Implement backup code storage
        Ok(())
    }

    /// Store TOTP secret (placeholder)
    pub async fn store_totp_secret(&self, _username: &str, _secret: &str) -> FusekiResult<()> {
        // TODO: Implement TOTP secret storage
        Ok(())
    }

    /// Cleanup LDAP cache
    pub async fn cleanup_ldap_cache(&self) {
        if let Some(ref ldap_service) = self.ldap_service {
            ldap_service.cleanup_expired_cache().await;
        }
    }
}

/// Axum authentication extractor
#[derive(Debug, Clone)]
pub struct AuthUser(pub User);

impl AuthUser {
    pub fn into_inner(self) -> User {
        self.0
    }
}

/// Convert AuthUser to User
impl From<AuthUser> for User {
    fn from(auth_user: AuthUser) -> Self {
        auth_user.0
    }
}

/// Convert User to AuthUser
impl From<User> for AuthUser {
    fn from(user: User) -> Self {
        AuthUser(user)
    }
}

/// Axum extractor implementation for AuthUser
use axum::{
    extract::{FromRequestParts, OptionalFromRequestParts},
    http::{request::Parts, StatusCode},
};
use axum_extra::headers::{authorization::Bearer, Authorization, HeaderMapExt};

impl<S> FromRequestParts<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = StatusCode;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        // Try to extract authorization header
        if let Some(auth_header) = parts.headers.typed_get::<Authorization<Bearer>>() {
            // Extract token from header
            let _token = auth_header.token();

            // Get auth service from app state (this would need to be properly implemented)
            // For now, return unauthorized
            return Err(StatusCode::UNAUTHORIZED);
        }

        // Try session-based authentication
        // This would need proper cookie handling implementation
        Err(StatusCode::UNAUTHORIZED)
    }
}

impl<S> OptionalFromRequestParts<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = std::convert::Infallible;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &S,
    ) -> Result<Option<Self>, Self::Rejection> {
        Ok(
            <Self as FromRequestParts<S>>::from_request_parts(parts, state)
                .await
                .ok(),
        )
    }
}

/// Permission requirement guard
pub struct RequirePermission(pub Permission);

/// Authentication errors
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
    #[error("Authentication required")]
    AuthenticationRequired,
    #[error("Invalid credentials")]
    InvalidCredentials,
    #[error("Permission denied")]
    PermissionDenied,
    #[error("Token expired")]
    TokenExpired,
    #[error("Invalid token")]
    InvalidToken,
    #[error("MFA required")]
    MfaRequired,
}

/// Convert AuthError to HTTP response
impl axum::response::IntoResponse for AuthError {
    fn into_response(self) -> axum::response::Response {
        let status = match self {
            AuthError::AuthenticationRequired => StatusCode::UNAUTHORIZED,
            AuthError::InvalidCredentials => StatusCode::UNAUTHORIZED,
            AuthError::PermissionDenied => StatusCode::FORBIDDEN,
            AuthError::TokenExpired => StatusCode::UNAUTHORIZED,
            AuthError::InvalidToken => StatusCode::UNAUTHORIZED,
            AuthError::MfaRequired => StatusCode::UNAUTHORIZED,
        };

        (status, self.to_string()).into_response()
    }
}

/// Helper function to decode basic auth
#[allow(dead_code)]
fn decode_basic_auth(encoded: &str) -> Result<(String, String), Box<dyn std::error::Error + Send>> {
    use base64::{engine::general_purpose::STANDARD, Engine};

    let decoded = STANDARD
        .decode(encoded)
        .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?;
    let credential =
        String::from_utf8(decoded).map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?;

    if let Some((username, password)) = credential.split_once(':') {
        Ok((username.to_string(), password.to_string()))
    } else {
        Err(Box::new(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "Invalid basic auth format",
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_decode_basic_auth() {
        let encoded = "dGVzdDpwYXNzd29yZA=="; // "test:password" in base64
        let result = decode_basic_auth(encoded).unwrap();
        assert_eq!(result.0, "test");
        assert_eq!(result.1, "password");
    }
}