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(
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#[derive(Clone, Deserialize)]
71pub struct DeviceTokenRequest {
72 pub grant_type: String,
74
75 pub device_code: String,
77
78 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#[derive(Clone, Serialize, Deserialize)]
97pub struct StoredDeviceAuthorization {
98 pub device_code: String,
100
101 pub user_code: String,
103
104 pub client_id: String,
106
107 pub scope: Option<String>,
109
110 pub status: DeviceAuthorizationStatus,
112
113 pub user_id: Option<String>,
115
116 pub created_at: SystemTime,
118
119 pub expires_at: SystemTime,
121
122 pub last_poll: Option<SystemTime>,
124
125 #[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub enum DeviceAuthorizationStatus {
157 Pending,
159 Authorized,
161 Denied,
163 Expired,
165}
166
167use std::fmt;
169
170#[derive(Clone)]
171pub struct DeviceAuthManager {
172 storage: Arc<dyn AuthStorage>,
174
175 authorizations: Arc<tokio::sync::RwLock<HashMap<String, StoredDeviceAuthorization>>>,
177
178 default_expiration: Duration,
180
181 min_interval: Duration,
183
184 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 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), min_interval: Duration::from_secs(5), verification_uri,
208 }
209 }
210
211 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 pub fn expiration(mut self, expiration: Duration) -> Self {
231 self.default_expiration = expiration;
232 self
233 }
234
235 pub fn interval(mut self, interval: Duration) -> Self {
239 self.min_interval = interval;
240 self
241 }
242
243 pub async fn create_authorization(
245 &self,
246 request: DeviceAuthorizationRequest,
247 ) -> Result<DeviceAuthorizationResponse> {
248 self.validate_request(&request)?;
250
251 let device_code = format!("dc_{}", Uuid::new_v4().simple());
253 let user_code = self.generate_user_code();
254
255 let now = SystemTime::now();
257 let expires_at = now + self.default_expiration;
258
259 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 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 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 let mut authorizations = self.authorizations.write().await;
305 authorizations.insert(device_code.clone(), stored);
306
307 self.cleanup_expired(&mut authorizations, now);
309
310 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 pub async fn poll_authorization(&self, device_code: &str) -> Result<StoredDeviceAuthorization> {
326 let device_key = format!("device_code:{}", device_code);
327
328 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 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 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 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 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 stored.last_poll = Some(now);
382
383 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(); let mut authorizations = self.authorizations.write().await;
398 authorizations.insert(device_code.to_string(), stored.clone());
399
400 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 pub async fn authorize_device(&self, user_code: &str, user_id: &str) -> Result<()> {
418 let user_key = format!("user_code:{}", user_code);
419
420 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 let now = SystemTime::now();
434 if now > stored.expires_at {
435 return Err(AuthError::auth_method("device_auth", "Device code expired"));
436 }
437
438 stored.status = DeviceAuthorizationStatus::Authorized;
440 stored.user_id = Some(user_id.to_string());
441
442 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 let mut authorizations = self.authorizations.write().await;
466 authorizations.insert(stored.device_code.clone(), stored);
467
468 Ok(())
469 }
470
471 pub async fn deny_device(&self, user_code: &str) -> Result<()> {
473 let user_key = format!("user_code:{}", user_code);
474
475 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 stored.status = DeviceAuthorizationStatus::Denied;
489
490 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 let mut authorizations = self.authorizations.write().await;
514 authorizations.insert(stored.device_code.clone(), stored);
515
516 Ok(())
517 }
518
519 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 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 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 Ok(())
553 }
554
555 fn generate_user_code(&self) -> String {
557 use rand::RngExt;
558 const CHARS: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; let mut rng = rand::rng();
560
561 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 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); 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 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 manager
648 .authorize_device(&response.user_code, "user_123")
649 .await
650 .unwrap();
651
652 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 manager.deny_device(&response.user_code).await.unwrap();
674
675 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 let _ = manager.poll_authorization(&response.device_code).await;
695
696 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 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 sleep(Duration::from_millis(150)).await;
723
724 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}