Skip to content

Commit 3a16012

Browse files
authored
fix(cli): prompt for fresh OIDC login after logout (#2773)
Signed-off-by: Gordon Sim <gsim@redhat.com>
1 parent 0d708d6 commit 3a16012

5 files changed

Lines changed: 123 additions & 7 deletions

File tree

‎crates/openshell-bootstrap/src/oidc_token.rs‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@ pub fn oidc_token_path(gateway_name: &str) -> Result<PathBuf> {
3939
Ok(user_gateway_dir(gateway_name)?.join("oidc_token.json"))
4040
}
4141

42+
/// Path to the one-shot marker that asks the next browser login to prompt.
43+
pub fn oidc_login_prompt_required_path(gateway_name: &str) -> Result<PathBuf> {
44+
Ok(user_gateway_dir(gateway_name)?.join("oidc_login_prompt_required"))
45+
}
46+
4247
/// Store an OIDC token bundle for a gateway.
4348
pub fn store_oidc_token(gateway_name: &str, bundle: &OidcTokenBundle) -> Result<()> {
4449
let path = oidc_token_path(gateway_name)?;
@@ -50,6 +55,7 @@ pub fn store_oidc_token(gateway_name: &str, bundle: &OidcTokenBundle) -> Result<
5055
.into_diagnostic()
5156
.wrap_err_with(|| format!("failed to write OIDC token to {}", path.display()))?;
5257
set_file_owner_only(&path)?;
58+
clear_oidc_login_prompt(gateway_name)?;
5359
Ok(())
5460
}
5561

@@ -76,6 +82,33 @@ pub fn remove_oidc_token(gateway_name: &str) -> Result<()> {
7682
Ok(())
7783
}
7884

85+
/// Mark the next interactive OIDC login as requiring a fresh `IdP` prompt.
86+
pub fn request_oidc_login_prompt(gateway_name: &str) -> Result<()> {
87+
let path = oidc_login_prompt_required_path(gateway_name)?;
88+
ensure_parent_dir_restricted(&path)?;
89+
std::fs::write(&path, b"1\n")
90+
.into_diagnostic()
91+
.wrap_err_with(|| format!("failed to write {}", path.display()))?;
92+
set_file_owner_only(&path)?;
93+
Ok(())
94+
}
95+
96+
/// Return whether the next interactive OIDC login should request a fresh prompt.
97+
pub fn oidc_login_prompt_required(gateway_name: &str) -> bool {
98+
oidc_login_prompt_required_path(gateway_name).is_ok_and(|path| path.exists())
99+
}
100+
101+
/// Clear the one-shot fresh-login marker for a gateway.
102+
pub fn clear_oidc_login_prompt(gateway_name: &str) -> Result<()> {
103+
let path = oidc_login_prompt_required_path(gateway_name)?;
104+
if path.exists() {
105+
std::fs::remove_file(&path)
106+
.into_diagnostic()
107+
.wrap_err_with(|| format!("failed to remove {}", path.display()))?;
108+
}
109+
Ok(())
110+
}
111+
79112
/// Check if the stored access token is expired or near expiry.
80113
///
81114
/// Returns `true` if the token expires within the next 30 seconds.
@@ -129,4 +162,36 @@ mod tests {
129162
assert!(remove_oidc_token("../escape").is_err());
130163
});
131164
}
165+
166+
#[test]
167+
fn oidc_login_prompt_marker_is_per_gateway() {
168+
let tmp = tempfile::tempdir().unwrap();
169+
with_tmp_xdg(tmp.path(), || {
170+
assert!(!oidc_login_prompt_required("alpha"));
171+
assert!(!oidc_login_prompt_required("beta"));
172+
173+
request_oidc_login_prompt("alpha").unwrap();
174+
175+
assert!(oidc_login_prompt_required("alpha"));
176+
assert!(!oidc_login_prompt_required("beta"));
177+
178+
let bundle = OidcTokenBundle {
179+
access_token: "token".to_string(),
180+
refresh_token: None,
181+
expires_at: None,
182+
issuer: "https://issuer.example.com".to_string(),
183+
client_id: "openshell-cli".to_string(),
184+
};
185+
store_oidc_token("alpha", &bundle).unwrap();
186+
187+
assert!(!oidc_login_prompt_required("alpha"));
188+
189+
request_oidc_login_prompt("alpha").unwrap();
190+
assert!(oidc_login_prompt_required("alpha"));
191+
192+
clear_oidc_login_prompt("alpha").unwrap();
193+
194+
assert!(!oidc_login_prompt_required("alpha"));
195+
});
196+
}
132197
}

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -912,6 +912,7 @@ pub async fn gateway_add(
912912
oidc_audience,
913913
oidc_scopes,
914914
gateway_insecure,
915+
false,
915916
)
916917
.await
917918
{
@@ -1116,6 +1117,8 @@ pub async fn gateway_login(name: &str, gateway_insecure: bool) -> Result<()> {
11161117
.unwrap_or("openshell-cli");
11171118
let audience = metadata.oidc_audience.as_deref();
11181119
let scopes = metadata.oidc_scopes.as_deref();
1120+
let force_fresh_login =
1121+
openshell_bootstrap::oidc_token::oidc_login_prompt_required(name);
11191122

11201123
let bundle = if std::env::var("OPENSHELL_OIDC_CLIENT_SECRET").is_ok() {
11211124
crate::oidc_auth::oidc_client_credentials_flow(
@@ -1133,12 +1136,14 @@ pub async fn gateway_login(name: &str, gateway_insecure: bool) -> Result<()> {
11331136
audience,
11341137
scopes,
11351138
gateway_insecure,
1139+
force_fresh_login,
11361140
)
11371141
.await?
11381142
};
11391143

11401144
let username = jwt_preferred_username(&bundle.access_token);
11411145
openshell_bootstrap::oidc_token::store_oidc_token(name, &bundle)?;
1146+
openshell_bootstrap::oidc_token::clear_oidc_login_prompt(name)?;
11421147

11431148
if let Some(user) = username {
11441149
eprintln!(
@@ -1184,6 +1189,7 @@ pub fn gateway_logout(name: &str) -> Result<()> {
11841189
match metadata.auth_mode.as_deref() {
11851190
Some("oidc") => {
11861191
openshell_bootstrap::oidc_token::remove_oidc_token(name)?;
1192+
openshell_bootstrap::oidc_token::request_oidc_login_prompt(name)?;
11871193
}
11881194
Some("cloudflare_jwt") => {
11891195
openshell_bootstrap::edge_token::remove_edge_token(name)?;
@@ -1430,6 +1436,9 @@ fn remove_gateway_registration(name: &str) {
14301436
if let Err(err) = openshell_bootstrap::oidc_token::remove_oidc_token(name) {
14311437
tracing::debug!("failed to remove oidc token: {err}");
14321438
}
1439+
if let Err(err) = openshell_bootstrap::oidc_token::clear_oidc_login_prompt(name) {
1440+
tracing::debug!("failed to clear oidc login prompt marker: {err}");
1441+
}
14331442
if let Err(err) = remove_gateway_metadata(name) {
14341443
tracing::debug!("failed to remove gateway metadata: {err}");
14351444
}

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1172,7 +1172,8 @@ enum GatewayCommands {
11721172
/// Authenticate with an edge-authenticated or OIDC gateway.
11731173
///
11741174
/// Opens a browser for the edge proxy's login flow and stores the
1175-
/// token locally. Use this to re-authenticate when a token expires.
1175+
/// token locally. After `gateway logout`, OIDC browser login requests a
1176+
/// fresh identity-provider prompt so you can switch users.
11761177
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
11771178
Login {
11781179
/// Gateway name (defaults to the active gateway).
@@ -1183,7 +1184,9 @@ enum GatewayCommands {
11831184
/// Clear stored authentication credentials for a gateway.
11841185
///
11851186
/// Removes the locally stored OIDC token or edge token so subsequent
1186-
/// commands require re-authentication via `gateway login`.
1187+
/// commands require re-authentication via `gateway login`. For OIDC
1188+
/// gateways, the next browser login asks the identity provider for a fresh
1189+
/// login instead of silently reusing an existing browser session.
11871190
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
11881191
Logout {
11891192
/// Gateway name (defaults to the active gateway).

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

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,20 @@ fn build_ci_scopes(scopes: Option<&str>) -> Vec<Scope> {
9696
.collect()
9797
}
9898

99+
fn interactive_authorization_params(
100+
audience: Option<&str>,
101+
force_fresh_login: bool,
102+
) -> Vec<(&'static str, String)> {
103+
let mut params = Vec::new();
104+
if force_fresh_login {
105+
params.push(("prompt", "login".to_string()));
106+
}
107+
if let Some(aud) = audience {
108+
params.push(("audience", aud.to_string()));
109+
}
110+
params
111+
}
112+
99113
/// Run the OIDC Authorization Code + PKCE browser flow.
100114
///
101115
/// Opens the user's browser to the Keycloak login page and waits for
@@ -106,6 +120,7 @@ pub async fn oidc_browser_auth_flow(
106120
audience: Option<&str>,
107121
scopes: Option<&str>,
108122
insecure: bool,
123+
force_fresh_login: bool,
109124
) -> Result<OidcTokenBundle> {
110125
let discovery = discover(issuer, insecure).await?;
111126

@@ -130,10 +145,14 @@ pub async fn oidc_browser_auth_flow(
130145

131146
let (mut auth_url, csrf_token) = auth_request.url();
132147

133-
// Append audience parameter for providers like Entra ID where the API
134-
// audience differs from the client ID.
135-
if let Some(aud) = audience {
136-
auth_url.query_pairs_mut().append_pair("audience", aud);
148+
// After `gateway logout`, ask the IdP for a fresh login prompt so the user
149+
// can switch browser identity. Ordinary repeated logins may reuse SSO.
150+
let params = interactive_authorization_params(audience, force_fresh_login);
151+
{
152+
let mut query = auth_url.query_pairs_mut();
153+
for (key, value) in &params {
154+
query.append_pair(key, value);
155+
}
137156
}
138157

139158
let (tx, rx) = oneshot::channel::<String>();
@@ -537,6 +556,26 @@ mod tests {
537556
assert!(scopes.is_empty());
538557
}
539558

559+
#[test]
560+
fn interactive_authorization_params_force_fresh_login() {
561+
assert_eq!(
562+
interactive_authorization_params(Some("api://openshell"), true),
563+
vec![
564+
("prompt", "login".to_string()),
565+
("audience", "api://openshell".to_string()),
566+
]
567+
);
568+
assert_eq!(
569+
interactive_authorization_params(None, true),
570+
vec![("prompt", "login".to_string())]
571+
);
572+
assert_eq!(
573+
interactive_authorization_params(Some("api://openshell"), false),
574+
vec![("audience", "api://openshell".to_string())]
575+
);
576+
assert!(interactive_authorization_params(None, false).is_empty());
577+
}
578+
540579
#[test]
541580
fn bundle_from_response_sets_fields() {
542581
use oauth2::basic::BasicTokenResponse;

‎docs/reference/gateway-auth.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ openshell gateway add https://gateway.example.com \
120120
--oidc-audience openshell-cli
121121
```
122122

123-
When you register or log in to an OIDC gateway, the CLI uses the Authorization Code flow with PKCE. It opens a browser, receives the authorization code on a localhost callback, exchanges the code for tokens, and stores the token bundle under the gateway credential directory. If `OPENSHELL_OIDC_CLIENT_SECRET` is set, the CLI uses the client credentials flow instead. Use that mode for CI and other non-interactive automation.
123+
When you register or log in to an OIDC gateway, the CLI uses the Authorization Code flow with PKCE. It opens a browser, receives the authorization code on a localhost callback, exchanges the code for tokens, and stores the token bundle under the gateway credential directory. After `openshell gateway logout`, the next browser login asks the identity provider for a fresh login prompt so you can choose a different browser user instead of silently reusing the previous session. If `OPENSHELL_OIDC_CLIENT_SECRET` is set, the CLI uses the client credentials flow instead. Use that mode for CI and other non-interactive automation.
124124

125125
The connection flow:
126126

0 commit comments

Comments
 (0)