uvb-biometric-security 0.2.1

Biometric verification factor implementation 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
//! # Biometric Security Enhancements
//!
//! Enterprise-grade biometric authentication security to address:
//! - **Risk #6**: Biometric spoofing attacks (deepfake voice, fingerprint molds)
//!
//! ## Features
//!
//! - **User Verification (UV) Enforcement**: Require UV=true in WebAuthn
//! - **Liveness Detection Validation**: Verify authenticator supports liveness
//! - **Step-Up Authentication**: Require additional auth for sensitive operations
//! - **Risk-Based Re-Verification**: Re-verify biometrics based on risk
//! - **Biometric Quality Checks**: Validate biometric quality scores
//! - **Authenticator Attestation**: Verify authenticator capabilities
//! - **Usage Tracking**: Monitor biometric usage patterns
//! - **Anomaly Detection**: Detect suspicious biometric usage

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

use uvb_core::{TenantId, UserId};

/// Errors that can occur in biometric security
#[derive(Debug, Error)]
pub enum BiometricError {
    #[error("User verification not performed")]
    UserVerificationNotPerformed,

    #[error("Liveness detection not supported")]
    LivenessNotSupported,

    #[error("Step-up authentication required")]
    StepUpRequired,

    #[error("Biometric re-verification required")]
    ReverificationRequired,

    #[error("Biometric quality too low: {quality} (minimum: {minimum})")]
    QualityTooLow { quality: u8, minimum: u8 },

    #[error("Authenticator not verified")]
    AuthenticatorNotVerified,

    #[error("Biometric verification expired at {0}")]
    VerificationExpired(DateTime<Utc>),

    #[error("Risk score too high: {0}")]
    RiskScoreTooHigh(u8),

    #[error("Storage error: {0}")]
    Storage(String),
}

/// Biometric modality
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum BiometricModality {
    Fingerprint,
    FaceRecognition,
    IrisScanning,
    VoiceRecognition,
    BehavioralBiometrics,
}

impl BiometricModality {
    /// Get modality name
    pub fn name(&self) -> &'static str {
        match self {
            Self::Fingerprint => "Fingerprint",
            Self::FaceRecognition => "Face Recognition",
            Self::IrisScanning => "Iris Scanning",
            Self::VoiceRecognition => "Voice Recognition",
            Self::BehavioralBiometrics => "Behavioral Biometrics",
        }
    }

    /// Get spoofing risk level
    pub fn spoofing_risk(&self) -> RiskLevel {
        match self {
            Self::IrisScanning => RiskLevel::Low,
            Self::FaceRecognition => RiskLevel::Medium, // Deepfake risk
            Self::Fingerprint => RiskLevel::Medium,     // Mold/lift risk
            Self::VoiceRecognition => RiskLevel::High,  // Deepfake risk
            Self::BehavioralBiometrics => RiskLevel::Low,
        }
    }

    /// Check if liveness detection is critical
    pub fn requires_liveness(&self) -> bool {
        matches!(
            self,
            Self::FaceRecognition | Self::Fingerprint | Self::VoiceRecognition
        )
    }
}

/// Risk level
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum RiskLevel {
    Low,
    Medium,
    High,
    Critical,
}

/// Authenticator capabilities
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuthenticatorCapabilities {
    /// AAGUID (Authenticator Attestation GUID)
    pub aaguid: String,

    /// Manufacturer
    pub manufacturer: Option<String>,

    /// Model
    pub model: Option<String>,

    /// Supports user verification
    pub supports_uv: bool,

    /// Supports liveness detection
    pub supports_liveness: bool,

    /// Biometric modality
    pub biometric_modality: Option<BiometricModality>,

    /// Certification level
    pub certification_level: CertificationLevel,

    /// Firmware version
    pub firmware_version: Option<String>,
}

impl AuthenticatorCapabilities {
    /// Create new capabilities
    pub fn new(aaguid: String) -> Self {
        Self {
            aaguid,
            manufacturer: None,
            model: None,
            supports_uv: false,
            supports_liveness: false,
            biometric_modality: None,
            certification_level: CertificationLevel::None,
            firmware_version: None,
        }
    }

    /// Check if authenticator is secure enough
    pub fn is_secure(&self) -> bool {
        self.supports_uv
            && self.supports_liveness
            && self.certification_level >= CertificationLevel::Level1
    }

    /// Get security score (0-100)
    pub fn security_score(&self) -> u8 {
        let mut score = 0u8;

        if self.supports_uv {
            score += 30;
        }
        if self.supports_liveness {
            score += 30;
        }
        score += match self.certification_level {
            CertificationLevel::Level3Plus => 40,
            CertificationLevel::Level3 => 30,
            CertificationLevel::Level2 => 20,
            CertificationLevel::Level1 => 10,
            CertificationLevel::None => 0,
        };

        score
    }
}

/// Certification level (FIDO)
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum CertificationLevel {
    None,
    Level1,
    Level2,
    Level3,
    Level3Plus,
}

/// Biometric verification
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BiometricVerification {
    /// Verification ID
    pub verification_id: String,

    /// User ID
    pub user_id: UserId,

    /// Tenant ID
    pub tenant_id: TenantId,

    /// Authenticator AAGUID
    pub aaguid: String,

    /// Biometric modality
    pub modality: Option<BiometricModality>,

    /// User verification performed
    pub user_verification: bool,

    /// Liveness detection performed
    pub liveness_detection: bool,

    /// Quality score (0-100)
    pub quality_score: Option<u8>,

    /// Verified at
    pub verified_at: DateTime<Utc>,

    /// Expires at
    pub expires_at: DateTime<Utc>,

    /// IP address
    pub ip_address: Option<String>,

    /// Risk score (0-100)
    pub risk_score: u8,

    /// Step-up completed
    pub step_up_completed: bool,
}

impl BiometricVerification {
    /// Create new verification
    pub fn new(
        user_id: UserId,
        tenant_id: TenantId,
        aaguid: String,
        modality: Option<BiometricModality>,
        user_verification: bool,
        liveness_detection: bool,
        validity_seconds: i64,
    ) -> Self {
        let now = Utc::now();
        Self {
            verification_id: Uuid::new_v4().to_string(),
            user_id,
            tenant_id,
            aaguid,
            modality,
            user_verification,
            liveness_detection,
            quality_score: None,
            verified_at: now,
            expires_at: now + Duration::seconds(validity_seconds),
            ip_address: None,
            risk_score: 0,
            step_up_completed: false,
        }
    }

    /// Check if verification is expired
    pub fn is_expired(&self) -> bool {
        Utc::now() > self.expires_at
    }

    /// Set quality score
    pub fn with_quality(mut self, score: u8) -> Self {
        self.quality_score = Some(score);
        self
    }

    /// Set risk score
    pub fn with_risk_score(mut self, score: u8) -> Self {
        self.risk_score = score;
        self
    }

    /// Set IP address
    pub fn with_ip(mut self, ip: String) -> Self {
        self.ip_address = Some(ip);
        self
    }

    /// Mark step-up completed
    pub fn mark_step_up_completed(mut self) -> Self {
        self.step_up_completed = true;
        self
    }
}

/// Biometric policy
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BiometricPolicy {
    /// Tenant ID
    pub tenant_id: TenantId,

    /// Require user verification
    pub require_uv: bool,

    /// Require liveness detection
    pub require_liveness: bool,

    /// Minimum quality score
    pub min_quality_score: u8,

    /// Minimum authenticator certification
    pub min_certification_level: CertificationLevel,

    /// Verification validity (seconds)
    pub verification_validity_seconds: i64,

    /// Require step-up for sensitive operations
    pub require_step_up_sensitive: bool,

    /// Risk threshold for re-verification
    pub risk_threshold_reverify: u8,

    /// Allowed biometric modalities
    pub allowed_modalities: Option<Vec<BiometricModality>>,
}

impl Default for BiometricPolicy {
    fn default() -> Self {
        Self {
            tenant_id: TenantId::new("default"),
            require_uv: true,        // CRITICAL: Always require UV
            require_liveness: false, // Optional by default
            min_quality_score: 50,
            min_certification_level: CertificationLevel::Level1,
            verification_validity_seconds: 300, // 5 minutes
            require_step_up_sensitive: true,
            risk_threshold_reverify: 70,
            allowed_modalities: None, // All allowed
        }
    }
}

impl BiometricPolicy {
    /// Create strict policy
    pub fn strict() -> Self {
        Self {
            tenant_id: TenantId::new("strict"),
            require_uv: true,
            require_liveness: true, // REQUIRED
            min_quality_score: 70,
            min_certification_level: CertificationLevel::Level2,
            verification_validity_seconds: 60, // 1 minute
            require_step_up_sensitive: true,
            risk_threshold_reverify: 50, // Lower threshold
            allowed_modalities: Some(vec![
                BiometricModality::Fingerprint,
                BiometricModality::FaceRecognition,
                BiometricModality::IrisScanning,
            ]),
        }
    }

    /// Create lenient policy
    pub fn lenient() -> Self {
        Self {
            tenant_id: TenantId::new("lenient"),
            require_uv: true, // Still required
            require_liveness: false,
            min_quality_score: 30,
            min_certification_level: CertificationLevel::None,
            verification_validity_seconds: 900, // 15 minutes
            require_step_up_sensitive: false,
            risk_threshold_reverify: 90, // Higher threshold
            allowed_modalities: None,
        }
    }

    /// Check compliance
    pub fn check_compliance(
        &self,
        verification: &BiometricVerification,
        capabilities: &AuthenticatorCapabilities,
    ) -> Result<(), BiometricError> {
        // Check UV requirement
        if self.require_uv && !verification.user_verification {
            return Err(BiometricError::UserVerificationNotPerformed);
        }

        // Check liveness requirement
        if self.require_liveness && !verification.liveness_detection {
            return Err(BiometricError::LivenessNotSupported);
        }

        // Check quality score
        if let Some(quality) = verification.quality_score {
            if quality < self.min_quality_score {
                return Err(BiometricError::QualityTooLow {
                    quality,
                    minimum: self.min_quality_score,
                });
            }
        }

        // Check certification level
        if capabilities.certification_level < self.min_certification_level {
            return Err(BiometricError::AuthenticatorNotVerified);
        }

        // Check expiration
        if verification.is_expired() {
            return Err(BiometricError::VerificationExpired(verification.expires_at));
        }

        // Check risk score
        if verification.risk_score > self.risk_threshold_reverify {
            return Err(BiometricError::ReverificationRequired);
        }

        // Check allowed modalities
        if let Some(ref allowed) = self.allowed_modalities {
            if let Some(modality) = verification.modality {
                if !allowed.contains(&modality) {
                    return Err(BiometricError::AuthenticatorNotVerified);
                }
            }
        }

        Ok(())
    }
}

/// Operation sensitivity level
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum OperationSensitivity {
    Low,
    Medium,
    High,
    Critical,
}

impl OperationSensitivity {
    /// Check if step-up required
    pub fn requires_step_up(&self) -> bool {
        matches!(self, Self::High | Self::Critical)
    }

    /// Get required verification freshness (seconds)
    pub fn required_freshness(&self) -> i64 {
        match self {
            Self::Low => 900,     // 15 minutes
            Self::Medium => 300,  // 5 minutes
            Self::High => 60,     // 1 minute
            Self::Critical => 30, // 30 seconds
        }
    }
}

/// Storage trait for biometric security
#[async_trait]
pub trait BiometricStorage: Send + Sync {
    /// Store authenticator capabilities
    async fn store_capabilities(
        &self,
        capabilities: &AuthenticatorCapabilities,
    ) -> Result<(), BiometricError>;

    /// Get authenticator capabilities
    async fn get_capabilities(
        &self,
        aaguid: &str,
    ) -> Result<Option<AuthenticatorCapabilities>, BiometricError>;

    /// Store verification
    async fn store_verification(
        &self,
        verification: &BiometricVerification,
    ) -> Result<(), BiometricError>;

    /// Get latest verification for user
    async fn get_latest_verification(
        &self,
        user_id: &UserId,
    ) -> Result<Option<BiometricVerification>, BiometricError>;

    /// Store policy
    async fn store_policy(&self, policy: &BiometricPolicy) -> Result<(), BiometricError>;

    /// Get policy
    async fn get_policy(&self, tenant_id: &TenantId) -> Result<BiometricPolicy, BiometricError>;
}

/// In-memory storage for testing
pub struct InMemoryBiometricStorage {
    capabilities: tokio::sync::RwLock<HashMap<String, AuthenticatorCapabilities>>,
    verifications: tokio::sync::RwLock<HashMap<UserId, BiometricVerification>>,
    policies: tokio::sync::RwLock<HashMap<TenantId, BiometricPolicy>>,
}

impl InMemoryBiometricStorage {
    pub fn new() -> Self {
        Self {
            capabilities: tokio::sync::RwLock::new(HashMap::new()),
            verifications: tokio::sync::RwLock::new(HashMap::new()),
            policies: tokio::sync::RwLock::new(HashMap::new()),
        }
    }
}

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

#[async_trait]
impl BiometricStorage for InMemoryBiometricStorage {
    async fn store_capabilities(
        &self,
        capabilities: &AuthenticatorCapabilities,
    ) -> Result<(), BiometricError> {
        let mut caps = self.capabilities.write().await;
        caps.insert(capabilities.aaguid.clone(), capabilities.clone());
        Ok(())
    }

    async fn get_capabilities(
        &self,
        aaguid: &str,
    ) -> Result<Option<AuthenticatorCapabilities>, BiometricError> {
        let caps = self.capabilities.read().await;
        Ok(caps.get(aaguid).cloned())
    }

    async fn store_verification(
        &self,
        verification: &BiometricVerification,
    ) -> Result<(), BiometricError> {
        let mut verifications = self.verifications.write().await;
        verifications.insert(verification.user_id.clone(), verification.clone());
        Ok(())
    }

    async fn get_latest_verification(
        &self,
        user_id: &UserId,
    ) -> Result<Option<BiometricVerification>, BiometricError> {
        let verifications = self.verifications.read().await;
        Ok(verifications.get(user_id).cloned())
    }

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

    async fn get_policy(&self, tenant_id: &TenantId) -> Result<BiometricPolicy, BiometricError> {
        let policies = self.policies.read().await;
        Ok(policies
            .get(tenant_id)
            .cloned()
            .unwrap_or_else(BiometricPolicy::default))
    }
}

/// Biometric security manager
pub struct BiometricSecurityManager<S: BiometricStorage> {
    storage: S,
}

impl<S: BiometricStorage> BiometricSecurityManager<S> {
    /// Create new manager
    pub fn new(storage: S) -> Self {
        Self { storage }
    }

    /// Register authenticator capabilities
    pub async fn register_authenticator(
        &self,
        capabilities: AuthenticatorCapabilities,
    ) -> Result<AuthenticatorCapabilities, BiometricError> {
        self.storage.store_capabilities(&capabilities).await?;
        info!(
            "Authenticator registered: {} (secure: {})",
            capabilities.aaguid,
            capabilities.is_secure()
        );
        Ok(capabilities)
    }

    /// Record biometric verification
    pub async fn record_verification(
        &self,
        verification: BiometricVerification,
    ) -> Result<BiometricVerification, BiometricError> {
        // Get policy
        let policy = self.storage.get_policy(&verification.tenant_id).await?;

        // Get authenticator capabilities
        let capabilities = self
            .storage
            .get_capabilities(&verification.aaguid)
            .await?
            .unwrap_or_else(|| AuthenticatorCapabilities::new(verification.aaguid.clone()));

        // Check compliance
        policy.check_compliance(&verification, &capabilities)?;

        self.storage.store_verification(&verification).await?;

        info!(
            "Biometric verification recorded for user {} (UV: {}, liveness: {})",
            verification.user_id, verification.user_verification, verification.liveness_detection
        );
        Ok(verification)
    }

    /// Verify biometric for operation
    pub async fn verify_for_operation(
        &self,
        user_id: &UserId,
        tenant_id: &TenantId,
        sensitivity: OperationSensitivity,
    ) -> Result<(), BiometricError> {
        // Get policy
        let policy = self.storage.get_policy(tenant_id).await?;

        // Get latest verification
        let verification = self
            .storage
            .get_latest_verification(user_id)
            .await?
            .ok_or(BiometricError::UserVerificationNotPerformed)?;

        // Get authenticator capabilities
        let capabilities = self
            .storage
            .get_capabilities(&verification.aaguid)
            .await?
            .unwrap_or_else(|| AuthenticatorCapabilities::new(verification.aaguid.clone()));

        // Check basic compliance
        policy.check_compliance(&verification, &capabilities)?;

        // Check freshness for operation sensitivity
        let age_seconds = (Utc::now() - verification.verified_at).num_seconds();
        if age_seconds > sensitivity.required_freshness() {
            return Err(BiometricError::ReverificationRequired);
        }

        // Check step-up requirement
        if sensitivity.requires_step_up()
            && policy.require_step_up_sensitive
            && !verification.step_up_completed
        {
            return Err(BiometricError::StepUpRequired);
        }

        info!(
            "Biometric verification passed for user {} (sensitivity: {:?})",
            user_id, sensitivity
        );
        Ok(())
    }

    /// Calculate risk score
    pub fn calculate_risk_score(
        &self,
        verification: &BiometricVerification,
        capabilities: &AuthenticatorCapabilities,
    ) -> u8 {
        let mut risk = 0u8;

        // No UV = +40 risk
        if !verification.user_verification {
            risk = risk.saturating_add(40);
        }

        // No liveness = +30 risk
        if !verification.liveness_detection {
            if let Some(modality) = verification.modality {
                if modality.requires_liveness() {
                    risk = risk.saturating_add(30);
                }
            }
        }

        // Low quality = +20 risk
        if let Some(quality) = verification.quality_score {
            if quality < 50 {
                risk = risk.saturating_add(20);
            }
        }

        // Low certification = +10 risk
        if capabilities.certification_level < CertificationLevel::Level1 {
            risk = risk.saturating_add(10);
        }

        risk
    }
}

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

    #[test]
    fn test_authenticator_security_score() {
        let mut caps = AuthenticatorCapabilities::new("test-aaguid".to_string());
        caps.supports_uv = true;
        caps.supports_liveness = true;
        caps.certification_level = CertificationLevel::Level3;

        assert_eq!(caps.security_score(), 90); // 30 + 30 + 30
        assert!(caps.is_secure());
    }

    #[tokio::test]
    async fn test_verification_recording() {
        let storage = InMemoryBiometricStorage::new();
        let manager = BiometricSecurityManager::new(storage);

        // Register authenticator
        let mut caps = AuthenticatorCapabilities::new("secure-auth".to_string());
        caps.supports_uv = true;
        caps.supports_liveness = true;
        caps.certification_level = CertificationLevel::Level2;
        manager.register_authenticator(caps).await.unwrap();

        // Record verification
        let verification = BiometricVerification::new(
            UserId::new("test_user"),
            TenantId::new("test_tenant"),
            "secure-auth".to_string(),
            Some(BiometricModality::Fingerprint),
            true,
            true,
            300,
        );

        let recorded = manager.record_verification(verification).await.unwrap();
        assert!(recorded.user_verification);
        assert!(recorded.liveness_detection);
    }

    #[tokio::test]
    async fn test_policy_compliance() {
        let policy = BiometricPolicy::strict();
        let mut caps = AuthenticatorCapabilities::new("test".to_string());
        caps.supports_uv = true;
        caps.supports_liveness = true;
        caps.certification_level = CertificationLevel::Level2;

        let verification = BiometricVerification::new(
            UserId::new("test_user"),
            TenantId::new("test_tenant"),
            "test".to_string(),
            Some(BiometricModality::Fingerprint),
            true,
            true,
            300,
        );

        // Should pass
        assert!(policy.check_compliance(&verification, &caps).is_ok());

        // Fail without UV
        let mut bad_verification = verification.clone();
        bad_verification.user_verification = false;
        assert!(policy.check_compliance(&bad_verification, &caps).is_err());
    }

    #[test]
    fn test_risk_scoring() {
        let storage = InMemoryBiometricStorage::new();
        let manager = BiometricSecurityManager::new(storage);

        let verification = BiometricVerification::new(
            UserId::new("test_user"),
            TenantId::new("test_tenant"),
            "test".to_string(),
            Some(BiometricModality::FaceRecognition),
            false, // No UV = +40
            false, // No liveness = +30
            300,
        )
        .with_quality(30); // Low quality = +20

        let caps = AuthenticatorCapabilities::new("test".to_string());
        // No certification = +10

        let risk = manager.calculate_risk_score(&verification, &caps);
        assert_eq!(risk, 100); // 40 + 30 + 20 + 10
    }
}