auth_framework/methods/enhanced_device/
mod.rs1use 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#[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#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct DeviceFlowInstructions {
34 pub verification_uri: String,
36 pub verification_uri_complete: Option<String>,
38 pub user_code: String,
40 pub qr_code: Option<String>,
42 pub expires_in: u64,
44 pub interval: u64,
46}
47
48#[cfg(feature = "enhanced-device-flow")]
50#[derive(Debug)]
51pub struct EnhancedDeviceFlowMethod {
52 pub client_id: String,
54 pub client_secret: Option<String>,
56 pub auth_url: String,
58 pub token_url: String,
60 pub device_auth_url: String,
62 pub scopes: Vec<String>,
64 pub _polling_interval: Option<std::time::Duration>,
66 pub enable_qr_code: bool,
68}
69
70#[cfg(feature = "enhanced-device-flow")]
71impl EnhancedDeviceFlowMethod {
72 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 pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
94 self.scopes = scopes;
95 self
96 }
97
98 pub fn with_polling_interval(mut self, interval: std::time::Duration) -> Self {
100 self._polling_interval = Some(interval);
101 self
102 }
103
104 pub fn with_qr_code(mut self, enable: bool) -> Self {
106 self.enable_qr_code = enable;
107 self
108 }
109
110 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(¶ms)
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, 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(¶ms)
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 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 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#[cfg(not(feature = "enhanced-device-flow"))]
255#[derive(Debug)]
256pub struct EnhancedDeviceFlowMethod {
257 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 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 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 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
339pub struct EnhancedDevice {
341 pub device_id: String,
343}
344
345impl EnhancedDevice {
346 pub fn new(device_id: String) -> Self {
348 Self { device_id }
349 }
350
351 pub async fn authenticate(&self, challenge: &str) -> Result<bool> {
353 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 if !self.verify_device_binding().await? {
370 tracing::warn!("Device binding verification failed for: {}", self.device_id);
371 return Ok(false);
372 }
373
374 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 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 async fn verify_device_binding(&self) -> Result<bool> {
395 tracing::debug!("Verifying device binding for: {}", self.device_id);
396
397 if self.device_id.len() < 8 {
405 tracing::warn!("Device ID too short for secure binding");
406 return Ok(false);
407 }
408
409 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 async fn check_device_trust_signals(&self) -> Result<bool> {
425 tracing::debug!("Checking device trust signals for: {}", self.device_id);
426
427 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 async fn calculate_trust_score(&self) -> f64 {
457 let mut score = 1.0_f64;
460
461 if self.device_id.contains("new") {
463 score -= 0.1;
464 }
465
466 if self.device_id.contains("test") {
468 score -= 0.2;
469 }
470
471 score.clamp(0.0, 1.0)
473 }
474
475 async fn validate_device_challenge(&self, challenge: &str) -> Result<bool> {
477 tracing::debug!("Validating device challenge for: {}", self.device_id);
478
479 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 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 #[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 #[tokio::test]
533 async fn test_device_binding_valid_uuid_format() {
534 let d = device("550e8400-e29b-41d4-a716-446655440000");
535 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"); 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 #[tokio::test]
561 async fn test_trust_score_clean_device_is_1_0() {
562 let d = device("abcd1234efgh5678"); 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 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 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 #[tokio::test]
624 async fn test_challenge_valid_hex_16_chars() {
625 let d = device("abcdefgh-1234");
626 let challenge = "0123456789abcdef"; 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"; 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 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 #[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 let d = device("550e8400-e29b-41d4-a716-446655440000");
675 let challenge = "SGVsbG8gV29ybGQh"; 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"); 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 let d = device("new-test-device-abcde"); 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}