Skip to content

Commit b85b41c

Browse files
committed
fix(cli): preserve the selected identity on shared gateway endpoints
Signed-off-by: Adrien Langou <alangou@nvidia.com>
1 parent 6fe64e1 commit b85b41c

3 files changed

Lines changed: 133 additions & 36 deletions

File tree

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

Lines changed: 76 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -45,19 +45,25 @@ impl From<GpuCliRequest> for GpuResourceRequirements {
4545
}
4646
}
4747

48-
/// Resolve the gateway name to a [`GatewayContext`] with the gateway endpoint.
49-
///
50-
/// Resolution priority:
51-
/// 1. `--gateway-endpoint` flag (direct URL, preserving metadata when available)
52-
/// 2. `--gateway` flag (explicit name)
53-
/// 3. `OPENSHELL_GATEWAY` environment variable
54-
/// 4. Active gateway from `~/.config/openshell/active_gateway`
55-
///
56-
/// When `--gateway-endpoint` is provided, it is used directly as the endpoint.
57-
/// If stored metadata can still identify the gateway, the stored gateway name
58-
/// is preserved so auth and TLS materials continue to resolve correctly.
59-
fn normalize_gateway_endpoint(endpoint: &str) -> &str {
60-
endpoint.trim_end_matches('/')
48+
fn normalize_gateway_endpoint(endpoint: &str) -> String {
49+
let endpoint = if endpoint.contains(['?', '#']) {
50+
endpoint
51+
} else {
52+
endpoint.trim_end_matches('/')
53+
};
54+
let Some((scheme, rest)) = endpoint.split_once("://") else {
55+
return endpoint.to_owned();
56+
};
57+
let (authority, route) = rest.split_at(rest.find(['/', '?', '#', '\\']).unwrap_or(rest.len()));
58+
let (userinfo, host_port) = authority.split_at(authority.rfind('@').map_or(0, |i| i + 1));
59+
if host_port.starts_with('[') {
60+
return endpoint.to_owned();
61+
}
62+
let (host, port) = host_port.split_at(host_port.find(':').unwrap_or(host_port.len()));
63+
format!(
64+
"{scheme}://{userinfo}{}{port}{route}",
65+
host.to_ascii_lowercase()
66+
)
6167
}
6268

6369
fn find_gateway_by_endpoint(endpoint: &str) -> Option<String> {
@@ -76,18 +82,33 @@ fn find_gateway_by_endpoint(endpoint: &str) -> Option<String> {
7682
})
7783
}
7884

85+
/// Resolve the gateway name to a [`GatewayContext`] with the gateway endpoint.
86+
///
87+
/// Resolution priority:
88+
/// 1. `--gateway-endpoint` flag (direct URL, preserving metadata when available)
89+
/// 2. `--gateway` flag (explicit name)
90+
/// 3. `OPENSHELL_GATEWAY` environment variable
91+
/// 4. Active gateway from `~/.config/openshell/active_gateway`
92+
///
93+
/// When `--gateway-endpoint` is provided, it is used directly as the endpoint.
94+
/// If stored metadata can still identify the gateway, the stored gateway name
95+
/// is preserved so auth and TLS materials continue to resolve correctly.
7996
fn resolve_gateway(
8097
gateway_flag: &Option<String>,
8198
gateway_endpoint: &Option<String>,
99+
allow_endpoint_override: bool,
82100
) -> Result<GatewayContext> {
83101
if let Some(endpoint) = gateway_endpoint {
84-
// When a gateway name is explicitly provided (via flag or env var),
85-
// trust it directly — don't require metadata to exist yet. This
86-
// avoids a race condition where mTLS certs are stored under the
87-
// real gateway name but the CLI falls back to using the raw
88-
// endpoint URL (producing a mangled path like `https___...`).
89102
let name = gateway_flag
90-
.clone()
103+
.as_ref()
104+
.filter(|name| {
105+
allow_endpoint_override
106+
|| get_gateway_metadata(name).is_some_and(|metadata| {
107+
normalize_gateway_endpoint(&metadata.gateway_endpoint)
108+
== normalize_gateway_endpoint(endpoint)
109+
})
110+
})
111+
.cloned()
91112
.or_else(|| find_gateway_by_endpoint(endpoint))
92113
.unwrap_or_else(|| endpoint.clone());
93114
return Ok(GatewayContext {
@@ -2797,16 +2818,11 @@ async fn run_async() -> Result<()> {
27972818
)
27982819
};
27992820
let current_gateway = || {
2800-
if let (Some(name), Some(endpoint)) = (&cli.gateway, &cli.gateway_endpoint)
2801-
&& explicit_gateway != explicit_endpoint
2802-
&& !get_gateway_metadata(name).is_some_and(|metadata| {
2803-
normalize_gateway_endpoint(&metadata.gateway_endpoint)
2804-
== normalize_gateway_endpoint(endpoint)
2805-
})
2806-
{
2807-
return resolve_gateway(&None, &cli.gateway_endpoint);
2808-
}
2809-
resolve_gateway(&cli.gateway, &cli.gateway_endpoint)
2821+
resolve_gateway(
2822+
&cli.gateway,
2823+
&cli.gateway_endpoint,
2824+
explicit_gateway == explicit_endpoint,
2825+
)
28102826
};
28112827

28122828
// Resolve colorization before anything is printed, so no command can emit
@@ -4355,8 +4371,9 @@ async fn run_async() -> Result<()> {
43554371
gateway_name.is_none() && (!explicit_gateway || explicit_endpoint);
43564372
let endpoint =
43574373
server.or_else(|| cli.gateway_endpoint.filter(|_| use_global_endpoint));
4358-
let profile = gateway_name.or_else(|| cli.gateway.filter(|_| explicit_gateway));
4359-
let ctx = resolve_gateway(&profile, &endpoint)?;
4374+
let allow_endpoint_override = gateway_name.is_some() || explicit_gateway;
4375+
let profile = gateway_name.or(cli.gateway);
4376+
let ctx = resolve_gateway(&profile, &endpoint, allow_endpoint_override)?;
43604377
let mut tls = tls.with_gateway_name(&ctx.name);
43614378
apply_auth(&mut tls, &ctx.name)?;
43624379
run::sandbox_ssh_proxy_by_name(&ctx.endpoint, &name, &tls, &cli.workspace).await?;
@@ -5258,12 +5275,37 @@ mod tests {
52585275
)
52595276
.unwrap();
52605277

5261-
let ctx = resolve_gateway(&None, &Some("https://gw.example.com/".to_string())).unwrap();
5278+
let ctx = resolve_gateway(&None, &Some("https://GW.example.com/".to_string()), false)
5279+
.unwrap();
52625280
assert_eq!(ctx.name, "edge-gateway");
5263-
assert_eq!(ctx.endpoint, "https://gw.example.com/");
5281+
assert_eq!(ctx.endpoint, "https://GW.example.com/");
52645282
});
52655283
}
52665284

5285+
#[test]
5286+
fn endpoint_matching_preserves_userinfo_port_and_route() {
5287+
let endpoint = "https://User:Password@GW.example:8443/Tenant?k=Token/#Section";
5288+
let normalized = normalize_gateway_endpoint(endpoint);
5289+
assert_eq!(normalized, endpoint.replace("GW", "gw"));
5290+
for (from, to) in [
5291+
("User", "user"),
5292+
("Password", "password"),
5293+
("8443", "443"),
5294+
("Tenant", "tenant"),
5295+
("Token", "token"),
5296+
("Section", "section"),
5297+
] {
5298+
assert_ne!(
5299+
normalized,
5300+
normalize_gateway_endpoint(&endpoint.replace(from, to))
5301+
);
5302+
}
5303+
assert_ne!(
5304+
normalize_gateway_endpoint("https://gw/?key=token/"),
5305+
normalize_gateway_endpoint("https://gw/?key=token")
5306+
);
5307+
}
5308+
52675309
#[test]
52685310
fn resolve_gateway_prefers_explicit_gateway_for_direct_endpoint() {
52695311
let tmp = tempfile::tempdir().unwrap();
@@ -5277,6 +5319,7 @@ mod tests {
52775319
let ctx = resolve_gateway(
52785320
&Some("named-gateway".to_string()),
52795321
&Some("https://override.example.com".to_string()),
5322+
true,
52805323
)
52815324
.unwrap();
52825325

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

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2461,9 +2461,6 @@ pub fn print_ssh_config(gateway: &str, name: &str, workspace: &str) -> Result<()
24612461

24622462
#[cfg(test)]
24632463
mod tests {
2464-
#[cfg(unix)]
2465-
use std::os::unix::process::CommandExt;
2466-
24672464
#[test]
24682465
fn ssh_verbosity_reaches_nested_proxy_commands_and_respects_override() {
24692466
for override_level in [None, Some("INFO")] {
@@ -2529,6 +2526,7 @@ mod tests {
25292526
fn interactive_wait_survives_terminal_signals_and_reaps_child() {
25302527
use nix::sys::signal::killpg;
25312528
use nix::unistd::Pid;
2529+
use std::os::unix::process::CommandExt;
25322530

25332531
struct Probe(std::process::Child);
25342532
impl Drop for Probe {

‎crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3120,6 +3120,62 @@ async fn ssh_profile_credentials_follow_the_selected_endpoint() {
31203120
);
31213121
}
31223122

3123+
#[tokio::test]
3124+
async fn selected_ssh_profile_wins_over_an_active_profile_on_the_same_host() {
3125+
let server = run_server().await;
3126+
let xdg = helpers::tempdir().unwrap();
3127+
prepare_cli_xdg(&server, &xdg, "openshell");
3128+
write_oidc_test_credentials(&server, &xdg, "https://unused.invalid", 4_102_444_800);
3129+
let endpoint = server.endpoint.replace("localhost", "LOCALHOST");
3130+
let profiles = xdg.path().join("openshell");
3131+
prepare_cli_xdg(&server, &xdg, "other");
3132+
fs::write(profiles.join("active_gateway"), "other").unwrap();
3133+
fs::write(
3134+
profiles.join("gateways/other/metadata.json"),
3135+
serde_json::to_vec(&openshell_bootstrap::GatewayMetadata {
3136+
name: "other".into(),
3137+
gateway_endpoint: endpoint.clone(),
3138+
..Default::default()
3139+
})
3140+
.unwrap(),
3141+
)
3142+
.unwrap();
3143+
let state = &server.openshell.state;
3144+
state
3145+
.ssh_session_failures_remaining
3146+
.store(3, Ordering::SeqCst);
3147+
for (request, args) in [
3148+
&["-g", "openshell", "sandbox", "connect", "demo"][..],
3149+
&["ssh-proxy", "--server", &endpoint, "--name", "demo"],
3150+
&[
3151+
"ssh-proxy",
3152+
"--gateway-endpoint",
3153+
&endpoint,
3154+
"--name",
3155+
"demo",
3156+
],
3157+
]
3158+
.into_iter()
3159+
.enumerate()
3160+
{
3161+
let output = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell"))
3162+
.args(args)
3163+
.env("OPENSHELL_GATEWAY", "openshell")
3164+
.env("OPENSHELL_GATEWAY_ENDPOINT", &endpoint)
3165+
.env("XDG_CONFIG_HOME", xdg.path())
3166+
.env("OPENSHELL_TELEMETRY_ENABLED", "false")
3167+
.output()
3168+
.await
3169+
.unwrap();
3170+
assert!(String::from_utf8_lossy(&output.stderr).contains("sandbox is not ready"));
3171+
assert_eq!(
3172+
state.ssh_requests_with_cached_bearer.load(Ordering::SeqCst),
3173+
request + 1,
3174+
"{args:?}"
3175+
);
3176+
}
3177+
}
3178+
31233179
#[tokio::test]
31243180
async fn sandbox_forward_background_tracks_owned_child_when_pid_discovery_fails() {
31253181
let server = run_server().await;

0 commit comments

Comments
 (0)