ssh-cli 0.5.1

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
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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Data model for `VpsRecord` (schema v3).
//!
//! Passwords use `SecretString` for automatic zeroize via `Drop`. On-disk TOML is
//! plaintext (mode 0o600) or encrypted (`sshcli-enc:v1:`) when a primary key exists.
//! `Debug` is customized to NEVER expose sensitive values.
//!
//! Schema v3: **English wire keys** on serialize (`name`, `port`, `username`, …).
//! Deserialize accepts both EN and legacy Portuguese aliases (`nome`, `porta`, …).
//! Schema v2: password **or** key auth, max_command/max_output duality, `disable_sudo`.

use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};

/// Current schema version of the `config.toml` file.
pub const CURRENT_SCHEMA_VERSION: u32 = 3;

/// Default timeout in milliseconds (60s).
pub const DEFAULT_TIMEOUT_MS: u64 = 60_000;

/// Default character limit for the **command** (one-shot maxChars).
pub const DEFAULT_MAX_COMMAND_CHARS: usize = 1_000;

/// Default character limit for captured **output**.
pub const DEFAULT_MAX_OUTPUT_CHARS: usize = 100_000;

/// VPS host record in the configuration file.
///
/// Wire format (serialize): English field names. Legacy Portuguese keys remain
/// readable via `serde(alias = …)` (GAP-AUD-20260717-001/002/021).
#[derive(Clone, Serialize, Deserialize)]
pub struct VpsRecord {
    /// Logical unique VPS name.
    #[serde(alias = "nome")]
    pub name: String,
    /// Server hostname or IP.
    pub host: String,
    /// SSH port.
    #[serde(alias = "porta")]
    pub port: u16,
    /// SSH username.
    #[serde(alias = "usuario")]
    pub username: String,
    /// SSH password (empty when key-only auth).
    #[serde(default, alias = "senha", with = "secret_string_serde")]
    pub password: SecretString,
    /// Absolute or expandable OpenSSH private key path.
    #[serde(default)]
    pub key_path: Option<String>,
    /// Private key passphrase (optional).
    #[serde(default, with = "opcao_secret_string_serde")]
    pub key_passphrase: Option<SecretString>,
    /// Timeout in milliseconds.
    #[serde(default = "default_timeout_ms")]
    pub timeout_ms: u64,
    /// Command character limit (input). `0` = unlimited at runtime.
    #[serde(default = "default_max_command_chars")]
    pub max_command_chars: usize,
    /// Stdout/stderr character limit. Accepts legacy alias `max_chars`.
    #[serde(default = "default_max_output_chars", alias = "max_chars")]
    pub max_output_chars: usize,
    /// Password for `sudo` (optional).
    #[serde(default, alias = "senha_sudo", with = "opcao_secret_string_serde")]
    pub sudo_password: Option<SecretString>,
    /// Password for `su -` (optional).
    #[serde(default, alias = "senha_su", with = "opcao_secret_string_serde")]
    pub su_password: Option<SecretString>,
    /// If true, `sudo-exec` and `su-exec` are rejected for this host.
    #[serde(default)]
    pub disable_sudo: bool,
    /// Schema version for this record.
    #[serde(default = "default_schema_version")]
    pub schema_version: u32,
    /// RFC 3339 inclusion timestamp.
    #[serde(default = "default_added_at", alias = "adicionado_em")]
    pub added_at: String,
}

fn default_max_command_chars() -> usize {
    DEFAULT_MAX_COMMAND_CHARS
}

fn default_max_output_chars() -> usize {
    DEFAULT_MAX_OUTPUT_CHARS
}

fn default_timeout_ms() -> u64 {
    DEFAULT_TIMEOUT_MS
}

fn default_schema_version() -> u32 {
    CURRENT_SCHEMA_VERSION
}

fn default_added_at() -> String {
    chrono::Utc::now().to_rfc3339()
}

impl std::fmt::Debug for VpsRecord {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VpsRecord")
            .field("name", &self.name)
            .field("host", &self.host)
            .field("port", &self.port)
            .field("username", &self.username)
            .field("password", &"<redacted>")
            .field("key_path", &self.key_path)
            .field(
                "key_passphrase",
                &self.key_passphrase.as_ref().map(|_| "<redacted>"),
            )
            .field("timeout_ms", &self.timeout_ms)
            .field("max_command_chars", &self.max_command_chars)
            .field("max_output_chars", &self.max_output_chars)
            .field(
                "sudo_password",
                &self.sudo_password.as_ref().map(|_| "<redacted>"),
            )
            .field("su_password", &self.su_password.as_ref().map(|_| "<redacted>"))
            .field("disable_sudo", &self.disable_sudo)
            .field("schema_version", &self.schema_version)
            .field("added_at", &self.added_at)
            .finish()
    }
}

impl VpsRecord {
    /// Creates a new record applying defaults.
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        name: String,
        host: String,
        port: u16,
        username: String,
        password: SecretString,
        key_path: Option<String>,
        key_passphrase: Option<SecretString>,
        timeout_ms: Option<u64>,
        max_command_chars: Option<usize>,
        max_output_chars: Option<usize>,
        sudo_password: Option<SecretString>,
        su_password: Option<SecretString>,
        disable_sudo: bool,
    ) -> Self {
        Self {
            name,
            host,
            port,
            username,
            password,
            key_path,
            key_passphrase,
            timeout_ms: timeout_ms.unwrap_or(DEFAULT_TIMEOUT_MS),
            max_command_chars: max_command_chars.unwrap_or(DEFAULT_MAX_COMMAND_CHARS),
            max_output_chars: max_output_chars.unwrap_or(DEFAULT_MAX_OUTPUT_CHARS),
            sudo_password,
            su_password,
            disable_sudo,
            schema_version: CURRENT_SCHEMA_VERSION,
            added_at: chrono::Utc::now().to_rfc3339(),
        }
    }

    /// Returns true if there is a non-empty password.
    #[must_use]
    pub fn has_password(&self) -> bool {
        !self.password.expose_secret().is_empty()
    }

    /// Returns true if there is a private key path.
    #[must_use]
    pub fn has_key(&self) -> bool {
        self.key_path.as_ref().is_some_and(|p| !p.trim().is_empty())
    }

    /// Validates that at least one authentication method exists.
    pub fn validate_credentials(&self) -> Result<(), String> {
        if !self.has_password() && !self.has_key() {
            return Err(
                "must provide --password or --key (password or private key auth)"
                    .to_string(),
            );
        }
        Ok(())
    }

    /// Full record validation at the write boundary (add/edit/import).
    ///
    /// Ensures port ∈ 1..=65535, non-empty host/user, and credentials present.
    /// Does not check that `key_path` exists on the filesystem (dispatcher does).
    pub fn validate(&self) -> Result<(), String> {
        if self.port == 0 {
            return Err("invalid SSH port: 0 (use 1..=65535)".to_string());
        }
        if self.host.trim().is_empty() {
            return Err("host cannot be empty".to_string());
        }
        if self.username.trim().is_empty() {
            return Err("SSH username cannot be empty".to_string());
        }
        self.validate_credentials()
    }

    /// Normalizes schema after deserialization (v1 → v2 migration).
    pub fn normalize_schema(&mut self) {
        if self.schema_version < CURRENT_SCHEMA_VERSION {
            self.schema_version = CURRENT_SCHEMA_VERSION;
        }
        if self.max_command_chars == 0 && self.max_output_chars == 0 {
            // nothing: 0 means unlimited at runtime validation
        }
    }
}

/// Parses a limit string (`"none"`, `"0"`, or a number).
///
/// `0`/`none` → `0` (unlimited at runtime).
#[must_use]
pub fn parse_char_limit(s: &str) -> usize {
    let t = s.trim();
    if t.eq_ignore_ascii_case("none") || t == "0" {
        0
    } else {
        t.parse().unwrap_or(DEFAULT_MAX_OUTPUT_CHARS)
    }
}

/// Converts a config limit into the effective value for truncation/validation.
///
/// `0` = unlimited (`usize::MAX` for comparison).
#[must_use]
pub fn effective_limit(configured: usize) -> usize {
    if configured == 0 {
        usize::MAX
    } else {
        configured
    }
}

mod secret_string_serde {
    use super::{ExposeSecret, SecretString};
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S: Serializer>(value: &SecretString, s: S) -> Result<S::Ok, S::Error> {
        let plain = value.expose_secret();
        let out = crate::secrets::serialize_secret(plain).map_err(serde::ser::Error::custom)?;
        s.serialize_str(&out)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<SecretString, D::Error> {
        let s = String::deserialize(d)?;
        let plain = crate::secrets::deserialize_secret(&s).map_err(serde::de::Error::custom)?;
        Ok(SecretString::from(plain))
    }
}

mod opcao_secret_string_serde {
    use super::{ExposeSecret, SecretString};
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S: Serializer>(value: &Option<SecretString>, s: S) -> Result<S::Ok, S::Error> {
        match value {
            Some(v) => {
                let out = crate::secrets::serialize_secret(v.expose_secret())
                    .map_err(serde::ser::Error::custom)?;
                s.serialize_some(&out)
            }
            None => s.serialize_none(),
        }
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<SecretString>, D::Error> {
        let opt = Option::<String>::deserialize(d)?;
        match opt {
            None => Ok(None),
            Some(s) => {
                let plain =
                    crate::secrets::deserialize_secret(&s).map_err(serde::de::Error::custom)?;
                Ok(Some(SecretString::from(plain)))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_record_applies_defaults() {
        let r = VpsRecord::new(
            "teste".into(),
            "1.2.3.4".into(),
            22,
            "root".into(),
            SecretString::from("senha".to_string()),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            false,
        );
        assert_eq!(r.timeout_ms, DEFAULT_TIMEOUT_MS);
        assert_eq!(r.max_command_chars, DEFAULT_MAX_COMMAND_CHARS);
        assert_eq!(r.max_output_chars, DEFAULT_MAX_OUTPUT_CHARS);
        assert_eq!(r.schema_version, CURRENT_SCHEMA_VERSION);
        assert!(!r.added_at.is_empty());
    }

    #[test]
    fn debug_does_not_show_password() {
        let r = VpsRecord::new(
            "t".into(),
            "h".into(),
            22,
            "u".into(),
            SecretString::from("senha-super-secreta".to_string()),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            false,
        );
        let dbg = format!("{r:?}");
        assert!(!dbg.contains("senha-super-secreta"));
        assert!(dbg.contains("redacted"));
    }

    #[test]
    #[serial_test::serial]
    fn round_trip_toml_preserves_data() {
        // Isolates at-rest encryption from other tests (global primary-key).
        let tmp = tempfile::TempDir::new().unwrap();
        crate::secrets::set_config_dir(Some(tmp.path().to_path_buf()));
        // SAFETY:
        // 1. Contract: temporary mutation of process environment for a serial test/setup path.
        // 2. Invariant: no concurrent threads in this process mutate the same env keys.
        // 3. Caller guarantees serial_test::serial (or single-threaded test) around this block.
        // 4. See std::env::set_var / remove_var safety notes for multi-threaded processes.
        unsafe {

            std::env::set_var("SSH_CLI_ALLOW_PLAINTEXT_SECRETS", "1");
        }
        let r = VpsRecord::new(
            "producao".into(),
            "srv.exemplo.com".into(),
            2222,
            "admin".into(),
            SecretString::from("senha-do-admin-longa".to_string()),
            Some("/home/u/.ssh/id_ed25519".into()),
            None,
            Some(5000),
            Some(500),
            Some(50_000),
            Some(SecretString::from("sudopass".to_string())),
            None,
            false,
        );
        let toml_str = toml::to_string(&r).expect("serializar");
        let r2: VpsRecord = toml::from_str(&toml_str).expect("deserializar");
        assert_eq!(r2.name, "producao");
        assert_eq!(r2.port, 2222);
        assert_eq!(r2.password.expose_secret(), "senha-do-admin-longa");
        assert_eq!(r2.key_path.as_deref(), Some("/home/u/.ssh/id_ed25519"));
        assert_eq!(r2.max_command_chars, 500);
        assert_eq!(r2.max_output_chars, 50_000);
        assert_eq!(
            r2.sudo_password
                .as_ref()
                .map(|s| s.expose_secret().to_string()),
            Some("sudopass".to_string())
        );
        assert!(r2.su_password.is_none());
        // SAFETY:

        // 1. Contract: temporary mutation of process environment for a serial test/setup path.

        // 2. Invariant: no concurrent threads in this process mutate the same env keys.

        // 3. Caller guarantees serial_test::serial (or single-threaded test) around this block.

        // 4. See std::env::set_var / remove_var safety notes for multi-threaded processes.

        unsafe {
            std::env::remove_var("SSH_CLI_ALLOW_PLAINTEXT_SECRETS");
        }
        crate::secrets::set_config_dir(None);
    }

    #[test]
    fn migrates_legacy_max_chars() {
        let legacy = r#"
nome = "x"
host = "h"
porta = 22
usuario = "u"
senha = "s"
timeout_ms = 30000
max_chars = 4242
schema_version = 1
adicionado_em = "2020-01-01T00:00:00Z"
"#;
        let r: VpsRecord = toml::from_str(legacy).expect("deserialize legacy PT wire");
        assert_eq!(r.max_output_chars, 4242);
        assert_eq!(r.max_command_chars, DEFAULT_MAX_COMMAND_CHARS);
        assert_eq!(r.name, "x");
        assert_eq!(r.port, 22);
        assert_eq!(r.username, "u");
    }

    #[test]
    fn deserializes_english_wire_keys() {
        let en = r#"
name = "prod"
host = "h.example"
port = 2222
username = "admin"
password = "secret"
timeout_ms = 5000
schema_version = 3
"#;
        let r: VpsRecord = toml::from_str(en).expect("deserialize EN wire");
        assert_eq!(r.name, "prod");
        assert_eq!(r.port, 2222);
        assert_eq!(r.username, "admin");
        assert!(!r.added_at.is_empty());
    }

    #[test]
    fn serializes_english_wire_keys() {
        let r = VpsRecord::new(
            "prod".into(),
            "h".into(),
            22,
            "u".into(),
            SecretString::from("p".to_string()),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            false,
        );
        let s = toml::to_string(&r).expect("serialize");
        assert!(s.contains("name ="), "expected EN key name: {s}");
        assert!(s.contains("port ="), "expected EN key port: {s}");
        assert!(s.contains("username ="), "expected EN key username: {s}");
        assert!(s.contains("password ="), "expected EN key password: {s}");
        assert!(s.contains("added_at ="), "expected EN key added_at: {s}");
        assert!(!s.contains("nome ="), "must not write PT key nome: {s}");
        assert!(!s.contains("porta ="), "must not write PT key porta: {s}");
        assert!(!s.contains("adicionado_em ="), "must not write PT adicionado_em: {s}");
    }

    #[test]
    fn deserializes_without_added_at() {
        let bare = r#"
nome = "x"
host = "h"
porta = 22
usuario = "u"
senha = "s"
schema_version = 2
"#;
        let r: VpsRecord = toml::from_str(bare).expect("default added_at");
        assert!(!r.added_at.is_empty());
    }

    #[test]
    fn validate_credentials_requires_password_or_key() {
        let mut r = VpsRecord::new(
            "t".into(),
            "h".into(),
            22,
            "u".into(),
            SecretString::from(String::new()),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            false,
        );
        assert!(r.validate_credentials().is_err());
        r.key_path = Some("/tmp/k".into());
        assert!(r.validate_credentials().is_ok());
    }

    #[test]
    fn parse_limit_none_and_zero() {
        assert_eq!(parse_char_limit("none"), 0);
        assert_eq!(parse_char_limit("0"), 0);
        assert_eq!(parse_char_limit("1000"), 1000);
        assert_eq!(effective_limit(0), usize::MAX);
        assert_eq!(effective_limit(10), 10);
    }
}