oxirs-fuseki 0.3.2

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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
//! 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 cluster_auth; // Cross-node authentication tokens for cluster communication (Track A24)
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 ldap_ha; // LDAP HA failover pool (multi-server, circuit breaker, round-robin)
pub mod mfa_storage; // MFA persistent/in-memory storage backend
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 policy_templates; // 🆕 Enterprise RBAC policy template registry (DBA, ReadOnly, Auditor)
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;
#[cfg(feature = "saml")]
pub mod saml_helpers;
#[cfg(feature = "saml")]
pub mod saml_parser;
#[cfg(feature = "saml")]
pub mod saml_provider;
#[cfg(all(test, feature = "saml"))]
mod saml_tests;
#[cfg(feature = "saml")]
pub mod saml_types;
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 cluster_auth::{
    ClusterAuthConfig, ClusterAuthError, ClusterAuthManager, ClusterNodeToken, NodeIdentity,
};
pub use policy_templates::{GraphScope, PolicyTemplate, PolicyTemplateRegistry};
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 (transient, keyed by challenge_id)
    mfa_challenges: Arc<RwLock<HashMap<String, MfaChallenge>>>,
    /// Persistent MFA profile storage (TOTP secrets, backup codes, phones, etc.)
    mfa_storage: Arc<mfa_storage::MfaStorage>,
    /// Transient WebAuthn registration challenges (keyed by user_id)
    webauthn_challenges: Arc<RwLock<HashMap<String, String>>>,
}

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())),
            mfa_storage: Arc::new(mfa_storage::MfaStorage::new(None)),
            webauthn_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<()> {
        info!("Storing MFA email for user: {}", username);
        self.mfa_storage.store_email(username, email).await
    }

    /// Get user's SMS phone number
    pub async fn get_user_sms_phone(&self, username: &str) -> FusekiResult<Option<String>> {
        self.mfa_storage.get_sms_phone(username).await
    }

    /// Get user's MFA email
    pub async fn get_user_mfa_email(&self, username: &str) -> FusekiResult<Option<String>> {
        self.mfa_storage.get_email(username).await
    }

    /// Store a transient WebAuthn registration challenge for user
    pub async fn store_webauthn_challenge(
        &self,
        username: &str,
        challenge: &str,
    ) -> FusekiResult<()> {
        let mut challenges = self.webauthn_challenges.write().await;
        challenges.insert(username.to_string(), challenge.to_string());
        debug!("Stored WebAuthn challenge for user: {}", username);
        Ok(())
    }

    /// Store SMS phone number for user
    pub async fn store_sms_phone(&self, username: &str, phone: &str) -> FusekiResult<()> {
        info!("Storing SMS phone for user: {}", username);
        self.mfa_storage.store_sms_phone(username, phone).await
    }

    /// 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 derived from stored MFA profile data
    pub async fn get_user_mfa_status(&self, username: &str) -> FusekiResult<MfaStatus> {
        use chrono::Utc;
        match self.mfa_storage.get_user_data(username).await? {
            None => Ok(MfaStatus {
                enabled: false,
                enrolled_methods: vec![],
                backup_codes_remaining: 0,
                last_used: None,
                expires_at: None,
                message: "MFA not configured".to_string(),
            }),
            Some(data) => {
                let enrolled_methods: Vec<MfaMethodInfo> = data
                    .enrolled_methods
                    .iter()
                    .filter_map(|m| {
                        let method_type = match m.as_str() {
                            "totp" => MfaType::Totp,
                            "sms" => MfaType::Sms,
                            "email" => MfaType::Email,
                            "webauthn" => MfaType::Hardware,
                            "backup" => MfaType::Backup,
                            _ => return None,
                        };
                        let identifier = match m.as_str() {
                            "sms" => data.sms_phone.clone().unwrap_or_default(),
                            "email" => data.email.clone().unwrap_or_default(),
                            _ => m.clone(),
                        };
                        Some(MfaMethodInfo {
                            method_type,
                            identifier,
                            enrolled_at: data.created_at,
                            last_used: Some(data.updated_at),
                            enabled: true,
                        })
                    })
                    .collect();
                let backup_codes_remaining = data.backup_codes.len().min(255) as u8;
                let enabled = !enrolled_methods.is_empty();
                let message = if enabled {
                    format!("{} MFA method(s) enrolled", enrolled_methods.len())
                } else {
                    "MFA disabled".to_string()
                };
                Ok(MfaStatus {
                    enabled,
                    enrolled_methods,
                    backup_codes_remaining,
                    last_used: Some(data.updated_at),
                    expires_at: None,
                    message,
                })
            }
        }
    }

    /// Disable an MFA method for user
    pub async fn disable_mfa_method(&self, username: &str, method: MfaMethod) -> FusekiResult<()> {
        let method_str = match method {
            MfaMethod::Totp => "totp",
            MfaMethod::Sms => "sms",
            MfaMethod::Email => "email",
            MfaMethod::Hardware => "webauthn",
            MfaMethod::Backup => "backup",
        };
        info!(
            "Disabling MFA method '{}' for user: {}",
            method_str, username
        );
        self.mfa_storage.disable_method(username, method_str).await
    }

    /// Store backup codes for user
    pub async fn store_backup_codes(&self, username: &str, codes: Vec<String>) -> FusekiResult<()> {
        info!(
            "Storing {} backup codes for user: {}",
            codes.len(),
            username
        );
        self.mfa_storage.store_backup_codes(username, codes).await
    }

    /// Store TOTP secret for user
    pub async fn store_totp_secret(&self, username: &str, secret: &str) -> FusekiResult<()> {
        info!("Storing TOTP secret for user: {}", username);
        self.mfa_storage.store_totp_secret(username, secret).await
    }

    /// 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::*;
    use crate::config::SecurityConfig;

    async fn make_auth_service() -> AuthService {
        AuthService::new(SecurityConfig::default())
            .await
            .expect("AuthService::new should succeed with default config")
    }

    #[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");
    }

    // --- MFA storage method tests ---

    #[tokio::test]
    async fn test_store_and_get_mfa_email() {
        let svc = make_auth_service().await;
        let user = "alice";
        let email = "alice@example.com";

        svc.store_mfa_email(user, email)
            .await
            .expect("store_mfa_email");
        let retrieved = svc
            .get_user_mfa_email(user)
            .await
            .expect("get_user_mfa_email");
        assert_eq!(retrieved, Some(email.to_string()));
    }

    #[tokio::test]
    async fn test_get_user_mfa_email_returns_none_when_absent() {
        let svc = make_auth_service().await;
        let result = svc
            .get_user_mfa_email("nobody")
            .await
            .expect("get_user_mfa_email");
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_store_and_get_sms_phone() {
        let svc = make_auth_service().await;
        let user = "bob";
        let phone = "+15550001234";

        svc.store_sms_phone(user, phone)
            .await
            .expect("store_sms_phone");
        let retrieved = svc
            .get_user_sms_phone(user)
            .await
            .expect("get_user_sms_phone");
        assert_eq!(retrieved, Some(phone.to_string()));
    }

    #[tokio::test]
    async fn test_get_user_sms_phone_returns_none_when_absent() {
        let svc = make_auth_service().await;
        let result = svc
            .get_user_sms_phone("nobody")
            .await
            .expect("get_user_sms_phone");
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_store_webauthn_challenge() {
        let svc = make_auth_service().await;
        let user = "carol";
        let challenge = "base64urlencodedchallenge==";

        svc.store_webauthn_challenge(user, challenge)
            .await
            .expect("store_webauthn_challenge");

        // Verify the challenge is stored in the internal map
        let challenges = svc.webauthn_challenges.read().await;
        assert_eq!(challenges.get(user).map(String::as_str), Some(challenge));
    }

    #[tokio::test]
    async fn test_store_totp_secret() {
        let svc = make_auth_service().await;
        let user = "dave";
        let secret = "JBSWY3DPEHPK3PXP";

        svc.store_totp_secret(user, secret)
            .await
            .expect("store_totp_secret");

        // Confirm via MFA status: totp method is enrolled
        let status = svc
            .get_user_mfa_status(user)
            .await
            .expect("get_user_mfa_status");
        assert!(status.enabled);
        assert!(status
            .enrolled_methods
            .iter()
            .any(|m| m.method_type == MfaType::Totp));
    }

    #[tokio::test]
    async fn test_store_backup_codes() {
        let svc = make_auth_service().await;
        let user = "eve";
        let codes = vec![
            "CODE1".to_string(),
            "CODE2".to_string(),
            "CODE3".to_string(),
        ];

        svc.store_backup_codes(user, codes.clone())
            .await
            .expect("store_backup_codes");

        let status = svc
            .get_user_mfa_status(user)
            .await
            .expect("get_user_mfa_status");
        assert_eq!(status.backup_codes_remaining, 3);
    }

    #[tokio::test]
    async fn test_disable_mfa_method_totp() {
        let svc = make_auth_service().await;
        let user = "frank";

        svc.store_totp_secret(user, "SECRETKEY")
            .await
            .expect("store_totp_secret");
        let before = svc.get_user_mfa_status(user).await.expect("status before");
        assert!(before
            .enrolled_methods
            .iter()
            .any(|m| m.method_type == MfaType::Totp));

        svc.disable_mfa_method(user, MfaMethod::Totp)
            .await
            .expect("disable_mfa_method");
        let after = svc.get_user_mfa_status(user).await.expect("status after");
        assert!(!after
            .enrolled_methods
            .iter()
            .any(|m| m.method_type == MfaType::Totp));
    }

    #[tokio::test]
    async fn test_disable_mfa_method_sms() {
        let svc = make_auth_service().await;
        let user = "grace";

        svc.store_sms_phone(user, "+15559990000")
            .await
            .expect("store_sms_phone");
        svc.disable_mfa_method(user, MfaMethod::Sms)
            .await
            .expect("disable_mfa_method sms");

        let phone = svc
            .get_user_sms_phone(user)
            .await
            .expect("get phone after disable");
        assert!(phone.is_none());
    }

    #[tokio::test]
    async fn test_get_user_mfa_status_no_profile() {
        let svc = make_auth_service().await;
        let status = svc.get_user_mfa_status("nobody").await.expect("mfa_status");
        assert!(!status.enabled);
        assert!(status.enrolled_methods.is_empty());
        assert_eq!(status.backup_codes_remaining, 0);
    }

    #[tokio::test]
    async fn test_get_user_mfa_status_full_profile() {
        let svc = make_auth_service().await;
        let user = "heidi";

        svc.store_totp_secret(user, "TOTPSECRET")
            .await
            .expect("store totp");
        svc.store_sms_phone(user, "+15551112222")
            .await
            .expect("store sms");
        svc.store_mfa_email(user, "heidi@example.com")
            .await
            .expect("store email");
        svc.store_backup_codes(user, vec!["B1".to_string(), "B2".to_string()])
            .await
            .expect("store backup codes");

        let status = svc.get_user_mfa_status(user).await.expect("mfa status");
        assert!(status.enabled);
        assert!(status
            .enrolled_methods
            .iter()
            .any(|m| m.method_type == MfaType::Totp));
        assert!(status
            .enrolled_methods
            .iter()
            .any(|m| m.method_type == MfaType::Sms));
        assert_eq!(status.backup_codes_remaining, 2);
    }
}