Skip to content

Commit 1894302

Browse files
committed
feat(ssh): open gateway-authenticated relays for pinned sandbox IDs
Signed-off-by: Adrien Langou <alangou@nvidia.com>
1 parent 73d3803 commit 1894302

15 files changed

Lines changed: 1184 additions & 228 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4330,13 +4330,14 @@ async fn run_async() -> Result<()> {
43304330
tls.oidc_token.as_deref(),
43314331
tls.edge_token.as_deref(),
43324332
)?;
4333-
openshell_tui::run(
4333+
openshell_tui::run_with_gateway_insecure(
43344334
channel,
43354335
interceptor,
43364336
&ctx.name,
43374337
&ctx.endpoint,
43384338
&cli.workspace,
43394339
theme,
4340+
tls.gateway_insecure,
43404341
)
43414342
.await?;
43424343
}

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

Lines changed: 167 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,15 @@ use miette::{IntoDiagnostic, Report, Result, WrapErr};
1414
use nix::sys::signal::Signal;
1515
use openshell_core::forward::{
1616
ForwardSpec, format_gateway_url, resolve_ssh_gateway, sandbox_ssh_args, shell_escape,
17-
validate_ssh_session_response, write_forward_pid,
17+
supports_direct_ssh, validate_ssh_session_response, write_forward_pid,
1818
};
1919
use openshell_core::proto::{
2020
CreateSshSessionRequest, CreateSshSessionResponse, GetSandboxRequest, SandboxPhase,
2121
SshRelayTarget, TcpForwardFrame, TcpForwardInit, tcp_forward_init,
2222
};
23-
use openshell_core::ssh_handoff::{PreparedProxy, SshCleanup, SshTarget};
23+
use openshell_core::ssh_handoff::{
24+
PreparedProxy, RelayAuthorization, SshAdmissionError, SshCleanup, SshTarget,
25+
};
2426
use openshell_core::upload::{
2527
DestinationKind as UploadDestinationKind, ExpectedDestination, UploadPlan,
2628
};
@@ -120,11 +122,13 @@ async fn ssh_session_config(
120122
) -> Result<SshSessionConfig> {
121123
let mut client = grpc_client(server, tls).await?;
122124

123-
let (sandbox, replica) = lookup_ssh_sandbox(&mut client, name, workspace).await?;
125+
let (sandbox, replica, direct_ssh) = lookup_ssh_sandbox(&mut client, name, workspace).await?;
124126
let gateway_name = tls
125127
.gateway_name()
126128
.ok_or_else(|| miette::miette!("gateway name is required to build SSH proxy command"))?;
127129
let mut target = SshTarget::new(server, gateway_name, name, workspace, sandbox.object_id());
130+
target.direct_ssh = Some(direct_ssh);
131+
target.gateway_insecure = tls.gateway_insecure;
128132
target.replica = replica
129133
.as_ref()
130134
.and_then(|v| v.to_str().ok())
@@ -424,6 +428,9 @@ fn next_connect_retry_delay(delay: Duration) -> Duration {
424428
}
425429

426430
fn connect_error_is_retryable(error: &Report) -> bool {
431+
if let Some(error) = error.downcast_ref::<SshAdmissionError>() {
432+
return error.is_retryable();
433+
}
427434
let message = format!("{error:?}").to_ascii_lowercase();
428435
[
429436
"broken pipe",
@@ -455,6 +462,7 @@ async fn sandbox_connect_supervised(
455462
cleanup: &SshCleanup,
456463
) -> Result<i32> {
457464
let mut selected_id = None;
465+
let mut require_direct = false;
458466
let mut recovery_deadline = None;
459467
let mut retry_delay = CONNECT_RETRY_INITIAL_DELAY;
460468
let mut cancellation = ConnectCancellation::new()?;
@@ -475,6 +483,10 @@ async fn sandbox_connect_supervised(
475483
{
476484
return Err(miette::miette!("sandbox was replaced before reconnecting"));
477485
}
486+
if require_direct && session.target.direct_ssh != Some(true) {
487+
return Err(SshAdmissionError::CapabilityLost.into());
488+
}
489+
require_direct = session.target.direct_ssh == Some(true);
478490
Ok((session.prepare().await?, session.main_terminal))
479491
},
480492
)))
@@ -1777,6 +1789,9 @@ where
17771789
}
17781790

17791791
fn sync_error_is_retryable(error: &Report) -> bool {
1792+
if let Some(error) = error.downcast_ref::<SshAdmissionError>() {
1793+
return error.is_retryable();
1794+
}
17801795
if let Some(error) = error.downcast_ref::<upload::UploadError>() {
17811796
return error.is_retryable();
17821797
}
@@ -1997,7 +2012,11 @@ async fn lookup_ssh_sandbox(
19972012
client: &mut GrpcClient,
19982013
name: &str,
19992014
workspace: &str,
2000-
) -> Result<(openshell_core::proto::Sandbox, Option<AsciiMetadataValue>)> {
2015+
) -> Result<(
2016+
openshell_core::proto::Sandbox,
2017+
Option<AsciiMetadataValue>,
2018+
bool,
2019+
)> {
20012020
let response = client
20022021
.get_sandbox(with_owner_hint(GetSandboxRequest {
20032022
name: name.to_string(),
@@ -2006,26 +2025,44 @@ async fn lookup_ssh_sandbox(
20062025
)),
20072026
}))
20082027
.await
2009-
.into_diagnostic()?;
2028+
.map_err(SshAdmissionError::Rpc)?;
20102029
let replica = owner_replica(&response);
2030+
let direct_ssh = supports_direct_ssh(&response)?;
20112031
let sandbox = response
20122032
.into_inner()
20132033
.sandbox
20142034
.ok_or_else(|| miette::miette!("sandbox not found"))?;
20152035

2016-
Ok((sandbox, replica))
2036+
Ok((sandbox, replica, direct_ssh))
20172037
}
20182038

2019-
/// Mint the token inside the proxy so neither SSH nor its other children inherit it.
2039+
/// Connect a saved SSH profile to the sandbox selected by this invocation.
20202040
pub async fn sandbox_ssh_proxy_by_name(
20212041
server: &str,
20222042
name: &str,
20232043
tls: &TlsOptions,
20242044
workspace: &str,
20252045
) -> Result<()> {
20262046
let mut client = grpc_client(server, tls).await?;
2027-
let (sandbox, replica) = lookup_ssh_sandbox(&mut client, name, workspace).await?;
2047+
let (sandbox, replica, direct_ssh) = lookup_ssh_sandbox(&mut client, name, workspace).await?;
20282048
let mut cancellation = ConnectCancellation::new()?;
2049+
if direct_ssh {
2050+
return cancellation
2051+
.wait(async {
2052+
let relay = open_direct_ssh(
2053+
&mut client,
2054+
name,
2055+
workspace,
2056+
sandbox.object_id(),
2057+
replica.as_ref(),
2058+
None,
2059+
)
2060+
.await?;
2061+
relay_ssh_proxy(relay).await
2062+
})
2063+
.await
2064+
.map_err(|_| miette::miette!("SSH proxy interrupted"))?;
2065+
}
20292066
let session = cancellation
20302067
.wait(client.create_ssh_session(CreateSshSessionRequest {
20312068
sandbox: name.to_string(),
@@ -2071,14 +2108,75 @@ pub async fn relay_prepared_ssh(
20712108
.map(str::parse)
20722109
.transpose()
20732110
.into_diagnostic()?;
2111+
let direct = matches!(&grant.authorization, Some(RelayAuthorization::Direct(_)));
2112+
let open = async {
2113+
match grant
2114+
.authorization
2115+
.ok_or_else(|| miette::miette!("missing SSH relay authorization"))?
2116+
{
2117+
RelayAuthorization::Session(session) => {
2118+
open_ssh_relay(
2119+
&grant.endpoint,
2120+
name,
2121+
tls,
2122+
workspace,
2123+
&session,
2124+
replica.as_ref(),
2125+
)
2126+
.await
2127+
}
2128+
RelayAuthorization::Direct(direct) => {
2129+
let mut tls = tls.clone();
2130+
tls.gateway_insecure = direct.gateway_insecure;
2131+
let mut client = grpc_client(&grant.endpoint, &tls).await?;
2132+
open_direct_ssh(
2133+
&mut client,
2134+
name,
2135+
workspace,
2136+
&direct.sandbox_id,
2137+
replica.as_ref(),
2138+
direct.registration_timeout()?,
2139+
)
2140+
.await
2141+
}
2142+
}
2143+
};
20742144
let opened = tokio::select! {
2075-
result = open_ssh_relay(&grant.endpoint, name, tls, workspace, &grant.session, replica.as_ref()) => result?,
2145+
result = open => result,
20762146
_ = peer.read_u8() => return Err(miette::miette!("SSH handoff closed before relay admission")),
20772147
};
2078-
peer.write_u8(1).await.into_diagnostic()?;
2079-
peer.read_u8().await.into_diagnostic()?;
2080-
drop(peer);
2081-
relay_ssh_proxy(opened).await
2148+
let result = match opened {
2149+
Ok(relay) => {
2150+
notify_ssh_issuer(&mut peer, 1).await?;
2151+
if !direct {
2152+
drop(peer);
2153+
return relay_ssh_proxy(relay).await;
2154+
}
2155+
relay_ssh_proxy(relay).await
2156+
}
2157+
Err(error) => Err(error),
2158+
};
2159+
if direct
2160+
&& let Err(error) = &result
2161+
&& error
2162+
.downcast_ref::<SshAdmissionError>()
2163+
.is_some_and(|rpc| !rpc.is_retryable())
2164+
{
2165+
let _ = notify_ssh_issuer(&mut peer, openshell_core::ssh_handoff::DIRECT_SSH_REFUSED).await;
2166+
}
2167+
result
2168+
}
2169+
2170+
async fn notify_ssh_issuer(
2171+
peer: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
2172+
reply: u8,
2173+
) -> Result<()> {
2174+
use tokio::io::AsyncReadExt;
2175+
peer.write_u8(reply).await.into_diagnostic()?;
2176+
if peer.read_u8().await.into_diagnostic()? != 1 {
2177+
return Err(miette::miette!("invalid SSH handoff acknowledgement"));
2178+
}
2179+
Ok(())
20822180
}
20832181

20842182
type SshRelay = (
@@ -2133,7 +2231,7 @@ async fn relay_ssh_proxy((tx, mut response): SshRelay) -> Result<()> {
21332231
let frame = match response.message().await {
21342232
Ok(Some(frame)) => frame,
21352233
Ok(None) => return Ok::<_, Report>(()),
2136-
Err(error) => return Err(error).into_diagnostic(),
2234+
Err(status) => return Err(SshAdmissionError::Rpc(status).into()),
21372235
};
21382236
let Some(openshell_core::proto::tcp_forward_frame::Payload::Data(data)) = frame.payload
21392237
else {
@@ -2213,21 +2311,66 @@ async fn open_ssh_relay(
22132311
None => lookup_ssh_sandbox(&mut client, name, workspace)
22142312
.await
22152313
.ok()
2216-
.and_then(|(_, owner)| owner),
2314+
.and_then(|(_, owner, _)| owner),
22172315
};
2316+
open_ssh_stream(
2317+
&mut client,
2318+
name,
2319+
workspace,
2320+
tcp_forward_init::Target::Ssh(SshRelayTarget {}),
2321+
&session.token,
2322+
owner.as_ref(),
2323+
)
2324+
.await
2325+
.into_diagnostic()
2326+
}
2327+
2328+
async fn open_direct_ssh(
2329+
client: &mut GrpcClient,
2330+
name: &str,
2331+
workspace: &str,
2332+
sandbox_id: &str,
2333+
replica: Option<&AsciiMetadataValue>,
2334+
registration_timeout: Option<Duration>,
2335+
) -> Result<SshRelay> {
2336+
openshell_core::forward::validate_ssh_sandbox_id(sandbox_id).into_diagnostic()?;
2337+
let started = Instant::now();
2338+
loop {
2339+
let target = tcp_forward_init::Target::DirectSshSandboxId(sandbox_id.to_owned());
2340+
match open_ssh_stream(client, name, workspace, target, "", replica).await {
2341+
Err(status)
2342+
if status.code() == tonic::Code::FailedPrecondition
2343+
&& status.message() == "sandbox is not ready"
2344+
&& registration_timeout.is_some_and(|timeout| started.elapsed() < timeout) =>
2345+
{
2346+
tokio::time::sleep(Duration::from_millis(50)).await;
2347+
}
2348+
result => return result.map_err(|status| Report::new(SshAdmissionError::Rpc(status))),
2349+
}
2350+
}
2351+
}
2352+
2353+
async fn open_ssh_stream(
2354+
client: &mut GrpcClient,
2355+
name: &str,
2356+
workspace: &str,
2357+
target: tcp_forward_init::Target,
2358+
token: &str,
2359+
replica: Option<&AsciiMetadataValue>,
2360+
) -> std::result::Result<SshRelay, tonic::Status> {
22182361
let init = TcpForwardFrame {
22192362
payload: Some(openshell_core::proto::tcp_forward_frame::Payload::Init(
22202363
TcpForwardInit {
22212364
sandbox: name.to_string(),
22222365
workspace: workspace.to_string(),
22232366
service_id: format!("ssh-proxy:{name}"),
2224-
target: Some(tcp_forward_init::Target::Ssh(SshRelayTarget {})),
2225-
authorization_token: session.token.clone(),
2367+
target: Some(target),
2368+
authorization_token: token.to_owned(),
22262369
},
22272370
)),
22282371
};
2229-
let (tx, response) = open_forward_tcp(&mut client, init, owner.as_ref()).await;
2230-
Ok((tx, response.into_diagnostic()?.into_inner()))
2372+
let (tx, response) = open_forward_tcp(client, init, replica).await;
2373+
Ok((tx, response?.into_inner()))
22312374
}
22322375

22332376
fn host_alias(name: &str, workspace: &str) -> String {
@@ -2884,6 +3027,11 @@ mod tests {
28843027

28853028
#[test]
28863029
fn connect_retry_filter_rejects_authentication_failures() {
3030+
let denied = Report::new(SshAdmissionError::Rpc(tonic::Status::permission_denied(
3031+
"connection unavailable",
3032+
)));
3033+
assert!(!connect_error_is_retryable(&denied));
3034+
assert!(!sync_error_is_retryable(&denied));
28873035
let transient = miette::miette!("transport error: connection reset by peer");
28883036
assert!(connect_error_is_retryable(&transient));
28893037

0 commit comments

Comments
 (0)