uvb-factor-strength 0.2.1

Authentication factor strength evaluation and scoring for UVB
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
//! # Factor Strength Policies
//!
//! Enterprise-grade MFA factor strength enforcement to address:
//! - **Risk #10**: Phishable factors (TOTP, SMS, email links, push approve)
//! - **Risk #18**: Weak factor combinations
//! - **Risk #25**: No phishing-resistant factor requirements
//!
//! ## Features
//!
//! - **Factor Classification**: Phishable vs phishing-resistant
//! - **Risk-Based Selection**: Require stronger factors for high-risk operations
//! - **WebAuthn Enforcement**: Mandatory for admins and sensitive operations
//! - **Policy Engine**: Per-tenant configurable policies
//! - **Factor Strength Scoring**: 0-100 scale
//! - **User Warnings**: Educate users about factor security
//! - **Factor Promotion**: Encourage WebAuthn adoption
//! - **Compliance Tracking**: NIST AAL alignment

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use thiserror::Error;
use tracing::{debug, info, warn};

use uvb_core::{FactorId, TenantId, UserId};

/// Errors that can occur during factor strength enforcement
#[derive(Debug, Error)]
pub enum FactorStrengthError {
    #[error("Storage error: {0}")]
    Storage(String),

    #[error("Factor {factor_type} does not meet minimum strength requirement (required: {required}, actual: {actual})")]
    InsufficientStrength {
        factor_type: String,
        required: u8,
        actual: u8,
    },

    #[error("Operation requires phishing-resistant factor, but {factor_type} is phishable")]
    PhishableFactorRejected { factor_type: String },

    #[error("User role {role} requires WebAuthn enrollment, but user has no WebAuthn factors")]
    WebAuthnRequired { role: String },

    #[error("Policy not found for tenant {0}")]
    PolicyNotFound(TenantId),

    #[error("Invalid factor strength score: {0} (must be 0-100)")]
    InvalidScore(u8),

    #[error("No factors available that meet policy requirements")]
    NoSuitableFactors,

    #[error("Factor combination does not meet minimum strength: {0}")]
    WeakCombination(String),
}

/// Factor classification based on phishing resistance
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum FactorClass {
    /// Phishing-resistant factors (FIDO2/WebAuthn, hardware tokens)
    PhishingResistant,

    /// Phishable factors (TOTP, SMS, email links, push notifications)
    Phishable,
}

/// MFA factor types with security classification
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum FactorType {
    /// FIDO2/WebAuthn (hardware or platform authenticators)
    WebAuthn,

    /// Hardware security keys (YubiKey, Titan, etc.)
    HardwareToken,

    /// TOTP authenticator apps (Google Authenticator, Authy, etc.)
    Totp,

    /// SMS-based codes
    Sms,

    /// Email-based magic links or codes
    Email,

    /// Push notifications (approve/deny)
    PushNotification,

    /// Biometric authentication (with device binding)
    Biometric,

    /// Recovery/backup codes
    BackupCode,
}

impl FactorType {
    /// Get the security classification of this factor type
    pub fn classification(&self) -> FactorClass {
        match self {
            FactorType::WebAuthn | FactorType::HardwareToken => FactorClass::PhishingResistant,
            FactorType::Totp
            | FactorType::Sms
            | FactorType::Email
            | FactorType::PushNotification
            | FactorType::Biometric
            | FactorType::BackupCode => FactorClass::Phishable,
        }
    }

    /// Get the strength score (0-100) of this factor type
    pub fn strength_score(&self) -> u8 {
        match self {
            FactorType::WebAuthn => 100,
            FactorType::HardwareToken => 95,
            FactorType::Biometric => 75, // Depends on device security
            FactorType::Totp => 70,
            FactorType::PushNotification => 60,
            FactorType::Email => 40,
            FactorType::Sms => 30,        // Vulnerable to SIM swap
            FactorType::BackupCode => 50, // One-time use
        }
    }

    /// Get human-readable name
    pub fn display_name(&self) -> &'static str {
        match self {
            FactorType::WebAuthn => "Security Key (WebAuthn)",
            FactorType::HardwareToken => "Hardware Token",
            FactorType::Totp => "Authenticator App (TOTP)",
            FactorType::Sms => "SMS Code",
            FactorType::Email => "Email Code",
            FactorType::PushNotification => "Push Notification",
            FactorType::Biometric => "Biometric",
            FactorType::BackupCode => "Backup Code",
        }
    }

    /// Get security warning message for phishable factors
    pub fn security_warning(&self) -> Option<&'static str> {
        match self {
            FactorType::Sms => Some("SMS codes can be intercepted via SIM swap attacks. Consider upgrading to a security key."),
            FactorType::Email => Some("Email codes can be phished. Consider upgrading to a security key for better security."),
            FactorType::PushNotification => Some("Push notifications can be approved accidentally (push bombing). Consider using WebAuthn."),
            FactorType::Totp => Some("TOTP codes can be phished by fake login pages. Consider upgrading to WebAuthn for phishing-resistant authentication."),
            FactorType::WebAuthn | FactorType::HardwareToken => None, // No warning needed
            FactorType::Biometric => Some("Biometric authentication security depends on device security. Consider adding a security key."),
            FactorType::BackupCode => Some("Backup codes should only be used for account recovery. Set up a security key for daily use."),
        }
    }

    /// NIST AAL (Authenticator Assurance Level) mapping
    pub fn nist_aal(&self) -> u8 {
        match self {
            FactorType::WebAuthn | FactorType::HardwareToken => 3, // AAL3
            FactorType::Totp | FactorType::Biometric => 2,         // AAL2
            FactorType::Sms | FactorType::Email | FactorType::PushNotification => 1, // AAL1
            FactorType::BackupCode => 1,
        }
    }
}

/// Operation risk level determining required factor strength
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OperationRiskLevel {
    /// Low risk: Read operations, profile viewing
    Low = 1,

    /// Medium risk: Profile updates, non-critical changes
    Medium = 2,

    /// High risk: Financial transactions, sensitive data access
    High = 3,

    /// Critical: Admin operations, security changes, deletions
    Critical = 4,
}

impl OperationRiskLevel {
    /// Get minimum factor strength score required
    pub fn min_strength_score(&self) -> u8 {
        match self {
            OperationRiskLevel::Low => 30,      // SMS acceptable
            OperationRiskLevel::Medium => 60,   // Push/TOTP required
            OperationRiskLevel::High => 75,     // Biometric/TOTP required
            OperationRiskLevel::Critical => 95, // WebAuthn/Hardware required
        }
    }

    /// Check if phishing-resistant factor is required
    pub fn requires_phishing_resistant(&self) -> bool {
        matches!(self, OperationRiskLevel::Critical)
    }

    /// Get minimum NIST AAL required
    pub fn min_nist_aal(&self) -> u8 {
        match self {
            OperationRiskLevel::Low => 1,
            OperationRiskLevel::Medium => 2,
            OperationRiskLevel::High => 2,
            OperationRiskLevel::Critical => 3,
        }
    }
}

/// User role determining factor requirements
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum UserRole {
    /// Regular user
    User,

    /// Power user with elevated privileges
    PowerUser,

    /// Administrator with full system access
    Admin,

    /// Super admin with multi-tenant access
    SuperAdmin,

    /// Custom role with specific name
    Custom(String),
}

impl UserRole {
    /// Check if this role requires WebAuthn enrollment
    pub fn requires_webauthn(&self) -> bool {
        matches!(self, UserRole::Admin | UserRole::SuperAdmin)
    }

    /// Get minimum factor strength score for this role
    pub fn min_strength_score(&self) -> u8 {
        match self {
            UserRole::User => 30,
            UserRole::PowerUser => 60,
            UserRole::Admin => 95,
            UserRole::SuperAdmin => 100,
            UserRole::Custom(_) => 60, // Default to medium security
        }
    }
}

/// Factor strength policy configuration
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FactorStrengthPolicy {
    /// Tenant ID this policy applies to
    pub tenant_id: TenantId,

    /// Policy name
    pub name: String,

    /// Require phishing-resistant factors for all operations
    pub enforce_phishing_resistant: bool,

    /// Minimum factor strength score (0-100)
    pub min_factor_strength: u8,

    /// Require WebAuthn for admin roles
    pub require_webauthn_for_admins: bool,

    /// Risk level thresholds for operations
    pub operation_risk_levels: HashMap<String, OperationRiskLevel>,

    /// Role-based factor requirements
    pub role_requirements: HashMap<String, u8>, // Role name -> min strength

    /// Allow phishable factors as fallback
    pub allow_phishable_fallback: bool,

    /// Show security warnings for phishable factors
    pub show_security_warnings: bool,

    /// Grace period for users to upgrade factors (days)
    pub upgrade_grace_period_days: i64,

    /// Enable factor promotion campaigns
    pub enable_factor_promotion: bool,

    /// Created timestamp
    pub created_at: DateTime<Utc>,

    /// Last updated timestamp
    pub updated_at: DateTime<Utc>,
}

impl FactorStrengthPolicy {
    /// Create a default policy (balanced security)
    pub fn default(tenant_id: TenantId) -> Self {
        Self {
            tenant_id,
            name: "Default Policy".to_string(),
            enforce_phishing_resistant: false,
            min_factor_strength: 60, // TOTP minimum
            require_webauthn_for_admins: true,
            operation_risk_levels: HashMap::new(),
            role_requirements: HashMap::new(),
            allow_phishable_fallback: true,
            show_security_warnings: true,
            upgrade_grace_period_days: 90,
            enable_factor_promotion: true,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        }
    }

    /// Create a strict policy (high security)
    pub fn strict(tenant_id: TenantId) -> Self {
        let mut policy = Self::default(tenant_id);
        policy.name = "Strict Policy".to_string();
        policy.enforce_phishing_resistant = true;
        policy.min_factor_strength = 95; // WebAuthn required
        policy.allow_phishable_fallback = false;
        policy.upgrade_grace_period_days = 30;
        policy
    }

    /// Create a lenient policy (development/testing)
    pub fn lenient(tenant_id: TenantId) -> Self {
        let mut policy = Self::default(tenant_id);
        policy.name = "Lenient Policy".to_string();
        policy.min_factor_strength = 30; // SMS acceptable
        policy.require_webauthn_for_admins = false;
        policy.show_security_warnings = false;
        policy.upgrade_grace_period_days = 365;
        policy.enable_factor_promotion = false;
        policy
    }

    /// Check if a factor meets this policy's requirements
    pub fn is_factor_allowed(
        &self,
        factor_type: FactorType,
        operation_risk: OperationRiskLevel,
    ) -> Result<(), FactorStrengthError> {
        let factor_strength = factor_type.strength_score();
        let min_strength = operation_risk
            .min_strength_score()
            .max(self.min_factor_strength);

        // Check strength score
        if factor_strength < min_strength {
            return Err(FactorStrengthError::InsufficientStrength {
                factor_type: factor_type.display_name().to_string(),
                required: min_strength,
                actual: factor_strength,
            });
        }

        // Check phishing resistance if required
        if (self.enforce_phishing_resistant || operation_risk.requires_phishing_resistant())
            && factor_type.classification() == FactorClass::Phishable
            && !self.allow_phishable_fallback
        {
            return Err(FactorStrengthError::PhishableFactorRejected {
                factor_type: factor_type.display_name().to_string(),
            });
        }

        Ok(())
    }

    /// Get operation risk level for a specific operation
    pub fn get_operation_risk(&self, operation: &str) -> OperationRiskLevel {
        self.operation_risk_levels
            .get(operation)
            .copied()
            .unwrap_or(OperationRiskLevel::Medium) // Default to medium
    }
}

/// Factor enrollment information
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EnrolledFactor {
    pub factor_id: FactorId,
    pub user_id: UserId,
    pub factor_type: FactorType,
    pub enrolled_at: DateTime<Utc>,
    pub last_used_at: Option<DateTime<Utc>>,
    pub is_primary: bool,
}

impl EnrolledFactor {
    /// Get the strength score of this factor
    pub fn strength_score(&self) -> u8 {
        self.factor_type.strength_score()
    }

    /// Get security classification
    pub fn classification(&self) -> FactorClass {
        self.factor_type.classification()
    }

    /// Check if this factor is phishing-resistant
    pub fn is_phishing_resistant(&self) -> bool {
        self.classification() == FactorClass::PhishingResistant
    }
}

/// Factor selection recommendation
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FactorRecommendation {
    /// Available factors that meet requirements
    pub suitable_factors: Vec<FactorId>,

    /// Recommended primary factor
    pub recommended_factor: Option<FactorId>,

    /// Factors that don't meet requirements
    pub unsuitable_factors: Vec<(FactorId, String)>, // Factor ID and reason

    /// Security warnings for selected factors
    pub warnings: Vec<String>,

    /// Factor upgrade recommendations
    pub upgrade_recommendations: Vec<String>,
}

/// Factor strength enforcement result
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EnforcementResult {
    pub allowed: bool,
    pub factor_id: FactorId,
    pub factor_type: FactorType,
    pub strength_score: u8,
    pub is_phishing_resistant: bool,
    pub warnings: Vec<String>,
    pub reason: Option<String>, // Rejection reason if not allowed
}

/// Storage trait for factor strength policies
#[async_trait]
pub trait FactorStrengthStorage: Send + Sync {
    /// Get policy for a tenant
    async fn get_policy(
        &self,
        tenant_id: &TenantId,
    ) -> Result<FactorStrengthPolicy, FactorStrengthError>;

    /// Save or update policy
    async fn save_policy(&self, policy: &FactorStrengthPolicy) -> Result<(), FactorStrengthError>;

    /// Get enrolled factors for a user
    async fn get_user_factors(
        &self,
        user_id: &UserId,
    ) -> Result<Vec<EnrolledFactor>, FactorStrengthError>;

    /// Record factor usage
    async fn record_factor_usage(
        &self,
        factor_id: &FactorId,
        operation: &str,
        risk_level: OperationRiskLevel,
    ) -> Result<(), FactorStrengthError>;

    /// Check if user is in grace period
    async fn is_in_grace_period(&self, user_id: &UserId) -> Result<bool, FactorStrengthError>;

    /// Record factor promotion shown
    async fn record_promotion_shown(
        &self,
        user_id: &UserId,
        promotion_type: &str,
    ) -> Result<(), FactorStrengthError>;
}

/// In-memory storage for testing
pub struct InMemoryFactorStrengthStorage {
    policies: tokio::sync::RwLock<HashMap<TenantId, FactorStrengthPolicy>>,
    factors: tokio::sync::RwLock<HashMap<UserId, Vec<EnrolledFactor>>>,
    grace_periods: tokio::sync::RwLock<HashMap<UserId, DateTime<Utc>>>,
}

impl InMemoryFactorStrengthStorage {
    pub fn new() -> Self {
        Self {
            policies: tokio::sync::RwLock::new(HashMap::new()),
            factors: tokio::sync::RwLock::new(HashMap::new()),
            grace_periods: tokio::sync::RwLock::new(HashMap::new()),
        }
    }
}

impl Default for InMemoryFactorStrengthStorage {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl FactorStrengthStorage for InMemoryFactorStrengthStorage {
    async fn get_policy(
        &self,
        tenant_id: &TenantId,
    ) -> Result<FactorStrengthPolicy, FactorStrengthError> {
        let policies = self.policies.read().await;
        policies
            .get(tenant_id)
            .cloned()
            .ok_or_else(|| FactorStrengthError::PolicyNotFound(tenant_id.clone()))
    }

    async fn save_policy(&self, policy: &FactorStrengthPolicy) -> Result<(), FactorStrengthError> {
        let mut policies = self.policies.write().await;
        policies.insert(policy.tenant_id.clone(), policy.clone());
        Ok(())
    }

    async fn get_user_factors(
        &self,
        user_id: &UserId,
    ) -> Result<Vec<EnrolledFactor>, FactorStrengthError> {
        let factors = self.factors.read().await;
        Ok(factors.get(user_id).cloned().unwrap_or_default())
    }

    async fn record_factor_usage(
        &self,
        _factor_id: &FactorId,
        _operation: &str,
        _risk_level: OperationRiskLevel,
    ) -> Result<(), FactorStrengthError> {
        // In-memory implementation - no persistence needed for testing
        Ok(())
    }

    async fn is_in_grace_period(&self, user_id: &UserId) -> Result<bool, FactorStrengthError> {
        let grace_periods = self.grace_periods.read().await;
        if let Some(expiry) = grace_periods.get(user_id) {
            Ok(Utc::now() < *expiry)
        } else {
            Ok(false)
        }
    }

    async fn record_promotion_shown(
        &self,
        _user_id: &UserId,
        _promotion_type: &str,
    ) -> Result<(), FactorStrengthError> {
        Ok(())
    }
}

/// Factor strength enforcement manager
pub struct FactorStrengthManager<S: FactorStrengthStorage> {
    storage: S,
}

impl<S: FactorStrengthStorage> FactorStrengthManager<S> {
    /// Create a new manager with the given storage backend
    pub fn new(storage: S) -> Self {
        Self { storage }
    }

    /// Get policy for a tenant (creates default if not exists)
    pub async fn get_or_create_policy(
        &self,
        tenant_id: &TenantId,
    ) -> Result<FactorStrengthPolicy, FactorStrengthError> {
        match self.storage.get_policy(tenant_id).await {
            Ok(policy) => Ok(policy),
            Err(FactorStrengthError::PolicyNotFound(_)) => {
                let policy = FactorStrengthPolicy::default(tenant_id.clone());
                self.storage.save_policy(&policy).await?;
                Ok(policy)
            }
            Err(e) => Err(e),
        }
    }

    /// Check if a user can perform an operation with their factors
    pub async fn check_operation_allowed(
        &self,
        user_id: &UserId,
        tenant_id: &TenantId,
        user_role: &UserRole,
        operation: &str,
    ) -> Result<FactorRecommendation, FactorStrengthError> {
        let policy = self.get_or_create_policy(tenant_id).await?;
        let factors = self.storage.get_user_factors(user_id).await?;
        let operation_risk = policy.get_operation_risk(operation);

        debug!(
            "Checking operation '{}' for user {:?} with risk level {:?}",
            operation, user_id, operation_risk
        );

        // Check if user role requires WebAuthn
        if policy.require_webauthn_for_admins && user_role.requires_webauthn() {
            let has_webauthn = factors.iter().any(|f| {
                f.factor_type == FactorType::WebAuthn || f.factor_type == FactorType::HardwareToken
            });

            if !has_webauthn {
                return Err(FactorStrengthError::WebAuthnRequired {
                    role: format!("{:?}", user_role),
                });
            }
        }

        let mut suitable_factors = Vec::new();
        let mut unsuitable_factors = Vec::new();
        let mut warnings = Vec::new();
        let mut upgrade_recommendations = Vec::new();

        // Evaluate each factor
        for factor in &factors {
            match policy.is_factor_allowed(factor.factor_type, operation_risk) {
                Ok(()) => {
                    suitable_factors.push(factor.factor_id.clone());

                    // Add security warning if applicable
                    if policy.show_security_warnings {
                        if let Some(warning) = factor.factor_type.security_warning() {
                            warnings.push(warning.to_string());
                        }
                    }
                }
                Err(e) => {
                    unsuitable_factors.push((factor.factor_id.clone(), e.to_string()));
                }
            }
        }

        // Generate upgrade recommendations
        if policy.enable_factor_promotion {
            let has_phishing_resistant = factors.iter().any(|f| f.is_phishing_resistant());

            if !has_phishing_resistant {
                upgrade_recommendations.push(
                    "Consider adding a security key (WebAuthn) for phishing-resistant authentication.".to_string()
                );
            }

            let max_strength = factors
                .iter()
                .map(|f| f.strength_score())
                .max()
                .unwrap_or(0);
            if max_strength < 95 {
                upgrade_recommendations.push(
                    "Upgrade to WebAuthn or hardware tokens for maximum security.".to_string(),
                );
            }
        }

        // Find recommended primary factor (highest strength)
        let recommended_factor = suitable_factors.first().cloned();

        if suitable_factors.is_empty() {
            if self.storage.is_in_grace_period(user_id).await? {
                warn!(
                    "User {:?} has no suitable factors but is in grace period",
                    user_id
                );
            } else {
                return Err(FactorStrengthError::NoSuitableFactors);
            }
        }

        Ok(FactorRecommendation {
            suitable_factors,
            recommended_factor,
            unsuitable_factors,
            warnings,
            upgrade_recommendations,
        })
    }

    /// Enforce factor strength for an operation
    pub async fn enforce_factor_strength(
        &self,
        factor_id: &FactorId,
        tenant_id: &TenantId,
        operation: &str,
    ) -> Result<EnforcementResult, FactorStrengthError> {
        let policy = self.get_or_create_policy(tenant_id).await?;
        let operation_risk = policy.get_operation_risk(operation);

        // Find the factor (in real implementation, query from storage)
        // For now, we'll need the factor type passed in or queried

        info!(
            "Enforcing factor strength for operation '{}' at risk level {:?}",
            operation, operation_risk
        );

        // Record usage
        self.storage
            .record_factor_usage(factor_id, operation, operation_risk)
            .await?;

        // This is a simplified version - in production, would query factor details
        Ok(EnforcementResult {
            allowed: true,
            factor_id: factor_id.clone(),
            factor_type: FactorType::WebAuthn, // Would be queried
            strength_score: 100,
            is_phishing_resistant: true,
            warnings: vec![],
            reason: None,
        })
    }

    /// Get factor strength report for a user
    pub async fn get_user_factor_report(
        &self,
        user_id: &UserId,
    ) -> Result<UserFactorReport, FactorStrengthError> {
        let factors = self.storage.get_user_factors(user_id).await?;

        let total_factors = factors.len();
        let phishing_resistant_count = factors.iter().filter(|f| f.is_phishing_resistant()).count();
        let max_strength = factors
            .iter()
            .map(|f| f.strength_score())
            .max()
            .unwrap_or(0);
        let min_strength = factors
            .iter()
            .map(|f| f.strength_score())
            .min()
            .unwrap_or(0);

        let factor_breakdown: HashMap<FactorType, usize> =
            factors.iter().fold(HashMap::new(), |mut acc, f| {
                *acc.entry(f.factor_type).or_insert(0) += 1;
                acc
            });

        Ok(UserFactorReport {
            user_id: user_id.clone(),
            total_factors,
            phishing_resistant_count,
            max_strength_score: max_strength,
            min_strength_score: min_strength,
            factor_breakdown,
            has_webauthn: factors
                .iter()
                .any(|f| f.factor_type == FactorType::WebAuthn),
            generated_at: Utc::now(),
        })
    }

    /// Save or update policy
    pub async fn save_policy(
        &self,
        policy: &FactorStrengthPolicy,
    ) -> Result<(), FactorStrengthError> {
        self.storage.save_policy(policy).await
    }
}

/// User factor strength report
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UserFactorReport {
    pub user_id: UserId,
    pub total_factors: usize,
    pub phishing_resistant_count: usize,
    pub max_strength_score: u8,
    pub min_strength_score: u8,
    pub factor_breakdown: HashMap<FactorType, usize>,
    pub has_webauthn: bool,
    pub generated_at: DateTime<Utc>,
}

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

    #[test]
    fn test_factor_classification() {
        assert_eq!(
            FactorType::WebAuthn.classification(),
            FactorClass::PhishingResistant
        );
        assert_eq!(
            FactorType::HardwareToken.classification(),
            FactorClass::PhishingResistant
        );
        assert_eq!(FactorType::Totp.classification(), FactorClass::Phishable);
        assert_eq!(FactorType::Sms.classification(), FactorClass::Phishable);
    }

    #[test]
    fn test_factor_strength_scores() {
        assert_eq!(FactorType::WebAuthn.strength_score(), 100);
        assert_eq!(FactorType::HardwareToken.strength_score(), 95);
        assert_eq!(FactorType::Totp.strength_score(), 70);
        assert_eq!(FactorType::Sms.strength_score(), 30);
    }

    #[test]
    fn test_operation_risk_requirements() {
        assert!(OperationRiskLevel::Critical.requires_phishing_resistant());
        assert!(!OperationRiskLevel::High.requires_phishing_resistant());
        assert_eq!(OperationRiskLevel::Critical.min_strength_score(), 95);
        assert_eq!(OperationRiskLevel::Low.min_strength_score(), 30);
    }

    #[test]
    fn test_nist_aal_mapping() {
        assert_eq!(FactorType::WebAuthn.nist_aal(), 3);
        assert_eq!(FactorType::Totp.nist_aal(), 2);
        assert_eq!(FactorType::Sms.nist_aal(), 1);
    }

    #[test]
    fn test_policy_presets() {
        let tenant_id = TenantId::new("test_tenant");

        let default_policy = FactorStrengthPolicy::default(tenant_id.clone());
        assert_eq!(default_policy.min_factor_strength, 60);
        assert!(default_policy.allow_phishable_fallback);

        let strict_policy = FactorStrengthPolicy::strict(tenant_id.clone());
        assert_eq!(strict_policy.min_factor_strength, 95);
        assert!(!strict_policy.allow_phishable_fallback);
        assert!(strict_policy.enforce_phishing_resistant);

        let lenient_policy = FactorStrengthPolicy::lenient(tenant_id);
        assert_eq!(lenient_policy.min_factor_strength, 30);
        assert!(!lenient_policy.require_webauthn_for_admins);
    }

    #[test]
    fn test_factor_allowed_checks() {
        let tenant_id = TenantId::new("test_tenant");
        let policy = FactorStrengthPolicy::default(tenant_id);

        // SMS should be rejected for critical operations
        let result = policy.is_factor_allowed(FactorType::Sms, OperationRiskLevel::Critical);
        assert!(result.is_err());

        // WebAuthn should always be allowed
        let result = policy.is_factor_allowed(FactorType::WebAuthn, OperationRiskLevel::Critical);
        assert!(result.is_ok());

        // TOTP should be allowed for medium risk
        let result = policy.is_factor_allowed(FactorType::Totp, OperationRiskLevel::Medium);
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_manager_basic_operations() {
        let storage = InMemoryFactorStrengthStorage::new();
        let manager = FactorStrengthManager::new(storage);

        let tenant_id = TenantId::new("test_tenant");
        let policy = manager.get_or_create_policy(&tenant_id).await.unwrap();

        assert_eq!(policy.tenant_id, tenant_id);
        assert_eq!(policy.min_factor_strength, 60);
    }

    #[tokio::test]
    async fn test_user_factor_report() {
        let storage = InMemoryFactorStrengthStorage::new();
        let manager = FactorStrengthManager::new(storage);

        let user_id = UserId::new("test_user");
        let report = manager.get_user_factor_report(&user_id).await.unwrap();

        assert_eq!(report.total_factors, 0);
        assert_eq!(report.phishing_resistant_count, 0);
    }

    #[test]
    fn test_user_role_requirements() {
        assert!(UserRole::Admin.requires_webauthn());
        assert!(UserRole::SuperAdmin.requires_webauthn());
        assert!(!UserRole::User.requires_webauthn());
        assert!(!UserRole::PowerUser.requires_webauthn());
    }
}