Skip to content

Commit 775fcb4

Browse files
committed
fix(cli): roll back gateway registration when auth fails during gateway add
When OIDC or Cloudflare browser auth fails during gateway add, remove the gateway registration and restore the previously active gateway instead of leaving a broken entry on disk. Previously, store_gateway_metadata and save_active_gateway were called before the auth attempt. On failure, the registration persisted with an 'authenticate later' message, causing stale entries to accumulate when users retried with different flags or names. The rollback is skipped when the browser is intentionally suppressed (OPENSHELL_NO_BROWSER=1), since the user intends to authenticate later with gateway login. Fixes #1537 Signed-off-by: Adel Zaalouk <[email protected]>
1 parent b41e0df commit 775fcb4

1 file changed

Lines changed: 165 additions & 12 deletions

File tree

  • crates/openshell-cli/src

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

Lines changed: 165 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -950,6 +950,7 @@ pub async fn gateway_add(
950950
// OIDC takes precedence over plaintext/mTLS/edge detection — the user
951951
// explicitly opted in with --oidc-issuer regardless of scheme.
952952
if let Some(issuer) = oidc_issuer {
953+
let previous_active = load_active_gateway();
953954
let metadata = GatewayMetadata {
954955
name: name.to_string(),
955956
gateway_endpoint: endpoint.clone(),
@@ -974,8 +975,10 @@ pub async fn gateway_add(
974975
eprintln!(" {} oidc", "Auth:".dimmed());
975976
eprintln!();
976977

978+
let auth_skipped = is_browser_suppressed();
979+
977980
// Check for client_credentials env var (CI mode).
978-
if std::env::var("OPENSHELL_OIDC_CLIENT_SECRET").is_ok() {
981+
let auth_ok = if std::env::var("OPENSHELL_OIDC_CLIENT_SECRET").is_ok() {
979982
match crate::oidc_auth::oidc_client_credentials_flow(
980983
issuer,
981984
oidc_client_id,
@@ -991,9 +994,11 @@ pub async fn gateway_add(
991994
"{} Authenticated via client credentials",
992995
"✓".green().bold()
993996
);
997+
true
994998
}
995999
Err(e) => {
9961000
eprintln!("{} Authentication failed: {e}", "!".yellow());
1001+
false
9971002
}
9981003
}
9991004
} else {
@@ -1009,15 +1014,17 @@ pub async fn gateway_add(
10091014
Ok(bundle) => {
10101015
openshell_bootstrap::oidc_token::store_oidc_token(name, &bundle)?;
10111016
eprintln!("{} Authenticated successfully", "✓".green().bold());
1017+
true
10121018
}
10131019
Err(e) => {
1014-
eprintln!("{} Authentication skipped: {e}", "!".yellow());
1015-
eprintln!(
1016-
" Authenticate later with: {}",
1017-
"openshell gateway login".dimmed(),
1018-
);
1020+
eprintln!("{} Authentication failed: {e}", "!".yellow());
1021+
false
10191022
}
10201023
}
1024+
};
1025+
1026+
if !auth_ok && !auth_skipped {
1027+
rollback_gateway_registration(name, previous_active.as_deref());
10211028
}
10221029

10231030
return Ok(());
@@ -1135,6 +1142,7 @@ pub async fn gateway_add(
11351142
eprintln!("{} TLS certificates present", "✓".green().bold());
11361143
} else {
11371144
// Cloud (edge-authenticated) gateway.
1145+
let previous_active = load_active_gateway();
11381146
let metadata = GatewayMetadata {
11391147
name: name.to_string(),
11401148
gateway_endpoint: endpoint.clone(),
@@ -1155,18 +1163,22 @@ pub async fn gateway_add(
11551163
eprintln!(" {} cloud", "Type:".dimmed());
11561164
eprintln!();
11571165

1158-
match crate::auth::browser_auth_flow(&endpoint).await {
1166+
let auth_skipped = is_browser_suppressed();
1167+
1168+
let auth_ok = match crate::auth::browser_auth_flow(&endpoint).await {
11591169
Ok(token) => {
11601170
openshell_bootstrap::edge_token::store_edge_token(name, &token)?;
11611171
eprintln!("{} Authenticated successfully", "✓".green().bold());
1172+
true
11621173
}
11631174
Err(e) => {
1164-
eprintln!("{} Authentication skipped: {e}", "!".yellow());
1165-
eprintln!(
1166-
" Authenticate later with: {}",
1167-
"openshell gateway login".dimmed(),
1168-
);
1175+
eprintln!("{} Authentication failed: {e}", "!".yellow());
1176+
false
11691177
}
1178+
};
1179+
1180+
if !auth_ok && !auth_skipped {
1181+
rollback_gateway_registration(name, previous_active.as_deref());
11701182
}
11711183
}
11721184

@@ -1435,6 +1447,29 @@ async fn gateway_reachable(server: &str, tls: &TlsOptions) -> bool {
14351447
matches!(http_health_check(server, tls).await, Ok(Some(status)) if status.is_success())
14361448
}
14371449

1450+
fn is_browser_suppressed() -> bool {
1451+
std::env::var("OPENSHELL_NO_BROWSER").is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1452+
}
1453+
1454+
fn rollback_gateway_registration(name: &str, previous_active: Option<&str>) {
1455+
remove_gateway_registration(name);
1456+
if let Some(prev) = previous_active
1457+
&& let Err(e) = save_active_gateway(prev)
1458+
{
1459+
tracing::warn!("failed to restore previous active gateway '{prev}': {e}");
1460+
eprintln!(
1461+
"{} Failed to restore previous active gateway '{}': {e}",
1462+
"!".yellow(),
1463+
prev,
1464+
);
1465+
}
1466+
eprintln!(
1467+
"{} Registration for '{}' removed. Fix the issue and retry gateway add.",
1468+
"!".yellow(),
1469+
name,
1470+
);
1471+
}
1472+
14381473
fn remove_gateway_registration(name: &str) {
14391474
if let Err(err) = openshell_bootstrap::edge_token::remove_edge_token(name) {
14401475
tracing::debug!("failed to remove edge token: {err}");
@@ -8765,4 +8800,122 @@ mod tests {
87658800
"Oauth2RefreshToken should be allowed for refresh bootstrap"
87668801
);
87678802
}
8803+
8804+
#[test]
8805+
fn gateway_add_oidc_rolls_back_on_auth_failure() {
8806+
let _ = rustls::crypto::ring::default_provider().install_default();
8807+
let tmpdir = tempfile::tempdir().expect("create tmpdir");
8808+
with_tmp_xdg(tmpdir.path(), || {
8809+
let runtime = tokio::runtime::Runtime::new().expect("create runtime");
8810+
8811+
// Register a working plaintext gateway first so we can verify
8812+
// the active gateway is restored after rollback.
8813+
runtime.block_on(async {
8814+
gateway_add(
8815+
"http://127.0.0.1:9999",
8816+
Some("existing-gw"),
8817+
None,
8818+
false,
8819+
None,
8820+
"openshell-cli",
8821+
None,
8822+
None,
8823+
false,
8824+
)
8825+
.await
8826+
.expect("register seed gateway");
8827+
});
8828+
assert_eq!(load_active_gateway().as_deref(), Some("existing-gw"));
8829+
8830+
// Attempt OIDC gateway add against an unreachable issuer.
8831+
// Auth will fail (connection refused), triggering rollback.
8832+
runtime.block_on(async {
8833+
gateway_add(
8834+
"https://gateway.example.com",
8835+
Some("oidc-fail"),
8836+
None,
8837+
false,
8838+
Some("http://127.0.0.1:1/realms/nonexistent"),
8839+
"openshell-cli",
8840+
None,
8841+
None,
8842+
false,
8843+
)
8844+
.await
8845+
.expect("gateway_add should not return Err on auth failure");
8846+
});
8847+
8848+
// The failed registration should have been rolled back.
8849+
assert!(
8850+
load_gateway_metadata("oidc-fail").is_err(),
8851+
"failed OIDC gateway should be removed after auth failure"
8852+
);
8853+
// The previously active gateway should be restored.
8854+
assert_eq!(
8855+
load_active_gateway().as_deref(),
8856+
Some("existing-gw"),
8857+
"active gateway should be restored after rollback"
8858+
);
8859+
});
8860+
}
8861+
8862+
#[test]
8863+
fn gateway_add_cloud_rolls_back_on_auth_failure() {
8864+
let _ = rustls::crypto::ring::default_provider().install_default();
8865+
let tmpdir = tempfile::tempdir().expect("create tmpdir");
8866+
with_tmp_xdg(tmpdir.path(), || {
8867+
let runtime = tokio::runtime::Runtime::new().expect("create runtime");
8868+
8869+
// Register a working plaintext gateway first.
8870+
runtime.block_on(async {
8871+
gateway_add(
8872+
"http://127.0.0.1:9999",
8873+
Some("existing-gw"),
8874+
None,
8875+
false,
8876+
None,
8877+
"openshell-cli",
8878+
None,
8879+
None,
8880+
false,
8881+
)
8882+
.await
8883+
.expect("register seed gateway");
8884+
});
8885+
assert_eq!(load_active_gateway().as_deref(), Some("existing-gw"));
8886+
8887+
// Attempt cloud gateway add. The browser flow will fail because
8888+
// OPENSHELL_NO_BROWSER is NOT set but the /auth/connect endpoint
8889+
// is unreachable (connection refused), so the 120s timeout would
8890+
// kick in. To keep the test fast, set OPENSHELL_NO_BROWSER=0
8891+
// (explicitly not suppressed) and use a port that refuses connections.
8892+
// The CF auth flow will fail quickly on connection refused.
8893+
runtime.block_on(async {
8894+
gateway_add(
8895+
"https://127.0.0.1:1",
8896+
Some("cloud-fail"),
8897+
None,
8898+
false,
8899+
None,
8900+
"openshell-cli",
8901+
None,
8902+
None,
8903+
false,
8904+
)
8905+
.await
8906+
.expect("gateway_add should not return Err on auth failure");
8907+
});
8908+
8909+
// The failed registration should have been rolled back.
8910+
assert!(
8911+
load_gateway_metadata("cloud-fail").is_err(),
8912+
"failed cloud gateway should be removed after auth failure"
8913+
);
8914+
assert_eq!(
8915+
load_active_gateway().as_deref(),
8916+
Some("existing-gw"),
8917+
"active gateway should be restored after rollback"
8918+
);
8919+
});
8920+
}
87688921
}

0 commit comments

Comments
 (0)