bssh 3.0.1

Parallel SSH command execution tool for cluster management
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
509
510
511
512
513
514
515
516
517
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0

use std::fs;
use std::process::Command;

use tempfile::tempdir;

fn bssh() -> Command {
    Command::new(env!("CARGO_BIN_EXE_bssh"))
}

fn pre_auth_test_key(directory: &std::path::Path) -> std::path::PathBuf {
    let key = directory.join("test-key");
    fs::write(
        &key,
        "test key material; connection fails before key parsing",
    )
    .expect("test key should be written");
    key
}

fn contains_ansi(bytes: &[u8]) -> bool {
    bytes.contains(&0x1b)
}

#[test]
fn version_matches_openssh_stream_contract() {
    let output = bssh().arg("-V").output().expect("bssh should run");

    assert!(output.status.success());
    assert!(output.stdout.is_empty());
    assert_eq!(
        output.stderr,
        format!("bssh_{}\n", env!("CARGO_PKG_VERSION")).as_bytes()
    );
}

#[test]
fn algorithm_queries_match_the_selectable_transport_surface() {
    let ciphers = bssh().args(["-Q", "cipher"]).output().unwrap();
    let macs = bssh().args(["-Q", "mac"]).output().unwrap();
    assert!(ciphers.status.success() && macs.status.success());
    let ciphers = String::from_utf8(ciphers.stdout).unwrap();
    let macs = String::from_utf8(macs.stdout).unwrap();
    assert!(ciphers.lines().any(|value| value == "aes128-cbc"));
    assert!(
        macs.lines()
            .any(|value| value == "hmac-sha2-256-etm@openssh.com")
    );
    assert!(
        !ciphers
            .lines()
            .any(|value| matches!(value, "clear" | "none"))
    );
    assert!(!macs.lines().any(|value| value == "none"));
}

#[test]
fn unsupported_algorithm_policies_fail_before_connecting_with_supported_values() {
    for (flag, policy, kind) in [
        ("-c", "-definitely-not-a-cipher", "cipher"),
        ("-m", "-definitely-not-a-mac", "mac"),
        ("-c", "+", "cipher"),
        ("-m", "^", "mac"),
    ] {
        let output = bssh()
            .args([flag, policy, "unresolvable.invalid", "true"])
            .output()
            .unwrap();
        let stderr = String::from_utf8_lossy(&output.stderr).to_ascii_lowercase();
        assert_eq!(output.status.code(), Some(1), "{flag} {policy}: {stderr}");
        assert!(output.stdout.is_empty());
        assert!(stderr.contains(kind), "{flag} {policy}: {stderr}");
        assert!(
            stderr.contains("supported values"),
            "{flag} {policy}: {stderr}"
        );
    }
}

#[test]
fn explicit_and_environment_color_controls_apply_to_stdout() {
    let never = bssh()
        .args(["--color=never", "cache-stats"])
        .output()
        .expect("bssh --color=never should run");
    assert!(never.status.success());
    assert!(!contains_ansi(&never.stdout));

    let always = bssh()
        .args(["--color=always", "cache-stats"])
        .output()
        .expect("bssh --color=always should run");
    assert!(always.status.success());
    assert!(contains_ansi(&always.stdout));

    let no_color = bssh()
        .args(["cache-stats"])
        .env("NO_COLOR", "1")
        .output()
        .expect("bssh with NO_COLOR should run");
    assert!(no_color.status.success());
    assert!(!contains_ansi(&no_color.stdout));

    let dumb = bssh()
        .args(["cache-stats"])
        .env("TERM", "dumb")
        .output()
        .expect("bssh with TERM=dumb should run");
    assert!(dumb.status.success());
    assert!(!contains_ansi(&dumb.stdout));
}

#[test]
fn canonical_unimplemented_and_unknown_diagnostics_use_real_source_and_log_file() {
    let directory = tempdir().expect("temporary directory should be created");
    let config = directory.path().join("ssh_config");
    let included = directory.path().join("included.conf");
    let log = directory.path().join("bssh.log");
    fs::write(
        &included,
        "# Source: /spoofed/config:9000\nChallengeResponseAuthentication no\nKbdInteractiveAuthentication yes\nSecurityKeyProvider /usr/lib/ssh/ssh-sk-helper\nDefinitelyUnknownOption yes\n",
    )
    .expect("included ssh config should be written");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        fs::set_permissions(&included, fs::Permissions::from_mode(0o600))
            .expect("included ssh config permissions should be safe");
    }
    fs::write(
        &config,
        format!("Host *\n    Include {}\n", included.display()),
    )
    .expect("main ssh config should be written");

    let output = bssh()
        .args([
            "-E",
            log.to_str().expect("UTF-8 log path"),
            "-F",
            config.to_str().expect("UTF-8 config path"),
            "-o",
            "ChallengeResponseAuthentication=no",
            "-o",
            "KbdInteractiveAuthentication=no",
            "-o",
            "DefinitelyUnknownOption=no",
            "-o",
            "AnotherUnknownOption=yes",
            "--connect-timeout=1",
            "--strict-host-key-checking=no",
            "127.0.0.1:1",
            "true",
        ])
        .output()
        .expect("bssh should parse the ssh config");

    assert!(!output.status.success());
    assert!(
        output.stdout.is_empty(),
        "config diagnostics leaked to stdout"
    );
    assert!(output.stderr.is_empty(), "-E diagnostics leaked to stderr");

    let diagnostics = fs::read_to_string(log).expect("diagnostic log should exist");
    let included = included.to_string_lossy();
    let alias = format!(
        "Unsupported SSH config option 'kbdinteractiveauthentication' at {included}:2; bssh parses this value for inspection but does not implement its runtime behavior"
    );
    let unimplemented = format!(
        "Unsupported SSH config option 'securitykeyprovider' at {included}:4; bssh parses this value for inspection but does not implement its runtime behavior"
    );
    let unknown = format!("Unknown SSH config option 'definitelyunknownoption' at {included}:5");
    let distinct_unknown = "Unknown SSH config option 'anotherunknownoption' at -o option #4";

    assert_eq!(
        diagnostics.lines().filter(|line| line == &alias).count(),
        1,
        "canonical alias diagnostic must be emitted once: {diagnostics:?}"
    );
    assert_eq!(
        diagnostics
            .lines()
            .filter(|line| line == &unimplemented)
            .count(),
        1,
        "unimplemented diagnostic must be emitted once: {diagnostics:?}"
    );
    assert_eq!(
        diagnostics.lines().filter(|line| line == &unknown).count(),
        1,
        "unknown diagnostic must be emitted once: {diagnostics:?}"
    );
    assert_eq!(
        diagnostics
            .lines()
            .filter(|line| line == &distinct_unknown)
            .count(),
        1,
        "distinct unknown diagnostic must remain independent: {diagnostics:?}"
    );
    assert!(!diagnostics.contains("/spoofed/config"));
}

#[cfg(unix)]
#[test]
fn config_diagnostics_escape_control_characters_in_paths_and_keywords() {
    let directory = tempdir().expect("temporary directory should be created");
    let config = directory.path().join("ssh_config\nFORGED PATH");
    let log = directory.path().join("bssh.log");
    fs::write(&config, "Host *\nBad\u{1b}[31mKeyword yes\n")
        .expect("maliciously named SSH config should be written");

    let output = bssh()
        .arg("-E")
        .arg(&log)
        .arg("-F")
        .arg(&config)
        .args([
            "--connect-timeout=1",
            "--strict-host-key-checking=no",
            "127.0.0.1:1",
            "true",
        ])
        .output()
        .expect("bssh should parse the maliciously named SSH config");

    assert!(!output.status.success());
    assert!(output.stdout.is_empty());
    assert!(output.stderr.is_empty());

    let diagnostics = fs::read_to_string(log).expect("diagnostic log should exist");
    let escaped_path = config.to_string_lossy().replace('\n', "\\n");
    let expected =
        format!("Unknown SSH config option 'bad\\u{{1b}}[31mkeyword' at {escaped_path}:2");
    assert_eq!(
        diagnostics
            .lines()
            .filter(|line| line.starts_with("Unknown SSH config option"))
            .collect::<Vec<_>>(),
        [expected],
        "untrusted diagnostic fields must remain on one escaped line: {diagnostics:?}"
    );
    assert!(!diagnostics.contains('\u{1b}'));
    assert!(
        !diagnostics
            .lines()
            .any(|line| line.starts_with("FORGED PATH")),
        "config path forged a separate diagnostic line: {diagnostics:?}"
    );
}

#[cfg(unix)]
#[test]
fn config_load_errors_escape_control_characters_in_nonexistent_paths() {
    let directory = tempdir().expect("temporary directory should be created");
    let missing = directory.path().join("missing\nFORGED-ERROR\u{1b}[31m");
    let log = directory.path().join("bssh.log");

    let output = bssh()
        .arg("-E")
        .arg(&log)
        .arg("-F")
        .arg(&missing)
        .args(["127.0.0.1", "true"])
        .output()
        .expect("bssh should report the missing malicious SSH config path");

    assert_eq!(output.status.code(), Some(1));
    assert!(output.stdout.is_empty());
    assert!(output.stderr.is_empty());

    let diagnostics = fs::read_to_string(log).expect("diagnostic log should exist");
    let escaped_path = missing
        .to_string_lossy()
        .replace('\n', "\\n")
        .replace('\u{1b}', "\\u{1b}");
    assert!(
        diagnostics.contains(&format!("Failed to canonicalize path: {escaped_path}")),
        "escaped missing path is absent from diagnostic chain: {diagnostics:?}"
    );
    assert!(!diagnostics.contains('\u{1b}'));
    assert!(
        !diagnostics
            .lines()
            .any(|line| line.starts_with("FORGED-ERROR")),
        "missing config path forged a separate error line: {diagnostics:?}"
    );
}

#[test]
fn connection_refused_is_actionable_and_exits_255() {
    let directory = tempdir().expect("temporary directory should be created");
    let key = pre_auth_test_key(directory.path());
    let output = bssh()
        .args([
            "-i",
            key.to_str().expect("UTF-8 key path"),
            "--connect-timeout=1",
            "--strict-host-key-checking=no",
            "127.0.0.1:1",
            "true",
        ])
        .output()
        .expect("bssh should report a refused connection");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(255),
        "unexpected SSH failure status; stderr: {stderr:?}"
    );
    assert!(output.stdout.is_empty());
    assert!(
        stderr.contains("ssh: connect to host 127.0.0.1 port 1:"),
        "missing OpenSSH-compatible connection context: {stderr:?}"
    );
    assert!(
        stderr.to_ascii_lowercase().contains("refused"),
        "missing OS refusal cause: {stderr:?}"
    );
    assert!(
        !stderr.lines().any(|line| line.trim() == "I/O error"),
        "bare I/O error leaked: {stderr:?}"
    );
}

#[test]
fn connection_error_uses_log_file_exactly_once() {
    let directory = tempdir().expect("temporary directory should be created");
    let log = directory.path().join("bssh.log");
    let key = pre_auth_test_key(directory.path());
    let output = bssh()
        .args([
            "-E",
            log.to_str().expect("UTF-8 log path"),
            "-i",
            key.to_str().expect("UTF-8 key path"),
            "--connect-timeout=1",
            "--strict-host-key-checking=no",
            "127.0.0.1:1",
            "true",
        ])
        .output()
        .expect("bssh should report a refused connection to the log file");

    let diagnostics = fs::read_to_string(log).expect("diagnostic log should exist");
    assert_eq!(
        output.status.code(),
        Some(255),
        "unexpected SSH failure status; log: {diagnostics:?}"
    );
    assert!(output.stdout.is_empty());
    assert!(output.stderr.is_empty());
    let matching_lines = diagnostics
        .lines()
        .filter(|line| line.contains("ssh: connect to host 127.0.0.1 port 1:"))
        .collect::<Vec<_>>();
    assert_eq!(
        matching_lines.len(),
        1,
        "diagnostic must be emitted once: {diagnostics:?}"
    );
    assert!(matching_lines[0].to_ascii_lowercase().contains("refused"));
    assert!(matching_lines[0].contains("os error"));
    assert!(!matching_lines[0].contains(" ERROR "));
}

#[test]
fn dns_failure_is_distinct_and_exits_255() {
    let directory = tempdir().expect("temporary directory should be created");
    let key = pre_auth_test_key(directory.path());
    let output = bssh()
        .args([
            "-i",
            key.to_str().expect("UTF-8 key path"),
            "--connect-timeout=2",
            "--strict-host-key-checking=no",
            "does-not-exist.invalid",
            "true",
        ])
        .output()
        .expect("bssh should report a DNS failure");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(255),
        "unexpected SSH failure status; stderr: {stderr:?}"
    );
    assert!(output.stdout.is_empty());
    assert!(
        stderr.contains("ssh: Could not resolve hostname does-not-exist.invalid:"),
        "missing DNS layer context: {stderr:?}"
    );
    assert!(!stderr.to_ascii_lowercase().contains("connect to host"));
    assert!(!stderr.lines().any(|line| line.trim() == "I/O error"));
}

#[test]
fn keyless_authentication_exhaustion_is_actionable_and_exits_255() {
    let directory = tempdir().expect("temporary directory should be created");
    // Keep this auth-diagnostic contract independent from machine-wide ssh_config.
    let config = directory.path().join("config");
    fs::write(&config, "Host *\\n").expect("minimal SSH config should be written");
    let output = bssh()
        .args([
            "-F",
            config.to_str().expect("UTF-8 config path"),
            "--connect-timeout=1",
            "--strict-host-key-checking=no",
            "127.0.0.1:1",
            "true",
        ])
        .env("HOME", directory.path())
        .env_remove("SSH_AUTH_SOCK")
        .output()
        .expect("bssh should report authentication exhaustion");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(255),
        "unexpected authentication status; stderr: {stderr:?}"
    );
    assert!(output.stdout.is_empty());
    assert_eq!(
        stderr.matches("Permission denied (publickey).").count(),
        1,
        "authentication diagnostic must be emitted once: {stderr:?}"
    );
    assert!(stderr.starts_with("Permission denied (publickey).\n"));
    assert!(stderr.contains("bssh: SSH agent: not available"));
    assert!(stderr.contains("bssh: Default SSH keys: not found or not authorized"));
    assert!(stderr.contains("bssh: Password authentication: not available"));
    assert!(!stderr.contains(" WARN "));
}

#[test]
fn keyless_authentication_exhaustion_uses_log_file_exactly_once() {
    let directory = tempdir().expect("temporary directory should be created");
    // Keep this auth-diagnostic contract independent from machine-wide ssh_config.
    let config = directory.path().join("config");
    fs::write(&config, "Host *\\n").expect("minimal SSH config should be written");
    let log = directory.path().join("bssh.log");
    let output = bssh()
        .args([
            "-E",
            log.to_str().expect("UTF-8 log path"),
            "-F",
            config.to_str().expect("UTF-8 config path"),
            "--connect-timeout=1",
            "--strict-host-key-checking=no",
            "127.0.0.1:1",
            "true",
        ])
        .env("HOME", directory.path())
        .env_remove("SSH_AUTH_SOCK")
        .output()
        .expect("bssh should route authentication exhaustion to the log");

    let diagnostics = fs::read_to_string(log).expect("diagnostic log should exist");
    assert_eq!(
        output.status.code(),
        Some(255),
        "unexpected authentication status; log: {diagnostics:?}"
    );
    assert!(output.stdout.is_empty());
    assert!(output.stderr.is_empty());
    assert_eq!(
        diagnostics
            .matches("Permission denied (publickey).")
            .count(),
        1,
        "authentication diagnostic must be logged once: {diagnostics:?}"
    );
    assert!(diagnostics.starts_with("Permission denied (publickey).\n"));
    assert!(!diagnostics.contains(" WARN "));
}

#[test]
fn cli_usage_error_keeps_clap_exit_status() {
    let output = bssh()
        .arg("--definitely-invalid-option")
        .output()
        .expect("bssh should report an invalid CLI option");

    assert_eq!(output.status.code(), Some(2));
    assert!(output.stdout.is_empty());
    assert!(String::from_utf8_lossy(&output.stderr).contains("unexpected argument"));
}

#[test]
fn local_config_error_keeps_generic_exit_status() {
    let directory = tempdir().expect("temporary directory should be created");
    let config = directory.path().join("missing_config");
    let output = bssh()
        .args([
            "-F",
            config.to_str().expect("UTF-8 config path"),
            "127.0.0.1",
            "true",
        ])
        .output()
        .expect("bssh should report a missing local config file");

    assert_eq!(output.status.code(), Some(1));
    assert!(output.stdout.is_empty());
    assert!(String::from_utf8_lossy(&output.stderr).contains("Failed to load SSH config"));
}