bssh 2.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
// 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
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! SSH connection management and node operations.

use anyhow::Result;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::node::Node;
use crate::security::SudoPassword;
use crate::ssh::{
    client::{CommandResult, ConnectionConfig},
    known_hosts::StrictHostKeyChecking,
    tokio_client::SshConnectionConfig,
    SshClient, SshConfig,
};

/// Configuration for node execution.
#[derive(Clone)]
pub(crate) struct ExecutionConfig<'a> {
    pub key_path: Option<&'a str>,
    pub strict_mode: StrictHostKeyChecking,
    pub use_agent: bool,
    pub use_password: bool,
    #[cfg(target_os = "macos")]
    pub use_keychain: bool,
    pub timeout: Option<u64>,
    pub connect_timeout: Option<u64>,
    pub jump_hosts: Option<&'a str>,
    pub sudo_password: Option<Arc<SudoPassword>>,
    pub ssh_config: Option<&'a SshConfig>,
    /// SSH connection configuration (keepalive settings).
    /// Threaded through to `Client::connect_with_ssh_config` so user-configured
    /// `server_alive_interval` / `server_alive_count_max` apply to exec mode.
    pub ssh_connection_config: Option<&'a SshConnectionConfig>,
}

/// Execute a command on a node with jump host support.
pub(crate) async fn execute_on_node_with_jump_hosts(
    node: Node,
    command: &str,
    config: &ExecutionConfig<'_>,
) -> Result<CommandResult> {
    let mut client = SshClient::new(node.host.clone(), node.port, node.username.clone());

    let key_path = config.key_path.map(Path::new);

    // Determine effective jump hosts: CLI takes precedence, then SSH config
    // Store the SSH config jump hosts String to extend its lifetime
    let ssh_config_jump_hosts = config
        .ssh_config
        .and_then(|ssh_config| ssh_config.get_proxy_jump(&node.host));

    let effective_jump_hosts = if config.jump_hosts.is_some() {
        // CLI jump hosts specified
        config.jump_hosts
    } else {
        // Fall back to SSH config ProxyJump for this specific host
        ssh_config_jump_hosts.as_deref()
    };

    let connection_config = ConnectionConfig {
        key_path,
        strict_mode: Some(config.strict_mode),
        use_agent: config.use_agent,
        use_password: config.use_password,
        #[cfg(target_os = "macos")]
        use_keychain: config.use_keychain,
        timeout_seconds: config.timeout,
        connect_timeout_seconds: config.connect_timeout,
        jump_hosts_spec: effective_jump_hosts,
        ssh_connection_config: config.ssh_connection_config,
    };

    // If sudo password is provided, use streaming execution to handle prompts
    if let Some(ref sudo_password) = config.sudo_password {
        use crate::ssh::tokio_client::CommandOutput;
        use tokio::sync::mpsc;

        let (tx, mut rx) = mpsc::channel(1000);
        let exit_status = client
            .connect_and_execute_with_sudo(command, &connection_config, tx, sudo_password)
            .await?;

        // Collect output from channel
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        while let Some(output) = rx.recv().await {
            match output {
                CommandOutput::StdOut(data) => stdout.extend_from_slice(&data),
                CommandOutput::StdErr(data) => stderr.extend_from_slice(&data),
                CommandOutput::ExitCode(_) => {
                    // Exit code is already captured from the function return value
                }
            }
        }

        Ok(CommandResult {
            host: node.host.clone(),
            output: stdout,
            stderr,
            exit_status,
        })
    } else {
        client
            .connect_and_execute_with_jump_hosts(command, &connection_config)
            .await
    }
}

/// Upload a file or directory to a node with jump host support.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn upload_to_node(
    node: Node,
    local_path: &Path,
    remote_path: &str,
    key_path: Option<&str>,
    strict_mode: StrictHostKeyChecking,
    use_agent: bool,
    use_password: bool,
    jump_hosts: Option<&str>,
    connect_timeout_seconds: Option<u64>,
    ssh_config: Option<&SshConfig>,
) -> Result<()> {
    let mut client = SshClient::new(node.host.clone(), node.port, node.username.clone());

    let key_path = key_path.map(Path::new);

    // Determine effective jump hosts: CLI takes precedence, then SSH config
    let ssh_config_jump_hosts =
        ssh_config.and_then(|ssh_config| ssh_config.get_proxy_jump(&node.host));

    let effective_jump_hosts = if jump_hosts.is_some() {
        jump_hosts
    } else {
        ssh_config_jump_hosts.as_deref()
    };

    // Check if the local path is a directory
    if local_path.is_dir() {
        client
            .upload_dir_with_jump_hosts(
                local_path,
                remote_path,
                key_path,
                Some(strict_mode),
                use_agent,
                use_password,
                effective_jump_hosts,
                connect_timeout_seconds,
            )
            .await
    } else {
        client
            .upload_file_with_jump_hosts(
                local_path,
                remote_path,
                key_path,
                Some(strict_mode),
                use_agent,
                use_password,
                effective_jump_hosts,
                connect_timeout_seconds,
            )
            .await
    }
}

/// Download a file from a node with jump host support.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn download_from_node(
    node: Node,
    remote_path: &str,
    local_path: &Path,
    key_path: Option<&str>,
    strict_mode: StrictHostKeyChecking,
    use_agent: bool,
    use_password: bool,
    jump_hosts: Option<&str>,
    connect_timeout_seconds: Option<u64>,
    ssh_config: Option<&SshConfig>,
) -> Result<PathBuf> {
    let mut client = SshClient::new(node.host.clone(), node.port, node.username.clone());

    let key_path = key_path.map(Path::new);

    // Determine effective jump hosts: CLI takes precedence, then SSH config
    let ssh_config_jump_hosts =
        ssh_config.and_then(|ssh_config| ssh_config.get_proxy_jump(&node.host));

    let effective_jump_hosts = if jump_hosts.is_some() {
        jump_hosts
    } else {
        ssh_config_jump_hosts.as_deref()
    };

    // This function handles both files and directories
    // The caller should check if it's a directory and use the appropriate method
    client
        .download_file_with_jump_hosts(
            remote_path,
            local_path,
            key_path,
            Some(strict_mode),
            use_agent,
            use_password,
            effective_jump_hosts,
            connect_timeout_seconds,
        )
        .await?;

    Ok(local_path.to_path_buf())
}

/// Download a directory from a node with jump host support.
#[allow(clippy::too_many_arguments)]
pub async fn download_dir_from_node(
    node: Node,
    remote_path: &str,
    local_path: &Path,
    key_path: Option<&str>,
    strict_mode: StrictHostKeyChecking,
    use_agent: bool,
    use_password: bool,
    jump_hosts: Option<&str>,
    connect_timeout_seconds: Option<u64>,
    ssh_config: Option<&SshConfig>,
) -> Result<PathBuf> {
    let mut client = SshClient::new(node.host.clone(), node.port, node.username.clone());

    let key_path = key_path.map(Path::new);

    // Determine effective jump hosts: CLI takes precedence, then SSH config
    let ssh_config_jump_hosts =
        ssh_config.and_then(|ssh_config| ssh_config.get_proxy_jump(&node.host));

    let effective_jump_hosts = if jump_hosts.is_some() {
        jump_hosts
    } else {
        ssh_config_jump_hosts.as_deref()
    };

    client
        .download_dir_with_jump_hosts(
            remote_path,
            local_path,
            key_path,
            Some(strict_mode),
            use_agent,
            use_password,
            effective_jump_hosts,
            connect_timeout_seconds,
        )
        .await?;

    Ok(local_path.to_path_buf())
}

/// Helper function to resolve effective jump hosts with priority:
/// 1. CLI jump hosts (highest priority)
/// 2. SSH config ProxyJump for the specific host
/// 3. None (direct connection)
///
/// This is extracted for testing purposes and used internally by all connection functions.
#[allow(dead_code)] // Used for testing
#[inline]
fn resolve_effective_jump_hosts(
    cli_jump_hosts: Option<&str>,
    ssh_config: Option<&SshConfig>,
    hostname: &str,
) -> Option<String> {
    if cli_jump_hosts.is_some() {
        return cli_jump_hosts.map(String::from);
    }
    ssh_config.and_then(|config| config.get_proxy_jump(hostname))
}

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

    /// Test that CLI jump hosts take precedence over SSH config
    #[test]
    fn test_resolve_effective_jump_hosts_cli_precedence() {
        let ssh_config_content = r#"
Host example.com
    ProxyJump bastion.example.com
"#;
        let ssh_config = SshConfig::parse(ssh_config_content).unwrap();

        // CLI should override SSH config
        let result = resolve_effective_jump_hosts(
            Some("cli-bastion.example.com"),
            Some(&ssh_config),
            "example.com",
        );
        assert_eq!(result, Some("cli-bastion.example.com".to_string()));
    }

    /// Test that SSH config ProxyJump is used when no CLI jump hosts
    #[test]
    fn test_resolve_effective_jump_hosts_ssh_config_fallback() {
        let ssh_config_content = r#"
Host example.com
    ProxyJump bastion.example.com
"#;
        let ssh_config = SshConfig::parse(ssh_config_content).unwrap();

        let result = resolve_effective_jump_hosts(None, Some(&ssh_config), "example.com");
        assert_eq!(result, Some("bastion.example.com".to_string()));
    }

    /// Test that no jump hosts is returned when neither CLI nor SSH config specifies one
    #[test]
    fn test_resolve_effective_jump_hosts_none() {
        let ssh_config = SshConfig::new();

        let result = resolve_effective_jump_hosts(None, Some(&ssh_config), "example.com");
        assert_eq!(result, None);
    }

    /// Test that no jump hosts is returned when SSH config is not provided
    #[test]
    fn test_resolve_effective_jump_hosts_no_ssh_config() {
        let result = resolve_effective_jump_hosts(None, None, "example.com");
        assert_eq!(result, None);
    }

    /// Test multi-hop ProxyJump chain from SSH config
    #[test]
    fn test_resolve_effective_jump_hosts_multi_hop() {
        let ssh_config_content = r#"
Host internal.example.com
    ProxyJump jump1.example.com,jump2.example.com
"#;
        let ssh_config = SshConfig::parse(ssh_config_content).unwrap();

        let result = resolve_effective_jump_hosts(None, Some(&ssh_config), "internal.example.com");
        assert_eq!(
            result,
            Some("jump1.example.com,jump2.example.com".to_string())
        );
    }

    /// Test ProxyJump with port specification
    #[test]
    fn test_resolve_effective_jump_hosts_with_port() {
        let ssh_config_content = r#"
Host internal.example.com
    ProxyJump bastion.example.com:2222
"#;
        let ssh_config = SshConfig::parse(ssh_config_content).unwrap();

        let result = resolve_effective_jump_hosts(None, Some(&ssh_config), "internal.example.com");
        assert_eq!(result, Some("bastion.example.com:2222".to_string()));
    }

    /// Test ProxyJump with user@host:port format
    #[test]
    fn test_resolve_effective_jump_hosts_with_user_and_port() {
        let ssh_config_content = r#"
Host internal.example.com
    ProxyJump admin@bastion.example.com:2222
"#;
        let ssh_config = SshConfig::parse(ssh_config_content).unwrap();

        let result = resolve_effective_jump_hosts(None, Some(&ssh_config), "internal.example.com");
        assert_eq!(result, Some("admin@bastion.example.com:2222".to_string()));
    }

    /// Test wildcard pattern matching for ProxyJump
    #[test]
    fn test_resolve_effective_jump_hosts_wildcard() {
        let ssh_config_content = r#"
Host *.internal.example.com
    ProxyJump gateway.example.com

Host db.internal.example.com
    ProxyJump db-gateway.example.com
"#;
        let ssh_config = SshConfig::parse(ssh_config_content).unwrap();

        // Should match db.internal.example.com specifically
        let result =
            resolve_effective_jump_hosts(None, Some(&ssh_config), "db.internal.example.com");
        assert_eq!(result, Some("db-gateway.example.com".to_string()));

        // Should match wildcard pattern
        let result =
            resolve_effective_jump_hosts(None, Some(&ssh_config), "web.internal.example.com");
        assert_eq!(result, Some("gateway.example.com".to_string()));
    }

    /// Test that unmatched hosts get no ProxyJump
    #[test]
    fn test_resolve_effective_jump_hosts_no_match() {
        let ssh_config_content = r#"
Host *.internal.example.com
    ProxyJump gateway.example.com
"#;
        let ssh_config = SshConfig::parse(ssh_config_content).unwrap();

        // Should not match - different domain
        let result = resolve_effective_jump_hosts(None, Some(&ssh_config), "external.example.com");
        assert_eq!(result, None);
    }

    /// Test ProxyJump none value (disables jump)
    #[test]
    fn test_resolve_effective_jump_hosts_none_value() {
        let ssh_config_content = r#"
Host *.example.com
    ProxyJump gateway.example.com

Host direct.example.com
    ProxyJump none
"#;
        let ssh_config = SshConfig::parse(ssh_config_content).unwrap();

        // direct.example.com should have ProxyJump explicitly set to "none"
        // Note: The actual handling of "none" as special value would be
        // done by the connection layer, but the config should return it
        let result = resolve_effective_jump_hosts(None, Some(&ssh_config), "direct.example.com");
        assert_eq!(result, Some("none".to_string()));
    }

    /// Test complex multi-hop chain with user and ports
    #[test]
    fn test_resolve_effective_jump_hosts_complex_chain() {
        let ssh_config_content = r#"
Host production.internal
    ProxyJump user1@jump1.example.com:22,user2@jump2.example.com:2222,jump3.example.com
"#;
        let ssh_config = SshConfig::parse(ssh_config_content).unwrap();

        let result = resolve_effective_jump_hosts(None, Some(&ssh_config), "production.internal");
        assert_eq!(
            result,
            Some(
                "user1@jump1.example.com:22,user2@jump2.example.com:2222,jump3.example.com"
                    .to_string()
            )
        );
    }
}