regent-sdk 0.15.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
//! Template file management attribute
//!
//! This module provides the `TemplateExpectedState` type for rendering a
//! [Tera](https://docs.rs/tera/latest/tera/) template and writing the result to a
//! destination file on the managed host. The template source can be a file path
//! (`TemplateOrigin::File`) or an inline string (`TemplateOrigin::InLine`), and
//! can be combined with an optional context map of variables.
//!
//! **Compatible OS:** Linux
//!
//! # Examples
//!
//! ## Rust API
//!
//! ```no_run
//! use std::path::PathBuf;
//! use std::collections::HashMap;
//! use regent_sdk::state::attribute::utilities::template::TemplateExpectedState;
//! use regent_sdk::{Attribute, ExpectedState, Privilege};
//!
//! // Render a template file to /etc/nginx/nginx.conf
//! let nginx = TemplateExpectedState::from_file(
//!     PathBuf::from("/etc/regent/templates/nginx.conf.j2"),
//!     PathBuf::from("/etc/nginx/nginx.conf"),
//! );
//!
//! // Render an inline template with a context map
//! let mut context = HashMap::from(vec![("port".to_string(), "8080".to_string()]);
//!
//! let server_block = TemplateExpectedState::from_inline_with_additional_context(
//!     "server { listen {{ port }}; }".to_string(),
//!     PathBuf::from("/etc/nginx/conf.d/default.conf"),
//!     context,
//! );
//!
//! let expected_state = ExpectedState::new()
//!     .with_attribute(Attribute::template(nginx, Privilege::WithSudo, None))
//!     .with_attribute(Attribute::template(server_block, Privilege::WithSudo, None))
//!     .build();
//! ```
//!
//! ## YAML API
//!
//! ```yaml
//! Attributes:
//!   - Name: Render nginx config from template file
//!     Privilege: !WithSudo
//!     Detail: !Template
//!       Template: !File /etc/regent/templates/nginx.conf.template
//!       Destination: /etc/nginx/nginx.conf
//!       Context:
//!         server_name: example.com
//!         port: 8080
//! ```
//!
//! For an inline template:
//!
//! ```yaml
//! Attributes:
//!   - Name: Render server block inline
//!     Privilege: !WithSudo
//!     Detail: !Template
//!       Template: !InLine |
//!         [Server]
//!         host = {{ host }}
//!         port = {{ port }}
//!         timeout = {{ 2 * 50 }}
//!       Destination: /etc/myapp/config.toml
//!       Context:
//!         host: srv.mydomain.com
//!         port: 443
//! ```

use crate::error::RegentError;
use crate::hosts::managed_host::InternalApiCallOutcome;
use crate::hosts::managed_host::{AssessCompliance, ReachCompliance, Timeout};
use crate::hosts::properties::{HostProperties, 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;
use std::{collections::HashMap, path::PathBuf};

#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum TemplateOrigin {
    File(PathBuf),
    InLine(String),
}

/// Manual `Serialize` implementation, required to escape the in-line tera template
/// when rendering tera at Attribute level (normal process, not specific to this Template attribute).
/// If not escaped, the Inline content will get prematurely rendered with wrong tera context
/// when attribute level "consider_context" method is called.
impl Serialize for TemplateOrigin {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            TemplateOrigin::File(path) => {
                serializer.serialize_newtype_variant("TemplateOrigin", 0, "File", path)
            }
            TemplateOrigin::InLine(content) => {
                let wrapped = format!("{{% raw %}}{}{{% endraw %}}", content);
                serializer.serialize_newtype_variant("TemplateOrigin", 1, "InLine", &wrapped)
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "PascalCase")]
pub struct TemplateExpectedState {
    pub template: TemplateOrigin,
    pub destination: PathBuf,
    pub context: Option<HashMap<String, String>>,
}

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

impl TemplateExpectedState {
    pub fn from_file(file: PathBuf, destination: PathBuf) -> TemplateExpectedState {
        TemplateExpectedState {
            template: TemplateOrigin::File(file),
            destination,
            context: None,
        }
    }

    pub fn from_file_with_additional_context(
        file: PathBuf,
        destination: PathBuf,
        context: HashMap<String, String>,
    ) -> TemplateExpectedState {
        TemplateExpectedState {
            template: TemplateOrigin::File(file),
            destination,
            context: Some(context),
        }
    }

    pub fn from_inline(inline: String, destination: PathBuf) -> TemplateExpectedState {
        TemplateExpectedState {
            template: TemplateOrigin::InLine(inline),
            destination,
            context: None,
        }
    }

    pub fn from_inline_with_additional_context(
        inline: String,
        destination: PathBuf,
        context: HashMap<String, String>,
    ) -> TemplateExpectedState {
        TemplateExpectedState {
            template: TemplateOrigin::InLine(inline),
            destination,
            context: Some(context),
        }
    }
}

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

    fn check_host_compatibility(
        &self,
        host_properties: &HostProperties,
    ) -> Result<(), RegentError> {
        match host_properties.os_kind() {
            OsKind::Linux(_) => Ok(()),
            incompatible_os_kind => Err(RegentError::IncompatibleHost(format!(
                "Host is {:?} but APT is only supported on Linux distributions",
                incompatible_os_kind
            ))),
        }
    }
}

impl<Handler: HostHandler> AssessCompliance<Handler> for TemplateExpectedState {
    async fn assess_compliance(
        &self,
        host_handler: &mut Handler,
        host_properties: &Option<HostProperties>,
        privilege: &Privilege,
        _optional_secret_provider: &Option<SecretProvidersPool>,
    ) -> Result<AttributeComplianceAssessment, RegentError> {
        if let Some(props) = host_properties {
            self.check_host_compatibility(props)?;
        }

        let expected_content = render_template_content(&self.template, &self.context)?;

        let destination = self.destination.to_string_lossy();

        // Check whether the destination file already exists on the host.
        let file_exists = host_handler
            .run_command(&format!("test -f {}", destination), &privilege)
            .await
            .map_err(|details| {
                RegentError::FailedDryRunEvaluation(format!(
                    "Unable to check existence of destination file {}: {:?}",
                    destination, details
                ))
            })?
            .return_code
            == 0;

        if !file_exists {
            return Ok(AttributeComplianceAssessment::NonCompliant(
                RemediationsList::from(vec![Remediation::Template(TemplateApiCall {
                    template: self.template.clone(),
                    destination: self.destination.clone(),
                    destination_action: DestinationFileAction::CreateFile,
                    context: self.context.clone(),
                    privilege: privilege.clone(),
                })])?,
            ));
        }

        let current_content = host_handler
            .run_command(&format!("cat {}", destination), &privilege)
            .await
            .map_err(|details| {
                RegentError::FailedDryRunEvaluation(format!(
                    "Unable to read destination file {}: {:?}",
                    destination, details
                ))
            })?
            .stdout;

        if current_content.trim_end_matches('\n') == expected_content.trim_end_matches('\n') {
            Ok(AttributeComplianceAssessment::Compliant)
        } else {
            // Content differs: remediation is a full content replacement.
            Ok(AttributeComplianceAssessment::NonCompliant(
                RemediationsList::from(vec![Remediation::Template(TemplateApiCall {
                    template: self.template.clone(),
                    destination: self.destination.clone(),
                    destination_action: DestinationFileAction::WrongContent,
                    context: self.context.clone(),
                    privilege: privilege.clone(),
                })])?,
            ))
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
enum DestinationFileAction {
    WrongContent,
    CreateFile,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TemplateApiCall {
    template: TemplateOrigin,
    destination: PathBuf,
    destination_action: DestinationFileAction,
    context: Option<HashMap<String, String>>,
    privilege: Privilege,
}

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

    fn check_host_compatibility(
        &self,
        host_properties: &HostProperties,
    ) -> Result<(), RegentError> {
        match host_properties.os_kind() {
            OsKind::Linux(_) => Ok(()),
            incompatible_os_kind => Err(RegentError::IncompatibleHost(format!(
                "Host is {:?} but APT is only supported on Linux distributions",
                incompatible_os_kind
            ))),
        }
    }
}

impl TemplateApiCall {
    pub fn display(&self) -> String {
        match &self.destination_action {
            DestinationFileAction::WrongContent => format!("Destination file content is wrong"),
            DestinationFileAction::CreateFile => format!("Destination file does not exist"),
        }
    }
}

impl<Handler: HostHandler> ReachCompliance<Handler> for TemplateApiCall {
    async fn call(
        &self,
        host_handler: &mut Handler,
        host_properties: &Option<HostProperties>,
        _optional_secret_provider: &Option<SecretProvidersPool>,
    ) -> Result<InternalApiCallOutcome, RegentError> {
        if let Some(props) = host_properties {
            self.check_host_compatibility(props)?;
        }

        let expected_content = render_template_content(&self.template, &self.context)?;

        let destination = self.destination.to_string_lossy();

        // Overwrite the destination file if it exists, or create it otherwise.
        // "printf ... > file" handles both cases: it truncates an existing file
        // and creates a new one when the file is absent. DestinationFileAction is
        // only used at assessment step to distinguish reasons for non-compliance.
        // Remediation is the same anyway.
        let cmd = format!(
            "printf '{}' > {}",
            escape_for_printf(&expected_content),
            destination
        );

        let cmd_result = host_handler
            .run_command(cmd.as_str(), &self.privilege)
            .await
            .map_err(|details| {
                RegentError::FailureToRunCommand(format!(
                    "Unable to write rendered template to {}: {:?}",
                    destination, details
                ))
            })?;

        if cmd_result.return_code != 0 {
            return Ok(InternalApiCallOutcome::Failure(format!(
                "RC: {}, STDOUT: {}, STDERR: {}",
                cmd_result.return_code, cmd_result.stdout, cmd_result.stderr
            )));
        }

        let verification = host_handler
            .run_command(&format!("cat {}", destination), &self.privilege)
            .await
            .map_err(|details| {
                RegentError::FailedDryRunEvaluation(format!(
                    "Unable to read destination file {} for verification: {:?}",
                    destination, details
                ))
            })?
            .stdout;

        if verification.trim_end_matches('\n') == expected_content.trim_end_matches('\n') {
            Ok(InternalApiCallOutcome::Success(None))
        } else {
            Ok(InternalApiCallOutcome::Failure(format!(
                "Command succeeded but post-verification failed (expected : {:?}, real : {:?}",
                expected_content, verification
            )))
        }
    }
}

fn render_template_content(
    template: &TemplateOrigin,
    context: &Option<HashMap<String, String>>,
) -> Result<String, RegentError> {
    let template_str = match template {
        TemplateOrigin::File(path) => std::fs::read_to_string(path).map_err(|details| {
            RegentError::FailedDryRunEvaluation(format!(
                "Unable to read template file {:?}: {}",
                path, details
            ))
        })?,
        TemplateOrigin::InLine(content) => content.clone(),
    };

    let tera_context = match context {
        Some(variables) => tera::Context::from_serialize(variables).map_err(|details| {
            RegentError::FailureToConsiderContext(format!(
                "Failed to build template context: {}",
                details
            ))
        })?,
        None => tera::Context::new(),
    };

    tera::Tera::one_off(&template_str, &tera_context, true).map_err(|details| {
        RegentError::FailureToConsiderContext(format!("Failed to render template: {}", details))
    })
}

fn escape_for_printf(content: &str) -> String {
    content
        .replace('\\', "\\\\")
        .replace('%', "%%")
        .replace('\n', "\\n")
        .replace('\'', "'\\''")
}