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