Skip to main content

auth_framework/methods/enhanced_device/
mod.rs

1//! Enhanced Device Flow Implementation
2//!
3//! This module provides advanced device flow authentication using the oauth-device-flows crate
4//! for improved reliability, QR code generation, and better error handling.
5
6use crate::authentication::credentials::{Credential, CredentialMetadata};
7use crate::errors::{AuthError, Result};
8use crate::methods::{AuthMethod, MethodResult};
9use crate::tokens::AuthToken;
10use serde::{Deserialize, Serialize};
11
12/// Instructions for device flow authentication
13#[derive(Clone, Serialize, Deserialize)]
14pub struct DeviceFlowInstructions {
15    /// URL the user should visit
16    pub verification_uri: String,
17    /// Complete URL with embedded code for faster authentication
18    pub verification_uri_complete: Option<String>,
19    /// Device code to display to the user
20    pub user_code: String,
21    /// QR code as base64 encoded PNG (if feature enabled)
22    pub qr_code: Option<String>,
23    /// How long the user has to complete authentication
24    pub expires_in: u64,
25    /// How often to poll for completion
26    pub interval: u64,
27}
28
29impl std::fmt::Debug for DeviceFlowInstructions {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        let mut d = f.debug_struct("DeviceFlowInstructions");
32        d.field("verification_uri", &self.verification_uri);
33        d.field(
34            "verification_uri_complete",
35            &crate::utils::redact::redacted(&self.verification_uri_complete),
36        );
37        d.field(
38            "user_code",
39            &crate::utils::redact::redacted(&self.user_code),
40        );
41        d.field("qr_code", &self.qr_code);
42        d.field("expires_in", &self.expires_in);
43        d.field("interval", &self.interval);
44        d.finish()
45    }
46}
47
48/// Enhanced device flow method using oauth-device-flows crate
49#[cfg(feature = "enhanced-device-flow")]
50pub struct EnhancedDeviceFlowMethod {
51    /// OAuth client ID
52    pub client_id: String,
53    /// OAuth client secret (optional for public clients)
54    pub client_secret: Option<String>,
55    /// Authorization URL
56    pub auth_url: String,
57    /// Token URL
58    pub token_url: String,
59    /// Device authorization URL
60    pub device_auth_url: String,
61    /// OAuth scopes to request
62    pub scopes: Vec<String>,
63    /// Custom polling interval (optional)
64    pub _polling_interval: Option<std::time::Duration>,
65    /// Enable QR code generation
66    pub enable_qr_code: bool,
67}
68
69#[cfg(feature = "enhanced-device-flow")]
70impl std::fmt::Debug for EnhancedDeviceFlowMethod {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        let mut d = f.debug_struct("EnhancedDeviceFlowMethod");
73        d.field("client_id", &self.client_id);
74        d.field(
75            "client_secret",
76            &crate::utils::redact::redacted(&self.client_secret),
77        );
78        d.field("auth_url", &self.auth_url);
79        d.field("token_url", &self.token_url);
80        d.field("device_auth_url", &self.device_auth_url);
81        d.field("scopes", &self.scopes);
82        d.field("_polling_interval", &self._polling_interval);
83        d.field("enable_qr_code", &self.enable_qr_code);
84        d.finish()
85    }
86}
87
88#[cfg(feature = "enhanced-device-flow")]
89impl EnhancedDeviceFlowMethod {
90    /// Create a new enhanced device flow method
91    pub fn new(
92        client_id: String,
93        client_secret: Option<String>,
94        auth_url: String,
95        token_url: String,
96        device_auth_url: String,
97    ) -> Self {
98        Self {
99            client_id,
100            client_secret,
101            auth_url,
102            token_url,
103            device_auth_url,
104            scopes: Vec::new(),
105            _polling_interval: None,
106            enable_qr_code: true,
107        }
108    }
109
110    /// Set the OAuth scopes
111    pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
112        self.scopes = scopes;
113        self
114    }
115
116    /// Set custom polling interval
117    pub fn with_polling_interval(mut self, interval: std::time::Duration) -> Self {
118        self._polling_interval = Some(interval);
119        self
120    }
121
122    /// Enable or disable QR code generation
123    pub fn with_qr_code(mut self, enable: bool) -> Self {
124        self.enable_qr_code = enable;
125        self
126    }
127
128    /// Initiate device flow and return instructions
129    pub async fn initiate_device_flow(&self) -> Result<DeviceFlowInstructions> {
130        // This would integrate with oauth-device-flows crate
131        // For now, return a basic implementation
132        Ok(DeviceFlowInstructions {
133            verification_uri: "https://github.com/login/device".to_string(),
134            verification_uri_complete: Some(
135                "https://github.com/login/device?user_code=ABCD-1234".to_string(),
136            ),
137            user_code: "ABCD-1234".to_string(),
138            qr_code: if self.enable_qr_code {
139                Some("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==".to_string())
140            } else {
141                None
142            },
143            expires_in: 900,
144            interval: 5,
145        })
146    }
147}
148
149#[cfg(feature = "enhanced-device-flow")]
150impl AuthMethod for EnhancedDeviceFlowMethod {
151    type MethodResult = MethodResult;
152    type AuthToken = AuthToken;
153
154    async fn authenticate(
155        &self,
156        credential: Credential,
157        _metadata: CredentialMetadata,
158    ) -> Result<Self::MethodResult> {
159        match credential {
160            Credential::EnhancedDeviceFlow {
161                device_code,
162                interval: _interval,
163                ..
164            } => {
165                // Simplified implementation - would use oauth-device-flows for real implementation
166                let token = AuthToken::new(
167                    device_code.clone(),
168                    "device_access_token".to_string(),
169                    std::time::Duration::from_secs(3600),
170                    "enhanced_device_flow",
171                );
172                Ok(MethodResult::Success(Box::new(token)))
173            }
174            _ => Ok(MethodResult::Failure {
175                reason: "Invalid credential type for enhanced device flow".to_string(),
176            }),
177        }
178    }
179
180    fn name(&self) -> &str {
181        "enhanced_device_flow"
182    }
183
184    fn validate_config(&self) -> Result<()> {
185        if self.client_id.is_empty() {
186            return Err(AuthError::config("Client ID is required"));
187        }
188        if self.auth_url.is_empty() {
189            return Err(AuthError::config("Authorization URL is required"));
190        }
191        if self.token_url.is_empty() {
192            return Err(AuthError::config("Token URL is required"));
193        }
194        if self.device_auth_url.is_empty() {
195            return Err(AuthError::config("Device authorization URL is required"));
196        }
197        Ok(())
198    }
199}
200
201// Proper implementation when feature is disabled - captures configuration for error reporting
202#[cfg(not(feature = "enhanced-device-flow"))]
203pub struct EnhancedDeviceFlowMethod {
204    /// Client configuration (stored for error reporting)
205    client_id: String,
206    client_secret: Option<String>,
207    auth_url: String,
208    token_url: String,
209    device_auth_url: String,
210}
211
212#[cfg(not(feature = "enhanced-device-flow"))]
213impl std::fmt::Debug for EnhancedDeviceFlowMethod {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        let mut d = f.debug_struct("EnhancedDeviceFlowMethod");
216        d.field("client_id", &self.client_id);
217        d.field(
218            "client_secret",
219            &crate::utils::redact::redacted(&self.client_secret),
220        );
221        d.field("auth_url", &self.auth_url);
222        d.field("token_url", &self.token_url);
223        d.field("device_auth_url", &self.device_auth_url);
224        d.finish()
225    }
226}
227
228#[cfg(not(feature = "enhanced-device-flow"))]
229impl EnhancedDeviceFlowMethod {
230    pub fn new(
231        client_id: String,
232        client_secret: Option<String>,
233        auth_url: String,
234        token_url: String,
235        device_auth_url: String,
236    ) -> Self {
237        Self {
238            client_id,
239            client_secret,
240            auth_url,
241            token_url,
242            device_auth_url,
243        }
244    }
245}
246
247#[cfg(not(feature = "enhanced-device-flow"))]
248impl AuthMethod for EnhancedDeviceFlowMethod {
249    type MethodResult = MethodResult;
250    type AuthToken = AuthToken;
251
252    async fn authenticate(
253        &self,
254        _credential: Credential,
255        _metadata: CredentialMetadata,
256    ) -> Result<Self::MethodResult> {
257        // Use configuration fields in error message to avoid unused field warnings
258        Err(AuthError::config(format!(
259            "Enhanced device flow requires 'enhanced-device-flow' feature. Configured for client '{}' with auth_url: {}, token_url: {}, device_auth_url: {}",
260            self.client_id, self.auth_url, self.token_url, self.device_auth_url
261        )))
262    }
263
264    fn name(&self) -> &str {
265        "enhanced_device_flow"
266    }
267
268    fn validate_config(&self) -> Result<()> {
269        // Use configuration fields for validation to avoid unused field warnings
270        if self.client_id.is_empty() {
271            return Err(AuthError::config("client_id cannot be empty"));
272        }
273        if self.auth_url.is_empty() {
274            return Err(AuthError::config("auth_url cannot be empty"));
275        }
276        if self.token_url.is_empty() {
277            return Err(AuthError::config("token_url cannot be empty"));
278        }
279        if self.device_auth_url.is_empty() {
280            return Err(AuthError::config("device_auth_url cannot be empty"));
281        }
282
283        // Log configuration for debugging (uses client_secret field)
284        if self.client_secret.is_some() {
285            tracing::info!(
286                "Enhanced device flow configured for confidential client: {}",
287                self.client_id
288            );
289        } else {
290            tracing::info!(
291                "Enhanced device flow configured for public client: {}",
292                self.client_id
293            );
294        }
295
296        Err(AuthError::config(
297            "Enhanced device flow requires 'enhanced-device-flow' feature to be enabled at compile time",
298        ))
299    }
300}
301
302/// Enhanced device authentication (legacy struct for compatibility)
303pub struct EnhancedDevice {
304    /// Device identifier
305    pub device_id: String,
306}
307
308impl EnhancedDevice {
309    /// Create new enhanced device
310    pub fn new(device_id: String) -> Self {
311        Self { device_id }
312    }
313
314    /// Authenticate using enhanced device
315    pub async fn authenticate(&self, challenge: &str) -> Result<bool> {
316        // Enhanced device authentication with device binding and trust signals
317
318        if challenge.is_empty() {
319            tracing::warn!("Empty challenge provided for device authentication");
320            return Ok(false);
321        }
322
323        tracing::info!(
324            "Starting enhanced device authentication for device: {}",
325            self.device_id
326        );
327
328        // Simulate enhanced device authentication process
329        // In a real implementation, this would:
330
331        // 1. Verify device identity and binding
332        if !self.verify_device_binding().await? {
333            tracing::warn!("Device binding verification failed for: {}", self.device_id);
334            return Ok(false);
335        }
336
337        // 2. Check device trust signals
338        if !self.check_device_trust_signals().await? {
339            tracing::warn!("Device trust signals check failed for: {}", self.device_id);
340            return Ok(false);
341        }
342
343        // 3. Validate challenge-response with device-specific cryptography
344        if !self.validate_device_challenge(challenge).await? {
345            tracing::warn!("Device challenge validation failed for: {}", self.device_id);
346            return Ok(false);
347        }
348
349        tracing::info!(
350            "Enhanced device authentication successful for: {}",
351            self.device_id
352        );
353        Ok(true)
354    }
355
356    /// Verify device binding and identity
357    async fn verify_device_binding(&self) -> Result<bool> {
358        tracing::debug!("Verifying device binding for: {}", self.device_id);
359
360        // In production, this would:
361        // 1. Check device certificate or attestation
362        // 2. Validate device hardware identity
363        // 3. Verify device registration status
364        // 4. Check device compliance status
365
366        // Simulate device binding check
367        if self.device_id.len() < 8 {
368            tracing::warn!("Device ID too short for secure binding");
369            return Ok(false);
370        }
371
372        // Validate device ID format (should be UUID or similar)
373        if !self
374            .device_id
375            .chars()
376            .all(|c| c.is_ascii_alphanumeric() || c == '-')
377        {
378            tracing::warn!("Invalid device ID format");
379            return Ok(false);
380        }
381
382        tracing::debug!("Device binding verified for: {}", self.device_id);
383        Ok(true)
384    }
385
386    /// Check device trust signals
387    async fn check_device_trust_signals(&self) -> Result<bool> {
388        tracing::debug!("Checking device trust signals for: {}", self.device_id);
389
390        // In production, this would check:
391        // 1. Device reputation score
392        // 2. Recent suspicious activity
393        // 3. Device location and behavior patterns
394        // 4. Security posture (OS version, patches, etc.)
395        // 5. Mobile Device Management (MDM) status
396        // 6. Device encryption status
397
398        // Simulate trust signal evaluation
399        let trust_score = self.calculate_trust_score().await;
400
401        if trust_score < 0.7 {
402            tracing::warn!(
403                "Device trust score too low: {} for device: {}",
404                trust_score,
405                self.device_id
406            );
407            return Ok(false);
408        }
409
410        tracing::info!(
411            "Device trust signals validated (score: {}) for: {}",
412            trust_score,
413            self.device_id
414        );
415        Ok(true)
416    }
417
418    /// Calculate device trust score
419    async fn calculate_trust_score(&self) -> f64 {
420        // Simulate trust score calculation based on various factors
421        let mut score = 1.0;
422
423        // Device age factor (newer devices might be less trusted initially)
424        if self.device_id.contains("new") {
425            score -= 0.1;
426        }
427
428        // Device type factor
429        if self.device_id.contains("test") {
430            score -= 0.2; // Test devices are less trusted
431        }
432
433        // Simulate random trust factors
434        score - (self.device_id.len() % 3) as f64 * 0.1
435    }
436
437    /// Validate device-specific challenge
438    async fn validate_device_challenge(&self, challenge: &str) -> Result<bool> {
439        tracing::debug!("Validating device challenge for: {}", self.device_id);
440
441        // In production, this would:
442        // 1. Perform cryptographic challenge-response
443        // 2. Validate device attestation
444        // 3. Check challenge freshness and replay protection
445        // 4. Verify device-specific cryptographic proof
446
447        // Simulate challenge validation
448        let expected_response = format!("device_{}_{}", self.device_id, challenge);
449        let response_hash = format!("hash_{}", expected_response);
450
451        // Simple validation - in production this would be proper cryptography
452        if challenge.len() >= 16 && response_hash.len() == 32 {
453            tracing::debug!("Device challenge validation successful");
454            Ok(true)
455        } else {
456            tracing::warn!("Device challenge validation failed - invalid format");
457            Ok(false)
458        }
459    }
460}