uvb-device-binding 0.2.1

Device-to-session binding and trust anchoring 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
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
//! # Device Binding and Trust Management
//!
//! Enterprise-grade device binding to address:
//! - **Risk #21**: Single-factor fallback on trusted devices (device trust misuse)
//!
//! ## Features
//!
//! - **Device Fingerprinting**: Browser/OS/hardware identification
//! - **Device Registration**: MFA-protected device enrollment
//! - **Trust Expiration**: Automatic trust expiry (30 days default)
//! - **Periodic Re-auth**: Require MFA even on trusted devices
//! - **Device Revocation**: User and automatic revocation
//! - **Risk-Based Trust**: Location, IP, behavior analysis
//! - **Sensitive Operation Blocks**: Never skip MFA for critical actions
//! - **Device History**: Track all device registrations and usage

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

use uvb_core::{TenantId, UserId};

/// Errors that can occur during device binding operations
#[derive(Debug, Error)]
pub enum DeviceBindingError {
    #[error("Storage error: {0}")]
    Storage(String),

    #[error("Device not found: {0}")]
    DeviceNotFound(String),

    #[error("Device trust expired (expired at: {0})")]
    TrustExpired(DateTime<Utc>),

    #[error("Device requires re-authentication (last auth: {0})")]
    ReauthRequired(DateTime<Utc>),

    #[error("Device is revoked (reason: {0})")]
    DeviceRevoked(String),

    #[error("MFA required for device registration")]
    MfaRequired,

    #[error("Operation {0} requires MFA even on trusted devices")]
    SensitiveOperationBlocked(String),

    #[error("Risk score too high for trusted device: {score} (threshold: {threshold})")]
    RiskTooHigh { score: u8, threshold: u8 },

    #[error("Device limit reached: {current} (max: {max})")]
    DeviceLimitReached { current: usize, max: usize },

    #[error("Invalid device fingerprint")]
    InvalidFingerprint,

    #[error("Device trust not established")]
    NotTrusted,
}

/// Device type classification
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum DeviceType {
    Desktop,
    Mobile,
    Tablet,
    Unknown,
}

/// Device platform/OS
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[allow(non_camel_case_types)]
pub enum DevicePlatform {
    Windows,
    MacOS,
    Linux,
    iOS,
    Android,
    ChromeOS,
    Unknown(String),
}

impl DevicePlatform {
    /// Parse platform from user agent string
    pub fn from_user_agent(user_agent: &str) -> Self {
        let ua_lower = user_agent.to_lowercase();

        if ua_lower.contains("windows") {
            Self::Windows
        } else if ua_lower.contains("mac os") || ua_lower.contains("macos") {
            Self::MacOS
        } else if ua_lower.contains("linux") && !ua_lower.contains("android") {
            Self::Linux
        } else if ua_lower.contains("iphone") || ua_lower.contains("ipad") {
            Self::iOS
        } else if ua_lower.contains("android") {
            Self::Android
        } else if ua_lower.contains("cros") {
            Self::ChromeOS
        } else {
            Self::Unknown(user_agent.to_string())
        }
    }
}

/// Browser identification
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum BrowserType {
    Chrome,
    Firefox,
    Safari,
    Edge,
    Opera,
    Brave,
    Unknown(String),
}

impl BrowserType {
    /// Parse browser from user agent string
    pub fn from_user_agent(user_agent: &str) -> Self {
        let ua_lower = user_agent.to_lowercase();

        if ua_lower.contains("edg/") || ua_lower.contains("edge/") {
            Self::Edge
        } else if ua_lower.contains("brave") {
            Self::Brave
        } else if ua_lower.contains("opr/") || ua_lower.contains("opera") {
            Self::Opera
        } else if ua_lower.contains("chrome") || ua_lower.contains("crios") {
            Self::Chrome
        } else if ua_lower.contains("firefox") || ua_lower.contains("fxios") {
            Self::Firefox
        } else if ua_lower.contains("safari") {
            Self::Safari
        } else {
            Self::Unknown(user_agent.to_string())
        }
    }
}

/// Device fingerprint for identification
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct DeviceFingerprint {
    /// User agent string
    pub user_agent: String,

    /// Device platform/OS
    pub platform: DevicePlatform,

    /// Browser type
    pub browser: BrowserType,

    /// Screen resolution (e.g., "1920x1080")
    pub screen_resolution: Option<String>,

    /// Timezone offset in minutes
    pub timezone_offset: Option<i32>,

    /// Browser language
    pub language: Option<String>,

    /// Hardware concurrency (CPU cores)
    pub hardware_concurrency: Option<u32>,

    /// WebGL vendor
    pub webgl_vendor: Option<String>,

    /// WebGL renderer
    pub webgl_renderer: Option<String>,

    /// Canvas fingerprint hash
    pub canvas_hash: Option<String>,

    /// Installed fonts hash
    pub fonts_hash: Option<String>,

    /// Browser plugins
    pub plugins: Vec<String>,

    /// Touch support
    pub touch_support: bool,

    /// Color depth
    pub color_depth: Option<u8>,
}

impl DeviceFingerprint {
    /// Generate a unique device ID from fingerprint
    pub fn generate_device_id(&self) -> String {
        let mut hasher = Sha256::new();

        // Combine stable attributes
        hasher.update(self.user_agent.as_bytes());
        if let Some(ref res) = self.screen_resolution {
            hasher.update(res.as_bytes());
        }
        if let Some(ref webgl_vendor) = self.webgl_vendor {
            hasher.update(webgl_vendor.as_bytes());
        }
        if let Some(ref webgl_renderer) = self.webgl_renderer {
            hasher.update(webgl_renderer.as_bytes());
        }
        if let Some(ref canvas) = self.canvas_hash {
            hasher.update(canvas.as_bytes());
        }
        if let Some(ref fonts) = self.fonts_hash {
            hasher.update(fonts.as_bytes());
        }

        hex::encode(hasher.finalize())
    }

    /// Calculate similarity score with another fingerprint (0.0 to 1.0)
    pub fn similarity(&self, other: &DeviceFingerprint) -> f64 {
        let mut matches = 0;
        let mut total = 0;

        // User agent
        total += 1;
        if self.user_agent == other.user_agent {
            matches += 1;
        }

        // Screen resolution (important for desktop devices)
        if self.screen_resolution.is_some() && other.screen_resolution.is_some() {
            total += 1;
            if self.screen_resolution == other.screen_resolution {
                matches += 1;
            }
        }

        // WebGL (stable attributes)
        if self.webgl_vendor.is_some() && other.webgl_vendor.is_some() {
            total += 1;
            if self.webgl_vendor == other.webgl_vendor {
                matches += 1;
            }
        }

        if self.webgl_renderer.is_some() && other.webgl_renderer.is_some() {
            total += 1;
            if self.webgl_renderer == other.webgl_renderer {
                matches += 1;
            }
        }

        // Canvas hash (unique per device)
        if self.canvas_hash.is_some() && other.canvas_hash.is_some() {
            total += 2; // Weight canvas more heavily
            if self.canvas_hash == other.canvas_hash {
                matches += 2;
            }
        }

        // Fonts hash
        if self.fonts_hash.is_some() && other.fonts_hash.is_some() {
            total += 1;
            if self.fonts_hash == other.fonts_hash {
                matches += 1;
            }
        }

        // Hardware concurrency
        if self.hardware_concurrency.is_some() && other.hardware_concurrency.is_some() {
            total += 1;
            if self.hardware_concurrency == other.hardware_concurrency {
                matches += 1;
            }
        }

        if total == 0 {
            return 0.0;
        }

        matches as f64 / total as f64
    }
}

/// Trusted device information
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TrustedDevice {
    /// Unique device ID
    pub device_id: String,

    /// User ID this device belongs to
    pub user_id: UserId,

    /// Tenant ID
    pub tenant_id: TenantId,

    /// Device fingerprint
    pub fingerprint: DeviceFingerprint,

    /// Device type
    pub device_type: DeviceType,

    /// User-provided device name (optional)
    pub device_name: Option<String>,

    /// When device was registered
    pub registered_at: DateTime<Utc>,

    /// When trust expires
    pub expires_at: DateTime<Utc>,

    /// Last authentication time
    pub last_auth_at: DateTime<Utc>,

    /// Last seen IP address
    pub last_ip: Option<String>,

    /// Last seen location (city, country)
    pub last_location: Option<String>,

    /// Is device currently trusted
    pub is_trusted: bool,

    /// Revocation reason (if revoked)
    pub revoked_reason: Option<String>,

    /// Revoked timestamp
    pub revoked_at: Option<DateTime<Utc>>,

    /// Number of times device was used
    pub usage_count: u64,

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

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

    /// Check if device requires re-authentication
    pub fn requires_reauth(&self, reauth_interval: Duration) -> bool {
        let next_auth_time = self.last_auth_at + reauth_interval;
        Utc::now() > next_auth_time
    }

    /// Check if device is revoked
    pub fn is_revoked(&self) -> bool {
        self.revoked_reason.is_some()
    }

    /// Check if device is valid for use
    pub fn is_valid(&self) -> Result<(), DeviceBindingError> {
        if self.is_revoked() {
            return Err(DeviceBindingError::DeviceRevoked(
                self.revoked_reason.clone().unwrap_or_default(),
            ));
        }

        if self.is_expired() {
            return Err(DeviceBindingError::TrustExpired(self.expires_at));
        }

        if !self.is_trusted {
            return Err(DeviceBindingError::NotTrusted);
        }

        Ok(())
    }

    /// Get device age in days
    pub fn age_days(&self) -> i64 {
        (Utc::now() - self.registered_at).num_days()
    }
}

/// Device binding configuration
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeviceBindingConfig {
    /// Enable device binding
    pub enabled: bool,

    /// Trust expiration (days)
    pub trust_expiration_days: i64,

    /// Require re-authentication interval (days)
    pub reauth_interval_days: i64,

    /// Maximum devices per user
    pub max_devices_per_user: usize,

    /// Risk score threshold for trust (0-100)
    pub risk_threshold: u8,

    /// Require MFA for device registration
    pub require_mfa_for_registration: bool,

    /// Automatically revoke devices on suspicious activity
    pub auto_revoke_on_suspicion: bool,

    /// Operations that always require MFA (even on trusted devices)
    pub sensitive_operations: Vec<String>,

    /// Minimum fingerprint similarity for device recognition (0.0-1.0)
    pub min_fingerprint_similarity: f64,

    /// Enable location-based risk scoring
    pub enable_location_risk: bool,

    /// Enable IP-based risk scoring
    pub enable_ip_risk: bool,
}

impl DeviceBindingConfig {
    /// Create default configuration
    pub fn new_default() -> Self {
        Self {
            enabled: true,
            trust_expiration_days: 30,
            reauth_interval_days: 7,
            max_devices_per_user: 10,
            risk_threshold: 70,
            require_mfa_for_registration: true,
            auto_revoke_on_suspicion: true,
            sensitive_operations: vec![
                "change_password".to_string(),
                "change_email".to_string(),
                "change_phone".to_string(),
                "add_payment_method".to_string(),
                "delete_account".to_string(),
                "change_mfa_settings".to_string(),
                "transfer_funds".to_string(),
            ],
            min_fingerprint_similarity: 0.8,
            enable_location_risk: true,
            enable_ip_risk: true,
        }
    }

    /// Create strict configuration
    pub fn strict() -> Self {
        let mut config = Self::new_default();
        config.trust_expiration_days = 14; // 2 weeks
        config.reauth_interval_days = 3; // Every 3 days
        config.max_devices_per_user = 5;
        config.risk_threshold = 50; // Stricter
        config.min_fingerprint_similarity = 0.9; // More strict matching
        config
    }

    /// Create lenient configuration (development)
    pub fn lenient() -> Self {
        let mut config = Self::new_default();
        config.trust_expiration_days = 365; // 1 year
        config.reauth_interval_days = 30;
        config.max_devices_per_user = 50;
        config.risk_threshold = 90; // Very lenient
        config.require_mfa_for_registration = false;
        config.auto_revoke_on_suspicion = false;
        config.sensitive_operations = vec![]; // Allow everything
        config.min_fingerprint_similarity = 0.5;
        config.enable_location_risk = false;
        config.enable_ip_risk = false;
        config
    }

    /// Check if operation is sensitive
    pub fn is_sensitive_operation(&self, operation: &str) -> bool {
        self.sensitive_operations.iter().any(|op| op == operation)
    }
}

/// Device registration request
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeviceRegistrationRequest {
    pub user_id: UserId,
    pub tenant_id: TenantId,
    pub fingerprint: DeviceFingerprint,
    pub device_type: DeviceType,
    pub device_name: Option<String>,
    pub ip_address: Option<String>,
    pub location: Option<String>,
    pub mfa_verified: bool,
}

/// Device trust validation result
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeviceTrustResult {
    pub device_id: String,
    pub is_trusted: bool,
    pub requires_mfa: bool,
    pub reason: String,
    pub risk_score: u8,
    pub expires_at: Option<DateTime<Utc>>,
}

/// Storage trait for device binding
#[async_trait]
pub trait DeviceBindingStorage: Send + Sync {
    /// Save a trusted device
    async fn save_device(&self, device: &TrustedDevice) -> Result<(), DeviceBindingError>;

    /// Get device by ID
    async fn get_device(&self, device_id: &str) -> Result<TrustedDevice, DeviceBindingError>;

    /// Get all devices for a user
    async fn get_user_devices(
        &self,
        user_id: &UserId,
    ) -> Result<Vec<TrustedDevice>, DeviceBindingError>;

    /// Update device last authentication time
    async fn update_last_auth(
        &self,
        device_id: &str,
        timestamp: DateTime<Utc>,
    ) -> Result<(), DeviceBindingError>;

    /// Revoke device
    async fn revoke_device(
        &self,
        device_id: &str,
        reason: String,
        revoked_at: DateTime<Utc>,
    ) -> Result<(), DeviceBindingError>;

    /// Delete device
    async fn delete_device(&self, device_id: &str) -> Result<(), DeviceBindingError>;

    /// Find devices by fingerprint similarity
    async fn find_similar_devices(
        &self,
        user_id: &UserId,
        fingerprint: &DeviceFingerprint,
        min_similarity: f64,
    ) -> Result<Vec<TrustedDevice>, DeviceBindingError>;
}

/// In-memory storage for testing
pub struct InMemoryDeviceStorage {
    devices: tokio::sync::RwLock<HashMap<String, TrustedDevice>>,
}

impl InMemoryDeviceStorage {
    pub fn new() -> Self {
        Self {
            devices: tokio::sync::RwLock::new(HashMap::new()),
        }
    }
}

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

#[async_trait]
impl DeviceBindingStorage for InMemoryDeviceStorage {
    async fn save_device(&self, device: &TrustedDevice) -> Result<(), DeviceBindingError> {
        let mut devices = self.devices.write().await;
        devices.insert(device.device_id.clone(), device.clone());
        Ok(())
    }

    async fn get_device(&self, device_id: &str) -> Result<TrustedDevice, DeviceBindingError> {
        let devices = self.devices.read().await;
        devices
            .get(device_id)
            .cloned()
            .ok_or_else(|| DeviceBindingError::DeviceNotFound(device_id.to_string()))
    }

    async fn get_user_devices(
        &self,
        user_id: &UserId,
    ) -> Result<Vec<TrustedDevice>, DeviceBindingError> {
        let devices = self.devices.read().await;
        Ok(devices
            .values()
            .filter(|d| d.user_id == *user_id)
            .cloned()
            .collect())
    }

    async fn update_last_auth(
        &self,
        device_id: &str,
        timestamp: DateTime<Utc>,
    ) -> Result<(), DeviceBindingError> {
        let mut devices = self.devices.write().await;
        if let Some(device) = devices.get_mut(device_id) {
            device.last_auth_at = timestamp;
            device.usage_count += 1;
            Ok(())
        } else {
            Err(DeviceBindingError::DeviceNotFound(device_id.to_string()))
        }
    }

    async fn revoke_device(
        &self,
        device_id: &str,
        reason: String,
        revoked_at: DateTime<Utc>,
    ) -> Result<(), DeviceBindingError> {
        let mut devices = self.devices.write().await;
        if let Some(device) = devices.get_mut(device_id) {
            device.is_trusted = false;
            device.revoked_reason = Some(reason);
            device.revoked_at = Some(revoked_at);
            Ok(())
        } else {
            Err(DeviceBindingError::DeviceNotFound(device_id.to_string()))
        }
    }

    async fn delete_device(&self, device_id: &str) -> Result<(), DeviceBindingError> {
        let mut devices = self.devices.write().await;
        devices
            .remove(device_id)
            .ok_or_else(|| DeviceBindingError::DeviceNotFound(device_id.to_string()))?;
        Ok(())
    }

    async fn find_similar_devices(
        &self,
        user_id: &UserId,
        fingerprint: &DeviceFingerprint,
        min_similarity: f64,
    ) -> Result<Vec<TrustedDevice>, DeviceBindingError> {
        let devices = self.devices.read().await;
        Ok(devices
            .values()
            .filter(|d| {
                d.user_id == *user_id && fingerprint.similarity(&d.fingerprint) >= min_similarity
            })
            .cloned()
            .collect())
    }
}

/// Device binding manager
pub struct DeviceBindingManager<S: DeviceBindingStorage> {
    storage: S,
    config: DeviceBindingConfig,
}

impl<S: DeviceBindingStorage> DeviceBindingManager<S> {
    /// Create a new manager with configuration
    pub fn new(storage: S, config: DeviceBindingConfig) -> Self {
        Self { storage, config }
    }

    /// Register a new device
    pub async fn register_device(
        &self,
        request: DeviceRegistrationRequest,
    ) -> Result<TrustedDevice, DeviceBindingError> {
        if !self.config.enabled {
            return Err(DeviceBindingError::Storage(
                "Device binding disabled".to_string(),
            ));
        }

        // Verify MFA if required
        if self.config.require_mfa_for_registration && !request.mfa_verified {
            return Err(DeviceBindingError::MfaRequired);
        }

        // Check device limit
        let existing_devices = self.storage.get_user_devices(&request.user_id).await?;
        if existing_devices.len() >= self.config.max_devices_per_user {
            return Err(DeviceBindingError::DeviceLimitReached {
                current: existing_devices.len(),
                max: self.config.max_devices_per_user,
            });
        }

        // Generate device ID
        let device_id = request.fingerprint.generate_device_id();

        // Calculate expiration
        let expires_at = Utc::now() + Duration::days(self.config.trust_expiration_days);

        let device = TrustedDevice {
            device_id: device_id.clone(),
            user_id: request.user_id,
            tenant_id: request.tenant_id,
            fingerprint: request.fingerprint,
            device_type: request.device_type,
            device_name: request.device_name,
            registered_at: Utc::now(),
            expires_at,
            last_auth_at: Utc::now(),
            last_ip: request.ip_address,
            last_location: request.location,
            is_trusted: true,
            revoked_reason: None,
            revoked_at: None,
            usage_count: 0,
            risk_score: 0, // Initial risk is 0
        };

        self.storage.save_device(&device).await?;

        info!(
            "Registered new device {} for user {:?}",
            device_id, device.user_id
        );

        Ok(device)
    }

    /// Validate device trust
    pub async fn validate_device_trust(
        &self,
        device_id: &str,
        operation: &str,
    ) -> Result<DeviceTrustResult, DeviceBindingError> {
        if !self.config.enabled {
            return Ok(DeviceTrustResult {
                device_id: device_id.to_string(),
                is_trusted: false,
                requires_mfa: true,
                reason: "Device binding disabled".to_string(),
                risk_score: 0,
                expires_at: None,
            });
        }

        // Sensitive operations always require MFA
        if self.config.is_sensitive_operation(operation) {
            return Ok(DeviceTrustResult {
                device_id: device_id.to_string(),
                is_trusted: false,
                requires_mfa: true,
                reason: format!("Sensitive operation '{}' requires MFA", operation),
                risk_score: 100,
                expires_at: None,
            });
        }

        let device = self.storage.get_device(device_id).await?;

        // Check if device is valid
        if let Err(e) = device.is_valid() {
            return Ok(DeviceTrustResult {
                device_id: device_id.to_string(),
                is_trusted: false,
                requires_mfa: true,
                reason: e.to_string(),
                risk_score: 100,
                expires_at: Some(device.expires_at),
            });
        }

        // Check if re-authentication is required
        let reauth_interval = Duration::days(self.config.reauth_interval_days);
        if device.requires_reauth(reauth_interval) {
            return Ok(DeviceTrustResult {
                device_id: device_id.to_string(),
                is_trusted: true, // Device is trusted, but needs reauth
                requires_mfa: true,
                reason: "Periodic re-authentication required".to_string(),
                risk_score: device.risk_score,
                expires_at: Some(device.expires_at),
            });
        }

        // Check risk score
        if device.risk_score > self.config.risk_threshold {
            warn!(
                "Device {} risk score {} exceeds threshold {}",
                device_id, device.risk_score, self.config.risk_threshold
            );

            if self.config.auto_revoke_on_suspicion {
                self.storage
                    .revoke_device(
                        device_id,
                        format!(
                            "Automatic revocation due to high risk score: {}",
                            device.risk_score
                        ),
                        Utc::now(),
                    )
                    .await?;

                return Ok(DeviceTrustResult {
                    device_id: device_id.to_string(),
                    is_trusted: false,
                    requires_mfa: true,
                    reason: "Device revoked due to high risk".to_string(),
                    risk_score: device.risk_score,
                    expires_at: None,
                });
            }

            return Ok(DeviceTrustResult {
                device_id: device_id.to_string(),
                is_trusted: false,
                requires_mfa: true,
                reason: format!(
                    "Risk score {} exceeds threshold {}",
                    device.risk_score, self.config.risk_threshold
                ),
                risk_score: device.risk_score,
                expires_at: Some(device.expires_at),
            });
        }

        // Device is trusted
        Ok(DeviceTrustResult {
            device_id: device_id.to_string(),
            is_trusted: true,
            requires_mfa: false,
            reason: "Device is trusted".to_string(),
            risk_score: device.risk_score,
            expires_at: Some(device.expires_at),
        })
    }

    /// Update device authentication time
    pub async fn record_authentication(&self, device_id: &str) -> Result<(), DeviceBindingError> {
        self.storage.update_last_auth(device_id, Utc::now()).await?;
        debug!("Recorded authentication for device {}", device_id);
        Ok(())
    }

    /// Revoke a device
    pub async fn revoke_device(
        &self,
        device_id: &str,
        reason: String,
    ) -> Result<(), DeviceBindingError> {
        self.storage
            .revoke_device(device_id, reason.clone(), Utc::now())
            .await?;
        info!("Revoked device {}: {}", device_id, reason);
        Ok(())
    }

    /// Delete a device
    pub async fn delete_device(&self, device_id: &str) -> Result<(), DeviceBindingError> {
        self.storage.delete_device(device_id).await?;
        info!("Deleted device {}", device_id);
        Ok(())
    }

    /// Get all devices for a user
    pub async fn get_user_devices(
        &self,
        user_id: &UserId,
    ) -> Result<Vec<TrustedDevice>, DeviceBindingError> {
        self.storage.get_user_devices(user_id).await
    }

    /// Find existing device by fingerprint
    pub async fn find_device_by_fingerprint(
        &self,
        user_id: &UserId,
        fingerprint: &DeviceFingerprint,
    ) -> Result<Option<TrustedDevice>, DeviceBindingError> {
        let similar = self
            .storage
            .find_similar_devices(user_id, fingerprint, self.config.min_fingerprint_similarity)
            .await?;

        Ok(similar.into_iter().next())
    }

    /// Cleanup expired devices
    pub async fn cleanup_expired_devices(
        &self,
        user_id: &UserId,
    ) -> Result<usize, DeviceBindingError> {
        let devices = self.storage.get_user_devices(user_id).await?;
        let mut removed = 0;

        for device in devices {
            if device.is_expired() {
                self.storage.delete_device(&device.device_id).await?;
                removed += 1;
            }
        }

        if removed > 0 {
            info!(
                "Cleaned up {} expired devices for user {:?}",
                removed, user_id
            );
        }

        Ok(removed)
    }
}

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

    fn create_test_fingerprint() -> DeviceFingerprint {
        DeviceFingerprint {
            user_agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)".to_string(),
            platform: DevicePlatform::MacOS,
            browser: BrowserType::Chrome,
            screen_resolution: Some("1920x1080".to_string()),
            timezone_offset: Some(-480),
            language: Some("en-US".to_string()),
            hardware_concurrency: Some(8),
            webgl_vendor: Some("Intel Inc.".to_string()),
            webgl_renderer: Some("Intel Iris Pro".to_string()),
            canvas_hash: Some("abc123".to_string()),
            fonts_hash: Some("def456".to_string()),
            plugins: vec![],
            touch_support: false,
            color_depth: Some(24),
        }
    }

    #[test]
    fn test_device_id_generation() {
        let fp = create_test_fingerprint();
        let id1 = fp.generate_device_id();
        let id2 = fp.generate_device_id();

        // Same fingerprint should generate same ID
        assert_eq!(id1, id2);
        assert_eq!(id1.len(), 64); // SHA256 hex
    }

    #[test]
    fn test_fingerprint_similarity() {
        let fp1 = create_test_fingerprint();
        let mut fp2 = fp1.clone();

        // Identical fingerprints
        assert_eq!(fp1.similarity(&fp2), 1.0);

        // Change one attribute
        fp2.user_agent = "Different".to_string();
        assert!(fp1.similarity(&fp2) < 1.0);
    }

    #[test]
    fn test_platform_detection() {
        assert_eq!(
            DevicePlatform::from_user_agent("Mozilla/5.0 (Windows NT 10.0)"),
            DevicePlatform::Windows
        );
        assert_eq!(
            DevicePlatform::from_user_agent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"),
            DevicePlatform::MacOS
        );
        assert_eq!(
            DevicePlatform::from_user_agent("Mozilla/5.0 (iPhone; CPU iPhone OS 14_0)"),
            DevicePlatform::iOS
        );
    }

    #[test]
    fn test_browser_detection() {
        assert_eq!(
            BrowserType::from_user_agent("Chrome/91.0.4472.124"),
            BrowserType::Chrome
        );
        assert_eq!(
            BrowserType::from_user_agent("Firefox/89.0"),
            BrowserType::Firefox
        );
        assert_eq!(
            BrowserType::from_user_agent("Edg/91.0.864.59"),
            BrowserType::Edge
        );
    }

    #[test]
    fn test_config_presets() {
        let default_config = DeviceBindingConfig::new_default();
        assert_eq!(default_config.trust_expiration_days, 30);
        assert!(default_config.require_mfa_for_registration);

        let strict_config = DeviceBindingConfig::strict();
        assert_eq!(strict_config.trust_expiration_days, 14);
        assert_eq!(strict_config.reauth_interval_days, 3);

        let lenient_config = DeviceBindingConfig::lenient();
        assert_eq!(lenient_config.trust_expiration_days, 365);
        assert!(!lenient_config.require_mfa_for_registration);
    }

    #[test]
    fn test_sensitive_operations() {
        let config = DeviceBindingConfig::new_default();
        assert!(config.is_sensitive_operation("change_password"));
        assert!(config.is_sensitive_operation("delete_account"));
        assert!(!config.is_sensitive_operation("view_profile"));
    }

    #[tokio::test]
    async fn test_device_registration() {
        let storage = InMemoryDeviceStorage::new();
        let config = DeviceBindingConfig::new_default();
        let manager = DeviceBindingManager::new(storage, config);

        let user_id = UserId::new("test_user");
        let tenant_id = TenantId::new("test_tenant");
        let fingerprint = create_test_fingerprint();

        let request = DeviceRegistrationRequest {
            user_id: user_id.clone(),
            tenant_id,
            fingerprint,
            device_type: DeviceType::Desktop,
            device_name: Some("My Laptop".to_string()),
            ip_address: Some("192.0.2.1".to_string()),
            location: Some("San Francisco, CA".to_string()),
            mfa_verified: true,
        };

        let device = manager.register_device(request).await.unwrap();
        assert_eq!(device.user_id, user_id);
        assert!(device.is_trusted);
        assert!(!device.is_expired());
    }

    #[tokio::test]
    async fn test_device_limit_enforcement() {
        let storage = InMemoryDeviceStorage::new();
        let mut config = DeviceBindingConfig::new_default();
        config.max_devices_per_user = 2;
        let manager = DeviceBindingManager::new(storage, config);

        let user_id = UserId::new("test_user");

        // Register 2 devices (should succeed)
        for i in 0..2 {
            let mut fp = create_test_fingerprint();
            fp.user_agent = format!("Device {}", i);

            let request = DeviceRegistrationRequest {
                user_id: user_id.clone(),
                tenant_id: TenantId::new("test_tenant"),
                fingerprint: fp,
                device_type: DeviceType::Desktop,
                device_name: Some(format!("Device {}", i)),
                ip_address: None,
                location: None,
                mfa_verified: true,
            };

            manager.register_device(request).await.unwrap();
        }

        // Third device should fail
        let mut fp = create_test_fingerprint();
        fp.user_agent = "Device 3".to_string();

        let request = DeviceRegistrationRequest {
            user_id,
            tenant_id: TenantId::new("test_tenant"),
            fingerprint: fp,
            device_type: DeviceType::Desktop,
            device_name: Some("Device 3".to_string()),
            ip_address: None,
            location: None,
            mfa_verified: true,
        };

        let result = manager.register_device(request).await;
        assert!(matches!(
            result,
            Err(DeviceBindingError::DeviceLimitReached { .. })
        ));
    }

    #[tokio::test]
    async fn test_sensitive_operation_blocks() {
        let storage = InMemoryDeviceStorage::new();
        let config = DeviceBindingConfig::new_default();
        let manager = DeviceBindingManager::new(storage, config);

        let user_id = UserId::new("test_user");
        let fingerprint = create_test_fingerprint();

        let request = DeviceRegistrationRequest {
            user_id,
            tenant_id: TenantId::new("test_tenant"),
            fingerprint,
            device_type: DeviceType::Desktop,
            device_name: Some("Test Device".to_string()),
            ip_address: None,
            location: None,
            mfa_verified: true,
        };

        let device = manager.register_device(request).await.unwrap();

        // Sensitive operation should require MFA even on trusted device
        let result = manager
            .validate_device_trust(&device.device_id, "change_password")
            .await
            .unwrap();

        assert!(result.requires_mfa);
        assert!(result.reason.contains("Sensitive operation"));
    }
}