1use 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")]
50pub struct EnhancedDeviceFlowMethod {
51 pub client_id: String,
53 pub client_secret: Option<String>,
55 pub auth_url: String,
57 pub token_url: String,
59 pub device_auth_url: String,
61 pub scopes: Vec<String>,
63 pub _polling_interval: Option<std::time::Duration>,
65 pub enable_qr_code: bool,
67}
68
69#[cfg(feature = "enhanced-device-flow")]
70impl std::fmt::Debug for EnhancedDeviceFlowMethod {
71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72 let mut d = f.debug_struct("EnhancedDeviceFlowMethod");
73 d.field("client_id", &self.client_id);
74 d.field(
75 "client_secret",
76 &crate::utils::redact::redacted(&self.client_secret),
77 );
78 d.field("auth_url", &self.auth_url);
79 d.field("token_url", &self.token_url);
80 d.field("device_auth_url", &self.device_auth_url);
81 d.field("scopes", &self.scopes);
82 d.field("_polling_interval", &self._polling_interval);
83 d.field("enable_qr_code", &self.enable_qr_code);
84 d.finish()
85 }
86}
87
88#[cfg(feature = "enhanced-device-flow")]
89impl EnhancedDeviceFlowMethod {
90 pub fn new(
92 client_id: String,
93 client_secret: Option<String>,
94 auth_url: String,
95 token_url: String,
96 device_auth_url: String,
97 ) -> Self {
98 Self {
99 client_id,
100 client_secret,
101 auth_url,
102 token_url,
103 device_auth_url,
104 scopes: Vec::new(),
105 _polling_interval: None,
106 enable_qr_code: true,
107 }
108 }
109
110 pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
112 self.scopes = scopes;
113 self
114 }
115
116 pub fn with_polling_interval(mut self, interval: std::time::Duration) -> Self {
118 self._polling_interval = Some(interval);
119 self
120 }
121
122 pub fn with_qr_code(mut self, enable: bool) -> Self {
124 self.enable_qr_code = enable;
125 self
126 }
127
128 pub async fn initiate_device_flow(&self) -> Result<DeviceFlowInstructions> {
130 let client = reqwest::Client::new();
131 let mut params = std::collections::HashMap::new();
132 params.insert("client_id", self.client_id.clone());
133 if !self.scopes.is_empty() {
134 params.insert("scope", self.scopes.join(" "));
135 }
136
137 let res = client
138 .post(&self.device_auth_url)
139 .form(¶ms)
140 .send()
141 .await
142 .map_err(AuthError::Network)?;
143
144 if !res.status().is_success() {
145 return Err(AuthError::config(&format!(
146 "Device auth request failed: {}",
147 res.status()
148 )));
149 }
150
151 #[derive(Deserialize)]
152 struct DeviceAuthResponse {
153 #[allow(
154 dead_code,
155 reason = "RFC 8628 device authorization response field; deserialized with the rest of the response but not used by this client"
156 )]
157 device_code: String,
158 user_code: String,
159 verification_uri: String,
160 verification_uri_complete: Option<String>,
161 expires_in: u64,
162 interval: Option<u64>,
163 }
164
165 let data: DeviceAuthResponse = res.json().await.map_err(AuthError::Network)?;
166
167 Ok(DeviceFlowInstructions {
168 verification_uri: data.verification_uri,
169 verification_uri_complete: data.verification_uri_complete,
170 user_code: data.user_code,
171 qr_code: None, expires_in: data.expires_in,
173 interval: data.interval.unwrap_or(5),
174 })
175 }
176}
177
178#[cfg(feature = "enhanced-device-flow")]
179impl AuthMethod for EnhancedDeviceFlowMethod {
180 type MethodResult = MethodResult;
181 type AuthToken = AuthToken;
182
183 async fn authenticate(
184 &self,
185 credential: Credential,
186 _metadata: CredentialMetadata,
187 ) -> Result<Self::MethodResult> {
188 let (device_code, _interval) = match credential {
189 Credential::EnhancedDeviceFlow {
190 device_code,
191 interval,
192 ..
193 } => (device_code, interval),
194 _ => {
195 return Ok(MethodResult::Failure {
196 reason: "Invalid credential type for enhanced device flow".to_string(),
197 });
198 }
199 };
200
201 let client = reqwest::Client::new();
202 let mut params = std::collections::HashMap::new();
203 params.insert("client_id", self.client_id.clone());
204 params.insert(
205 "grant_type",
206 "urn:ietf:params:oauth:grant-type:device_code".to_string(),
207 );
208 params.insert("device_code", device_code);
209
210 if let Some(secret) = &self.client_secret {
211 params.insert("client_secret", secret.clone());
212 }
213
214 let res = client
215 .post(&self.token_url)
216 .form(¶ms)
217 .send()
218 .await
219 .map_err(AuthError::Network)?;
220
221 if !res.status().is_success() {
222 let error_text = res.text().await.unwrap_or_default();
223 return Ok(MethodResult::Failure {
225 reason: format!("Token exchange failed: {}", error_text),
226 });
227 }
228
229 #[derive(Deserialize)]
230 struct TokenResponse {
231 access_token: String,
232 refresh_token: Option<String>,
233 expires_in: Option<u64>,
234 }
235
236 let token_data: TokenResponse = res.json().await.map_err(AuthError::Network)?;
237
238 let user_id = extract_sub_from_jwt(&token_data.access_token)
240 .unwrap_or_else(|| "unknown_device_user".to_string());
241
242 let expires_in = std::time::Duration::from_secs(token_data.expires_in.unwrap_or(3600));
243
244 let mut token = AuthToken::new(user_id, &token_data.access_token, expires_in, self.name());
245 token.refresh_token = token_data.refresh_token;
246
247 Ok(MethodResult::Success(Box::new(token)))
248 }
249
250 fn name(&self) -> &str {
251 "enhanced_device_flow"
252 }
253
254 fn validate_config(&self) -> Result<()> {
255 if self.client_id.is_empty() {
256 return Err(AuthError::config("Client ID is required"));
257 }
258 if self.auth_url.is_empty() {
259 return Err(AuthError::config("Authorization URL is required"));
260 }
261 if self.token_url.is_empty() {
262 return Err(AuthError::config("Token URL is required"));
263 }
264 if self.device_auth_url.is_empty() {
265 return Err(AuthError::config("Device authorization URL is required"));
266 }
267 Ok(())
268 }
269}
270
271#[cfg(not(feature = "enhanced-device-flow"))]
273pub struct EnhancedDeviceFlowMethod {
274 client_id: String,
276 client_secret: Option<String>,
277 auth_url: String,
278 token_url: String,
279 device_auth_url: String,
280}
281
282#[cfg(not(feature = "enhanced-device-flow"))]
283impl std::fmt::Debug for EnhancedDeviceFlowMethod {
284 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285 let mut d = f.debug_struct("EnhancedDeviceFlowMethod");
286 d.field("client_id", &self.client_id);
287 d.field(
288 "client_secret",
289 &crate::utils::redact::redacted(&self.client_secret),
290 );
291 d.field("auth_url", &self.auth_url);
292 d.field("token_url", &self.token_url);
293 d.field("device_auth_url", &self.device_auth_url);
294 d.finish()
295 }
296}
297
298#[cfg(not(feature = "enhanced-device-flow"))]
299impl EnhancedDeviceFlowMethod {
300 pub fn new(
301 client_id: String,
302 client_secret: Option<String>,
303 auth_url: String,
304 token_url: String,
305 device_auth_url: String,
306 ) -> Self {
307 Self {
308 client_id,
309 client_secret,
310 auth_url,
311 token_url,
312 device_auth_url,
313 }
314 }
315}
316
317#[cfg(not(feature = "enhanced-device-flow"))]
318impl AuthMethod for EnhancedDeviceFlowMethod {
319 type MethodResult = MethodResult;
320 type AuthToken = AuthToken;
321
322 async fn authenticate(
323 &self,
324 _credential: Credential,
325 _metadata: CredentialMetadata,
326 ) -> Result<Self::MethodResult> {
327 Err(AuthError::config(format!(
329 "Enhanced device flow requires 'enhanced-device-flow' feature. Configured for client '{}' with auth_url: {}, token_url: {}, device_auth_url: {}",
330 self.client_id, self.auth_url, self.token_url, self.device_auth_url
331 )))
332 }
333
334 fn name(&self) -> &str {
335 "enhanced_device_flow"
336 }
337
338 fn validate_config(&self) -> Result<()> {
339 if self.client_id.is_empty() {
341 return Err(AuthError::config("client_id cannot be empty"));
342 }
343 if self.auth_url.is_empty() {
344 return Err(AuthError::config("auth_url cannot be empty"));
345 }
346 if self.token_url.is_empty() {
347 return Err(AuthError::config("token_url cannot be empty"));
348 }
349 if self.device_auth_url.is_empty() {
350 return Err(AuthError::config("device_auth_url cannot be empty"));
351 }
352
353 if self.client_secret.is_some() {
355 tracing::info!(
356 "Enhanced device flow configured for confidential client: {}",
357 self.client_id
358 );
359 } else {
360 tracing::info!(
361 "Enhanced device flow configured for public client: {}",
362 self.client_id
363 );
364 }
365
366 Err(AuthError::config(
367 "Enhanced device flow requires 'enhanced-device-flow' feature to be enabled at compile time",
368 ))
369 }
370}
371
372pub struct EnhancedDevice {
374 pub device_id: String,
376}
377
378impl EnhancedDevice {
379 pub fn new(device_id: String) -> Self {
381 Self { device_id }
382 }
383
384 pub async fn authenticate(&self, challenge: &str) -> Result<bool> {
386 if challenge.is_empty() {
389 tracing::warn!("Empty challenge provided for device authentication");
390 return Ok(false);
391 }
392
393 tracing::info!(
394 "Starting enhanced device authentication for device: {}",
395 self.device_id
396 );
397
398 if !self.verify_device_binding().await? {
403 tracing::warn!("Device binding verification failed for: {}", self.device_id);
404 return Ok(false);
405 }
406
407 if !self.check_device_trust_signals().await? {
409 tracing::warn!("Device trust signals check failed for: {}", self.device_id);
410 return Ok(false);
411 }
412
413 if !self.validate_device_challenge(challenge).await? {
415 tracing::warn!("Device challenge validation failed for: {}", self.device_id);
416 return Ok(false);
417 }
418
419 tracing::info!(
420 "Enhanced device authentication successful for: {}",
421 self.device_id
422 );
423 Ok(true)
424 }
425
426 async fn verify_device_binding(&self) -> Result<bool> {
428 tracing::debug!("Verifying device binding for: {}", self.device_id);
429
430 if self.device_id.len() < 8 {
438 tracing::warn!("Device ID too short for secure binding");
439 return Ok(false);
440 }
441
442 if !self
444 .device_id
445 .chars()
446 .all(|c| c.is_ascii_alphanumeric() || c == '-')
447 {
448 tracing::warn!("Invalid device ID format");
449 return Ok(false);
450 }
451
452 tracing::debug!("Device binding verified for: {}", self.device_id);
453 Ok(true)
454 }
455
456 async fn check_device_trust_signals(&self) -> Result<bool> {
458 tracing::debug!("Checking device trust signals for: {}", self.device_id);
459
460 let trust_score = self.calculate_trust_score().await;
470
471 if trust_score < 0.7 {
472 tracing::warn!(
473 "Device trust score too low: {} for device: {}",
474 trust_score,
475 self.device_id
476 );
477 return Ok(false);
478 }
479
480 tracing::info!(
481 "Device trust signals validated (score: {}) for: {}",
482 trust_score,
483 self.device_id
484 );
485 Ok(true)
486 }
487
488 async fn calculate_trust_score(&self) -> f64 {
490 let mut score = 1.0_f64;
493
494 if self.device_id.contains("new") {
496 score -= 0.1;
497 }
498
499 if self.device_id.contains("test") {
501 score -= 0.2;
502 }
503
504 score.clamp(0.0, 1.0)
506 }
507
508 async fn validate_device_challenge(&self, challenge: &str) -> Result<bool> {
510 tracing::debug!("Validating device challenge for: {}", self.device_id);
511
512 if challenge.len() < 16 {
520 tracing::warn!(
521 "Device challenge too short ({} chars) for: {}",
522 challenge.len(),
523 self.device_id
524 );
525 return Ok(false);
526 }
527
528 let valid_chars = challenge
531 .chars()
532 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '-' | '_' | '='));
533
534 if !valid_chars {
535 tracing::warn!(
536 "Device challenge contains invalid characters for: {}",
537 self.device_id
538 );
539 return Ok(false);
540 }
541
542 tracing::debug!("Device challenge validation successful");
543 Ok(true)
544 }
545}
546
547#[cfg(test)]
548mod tests {
549 use super::*;
550
551 fn device(id: &str) -> EnhancedDevice {
552 EnhancedDevice::new(id.to_string())
553 }
554
555 #[test]
558 fn test_new_stores_device_id() {
559 let d = device("my-device-abc123");
560 assert_eq!(d.device_id, "my-device-abc123");
561 }
562
563 #[tokio::test]
566 async fn test_device_binding_valid_uuid_format() {
567 let d = device("550e8400-e29b-41d4-a716-446655440000");
568 let result = d.verify_device_binding().await.unwrap();
570 assert!(result, "UUID-format device ID should pass binding check");
571 }
572
573 #[tokio::test]
574 async fn test_device_binding_too_short() {
575 let d = device("abc123"); assert!(
577 !d.verify_device_binding().await.unwrap(),
578 "Device IDs shorter than 8 chars must fail"
579 );
580 }
581
582 #[tokio::test]
583 async fn test_device_binding_invalid_chars() {
584 let d = device("device@with#special!chars");
585 assert!(
586 !d.verify_device_binding().await.unwrap(),
587 "Device IDs with special chars (not alphanumeric/-) must fail"
588 );
589 }
590
591 #[tokio::test]
594 async fn test_trust_score_clean_device_is_1_0() {
595 let d = device("abcd1234efgh5678"); let score = d.calculate_trust_score().await;
597 assert!(
598 (score - 1.0).abs() < f64::EPSILON,
599 "Clean device should score 1.0, got {score}"
600 );
601 }
602
603 #[tokio::test]
604 async fn test_trust_score_new_device_is_reduced() {
605 let d = device("newdevice-abcd1234");
606 let score = d.calculate_trust_score().await;
607 assert!(
608 score < 1.0,
609 "Device containing 'new' should have score < 1.0, got {score}"
610 );
611 assert!(
612 (score - 0.9).abs() < f64::EPSILON,
613 "Expected 0.9, got {score}"
614 );
615 }
616
617 #[tokio::test]
618 async fn test_trust_score_test_device_is_reduced() {
619 let d = device("testdevice-abcd1234");
620 let score = d.calculate_trust_score().await;
621 assert!(
622 (score - 0.8).abs() < f64::EPSILON,
623 "Expected 0.8 for 'test' device, got {score}"
624 );
625 }
626
627 #[tokio::test]
628 async fn test_trust_score_new_and_test_device() {
629 let d = device("new-testdevice-abcd1234");
630 let score = d.calculate_trust_score().await;
631 assert!(
633 (score - 0.7).abs() < f64::EPSILON,
634 "Expected 0.7 for device containing both 'new' and 'test', got {score}"
635 );
636 }
637
638 #[tokio::test]
639 async fn test_trust_score_always_in_range() {
640 for id in &[
642 "new-test-device-id",
643 "new-new-new-test-test-test-device",
644 "aaaaaaaaaaaaa",
645 ] {
646 let score = device(id).calculate_trust_score().await;
647 assert!(
648 (0.0f64..=1.0).contains(&score),
649 "Trust score {score} out of range [0,1] for '{id}'"
650 );
651 }
652 }
653
654 #[tokio::test]
657 async fn test_challenge_valid_hex_16_chars() {
658 let d = device("abcdefgh-1234");
659 let challenge = "0123456789abcdef"; assert!(d.validate_device_challenge(challenge).await.unwrap());
661 }
662
663 #[tokio::test]
664 async fn test_challenge_valid_base64url() {
665 let d = device("abcdefgh-1234");
666 let challenge = "SGVsbG8gV29ybGQh"; assert!(d.validate_device_challenge(challenge).await.unwrap());
668 }
669
670 #[tokio::test]
671 async fn test_challenge_too_short() {
672 let d = device("abcdefgh-1234");
673 assert!(
674 !d.validate_device_challenge("short123").await.unwrap(),
675 "Challenge < 16 chars must be rejected"
676 );
677 }
678
679 #[tokio::test]
680 async fn test_challenge_empty() {
681 let d = device("abcdefgh-1234");
682 assert!(!d.validate_device_challenge("").await.unwrap());
683 }
684
685 #[tokio::test]
686 async fn test_challenge_invalid_chars() {
687 let d = device("abcdefgh-1234");
688 let challenge = "Hello World!!!!!";
690 assert!(
691 !d.validate_device_challenge(challenge).await.unwrap(),
692 "Challenge with spaces/exclamation marks must be rejected"
693 );
694 }
695
696 #[tokio::test]
699 async fn test_authenticate_empty_challenge_returns_false() {
700 let d = device("abcdefgh-1234");
701 assert!(!d.authenticate("").await.unwrap());
702 }
703
704 #[tokio::test]
705 async fn test_authenticate_valid_device_and_challenge() {
706 let d = device("550e8400-e29b-41d4-a716-446655440000");
708 let challenge = "SGVsbG8gV29ybGQh"; assert!(
711 d.authenticate(challenge).await.unwrap(),
712 "Valid device + valid challenge should authenticate"
713 );
714 }
715
716 #[tokio::test]
717 async fn test_authenticate_short_device_id_fails() {
718 let d = device("tiny"); let challenge = "SGVsbG8gV29ybGQh";
720 assert!(
721 !d.authenticate(challenge).await.unwrap(),
722 "Short device ID must fail authentication"
723 );
724 }
725
726 #[tokio::test]
727 async fn test_authenticate_at_minimum_trust_score_passes() {
728 let d = device("new-test-device-abcde"); let challenge = "SGVsbG8gV29ybGQh";
732 assert!(
733 d.authenticate(challenge).await.unwrap(),
734 "Device at minimum trust score (0.7) should still authenticate"
735 );
736 }
737}