-
Notifications
You must be signed in to change notification settings - Fork 560
Expand file tree
/
Copy pathssh.rs
More file actions
1252 lines (1122 loc) · 40.9 KB
/
ssh.rs
File metadata and controls
1252 lines (1122 loc) · 40.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! SSH connection and proxy utilities.
use crate::tls::{TlsOptions, build_rustls_config, grpc_client, require_tls_materials};
use miette::{IntoDiagnostic, Result, WrapErr};
#[cfg(unix)]
use nix::sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal, sigaction};
use openshell_core::forward::{
find_ssh_forward_pid, resolve_ssh_gateway, shell_escape, write_forward_pid,
};
use openshell_core::proto::{CreateSshSessionRequest, GetSandboxRequest};
use owo_colors::OwoColorize;
use rustls::pki_types::ServerName;
use std::fs;
use std::io::IsTerminal;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::process::Command as TokioCommand;
use tokio_rustls::TlsConnector;
const FOREGROUND_FORWARD_STARTUP_GRACE_PERIOD: Duration = Duration::from_secs(2);
#[derive(Clone, Copy, Debug)]
pub enum Editor {
Vscode,
Cursor,
}
impl Editor {
fn binary(self) -> &'static str {
match self {
Self::Vscode => "code",
Self::Cursor => "cursor",
}
}
fn remote_target(self, host_alias: &str) -> String {
format!("ssh-remote+{host_alias}")
}
fn label(self) -> &'static str {
match self {
Self::Vscode => "VS Code",
Self::Cursor => "Cursor",
}
}
}
struct SshSessionConfig {
proxy_command: String,
sandbox_id: String,
gateway_url: String,
token: String,
}
async fn ssh_session_config(
server: &str,
name: &str,
tls: &TlsOptions,
) -> Result<SshSessionConfig> {
let mut client = grpc_client(server, tls).await?;
// Resolve sandbox name to id.
let sandbox = client
.get_sandbox(GetSandboxRequest {
name: name.to_string(),
})
.await
.into_diagnostic()?
.into_inner()
.sandbox
.ok_or_else(|| miette::miette!("sandbox not found"))?;
let response = client
.create_ssh_session(CreateSshSessionRequest {
sandbox_id: sandbox.id,
})
.await
.into_diagnostic()?;
let session = response.into_inner();
let exe = std::env::current_exe()
.into_diagnostic()
.wrap_err("failed to resolve OpenShell executable")?;
let exe_command = shell_escape(&exe.to_string_lossy());
// When using Cloudflare bearer auth, the SSH CONNECT must go through the
// external tunnel endpoint (the cluster URL), not the server's internal
// scheme/host/port which may be plaintext HTTP on 127.0.0.1.
let gateway_url = if tls.is_bearer_auth() {
let base = server.trim_end_matches('/');
format!("{base}{}", session.connect_path)
} else {
// If the server returned a loopback gateway address, override it with the
// cluster endpoint's host. This handles the case where the server defaults
// to 127.0.0.1 but the cluster is actually running on a remote host.
#[allow(clippy::cast_possible_truncation)]
let gateway_port_u16 = session.gateway_port as u16;
let (gateway_host, gateway_port) =
resolve_ssh_gateway(&session.gateway_host, gateway_port_u16, server);
format!(
"{}://{}:{}{}",
session.gateway_scheme, gateway_host, gateway_port, session.connect_path
)
};
let gateway_name = tls
.gateway_name()
.ok_or_else(|| miette::miette!("gateway name is required to build SSH proxy command"))?;
let proxy_command = format!(
"{exe_command} ssh-proxy --gateway {} --sandbox-id {} --token {} --gateway-name {}",
gateway_url,
session.sandbox_id,
session.token,
shell_escape(gateway_name),
);
Ok(SshSessionConfig {
proxy_command,
sandbox_id: session.sandbox_id.clone(),
gateway_url,
token: session.token,
})
}
fn ssh_base_command(proxy_command: &str) -> Command {
let mut command = Command::new("ssh");
command
.arg("-o")
.arg(format!("ProxyCommand={proxy_command}"))
.arg("-o")
.arg("StrictHostKeyChecking=no")
.arg("-o")
.arg("UserKnownHostsFile=/dev/null")
.arg("-o")
.arg("GlobalKnownHostsFile=/dev/null")
.arg("-o")
.arg("LogLevel=ERROR");
command
}
#[cfg(unix)]
const TRANSIENT_TTY_SIGNALS: &[Signal] = &[Signal::SIGINT, Signal::SIGQUIT, Signal::SIGTERM];
#[cfg(unix)]
struct ParentSignalGuard {
previous: Vec<(Signal, SigAction)>,
}
#[cfg(unix)]
impl ParentSignalGuard {
#[allow(unsafe_code)]
fn ignore_transient_tty_signals() -> Result<Self> {
let mut previous = Vec::with_capacity(TRANSIENT_TTY_SIGNALS.len());
for &signal in TRANSIENT_TTY_SIGNALS {
let action = SigAction::new(SigHandler::SigIgn, SaFlags::empty(), SigSet::empty());
// SAFETY: `sigaction` is the POSIX API for updating process signal
// dispositions. We install `SIG_IGN` for a small fixed set of
// terminal signals and store the previous handlers for restoration.
let old = unsafe { sigaction(signal, &action) }.into_diagnostic()?;
previous.push((signal, old));
}
Ok(Self { previous })
}
}
#[cfg(unix)]
impl Drop for ParentSignalGuard {
#[allow(unsafe_code)]
fn drop(&mut self) {
for &(signal, previous) in self.previous.iter().rev() {
// SAFETY: these `SigAction` values were returned by `sigaction`
// above for this process, so restoring them here returns the parent
// signal handlers to their original state.
let _ = unsafe { sigaction(signal, &previous) };
}
}
}
#[cfg(unix)]
#[allow(unsafe_code)]
fn reset_transient_tty_signals(command: &mut Command) {
// SAFETY: `pre_exec` runs in the forked child immediately before `exec`.
// We only reset a small fixed set of signal handlers to `SIG_DFL`, which is
// required so SSH receives terminal signals normally even though the parent
// process temporarily ignores them to preserve cleanup.
unsafe {
command.pre_exec(|| {
for &signal in TRANSIENT_TTY_SIGNALS {
let action = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty());
sigaction(signal, &action).map_err(|err| std::io::Error::other(err.to_string()))?;
}
Ok(())
});
}
}
fn exec_or_wait(mut command: Command, replace_process: bool) -> Result<()> {
if replace_process && std::io::stdin().is_terminal() {
#[cfg(unix)]
{
let err = command.exec();
return Err(miette::miette!("failed to exec ssh: {err}"));
}
}
#[cfg(unix)]
let _signal_guard = if !replace_process && std::io::stdin().is_terminal() {
reset_transient_tty_signals(&mut command);
Some(ParentSignalGuard::ignore_transient_tty_signals()?)
} else {
None
};
let status = command.status().into_diagnostic()?;
if !status.success() {
return Err(miette::miette!("ssh exited with status {status}"));
}
Ok(())
}
async fn sandbox_connect_with_mode(
server: &str,
name: &str,
tls: &TlsOptions,
replace_process: bool,
) -> Result<()> {
let session = ssh_session_config(server, name, tls).await?;
let mut command = ssh_base_command(&session.proxy_command);
command
.arg("-tt")
.arg("-o")
.arg("RequestTTY=force")
.arg("-o")
.arg("SetEnv=TERM=xterm-256color")
.arg("sandbox")
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
tokio::task::spawn_blocking(move || exec_or_wait(command, replace_process))
.await
.into_diagnostic()??;
Ok(())
}
/// Connect to a sandbox via SSH.
pub async fn sandbox_connect(server: &str, name: &str, tls: &TlsOptions) -> Result<()> {
sandbox_connect_with_mode(server, name, tls, true).await
}
pub(crate) async fn sandbox_connect_without_exec(
server: &str,
name: &str,
tls: &TlsOptions,
) -> Result<()> {
sandbox_connect_with_mode(server, name, tls, false).await
}
pub async fn sandbox_connect_editor(
server: &str,
gateway: &str,
name: &str,
editor: Editor,
tls: &TlsOptions,
) -> Result<()> {
// Verify the sandbox exists before writing SSH config / launching the editor.
let mut client = grpc_client(server, tls).await?;
client
.get_sandbox(GetSandboxRequest {
name: name.to_string(),
})
.await
.into_diagnostic()?
.into_inner()
.sandbox
.ok_or_else(|| miette::miette!("sandbox not found: {name}"))?;
let host_alias = host_alias(name);
install_ssh_config(gateway, name)?;
launch_editor(editor, &host_alias)?;
eprintln!(
"{} Opened {} for sandbox {}",
"✓".green().bold(),
editor.label(),
name
);
Ok(())
}
/// Forward a local port to a sandbox via SSH.
///
/// When `background` is `true` the SSH process is forked into the background
/// (using `-f`) and its PID is written to a state file so it can be managed
/// later via [`stop_forward`] or [`list_forwards`].
pub async fn sandbox_forward(
server: &str,
name: &str,
spec: &openshell_core::forward::ForwardSpec,
background: bool,
tls: &TlsOptions,
) -> Result<()> {
openshell_core::forward::check_port_available(spec)?;
let session = ssh_session_config(server, name, tls).await?;
let mut command = TokioCommand::from(ssh_base_command(&session.proxy_command));
command
.arg("-N")
.arg("-o")
.arg("ExitOnForwardFailure=yes")
.arg("-L")
.arg(spec.ssh_forward_arg());
if background {
// SSH -f: fork to background after authentication.
command.arg("-f");
}
command
.arg("sandbox")
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
let port = spec.port;
let status = if background {
command.status().await.into_diagnostic()?
} else {
let mut child = command.spawn().into_diagnostic()?;
match tokio::time::timeout(FOREGROUND_FORWARD_STARTUP_GRACE_PERIOD, child.wait()).await {
Ok(status) => status.into_diagnostic()?,
Err(_) => {
eprintln!("{}", foreground_forward_started_message(name, spec));
child.wait().await.into_diagnostic()?
}
}
};
if !status.success() {
return Err(miette::miette!("ssh exited with status {status}"));
}
if background {
// SSH has forked — find its PID and record it.
if let Some(pid) = find_ssh_forward_pid(&session.sandbox_id, port) {
write_forward_pid(name, port, pid, &session.sandbox_id, &spec.bind_addr)?;
} else {
eprintln!(
"{} Could not discover backgrounded SSH process; \
forward may be running but is not tracked",
"!".yellow(),
);
}
}
Ok(())
}
fn foreground_forward_started_message(
name: &str,
spec: &openshell_core::forward::ForwardSpec,
) -> String {
format!(
"{} Forwarding port {} to sandbox {name}\n Access at: {}\n Press Ctrl+C to stop\n {}",
"✓".green().bold(),
spec.port,
spec.access_url(),
"Hint: pass --background to start forwarding without blocking your terminal".dimmed(),
)
}
async fn sandbox_exec_with_mode(
server: &str,
name: &str,
command: &[String],
tty: bool,
tls: &TlsOptions,
replace_process: bool,
) -> Result<()> {
if command.is_empty() {
return Err(miette::miette!("no command provided"));
}
let session = ssh_session_config(server, name, tls).await?;
let mut ssh = ssh_base_command(&session.proxy_command);
if tty {
ssh.arg("-tt")
.arg("-o")
.arg("RequestTTY=force")
.arg("-o")
.arg("SetEnv=TERM=xterm-256color");
} else {
ssh.arg("-T").arg("-o").arg("RequestTTY=no");
}
let command_str = command
.iter()
.map(|arg| shell_escape(arg))
.collect::<Vec<_>>()
.join(" ");
ssh.arg("sandbox")
.arg(command_str)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
tokio::task::spawn_blocking(move || exec_or_wait(ssh, tty && replace_process))
.await
.into_diagnostic()??;
Ok(())
}
/// Execute a command in a sandbox via SSH.
pub async fn sandbox_exec(
server: &str,
name: &str,
command: &[String],
tty: bool,
tls: &TlsOptions,
) -> Result<()> {
sandbox_exec_with_mode(server, name, command, tty, tls, true).await
}
pub(crate) async fn sandbox_exec_without_exec(
server: &str,
name: &str,
command: &[String],
tty: bool,
tls: &TlsOptions,
) -> Result<()> {
sandbox_exec_with_mode(server, name, command, tty, tls, false).await
}
/// What to pack into the tar archive streamed to the sandbox.
enum UploadSource {
/// A single local file or directory. `tar_name` controls the entry name
/// inside the archive (e.g. the target basename for file-to-file uploads).
SinglePath {
local_path: PathBuf,
tar_name: std::ffi::OsString,
},
/// A set of files relative to a base directory (git-filtered uploads).
FileList {
base_dir: PathBuf,
files: Vec<String>,
},
}
/// Core tar-over-SSH upload: streams a tar archive into `dest_dir` on the
/// sandbox. Callers are responsible for splitting the destination path so
/// that `dest_dir` is always a directory.
///
/// When `dest_dir` is `None`, the sandbox user's home directory (`$HOME`) is
/// used as the extraction target. This avoids hard-coding any particular
/// path and works for custom container images with non-default `WORKDIR`.
async fn ssh_tar_upload(
server: &str,
name: &str,
dest_dir: Option<&str>,
source: UploadSource,
tls: &TlsOptions,
) -> Result<()> {
let session = ssh_session_config(server, name, tls).await?;
// When no explicit destination is given, use the unescaped `$HOME` shell
// variable so the remote shell resolves it at runtime.
let escaped_dest = match dest_dir {
Some(d) => shell_escape(d),
None => "$HOME".to_string(),
};
let mut ssh = ssh_base_command(&session.proxy_command);
ssh.arg("-T")
.arg("-o")
.arg("RequestTTY=no")
.arg("sandbox")
.arg(format!(
"mkdir -p {escaped_dest} && cat | tar xf - -C {escaped_dest}",
))
.stdin(Stdio::piped())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
let mut child = ssh.spawn().into_diagnostic()?;
let stdin = child
.stdin
.take()
.ok_or_else(|| miette::miette!("failed to open stdin for ssh process"))?;
// Build the tar archive in a blocking task since the tar crate is synchronous.
tokio::task::spawn_blocking(move || -> Result<()> {
let mut archive = tar::Builder::new(stdin);
match source {
UploadSource::SinglePath {
local_path,
tar_name,
} => {
if local_path.is_file() {
archive
.append_path_with_name(&local_path, &tar_name)
.into_diagnostic()?;
} else if local_path.is_dir() {
archive.append_dir_all(".", &local_path).into_diagnostic()?;
} else {
return Err(miette::miette!(
"local path does not exist: {}",
local_path.display()
));
}
}
UploadSource::FileList { base_dir, files } => {
for file in &files {
let full_path = base_dir.join(file);
if full_path.is_file() {
archive
.append_path_with_name(&full_path, file)
.into_diagnostic()
.wrap_err_with(|| format!("failed to add {file} to tar archive"))?;
} else if full_path.is_dir() {
archive
.append_dir_all(file, &full_path)
.into_diagnostic()
.wrap_err_with(|| {
format!("failed to add directory {file} to tar archive")
})?;
}
}
}
}
archive.finish().into_diagnostic()?;
Ok(())
})
.await
.into_diagnostic()??;
let status = tokio::task::spawn_blocking(move || child.wait())
.await
.into_diagnostic()?
.into_diagnostic()?;
if !status.success() {
return Err(miette::miette!(
"ssh tar extract exited with status {status}"
));
}
Ok(())
}
/// Split a sandbox path into (parent_directory, basename).
///
/// Examples:
/// `"/sandbox/.bashrc"` -> `("/sandbox", ".bashrc")`
/// `"/sandbox/sub/file"` -> `("/sandbox/sub", "file")`
/// `"file.txt"` -> `(".", "file.txt")`
fn split_sandbox_path(path: &str) -> (&str, &str) {
match path.rfind('/') {
Some(0) => ("/", &path[1..]),
Some(pos) => (&path[..pos], &path[pos + 1..]),
None => (".", path),
}
}
/// Push a list of files from a local directory into a sandbox using tar-over-SSH.
///
/// Files are streamed as a tar archive to `ssh ... tar xf - -C <dest>` on
/// the sandbox side. When `dest` is `None`, files are uploaded to the
/// sandbox user's home directory.
pub async fn sandbox_sync_up_files(
server: &str,
name: &str,
base_dir: &Path,
files: &[String],
dest: Option<&str>,
tls: &TlsOptions,
) -> Result<()> {
if files.is_empty() {
return Ok(());
}
ssh_tar_upload(
server,
name,
dest,
UploadSource::FileList {
base_dir: base_dir.to_path_buf(),
files: files.to_vec(),
},
tls,
)
.await
}
/// Push a local path (file or directory) into a sandbox using tar-over-SSH.
///
/// When `sandbox_path` is `None`, files are uploaded to the sandbox user's
/// home directory. When uploading a single file to an explicit destination
/// that does not end with `/`, the destination is treated as a file path:
/// the parent directory is created and the file is written with the
/// destination's basename. This matches `cp` / `scp` semantics.
pub async fn sandbox_sync_up(
server: &str,
name: &str,
local_path: &Path,
sandbox_path: Option<&str>,
tls: &TlsOptions,
) -> Result<()> {
// When an explicit destination is given and looks like a file path (does
// not end with '/'), split into parent directory + target basename so that
// `mkdir -p` creates the parent and tar extracts the file with the right
// name.
//
// Exception: if splitting would yield "/" as the parent (e.g. the user
// passed "/sandbox"), fall through to directory semantics instead. The
// sandbox user cannot write to "/" and the intent is almost certainly
// "put the file inside /sandbox", not "create a file named sandbox in /".
if let Some(path) = sandbox_path {
if local_path.is_file() && !path.ends_with('/') {
let (parent, target_name) = split_sandbox_path(path);
if parent != "/" {
return ssh_tar_upload(
server,
name,
Some(parent),
UploadSource::SinglePath {
local_path: local_path.to_path_buf(),
tar_name: target_name.into(),
},
tls,
)
.await;
}
}
}
let tar_name = if local_path.is_file() {
local_path
.file_name()
.ok_or_else(|| miette::miette!("path has no file name"))?
.to_os_string()
} else {
// For directories the tar_name is unused — append_dir_all uses "."
".".into()
};
ssh_tar_upload(
server,
name,
sandbox_path,
UploadSource::SinglePath {
local_path: local_path.to_path_buf(),
tar_name,
},
tls,
)
.await
}
/// Pull a path from a sandbox to a local destination using tar-over-SSH.
pub async fn sandbox_sync_down(
server: &str,
name: &str,
sandbox_path: &str,
local_path: &Path,
tls: &TlsOptions,
) -> Result<()> {
let session = ssh_session_config(server, name, tls).await?;
// Build tar command. When the sandbox path is a directory we tar its
// *contents* (using `-C <path> .`) so the caller gets the files directly
// without an extra wrapper directory. For a single file we split into
// the parent directory and the filename.
let sandbox_path_clean = sandbox_path.trim_end_matches('/');
let tar_cmd = format!(
"if [ -d {path} ]; then tar cf - -C {path} .; else tar cf - -C {parent} {name}; fi",
path = shell_escape(sandbox_path_clean),
parent = shell_escape(
sandbox_path_clean
.rfind('/')
.map_or(".", |pos| if pos == 0 {
"/"
} else {
&sandbox_path_clean[..pos]
})
),
name = shell_escape(
sandbox_path_clean
.rfind('/')
.map_or(sandbox_path_clean, |pos| &sandbox_path_clean[pos + 1..])
),
);
let mut ssh = ssh_base_command(&session.proxy_command);
ssh.arg("-T")
.arg("-o")
.arg("RequestTTY=no")
.arg("sandbox")
.arg(tar_cmd)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::inherit());
let mut child = ssh.spawn().into_diagnostic()?;
let stdout = child
.stdout
.take()
.ok_or_else(|| miette::miette!("failed to open stdout for ssh process"))?;
let local_path = local_path.to_path_buf();
tokio::task::spawn_blocking(move || -> Result<()> {
fs::create_dir_all(&local_path)
.into_diagnostic()
.wrap_err("failed to create local destination directory")?;
let mut archive = tar::Archive::new(stdout);
archive
.unpack(&local_path)
.into_diagnostic()
.wrap_err("failed to extract tar archive from sandbox")?;
Ok(())
})
.await
.into_diagnostic()??;
let status = tokio::task::spawn_blocking(move || child.wait())
.await
.into_diagnostic()?
.into_diagnostic()?;
if !status.success() {
return Err(miette::miette!(
"ssh tar create exited with status {status}"
));
}
Ok(())
}
/// Run the SSH proxy, connecting stdin/stdout to the gateway.
pub async fn sandbox_ssh_proxy(
gateway_url: &str,
sandbox_id: &str,
token: &str,
tls: &TlsOptions,
) -> Result<()> {
let url: url::Url = gateway_url
.parse()
.into_diagnostic()
.wrap_err("invalid gateway URL")?;
let scheme = url.scheme();
let gateway_host = url
.host_str()
.ok_or_else(|| miette::miette!("gateway URL missing host"))?;
let gateway_port = url
.port_or_known_default()
.ok_or_else(|| miette::miette!("gateway URL missing port"))?;
let connect_path = url.path();
let mut stream: Box<dyn ProxyStream> =
connect_gateway(scheme, gateway_host, gateway_port, tls).await?;
let request = format!(
"CONNECT {connect_path} HTTP/1.1\r\nHost: {gateway_host}\r\nX-Sandbox-Id: {sandbox_id}\r\nX-Sandbox-Token: {token}\r\n\r\n"
);
stream
.write_all(request.as_bytes())
.await
.into_diagnostic()?;
// Wrap in a BufReader **before** reading the HTTP response. The gateway
// may send the 200 OK response and the first SSH protocol bytes in the
// same TCP segment / WebSocket frame. A plain `read()` would consume
// those SSH bytes into our buffer and discard them, causing SSH to see a
// truncated protocol banner and exit with code 255. BufReader ensures
// any bytes read past the `\r\n\r\n` header boundary stay buffered and
// are returned by subsequent reads during the bidirectional copy phase.
let mut buf_stream = BufReader::new(stream);
let status = read_connect_status(&mut buf_stream).await?;
if status != 200 {
return Err(miette::miette!(
"gateway CONNECT failed with status {status}"
));
}
let (reader, writer) = tokio::io::split(buf_stream);
let stdin = tokio::io::stdin();
let stdout = tokio::io::stdout();
// Spawn both copy directions as independent tasks. Using separate spawned
// tasks (instead of try_join!/select!) ensures that when one direction
// completes or errors, the other continues independently until it also
// finishes. This is critical: when the remote side closes the connection,
// we must keep the stdin→gateway copy alive so SSH can finish sending its
// protocol-close packets, and vice-versa.
let to_remote = tokio::spawn(copy_ignoring_errors(stdin, writer));
let from_remote = tokio::spawn(copy_ignoring_errors(reader, stdout));
let _ = from_remote.await;
// Once the remote→stdout direction is done, SSH has received all the data
// it needs. Drop the stdin→gateway task – SSH will close its pipe when
// it's done regardless.
to_remote.abort();
Ok(())
}
/// Run the SSH proxy in "name mode": create a session on the fly, then proxy.
///
/// This is equivalent to [`sandbox_ssh_proxy`] but accepts a cluster endpoint
/// and sandbox name instead of pre-created gateway/token credentials. It is
/// suitable for use as an SSH `ProxyCommand` in `~/.ssh/config` because it
/// creates a fresh session on every invocation.
pub async fn sandbox_ssh_proxy_by_name(server: &str, name: &str, tls: &TlsOptions) -> Result<()> {
let session = ssh_session_config(server, name, tls).await?;
sandbox_ssh_proxy(
&session.gateway_url,
&session.sandbox_id,
&session.token,
tls,
)
.await
}
fn host_alias(name: &str) -> String {
format!("openshell-{name}")
}
fn render_ssh_config(gateway: &str, name: &str) -> String {
let exe = std::env::current_exe().expect("failed to resolve OpenShell executable");
let exe = shell_escape(&exe.to_string_lossy());
let proxy_cmd = format!("{exe} ssh-proxy --gateway-name {gateway} --name {name}");
let host_alias = host_alias(name);
format!(
"Host {host_alias}\n User sandbox\n StrictHostKeyChecking no\n UserKnownHostsFile /dev/null\n GlobalKnownHostsFile /dev/null\n LogLevel ERROR\n ProxyCommand {proxy_cmd}\n"
)
}
fn openshell_ssh_config_path() -> Result<PathBuf> {
Ok(openshell_core::paths::xdg_config_dir()?
.join("openshell")
.join("ssh_config"))
}
fn user_ssh_config_path() -> Result<PathBuf> {
let home = std::env::var("HOME")
.into_diagnostic()
.wrap_err("HOME is not set")?;
Ok(PathBuf::from(home).join(".ssh").join("config"))
}
fn render_include_line(path: &Path) -> String {
format!("Include \"{}\"", path.display())
}
fn ssh_config_includes_path(contents: &str, path: &Path) -> bool {
let quoted = format!("\"{}\"", path.display());
let plain = path.display().to_string();
contents.lines().any(|line| {
let trimmed = line.trim();
if !trimmed.starts_with("Include ") {
return false;
}
trimmed["Include ".len()..]
.split_whitespace()
.any(|token| token == quoted || token == plain)
})
}
fn ensure_openshell_include(main_config: &Path, managed_config: &Path) -> Result<()> {
if let Some(parent) = main_config.parent() {
fs::create_dir_all(parent)
.into_diagnostic()
.wrap_err("failed to create ~/.ssh directory")?;
}
let include_line = render_include_line(managed_config);
let contents = fs::read_to_string(main_config).unwrap_or_default();
let mut lines: Vec<&str> = contents.lines().collect();
lines.retain(|line| !ssh_config_includes_path(line, managed_config));
let insert_at = lines
.iter()
.position(|line| {
let trimmed = line.trim_start();
trimmed.starts_with("Host ") || trimmed.starts_with("Match ")
})
.unwrap_or(lines.len());
let mut out = Vec::new();
out.extend_from_slice(&lines[..insert_at]);
if !out.is_empty() && !out.last().is_some_and(|line| line.is_empty()) {
out.push("");
}
out.push(&include_line);
if insert_at < lines.len() && !lines[insert_at].is_empty() {
out.push("");
}
out.extend_from_slice(&lines[insert_at..]);
let mut rendered = out.join("\n");
if !rendered.is_empty() {
rendered.push('\n');
}
fs::write(main_config, rendered)
.into_diagnostic()
.wrap_err("failed to update ~/.ssh/config")?;
Ok(())
}
fn host_line_matches(line: &str, alias: &str) -> bool {
let trimmed = line.trim_start();
if !trimmed.starts_with("Host ") {
return false;
}
trimmed["Host ".len()..]
.split_whitespace()
.any(|token| token == alias)
}
fn upsert_host_block(contents: &str, alias: &str, block: &str) -> String {
let lines: Vec<&str> = contents.lines().collect();
let start = lines.iter().position(|line| host_line_matches(line, alias));
let mut out = Vec::new();
if let Some(start) = start {
let end = lines
.iter()
.enumerate()
.skip(start + 1)
.find(|(_, line)| line.trim_start().starts_with("Host "))
.map(|(idx, _)| idx)
.unwrap_or(lines.len());
out.extend_from_slice(&lines[..start]);
if !out.is_empty() && !out.last().is_some_and(|line| line.is_empty()) {
out.push("");
}
out.extend(block.lines());
if end < lines.len() && !lines[end..].first().is_some_and(|line| line.is_empty()) {
out.push("");
}
out.extend_from_slice(&lines[end..]);
} else {
out.extend_from_slice(&lines);
if !out.is_empty() && !out.last().is_some_and(|line| line.is_empty()) {
out.push("");
}
out.extend(block.lines());
}
let mut rendered = out.join("\n");
if !rendered.is_empty() {
rendered.push('\n');
}
rendered
}
pub fn install_ssh_config(gateway: &str, name: &str) -> Result<PathBuf> {
let managed_config = openshell_ssh_config_path()?;
let main_config = user_ssh_config_path()?;
ensure_openshell_include(&main_config, &managed_config)?;
if let Some(parent) = managed_config.parent() {
openshell_core::paths::create_dir_restricted(parent)?;
}
let alias = host_alias(name);
let block = render_ssh_config(gateway, name);
let contents = fs::read_to_string(&managed_config).unwrap_or_default();
let updated = upsert_host_block(&contents, &alias, &block);
fs::write(&managed_config, updated)
.into_diagnostic()
.wrap_err("failed to write OpenShell SSH config")?;
Ok(managed_config)
}
fn launch_editor(editor: Editor, host_alias: &str) -> Result<()> {
launch_editor_command(
editor.binary(),
editor.label(),
&editor.remote_target(host_alias),
)
}