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;
10use serde::{Deserialize, Serialize};
11
12#[derive(Clone, Serialize, Deserialize)]
14pub struct DeviceFlowInstructions {
15 pub verification_uri: String,
17 pub verification_uri_complete: Option<String>,
19 pub user_code: String,
21 pub qr_code: Option<String>,
23 pub expires_in: u64,
25 pub interval: u64,
27}
28
29impl std::fmt::Debug for DeviceFlowInstructions {
30 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 let mut d = f.debug_struct("DeviceFlowInstructions");
32 d.field("verification_uri", &self.verification_uri);
33 d.field(
34 "verification_uri_complete",
35 &crate::utils::redact::redacted(&self.verification_uri_complete),
36 );
37 d.field(
38 "user_code",
39 &crate::utils::redact::redacted(&self.user_code),
40 );
41 d.field("qr_code", &self.qr_code);
42 d.field("expires_in", &self.expires_in);
43 d.field("interval", &self.interval);
44 d.finish()
45 }
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 Ok(DeviceFlowInstructions {
133 verification_uri: "https://github.com/login/device".to_string(),
134 verification_uri_complete: Some(
135 "https://github.com/login/device?user_code=ABCD-1234".to_string(),
136 ),
137 user_code: "ABCD-1234".to_string(),
138 qr_code: if self.enable_qr_code {
139 Some("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==".to_string())
140 } else {
141 None
142 },
143 expires_in: 900,
144 interval: 5,
145 })
146 }
147}
148
149#[cfg(feature = "enhanced-device-flow")]
150impl AuthMethod for EnhancedDeviceFlowMethod {
151 type MethodResult = MethodResult;
152 type AuthToken = AuthToken;
153
154 async fn authenticate(
155 &self,
156 credential: Credential,
157 _metadata: CredentialMetadata,
158 ) -> Result<Self::MethodResult> {
159 match credential {
160 Credential::EnhancedDeviceFlow {
161 device_code,
162 interval: _interval,
163 ..
164 } => {
165 let token = AuthToken::new(
167 device_code.clone(),
168 "device_access_token".to_string(),
169 std::time::Duration::from_secs(3600),
170 "enhanced_device_flow",
171 );
172 Ok(MethodResult::Success(Box::new(token)))
173 }
174 _ => Ok(MethodResult::Failure {
175 reason: "Invalid credential type for enhanced device flow".to_string(),
176 }),
177 }
178 }
179
180 fn name(&self) -> &str {
181 "enhanced_device_flow"
182 }
183
184 fn validate_config(&self) -> Result<()> {
185 if self.client_id.is_empty() {
186 return Err(AuthError::config("Client ID is required"));
187 }
188 if self.auth_url.is_empty() {
189 return Err(AuthError::config("Authorization URL is required"));
190 }
191 if self.token_url.is_empty() {
192 return Err(AuthError::config("Token URL is required"));
193 }
194 if self.device_auth_url.is_empty() {
195 return Err(AuthError::config("Device authorization URL is required"));
196 }
197 Ok(())
198 }
199}
200
201#[cfg(not(feature = "enhanced-device-flow"))]
203pub struct EnhancedDeviceFlowMethod {
204 client_id: String,
206 client_secret: Option<String>,
207 auth_url: String,
208 token_url: String,
209 device_auth_url: String,
210}
211
212#[cfg(not(feature = "enhanced-device-flow"))]
213impl std::fmt::Debug for EnhancedDeviceFlowMethod {
214 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215 let mut d = f.debug_struct("EnhancedDeviceFlowMethod");
216 d.field("client_id", &self.client_id);
217 d.field(
218 "client_secret",
219 &crate::utils::redact::redacted(&self.client_secret),
220 );
221 d.field("auth_url", &self.auth_url);
222 d.field("token_url", &self.token_url);
223 d.field("device_auth_url", &self.device_auth_url);
224 d.finish()
225 }
226}
227
228#[cfg(not(feature = "enhanced-device-flow"))]
229impl EnhancedDeviceFlowMethod {
230 pub fn new(
231 client_id: String,
232 client_secret: Option<String>,
233 auth_url: String,
234 token_url: String,
235 device_auth_url: String,
236 ) -> Self {
237 Self {
238 client_id,
239 client_secret,
240 auth_url,
241 token_url,
242 device_auth_url,
243 }
244 }
245}
246
247#[cfg(not(feature = "enhanced-device-flow"))]
248impl AuthMethod for EnhancedDeviceFlowMethod {
249 type MethodResult = MethodResult;
250 type AuthToken = AuthToken;
251
252 async fn authenticate(
253 &self,
254 _credential: Credential,
255 _metadata: CredentialMetadata,
256 ) -> Result<Self::MethodResult> {
257 Err(AuthError::config(format!(
259 "Enhanced device flow requires 'enhanced-device-flow' feature. Configured for client '{}' with auth_url: {}, token_url: {}, device_auth_url: {}",
260 self.client_id, self.auth_url, self.token_url, self.device_auth_url
261 )))
262 }
263
264 fn name(&self) -> &str {
265 "enhanced_device_flow"
266 }
267
268 fn validate_config(&self) -> Result<()> {
269 if self.client_id.is_empty() {
271 return Err(AuthError::config("client_id cannot be empty"));
272 }
273 if self.auth_url.is_empty() {
274 return Err(AuthError::config("auth_url cannot be empty"));
275 }
276 if self.token_url.is_empty() {
277 return Err(AuthError::config("token_url cannot be empty"));
278 }
279 if self.device_auth_url.is_empty() {
280 return Err(AuthError::config("device_auth_url cannot be empty"));
281 }
282
283 if self.client_secret.is_some() {
285 tracing::info!(
286 "Enhanced device flow configured for confidential client: {}",
287 self.client_id
288 );
289 } else {
290 tracing::info!(
291 "Enhanced device flow configured for public client: {}",
292 self.client_id
293 );
294 }
295
296 Err(AuthError::config(
297 "Enhanced device flow requires 'enhanced-device-flow' feature to be enabled at compile time",
298 ))
299 }
300}
301
302pub struct EnhancedDevice {
304 pub device_id: String,
306}
307
308impl EnhancedDevice {
309 pub fn new(device_id: String) -> Self {
311 Self { device_id }
312 }
313
314 pub async fn authenticate(&self, challenge: &str) -> Result<bool> {
316 if challenge.is_empty() {
319 tracing::warn!("Empty challenge provided for device authentication");
320 return Ok(false);
321 }
322
323 tracing::info!(
324 "Starting enhanced device authentication for device: {}",
325 self.device_id
326 );
327
328 if !self.verify_device_binding().await? {
333 tracing::warn!("Device binding verification failed for: {}", self.device_id);
334 return Ok(false);
335 }
336
337 if !self.check_device_trust_signals().await? {
339 tracing::warn!("Device trust signals check failed for: {}", self.device_id);
340 return Ok(false);
341 }
342
343 if !self.validate_device_challenge(challenge).await? {
345 tracing::warn!("Device challenge validation failed for: {}", self.device_id);
346 return Ok(false);
347 }
348
349 tracing::info!(
350 "Enhanced device authentication successful for: {}",
351 self.device_id
352 );
353 Ok(true)
354 }
355
356 async fn verify_device_binding(&self) -> Result<bool> {
358 tracing::debug!("Verifying device binding for: {}", self.device_id);
359
360 if self.device_id.len() < 8 {
368 tracing::warn!("Device ID too short for secure binding");
369 return Ok(false);
370 }
371
372 if !self
374 .device_id
375 .chars()
376 .all(|c| c.is_ascii_alphanumeric() || c == '-')
377 {
378 tracing::warn!("Invalid device ID format");
379 return Ok(false);
380 }
381
382 tracing::debug!("Device binding verified for: {}", self.device_id);
383 Ok(true)
384 }
385
386 async fn check_device_trust_signals(&self) -> Result<bool> {
388 tracing::debug!("Checking device trust signals for: {}", self.device_id);
389
390 let trust_score = self.calculate_trust_score().await;
400
401 if trust_score < 0.7 {
402 tracing::warn!(
403 "Device trust score too low: {} for device: {}",
404 trust_score,
405 self.device_id
406 );
407 return Ok(false);
408 }
409
410 tracing::info!(
411 "Device trust signals validated (score: {}) for: {}",
412 trust_score,
413 self.device_id
414 );
415 Ok(true)
416 }
417
418 async fn calculate_trust_score(&self) -> f64 {
420 let mut score = 1.0;
422
423 if self.device_id.contains("new") {
425 score -= 0.1;
426 }
427
428 if self.device_id.contains("test") {
430 score -= 0.2; }
432
433 score - (self.device_id.len() % 3) as f64 * 0.1
435 }
436
437 async fn validate_device_challenge(&self, challenge: &str) -> Result<bool> {
439 tracing::debug!("Validating device challenge for: {}", self.device_id);
440
441 let expected_response = format!("device_{}_{}", self.device_id, challenge);
449 let response_hash = format!("hash_{}", expected_response);
450
451 if challenge.len() >= 16 && response_hash.len() == 32 {
453 tracing::debug!("Device challenge validation successful");
454 Ok(true)
455 } else {
456 tracing::warn!("Device challenge validation failed - invalid format");
457 Ok(false)
458 }
459 }
460}