ssh-commander-core 0.1.0

Async Rust domain layer for SSH, SFTP, FTP/FTPS, PostgreSQL, and connection management — the engine behind midnight-ssh.
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
use anyhow::Result;
use russh::*;
use russh_sftp::client::SftpSession;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

use crate::ssh::{Client, HostKeyStore};

/// Configuration for a standalone SFTP connection (SSH transport, no PTY).
#[derive(Clone, Deserialize)]
pub struct SftpConfig {
    pub host: String,
    pub port: u16,
    pub username: String,
    pub auth_method: SftpAuthMethod,
}

impl std::fmt::Debug for SftpConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SftpConfig")
            .field("host", &self.host)
            .field("port", &self.port)
            .field("username", &self.username)
            .field("auth_method", &self.auth_method)
            .finish()
    }
}

#[derive(Clone, Deserialize)]
#[serde(tag = "type")]
pub enum SftpAuthMethod {
    Password {
        password: String,
    },
    PublicKey {
        key_path: String,
        passphrase: Option<String>,
    },
}

impl std::fmt::Debug for SftpAuthMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SftpAuthMethod::Password { .. } => f
                .debug_struct("SftpAuthMethod::Password")
                .field("password", &"<redacted>")
                .finish(),
            SftpAuthMethod::PublicKey {
                key_path,
                passphrase,
            } => f
                .debug_struct("SftpAuthMethod::PublicKey")
                .field("key_path", key_path)
                .field(
                    "passphrase",
                    &passphrase
                        .as_ref()
                        .map(|_| "<redacted>")
                        .unwrap_or("<none>"),
                )
                .finish(),
        }
    }
}

/// A single file/directory entry returned from directory listings.
/// Used by both local and remote (SFTP/FTP) file operations.
#[derive(Debug, Clone, Serialize)]
pub struct FileEntry {
    pub name: String,
    pub size: u64,
    /// Pre-formatted timestamp string for human display.
    pub modified: Option<String>,
    /// Raw modification time as Unix epoch seconds. Surfaced
    /// alongside `modified` so consumers (the macOS file table)
    /// can sort numerically and reformat per-locale instead of
    /// relying on lexical comparison of the formatted string.
    pub modified_unix: Option<i64>,
    pub permissions: Option<String>,
    pub owner: Option<String>,
    pub group: Option<String>,
    pub file_type: FileEntryType,
}

/// Backward-compatible alias for code that still references RemoteFileEntry.
pub type RemoteFileEntry = FileEntry;

#[derive(Debug, Clone, Serialize, PartialEq)]
pub enum FileEntryType {
    File,
    Directory,
    Symlink,
}

/// Standalone SFTP client — opens an SSH connection and SFTP subsystem
/// channel without allocating a PTY.
pub struct StandaloneSftpClient {
    session: Option<Arc<client::Handle<Client>>>,
    sftp: Option<SftpSession>,
}

impl StandaloneSftpClient {
    /// Establish an SSH connection, authenticate, and open the SFTP subsystem.
    pub async fn connect(config: &SftpConfig, host_keys: Arc<HostKeyStore>) -> Result<Self> {
        let auth = match &config.auth_method {
            SftpAuthMethod::Password { password } => {
                crate::ssh::ResolvedAuth::Password { password }
            }
            SftpAuthMethod::PublicKey {
                key_path,
                passphrase,
            } => crate::ssh::ResolvedAuth::Key {
                key: Box::new(crate::ssh::load_private_key(
                    key_path,
                    passphrase.as_deref(),
                )?),
                key_path_hint: Some(key_path),
            },
        };

        let ssh_session = crate::ssh::connect_authenticated(
            &config.host,
            config.port,
            &config.username,
            auth,
            Duration::from_secs(10),
            host_keys,
        )
        .await?;
        let session = Arc::new(ssh_session);

        // Open an SFTP subsystem channel (no PTY)
        let channel = session.channel_open_session().await?;
        channel.request_subsystem(true, "sftp").await?;
        let sftp = SftpSession::new(channel.into_stream()).await?;

        Ok(Self {
            session: Some(session),
            sftp: Some(sftp),
        })
    }

    pub async fn disconnect(&mut self) -> Result<()> {
        // Drop SFTP session first
        self.sftp.take();
        // Disconnect SSH session
        if let Some(session) = self.session.take() {
            match Arc::try_unwrap(session) {
                Ok(session) => {
                    if let Err(e) = session.disconnect(Disconnect::ByApplication, "", "").await {
                        tracing::warn!("SFTP SSH disconnect failed cleanly: {}", e);
                    }
                }
                Err(arc_session) => {
                    // Other references (e.g. pending SFTP ops) still exist;
                    // drop ours. The session ends when the last reference dies.
                    drop(arc_session);
                }
            }
        }
        Ok(())
    }

    // ===== File Operations =====

    /// List directory contents at `path`.
    pub async fn list_dir(&self, path: &str) -> Result<Vec<RemoteFileEntry>> {
        let sftp = self
            .sftp
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("SFTP session not connected"))?;

        let entries = sftp
            .read_dir(path)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to list directory '{}': {}", path, e))?;

        let mut result = Vec::new();
        for entry in entries {
            let name = entry.file_name();
            // Skip . and .. entries
            if name == "." || name == ".." {
                continue;
            }

            let attrs = entry.metadata();
            let size = attrs.size.unwrap_or(0);
            let mtime_secs = attrs.mtime.map(|t| t as i64);
            let modified = mtime_secs.map(format_unix_timestamp);

            let permissions = attrs.permissions.map(format_permissions);
            let owner = attrs.uid.map(|u| u.to_string());
            let group = attrs.gid.map(|g| g.to_string());

            let file_type = if attrs.is_dir() {
                FileEntryType::Directory
            } else if attrs.is_symlink() {
                FileEntryType::Symlink
            } else {
                FileEntryType::File
            };

            result.push(RemoteFileEntry {
                name,
                size,
                modified,
                modified_unix: mtime_secs,
                permissions,
                owner,
                group,
                file_type,
            });
        }

        // Sort: directories first, then by name
        result.sort_by(|a, b| {
            let a_is_dir = matches!(a.file_type, FileEntryType::Directory);
            let b_is_dir = matches!(b.file_type, FileEntryType::Directory);
            b_is_dir
                .cmp(&a_is_dir)
                .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
        });

        Ok(result)
    }

    /// Download a remote file to a local path. Streams chunks — never buffers
    /// the whole file. Returns bytes downloaded.
    pub async fn download_file(&self, remote_path: &str, local_path: &str) -> Result<u64> {
        let sftp = self
            .sftp
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("SFTP session not connected"))?;

        let mut remote_file = sftp
            .open(remote_path)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to open remote file '{}': {}", remote_path, e))?;
        let mut local_file = tokio::fs::File::create(local_path)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to create local file '{}': {}", local_path, e))?;

        let mut buf = vec![0u8; crate::ssh::SFTP_CHUNK_SIZE];
        let mut total_bytes = 0u64;
        loop {
            let n = remote_file.read(&mut buf).await?;
            if n == 0 {
                break;
            }
            local_file.write_all(&buf[..n]).await?;
            total_bytes += n as u64;
        }
        local_file.flush().await?;
        Ok(total_bytes)
    }

    /// Upload a local file to a remote path. Streams chunks — never buffers
    /// the whole file. Returns bytes uploaded.
    pub async fn upload_file(&self, local_path: &str, remote_path: &str) -> Result<u64> {
        let sftp = self
            .sftp
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("SFTP session not connected"))?;

        let mut local_file = tokio::fs::File::open(local_path)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to open local file '{}': {}", local_path, e))?;
        let mut remote_file = sftp.create(remote_path).await.map_err(|e| {
            anyhow::anyhow!("Failed to create remote file '{}': {}", remote_path, e)
        })?;

        let mut buf = vec![0u8; crate::ssh::SFTP_CHUNK_SIZE];
        let mut total_bytes = 0u64;
        loop {
            let n = local_file.read(&mut buf).await?;
            if n == 0 {
                break;
            }
            remote_file.write_all(&buf[..n]).await?;
            total_bytes += n as u64;
        }
        remote_file.flush().await?;

        Ok(total_bytes)
    }

    /// Create a directory on the remote server.
    pub async fn create_dir(&self, path: &str) -> Result<()> {
        let sftp = self
            .sftp
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("SFTP session not connected"))?;

        sftp.create_dir(path)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to create directory '{}': {}", path, e))?;
        Ok(())
    }

    /// Rename a file or directory.
    pub async fn rename(&self, old_path: &str, new_path: &str) -> Result<()> {
        let sftp = self
            .sftp
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("SFTP session not connected"))?;

        sftp.rename(old_path, new_path).await.map_err(|e| {
            anyhow::anyhow!("Failed to rename '{}' to '{}': {}", old_path, new_path, e)
        })?;
        Ok(())
    }

    /// Delete a file on the remote server.
    pub async fn delete_file(&self, path: &str) -> Result<()> {
        let sftp = self
            .sftp
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("SFTP session not connected"))?;

        sftp.remove_file(path)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to delete file '{}': {}", path, e))?;
        Ok(())
    }

    /// Delete a directory on the remote server.
    pub async fn delete_dir(&self, path: &str) -> Result<()> {
        let sftp = self
            .sftp
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("SFTP session not connected"))?;

        sftp.remove_dir(path)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to delete directory '{}': {}", path, e))?;
        Ok(())
    }
}

/// Convert a Unix timestamp (seconds since epoch) to a readable UTC datetime
/// string ("YYYY-MM-DD HH:MM:SS"). Uses chrono for correct leap-year and
/// post-2106 handling.
pub fn format_unix_timestamp(secs: i64) -> String {
    chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0)
        .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
        .unwrap_or_else(|| "invalid-timestamp".to_string())
}

/// Format Unix file permissions (mode bits) as a string like `rwxr-xr-x`.
pub(crate) fn format_permissions(mode: u32) -> String {
    let mut s = String::with_capacity(9);
    let flags = [
        (0o400, 'r'),
        (0o200, 'w'),
        (0o100, 'x'),
        (0o040, 'r'),
        (0o020, 'w'),
        (0o010, 'x'),
        (0o004, 'r'),
        (0o002, 'w'),
        (0o001, 'x'),
    ];
    for (bit, ch) in flags.iter() {
        if mode & bit != 0 {
            s.push(*ch);
        } else {
            s.push('-');
        }
    }
    s
}

// =============================================================================
// Unit tests — Task 4.3
// =============================================================================
#[cfg(test)]
mod tests {
    use super::*;

    // ---- Helper function tests ----

    #[test]
    fn test_format_permissions_full() {
        assert_eq!(format_permissions(0o777), "rwxrwxrwx");
    }

    #[test]
    fn test_format_permissions_none() {
        assert_eq!(format_permissions(0o000), "---------");
    }

    #[test]
    fn test_format_permissions_typical_file() {
        assert_eq!(format_permissions(0o644), "rw-r--r--");
    }

    #[test]
    fn test_format_permissions_typical_dir() {
        assert_eq!(format_permissions(0o755), "rwxr-xr-x");
    }

    #[test]
    fn test_format_permissions_write_only() {
        assert_eq!(format_permissions(0o200), "-w-------");
    }

    #[test]
    fn format_unix_timestamp_epoch() {
        assert_eq!(format_unix_timestamp(0), "1970-01-01 00:00:00");
    }

    #[test]
    fn format_unix_timestamp_known_date() {
        // 2024-01-01 00:00:00 UTC
        assert_eq!(format_unix_timestamp(1704067200), "2024-01-01 00:00:00");
    }

    #[test]
    fn format_unix_timestamp_with_time() {
        // 2000-06-15 11:30:45 UTC
        assert_eq!(format_unix_timestamp(961068645), "2000-06-15 11:30:45");
    }

    #[test]
    fn format_unix_timestamp_post_2106() {
        // 2200-01-01 00:00:00 UTC — past the u32 epoch cutoff that the old
        // hand-rolled code would have silently truncated.
        assert_eq!(format_unix_timestamp(7258118400), "2200-01-01 00:00:00");
    }

    // ---- StandaloneSftpClient unit tests ----

    #[test]
    fn test_file_entry_type_serialization() {
        // Verify that FileEntryType variants serialize correctly
        let entry = RemoteFileEntry {
            name: "test.txt".to_string(),
            size: 1024,
            modified: Some("2024-01-01 00:00:00".to_string()),
            modified_unix: Some(1_704_067_200),
            permissions: Some("rw-r--r--".to_string()),
            owner: Some("501".to_string()),
            group: Some("20".to_string()),
            file_type: FileEntryType::File,
        };
        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"name\":\"test.txt\""));
        assert!(json.contains("\"size\":1024"));
        assert!(json.contains("File"));
    }

    #[test]
    fn test_directory_entry_serialization() {
        let entry = RemoteFileEntry {
            name: "mydir".to_string(),
            size: 4096,
            modified: None,
            modified_unix: None,
            permissions: Some("rwxr-xr-x".to_string()),
            owner: None,
            group: None,
            file_type: FileEntryType::Directory,
        };
        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("Directory"));
        assert!(json.contains("\"modified\":null"));
    }

    #[test]
    fn test_symlink_entry_serialization() {
        let entry = RemoteFileEntry {
            name: "link".to_string(),
            size: 0,
            modified: None,
            modified_unix: None,
            permissions: None,
            owner: None,
            group: None,
            file_type: FileEntryType::Symlink,
        };
        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("Symlink"));
    }

    #[test]
    fn test_sftp_config_deserialization() {
        let json = r#"{"host":"10.0.0.1","port":22,"username":"admin","auth_method":{"type":"Password","password":"secret"}}"#;
        let config: SftpConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.host, "10.0.0.1");
        assert_eq!(config.port, 22);
        assert_eq!(config.username, "admin");
        match config.auth_method {
            SftpAuthMethod::Password { password } => assert_eq!(password, "secret"),
            _ => panic!("Expected Password auth method"),
        }
    }

    #[test]
    fn test_sftp_config_publickey() {
        let json = r#"{"host":"server","port":2222,"username":"deploy","auth_method":{"type":"PublicKey","key_path":"/home/user/.ssh/id_rsa","passphrase":null}}"#;
        let config: SftpConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.port, 2222);
        match config.auth_method {
            SftpAuthMethod::PublicKey {
                key_path,
                passphrase,
            } => {
                assert_eq!(key_path, "/home/user/.ssh/id_rsa");
                assert!(passphrase.is_none());
            }
            _ => panic!("Expected PublicKey auth method"),
        }
    }
}