regent-sdk 0.16.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
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! APT repository management attribute
//!
//! This module provides the `AptRepoExpectedState` type for managing APT repository
//! sources in `/etc/apt/sources.list.d/`. Supports both legacy `.list` format and modern
//! `.sources` (deb822) format.
//!
//! **Compatible OS:** Linux (Debian-based distributions: Debian, Ubuntu, etc.)
//!
//! # Examples
//!
//! ## Rust API
//!
//! ```no_run
//! use regent_sdk::state::attribute::package::apt_repo::AptRepoExpectedState;
//! use regent_sdk::{Attribute, ExpectedState, Privilege};
//!
//! // Add a repository using legacy format, then update the APT cache
//! let repo = AptRepoExpectedState::present_legacy(
//!     "docker",
//!     "deb [arch=amd64] https://download.docker.com/linux/ubuntu jammy stable",
//!     true,
//! );
//!
//! // Add a repository using deb822 format (binary packages only)
//! let repo_deb822 = AptRepoExpectedState::present_deb822(
//!     "docker",
//!     vec!["https://download.docker.com/linux/ubuntu".to_string()],
//!     vec!["jammy".to_string()],
//!     Some(vec!["stable".to_string()]),
//!     Some("/etc/apt/keyrings/docker.asc".to_string()),
//!     None,
//!     Some(vec!["amd64".to_string()]),
//!     true,
//! );
//!
//! // Remove a repository
//! let repo_absent = AptRepoExpectedState::absent("docker", true);
//!
//! let expected_state = ExpectedState::new()
//!     .with_attribute(Attribute::apt_repo(repo, Privilege::WithSudo, None))
//!     .build();
//! ```
//!
//! ## YAML API
//!
//! ```yaml
//! Attributes:
//!   - Name: Docker repository must be present
//!     Privilege: !WithSudo
//!     Detail: !AptRepo
//!       Filename: docker
//!       State: Present
//!       Format:
//!         Repo: "deb [arch=amd64] https://download.docker.com/linux/ubuntu jammy stable"
//!       UpdateCache: true
//! ```

use crate::error::RegentError;
use crate::hosts::managed_host::InternalApiCallOutcome;
use crate::hosts::managed_host::{AssessCompliance, ReachCompliance, Timeout};
use crate::hosts::properties::{HostProperties, 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::attribute::package::RepoExpectedStatus;
use crate::state::compliance::AttributeComplianceAssessment;
use serde::{Deserialize, Serialize};
use std::time::Duration;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum AptRepoType {
    Deb,
    DebSrc,
}

impl AptRepoType {
    fn as_str(&self) -> &str {
        match self {
            AptRepoType::Deb => "deb",
            AptRepoType::DebSrc => "deb-src",
        }
    }
}

/// Configuration for an APT repository
///
/// Manages an APT repository source file in `/etc/apt/sources.list.d/`.
/// Supports two formats:
///
/// **Legacy** (.list): set `repo` to the full one-liner string
///   `repo: "deb https://... focal main"`
///
/// **Deb822** (.sources): set `types`, `uris`, `suites` (and optionally `components`,
///   `signed_by`, `architectures`, `enabled`)
///
/// `filename` (without extension) is required in both cases.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "PascalCase")]
pub struct AptRepoExpectedState {
    /// Filename (without extension) for the repository file in /etc/apt/sources.list.d/
    filename: String,
    state: RepoExpectedStatus,
    /// Whether to run apt-get update after adding/removing repositories
    #[serde(default)]
    cache_up_to_date: bool,
    #[serde(default)]
    format: Option<AptRepoFormat>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
#[serde(untagged)]
pub enum AptRepoFormat {
    #[serde(rename_all = "PascalCase")]
    Legacy {
        /// Legacy one-liner format → writes to a `.list` file
        repo: String,
    },
    #[serde(rename_all = "PascalCase")]
    Deb822 {
        /// Repository types for deb822 format → writes to a `.sources` file
        types: Vec<AptRepoType>,
        uris: Vec<String>,
        suites: Vec<String>,
        components: Option<Vec<String>>,
        signed_by: Option<String>,
        enabled: Option<bool>,
        architectures: Option<Vec<String>>,
    },
}

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

impl AptRepoExpectedState {
    pub fn legacy_format(
        filename: &str,
        repo: &str,
        state: RepoExpectedStatus,
        cache_up_to_date: bool,
    ) -> AptRepoExpectedState {
        AptRepoExpectedState {
            filename: filename.to_string(),
            state,
            cache_up_to_date,
            format: Some(AptRepoFormat::Legacy {
                repo: repo.to_string(),
            }),
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub fn deb822_format(
        filename: &str,
        state: RepoExpectedStatus,
        types: Vec<AptRepoType>,
        uris: Vec<String>,
        suites: Vec<String>,
        components: Option<Vec<String>>,
        signed_by: Option<String>,
        enabled: Option<bool>,
        architectures: Option<Vec<String>>,
        cache_up_to_date: bool,
    ) -> AptRepoExpectedState {
        AptRepoExpectedState {
            filename: filename.to_string(),
            state,
            cache_up_to_date,
            format: Some(AptRepoFormat::Deb822 {
                types,
                uris,
                suites,
                components,
                signed_by,
                enabled,
                architectures,
            }),
        }
    }

    /// Repository must be present, written in legacy one-liner format (`.list`)
    pub fn present_legacy(
        filename: &str,
        repo: &str,
        cache_up_to_date: bool,
    ) -> AptRepoExpectedState {
        AptRepoExpectedState::legacy_format(
            filename,
            repo,
            RepoExpectedStatus::Present,
            cache_up_to_date,
        )
    }

    /// Repository must be present, written in deb822 format (`.sources`), for binary
    /// packages only (`Types: deb`)
    #[allow(clippy::too_many_arguments)]
    pub fn present_deb822(
        filename: &str,
        uris: Vec<String>,
        suites: Vec<String>,
        components: Option<Vec<String>>,
        signed_by: Option<String>,
        enabled: Option<bool>,
        architectures: Option<Vec<String>>,
        cache_up_to_date: bool,
    ) -> AptRepoExpectedState {
        AptRepoExpectedState::deb822_format(
            filename,
            RepoExpectedStatus::Present,
            vec![AptRepoType::Deb],
            uris,
            suites,
            components,
            signed_by,
            enabled,
            architectures,
            cache_up_to_date,
        )
    }

    /// Repository must be present, written in deb822 format (`.sources`), for binary and
    /// source packages (`Types: deb deb-src`)
    #[allow(clippy::too_many_arguments)]
    pub fn present_deb822_with_source_packages(
        filename: &str,
        uris: Vec<String>,
        suites: Vec<String>,
        components: Option<Vec<String>>,
        signed_by: Option<String>,
        enabled: Option<bool>,
        architectures: Option<Vec<String>>,
        cache_up_to_date: bool,
    ) -> AptRepoExpectedState {
        AptRepoExpectedState::deb822_format(
            filename,
            RepoExpectedStatus::Present,
            vec![AptRepoType::Deb, AptRepoType::DebSrc],
            uris,
            suites,
            components,
            signed_by,
            enabled,
            architectures,
            cache_up_to_date,
        )
    }

    /// Repository file must be removed (no format to describe)
    pub fn absent(filename: &str, cache_up_to_date: bool) -> AptRepoExpectedState {
        AptRepoExpectedState {
            filename: filename.to_string(),
            state: RepoExpectedStatus::Absent,
            cache_up_to_date,
            format: None,
        }
    }
}

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

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

impl<Handler: HostHandler> AssessCompliance<Handler> for AptRepoExpectedState {
    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 mut remediations: Vec<Remediation> = Vec::new();

        let current_content = match read_file(host_handler, &self.filename).await {
            Ok(c) => c,
            Err(e) => return Err(RegentError::FailedDryRunEvaluation(e)),
        };

        match self.state {
            RepoExpectedStatus::Absent => {
                if current_content.is_some() {
                    remediations.push(Remediation::AptRepo(AptRepoApiCall::from(
                        AptRepoModuleInternalApiCall::RemoveFile {
                            path: self.filename.clone(),
                        },
                        privilege.clone(),
                    )));
                }
            }
            RepoExpectedStatus::Present => {
                let format = self
                    .format
                    .as_ref()
                    .expect("Format must be provided for Present state");
                let expected_content = match format {
                    AptRepoFormat::Legacy { repo } => build_legacy_content(repo),
                    AptRepoFormat::Deb822 {
                        types: _,
                        uris: _,
                        suites: _,
                        components: _,
                        signed_by: _,
                        enabled: _,
                        architectures: _,
                    } => build_deb822_content(format),
                };

                if current_content.is_some() {
                    if let Some(current) = current_content
                        && current.trim() != expected_content.trim()
                    {
                        remediations.push(Remediation::AptRepo(AptRepoApiCall::from(
                            AptRepoModuleInternalApiCall::WriteFile {
                                path: self.filename.clone(),
                                content: expected_content,
                            },
                            privilege.clone(),
                        )));
                    }
                } else {
                    remediations.push(Remediation::AptRepo(AptRepoApiCall::from(
                        AptRepoModuleInternalApiCall::WriteFile {
                            path: self.filename.clone(),
                            content: expected_content,
                        },
                        privilege.clone(),
                    )));
                }
            }
        }

        if self.cache_up_to_date {
            remediations.push(Remediation::AptRepo(AptRepoApiCall::from(
                AptRepoModuleInternalApiCall::UpdateCache,
                privilege.clone(),
            )));
        }

        if remediations.is_empty() {
            Ok(AttributeComplianceAssessment::Compliant)
        } else {
            Ok(AttributeComplianceAssessment::NonCompliant(
                RemediationsList::from(remediations)?,
            ))
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum AptRepoModuleInternalApiCall {
    WriteFile { path: String, content: String },
    RemoveFile { path: String },
    UpdateCache,
}

impl std::fmt::Display for AptRepoModuleInternalApiCall {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AptRepoModuleInternalApiCall::WriteFile { path, .. } => {
                write!(f, "write apt repo file {}", path)
            }
            AptRepoModuleInternalApiCall::RemoveFile { path } => {
                write!(f, "remove apt repo file {}", path)
            }
            AptRepoModuleInternalApiCall::UpdateCache => write!(f, "apt-get update"),
        }
    }
}

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

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

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

impl AptRepoApiCall {
    pub fn display(&self) -> String {
        match &self.api_call {
            AptRepoModuleInternalApiCall::WriteFile { path, .. } => {
                format!("Write apt repo file {}", path)
            }
            AptRepoModuleInternalApiCall::RemoveFile { path } => {
                format!("Remove apt repo file {}", path)
            }
            AptRepoModuleInternalApiCall::UpdateCache => "Run apt-get update".to_string(),
        }
    }

    fn from(api_call: AptRepoModuleInternalApiCall, privilege: Privilege) -> AptRepoApiCall {
        AptRepoApiCall {
            api_call,
            privilege,
        }
    }
}

impl<Handler: HostHandler> ReachCompliance<Handler> for AptRepoApiCall {
    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 (cmd, privilege) = match &self.api_call {
            AptRepoModuleInternalApiCall::WriteFile { path, content } => (
                format!("printf '{}' > {}", escape_for_printf(content), path),
                &self.privilege,
            ),
            AptRepoModuleInternalApiCall::RemoveFile { path } => {
                (format!("rm -f {}", path), &self.privilege)
            }
            AptRepoModuleInternalApiCall::UpdateCache => {
                ("apt-get update".to_string(), &self.privilege)
            }
        };

        let cmd_result = host_handler
            .run_command(cmd.as_str(), privilege)
            .await
            .unwrap();

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

// Not wired into the assessment yet
#[allow(dead_code)]
fn apt_repo_file_path(filename: &str, is_legacy: bool) -> String {
    let ext = if is_legacy { "list" } else { "sources" };
    format!("/etc/apt/sources.list.d/{}.{}", filename, ext)
}

fn build_legacy_content(repo_line: &str) -> String {
    format!("{}\n", repo_line.trim())
}

fn build_deb822_content(format: &AptRepoFormat) -> String {
    let mut lines: Vec<String> = Vec::new();

    match format {
        AptRepoFormat::Legacy { .. } => {
            // This shouldn't be called for Legacy format
            unreachable!();
        }
        AptRepoFormat::Deb822 {
            types,
            uris,
            suites,
            components,
            signed_by,
            enabled,
            architectures,
        } => {
            if let Some(false) = enabled {
                lines.push("Enabled: no".to_string());
            }
            if !types.is_empty() {
                let s: Vec<&str> = types.iter().map(|t| t.as_str()).collect();
                lines.push(format!("Types: {}", s.join(" ")));
            }
            if !uris.is_empty() {
                lines.push(format!("URIs: {}", uris.join(" ")));
            }
            if !suites.is_empty() {
                lines.push(format!("Suites: {}", suites.join(" ")));
            }
            if let Some(components) = components
                && !components.is_empty()
            {
                lines.push(format!("Components: {}", components.join(" ")));
            }
            if let Some(archs) = architectures
                && !archs.is_empty()
            {
                lines.push(format!("Architectures: {}", archs.join(" ")));
            }
            if let Some(signed_by) = signed_by {
                lines.push(format!("Signed-By: {}", signed_by));
            }
        }
    }

    lines.join("\n") + "\n"
}

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

// Not wired into the assessment yet
#[allow(dead_code)]
/// Ensures that repository URLs are explicitly checked during assessment.
fn extract_uris_from_deb822(content: &str) -> Option<Vec<String>> {
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("URIs:") || trimmed.starts_with("URI:") {
            let uris_part = trimmed.split(':').nth(1).map(|s| s.trim());
            if let Some(uris_str) = uris_part {
                let uris: Vec<String> =
                    uris_str.split_whitespace().map(|s| s.to_string()).collect();
                return Some(uris);
            }
        }
    }
    None
}

async fn read_file<Handler: HostHandler>(
    host_handler: &mut Handler,
    path: &str,
) -> Result<Option<String>, String> {
    match host_handler
        .run_command(&format!("cat {}", path), &Privilege::None)
        .await
    {
        Ok(result) => {
            if result.return_code == 0 {
                Ok(Some(result.stdout))
            } else {
                Ok(None) // File does not exist
            }
        }
        Err(e) => Err(format!("Failed to read {}: {:?}", path, e)),
    }
}

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

    #[test]
    fn parsing_apt_repo_legacy_from_yaml() {
        let raw = "---
- Filename: docker
  State: Present
  Format:
    Repo: 'deb https://download.docker.com/linux/ubuntu focal stable'

- Filename: docker
  State: Absent
        ";
        let _attrs: Vec<AptRepoExpectedState> = yaml_serde::from_str(raw).unwrap();
    }

    #[test]
    fn parsing_apt_repo_deb822_from_yaml() {
        let raw = "---
- Filename: docker
  State: Present
  Format:
    Types:
      - Deb
    Uris:
      - https://download.docker.com/linux/ubuntu
    Suites:
      - focal
    Components:
      - stable
    SignedBy: /usr/share/keyrings/docker-archive-keyring.gpg
        ";
        let _attrs: Vec<AptRepoExpectedState> = yaml_serde::from_str(raw).unwrap();
    }

    #[test]
    fn build_legacy_content_trims_and_adds_newline() {
        let content = build_legacy_content("  deb http://example.com focal main  ");
        assert_eq!(content, "deb http://example.com focal main\n");
    }

    #[test]
    fn escape_for_printf_handles_special_chars() {
        let escaped = escape_for_printf("a\nb%c\\d");
        assert_eq!(escaped, "a\\nb%%c\\\\d");
    }

    #[test]
    fn present_and_absent_shortcuts_match_explicit_states() {
        assert_eq!(
            AptRepoExpectedState::present_legacy(
                "docker",
                "deb https://example.com focal main",
                true
            ),
            AptRepoExpectedState::legacy_format(
                "docker",
                "deb https://example.com focal main",
                RepoExpectedStatus::Present,
                true
            )
        );

        let uris = vec!["https://download.docker.com/linux/ubuntu".to_string()];
        let suites = vec!["focal".to_string()];
        let components = Some(vec!["stable".to_string()]);
        let signed_by = Some("/usr/share/keyrings/docker.gpg".to_string());
        let architectures = Some(vec!["amd64".to_string()]);
        let explicit = |types: Vec<AptRepoType>| {
            AptRepoExpectedState::deb822_format(
                "docker",
                RepoExpectedStatus::Present,
                types,
                uris.clone(),
                suites.clone(),
                components.clone(),
                signed_by.clone(),
                Some(false),
                architectures.clone(),
                false,
            )
        };
        assert_eq!(
            AptRepoExpectedState::present_deb822(
                "docker",
                uris.clone(),
                suites.clone(),
                components.clone(),
                signed_by.clone(),
                Some(false),
                architectures.clone(),
                false,
            ),
            explicit(vec![AptRepoType::Deb])
        );
        assert_eq!(
            AptRepoExpectedState::present_deb822_with_source_packages(
                "docker",
                uris.clone(),
                suites.clone(),
                components.clone(),
                signed_by.clone(),
                Some(false),
                architectures.clone(),
                false,
            ),
            explicit(vec![AptRepoType::Deb, AptRepoType::DebSrc])
        );

        // Same as `State: Absent` in YAML: no format
        let parsed: AptRepoExpectedState =
            yaml_serde::from_str("Filename: docker\nState: Absent\nCacheUpToDate: true\n").unwrap();
        assert_eq!(AptRepoExpectedState::absent("docker", true), parsed);
    }
}