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
// SPDX-License-Identifier: MIT OR Apache-2.0
// G-COMP: VPS CRUD dispatcher extracted from vps/mod (SRP; line budget).
#![forbid(unsafe_code)]
//! Dispatcher for `ssh-cli vps …` subcommands.
use super::config_io::{load, lock_config, resolve_config_path, validate_key_path_exists};
use super::doctor::run_doctor_with_optional_probe;
use super::health::run_health_check;
use super::import_export::{run_export, run_import};
use super::model::{self, VpsRecord};
use super::secrets_cmd::take_auto_key_meta;
use super::selection::HostSelection;
use super::{read_secret_stdin, use_json};
use crate::cli::{OutputFormat, VpsAction};
use crate::errors::SshCliError;
use anyhow::Result;
use secrecy::SecretString;
use std::path::{Path, PathBuf};
/// Dispatcher dos subcomandos `vps`.
pub async fn run_vps_command(
action: VpsAction,
config_override: Option<PathBuf>,
format: OutputFormat,
) -> Result<()> {
let path = resolve_config_path(config_override.as_deref())?;
match action {
VpsAction::Add {
name,
host,
port,
user,
password,
password_stdin,
key,
key_passphrase,
key_passphrase_stdin,
use_agent,
agent_socket,
timeout,
max_command_chars,
max_output_chars,
max_chars,
sudo_password,
sudo_password_stdin,
su_password,
su_password_stdin,
disable_sudo,
tags,
tls,
tls_sni,
tls_client_cert,
tls_client_key,
check,
} => {
// GAP-SSH-VAL-001: validate na fronteira de escrita.
let name = crate::paths::validate_and_normalize(&name)
.map_err(|e| SshCliError::InvalidArgument(format!("invalid VPS name: {e}")))?;
let name_key = name.as_str().to_owned();
// Early, advisory duplicate check: fails before any stdin prompt. The
// authoritative check happens again under the config lock, below.
if load(&path)?.hosts.contains_key(&name_key) {
return Err(SshCliError::VpsDuplicate(name_key).into());
}
// Stdin can only be drained once, so ANY two `--*-stdin` flags conflict.
// D13: the old guard was `password_stdin && (sudo || su)`, which let
// `--sudo-password-stdin --su-password-stdin` through: the first read
// consumed stdin and the second silently produced an empty secret.
// Counting is the invariant; enumerating pairs is not.
let stdin_secrets = usize::from(password_stdin)
+ usize::from(key_passphrase_stdin)
+ usize::from(sudo_password_stdin)
+ usize::from(su_password_stdin);
if stdin_secrets > 1 {
return Err(SshCliError::InvalidArgument(
"only one --*-stdin per one-shot invocation (stdin is drained once); \
use vps edit for the remaining secrets"
.into(),
)
.into());
}
let password = if password_stdin {
read_secret_stdin()?
} else {
SecretString::from(password.unwrap_or_default())
};
let key_passphrase = if key_passphrase_stdin {
Some(read_secret_stdin()?)
} else {
key_passphrase.map(SecretString::from)
};
let sudo_s = if sudo_password_stdin {
Some(read_secret_stdin()?)
} else {
sudo_password.map(SecretString::from)
};
let su_s = if su_password_stdin {
Some(read_secret_stdin()?)
} else {
su_password.map(SecretString::from)
};
let key = key.map(|p| p.to_string_lossy().into_owned());
if let Some(ref k) = key {
validate_key_path_exists(k)?;
}
// legacy max_chars → command if max_command was not set explicitly
// (clap already parses `none`/`0`/decimal via parse_cli_char_limit)
let max_cmd = max_command_chars
.or(max_chars)
.unwrap_or(model::DEFAULT_MAX_COMMAND_CHARS);
let max_out = max_output_chars.unwrap_or(model::DEFAULT_MAX_OUTPUT_CHARS);
// GAP-AUD-009: timeout is milliseconds; warn agents that use "5" meaning seconds.
if timeout > 0 && timeout < 1000 {
crate::output::print_warning_fmt(format_args!(
"--timeout {timeout} is only {timeout}ms (< 1s); did you mean seconds? Use e.g. --timeout 5000 for 5s"
));
}
let mut record = VpsRecord::try_new(
name.as_str(),
host,
port,
user,
password,
key,
key_passphrase,
Some(timeout),
Some(max_cmd),
Some(max_out),
sudo_s,
su_s,
disable_sudo,
)
.map_err(SshCliError::InvalidArgument)?;
// G-E2E-19: registry auth triplo (password | key | agent).
if use_agent {
record.use_agent = true;
record.password = SecretString::from(String::new());
record.key_path = None;
record.key_passphrase = None;
record.agent_socket = agent_socket.map(|p| p.to_string_lossy().into_owned());
}
// G-O2: tags for fleet selection (dedupe preserve order).
let tag_list = crate::vps::selection::dedupe_host_names(tags);
record
.set_tags_from_raw(tag_list)
.map_err(SshCliError::from)?;
record.tls = tls;
record.tls_sni = tls_sni;
record.tls_client_cert = tls_client_cert.map(|p| p.to_string_lossy().into_owned());
record.tls_client_key = tls_client_key.map(|p| p.to_string_lossy().into_owned());
if record.tls {
// Validate options early (SNI empty / partial mTLS).
let sni = record
.tls_sni
.as_deref()
.filter(|s| !s.trim().is_empty())
.unwrap_or(record.host.as_str());
let _ = crate::tls::TlsConnectOptions::try_new(
sni,
record
.tls_client_cert
.as_ref()
.map(std::path::PathBuf::from),
record.tls_client_key.as_ref().map(std::path::PathBuf::from),
)?;
}
// GAP-SSH-VAL-002 / VAL-003: full domain validation on the write-path.
record.validate().map_err(SshCliError::from)?;
// Read-modify-write under one lock: a concurrent `vps add` that loaded the
// same snapshot would otherwise overwrite this host on save.
let guard = lock_config(&path)?;
let mut file = load(&path)?;
if file.hosts.contains_key(&name_key) {
return Err(SshCliError::VpsDuplicate(name_key).into());
}
file.hosts.insert(name_key.clone(), record);
file.schema_version = model::CURRENT_SCHEMA_VERSION;
guard.save(&path, &file)?;
// Release before `--check`: the lock must never span an SSH round trip.
drop(guard);
// G-E2E-04 / one-shot: single stdout document (fold auto-key into vps-added).
// Workload: local single-file CRUD — sequential justified (≪ SSH RTT).
let auto_key = take_auto_key_meta();
let mut data = serde_json::json!({ "name": name_key });
if let Some(ref meta) = auto_key {
data["secrets_key_auto_created"] = serde_json::Value::Bool(true);
data["key_file"] = serde_json::Value::String(meta.key_file.clone());
data["key_source"] = serde_json::Value::String(meta.key_source.to_owned());
} else {
data["secrets_key_auto_created"] = serde_json::Value::Bool(false);
}
let msg = if let Some(ref meta) = auto_key {
format!(
"{}; primary-key auto-created at {}",
crate::i18n::t(crate::i18n::Message::VpsAdded {
name: name_key.clone(),
}),
meta.key_file
)
} else {
crate::i18n::t(crate::i18n::Message::VpsAdded {
name: name_key.clone(),
})
};
crate::output::emit_success("vps-added", data, &msg, format == OutputFormat::Json)?;
if check {
run_health_check(crate::vps::HealthCheckRequest {
selection: HostSelection::Single(name.clone()),
config_override,
format,
json_local: false,
password_override: None,
timeout_override: None,
key_override: None,
key_passphrase_override: None,
replace_host_key: false,
})
.await?;
}
}
VpsAction::List { json, tags } => {
let file = load(&path)?;
let records: Vec<_> = if tags.is_empty() {
file.hosts.values().cloned().collect()
} else {
{
let wanted = crate::domain::try_tags(&tags)
.map_err(|e| SshCliError::InvalidArgument(e.to_string()))?;
file.hosts
.values()
.filter(|r| r.has_any_tag(&wanted))
.cloned()
.collect()
}
};
// GAP-SSH-IO-001: respeitar format global.
if use_json(json, format) {
crate::output::print_list_json(&records)?;
} else {
crate::output::print_list_text(&records);
}
}
VpsAction::Remove { name } => {
// Lock spans load → mutate → save so a concurrent edit is not resurrected.
let guard = lock_config(&path)?;
let mut file = load(&path)?;
if !file.hosts.contains_key(&name) {
return Err(SshCliError::VpsNotFound(name).into());
}
// C2: previewed *after* the existence check, so the plan never promises
// a removal that the real run would reject with exit 66. A dry-run that
// reports success for a host that does not exist is worse than no
// preview, because the agent then treats the failure as a regression.
if crate::cli::dry_run_stop(
"vps-remove",
&[
("name", serde_json::json!(name)),
("config_path", serde_json::json!(path.display().to_string())),
],
)? {
return Ok(());
}
file.hosts.remove(&name);
guard.save(&path, &file)?;
drop(guard);
// GAP-SSH-STATE-001: clear orphan active marker.
clear_active_if_name(&path, &name)?;
crate::output::emit_success(
"vps-removed",
serde_json::json!({ "name": name }),
&crate::i18n::t(crate::i18n::Message::VpsRemoved { name: name.clone() }),
format == OutputFormat::Json,
)?;
}
VpsAction::Edit {
name,
host,
port,
user,
password,
password_stdin,
key,
key_passphrase,
key_passphrase_stdin,
use_agent,
agent_socket,
timeout,
max_command_chars,
max_output_chars,
max_chars,
sudo_password,
sudo_password_stdin,
su_password,
su_password_stdin,
disable_sudo,
enable_sudo,
tls,
no_tls,
tls_sni,
tls_client_cert,
tls_client_key,
} => {
// D13: `edit` had NO mutual-exclusion guard at all and read stdin up to
// three times in a row. Only the first read saw data; the rest silently
// stored empty secrets. Same invariant as `add`: stdin drains once.
let stdin_secrets = usize::from(password_stdin)
+ usize::from(key_passphrase_stdin)
+ usize::from(sudo_password_stdin)
+ usize::from(su_password_stdin);
if stdin_secrets > 1 {
return Err(SshCliError::InvalidArgument(
"only one --*-stdin per one-shot invocation (stdin is drained once); \
run vps edit again for the remaining secrets"
.into(),
)
.into());
}
// Stdin secrets are read *before* the lock: a blocking read must never hold
// it, or a concurrent one-shot would wait on the operator's terminal.
let password_stdin_value = if password_stdin {
Some(read_secret_stdin()?)
} else {
None
};
let key_passphrase_stdin_value = if key_passphrase_stdin {
Some(read_secret_stdin()?)
} else {
None
};
let sudo_stdin_value = if sudo_password_stdin {
Some(read_secret_stdin()?)
} else {
None
};
let su_stdin_value = if su_password_stdin {
Some(read_secret_stdin()?)
} else {
None
};
// Lock spans load → mutate → save (lost-update on concurrent edits).
let guard = lock_config(&path)?;
let mut file = load(&path)?;
let record = file
.hosts
.get_mut(&name)
.ok_or(SshCliError::VpsNotFound(name.clone()))?;
use crate::domain::{CharLimit, KeyPath, SshHost, SshPort, SshUser, TimeoutMs};
if let Some(h) = host {
record.host =
SshHost::try_new(h).map_err(|e| SshCliError::InvalidArgument(e.to_string()))?;
}
if let Some(p) = port {
record.port =
SshPort::try_new(p).map_err(|e| SshCliError::InvalidArgument(e.to_string()))?;
}
if let Some(u) = user {
record.username =
SshUser::try_new(u).map_err(|e| SshCliError::InvalidArgument(e.to_string()))?;
}
if use_agent {
record.use_agent = true;
record.password = SecretString::from(String::new());
record.key_path = None;
record.key_passphrase = None;
if let Some(s) = agent_socket {
record.agent_socket = Some(s.to_string_lossy().into_owned());
}
} else {
if let Some(pw) = password_stdin_value {
record.password = pw;
record.use_agent = false;
} else if let Some(pw) = password {
record.password = SecretString::from(pw);
record.use_agent = false;
}
if let Some(k) = key {
let k = k.to_string_lossy().into_owned();
validate_key_path_exists(&k)?;
record.key_path = Some(
KeyPath::try_new(k)
.map_err(|e| SshCliError::InvalidArgument(e.to_string()))?,
);
record.use_agent = false;
}
if let Some(kp) = key_passphrase_stdin_value {
record.key_passphrase = Some(kp);
} else if let Some(kp) = key_passphrase {
record.key_passphrase = Some(SecretString::from(kp));
}
if let Some(s) = agent_socket {
record.agent_socket = Some(s.to_string_lossy().into_owned());
}
}
if let Some(t) = timeout {
record.timeout_ms = TimeoutMs::try_new(t)
.map_err(|e| SshCliError::InvalidArgument(e.to_string()))?;
}
if let Some(m) = max_command_chars.or(max_chars) {
record.max_command_chars = CharLimit::try_new(m)
.map_err(|e| SshCliError::InvalidArgument(e.to_string()))?;
}
if let Some(m) = max_output_chars {
record.max_output_chars = CharLimit::try_new(m)
.map_err(|e| SshCliError::InvalidArgument(e.to_string()))?;
}
if let Some(sp) = sudo_stdin_value {
record.sudo_password = Some(sp);
} else if let Some(sp) = sudo_password {
record.sudo_password = Some(SecretString::from(sp));
}
if let Some(sp) = su_stdin_value {
record.su_password = Some(sp);
} else if let Some(sp) = su_password {
record.su_password = Some(SecretString::from(sp));
}
// G-10: tri-state edit without Option<bool> — exclusive SetTrue flags.
if disable_sudo {
record.disable_sudo = true;
} else if enable_sudo {
record.disable_sudo = false;
}
if tls {
record.tls = true;
} else if no_tls {
record.tls = false;
}
if let Some(sni) = tls_sni {
record.tls_sni = Some(sni);
}
if let Some(c) = tls_client_cert {
record.tls_client_cert = Some(c.to_string_lossy().into_owned());
}
if let Some(k) = tls_client_key {
record.tls_client_key = Some(k.to_string_lossy().into_owned());
}
if record.tls {
let sni = record
.tls_sni
.as_deref()
.filter(|s| !s.trim().is_empty())
.unwrap_or(record.host.as_str());
let _ = crate::tls::TlsConnectOptions::try_new(
sni,
record
.tls_client_cert
.as_ref()
.map(std::path::PathBuf::from),
record.tls_client_key.as_ref().map(std::path::PathBuf::from),
)?;
}
record.validate().map_err(SshCliError::from)?;
guard.save(&path, &file)?;
drop(guard);
crate::output::emit_success(
"vps-edited",
serde_json::json!({ "name": name }),
&crate::i18n::t(crate::i18n::Message::VpsEdited { name: name.clone() }),
format == OutputFormat::Json,
)?;
}
VpsAction::Show { name, json } => {
let file = load(&path)?;
let record = file
.hosts
.get(&name)
.ok_or(SshCliError::VpsNotFound(name.clone()))?;
if use_json(json, format) {
crate::output::print_details_json(record)?;
} else {
crate::output::print_details_text(record);
}
}
VpsAction::Path => {
// G-AUD-02: JSON envelope when format is Json; plain path in Text.
if use_json(false, format) {
let path_s = path.display().to_string();
crate::output::emit_success(
"vps-path",
serde_json::json!({ "path": path_s }),
&path_s,
true,
)?;
} else {
// G-MAC-01: format_args + write_fmt — no intermediate String for Display.
crate::output::write_line_fmt(format_args!("{}", path.display()))?;
}
}
VpsAction::Doctor {
json,
probe_ssh,
hosts,
} => {
// G-PAR-38/42: single envelope (local + optional ssh_probe); no dual JSON roots.
let as_json = use_json(json, format);
if hosts.is_some() && !probe_ssh {
return Err(SshCliError::InvalidArgument(
"--hosts on vps doctor requires --probe-ssh".into(),
)
.into());
}
let selection = if probe_ssh {
match hosts {
None => HostSelection::All,
Some(raw) => {
let names = crate::cli::parse_hosts_list(&raw);
if names.is_empty() {
return Err(SshCliError::InvalidArgument(
"--hosts requires at least one host name".into(),
)
.into());
}
let names = names
.into_iter()
.map(crate::domain::VpsName::try_new)
.collect::<Result<Vec<_>, _>>()
.map_err(|e| SshCliError::InvalidArgument(e.to_string()))?;
HostSelection::Named(names)
}
}
} else {
// unused when !probe_ssh
HostSelection::All
};
run_doctor_with_optional_probe(
config_override.as_deref(),
as_json,
probe_ssh,
if probe_ssh { Some(selection) } else { None },
)
.await?;
}
VpsAction::Export {
include_secrets,
output,
json,
i_understand_secrets_on_stdout,
} => {
// G-AUD-03: export body JSON when local --json or global format Json.
run_export(
&path,
include_secrets,
output.as_deref(),
json,
i_understand_secrets_on_stdout,
format,
)?;
}
VpsAction::Import {
file,
allow_incomplete,
} => {
run_import(&path, &file, allow_incomplete, format)?;
}
}
Ok(())
}
/// Removes the `active` file if its content matches the removed name (STATE-001).
fn clear_active_if_name(config_path: &Path, name: &str) -> Result<()> {
let active = config_path
.parent()
.map(|p| p.join(crate::constants::ACTIVE_VPS_FILE_NAME))
.unwrap_or_else(|| PathBuf::from(crate::constants::ACTIVE_VPS_FILE_NAME));
if !active.exists() {
return Ok(());
}
let content = std::fs::read_to_string(&active).unwrap_or_default();
if content.trim() == name {
let _ = std::fs::remove_file(&active);
}
Ok(())
}