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