Skip to main content

auth_framework/server/oauth/
device.rs

1//! Device Authorization Grant Implementation - RFC 8628
2//!
3//! This module implements RFC 8628 - OAuth 2.0 Device Authorization Grant
4//! which allows devices with limited input capability (smart TVs, printers, etc.)
5//! to obtain user authorization.
6
7use crate::errors::{AuthError, Result};
8use crate::storage::AuthStorage;
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11use std::sync::Arc;
12use std::time::{Duration, SystemTime};
13use uuid::Uuid;
14
15/// Device authorization request
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct DeviceAuthorizationRequest {
18    /// Client identifier
19    pub client_id: String,
20
21    /// Requested scopes
22    pub scope: Option<String>,
23}
24
25/// Device authorization response
26#[derive(Clone, Serialize, Deserialize)]
27pub struct DeviceAuthorizationResponse {
28    /// Device verification code (for storage)
29    pub device_code: String,
30
31    /// User-friendly code to enter
32    pub user_code: String,
33
34    /// URL where user should authorize
35    pub verification_uri: String,
36
37    /// Complete verification URL with user_code (optional)
38    pub verification_uri_complete: Option<String>,
39
40    /// Polling interval in seconds
41    pub interval: u64,
42
43    /// Device code expires in seconds
44    pub expires_in: u64,
45}
46
47impl std::fmt::Debug for DeviceAuthorizationResponse {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        let mut d = f.debug_struct("DeviceAuthorizationResponse");
50        d.field(
51            "device_code",
52            &crate::utils::redact::redacted(&self.device_code),
53        );
54        d.field(
55            "user_code",
56            &crate::utils::redact::redacted(&self.user_code),
57        );
58        d.field("verification_uri", &self.verification_uri);
59        d.field(
60            "verification_uri_complete",
61            &crate::utils::redact::redacted(&self.verification_uri_complete),
62        );
63        d.field("interval", &self.interval);
64        d.field("expires_in", &self.expires_in);
65        d.finish()
66    }
67}
68
69/// Token request for device code grant
70#[derive(Clone, Deserialize)]
71pub struct DeviceTokenRequest {
72    /// Grant type (must be "urn:ietf:params:oauth:grant-type:device_code")
73    pub grant_type: String,
74
75    /// Device code received from device authorization
76    pub device_code: String,
77
78    /// Client identifier
79    pub client_id: String,
80}
81
82impl std::fmt::Debug for DeviceTokenRequest {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        let mut d = f.debug_struct("DeviceTokenRequest");
85        d.field("grant_type", &self.grant_type);
86        d.field(
87            "device_code",
88            &crate::utils::redact::redacted(&self.device_code),
89        );
90        d.field("client_id", &self.client_id);
91        d.finish()
92    }
93}
94
95/// Stored device authorization data
96#[derive(Clone, Serialize, Deserialize)]
97pub struct StoredDeviceAuthorization {
98    /// Device code
99    pub device_code: String,
100
101    /// User code
102    pub user_code: String,
103
104    /// Client ID
105    pub client_id: String,
106
107    /// Requested scopes
108    pub scope: Option<String>,
109
110    /// Authorization status
111    pub status: DeviceAuthorizationStatus,
112
113    /// User ID (once authorized)
114    pub user_id: Option<String>,
115
116    /// When the request was created
117    pub created_at: SystemTime,
118
119    /// When the request expires
120    pub expires_at: SystemTime,
121
122    /// Last poll time (for slow_down error)
123    pub last_poll: Option<SystemTime>,
124
125    /// Number of times the client has been told to slow down (RFC 8628 §3.5).
126    /// Each slow_down increases the required interval by 5 seconds.
127    #[serde(default)]
128    pub slow_down_count: u32,
129}
130
131impl std::fmt::Debug for StoredDeviceAuthorization {
132    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133        let mut d = f.debug_struct("StoredDeviceAuthorization");
134        d.field(
135            "device_code",
136            &crate::utils::redact::redacted(&self.device_code),
137        );
138        d.field(
139            "user_code",
140            &crate::utils::redact::redacted(&self.user_code),
141        );
142        d.field("client_id", &self.client_id);
143        d.field("scope", &self.scope);
144        d.field("status", &self.status);
145        d.field("user_id", &self.user_id);
146        d.field("created_at", &self.created_at);
147        d.field("expires_at", &self.expires_at);
148        d.field("last_poll", &self.last_poll);
149        d.field("slow_down_count", &self.slow_down_count);
150        d.finish()
151    }
152}
153
154/// Device authorization status
155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub enum DeviceAuthorizationStatus {
157    /// Awaiting user authorization
158    Pending,
159    /// User has authorized
160    Authorized,
161    /// User has denied
162    Denied,
163    /// Authorization expired
164    Expired,
165}
166
167/// Device authorization manager with persistent storage
168use std::fmt;
169
170#[derive(Clone)]
171pub struct DeviceAuthManager {
172    /// Persistent storage backend
173    storage: Arc<dyn AuthStorage>,
174
175    /// Memory cache for fast access
176    authorizations: Arc<tokio::sync::RwLock<HashMap<String, StoredDeviceAuthorization>>>,
177
178    /// Default expiration time for device codes
179    default_expiration: Duration,
180
181    /// Minimum polling interval
182    min_interval: Duration,
183
184    /// Base verification URI
185    verification_uri: String,
186}
187
188impl fmt::Debug for DeviceAuthManager {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        f.debug_struct("DeviceAuthManager")
191            .field("storage", &"<dyn AuthStorage>")
192            .field("default_expiration", &self.default_expiration)
193            .field("min_interval", &self.min_interval)
194            .field("verification_uri", &self.verification_uri)
195            .finish()
196    }
197}
198
199impl DeviceAuthManager {
200    /// Create a new device authorization manager
201    pub fn new(storage: Arc<dyn AuthStorage>, verification_uri: String) -> Self {
202        Self {
203            storage,
204            authorizations: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
205            default_expiration: Duration::from_secs(600), // 10 minutes (RFC 8628 recommendation)
206            min_interval: Duration::from_secs(5),         // 5 seconds minimum
207            verification_uri,
208        }
209    }
210
211    /// Create a new device authorization manager with custom settings
212    pub fn with_settings(
213        storage: Arc<dyn AuthStorage>,
214        verification_uri: String,
215        expiration: Duration,
216        min_interval: Duration,
217    ) -> Self {
218        Self {
219            storage,
220            authorizations: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
221            default_expiration: expiration,
222            min_interval,
223            verification_uri,
224        }
225    }
226
227    /// Set the default expiration time for device codes (chainable).
228    ///
229    /// Default: 600 seconds (10 minutes, per RFC 8628 recommendation).
230    pub fn expiration(mut self, expiration: Duration) -> Self {
231        self.default_expiration = expiration;
232        self
233    }
234
235    /// Set the minimum polling interval (chainable).
236    ///
237    /// Default: 5 seconds.
238    pub fn interval(mut self, interval: Duration) -> Self {
239        self.min_interval = interval;
240        self
241    }
242
243    /// Initiate device authorization flow
244    pub async fn create_authorization(
245        &self,
246        request: DeviceAuthorizationRequest,
247    ) -> Result<DeviceAuthorizationResponse> {
248        // Validate the request
249        self.validate_request(&request)?;
250
251        // Generate device code and user code
252        let device_code = format!("dc_{}", Uuid::new_v4().simple());
253        let user_code = self.generate_user_code();
254
255        // Calculate expiration
256        let now = SystemTime::now();
257        let expires_at = now + self.default_expiration;
258
259        // Create stored authorization
260        let stored = StoredDeviceAuthorization {
261            device_code: device_code.clone(),
262            user_code: user_code.clone(),
263            client_id: request.client_id.clone(),
264            scope: request.scope.clone(),
265            status: DeviceAuthorizationStatus::Pending,
266            user_id: None,
267            created_at: now,
268            expires_at,
269            last_poll: None,
270            slow_down_count: 0,
271        };
272
273        // Store in persistent backend with TTL
274        let device_key = format!("device_code:{}", device_code);
275        let user_key = format!("user_code:{}", user_code);
276
277        let serialized = serde_json::to_string(&stored)
278            .map_err(|e| AuthError::internal(format!("Failed to serialize device auth: {}", e)))?;
279
280        self.storage
281            .store_kv(
282                &device_key,
283                serialized.as_bytes(),
284                Some(self.default_expiration),
285            )
286            .await
287            .map_err(|e| {
288                AuthError::internal(format!("Failed to store device authorization: {}", e))
289            })?;
290
291        // Also store under user_code for verification page
292        self.storage
293            .store_kv(
294                &user_key,
295                serialized.as_bytes(),
296                Some(self.default_expiration),
297            )
298            .await
299            .map_err(|e| {
300                AuthError::internal(format!("Failed to store user code mapping: {}", e))
301            })?;
302
303        // Cache in memory
304        let mut authorizations = self.authorizations.write().await;
305        authorizations.insert(device_code.clone(), stored);
306
307        // Cleanup expired entries
308        self.cleanup_expired(&mut authorizations, now);
309
310        // Create response
311        let verification_uri_complete =
312            format!("{}?user_code={}", self.verification_uri, user_code);
313
314        Ok(DeviceAuthorizationResponse {
315            device_code,
316            user_code,
317            verification_uri: self.verification_uri.clone(),
318            verification_uri_complete: Some(verification_uri_complete),
319            interval: self.min_interval.as_secs(),
320            expires_in: self.default_expiration.as_secs(),
321        })
322    }
323
324    /// Poll for authorization status (used during token endpoint polling)
325    pub async fn poll_authorization(&self, device_code: &str) -> Result<StoredDeviceAuthorization> {
326        let device_key = format!("device_code:{}", device_code);
327
328        // Try to load from persistent storage first
329        let mut stored = if let Some(data) = self.storage.get_kv(&device_key).await? {
330            let serialized = String::from_utf8(data)
331                .map_err(|_| AuthError::internal("Invalid UTF-8 in stored device auth data"))?;
332
333            serde_json::from_str::<StoredDeviceAuthorization>(&serialized).map_err(|e| {
334                AuthError::internal(format!("Failed to deserialize device auth: {}", e))
335            })?
336        } else {
337            // Fallback to memory cache
338            let authorizations = self.authorizations.read().await;
339            authorizations
340                .get(device_code)
341                .cloned()
342                .ok_or_else(|| AuthError::auth_method("device_auth", "Invalid device_code"))?
343        };
344
345        // Check expiration
346        let now = SystemTime::now();
347        if now > stored.expires_at {
348            stored.status = DeviceAuthorizationStatus::Expired;
349            return Err(AuthError::auth_method("device_auth", "Device code expired"));
350        }
351
352        // Check for slow_down (polling too frequently) — RFC 8628 §3.5
353        // The required interval increases by 5 seconds each time the client
354        // polls too fast, implementing exponential backoff.
355        let effective_interval =
356            self.min_interval + Duration::from_secs(5 * u64::from(stored.slow_down_count));
357        if let Some(last_poll) = stored.last_poll {
358            let elapsed = now.duration_since(last_poll).unwrap_or(Duration::ZERO);
359            if elapsed < effective_interval {
360                stored.slow_down_count += 1;
361                // Persist the updated slow_down_count
362                stored.last_poll = Some(now);
363                let serialized = serde_json::to_string(&stored).map_err(|e| {
364                    AuthError::internal(format!("Failed to serialize device auth: {}", e))
365                })?;
366                self.storage
367                    .store_kv(
368                        &device_key,
369                        serialized.as_bytes(),
370                        Some(self.default_expiration),
371                    )
372                    .await
373                    .ok();
374                let mut authorizations = self.authorizations.write().await;
375                authorizations.insert(device_code.to_string(), stored);
376                return Err(AuthError::auth_method("device_auth", "slow_down"));
377            }
378        }
379
380        // Update last poll time
381        stored.last_poll = Some(now);
382
383        // Persist updated state
384        let serialized = serde_json::to_string(&stored)
385            .map_err(|e| AuthError::internal(format!("Failed to serialize device auth: {}", e)))?;
386
387        self.storage
388            .store_kv(
389                &device_key,
390                serialized.as_bytes(),
391                Some(self.default_expiration),
392            )
393            .await
394            .ok(); // Ignore errors for poll time update
395
396        // Update memory cache
397        let mut authorizations = self.authorizations.write().await;
398        authorizations.insert(device_code.to_string(), stored.clone());
399
400        // Return current status
401        match stored.status {
402            DeviceAuthorizationStatus::Pending => Err(AuthError::auth_method(
403                "device_auth",
404                "authorization_pending",
405            )),
406            DeviceAuthorizationStatus::Authorized => Ok(stored),
407            DeviceAuthorizationStatus::Denied => {
408                Err(AuthError::auth_method("device_auth", "access_denied"))
409            }
410            DeviceAuthorizationStatus::Expired => {
411                Err(AuthError::auth_method("device_auth", "expired_token"))
412            }
413        }
414    }
415
416    /// Authorize a device (called when user approves on verification page)
417    pub async fn authorize_device(&self, user_code: &str, user_id: &str) -> Result<()> {
418        let user_key = format!("user_code:{}", user_code);
419
420        // Load from storage
421        let mut stored = if let Some(data) = self.storage.get_kv(&user_key).await? {
422            let serialized = String::from_utf8(data)
423                .map_err(|_| AuthError::internal("Invalid UTF-8 in stored device auth data"))?;
424
425            serde_json::from_str::<StoredDeviceAuthorization>(&serialized).map_err(|e| {
426                AuthError::internal(format!("Failed to deserialize device auth: {}", e))
427            })?
428        } else {
429            return Err(AuthError::auth_method("device_auth", "Invalid user_code"));
430        };
431
432        // Check if expired
433        let now = SystemTime::now();
434        if now > stored.expires_at {
435            return Err(AuthError::auth_method("device_auth", "Device code expired"));
436        }
437
438        // Update status
439        stored.status = DeviceAuthorizationStatus::Authorized;
440        stored.user_id = Some(user_id.to_string());
441
442        // Persist updated state
443        let serialized = serde_json::to_string(&stored)
444            .map_err(|e| AuthError::internal(format!("Failed to serialize device auth: {}", e)))?;
445
446        let device_key = format!("device_code:{}", stored.device_code);
447
448        self.storage
449            .store_kv(
450                &device_key,
451                serialized.as_bytes(),
452                Some(self.default_expiration),
453            )
454            .await?;
455
456        self.storage
457            .store_kv(
458                &user_key,
459                serialized.as_bytes(),
460                Some(self.default_expiration),
461            )
462            .await?;
463
464        // Update memory cache
465        let mut authorizations = self.authorizations.write().await;
466        authorizations.insert(stored.device_code.clone(), stored);
467
468        Ok(())
469    }
470
471    /// Deny a device authorization
472    pub async fn deny_device(&self, user_code: &str) -> Result<()> {
473        let user_key = format!("user_code:{}", user_code);
474
475        // Load from storage
476        let mut stored = if let Some(data) = self.storage.get_kv(&user_key).await? {
477            let serialized = String::from_utf8(data)
478                .map_err(|_| AuthError::internal("Invalid UTF-8 in stored device auth data"))?;
479
480            serde_json::from_str::<StoredDeviceAuthorization>(&serialized).map_err(|e| {
481                AuthError::internal(format!("Failed to deserialize device auth: {}", e))
482            })?
483        } else {
484            return Err(AuthError::auth_method("device_auth", "Invalid user_code"));
485        };
486
487        // Update status
488        stored.status = DeviceAuthorizationStatus::Denied;
489
490        // Persist updated state
491        let serialized = serde_json::to_string(&stored)
492            .map_err(|e| AuthError::internal(format!("Failed to serialize device auth: {}", e)))?;
493
494        let device_key = format!("device_code:{}", stored.device_code);
495
496        self.storage
497            .store_kv(
498                &device_key,
499                serialized.as_bytes(),
500                Some(self.default_expiration),
501            )
502            .await?;
503
504        self.storage
505            .store_kv(
506                &user_key,
507                serialized.as_bytes(),
508                Some(self.default_expiration),
509            )
510            .await?;
511
512        // Update memory cache
513        let mut authorizations = self.authorizations.write().await;
514        authorizations.insert(stored.device_code.clone(), stored);
515
516        Ok(())
517    }
518
519    /// Get device authorization by user code (for verification page)
520    pub async fn get_by_user_code(&self, user_code: &str) -> Result<StoredDeviceAuthorization> {
521        let user_key = format!("user_code:{}", user_code);
522
523        if let Some(data) = self.storage.get_kv(&user_key).await? {
524            let serialized = String::from_utf8(data)
525                .map_err(|_| AuthError::internal("Invalid UTF-8 in stored device auth data"))?;
526
527            let stored: StoredDeviceAuthorization =
528                serde_json::from_str(&serialized).map_err(|e| {
529                    AuthError::internal(format!("Failed to deserialize device auth: {}", e))
530                })?;
531
532            // Check expiration
533            let now = SystemTime::now();
534            if now > stored.expires_at {
535                return Err(AuthError::auth_method("device_auth", "User code expired"));
536            }
537
538            Ok(stored)
539        } else {
540            Err(AuthError::auth_method("device_auth", "Invalid user_code"))
541        }
542    }
543
544    /// Validate device authorization request
545    fn validate_request(&self, request: &DeviceAuthorizationRequest) -> Result<()> {
546        if request.client_id.is_empty() {
547            return Err(AuthError::auth_method("device_auth", "Missing client_id"));
548        }
549
550        // In production, validate client_id against registered clients
551
552        Ok(())
553    }
554
555    /// Generate a user-friendly code (uppercase, no ambiguous characters)
556    fn generate_user_code(&self) -> String {
557        use rand::RngExt;
558        const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // No ambiguous: 0,O,I,1
559        let mut rng = rand::rng();
560
561        // Generate 9-character code with dash for readability: XXXX-XXXX
562        let code: String = (0..9)
563            .map(|i| {
564                if i == 4 {
565                    '-'
566                } else {
567                    let idx = rng.random_range(0..CHARS.len());
568                    CHARS[idx] as char
569                }
570            })
571            .collect();
572
573        code
574    }
575
576    /// Clean up expired entries from memory cache
577    fn cleanup_expired(
578        &self,
579        authorizations: &mut HashMap<String, StoredDeviceAuthorization>,
580        now: SystemTime,
581    ) {
582        authorizations.retain(|_, auth| now <= auth.expires_at);
583    }
584}
585
586#[cfg(test)]
587mod tests {
588    use super::*;
589    use crate::storage::MemoryStorage;
590    use tokio::time::sleep;
591
592    fn create_test_manager() -> DeviceAuthManager {
593        let storage = Arc::new(MemoryStorage::new());
594        DeviceAuthManager::new(storage, "https://example.com/device".to_string())
595    }
596
597    #[tokio::test]
598    async fn test_create_authorization() {
599        let manager = create_test_manager();
600
601        let request = DeviceAuthorizationRequest {
602            client_id: "test_client".to_string(),
603            scope: Some("openid profile".to_string()),
604        };
605
606        let response = manager.create_authorization(request).await.unwrap();
607
608        assert!(response.device_code.starts_with("dc_"));
609        assert_eq!(response.user_code.len(), 9); // XXXX-XXXX
610        assert!(response.user_code.contains('-'));
611        assert_eq!(response.verification_uri, "https://example.com/device");
612        assert!(response.verification_uri_complete.is_some());
613        assert_eq!(response.interval, 5);
614        assert_eq!(response.expires_in, 600);
615    }
616
617    #[tokio::test]
618    async fn test_poll_pending() {
619        let manager = create_test_manager();
620
621        let request = DeviceAuthorizationRequest {
622            client_id: "test_client".to_string(),
623            scope: None,
624        };
625
626        let response = manager.create_authorization(request).await.unwrap();
627
628        // Poll should return authorization_pending
629        let result = manager.poll_authorization(&response.device_code).await;
630        assert!(result.is_err());
631        let err = result.unwrap_err();
632        assert!(err.to_string().contains("authorization_pending"));
633    }
634
635    #[tokio::test]
636    async fn test_authorize_and_poll() {
637        let manager = create_test_manager();
638
639        let request = DeviceAuthorizationRequest {
640            client_id: "test_client".to_string(),
641            scope: Some("openid".to_string()),
642        };
643
644        let response = manager.create_authorization(request).await.unwrap();
645
646        // Authorize the device
647        manager
648            .authorize_device(&response.user_code, "user_123")
649            .await
650            .unwrap();
651
652        // Poll should now succeed
653        let stored = manager
654            .poll_authorization(&response.device_code)
655            .await
656            .unwrap();
657        assert_eq!(stored.status, DeviceAuthorizationStatus::Authorized);
658        assert_eq!(stored.user_id, Some("user_123".to_string()));
659    }
660
661    #[tokio::test]
662    async fn test_deny_device() {
663        let manager = create_test_manager();
664
665        let request = DeviceAuthorizationRequest {
666            client_id: "test_client".to_string(),
667            scope: None,
668        };
669
670        let response = manager.create_authorization(request).await.unwrap();
671
672        // Deny the device
673        manager.deny_device(&response.user_code).await.unwrap();
674
675        // Poll should return access_denied
676        let result = manager.poll_authorization(&response.device_code).await;
677        assert!(result.is_err());
678        let err = result.unwrap_err();
679        assert!(err.to_string().contains("access_denied"));
680    }
681
682    #[tokio::test]
683    async fn test_slow_down() {
684        let manager = create_test_manager();
685
686        let request = DeviceAuthorizationRequest {
687            client_id: "test_client".to_string(),
688            scope: None,
689        };
690
691        let response = manager.create_authorization(request).await.unwrap();
692
693        // First poll
694        let _ = manager.poll_authorization(&response.device_code).await;
695
696        // Immediate second poll should return slow_down
697        let result = manager.poll_authorization(&response.device_code).await;
698        assert!(result.is_err());
699        let err = result.unwrap_err();
700        assert!(err.to_string().contains("slow_down"));
701    }
702
703    #[tokio::test]
704    async fn test_expiration() {
705        let storage = Arc::new(MemoryStorage::new());
706        // Create manager with very short expiration
707        let manager = DeviceAuthManager::with_settings(
708            storage,
709            "https://example.com/device".to_string(),
710            Duration::from_millis(100),
711            Duration::from_secs(1),
712        );
713
714        let request = DeviceAuthorizationRequest {
715            client_id: "test_client".to_string(),
716            scope: None,
717        };
718
719        let response = manager.create_authorization(request).await.unwrap();
720
721        // Wait for expiration
722        sleep(Duration::from_millis(150)).await;
723
724        // Poll should return expired
725        let result = manager.poll_authorization(&response.device_code).await;
726        assert!(result.is_err());
727        let err = result.unwrap_err();
728        assert!(err.to_string().contains("expired"));
729    }
730
731    #[tokio::test]
732    async fn test_chainable_expiration_and_interval() {
733        let storage = Arc::new(MemoryStorage::new());
734        let manager = DeviceAuthManager::new(storage, "https://example.com/device".to_string())
735            .expiration(Duration::from_secs(300))
736            .interval(Duration::from_secs(10));
737
738        let request = DeviceAuthorizationRequest {
739            client_id: "test_client".to_string(),
740            scope: None,
741        };
742
743        let response = manager.create_authorization(request).await.unwrap();
744        assert_eq!(response.expires_in, 300);
745        assert_eq!(response.interval, 10);
746    }
747}