cnctd-service-ssh 0.1.0

SSH command execution service - library and MCP server
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
//! Business logic for the SSH service.
//!
//! Provides both instance-based and global (legacy) APIs for SSH operations.
//! 
//! # Instance-based API (recommended for library usage)
//! 
//! ```rust,no_run
//! use cnctd_service_ssh::{SshService, SshRegisterArgs, SshExecArgs};
//! 
//! let service = SshService::new();
//! service.register(args).await?;
//! let result = service.exec(args).await?;
//! ```
//! 
//! # Global API (used by MCP server)
//! 
//! ```rust,no_run
//! use cnctd_service_ssh::{ssh_register, ssh_exec};
//! 
//! ssh_register(args).await?;
//! let result = ssh_exec(args).await?;
//! ```

use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
use tokio::task;
use tracing::{debug, info, warn};

use crate::service_error::ServiceError;

// =============================================================================
// Public Types
// =============================================================================

/// Arguments for registering an SSH target
#[derive(Debug, Clone, Deserialize)]
pub struct SshRegisterArgs {
    /// Client-defined identifier for this target (unique key)
    pub id: String,
    /// Hostname or IP of the SSH server
    pub host: String,
    /// Username to authenticate as
    pub user: String,
    /// SSH port (default 22)
    #[serde(default = "default_port")]
    pub port: u16,
    /// Optional passphrase for the private key (note: not supported with ssh command)
    pub key_passphrase: Option<String>,
    /// Path to OpenSSH known_hosts file (default "~/.ssh/known_hosts")
    #[serde(default = "default_known_hosts")]
    pub known_hosts_path: String,
}

/// Arguments for executing a command on an SSH target
#[derive(Debug, Clone, Deserialize)]
pub struct SshExecArgs {
    /// Target id previously registered
    pub id: String,
    /// Shell command to execute remotely
    pub command: String,
    /// Timeout in seconds (default 120)
    #[serde(default = "default_timeout_secs")]
    pub timeout_secs: u64,
}

/// Result of an SSH command execution
#[derive(Debug, Clone, Serialize)]
pub struct SshExecResult {
    /// Unique execution identifier
    pub exec_id: String,
    /// Command exit code (0 = success)
    pub exit_code: i32,
    /// Standard output
    pub stdout: String,
    /// Standard error
    pub stderr: String,
    /// Execution duration in milliseconds
    pub duration_ms: u128,
}

/// Result of registering an SSH target
#[derive(Debug, Clone, Serialize)]
pub struct SshRegisterResult {
    pub id: String,
    pub host: String,
    pub port: u16,
    pub user: String,
}

/// Result of unregistering an SSH target
#[derive(Debug, Clone, Serialize)]
pub struct SshUnregisterResult {
    pub id: String,
    pub existed: bool,
}

// =============================================================================
// Internal Types
// =============================================================================

#[derive(Debug, Clone)]
struct TargetConfig {
    host: String,
    user: String,
    port: u16,
    key_path: PathBuf,
    key_passphrase: Option<String>,
}

type TargetRegistry = RwLock<HashMap<String, TargetConfig>>;

// =============================================================================
// SshService - Instance-based API
// =============================================================================

/// SSH service with its own target registry.
/// 
/// Use this for library usage where you want isolated target management.
#[derive(Clone)]
pub struct SshService {
    targets: Arc<TargetRegistry>,
}

impl Default for SshService {
    fn default() -> Self {
        Self::new()
    }
}

impl SshService {
    /// Create a new SSH service with an empty target registry
    pub fn new() -> Self {
        Self {
            targets: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Create an SSH service using the global target registry.
    /// This is useful when you want to share targets with the MCP server.
    pub fn global() -> Self {
        Self {
            targets: Arc::clone(&GLOBAL_TARGETS),
        }
    }

    /// Register or replace an SSH target configuration
    pub async fn register(&self, args: SshRegisterArgs) -> Result<SshRegisterResult, ServiceError> {
        register_impl(&self.targets, args).await
    }

    /// Execute a command on a registered target
    pub async fn exec(&self, args: SshExecArgs) -> Result<SshExecResult, ServiceError> {
        exec_impl(&self.targets, args).await
    }

    /// Unregister a target by id
    pub async fn unregister(&self, id: String) -> Result<SshUnregisterResult, ServiceError> {
        unregister_impl(&self.targets, id).await
    }

    /// List all registered target IDs
    pub fn list_targets(&self) -> Result<Vec<String>, ServiceError> {
        let map = self.targets.read()
            .map_err(|e| ServiceError::Internal(format!("lock poisoned: {}", e)))?;
        Ok(map.keys().cloned().collect())
    }

    /// Check if a target is registered
    pub fn has_target(&self, id: &str) -> Result<bool, ServiceError> {
        let map = self.targets.read()
            .map_err(|e| ServiceError::Internal(format!("lock poisoned: {}", e)))?;
        Ok(map.contains_key(id))
    }
}

// =============================================================================
// Global API (Legacy, used by MCP server)
// =============================================================================

/// Global target registry for MCP server mode
static GLOBAL_TARGETS: Lazy<Arc<TargetRegistry>> =
    Lazy::new(|| Arc::new(RwLock::new(HashMap::new())));

/// Register or replace an SSH target configuration (global registry)
pub async fn ssh_register(args: SshRegisterArgs) -> Result<Value, ServiceError> {
    let result = register_impl(&GLOBAL_TARGETS, args).await?;
    Ok(json!(result))
}

/// Execute a command on a registered target (global registry)
pub async fn ssh_exec(args: SshExecArgs) -> Result<Value, ServiceError> {
    let result = exec_impl(&GLOBAL_TARGETS, args).await?;
    Ok(json!(result))
}

/// Unregister a target by id (global registry)
pub async fn ssh_unregister(id: String) -> Result<Value, ServiceError> {
    let result = unregister_impl(&GLOBAL_TARGETS, id).await?;
    Ok(json!(result))
}

// =============================================================================
// Implementation
// =============================================================================

async fn register_impl(
    targets: &TargetRegistry,
    args: SshRegisterArgs,
) -> Result<SshRegisterResult, ServiceError> {
    info!("Registering SSH target: {}", args.id);

    // Get key path from environment
    let key_path_str = std::env::var("SSH_KEY_PATH")
        .map_err(|_| ServiceError::InvalidParams(
            "SSH_KEY_PATH environment variable not set".to_string(),
        ))?;
    
    let key_path = expand_tilde(&key_path_str);
    
    if !key_path.exists() {
        return Err(ServiceError::InvalidParams(format!(
            "key_path not found: {}", key_path.display()
        )));
    }

    // Check key file is readable
    if let Err(e) = fs::metadata(&key_path) {
        return Err(ServiceError::InvalidParams(format!(
            "cannot read key_path {}: {}", key_path.display(), e
        )));
    }

    // Warn if passphrase is provided (not used with ssh command)
    if args.key_passphrase.is_some() {
        warn!("key_passphrase is not supported when using ssh command - key must be unencrypted or use ssh-agent");
    }

    let cfg = TargetConfig {
        host: args.host.clone(),
        user: args.user.clone(),
        port: args.port,
        key_path,
        key_passphrase: args.key_passphrase,
    };

    {
        let mut map = targets.write()
            .map_err(|e| ServiceError::Internal(format!("target registry lock poisoned: {}", e)))?;
        
        // Security: Prevent overwriting existing targets without explicit unregister
        if map.contains_key(&args.id) {
            return Err(ServiceError::InvalidParams(format!(
                "target '{}' already exists. Use unregister first to replace it.",
                args.id
            )));
        }
        
        map.insert(args.id.clone(), cfg);
    }

    info!("Successfully registered SSH target: {}", args.id);
    Ok(SshRegisterResult {
        id: args.id,
        host: args.host,
        port: args.port,
        user: args.user,
    })
}

async fn exec_impl(
    targets: &TargetRegistry,
    args: SshExecArgs,
) -> Result<SshExecResult, ServiceError> {
    info!("Executing command on target {}: {}", args.id, args.command);

    let cfg = {
        let map = targets.read()
            .map_err(|e| ServiceError::Internal(format!("target registry lock poisoned: {}", e)))?;
        match map.get(&args.id) {
            Some(c) => c.clone(),
            None => {
                return Err(ServiceError::NotFound(format!(
                    "unknown target id: {}. Use register first.",
                    args.id
                )))
            }
        }
    };

    let command = args.command.clone();
    let timeout = Duration::from_secs(args.timeout_secs.max(1));
    
    let result = task::spawn_blocking(move || exec_over_ssh(&cfg, &command, timeout))
        .await
        .map_err(|e| ServiceError::Internal(format!("task join error: {}", e)))??;

    info!(
        "Command completed on {}: exit_code={}, duration={}ms",
        args.id, result.exit_code, result.duration_ms
    );

    Ok(result)
}

async fn unregister_impl(
    targets: &TargetRegistry,
    id: String,
) -> Result<SshUnregisterResult, ServiceError> {
    info!("Unregistering SSH target: {}", id);

    let existed = {
        let mut map = targets.write()
            .map_err(|e| ServiceError::Internal(format!("target registry lock poisoned: {}", e)))?;
        map.remove(&id).is_some()
    };

    if existed {
        info!("Successfully unregistered SSH target: {}", id);
    } else {
        warn!("Target {} was not registered", id);
    }

    Ok(SshUnregisterResult { id, existed })
}

fn exec_over_ssh(
    cfg: &TargetConfig,
    command: &str,
    timeout: Duration,
) -> Result<SshExecResult, ServiceError> {
    // Final validation that key file is readable
    if let Err(e) = fs::metadata(&cfg.key_path) {
        return Err(ServiceError::InvalidParams(format!(
            "cannot read key_path {}: {}", cfg.key_path.display(), e
        )));
    }

    let start = Instant::now();
    
    // Build SSH command
    let target = format!("{}@{}", cfg.user, cfg.host);
    
    debug!("Executing SSH command: ssh -i {} -p {} {} {}", 
        cfg.key_path.display(), cfg.port, target, command);
    
    let output = Command::new("ssh")
        .arg("-i")
        .arg(&cfg.key_path)
        .arg("-p")
        .arg(cfg.port.to_string())
        .arg("-o")
        .arg("BatchMode=yes") // Non-interactive mode
        .arg("-o")
        .arg("ConnectTimeout=30")
        .arg(&target)
        .arg(command)
        .output()
        .map_err(|e| ServiceError::Internal(format!(
            "failed to execute ssh command: {}", e
        )))?;

    let duration_ms = start.elapsed().as_millis();

    // Check if we exceeded timeout
    if duration_ms > timeout.as_millis() {
        warn!("SSH command exceeded timeout of {}s", timeout.as_secs());
    }

    let exit_code = output.status.code().unwrap_or(-1);
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    debug!("SSH command completed: exit_code={}, stdout_len={}, stderr_len={}", 
        exit_code, stdout.len(), stderr.len());

    Ok(SshExecResult {
        exec_id: uuid::Uuid::new_v4().to_string(),
        exit_code,
        stdout,
        stderr,
        duration_ms,
    })
}

// =============================================================================
// Helpers
// =============================================================================

fn default_port() -> u16 {
    22
}

fn default_known_hosts() -> String {
    "~/.ssh/known_hosts".into()
}

fn default_timeout_secs() -> u64 {
    120
}

fn expand_tilde(p: &str) -> PathBuf {
    if let Some(rest) = p.strip_prefix("~/") {
        if let Ok(home) = std::env::var("HOME") {
            return PathBuf::from(home).join(rest);
        }
    }
    PathBuf::from(p)
}