Skip to content

Commit 62a1dab

Browse files
committed
feat(cli): support OIDC device authorization grant for headless login
Closes NVIDIA#2793 Add OAuth 2.0 Device Authorization Grant (RFC 8628) support to the OpenShell CLI's OIDC login flow. When running in a headless environment (OPENSHELL_NO_BROWSER=1) without a client secret configured, the CLI now uses the device code flow instead of the browser-based PKCE flow. The device code flow: - Requests a device code and user code from the IdP's device authorization endpoint - Displays a verification URL and user code to the user - Polls the token endpoint until the user completes authorization or the code expires - Supports slow_down responses per RFC 8628 by increasing the polling interval This implementation: - Extends OidcDiscovery to optionally capture device_authorization_endpoint - Adds oidc_device_code_flow function with proper error handling for all RFC 8628 error codes - Updates gateway add and gateway login to dispatch to device flow when browser is suppressed - Adds comprehensive unit tests for device flow structs and response parsing - Updates gateway authentication documentation to describe the device code fallback Signed-off-by: Jesse Jaggars <[email protected]>
1 parent 3a16012 commit 62a1dab

3 files changed

Lines changed: 333 additions & 4 deletions

File tree

‎crates/openshell-cli/src/commands/gateway.rs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -905,6 +905,26 @@ pub async fn gateway_add(
905905
false
906906
}
907907
}
908+
} else if is_browser_suppressed() {
909+
match crate::oidc_auth::oidc_device_code_flow(
910+
issuer,
911+
oidc_client_id,
912+
oidc_audience,
913+
oidc_scopes,
914+
gateway_insecure,
915+
)
916+
.await
917+
{
918+
Ok(bundle) => {
919+
openshell_bootstrap::oidc_token::store_oidc_token(name, &bundle)?;
920+
eprintln!("{} Authenticated via device code", "✓".green().bold());
921+
true
922+
}
923+
Err(e) => {
924+
eprintln!("{} Authentication failed: {e}", "!".yellow());
925+
false
926+
}
927+
}
908928
} else {
909929
match crate::oidc_auth::oidc_browser_auth_flow(
910930
issuer,
@@ -1129,6 +1149,15 @@ pub async fn gateway_login(name: &str, gateway_insecure: bool) -> Result<()> {
11291149
gateway_insecure,
11301150
)
11311151
.await?
1152+
} else if is_browser_suppressed() {
1153+
crate::oidc_auth::oidc_device_code_flow(
1154+
issuer,
1155+
client_id,
1156+
audience,
1157+
scopes,
1158+
gateway_insecure,
1159+
)
1160+
.await?
11321161
} else {
11331162
crate::oidc_auth::oidc_browser_auth_flow(
11341163
issuer,

‎crates/openshell-cli/src/oidc_auth.rs‎

Lines changed: 302 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33

44
//! OIDC authentication flows for CLI gateway login.
55
//!
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.
1010
use bytes::Bytes;
1111
use http_body_util::Full;
1212
use hyper::service::service_fn;
@@ -37,6 +37,31 @@ struct OidcDiscovery {
3737
issuer: String,
3838
authorization_endpoint: String,
3939
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,
4065
}
4166

4267
/// Discover OIDC endpoints from the issuer's well-known configuration.
@@ -245,6 +270,163 @@ pub async fn oidc_client_credentials_flow(
245270
))
246271
}
247272

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+
248430
/// Refresh an OIDC token using the `refresh_token` grant.
249431
///
250432
/// Reuses the configured login scopes when supplied so providers can select
@@ -345,6 +527,29 @@ fn bundle_from_oauth2_response(
345527
}
346528
}
347529

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+
348553
/// Percent-decode a URL query parameter value.
349554
fn percent_decode(s: &str) -> String {
350555
let mut out = Vec::with_capacity(s.len());
@@ -611,4 +816,97 @@ mod tests {
611816
assert_eq!(refreshed.client_id, previous.client_id);
612817
assert_eq!(refreshed.expires_at, Some(300));
613818
}
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+
}
614912
}

‎docs/reference/gateway-auth.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,8 @@ When you register or log in to an OIDC gateway, the CLI uses the Authorization C
124124

125125
The connection flow:
126126

127+
When the browser cannot be opened (such as in a headless environment or when `OPENSHELL_NO_BROWSER=1` is set), and `OPENSHELL_OIDC_CLIENT_SECRET` is not configured, the CLI falls back to the Device Authorization Grant (RFC 8628). This flow prompts the user to visit a verification URL on any device with a browser and enter a displayed code. The CLI polls the token endpoint until the user completes authorization. This requires the OIDC client to have the device authorization grant enabled on the identity provider.
128+
127129
1. The CLI loads the stored OIDC token bundle.
128130
2. If the access token is expired and a refresh token is available, the CLI refreshes it with the OIDC scopes saved in the gateway metadata.
129131
3. The CLI connects to the gateway and attaches `authorization: Bearer <token>` metadata to each gRPC request.

0 commit comments

Comments
 (0)