Skip to content

Commit 73d3803

Browse files
committed
refactor(ssh): isolate proxy command formatting and verify grant cleanup
Signed-off-by: Adrien Langou <alangou@nvidia.com>
1 parent b85b41c commit 73d3803

4 files changed

Lines changed: 43 additions & 36 deletions

File tree

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

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ struct SandboxState {
8585
ssh_requests_with_cached_bearer: Arc<AtomicUsize>,
8686
replace_after_first_ssh_revoke: Arc<AtomicBool>,
8787
ssh_session_revocations: Arc<AtomicUsize>,
88+
revoked_ssh_tokens: Arc<Mutex<Vec<String>>>,
8889
/// Reject token-less `ForwardTcp` inits the way a gateway that predates
8990
/// principal-authorized TCP forwards does.
9091
forward_requires_session_token: Arc<AtomicBool>,
@@ -459,8 +460,8 @@ impl OpenShell for TestOpenShell {
459460
let request = request.into_inner();
460461
let sandbox_id = self.state.ssh_sandbox_id(&request.sandbox);
461462
Ok(Response::new(CreateSshSessionResponse {
463+
token: format!("token-{sandbox_id}"),
462464
sandbox_id,
463-
token: "test-token".to_string(),
464465
gateway_scheme: "https".to_string(),
465466
gateway_host: "localhost".to_string(),
466467
gateway_port: 443,
@@ -503,8 +504,13 @@ impl OpenShell for TestOpenShell {
503504

504505
async fn revoke_ssh_session(
505506
&self,
506-
_request: tonic::Request<RevokeSshSessionRequest>,
507+
request: tonic::Request<RevokeSshSessionRequest>,
507508
) -> Result<Response<RevokeSshSessionResponse>, Status> {
509+
self.state
510+
.revoked_ssh_tokens
511+
.lock()
512+
.await
513+
.push(request.into_inner().token);
508514
self.state
509515
.ssh_session_revocations
510516
.fetch_add(1, Ordering::SeqCst);
@@ -892,7 +898,9 @@ impl OpenShell for TestOpenShell {
892898
"authorization_token is required for ForwardTcp",
893899
));
894900
}
895-
} else if init.authorization_token != "test-token" {
901+
} else if init.authorization_token
902+
!= format!("token-{}", self.state.ssh_sandbox_id(&init.sandbox))
903+
{
896904
return Err(Status::unauthenticated("SSH session token not found"));
897905
}
898906

@@ -3009,7 +3017,10 @@ async fn copy_retry_refuses_and_revokes_a_same_name_replacement() {
30093017
"{err:?}"
30103018
);
30113019
assert_eq!(state.ssh_session_requests.load(Ordering::SeqCst), 2);
3012-
assert_eq!(state.ssh_session_revocations.load(Ordering::SeqCst), 2);
3020+
assert_eq!(
3021+
*state.revoked_ssh_tokens.lock().await,
3022+
["token-id-copy", "token-replacement-copy"]
3023+
);
30133024
assert_eq!(fs::read(&file).unwrap(), b"original data");
30143025
}
30153026
})
@@ -4153,7 +4164,7 @@ async fn service_forward_falls_back_to_session_tokens_once_for_a_legacy_gateway(
41534164
echo_through_local_forward(&forward, port, b"first connection").await;
41544165
wait_for_count(&state.ssh_session_revocations, 1, "revocation").await;
41554166
let inits = state.forward_inits.lock().await.clone();
4156-
assert_eq!(forward_tokens(&inits), vec!["", "test-token"]);
4167+
assert_eq!(forward_tokens(&inits), vec!["", "token-id-svc-sandbox"]);
41574168
assert_eq!(state.forward_token_rejections.load(Ordering::SeqCst), 1);
41584169
assert_eq!(state.ssh_session_requests.load(Ordering::SeqCst), 1);
41594170

@@ -4162,7 +4173,10 @@ async fn service_forward_falls_back_to_session_tokens_once_for_a_legacy_gateway(
41624173
echo_through_local_forward(&forward, port, b"second connection").await;
41634174
wait_for_count(&state.ssh_session_revocations, 2, "revocations").await;
41644175
let inits = state.forward_inits.lock().await.clone();
4165-
assert_eq!(forward_tokens(&inits), vec!["", "test-token", "test-token"]);
4176+
assert_eq!(
4177+
forward_tokens(&inits),
4178+
vec!["", "token-id-svc-sandbox", "token-id-svc-sandbox"]
4179+
);
41664180
assert_eq!(state.forward_token_rejections.load(Ordering::SeqCst), 1);
41674181
assert_eq!(state.ssh_session_requests.load(Ordering::SeqCst), 2);
41684182
assert!(

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

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -124,18 +124,13 @@ async fn proxy_exits_with_stdin_open(relay_status: Status) {
124124
.kill_on_drop(true)
125125
.spawn()
126126
.unwrap();
127-
child
128-
.stdin
129-
.as_mut()
130-
.unwrap()
131-
.write_all(b"probe")
132-
.await
133-
.unwrap();
134-
// Keep child.stdin alive throughout wait: closing it would conceal the bug.
127+
let mut stdin = child.stdin.take().unwrap();
128+
stdin.write_all(b"probe").await.unwrap();
135129
let status = tokio::time::timeout(Duration::from_secs(5), child.wait())
136130
.await
137131
.expect("SSH proxy must exit even while the parent holds stdin open")
138132
.unwrap();
133+
drop(stdin);
139134
let mut stderr = String::new();
140135
tokio::io::AsyncReadExt::read_to_string(child.stderr.as_mut().unwrap(), &mut stderr)
141136
.await

‎crates/openshell-core/src/forward.rs‎

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -924,15 +924,15 @@ pub fn shell_escape(value: &str) -> String {
924924

925925
/// Build a one-use proxy command. The handle identifies an owner-only IPC
926926
/// endpoint. Only the parent and proxy exchange the relay credentials.
927-
pub fn build_proxy_command(handle: &str, sandbox: &str, workspace: &str) -> Result<String> {
928-
let exe = std::env::current_exe().into_diagnostic()?;
929-
Ok(format!(
927+
pub fn build_proxy_command(exe: &str, handle: &str, sandbox: &str, workspace: &str) -> String {
928+
format!(
930929
"{} ssh-proxy --sandbox {} --workspace {} --handoff {}",
931-
shell_escape(&exe.to_string_lossy()).replace('%', "%%"),
932-
shell_escape(sandbox).replace('%', "%%"),
933-
shell_escape(workspace).replace('%', "%%"),
930+
shell_escape(exe),
931+
shell_escape(sandbox),
932+
shell_escape(workspace),
934933
shell_escape(handle),
935-
))
934+
)
935+
.replace('%', "%%")
936936
}
937937

938938
/// Build the `ssh` options shared by every sandbox session.
@@ -1327,8 +1327,12 @@ mod tests {
13271327
#[test]
13281328
fn build_proxy_command_escapes_shell_metacharacters() {
13291329
// Attacker-controlled values in every escapable position.
1330-
let cmd =
1331-
build_proxy_command("handle", "x$(touch /tmp/pwn)x", "ws; touch /tmp/pwn").unwrap();
1330+
let cmd = build_proxy_command(
1331+
"/usr/local/bin/openshell",
1332+
"handle",
1333+
"x$(touch /tmp/pwn)x",
1334+
"ws; touch /tmp/pwn",
1335+
);
13321336

13331337
// The `$` / backtick must only appear inside single-quoted regions.
13341338
// A simple grep-based check: split on single-quoted runs and assert
@@ -1345,25 +1349,17 @@ mod tests {
13451349
fn build_proxy_command_empty_values_quote_rather_than_vanish() {
13461350
// An empty value must become `''` rather than disappearing — otherwise
13471351
// downstream argv splitting would misalign.
1348-
let cmd = build_proxy_command("handle", "", "").unwrap();
1352+
let cmd = build_proxy_command("exe", "handle", "", "");
13491353
assert!(cmd.contains("--sandbox ''"));
13501354
assert!(cmd.contains("--workspace ''"));
13511355
}
13521356

13531357
#[test]
13541358
fn build_proxy_command_contains_only_handle_and_sandbox_identity() {
1355-
let cmd = build_proxy_command("opaque", "sb-123", "workspace-1").unwrap();
1359+
let cmd = build_proxy_command("/opt/My %h/bin", "opaque", "sb-123", "workspace-1");
13561360
assert_eq!(
1357-
&split_proxy_command_words(&cmd)[1..],
1358-
&[
1359-
"ssh-proxy",
1360-
"--sandbox",
1361-
"sb-123",
1362-
"--workspace",
1363-
"workspace-1",
1364-
"--handoff",
1365-
"opaque"
1366-
]
1361+
cmd,
1362+
"'/opt/My %%h/bin' ssh-proxy --sandbox sb-123 --workspace workspace-1 --handoff opaque"
13671363
);
13681364
}
13691365

‎crates/openshell-core/src/ssh_handoff.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,9 @@ impl SshTarget {
126126
let id = Uuid::new_v4();
127127
let listener = ipc::Listener::bind(id).into_diagnostic()?;
128128
let handle = format!("{}-{id}", std::process::id());
129-
let command = build_proxy_command(&handle, &self.name, &self.workspace)?;
129+
let exe = std::env::current_exe().into_diagnostic()?;
130+
let command =
131+
build_proxy_command(&exe.to_string_lossy(), &handle, &self.name, &self.workspace);
130132
Ok((listener, command))
131133
};
132134
let (listener, command) = match setup() {

0 commit comments

Comments
 (0)