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;
10#[cfg(feature = "enhanced-device-flow")]
11use base64::Engine as _;
12#[cfg(feature = "enhanced-device-flow")]
13use base64::engine::general_purpose::URL_SAFE_NO_PAD;
14use serde::{Deserialize, Serialize};
15
16/// Extract the `sub` claim from a JWT access token without verifying the
17/// signature.  This is acceptable here because the token was *just* received
18/// over TLS from the authorisation server; full signature verification is
19/// performed later by the framework's token validation layer.
20#[cfg(feature = "enhanced-device-flow")]
21fn extract_sub_from_jwt(jwt: &str) -> Option<String> {
22    let parts: Vec<&str> = jwt.splitn(3, '.').collect();
23    if parts.len() < 2 {
24        return None;
25    }
26    let payload = URL_SAFE_NO_PAD.decode(parts[1]).ok()?;
27    let claims: serde_json::Value = serde_json::from_slice(&payload).ok()?;
28    claims.get("sub").and_then(|v| v.as_str()).map(String::from)
29}
30
31/// Instructions for device flow authentication
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct DeviceFlowInstructions {
34    /// URL the user should visit
35    pub verification_uri: String,
36    /// Complete URL with embedded code for faster authentication
37    pub verification_uri_complete: Option<String>,
38    /// Device code to display to the user
39    pub user_code: String,
40    /// QR code as base64 encoded PNG (if feature enabled)
41    pub qr_code: Option<String>,
42    /// How long the user has to complete authentication
43    pub expires_in: u64,
44    /// How often to poll for completion
45    pub interval: u64,
46}
47
48/// Enhanced device flow method using oauth-device-flows crate
49#[cfg(feature = "enhanced-device-flow")]
50#[derive(Debug)]
51pub struct EnhancedDeviceFlowMethod {
52    /// OAuth client ID
53    pub client_id: String,
54    /// OAuth client secret (optional for public clients)
55    pub client_secret: Option<String>,
56    /// Authorization URL
57    pub auth_url: String,
58    /// Token URL
59    pub token_url: String,
60    /// Device authorization URL
61    pub device_auth_url: String,
62    /// OAuth scopes to request
63    pub scopes: Vec<String>,
64    /// Custom polling interval (optional)
65    pub _polling_interval: Option<std::time::Duration>,
66    /// Enable QR code generation
67    pub enable_qr_code: bool,
68}
69
70#[cfg(feature = "enhanced-device-flow")]
71impl EnhancedDeviceFlowMethod {
72    /// Create a new enhanced device flow method
73    pub fn new(
74        client_id: String,
75        client_secret: Option<String>,
76        auth_url: String,
77        token_url: String,
78        device_auth_url: String,
79    ) -> Self {
80        Self {
81            client_id,
82            client_secret,
83            auth_url,
84            token_url,
85            device_auth_url,
86            scopes: Vec::new(),
87            _polling_interval: None,
88            enable_qr_code: true,
89        }
90    }
91
92    /// Set the OAuth scopes
93    pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
94        self.scopes = scopes;
95        self
96    }
97
98    /// Set custom polling interval
99    pub fn with_polling_interval(mut self, interval: std::time::Duration) -> Self {
100        self._polling_interval = Some(interval);
101        self
102    }
103
104    /// Enable or disable QR code generation
105    pub fn with_qr_code(mut self, enable: bool) -> Self {
106        self.enable_qr_code = enable;
107        self
108    }
109
110    /// Initiate device flow and return instructions
111    pub async fn initiate_device_flow(&self) -> Result<DeviceFlowInstructions> {
112        let client = reqwest::Client::new();
113        let mut params = std::collections::HashMap::new();
114        params.insert("client_id", self.client_id.clone());
115        if !self.scopes.is_empty() {
116            params.insert("scope", self.scopes.join(" "));
117        }
118
119        let res = client
120            .post(&self.device_auth_url)
121            .form(&params)
122            .send()
123            .await
124            .map_err(AuthError::Network)?;
125
126        if !res.status().is_success() {
127            return Err(AuthError::config(&format!(
128                "Device auth request failed: {}",
129                res.status()
130            )));
131        }
132
133        #[derive(Deserialize)]
134        struct DeviceAuthResponse {
135            #[allow(
136                dead_code,
137                reason = "RFC 8628 device authorization response field; deserialized with the rest of the response but not used by this client"
138            )]
139            device_code: String,
140            user_code: String,
141            verification_uri: String,
142            verification_uri_complete: Option<String>,
143            expires_in: u64,
144            interval: Option<u64>,
145        }
146
147        let data: DeviceAuthResponse = res.json().await.map_err(AuthError::Network)?;
148
149        Ok(DeviceFlowInstructions {
150            verification_uri: data.verification_uri,
151            verification_uri_complete: data.verification_uri_complete,
152            user_code: data.user_code,
153            qr_code: None, // QR Code generation could be added here
154            expires_in: data.expires_in,
155            interval: data.interval.unwrap_or(5),
156        })
157    }
158}
159
160#[cfg(feature = "enhanced-device-flow")]
161impl AuthMethod for EnhancedDeviceFlowMethod {
162    type MethodResult = MethodResult;
163    type AuthToken = AuthToken;
164
165    async fn authenticate(
166        &self,
167        credential: Credential,
168        _metadata: CredentialMetadata,
169    ) -> Result<Self::MethodResult> {
170        let (device_code, _interval) = match credential {
171            Credential::EnhancedDeviceFlow {
172                device_code,
173                interval,
174                ..
175            } => (device_code, interval),
176            _ => {
177                return Ok(MethodResult::Failure {
178                    reason: "Invalid credential type for enhanced device flow".to_string(),
179                });
180            }
181        };
182
183        let client = reqwest::Client::new();
184        let mut params = std::collections::HashMap::new();
185        params.insert("client_id", self.client_id.clone());
186        params.insert(
187            "grant_type",
188            "urn:ietf:params:oauth:grant-type:device_code".to_string(),
189        );
190        params.insert("device_code", device_code);
191
192        if let Some(secret) = &self.client_secret {
193            params.insert("client_secret", secret.clone());
194        }
195
196        let res = client
197            .post(&self.token_url)
198            .form(&params)
199            .send()
200            .await
201            .map_err(AuthError::Network)?;
202
203        if !res.status().is_success() {
204            let error_text = res.text().await.unwrap_or_default();
205            // Typical errors like authorization_pending, slow_down, expired_token, access_denied
206            return Ok(MethodResult::Failure {
207                reason: format!("Token exchange failed: {}", error_text),
208            });
209        }
210
211        #[derive(Deserialize)]
212        struct TokenResponse {
213            access_token: String,
214            refresh_token: Option<String>,
215            expires_in: Option<u64>,
216        }
217
218        let token_data: TokenResponse = res.json().await.map_err(AuthError::Network)?;
219
220        // Extract user_id from the JWT access token (the `sub` claim).
221        let user_id = extract_sub_from_jwt(&token_data.access_token)
222            .unwrap_or_else(|| "unknown_device_user".to_string());
223
224        let expires_in = std::time::Duration::from_secs(token_data.expires_in.unwrap_or(3600));
225
226        let mut token = AuthToken::new(user_id, &token_data.access_token, expires_in, self.name());
227        token.refresh_token = token_data.refresh_token;
228
229        Ok(MethodResult::Success(Box::new(token)))
230    }
231
232    fn name(&self) -> &str {
233        "enhanced_device_flow"
234    }
235
236    fn validate_config(&self) -> Result<()> {
237        if self.client_id.is_empty() {
238            return Err(AuthError::config("Client ID is required"));
239        }
240        if self.auth_url.is_empty() {
241            return Err(AuthError::config("Authorization URL is required"));
242        }
243        if self.token_url.is_empty() {
244            return Err(AuthError::config("Token URL is required"));
245        }
246        if self.device_auth_url.is_empty() {
247            return Err(AuthError::config("Device authorization URL is required"));
248        }
249        Ok(())
250    }
251}
252
253// Proper implementation when feature is disabled - captures configuration for error reporting
254#[cfg(not(feature = "enhanced-device-flow"))]
255#[derive(Debug)]
256pub struct EnhancedDeviceFlowMethod {
257    /// Client configuration (stored for error reporting)
258    client_id: String,
259    client_secret: Option<String>,
260    auth_url: String,
261    token_url: String,
262    device_auth_url: String,
263}
264
265#[cfg(not(feature = "enhanced-device-flow"))]
266impl EnhancedDeviceFlowMethod {
267    pub fn new(
268        client_id: String,
269        client_secret: Option<String>,
270        auth_url: String,
271        token_url: String,
272        device_auth_url: String,
273    ) -> Self {
274        Self {
275            client_id,
276            client_secret,
277            auth_url,
278            token_url,
279            device_auth_url,
280        }
281    }
282}
283
284#[cfg(not(feature = "enhanced-device-flow"))]
285impl AuthMethod for EnhancedDeviceFlowMethod {
286    type MethodResult = MethodResult;
287    type AuthToken = AuthToken;
288
289    async fn authenticate(
290        &self,
291        _credential: Credential,
292        _metadata: CredentialMetadata,
293    ) -> Result<Self::MethodResult> {
294        // Use configuration fields in error message to avoid unused field warnings
295        Err(AuthError::config(format!(
296            "Enhanced device flow requires 'enhanced-device-flow' feature. Configured for client '{}' with auth_url: {}, token_url: {}, device_auth_url: {}",
297            self.client_id, self.auth_url, self.token_url, self.device_auth_url
298        )))
299    }
300
301    fn name(&self) -> &str {
302        "enhanced_device_flow"
303    }
304
305    fn validate_config(&self) -> Result<()> {
306        // Use configuration fields for validation to avoid unused field warnings
307        if self.client_id.is_empty() {
308            return Err(AuthError::config("client_id cannot be empty"));
309        }
310        if self.auth_url.is_empty() {
311            return Err(AuthError::config("auth_url cannot be empty"));
312        }
313        if self.token_url.is_empty() {
314            return Err(AuthError::config("token_url cannot be empty"));
315        }
316        if self.device_auth_url.is_empty() {
317            return Err(AuthError::config("device_auth_url cannot be empty"));
318        }
319
320        // Log configuration for debugging (uses client_secret field)
321        if self.client_secret.is_some() {
322            tracing::info!(
323                "Enhanced device flow configured for confidential client: {}",
324                self.client_id
325            );
326        } else {
327            tracing::info!(
328                "Enhanced device flow configured for public client: {}",
329                self.client_id
330            );
331        }
332
333        Err(AuthError::config(
334            "Enhanced device flow requires 'enhanced-device-flow' feature to be enabled at compile time",
335        ))
336    }
337}
338
339/// Enhanced device authentication (legacy struct for compatibility)
340pub struct EnhancedDevice {
341    /// Device identifier
342    pub device_id: String,
343}
344
345impl EnhancedDevice {
346    /// Create new enhanced device
347    pub fn new(device_id: String) -> Self {
348        Self { device_id }
349    }
350
351    /// Authenticate using enhanced device
352    pub async fn authenticate(&self, challenge: &str) -> Result<bool> {
353        // Enhanced device authentication with device binding and trust signals
354
355        if challenge.is_empty() {
356            tracing::warn!("Empty challenge provided for device authentication");
357            return Ok(false);
358        }
359
360        tracing::info!(
361            "Starting enhanced device authentication for device: {}",
362            self.device_id
363        );
364
365        // Simulate enhanced device authentication process
366        // In a real implementation, this would:
367
368        // 1. Verify device identity and binding
369        if !self.verify_device_binding().await? {
370            tracing::warn!("Device binding verification failed for: {}", self.device_id);
371            return Ok(false);
372        }
373
374        // 2. Check device trust signals
375        if !self.check_device_trust_signals().await? {
376            tracing::warn!("Device trust signals check failed for: {}", self.device_id);
377            return Ok(false);
378        }
379
380        // 3. Validate challenge-response with device-specific cryptography
381        if !self.validate_device_challenge(challenge).await? {
382            tracing::warn!("Device challenge validation failed for: {}", self.device_id);
383            return Ok(false);
384        }
385
386        tracing::info!(
387            "Enhanced device authentication successful for: {}",
388            self.device_id
389        );
390        Ok(true)
391    }
392
393    /// Verify device binding and identity
394    async fn verify_device_binding(&self) -> Result<bool> {
395        tracing::debug!("Verifying device binding for: {}", self.device_id);
396
397        // In production, this would:
398        // 1. Check device certificate or attestation
399        // 2. Validate device hardware identity
400        // 3. Verify device registration status
401        // 4. Check device compliance status
402
403        // Simulate device binding check
404        if self.device_id.len() < 8 {
405            tracing::warn!("Device ID too short for secure binding");
406            return Ok(false);
407        }
408
409        // Validate device ID format (should be UUID or similar)
410        if !self
411            .device_id
412            .chars()
413            .all(|c| c.is_ascii_alphanumeric() || c == '-')
414        {
415            tracing::warn!("Invalid device ID format");
416            return Ok(false);
417        }
418
419        tracing::debug!("Device binding verified for: {}", self.device_id);
420        Ok(true)
421    }
422
423    /// Check device trust signals
424    async fn check_device_trust_signals(&self) -> Result<bool> {
425        tracing::debug!("Checking device trust signals for: {}", self.device_id);
426
427        // In production, this would check:
428        // 1. Device reputation score
429        // 2. Recent suspicious activity
430        // 3. Device location and behavior patterns
431        // 4. Security posture (OS version, patches, etc.)
432        // 5. Mobile Device Management (MDM) status
433        // 6. Device encryption status
434
435        // Simulate trust signal evaluation
436        let trust_score = self.calculate_trust_score().await;
437
438        if trust_score < 0.7 {
439            tracing::warn!(
440                "Device trust score too low: {} for device: {}",
441                trust_score,
442                self.device_id
443            );
444            return Ok(false);
445        }
446
447        tracing::info!(
448            "Device trust signals validated (score: {}) for: {}",
449            trust_score,
450            self.device_id
451        );
452        Ok(true)
453    }
454
455    /// Calculate device trust score
456    async fn calculate_trust_score(&self) -> f64 {
457        // Simulate trust score calculation based on verifiable device properties.
458        // In production this would query MDM, EDR, and attestation services.
459        let mut score = 1.0_f64;
460
461        // Newly-registered devices start with a lower initial trust score
462        if self.device_id.contains("new") {
463            score -= 0.1;
464        }
465
466        // Test/development devices are considered less trusted
467        if self.device_id.contains("test") {
468            score -= 0.2;
469        }
470
471        // Clamp to [0.0, 1.0] so callers always receive a valid score
472        score.clamp(0.0, 1.0)
473    }
474
475    /// Validate device-specific challenge
476    async fn validate_device_challenge(&self, challenge: &str) -> Result<bool> {
477        tracing::debug!("Validating device challenge for: {}", self.device_id);
478
479        // In production, this would:
480        // 1. Perform cryptographic challenge-response
481        // 2. Validate device attestation
482        // 3. Check challenge freshness and replay protection
483        // 4. Verify device-specific cryptographic proof
484
485        // Minimum length requirement — too-short challenges cannot provide replay protection
486        if challenge.len() < 16 {
487            tracing::warn!(
488                "Device challenge too short ({} chars) for: {}",
489                challenge.len(),
490                self.device_id
491            );
492            return Ok(false);
493        }
494
495        // The challenge must consist only of URL-safe base64 / hex characters
496        // (alphanumeric, '+', '/', '-', '_', '=')
497        let valid_chars = challenge
498            .chars()
499            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '-' | '_' | '='));
500
501        if !valid_chars {
502            tracing::warn!(
503                "Device challenge contains invalid characters for: {}",
504                self.device_id
505            );
506            return Ok(false);
507        }
508
509        tracing::debug!("Device challenge validation successful");
510        Ok(true)
511    }
512}
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517
518    fn device(id: &str) -> EnhancedDevice {
519        EnhancedDevice::new(id.to_string())
520    }
521
522    // ── EnhancedDevice::new ───────────────────────────────────────────────────
523
524    #[test]
525    fn test_new_stores_device_id() {
526        let d = device("my-device-abc123");
527        assert_eq!(d.device_id, "my-device-abc123");
528    }
529
530    // ── verify_device_binding ────────────────────────────────────────────────
531
532    #[tokio::test]
533    async fn test_device_binding_valid_uuid_format() {
534        let d = device("550e8400-e29b-41d4-a716-446655440000");
535        // UUID-style device_id is ≥ 8 chars and only alphanumeric + dash
536        let result = d.verify_device_binding().await.unwrap();
537        assert!(result, "UUID-format device ID should pass binding check");
538    }
539
540    #[tokio::test]
541    async fn test_device_binding_too_short() {
542        let d = device("abc123"); // 6 chars — below 8
543        assert!(
544            !d.verify_device_binding().await.unwrap(),
545            "Device IDs shorter than 8 chars must fail"
546        );
547    }
548
549    #[tokio::test]
550    async fn test_device_binding_invalid_chars() {
551        let d = device("device@with#special!chars");
552        assert!(
553            !d.verify_device_binding().await.unwrap(),
554            "Device IDs with special chars (not alphanumeric/-) must fail"
555        );
556    }
557
558    // ── calculate_trust_score ────────────────────────────────────────────────
559
560    #[tokio::test]
561    async fn test_trust_score_clean_device_is_1_0() {
562        let d = device("abcd1234efgh5678"); // no "new" or "test" in name
563        let score = d.calculate_trust_score().await;
564        assert!(
565            (score - 1.0).abs() < f64::EPSILON,
566            "Clean device should score 1.0, got {score}"
567        );
568    }
569
570    #[tokio::test]
571    async fn test_trust_score_new_device_is_reduced() {
572        let d = device("newdevice-abcd1234");
573        let score = d.calculate_trust_score().await;
574        assert!(
575            score < 1.0,
576            "Device containing 'new' should have score < 1.0, got {score}"
577        );
578        assert!(
579            (score - 0.9).abs() < f64::EPSILON,
580            "Expected 0.9, got {score}"
581        );
582    }
583
584    #[tokio::test]
585    async fn test_trust_score_test_device_is_reduced() {
586        let d = device("testdevice-abcd1234");
587        let score = d.calculate_trust_score().await;
588        assert!(
589            (score - 0.8).abs() < f64::EPSILON,
590            "Expected 0.8 for 'test' device, got {score}"
591        );
592    }
593
594    #[tokio::test]
595    async fn test_trust_score_new_and_test_device() {
596        let d = device("new-testdevice-abcd1234");
597        let score = d.calculate_trust_score().await;
598        // 1.0 - 0.1 (new) - 0.2 (test) = 0.7
599        assert!(
600            (score - 0.7).abs() < f64::EPSILON,
601            "Expected 0.7 for device containing both 'new' and 'test', got {score}"
602        );
603    }
604
605    #[tokio::test]
606    async fn test_trust_score_always_in_range() {
607        // Even extreme inputs should stay in [0.0, 1.0]
608        for id in &[
609            "new-test-device-id",
610            "new-new-new-test-test-test-device",
611            "aaaaaaaaaaaaa",
612        ] {
613            let score = device(id).calculate_trust_score().await;
614            assert!(
615                (0.0f64..=1.0).contains(&score),
616                "Trust score {score} out of range [0,1] for '{id}'"
617            );
618        }
619    }
620
621    // ── validate_device_challenge ────────────────────────────────────────────
622
623    #[tokio::test]
624    async fn test_challenge_valid_hex_16_chars() {
625        let d = device("abcdefgh-1234");
626        let challenge = "0123456789abcdef"; // 16 hex chars
627        assert!(d.validate_device_challenge(challenge).await.unwrap());
628    }
629
630    #[tokio::test]
631    async fn test_challenge_valid_base64url() {
632        let d = device("abcdefgh-1234");
633        let challenge = "SGVsbG8gV29ybGQh"; // base64url, 16 chars
634        assert!(d.validate_device_challenge(challenge).await.unwrap());
635    }
636
637    #[tokio::test]
638    async fn test_challenge_too_short() {
639        let d = device("abcdefgh-1234");
640        assert!(
641            !d.validate_device_challenge("short123").await.unwrap(),
642            "Challenge < 16 chars must be rejected"
643        );
644    }
645
646    #[tokio::test]
647    async fn test_challenge_empty() {
648        let d = device("abcdefgh-1234");
649        assert!(!d.validate_device_challenge("").await.unwrap());
650    }
651
652    #[tokio::test]
653    async fn test_challenge_invalid_chars() {
654        let d = device("abcdefgh-1234");
655        // Contains space and exclamation mark — invalid
656        let challenge = "Hello World!!!!!";
657        assert!(
658            !d.validate_device_challenge(challenge).await.unwrap(),
659            "Challenge with spaces/exclamation marks must be rejected"
660        );
661    }
662
663    // ── authenticate (integration path) ──────────────────────────────────────
664
665    #[tokio::test]
666    async fn test_authenticate_empty_challenge_returns_false() {
667        let d = device("abcdefgh-1234");
668        assert!(!d.authenticate("").await.unwrap());
669    }
670
671    #[tokio::test]
672    async fn test_authenticate_valid_device_and_challenge() {
673        // Device id: valid format (UUID-like), Challenge: valid base64url ≥ 16 chars
674        let d = device("550e8400-e29b-41d4-a716-446655440000");
675        let challenge = "SGVsbG8gV29ybGQh"; // valid base64url, 16 chars
676        // Trust score is 1.0 (no "new" or "test"), binding passes, challenge passes
677        assert!(
678            d.authenticate(challenge).await.unwrap(),
679            "Valid device + valid challenge should authenticate"
680        );
681    }
682
683    #[tokio::test]
684    async fn test_authenticate_short_device_id_fails() {
685        let d = device("tiny"); // < 8 chars, fails binding
686        let challenge = "SGVsbG8gV29ybGQh";
687        assert!(
688            !d.authenticate(challenge).await.unwrap(),
689            "Short device ID must fail authentication"
690        );
691    }
692
693    #[tokio::test]
694    async fn test_authenticate_at_minimum_trust_score_passes() {
695        // "new" (-0.1) + "test" (-0.2) → score = 0.7, exactly at the threshold.
696        // check_device_trust_signals fails only when score < 0.7, so this passes.
697        let d = device("new-test-device-abcde"); // score exactly 0.7
698        let challenge = "SGVsbG8gV29ybGQh";
699        assert!(
700            d.authenticate(challenge).await.unwrap(),
701            "Device at minimum trust score (0.7) should still authenticate"
702        );
703    }
704}