regent-sdk 0.9.1

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
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Hostname management attribute
//!
//! This module provides the `HostnameBlockExpectedState` type for setting and managing
//! the system hostname.
//!
//! **Compatible OS:**
//! - Linux, macOS, FreeBSD - uses hostnamectl or /etc/hostname
//! - Windows (when `windows` feature is enabled) - uses Windows hostname commands
//!
//! # Examples
//!
//! ## Rust API
//!
//! ```no_run
//! use regent_sdk::state::attribute::system::hostname::{HostnameBlockExpectedState, HostnameMethod};
//! use regent_sdk::{Attribute, ExpectedState, Privilege};
//!
//! // Set hostname using systemd method
//! let hostname = HostnameBlockExpectedState::builder("myserver.example.com")
//!     .with_method(HostnameMethod::Systemd)
//!     .build()
//!     .unwrap();
//!
//! let expected_state = ExpectedState::new()
//!     .with_attribute(Attribute::hostname(hostname, Privilege::WithSudo, None))
//!     .build();
//! ```
//!
//! ## YAML API
//!
//! ```yaml
//! Attributes:
//!   - Name: Hostname must be myserver.example.com
//!     Privilege: !WithSudo
//!     Detail: !Hostname
//!       Name: myserver.example.com
//!       Method: !Systemd
//! ```

use crate::error::RegentError;
use crate::hosts::managed_host::InternalApiCallOutcome;
use crate::hosts::managed_host::{AssessCompliance, ReachCompliance, Timeout};
use crate::hosts::properties::{HostProperties, InitSystem, LinuxFlavor, LinuxSpecifics, OsKind};
use crate::secrets::SecretProvidersPool;
use crate::state::Check;
use crate::state::attribute::HostHandler;
use crate::state::attribute::Privilege;
use crate::state::attribute::Remediation;
use crate::state::attribute::RemediationsList;
use crate::state::compliance::AttributeComplianceAssessment;
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Method for setting the hostname
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum HostnameMethod {
    /// Uses hostnamectl set-hostname (systemd, persistent across reboots)
    Systemd,
    /// Uses hostname command + writes /etc/hostname (non-systemd systems)
    Generic,
    #[cfg(feature = "windows")]
    /// Uses Windows hostname command (Windows only)
    Windows,
}

/// Configuration for managing the system hostname
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "PascalCase")]
pub struct HostnameBlockExpectedState {
    /// The desired hostname
    name: String,
    /// Method to use for setting the hostname (defaults to auto-detection)
    method: Option<HostnameMethod>,
}

impl Timeout for HostnameBlockExpectedState {
    fn default_timeout(&self) -> Duration {
        Duration::from_secs(5)
    }
}

impl HostnameBlockExpectedState {
    pub fn new(hostname: &str, method: Option<HostnameMethod>) -> HostnameBlockExpectedState {
        HostnameBlockExpectedState {
            name: hostname.to_string(),
            method,
        }
    }
}

impl Check for HostnameBlockExpectedState {
    fn check(&self) -> Result<(), RegentError> {
        if self.name.is_empty() {
            return Err(RegentError::IncoherentExpectedState(
                "Hostname cannot be empty.".to_string(),
            ));
        } else if let Err(details) = is_valid_hostname(&self.name) {
            return Err(RegentError::IncoherentExpectedState(details));
        }

        Ok(())
    }

    fn check_host_compatibility(
        &self,
        host_properties: &HostProperties,
    ) -> Result<(), RegentError> {
        match host_properties.os_kind() {
            OsKind::Linux(_) | OsKind::MacOs(_) | OsKind::FreeBsd(_) => Ok(()),
            #[cfg(feature = "windows")]
            OsKind::Windows(_) => Ok(()),
            incompatible_os_kind => Err(RegentError::IncompatibleHost(format!(
                "Host is {:?} but hostname management is only supported on Unix-like systems or Windows (with windows feature)",
                incompatible_os_kind
            ))),
        }
    }
}

impl<Handler: HostHandler> AssessCompliance<Handler> for HostnameBlockExpectedState {
    async fn assess_compliance(
        &self,
        host_handler: &mut Handler,
        host_properties: &Option<HostProperties>,
        privilege: &Privilege,
        _optional_secret_provider: &Option<SecretProvidersPool>,
    ) -> Result<AttributeComplianceAssessment, RegentError> {
        // Early check: verify we're on a compatible host
        if let Some(props) = host_properties {
            self.check_host_compatibility(props)?;
        }

        if let Err(details) = self.check() {
            return Err(RegentError::FailedDryRunEvaluation(format!(
                "Runtime check failed : {}",
                details
            )));
        }

        // Determine the effective OS kind - assume Linux if HostProperties is None
        let os_kind = host_properties
            .as_ref()
            .map(|props| props.os_kind())
            .unwrap_or(&OsKind::Linux(LinuxSpecifics {
                linux_flavor: LinuxFlavor::Debian,
                init_system: InitSystem::Systemd,
            }));

        // Get current hostname based on OS
        let current_hostname = match os_kind {
            #[cfg(feature = "windows")]
            OsKind::Windows(_) => match host_handler.run_windows_command("hostname").await {
                Ok(result) => {
                    if result.return_code != 0 {
                        return Err(RegentError::FailedDryRunEvaluation(
                            "Failed to get current hostname on Windows".to_string(),
                        ));
                    }
                    result.stdout.trim().to_string()
                }
                Err(e) => {
                    return Err(RegentError::FailedDryRunEvaluation(format!(
                        "Unable to get hostname on Windows: {:?}",
                        e
                    )));
                }
            },
            OsKind::Linux(_) | OsKind::MacOs(_) | OsKind::FreeBsd(_) => {
                match host_handler
                    .run_command("cat /etc/hostname", &Privilege::None)
                    .await
                {
                    Ok(result) => {
                        if result.return_code != 0 {
                            return Err(RegentError::FailedDryRunEvaluation(
                                "Failed to get current hostname".to_string(),
                            ));
                        }
                        result.stdout.trim().to_string()
                    }
                    Err(e) => {
                        return Err(RegentError::FailedDryRunEvaluation(format!(
                            "Unable to get hostname: {:?}",
                            e
                        )));
                    }
                }
            }
            OsKind::Unknown => {
                return Err(RegentError::FailedDryRunEvaluation(
                    "Cannot determine hostname on unknown OS".to_string(),
                ));
            }
        };

        if current_hostname == self.name {
            return Ok(AttributeComplianceAssessment::Compliant);
        }

        // Determine method based on OS and user preference
        let method = match os_kind {
            #[cfg(feature = "windows")]
            OsKind::Windows(_) => {
                // On Windows, only Windows method makes sense
                self.method.clone().unwrap_or(HostnameMethod::Windows)
            }
            OsKind::Linux(_) => {
                // On Linux, use user preference or default to Systemd
                self.method.clone().unwrap_or(HostnameMethod::Systemd)
            }
            OsKind::MacOs(_) | OsKind::FreeBsd(_) => {
                // On macOS and FreeBSD, Generic method is more appropriate
                self.method.clone().unwrap_or(HostnameMethod::Generic)
            }
            OsKind::Unknown => {
                return Err(RegentError::FailedDryRunEvaluation(
                    "Cannot set hostname on unknown OS".to_string(),
                ));
            }
        };

        Ok(AttributeComplianceAssessment::NonCompliant(
            RemediationsList::from(vec![Remediation::Hostname(HostnameApiCall::from(
                HostnameModuleInternalApiCall::SetHostname {
                    name: self.name.clone(),
                    method,
                },
                privilege.clone(),
            ))])
            .unwrap(),
        ))
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum HostnameModuleInternalApiCall {
    SetHostname {
        name: String,
        method: HostnameMethod,
    },
}

impl std::fmt::Display for HostnameModuleInternalApiCall {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HostnameModuleInternalApiCall::SetHostname { name, .. } => {
                write!(f, "set hostname to {}", name)
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HostnameApiCall {
    pub api_call: HostnameModuleInternalApiCall,
    privilege: Privilege,
}

impl HostnameApiCall {
    pub fn display(&self) -> String {
        match &self.api_call {
            HostnameModuleInternalApiCall::SetHostname { name, .. } => {
                format!("Set hostname to {}", name)
            }
        }
    }

    fn from(api_call: HostnameModuleInternalApiCall, privilege: Privilege) -> HostnameApiCall {
        HostnameApiCall {
            api_call,
            privilege,
        }
    }
}

impl Check for HostnameApiCall {
    fn check(&self) -> Result<(), RegentError> {
        Ok(())
    }

    fn check_host_compatibility(
        &self,
        host_properties: &HostProperties,
    ) -> Result<(), RegentError> {
        match host_properties.os_kind() {
            OsKind::Linux(_) | OsKind::MacOs(_) | OsKind::FreeBsd(_) => Ok(()),
            #[cfg(feature = "windows")]
            OsKind::Windows(_) => Ok(()),
            incompatible_os_kind => Err(RegentError::IncompatibleHost(format!(
                "Host is {:?} but hostname management is only supported on Unix-like systems or Windows (with windows feature)",
                incompatible_os_kind
            ))),
        }
    }
}

impl<Handler: HostHandler> ReachCompliance<Handler> for HostnameApiCall {
    async fn call(
        &self,
        host_handler: &mut Handler,
        host_properties: &Option<HostProperties>,
        _optional_secret_provider: &Option<SecretProvidersPool>,
    ) -> Result<InternalApiCallOutcome, RegentError> {
        // Early check: verify we're on a compatible host
        if let Some(props) = host_properties {
            self.check_host_compatibility(props)?;
        }

        // Determine the effective OS kind - assume Linux if HostProperties is None
        let os_kind = host_properties
            .as_ref()
            .map(|props| props.os_kind())
            .unwrap_or(&OsKind::Linux(LinuxSpecifics {
                linux_flavor: LinuxFlavor::Debian,
                init_system: InitSystem::Systemd,
            }));

        // Match on OS kind to execute the appropriate hostname command
        match os_kind {
            #[cfg(feature = "windows")]
            OsKind::Windows(_) => {
                // Extract hostname and method from the API call
                let (name, method) = match &self.api_call {
                    HostnameModuleInternalApiCall::SetHostname { name, method } => (name, method),
                };

                // Build Windows hostname command
                let cmd = match method {
                    HostnameMethod::Windows => format!("hostname {}", name),
                    // For Windows, we'll use the Windows method even if user specified systemd/generic
                    HostnameMethod::Systemd | HostnameMethod::Generic => {
                        format!("hostname {}", name)
                    }
                };

                // Execute Windows command
                let cmd_result = host_handler.run_windows_command(&cmd).await;

                match cmd_result {
                    Ok(result) => {
                        if result.return_code == 0 {
                            Ok(InternalApiCallOutcome::Success(None))
                        } else {
                            Ok(InternalApiCallOutcome::Failure(format!(
                                "RC: {}, STDOUT: {}, STDERR: {}",
                                result.return_code, result.stdout, result.stderr
                            )))
                        }
                    }
                    Err(e) => Ok(InternalApiCallOutcome::Failure(format!(
                        "Command execution failed: {:?}",
                        e
                    ))),
                }
            }
            OsKind::Linux(_) | OsKind::MacOs(_) | OsKind::FreeBsd(_) => {
                // Extract hostname and method from the API call
                let (name, method) = match &self.api_call {
                    HostnameModuleInternalApiCall::SetHostname { name, method } => (name, method),
                };

                // Build Unix hostname command
                let cmd = match method {
                    HostnameMethod::Systemd => format!("hostnamectl set-hostname {}", name),
                    HostnameMethod::Generic => {
                        format!("hostname {} && echo {} > /etc/hostname", name, name)
                    }
                    #[cfg(feature = "windows")]
                    HostnameMethod::Windows => {
                        // On Unix, use systemd as fallback for Windows method
                        format!("hostnamectl set-hostname {}", name)
                    }
                };

                // Execute Unix command
                let cmd_result = host_handler.run_command(&cmd, &self.privilege).await;

                match cmd_result {
                    Ok(result) => {
                        if result.return_code == 0 {
                            Ok(InternalApiCallOutcome::Success(None))
                        } else {
                            Ok(InternalApiCallOutcome::Failure(format!(
                                "RC: {}, STDOUT: {}, STDERR: {}",
                                result.return_code, result.stdout, result.stderr
                            )))
                        }
                    }
                    Err(e) => Ok(InternalApiCallOutcome::Failure(format!(
                        "Command execution failed: {:?}",
                        e
                    ))),
                }
            }
            OsKind::Unknown => Err(RegentError::FailedDryRunEvaluation(
                "Cannot set hostname on unknown OS".to_string(),
            )),
        }
    }
}

// Checking RFC952 and RFC1123 compliance
fn is_valid_hostname(hostname: &str) -> Result<(), String> {
    if hostname.is_empty() {
        return Err("hostname is empty".to_string());
    }

    if hostname.len() > 253 {
        return Err("hostname too long (max 253 characters)".to_string());
    }

    if hostname.contains("--") {
        return Err("hostname forbidden to have --".to_string());
    }

    for element in hostname.split('.') {
        if element.is_empty() {
            return Err("one empty element between 2 points".to_string());
        } else if element.len() > 63 {
            return Err("element too long (max 63 characters)".to_string());
        }

        for (i, c) in element.chars().enumerate() {
            match c {
                'a'..='z' | '0'..='9' => (),
                '-' => {
                    if i == 0 {
                        return Err("element forbidden to start with -".to_string());
                    } else if i == element.len() - 1 {
                        return Err("element forbidden to end with -".to_string());
                    }
                }
                forbidden_character => {
                    return Err(format!("forbidden character : {forbidden_character}"));
                }
            }
        }
    }

    Ok(())
}

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

    #[test]
    fn parsing_hostname_module_block_from_yaml_str() {
        let raw_attributes = "---
- Name: myserver.example.com

- Name: webserver
  Method: !Systemd

- Name: oldbox
  Method: !Generic
        ";

        let _attributes: Vec<HostnameBlockExpectedState> =
            yaml_serde::from_str(raw_attributes).unwrap();
    }

    #[test]
    fn is_valid_hostname_rejects_empty_hostname() {
        assert!(is_valid_hostname("").is_err());
    }

    #[test]
    fn is_valid_hostname_rejects_hostname_longer_than_253_chars() {
        let long_hostname = "a".repeat(254);
        assert!(is_valid_hostname(&long_hostname).is_err());
    }

    #[test]
    fn is_valid_hostname_rejects_hostname_with_consecutive_dashes() {
        assert!(is_valid_hostname("my--server").is_err());
    }

    #[test]
    fn is_valid_hostname_rejects_hostname_with_leading_or_trailing_dashes() {
        assert!(is_valid_hostname("-myserver").is_err());
        assert!(is_valid_hostname("myserver-").is_err());
    }

    #[test]
    fn is_valid_hostname_rejects_hostname_with_invalid_chars() {
        assert!(is_valid_hostname("my!server").is_err());
        assert!(is_valid_hostname("my@server").is_err());
    }

    #[test]
    fn is_valid_hostname_accepts_valid_hostname() {
        assert!(is_valid_hostname("myserver").is_ok());
        assert!(is_valid_hostname("myserver.example.com").is_ok());
    }

    #[test]
    fn is_valid_hostname_rejects_hostname_with_labels_longer_than_63_chars() {
        let long_label = format!("element-1.{}.element-2", "a".repeat(64));
        assert!(is_valid_hostname(&format!("{}.example.com", long_label)).is_err());
    }
}