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