|
3 | 3 |
|
4 | 4 | //! OIDC authentication flows for CLI gateway login. |
5 | 5 | //! |
6 | | -//! Implements Authorization Code + PKCE (interactive browser flow) and |
7 | | -//! Client Credentials (CI/automation) `OAuth2` grant types against a |
8 | | -//! Keycloak-compatible OIDC provider. |
9 | | -
|
| 6 | +//! Implements Authorization Code + PKCE (interactive browser flow), |
| 7 | +//! Device Authorization Grant (headless flow), and Client Credentials |
| 8 | +//! (CI/automation) `OAuth2` grant types against a Keycloak-compatible |
| 9 | +//! OIDC provider. |
10 | 10 | use bytes::Bytes; |
11 | 11 | use http_body_util::Full; |
12 | 12 | use hyper::service::service_fn; |
@@ -37,6 +37,31 @@ struct OidcDiscovery { |
37 | 37 | issuer: String, |
38 | 38 | authorization_endpoint: String, |
39 | 39 | token_endpoint: String, |
| 40 | + device_authorization_endpoint: Option<String>, |
| 41 | +} |
| 42 | + |
| 43 | +/// Device authorization response from the provider. |
| 44 | +#[derive(Debug, Deserialize)] |
| 45 | +struct DeviceAuthorizationResponse { |
| 46 | + device_code: String, |
| 47 | + user_code: String, |
| 48 | + verification_uri: String, |
| 49 | + verification_uri_complete: Option<String>, |
| 50 | + expires_in: u64, |
| 51 | + #[serde(default = "default_interval")] |
| 52 | + interval: u64, |
| 53 | +} |
| 54 | + |
| 55 | +fn default_interval() -> u64 { |
| 56 | + 5 |
| 57 | +} |
| 58 | + |
| 59 | +/// Device token polling error responses (RFC 8628). |
| 60 | +#[derive(Debug, Deserialize)] |
| 61 | +struct DeviceTokenErrorResponse { |
| 62 | + error: String, |
| 63 | + #[serde(default)] |
| 64 | + error_description: String, |
40 | 65 | } |
41 | 66 |
|
42 | 67 | /// Discover OIDC endpoints from the issuer's well-known configuration. |
@@ -245,6 +270,163 @@ pub async fn oidc_client_credentials_flow( |
245 | 270 | )) |
246 | 271 | } |
247 | 272 |
|
| 273 | +/// Run the OIDC Device Authorization Grant flow (RFC 8628). |
| 274 | +/// |
| 275 | +/// Prompts the user to visit a verification URL and enter a code on any device |
| 276 | +/// with a browser. Polls the token endpoint until the user completes authorization |
| 277 | +/// or the device code expires. |
| 278 | +pub async fn oidc_device_code_flow( |
| 279 | + issuer: &str, |
| 280 | + client_id: &str, |
| 281 | + audience: Option<&str>, |
| 282 | + scopes: Option<&str>, |
| 283 | + insecure: bool, |
| 284 | +) -> Result<OidcTokenBundle> { |
| 285 | + let discovery = discover(issuer, insecure).await?; |
| 286 | + |
| 287 | + let device_auth_endpoint = discovery.device_authorization_endpoint.as_deref().ok_or_else(|| { |
| 288 | + miette::miette!( |
| 289 | + "The OIDC provider does not advertise a device_authorization_endpoint.\n\ |
| 290 | + Enable the device authorization grant on this client, or use client credentials for headless automation." |
| 291 | + ) |
| 292 | + })?; |
| 293 | + |
| 294 | + // Step 1: Request device and user codes |
| 295 | + let http = http_client(insecure); |
| 296 | + let scopes_param = build_scopes(scopes) |
| 297 | + .iter() |
| 298 | + .map(|s| s.to_string()) |
| 299 | + .collect::<Vec<_>>() |
| 300 | + .join(" "); |
| 301 | + |
| 302 | + let mut form_params = vec![("client_id", client_id), ("scope", &scopes_param)]; |
| 303 | + |
| 304 | + // Add audience if present |
| 305 | + let audience_str; |
| 306 | + if let Some(aud) = audience { |
| 307 | + audience_str = aud.to_string(); |
| 308 | + form_params.push(("audience", &audience_str)); |
| 309 | + } |
| 310 | + |
| 311 | + let device_auth_resp = http |
| 312 | + .post(device_auth_endpoint) |
| 313 | + .form(&form_params) |
| 314 | + .send() |
| 315 | + .await |
| 316 | + .into_diagnostic()?; |
| 317 | + |
| 318 | + if !device_auth_resp.status().is_success() { |
| 319 | + let status = device_auth_resp.status(); |
| 320 | + let body = device_auth_resp.text().await.unwrap_or_default(); |
| 321 | + return Err(miette::miette!( |
| 322 | + "Device authorization request failed (status {status}): {body}" |
| 323 | + )); |
| 324 | + } |
| 325 | + |
| 326 | + let device_auth: DeviceAuthorizationResponse = |
| 327 | + device_auth_resp.json().await.into_diagnostic()?; |
| 328 | + |
| 329 | + // Step 2: Display instructions to the user |
| 330 | + eprintln!(); |
| 331 | + eprintln!(" To authenticate, visit:"); |
| 332 | + if let Some(uri_complete) = &device_auth.verification_uri_complete { |
| 333 | + eprintln!(" {uri_complete}"); |
| 334 | + } else { |
| 335 | + eprintln!(" {}", device_auth.verification_uri); |
| 336 | + eprintln!(); |
| 337 | + eprintln!(" And enter this code:"); |
| 338 | + eprintln!(" {}", device_auth.user_code); |
| 339 | + } |
| 340 | + eprintln!(); |
| 341 | + eprintln!(" Waiting for authorization..."); |
| 342 | + |
| 343 | + // Step 3: Poll the token endpoint |
| 344 | + let start_time = std::time::Instant::now(); |
| 345 | + let expires_duration = Duration::from_secs(device_auth.expires_in); |
| 346 | + let mut poll_interval = Duration::from_secs(device_auth.interval); |
| 347 | + |
| 348 | + loop { |
| 349 | + if start_time.elapsed() >= expires_duration { |
| 350 | + return Err(miette::miette!( |
| 351 | + "Device code expired after {} seconds. Please try again.", |
| 352 | + device_auth.expires_in |
| 353 | + )); |
| 354 | + } |
| 355 | + |
| 356 | + tokio::time::sleep(poll_interval).await; |
| 357 | + |
| 358 | + let token_params = vec![ |
| 359 | + ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"), |
| 360 | + ("device_code", &device_auth.device_code), |
| 361 | + ("client_id", client_id), |
| 362 | + ]; |
| 363 | + |
| 364 | + let poll_resp = http |
| 365 | + .post(&discovery.token_endpoint) |
| 366 | + .form(&token_params) |
| 367 | + .send() |
| 368 | + .await |
| 369 | + .into_diagnostic()?; |
| 370 | + |
| 371 | + let status = poll_resp.status(); |
| 372 | + |
| 373 | + if status.is_success() { |
| 374 | + // Success! Parse the token response |
| 375 | + let token_response: serde_json::Value = poll_resp.json().await.into_diagnostic()?; |
| 376 | + |
| 377 | + return Ok(bundle_from_device_token_response( |
| 378 | + &token_response, |
| 379 | + issuer, |
| 380 | + client_id, |
| 381 | + )); |
| 382 | + } |
| 383 | + |
| 384 | + // Parse error response |
| 385 | + let error_resp: DeviceTokenErrorResponse = match poll_resp.json().await { |
| 386 | + Ok(e) => e, |
| 387 | + Err(_) => { |
| 388 | + return Err(miette::miette!( |
| 389 | + "Token polling failed with status {status} and unparseable response" |
| 390 | + )); |
| 391 | + } |
| 392 | + }; |
| 393 | + |
| 394 | + match error_resp.error.as_str() { |
| 395 | + "authorization_pending" => { |
| 396 | + // Keep polling |
| 397 | + debug!("Device authorization pending, continuing to poll"); |
| 398 | + } |
| 399 | + "slow_down" => { |
| 400 | + // Increase polling interval per RFC 8628 |
| 401 | + poll_interval += Duration::from_secs(5); |
| 402 | + debug!( |
| 403 | + "Received slow_down, increasing interval to {:?}", |
| 404 | + poll_interval |
| 405 | + ); |
| 406 | + } |
| 407 | + "access_denied" => { |
| 408 | + return Err(miette::miette!( |
| 409 | + "Authorization was denied by the user or administrator" |
| 410 | + )); |
| 411 | + } |
| 412 | + "expired_token" => { |
| 413 | + return Err(miette::miette!("Device code expired. Please try again.")); |
| 414 | + } |
| 415 | + _ => { |
| 416 | + let desc = if error_resp.error_description.is_empty() { |
| 417 | + String::new() |
| 418 | + } else { |
| 419 | + format!(": {}", error_resp.error_description) |
| 420 | + }; |
| 421 | + return Err(miette::miette!( |
| 422 | + "Device authorization failed: {}{desc}", |
| 423 | + error_resp.error |
| 424 | + )); |
| 425 | + } |
| 426 | + } |
| 427 | + } |
| 428 | +} |
| 429 | + |
248 | 430 | /// Refresh an OIDC token using the `refresh_token` grant. |
249 | 431 | /// |
250 | 432 | /// Reuses the configured login scopes when supplied so providers can select |
@@ -345,6 +527,29 @@ fn bundle_from_oauth2_response( |
345 | 527 | } |
346 | 528 | } |
347 | 529 |
|
| 530 | +fn bundle_from_device_token_response( |
| 531 | + resp: &serde_json::Value, |
| 532 | + issuer: &str, |
| 533 | + client_id: &str, |
| 534 | +) -> OidcTokenBundle { |
| 535 | + let now = std::time::SystemTime::now() |
| 536 | + .duration_since(std::time::UNIX_EPOCH) |
| 537 | + .unwrap_or_default() |
| 538 | + .as_secs(); |
| 539 | + |
| 540 | + let access_token = resp["access_token"].as_str().unwrap_or("").to_string(); |
| 541 | + let refresh_token = resp["refresh_token"].as_str().map(String::from); |
| 542 | + let expires_in = resp["expires_in"].as_u64(); |
| 543 | + |
| 544 | + OidcTokenBundle { |
| 545 | + access_token, |
| 546 | + refresh_token, |
| 547 | + expires_at: expires_in.map(|ei| now + ei), |
| 548 | + issuer: issuer.to_string(), |
| 549 | + client_id: client_id.to_string(), |
| 550 | + } |
| 551 | +} |
| 552 | + |
348 | 553 | /// Percent-decode a URL query parameter value. |
349 | 554 | fn percent_decode(s: &str) -> String { |
350 | 555 | let mut out = Vec::with_capacity(s.len()); |
@@ -611,4 +816,97 @@ mod tests { |
611 | 816 | assert_eq!(refreshed.client_id, previous.client_id); |
612 | 817 | assert_eq!(refreshed.expires_at, Some(300)); |
613 | 818 | } |
| 819 | + |
| 820 | + #[test] |
| 821 | + fn discovery_missing_device_endpoint_is_optional() { |
| 822 | + let discovery_json = "{\"issuer\":\"https://issuer.example\",\"authorization_endpoint\":\"https://issuer.example/auth\",\"token_endpoint\":\"https://issuer.example/token\"}"; |
| 823 | + let discovery: OidcDiscovery = serde_json::from_str(discovery_json).unwrap(); |
| 824 | + assert!(discovery.device_authorization_endpoint.is_none()); |
| 825 | + assert_eq!(discovery.issuer, "https://issuer.example"); |
| 826 | + } |
| 827 | + |
| 828 | + #[test] |
| 829 | + fn discovery_with_device_endpoint_is_captured() { |
| 830 | + let discovery_json = "{\"issuer\":\"https://issuer.example\",\"authorization_endpoint\":\"https://issuer.example/auth\",\"token_endpoint\":\"https://issuer.example/token\",\"device_authorization_endpoint\":\"https://issuer.example/device\"}"; |
| 831 | + let discovery: OidcDiscovery = serde_json::from_str(discovery_json).unwrap(); |
| 832 | + assert_eq!( |
| 833 | + discovery.device_authorization_endpoint.as_deref(), |
| 834 | + Some("https://issuer.example/device") |
| 835 | + ); |
| 836 | + } |
| 837 | + |
| 838 | + #[test] |
| 839 | + fn device_auth_response_parses_minimal() { |
| 840 | + let json = "{\"device_code\":\"GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS\",\"user_code\":\"WDJB-MJHT\",\"verification_uri\":\"https://example.com/device\",\"expires_in\":1800}"; |
| 841 | + let resp: DeviceAuthorizationResponse = serde_json::from_str(json).unwrap(); |
| 842 | + assert_eq!( |
| 843 | + resp.device_code, |
| 844 | + "GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS" |
| 845 | + ); |
| 846 | + assert_eq!(resp.user_code, "WDJB-MJHT"); |
| 847 | + assert_eq!(resp.verification_uri, "https://example.com/device"); |
| 848 | + assert_eq!(resp.expires_in, 1800); |
| 849 | + assert_eq!(resp.interval, 5); |
| 850 | + assert!(resp.verification_uri_complete.is_none()); |
| 851 | + } |
| 852 | + |
| 853 | + #[test] |
| 854 | + fn device_auth_response_parses_complete() { |
| 855 | + let json = "{\"device_code\":\"test-device-code\",\"user_code\":\"TEST-CODE\",\"verification_uri\":\"https://example.com/device\",\"verification_uri_complete\":\"https://example.com/device?user_code=TEST-CODE\",\"expires_in\":900,\"interval\":10}"; |
| 856 | + let resp: DeviceAuthorizationResponse = serde_json::from_str(json).unwrap(); |
| 857 | + assert_eq!(resp.interval, 10); |
| 858 | + assert_eq!( |
| 859 | + resp.verification_uri_complete.as_deref(), |
| 860 | + Some("https://example.com/device?user_code=TEST-CODE") |
| 861 | + ); |
| 862 | + } |
| 863 | + |
| 864 | + #[test] |
| 865 | + fn device_token_error_response_parses() { |
| 866 | + let json = "{\"error\":\"authorization_pending\",\"error_description\":\"User has not authorized yet\"}"; |
| 867 | + let resp: DeviceTokenErrorResponse = serde_json::from_str(json).unwrap(); |
| 868 | + assert_eq!(resp.error, "authorization_pending"); |
| 869 | + assert_eq!(resp.error_description, "User has not authorized yet"); |
| 870 | + } |
| 871 | + |
| 872 | + #[test] |
| 873 | + fn device_token_error_response_defaults_empty_description() { |
| 874 | + let json = "{\"error\":\"slow_down\"}"; |
| 875 | + let resp: DeviceTokenErrorResponse = serde_json::from_str(json).unwrap(); |
| 876 | + assert_eq!(resp.error, "slow_down"); |
| 877 | + assert_eq!(resp.error_description, ""); |
| 878 | + } |
| 879 | + |
| 880 | + #[test] |
| 881 | + fn bundle_from_device_token_response_complete() { |
| 882 | + let json = serde_json::json!({ |
| 883 | + "access_token": "device-access-token", |
| 884 | + "token_type": "Bearer", |
| 885 | + "expires_in": 3600, |
| 886 | + "refresh_token": "device-refresh-token" |
| 887 | + }); |
| 888 | + let bundle = |
| 889 | + bundle_from_device_token_response(&json, "https://issuer.example", "test-client"); |
| 890 | + assert_eq!(bundle.access_token, "device-access-token"); |
| 891 | + assert_eq!( |
| 892 | + bundle.refresh_token.as_deref(), |
| 893 | + Some("device-refresh-token") |
| 894 | + ); |
| 895 | + assert_eq!(bundle.issuer, "https://issuer.example"); |
| 896 | + assert_eq!(bundle.client_id, "test-client"); |
| 897 | + assert!(bundle.expires_at.is_some()); |
| 898 | + } |
| 899 | + |
| 900 | + #[test] |
| 901 | + fn bundle_from_device_token_response_minimal() { |
| 902 | + let json = serde_json::json!({ |
| 903 | + "access_token": "device-access-only", |
| 904 | + "token_type": "Bearer" |
| 905 | + }); |
| 906 | + let bundle = |
| 907 | + bundle_from_device_token_response(&json, "https://issuer.example", "test-client"); |
| 908 | + assert_eq!(bundle.access_token, "device-access-only"); |
| 909 | + assert!(bundle.refresh_token.is_none()); |
| 910 | + assert!(bundle.expires_at.is_none()); |
| 911 | + } |
614 | 912 | } |
0 commit comments