1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct DeviceAuthorizationRequest {
18 pub client_id: String,
20
21 pub scope: Option<String>,
23}
24
25#[derive(Clone, Serialize, Deserialize)]
27pub struct DeviceAuthorizationResponse {
28 pub device_code: String,
30
31 pub user_code: String,
33
34 pub verification_uri: String,
36
37 pub verification_uri_complete: Option<String>,
39
40 pub interval: u64,
42
43 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#[derive(Clone, Deserialize)]
65pub struct DeviceTokenRequest {
66 pub grant_type: String,
68
69 pub device_code: String,
71
72 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#[derive(Clone, Serialize, Deserialize)]
91pub struct StoredDeviceAuthorization {
92 pub device_code: String,
94
95 pub user_code: String,
97
98 pub client_id: String,
100
101 pub scope: Option<String>,
103
104 pub status: DeviceAuthorizationStatus,
106
107 pub user_id: Option<String>,
109
110 pub created_at: SystemTime,
112
113 pub expires_at: SystemTime,
115
116 pub last_poll: Option<SystemTime>,
118
119 #[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
147pub enum DeviceAuthorizationStatus {
148 Pending,
150 Authorized,
152 Denied,
154 Expired,
156}
157
158use std::fmt;
160
161#[derive(Clone)]
162pub struct DeviceAuthManager {
163 storage: Arc<dyn AuthStorage>,
165
166 authorizations: Arc<tokio::sync::RwLock<HashMap<String, StoredDeviceAuthorization>>>,
168
169 default_expiration: Duration,
171
172 min_interval: Duration,
174
175 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 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), min_interval: Duration::from_secs(5), verification_uri,
199 }
200 }
201
202 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 pub fn expiration(mut self, expiration: Duration) -> Self {
222 self.default_expiration = expiration;
223 self
224 }
225
226 pub fn interval(mut self, interval: Duration) -> Self {
230 self.min_interval = interval;
231 self
232 }
233
234 pub async fn create_authorization(
236 &self,
237 request: DeviceAuthorizationRequest,
238 ) -> Result<DeviceAuthorizationResponse> {
239 self.validate_request(&request)?;
241
242 let device_code = format!("dc_{}", Uuid::new_v4().simple());
244 let user_code = self.generate_user_code();
245
246 let now = SystemTime::now();
248 let expires_at = now + self.default_expiration;
249
250 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 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 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 let mut authorizations = self.authorizations.write().await;
296 authorizations.insert(device_code.clone(), stored);
297
298 self.cleanup_expired(&mut authorizations, now);
300
301 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 pub async fn poll_authorization(&self, device_code: &str) -> Result<StoredDeviceAuthorization> {
317 let device_key = format!("device_code:{}", device_code);
318
319 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 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 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 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 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 stored.last_poll = Some(now);
373
374 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(); let mut authorizations = self.authorizations.write().await;
389 authorizations.insert(device_code.to_string(), stored.clone());
390
391 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 pub async fn authorize_device(&self, user_code: &str, user_id: &str) -> Result<()> {
409 let user_key = format!("user_code:{}", user_code);
410
411 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 let now = SystemTime::now();
425 if now > stored.expires_at {
426 return Err(AuthError::auth_method("device_auth", "Device code expired"));
427 }
428
429 stored.status = DeviceAuthorizationStatus::Authorized;
431 stored.user_id = Some(user_id.to_string());
432
433 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 let mut authorizations = self.authorizations.write().await;
457 authorizations.insert(stored.device_code.clone(), stored);
458
459 Ok(())
460 }
461
462 pub async fn deny_device(&self, user_code: &str) -> Result<()> {
464 let user_key = format!("user_code:{}", user_code);
465
466 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 stored.status = DeviceAuthorizationStatus::Denied;
480
481 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 let mut authorizations = self.authorizations.write().await;
505 authorizations.insert(stored.device_code.clone(), stored);
506
507 Ok(())
508 }
509
510 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 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 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 Ok(())
544 }
545
546 fn generate_user_code(&self) -> String {
548 use rand::RngExt;
549 const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; let mut rng = rand::rng();
551
552 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 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); 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 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 manager
639 .authorize_device(&response.user_code, "user_123")
640 .await
641 .unwrap();
642
643 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 manager.deny_device(&response.user_code).await.unwrap();
665
666 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 let _ = manager.poll_authorization(&response.device_code).await;
686
687 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 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 sleep(Duration::from_millis(150)).await;
714
715 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}