regent-sdk 0.6.0

Multi-paradigm configuration management system as a library
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
use serde::Deserialize;
use serde::Serialize;
use serde::de;
use ssh2::Session;
use std::io::Read;
use std::net::TcpStream;
use std::path::PathBuf;
#[allow(unused)]
use tracing::{debug, error, info, trace, warn};

use crate::command::CommandResult;
use crate::error::RegentError;
use crate::hosts::handlers::HostHandler;
use crate::hosts::handlers::final_command;
use crate::hosts::handlers::localhost::WhichUser;
use crate::hosts::privilege::Credentials;
use crate::hosts::privilege::LoginKey;
use crate::hosts::privilege::LoginKeyRef;
use crate::hosts::privilege::Privilege;
use crate::secrets::SecretProvider;
use crate::secrets::SecretReference;

#[derive(Clone)]
pub struct Ssh2HostHandler {
    auth: Ssh2AuthMethod,
    session: Session,
}

impl<'de> Deserialize<'de> for Ssh2HostHandler {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Ssh2HostHandlerHelper {
            auth: Ssh2AuthMethod,
        }

        let helper = Ssh2HostHandlerHelper::deserialize(deserializer)?;
        match Ssh2HostHandler::from(helper.auth) {
            Ok(ssh2_host_handler) => Ok(ssh2_host_handler),
            Err(details) => Err(de::Error::custom(format!("{:?}", details))),
        }
    }
}

impl std::fmt::Debug for Ssh2HostHandler {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Ssh2HostHandler")
            .field("auth", &self.auth)
            .field("authenticated", &self.session.authenticated())
            .finish()
    }
}

impl HostHandler for Ssh2HostHandler {
    fn connect(
        &mut self,
        endpoint: &str,
        _secret_provider: &Option<SecretProvider>,
    ) -> Result<(), RegentError> {
        // Check whether a session is already enabled or not (init() might have already been called
        // on this host)
        if self.is_connected() {
            return Ok(());
        }

        let address_and_port: Vec<&str> = endpoint.split(':').collect();
        if address_and_port.is_empty() {
            return Err(RegentError::FailedInitialization(
                "empty address".to_string(),
            ));
        }

        let address = address_and_port[0];
        let ssh_port: u16 = match address_and_port.get(1) {
            Some(port) => match port.parse::<u16>() {
                Ok(p) => p,
                Err(e) => {
                    return Err(RegentError::FailedInitialization(format!(
                        "invalid port: {}",
                        e
                    )));
                }
            },
            None => 22,
        };

        match TcpStream::connect(format!("{}:{}", address, ssh_port)) {
            Ok(tcp) => {
                self.session.set_tcp_stream(tcp);

                if let Err(details) = self.session.handshake() {
                    return Err(RegentError::FailedInitialization(format!("{:?}", details)));
                }

                match &self.auth {
                    Ssh2AuthMethod::UsernamePassword(credentials) => {
                        match self
                            .session
                            .userauth_password(credentials.username(), credentials.password())
                        {
                            Ok(()) => Ok(()),
                            Err(detailss) => {
                                Err(RegentError::FailedInitialization(format!("{:?}", detailss)))
                            }
                        }
                    }
                    Ssh2AuthMethod::Key(login_key) => {
                        match self.session.userauth_pubkey_memory(
                            login_key.username(),
                            None,
                            login_key.key(),
                            None,
                        ) {
                            Ok(()) => Ok(()),
                            Err(detailss) => {
                                Err(RegentError::FailedInitialization(format!("{:?}", detailss)))
                            }
                        }
                    }
                    // Ssh2AuthMethod::Agent(_agent) => {
                    //     return Ok(());
                    // }
                    _ => {
                        return Err(RegentError::FailedInitialization(String::from(
                            "Other RegentError",
                        )));
                    }
                }
            }
            Err(e) => {
                return Err(RegentError::FailedTcpBinding(format!("{:?}", e)));
            }
        }
    }

    fn is_connected(&mut self) -> bool {
        self.session.authenticated()
    }

    fn disconnect(&mut self) -> Result<(), RegentError> {
        if let Err(ssh2_details) = self.session.disconnect(
            Some(ssh2::DisconnectCode::ByApplication),
            "disconnection called",
            None,
        ) {
            return Err(RegentError::AnyOtherError(format!(
                "failed to close SSH2 session : {}",
                ssh2_details
            )));
        }
        Ok(())
    }

    fn is_this_command_available(
        &mut self,
        command: &str,
        privilege: &Privilege,
    ) -> Result<bool, RegentError> {
        let check_cmd_content = format!("command -v {}", command);
        let check_cmd_result = self.run_command(check_cmd_content.as_str(), privilege);

        match check_cmd_result {
            Ok(cmd_result) => {
                if cmd_result.return_code == 0 {
                    Ok(true)
                } else {
                    Ok(false)
                }
            }
            Err(e) => {
                return Err(RegentError::FailureToRunCommand(format!("{:?}", e)));
            }
        }
    }

    fn run_command(
        &mut self,
        command: &str,
        privilege: &Privilege,
    ) -> Result<CommandResult, RegentError> {
        match self.session.channel_session() {
            Ok(mut channel) => {
                let final_command = final_command(command, privilege, &WhichUser::CurrentUser);

                if let Err(details) = channel.exec(&final_command) {
                    return Err(RegentError::FailureToRunCommand(format!("{:?}", details)));
                }

                let mut stdout = String::new();
                let mut stderr = String::new();

                let mut ssh_stdout = channel.stream(0);
                let mut ssh_stderr = channel.stderr();

                if let Err(details) = ssh_stdout.read_to_string(&mut stdout) {
                    return Err(RegentError::FailureToRunCommand(format!(
                        "Unable to read from SSH STDOUT : {:?}",
                        details
                    )));
                }
                if let Err(details) = ssh_stderr.read_to_string(&mut stderr) {
                    return Err(RegentError::FailureToRunCommand(format!(
                        "Unable to read from SSH STDERR : {:?}",
                        details
                    )));
                }

                if let Err(details) = channel.close() {
                    return Err(RegentError::ProblemWithHostConnection(format!(
                        "Unable to close connection properly : {:?}",
                        details
                    )));
                }

                let return_code = match channel.exit_status() {
                    Ok(code) => code,
                    Err(e) => {
                        return Err(RegentError::ProblemWithHostConnection(format!(
                            "RegentError getting exit status: {}",
                            e
                        )));
                    }
                };

                Ok(CommandResult {
                    return_code,
                    stdout,
                    stderr,
                })
            }

            Err(e) => Err(RegentError::FailureToEstablishConnection(e.to_string())),
        }
    }

    fn run_windows_command(&mut self, command: &str) -> Result<CommandResult, RegentError> {
        match self.session.channel_session() {
            Ok(mut channel) => {
                let final_command = format!("cmd /C {}", command);

                if let Err(details) = channel.exec(&final_command) {
                    return Err(RegentError::FailureToRunCommand(format!("{:?}", details)));
                }
                let mut stdout = String::new();
                let mut stderr = String::new();

                let mut ssh_stdout = channel.stream(0);
                let mut ssh_stderr = channel.stderr();

                if let Err(details) = ssh_stdout.read_to_string(&mut stdout) {
                    return Err(RegentError::FailureToRunCommand(format!(
                        "Unable to read from SSH STDOUT : {:?}",
                        details
                    )));
                }
                if let Err(details) = ssh_stderr.read_to_string(&mut stderr) {
                    return Err(RegentError::FailureToRunCommand(format!(
                        "Unable to read from SSH STDERR : {:?}",
                        details
                    )));
                }

                if let Err(details) = channel.wait_close() {
                    warn!("Failed ton wait on SSH channel closing : {:?}", details);
                }

                let return_code = match channel.exit_status() {
                    Ok(code) => code,
                    Err(e) => {
                        return Err(RegentError::ProblemWithHostConnection(format!(
                            "RegentError getting exit status: {}",
                            e
                        )));
                    }
                };

                return Ok(CommandResult {
                    return_code,
                    stdout,
                    stderr,
                });
            }
            Err(e) => {
                return Err(RegentError::FailureToEstablishConnection(format!("{e}")));
            }
        }
    }

    fn get_file(&mut self, path: PathBuf) -> Result<Vec<u8>, RegentError> {
        if !self.is_connected() {
            return Err(RegentError::FailedInitialization(
                "Not connected to host".to_string(),
            ));
        }

        let (mut file_channel, stat) = match self.session.scp_recv(&path) {
            Ok((channel, filestats)) => (channel, filestats),
            Err(details) => {
                return Err(RegentError::ConnectionLevel(format!(
                    "Failed to establish SSH2 channel to retrieve file : {:?}",
                    details
                )));
            }
        };

        let mut buffer: Vec<u8> = match stat.size().try_into() {
            Ok(size) => Vec::with_capacity(size),
            Err(_) => Vec::new(),
        };
        if let Err(details) = file_channel.read_to_end(&mut buffer) {
            error!("Failed to read SSH2 buffer : {:?}", details);
            return Err(RegentError::ConnectionLevel(format!(
                "Failed to read SSH2 buffer : {:?}",
                details
            )));
        }

        // Close the channel and wait for the whole content to be tranferred
        if let Err(details) = file_channel.send_eof() {
            return Err(RegentError::ConnectionLevel(format!("{:?}", details)));
        }
        if let Err(details) = file_channel.wait_eof() {
            return Err(RegentError::ConnectionLevel(format!("{:?}", details)));
        }
        if let Err(details) = file_channel.close() {
            return Err(RegentError::ConnectionLevel(format!("{:?}", details)));
        }
        if let Err(details) = file_channel.wait_close() {
            return Err(RegentError::ConnectionLevel(format!("{:?}", details)));
        }

        Ok(buffer)
    }
}

impl Ssh2HostHandler {
    pub fn from(auth: Ssh2AuthMethod) -> Result<Ssh2HostHandler, RegentError> {
        match Session::new() {
            Ok(session) => Ok(Ssh2HostHandler { auth, session }),
            Err(details) => Err(RegentError::ConnectionLevel(format!(
                "Failed to create new SSH2 session : {:?}",
                details
            ))),
        }
    }

    pub fn username_password(
        username: &str,
        password: &str,
    ) -> Result<Ssh2HostHandler, RegentError> {
        match Ssh2HostHandler::from(Ssh2AuthMethod::UsernamePassword(Credentials::from(
            username, password,
        ))) {
            Ok(ssh2_host_handler) => Ok(ssh2_host_handler),
            Err(details) => Err(RegentError::ConnectionLevel(format!(
                "Failed to create new Ssh2HostHandler : {:?}",
                details
            ))),
        }
    }

    pub fn key(username: &str, key: String) -> Result<Ssh2HostHandler, RegentError> {
        match Ssh2HostHandler::from(Ssh2AuthMethod::Key(LoginKey::from(
            username.to_string(),
            key,
        ))) {
            Ok(ssh2_host_handler) => Ok(ssh2_host_handler),
            Err(details) => Err(RegentError::ConnectionLevel(format!(
                "Failed to create new Ssh2HostHandler : {:?}",
                details
            ))),
        }
    }

    pub fn agent(agent_name: &str) -> Result<Ssh2HostHandler, RegentError> {
        match Ssh2HostHandler::from(Ssh2AuthMethod::Agent(agent_name.to_string())) {
            Ok(ssh2_host_handler) => Ok(ssh2_host_handler),
            Err(details) => Err(RegentError::ConnectionLevel(format!(
                "Failed to create new Ssh2HostHandler : {:?}",
                details
            ))),
        }
    }
}

#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum Ssh2AuthMethod {
    UsernamePassword(Credentials),

    Key(LoginKey),
    Agent(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum Ssh2AuthReference {
    UsernamePassword(SecretReference),
    Key(LoginKeyRef),
    Agent(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
#[serde(deny_unknown_fields)]
pub struct Ssh2Auth {
    pub auth_method: Ssh2AuthReference,
}

impl Ssh2Auth {
    pub fn username_password(secret_reference: &str) -> Self {
        Self {
            auth_method: Ssh2AuthReference::UsernamePassword(SecretReference::from(
                secret_reference,
            )),
        }
    }

    pub fn key(username: &str, key_secret_reference: &str) -> Self {
        Self {
            auth_method: Ssh2AuthReference::Key(LoginKeyRef::from(
                username.to_string(),
                SecretReference::from(key_secret_reference),
            )),
        }
    }

    pub fn agent(agent_name: &str) -> Self {
        Self {
            auth_method: Ssh2AuthReference::Agent(agent_name.to_string()),
        }
    }
}

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

    #[test]
    fn test_deserialize_username_password() {
        let yaml = r#"
            !UsernamePassword
              Username: "testuser"
              Password: "testpass"
        "#;
        let auth_method = yaml_serde::from_str::<Ssh2AuthMethod>(yaml);
        matches!(auth_method, Ok(Ssh2AuthMethod::UsernamePassword(_)));
    }

    #[test]
    fn test_deserialize_key_file() {
        let yaml = r#"
            !Key
              Username: testuser
              Key: /path/to/private/key
        "#;
        let auth_method = yaml_serde::from_str::<Ssh2AuthMethod>(yaml);
        matches!(auth_method, Ok(Ssh2AuthMethod::Key(_)));
    }

    #[test]
    fn test_deserialize_agent() {
        let yaml = r#"
            !Agent
                "default"
        "#;
        let auth_method = yaml_serde::from_str::<Ssh2AuthMethod>(yaml);
        matches!(auth_method, Ok(Ssh2AuthMethod::Agent(_)));
    }
}

impl std::fmt::Debug for Ssh2AuthMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Ssh2AuthMethod::UsernamePassword(creds) => {
                write!(
                    f,
                    "UsernamePassword(Credentials {{ username: {:?}, password: \"********\" }})",
                    creds.username()
                )
            }
            Ssh2AuthMethod::Key(login_key_path) => {
                write!(f, "Key(({:?}, ********))", login_key_path.username())
            }
            Ssh2AuthMethod::Agent(agent_name) => {
                write!(f, "Agent({:?})", agent_name)
            }
        }
    }
}