ssh-cli 0.5.4

Native Rust CLI that gives LLMs (Claude Code, Cursor, Windsurf) the ability to operate remote servers via SSH over stdin/stdout
Documentation
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// G-COMP: unit tests extracted for line budget.
#![forbid(unsafe_code)]

use super::*;
use crate::cli::SshAuthArgs;
use crate::ssh::client::{
    ConnectionConfig, ExecutionOutput, SshClientTrait, TransferResult, TunnelChannel,
};
use crate::vps::model::{VpsRecord, CURRENT_SCHEMA_VERSION};
use crate::vps::{self, ConfigFile};
use async_trait::async_trait;
use secrecy::SecretString;
use serial_test::serial;
use std::collections::BTreeMap;
use std::path::Path;
use tempfile::TempDir;

struct FakeScpClient {
    upload_ok: bool,
    download_ok: bool,
    bytes_upload: u64,
    bytes_download: u64,
}

#[async_trait]
impl SshClientTrait for FakeScpClient {
    async fn connect(_cfg: ConnectionConfig) -> Result<Box<Self>, SshCliError> {
        Err(SshCliError::ConnectionFailed(
            "not implemented in test".into(),
        ))
    }

    async fn run_command(
        &mut self,
        _cmd: &str,
        _max_chars: usize,
        _stdin_data: Option<Vec<u8>>,
    ) -> Result<ExecutionOutput, SshCliError> {
        Err(SshCliError::channel_msg("not implemented in test"))
    }

    async fn upload(&self, _local: &Path, _remote: &Path) -> Result<TransferResult, SshCliError> {
        if self.upload_ok {
            Ok(TransferResult {
                bytes_transferred: self.bytes_upload,
                duration_ms: 10,
                ..Default::default()
            })
        } else {
            Err(SshCliError::channel_msg("upload failed"))
        }
    }

    async fn download(&self, _remote: &Path, _local: &Path) -> Result<TransferResult, SshCliError> {
        if self.download_ok {
            Ok(TransferResult {
                bytes_transferred: self.bytes_download,
                duration_ms: 20,
                ..Default::default()
            })
        } else {
            Err(SshCliError::channel_msg("download failed"))
        }
    }

    async fn open_tunnel_channel(
        &self,
        _host_remoto: &str,
        _porta_remota: u16,
        _endereco_origem: &str,
        _porta_origem: u16,
    ) -> Result<Box<dyn TunnelChannel>, SshCliError> {
        Err(SshCliError::channel_msg("not implemented in test"))
    }

    async fn disconnect(&self) -> Result<(), SshCliError> {
        Ok(())
    }
}

fn registro_teste(name: &str) -> VpsRecord {
    VpsRecord::test_new(
        name,
        "127.0.0.1",
        1,
        "root",
        SecretString::from("senha-teste".to_string()),
        None,
        None,
        Some(100),
        Some(1000),
        Some(1000),
        None,
        None,
        false,
    )
}

fn save_config_with_vps(tmp: &TempDir, name: &str) {
    let mut hosts = BTreeMap::new();
    hosts.insert(name.to_string(), registro_teste(name));
    let file = ConfigFile {
        schema_version: CURRENT_SCHEMA_VERSION,
        hosts,
    };
    let path = tmp.path().join("config.toml");
    vps::save(&path, &file).expect("save test config");
}

fn empty_auth() -> SshAuthArgs {
    SshAuthArgs {
        password: None,
        password_stdin: false,
        key: None,
        key_passphrase: None,
        key_passphrase_stdin: false,
        use_agent: false,
        agent_socket: None,
    }
}

/// G-PAR-47 / G-PAR-54: multi-file uses one session — N uploads, zero extra connects.
struct CountingSessionClient {
    uploads: std::sync::atomic::AtomicUsize,
    downloads: std::sync::atomic::AtomicUsize,
}

#[async_trait]
impl SshClientTrait for CountingSessionClient {
    async fn connect(_cfg: ConnectionConfig) -> Result<Box<Self>, SshCliError> {
        // Production multi-file calls connect once outside this helper.
        // If this is invoked, session-reuse was broken.
        Err(SshCliError::ConnectionFailed(
            "connect must not be called from multi_file_*_on_session".into(),
        ))
    }

    async fn run_command(
        &mut self,
        _cmd: &str,
        _max_chars: usize,
        _stdin_data: Option<Vec<u8>>,
    ) -> Result<ExecutionOutput, SshCliError> {
        Err(SshCliError::channel_msg("unused"))
    }

    async fn upload(&self, _local: &Path, _remote: &Path) -> Result<TransferResult, SshCliError> {
        self.uploads
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        Ok(TransferResult {
            bytes_transferred: 1,
            duration_ms: 1,
            ..Default::default()
        })
    }

    async fn download(&self, _remote: &Path, _local: &Path) -> Result<TransferResult, SshCliError> {
        self.downloads
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        Ok(TransferResult {
            bytes_transferred: 2,
            duration_ms: 1,
            ..Default::default()
        })
    }

    async fn open_tunnel_channel(
        &self,
        _host_remoto: &str,
        _porta_remota: u16,
        _endereco_origem: &str,
        _porta_origem: u16,
    ) -> Result<Box<dyn TunnelChannel>, SshCliError> {
        Err(SshCliError::channel_msg("unused"))
    }

    async fn disconnect(&self) -> Result<(), SshCliError> {
        Ok(())
    }
}

/// `#[serial]` is required: the transfer loop polls the process-wide cancel flags,
/// and sibling tests in this file (and in `concurrency_tests`) legitimately set them.
/// Run in parallel, this test observes a foreign cancellation and every result comes
/// back `ok: false` — a failure with no relation to the code under test.
#[tokio::test]
#[serial]
async fn multi_file_upload_on_session_n_files_one_client() {
    crate::signals::reset_flags_for_tests();
    let client = CountingSessionClient {
        uploads: std::sync::atomic::AtomicUsize::new(0),
        downloads: std::sync::atomic::AtomicUsize::new(0),
    };
    let sources = vec![
        PathBuf::from("a.bin"),
        PathBuf::from("b.bin"),
        PathBuf::from("c.bin"),
    ];
    let results =
        batch::multi_file_upload_on_session(&client, &sources, Path::new("/tmp"), None).await;
    assert_eq!(results.len(), 3);
    assert!(results.iter().all(|r| r.ok));
    assert_eq!(
        client.uploads.load(std::sync::atomic::Ordering::SeqCst),
        3,
        "three serial uploads on the same session"
    );
    assert_eq!(
        client.downloads.load(std::sync::atomic::Ordering::SeqCst),
        0
    );
}

/// See the upload counterpart: `#[serial]` protects against a foreign cancel flag.
#[tokio::test]
#[serial]
async fn multi_file_download_on_session_n_files_one_client() {
    crate::signals::reset_flags_for_tests();
    let client = CountingSessionClient {
        uploads: std::sync::atomic::AtomicUsize::new(0),
        downloads: std::sync::atomic::AtomicUsize::new(0),
    };
    let remotes = vec![PathBuf::from("/r/a"), PathBuf::from("/r/b")];
    let tmp = TempDir::new().unwrap();
    let results =
        batch::multi_file_download_on_session(&client, &remotes, tmp.path(), Some("prod")).await;
    assert_eq!(results.len(), 2);
    assert!(results.iter().all(|r| r.ok));
    assert!(results[0].name.starts_with("prod:"));
    assert_eq!(
        client.downloads.load(std::sync::atomic::Ordering::SeqCst),
        2
    );
}

/// G5/G17: cancel mid-batch must preserve input cardinality (no short vector).
#[tokio::test]
#[serial]
async fn multi_file_upload_cancel_preserves_cardinality() {
    crate::signals::reset_flags_for_tests();
    crate::signals::cancellation_flag().store(true, std::sync::atomic::Ordering::Release);
    let client = CountingSessionClient {
        uploads: std::sync::atomic::AtomicUsize::new(0),
        downloads: std::sync::atomic::AtomicUsize::new(0),
    };
    let sources = vec![
        PathBuf::from("a.bin"),
        PathBuf::from("b.bin"),
        PathBuf::from("c.bin"),
    ];
    let results =
        batch::multi_file_upload_on_session(&client, &sources, Path::new("/tmp"), None).await;
    crate::signals::reset_flags_for_tests();
    assert_eq!(
        results.len(),
        3,
        "G5: results.len() must equal sources.len()"
    );
    assert!(
        results.iter().all(|r| !r.ok),
        "all remaining must be cancelled"
    );
    assert_eq!(
        client.uploads.load(std::sync::atomic::Ordering::SeqCst),
        0,
        "no uploads after cancel"
    );
}

#[tokio::test]
async fn scp_upload_with_client_returns_ok() {
    let client = Box::new(FakeScpClient {
        upload_ok: true,
        download_ok: true,
        bytes_upload: 128,
        bytes_download: 0,
    });
    let local = Path::new("/tmp/local.txt");
    let remote = Path::new("/tmp/remote.txt");
    let result = run_scp_upload_with_client("v1", local, remote, client, false).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn scp_download_with_client_returns_ok() {
    let client = Box::new(FakeScpClient {
        upload_ok: true,
        download_ok: true,
        bytes_upload: 0,
        bytes_download: 256,
    });
    let result = run_scp_download_with_client(
        "v1",
        Path::new("/tmp/remote.txt"),
        Path::new("/tmp/local.txt"),
        client,
        false,
    )
    .await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn scp_upload_with_client_returns_error() {
    let client = Box::new(FakeScpClient {
        upload_ok: false,
        download_ok: true,
        bytes_upload: 0,
        bytes_download: 0,
    });
    let result = run_scp_upload_with_client(
        "v1",
        Path::new("/tmp/local.txt"),
        Path::new("/tmp/remote.txt"),
        client,
        false,
    )
    .await;
    assert!(result.is_err());
}

#[tokio::test]
async fn scp_download_with_client_returns_error() {
    let client = Box::new(FakeScpClient {
        upload_ok: true,
        download_ok: false,
        bytes_upload: 0,
        bytes_download: 0,
    });
    let result = run_scp_download_with_client(
        "v1",
        Path::new("/tmp/remote.txt"),
        Path::new("/tmp/local.txt"),
        client,
        false,
    )
    .await;
    assert!(result.is_err());
}

#[tokio::test]
#[serial]
async fn scp_upload_tries_connect_when_vps_exists() {
    let tmp = TempDir::new().unwrap();
    save_config_with_vps(&tmp, "vps-upload");
    let local = tmp.path().join("local.bin");
    std::fs::write(&local, b"abc").unwrap();
    let action = ScpAction::Upload {
        all: false,
        hosts: None,
        target: vec![
            "vps-upload".to_string(),
            local.display().to_string(),
            "/tmp/x".to_string(),
        ],
        auth: empty_auth(),
        timeout: Some(100),
        json: false,
    };
    let r = run_scp(
        action,
        Some(tmp.path().to_path_buf()),
        ScpOptions {
            timeout: Some(crate::domain::TimeoutMs::try_new(100).expect("timeout")),
            ..Default::default()
        },
    )
    .await;
    assert!(r.is_err());
}

#[tokio::test]
#[serial]
async fn scp_download_tries_connect_when_vps_exists() {
    let tmp = TempDir::new().unwrap();
    save_config_with_vps(&tmp, "vps-download");
    let action = ScpAction::Download {
        all: false,
        hosts: None,
        target: vec![
            "vps-download".to_string(),
            "/tmp/x".to_string(),
            tmp.path().join("out.bin").display().to_string(),
        ],
        auth: empty_auth(),
        timeout: Some(100),
        json: false,
    };
    let r = run_scp(
        action,
        Some(tmp.path().to_path_buf()),
        ScpOptions {
            timeout: Some(crate::domain::TimeoutMs::try_new(100).expect("timeout")),
            ..Default::default()
        },
    )
    .await;
    assert!(r.is_err());
}

#[tokio::test]
#[serial]
async fn scp_upload_rejects_directory() {
    let tmp = TempDir::new().unwrap();
    save_config_with_vps(&tmp, "vps-dir");
    let action = ScpAction::Upload {
        all: false,
        hosts: None,
        target: vec![
            "vps-dir".to_string(),
            tmp.path().display().to_string(),
            "/tmp/x".to_string(),
        ],
        auth: empty_auth(),
        timeout: None,
        json: false,
    };
    let r = run_scp(
        action,
        Some(tmp.path().to_path_buf()),
        ScpOptions::default(),
    )
    .await;
    assert!(r.is_err());
}