termscp 1.2.0

termscp is a feature rich terminal file transfer and explorer with support for SCP/SFTP/FTP/Kube/S3/GCS/SMB/WebDAV
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
//! ## builder
//!
//! Remotefs client builder

use std::path::PathBuf;
use std::sync::Arc;

use remotefs::RemoteFs;
use remotefs_aws_s3::AwsS3Fs;
use remotefs_ftp::FtpFs;
use remotefs_gcs::credentials::service_account;
use remotefs_gcs::{GoogleCloudStorageCredentials, GoogleCloudStorageFs};
use remotefs_kube::KubeMultiPodFs as KubeFs;
#[cfg(smb_unix)]
use remotefs_smb::{
    PavaoSmbCredentials as SmbCredentials, PavaoSmbFs as SmbFs, PavaoSmbOptions as SmbOptions,
    SmbDialect as RemoteSmbDialect,
};
#[cfg(smb_windows)]
use remotefs_smb::{WNetSmbCredentials as SmbCredentials, WNetSmbFs as SmbFs};
use remotefs_ssh::{
    NoCheckServerKey, RusshSession as SshSession, ScpFs, SftpFs, SshAgentIdentity,
    SshConfigParseRule, SshOpts,
};
use remotefs_webdav::WebDAVFs;

#[cfg(smb_unix)]
use super::params::SmbDialect;
#[cfg(not(smb))]
use super::params::{AwsS3Params, GenericProtocolParams, GoogleCloudStorageParams};
#[cfg(smb)]
use super::params::{AwsS3Params, GenericProtocolParams, GoogleCloudStorageParams, SmbParams};
use super::params::{KubeProtocolParams, WebDAVProtocolParams};
use super::{FileTransferProtocol, ProtocolParams};
use crate::system::config_client::ConfigClient;
use crate::system::sshkey_storage::SshKeyStorage;

/// Remotefs builder
pub struct RemoteFsBuilder;

impl RemoteFsBuilder {
    /// Build RemoteFs client from protocol and params.
    ///
    /// if protocol and parameters are inconsistent, the function will panic.
    pub fn build(
        protocol: FileTransferProtocol,
        params: ProtocolParams,
        config_client: &ConfigClient,
    ) -> Result<Box<dyn RemoteFs>, String> {
        match (protocol, params) {
            (FileTransferProtocol::AwsS3, ProtocolParams::AwsS3(params)) => {
                Ok(Box::new(Self::aws_s3_client(params)?))
            }
            (FileTransferProtocol::Ftp(secure), ProtocolParams::Generic(params)) => {
                Ok(Box::new(Self::ftp_client(params, secure)))
            }
            (
                FileTransferProtocol::GoogleCloudStorage,
                ProtocolParams::GoogleCloudStorage(params),
            ) => Ok(Box::new(Self::gcs_client(params)?)),
            (FileTransferProtocol::Kube, ProtocolParams::Kube(params)) => {
                Ok(Box::new(Self::kube_client(params)?))
            }
            (FileTransferProtocol::Scp, ProtocolParams::Generic(params)) => {
                Ok(Box::new(Self::scp_client(params, config_client)?))
            }
            (FileTransferProtocol::Sftp, ProtocolParams::Generic(params)) => {
                Ok(Box::new(Self::sftp_client(params, config_client)?))
            }
            #[cfg(smb)]
            (FileTransferProtocol::Smb, ProtocolParams::Smb(params)) => {
                Ok(Box::new(Self::smb_client(params)?))
            }
            (FileTransferProtocol::WebDAV, ProtocolParams::WebDAV(params)) => {
                Ok(Box::new(Self::webdav_client(params)))
            }
            (protocol, params) => {
                error!("Invalid params for protocol '{:?}'", protocol);
                Err(format!(
                    "Invalid protocol '{protocol:?}' with parameters of type {params:?}",
                ))
            }
        }
    }

    /// Build aws s3 client from parameters
    fn aws_s3_client(params: AwsS3Params) -> Result<AwsS3Fs, String> {
        let rt = Arc::new(
            tokio::runtime::Builder::new_current_thread()
                .worker_threads(1)
                .enable_all()
                .build()
                .map_err(|e| format!("Unable to create tokio runtime: {e}"))?,
        );
        let mut client =
            AwsS3Fs::new(params.bucket_name, &rt).new_path_style(params.new_path_style);
        if let Some(region) = params.region {
            client = client.region(region);
        }
        if let Some(profile) = params.profile {
            client = client.profile(profile);
        }
        if let Some(endpoint) = params.endpoint {
            client = client.endpoint(endpoint);
        }
        if let Some(access_key) = params.access_key {
            client = client.access_key(access_key);
        }
        if let Some(secret_access_key) = params.secret_access_key {
            client = client.secret_access_key(secret_access_key);
        }
        if let Some(security_token) = params.security_token {
            client = client.security_token(security_token);
        }
        if let Some(session_token) = params.session_token {
            client = client.session_token(session_token);
        }
        Ok(client)
    }

    /// Build a Google Cloud Storage client from parameters.
    fn gcs_client(params: GoogleCloudStorageParams) -> Result<GoogleCloudStorageFs, String> {
        let runtime = Self::tokio_runtime()?;
        let mut client = match params.service_account_key {
            None => GoogleCloudStorageFs::new(params.bucket_name, &runtime),
            Some(path) => {
                let raw = std::fs::read_to_string(&path).map_err(|error| {
                    format!("Unable to read GCS service-account file '{path}': {error}")
                })?;
                let key = serde_json::from_str(&raw).map_err(|error| {
                    format!("Invalid GCS service-account JSON in '{path}': {error}")
                })?;
                let credentials = {
                    let _guard = runtime.enter();
                    service_account::Builder::new(key).build()
                }
                .map_err(|error| {
                    format!("Invalid GCS service-account credentials in '{path}': {error}")
                })?;
                GoogleCloudStorageFs::with_credentials(
                    params.bucket_name,
                    GoogleCloudStorageCredentials::custom(credentials),
                    &runtime,
                )
            }
        };
        client = client.endpoint(params.endpoint);
        Ok(client)
    }

    /// Build ftp client from parameters
    fn ftp_client(params: GenericProtocolParams, secure: bool) -> FtpFs {
        let mut client = FtpFs::new(params.address, params.port).passive_mode();
        if let Some(username) = params.username {
            client = client.username(username);
        }
        if let Some(password) = params.password {
            client = client.password(password);
        }
        if secure {
            client = client.secure(true, true);
        }
        client
    }

    /// Build kube client
    fn kube_client(params: KubeProtocolParams) -> Result<KubeFs, String> {
        let rt = Self::tokio_runtime()?;
        let kube_fs = KubeFs::new(&rt);
        if let Some(config) = params.config() {
            Ok(kube_fs.config(config))
        } else {
            Ok(kube_fs)
        }
    }

    /// Build scp client
    fn scp_client(
        params: GenericProtocolParams,
        config_client: &ConfigClient,
    ) -> Result<ScpFs<SshSession<NoCheckServerKey>>, String> {
        let opts = Self::build_ssh_opts(params, config_client);
        let rt = Self::tokio_runtime()?;
        Ok(ScpFs::russh(opts, rt))
    }

    /// Build sftp client
    fn sftp_client(
        params: GenericProtocolParams,
        config_client: &ConfigClient,
    ) -> Result<SftpFs<SshSession<NoCheckServerKey>>, String> {
        let opts = Self::build_ssh_opts(params, config_client);
        let rt = Self::tokio_runtime()?;
        Ok(SftpFs::russh(opts, rt))
    }

    /// Maps the user-facing SMB family to inclusive remotefs dialect bounds.
    #[cfg(smb_unix)]
    fn smb_dialect_bounds(dialect: SmbDialect) -> (RemoteSmbDialect, RemoteSmbDialect) {
        match dialect {
            SmbDialect::Auto => (RemoteSmbDialect::Smb202, RemoteSmbDialect::Smb311),
            SmbDialect::Smb1 => (RemoteSmbDialect::Nt1, RemoteSmbDialect::Nt1),
            SmbDialect::Smb2 => (RemoteSmbDialect::Smb202, RemoteSmbDialect::Smb210),
            SmbDialect::Smb3 => (RemoteSmbDialect::Smb300, RemoteSmbDialect::Smb311),
        }
    }

    #[cfg(smb_unix)]
    fn smb_client(params: SmbParams) -> Result<SmbFs, String> {
        let mut credentials = SmbCredentials::default()
            .server(format!("smb://{}:{}", params.address, params.port))
            .share(params.share);

        if let Some(username) = params.username {
            credentials = credentials.username(username);
        }
        if let Some(password) = params.password {
            credentials = credentials.password(password);
        }
        if let Some(workgroup) = params.workgroup {
            credentials = credentials.workgroup(workgroup);
        }

        let (min_dialect, max_dialect) = Self::smb_dialect_bounds(params.dialect);
        SmbFs::try_new_with_dialect(
            credentials,
            SmbOptions::default()
                .one_share_per_server(true)
                .case_sensitive(false),
            min_dialect,
            max_dialect,
        )
        .map_err(|e| {
            error!("Invalid params for protocol SMB: {e}");
            format!("Invalid params for protocol SMB: {e}")
        })
    }

    #[cfg(smb_windows)]
    fn smb_client(params: SmbParams) -> Result<SmbFs, String> {
        let mut credentials = SmbCredentials::new(params.address, params.share);

        if let Some(username) = params.username {
            credentials = credentials.username(username);
        }
        if let Some(password) = params.password {
            credentials = credentials.password(password);
        }

        // Dialect is OS-managed on Windows.
        Ok(SmbFs::new(credentials))
    }

    fn webdav_client(params: WebDAVProtocolParams) -> WebDAVFs {
        WebDAVFs::new(&params.username, &params.password, &params.uri)
    }

    /// Build ssh options from generic protocol params and client configuration
    fn build_ssh_opts(params: GenericProtocolParams, config_client: &ConfigClient) -> SshOpts {
        let mut opts = SshOpts::new(params.address.clone())
            .key_storage(Box::new(Self::make_ssh_storage(config_client)))
            .ssh_agent_identity(Some(SshAgentIdentity::All))
            .port(params.port);
        if let Some(username) = params.username {
            opts = opts.username(username);
        } else if let Ok(username) = whoami::username() {
            opts = opts.username(username);
        }
        // For SSH protocols, only set password if explicitly provided and non-empty.
        // This allows the SSH library to prioritize key-based and agent authentication.
        if let Some(password) = params.password
            && !password.is_empty()
        {
            opts = opts.password(password);
        }
        if let Some(config_path) = config_client.get_ssh_config() {
            opts = opts.config_file(
                PathBuf::from(config_path),
                SshConfigParseRule::ALLOW_UNKNOWN_FIELDS,
            );
        }
        opts
    }

    /// Make ssh storage from `ConfigClient` if possible, empty otherwise (empty is implicit if degraded)
    fn make_ssh_storage(config_client: &ConfigClient) -> SshKeyStorage {
        SshKeyStorage::from(config_client)
    }

    /// Create tokio runtime to run async code for remotefs
    fn tokio_runtime() -> Result<Arc<tokio::runtime::Runtime>, String> {
        Ok(Arc::new(
            tokio::runtime::Builder::new_current_thread()
                .worker_threads(1)
                .enable_all()
                .build()
                .map_err(|e| format!("Unable to create tokio runtime: {e}"))?,
        ))
    }
}

#[cfg(test)]
mod test {

    use std::path::{Path, PathBuf};

    #[cfg(smb)]
    use serial_test::serial;
    use tempfile::TempDir;

    use super::*;

    #[test]
    fn should_build_aws_s3_fs() {
        let params = ProtocolParams::AwsS3(
            AwsS3Params::new("omar", Some("eu-west-1"), Some("test"))
                .endpoint(Some("http://localhost:9000"))
                .new_path_style(true)
                .access_key(Some("pippo"))
                .secret_access_key(Some("pluto"))
                .security_token(Some("omar"))
                .session_token(Some("gerry-scotti")),
        );
        let config_client = get_config_client();
        assert!(
            RemoteFsBuilder::build(FileTransferProtocol::AwsS3, params, &config_client).is_ok()
        );
    }

    #[test]
    fn should_build_gcs_fs_with_application_default_credentials() {
        let params = ProtocolParams::GoogleCloudStorage(GoogleCloudStorageParams::new("my-bucket"));
        let config_client = get_config_client();

        assert!(
            RemoteFsBuilder::build(
                FileTransferProtocol::GoogleCloudStorage,
                params,
                &config_client,
            )
            .is_ok()
        );
    }

    #[test]
    fn should_reject_missing_gcs_service_account_file() {
        let directory = tempfile::TempDir::new().unwrap();
        let missing = directory.path().join("missing.json");
        let params = GoogleCloudStorageParams::new("my-bucket")
            .service_account_key(Some(missing.to_string_lossy().into_owned()));

        assert!(RemoteFsBuilder::gcs_client(params).is_err());
    }

    #[test]
    fn should_reject_malformed_gcs_service_account_json() {
        let file = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(file.path(), "not-json").unwrap();
        let params = GoogleCloudStorageParams::new("my-bucket")
            .service_account_key(Some(file.path().to_string_lossy().into_owned()));

        assert!(RemoteFsBuilder::gcs_client(params).is_err());
    }

    #[test]
    fn should_build_gcs_fs_with_service_account_file() {
        let file = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(
            file.path(),
            r#"{
                "type": "service_account",
                "client_email": "termscp@example.iam.gserviceaccount.com",
                "private_key_id": "test-key",
                "private_key": "-----BEGIN PRIVATE KEY-----\ninvalid-test-key\n-----END PRIVATE KEY-----\n",
                "project_id": "termscp-test",
                "universe_domain": "googleapis.com"
            }"#,
        )
        .unwrap();
        let params = GoogleCloudStorageParams::new("my-bucket")
            .service_account_key(Some(file.path().to_string_lossy().into_owned()));

        assert!(RemoteFsBuilder::gcs_client(params).is_ok());
    }

    #[test]
    fn should_build_ftp_fs() {
        let params = ProtocolParams::Generic(
            GenericProtocolParams::default()
                .address("127.0.0.1")
                .port(21)
                .username(Some("omar"))
                .password(Some("qwerty123")),
        );
        let config_client = get_config_client();
        assert!(
            RemoteFsBuilder::build(FileTransferProtocol::Ftp(true), params, &config_client).is_ok()
        );
    }

    #[test]
    fn test_should_build_kube_fs() {
        let params = ProtocolParams::Kube(KubeProtocolParams {
            namespace: Some("namespace".to_string()),
            cluster_url: Some("cluster_url".to_string()),
            username: Some("username".to_string()),
            client_cert: Some("client_cert".to_string()),
            client_key: Some("client_key".to_string()),
        });
        let config_client = get_config_client();
        assert!(RemoteFsBuilder::build(FileTransferProtocol::Kube, params, &config_client).is_ok());
    }

    #[test]
    fn should_build_scp_fs() {
        let params = ProtocolParams::Generic(
            GenericProtocolParams::default()
                .address("127.0.0.1")
                .port(22)
                .username(Some("omar"))
                .password(Some("qwerty123")),
        );
        let config_client = get_config_client();
        assert!(RemoteFsBuilder::build(FileTransferProtocol::Scp, params, &config_client).is_ok());
    }

    #[test]
    fn should_build_sftp_fs() {
        let params = ProtocolParams::Generic(
            GenericProtocolParams::default()
                .address("127.0.0.1")
                .port(22)
                .username(Some("omar"))
                .password(Some("qwerty123")),
        );
        let config_client = get_config_client();
        assert!(RemoteFsBuilder::build(FileTransferProtocol::Sftp, params, &config_client).is_ok());
    }

    #[test]
    #[cfg(smb)]
    #[serial]
    fn should_build_smb_fs() {
        let params = ProtocolParams::Smb(SmbParams::new("localhost", "share"));
        let config_client = get_config_client();
        assert!(RemoteFsBuilder::build(FileTransferProtocol::Smb, params, &config_client).is_ok());
    }

    #[test]
    #[cfg(smb_unix)]
    fn should_map_smb_dialect_to_bounds() {
        use remotefs_smb::SmbDialect as RemoteSmbDialect;

        use crate::filetransfer::params::SmbDialect;

        assert_eq!(
            RemoteFsBuilder::smb_dialect_bounds(SmbDialect::Auto),
            (RemoteSmbDialect::Smb202, RemoteSmbDialect::Smb311)
        );
        assert_eq!(
            RemoteFsBuilder::smb_dialect_bounds(SmbDialect::Smb1),
            (RemoteSmbDialect::Nt1, RemoteSmbDialect::Nt1)
        );
        assert_eq!(
            RemoteFsBuilder::smb_dialect_bounds(SmbDialect::Smb2),
            (RemoteSmbDialect::Smb202, RemoteSmbDialect::Smb210)
        );
        assert_eq!(
            RemoteFsBuilder::smb_dialect_bounds(SmbDialect::Smb3),
            (RemoteSmbDialect::Smb300, RemoteSmbDialect::Smb311)
        );
    }

    #[test]
    #[cfg(smb)]
    #[serial]
    fn should_build_smb_fs_with_dialect() {
        use crate::filetransfer::params::SmbDialect;

        let params =
            ProtocolParams::Smb(SmbParams::new("localhost", "share").dialect(SmbDialect::Smb1));
        let config_client = get_config_client();
        assert!(RemoteFsBuilder::build(FileTransferProtocol::Smb, params, &config_client).is_ok());
    }

    #[test]
    fn should_not_build_fs() {
        let params = ProtocolParams::Generic(
            GenericProtocolParams::default()
                .address("127.0.0.1")
                .port(22)
                .username(Some("omar"))
                .password(Some("qwerty123")),
        );
        let config_client = get_config_client();
        assert!(
            RemoteFsBuilder::build(FileTransferProtocol::AwsS3, params, &config_client).is_err()
        );
    }

    fn get_config_client() -> ConfigClient {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, ssh_keys_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        ConfigClient::new(cfg_path.as_path(), ssh_keys_path.as_path())
            .ok()
            .unwrap()
    }

    /// Get paths for configuration and keys directory
    fn get_paths(dir: &Path) -> (PathBuf, PathBuf) {
        let mut k: PathBuf = PathBuf::from(dir);
        let mut c: PathBuf = k.clone();
        k.push("ssh-keys/");
        c.push("config.toml");
        (c, k)
    }
}