regent-sdk 0.8.3

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
//! Group management attribute
//!
//! This module provides the `GroupBlockExpectedState` type for managing Unix system groups
//! using the groupadd, groupmod, and groupdel commands (or lgroupadd, lgroupdel for local groups).
//!
//! **Compatible OS:** Linux (all distributions)
//!
//! # Examples
//!
//! ## Rust API
//!
//! ```no_run
//! use regent_sdk::state::attribute::system::group::{GroupBlockExpectedState, GroupExpectedState};
//! use regent_sdk::{Attribute, ExpectedState, Privilege};
//!
//! // Create a group with a specific GID
//! let developers = GroupBlockExpectedState::builder("developers")
//!     .with_state(GroupExpectedState::Present)
//!     .with_gid(1500)
//!     .build()
//!     .unwrap();
//!
//! let expected_state = ExpectedState::new()
//!     .with_attribute(Attribute::group(developers, Privilege::WithSudo, None))
//!     .build();
//! ```
//!
//! ## YAML API
//!
//! ```yaml
//! Attributes:
//!   - Detail: !Group
//!       Name: developers
//!       State: !Present
//!       Gid: 1500
//!       Privilege: !WithSudo
//! ```

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::compliance::AttributeComplianceAssessment;
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Desired state of a group
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum GroupExpectedState {
    /// Group should exist
    Present,
    /// Group should not exist
    Absent,
}

/// Configuration for a system group
///
/// Use the builder pattern to create group configurations. Each group must have a name.
/// You can specify the desired state (Present/Absent), GID, and whether it's a system or local group.
///
/// When state is Absent, gid and system fields are not allowed.
/// When state is Present (or None, which defaults to Present), you can optionally specify:
/// - gid: The numeric group ID
/// - system: Whether to create a system group (uses -r flag)
/// - local: Whether to use local commands (lgroupadd/lgroupdel instead of groupadd/groupdel)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "PascalCase")]
pub struct GroupBlockExpectedState {
    /// Unique name of the group
    name: String,
    /// Desired state of the group (defaults to Present if not specified)
    state: Option<GroupExpectedState>,
    /// Group ID to assign (optional)
    gid: Option<u32>,
    /// List of users that should be members of this group
    members: Option<Vec<String>>,
    /// Whether this is a system group (uses -r flag with groupadd)
    system: Option<bool>,
    /// Whether to use local commands (lgroupadd/lgroupdel) instead of system commands
    local: Option<bool>,
}

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

impl GroupBlockExpectedState {
    pub fn builder(groupname: &str) -> GroupBlockExpectedState {
        GroupBlockExpectedState {
            name: groupname.to_string(),
            state: None,
            gid: None,
            members: None,
            system: None,
            local: None,
        }
    }

    pub fn with_state(&mut self, state: GroupExpectedState) -> &mut Self {
        self.state = Some(state);
        self
    }

    pub fn with_gid(&mut self, gid: u32) -> &mut Self {
        self.gid = Some(gid);
        self
    }

    pub fn with_members(&mut self, members: Vec<String>) -> &mut Self {
        self.members = Some(members);
        self
    }

    pub fn with_system(&mut self, system: bool) -> &mut Self {
        self.system = Some(system);
        self
    }

    pub fn with_local(&mut self, local: bool) -> &mut Self {
        self.local = Some(local);
        self
    }

    pub fn build(&self) -> Result<GroupBlockExpectedState, RegentError> {
        self.check()?;
        Ok(self.clone())
    }
}

impl Check for GroupBlockExpectedState {
    fn check(&self) -> Result<(), RegentError> {
        if let Some(GroupExpectedState::Absent) = &self.state {
            if self.gid.is_some() || self.system.is_some() {
                return Err(RegentError::IncoherentExpectedState(
                    "Gid and System are incompatible with state Absent.".to_string(),
                ));
            }
        }
        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 group management is only supported on Linux",
                incompatible_os_kind
            ))),
        }
    }
}

impl<Handler: HostHandler> AssessCompliance<Handler> for GroupBlockExpectedState {
    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 (Linux)
        if let Some(props) = host_properties {
            self.check_host_compatibility(props)?;
        }
        let expected_state = self.state.as_ref().unwrap_or(&GroupExpectedState::Present);
        let local = self.local.unwrap_or(false);

        let group_exists = match group_exists(host_handler, &self.name).await {
            Ok(exists) => exists,
            Err(e) => return Err(RegentError::FailedDryRunEvaluation(e)),
        };

        match expected_state {
            GroupExpectedState::Absent => {
                if !group_exists {
                    return Ok(AttributeComplianceAssessment::Compliant);
                }
                return Ok(AttributeComplianceAssessment::NonCompliant(vec![
                    Remediation::Group(GroupApiCall::from(
                        GroupModuleInternalApiCall::Delete {
                            groupname: self.name.clone(),
                            local,
                        },
                        privilege.clone(),
                    )),
                ]));
            }
            GroupExpectedState::Present => {
                if !group_exists {
                    return Ok(AttributeComplianceAssessment::NonCompliant(vec![
                        Remediation::Group(GroupApiCall::from(
                            GroupModuleInternalApiCall::Add {
                                groupname: self.name.clone(),
                                gid: self.gid,
                                members: self.members.clone(),
                                system: self.system.unwrap_or(false),
                                local,
                            },
                            privilege.clone(),
                        )),
                    ]));
                }

                // Group exists: check GID if specified
                if let Some(expected_gid) = self.gid {
                    let current_gid = match get_group_gid(host_handler, &self.name).await {
                        Ok(gid) => gid,
                        Err(e) => return Err(RegentError::FailedDryRunEvaluation(e)),
                    };
                    if current_gid != expected_gid {
                        return Ok(AttributeComplianceAssessment::NonCompliant(vec![
                            Remediation::Group(GroupApiCall::from(
                                GroupModuleInternalApiCall::ModifyGid {
                                    groupname: self.name.clone(),
                                    gid: expected_gid,
                                },
                                privilege.clone(),
                            )),
                        ]));
                    }
                }

                // Group exists: check members if specified
                if let Some(expected_members) = &self.members {
                    let current_members = match get_group_members(host_handler, &self.name).await {
                        Ok(members) => members,
                        Err(e) => return Err(RegentError::FailedDryRunEvaluation(e)),
                    };

                    // Sort both lists for comparison (order doesn't matter for group members)
                    let mut expected_sorted = expected_members.clone();
                    let mut current_sorted = current_members.clone();
                    expected_sorted.sort();
                    current_sorted.sort();

                    if expected_sorted != current_sorted {
                        return Ok(AttributeComplianceAssessment::NonCompliant(vec![
                            Remediation::Group(GroupApiCall::from(
                                GroupModuleInternalApiCall::ModifyMembers {
                                    groupname: self.name.clone(),
                                    members: expected_members.clone(),
                                },
                                privilege.clone(),
                            )),
                        ]));
                    }
                }

                Ok(AttributeComplianceAssessment::Compliant)
            }
        }
    }
}

/// Internal API calls for group management
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum GroupModuleInternalApiCall {
    /// Create a new group
    Add {
        groupname: String,
        gid: Option<u32>,
        members: Option<Vec<String>>,
        system: bool,
        /// Uses lgroupadd instead of groupadd (shadow-utils local command)
        local: bool,
    },
    /// Modify an existing group's GID
    ModifyGid { groupname: String, gid: u32 },
    /// Modify an existing group's members
    ModifyMembers {
        groupname: String,
        members: Vec<String>,
    },
    /// Remove a group
    Delete { groupname: String, local: bool },
}

impl std::fmt::Display for GroupModuleInternalApiCall {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GroupModuleInternalApiCall::Add { groupname, .. } => {
                write!(f, "add group {}", groupname)
            }
            GroupModuleInternalApiCall::ModifyGid { groupname, gid } => {
                write!(f, "modify group {} gid to {}", groupname, gid)
            }
            GroupModuleInternalApiCall::ModifyMembers { groupname, members } => {
                write!(f, "modify group {} members to {:?}", groupname, members)
            }
            GroupModuleInternalApiCall::Delete { groupname, .. } => {
                write!(f, "delete group {}", groupname)
            }
        }
    }
}

/// A group API call with its associated privilege level
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GroupApiCall {
    /// The internal API call to execute
    pub api_call: GroupModuleInternalApiCall,
    /// Privilege level required for this call
    privilege: Privilege,
}

impl GroupApiCall {
    pub fn display(&self) -> String {
        match &self.api_call {
            GroupModuleInternalApiCall::Add { groupname, .. } => {
                format!("Add group {}", groupname)
            }
            GroupModuleInternalApiCall::ModifyGid { groupname, gid } => {
                format!("Modify group {} GID to {}", groupname, gid)
            }
            GroupModuleInternalApiCall::ModifyMembers { groupname, members } => {
                format!("Modify group {} members to {:?}", groupname, members)
            }
            GroupModuleInternalApiCall::Delete { groupname, .. } => {
                format!("Delete group {}", groupname)
            }
        }
    }

    fn from(api_call: GroupModuleInternalApiCall, privilege: Privilege) -> GroupApiCall {
        GroupApiCall {
            api_call,
            privilege,
        }
    }
}

impl Check for GroupApiCall {
    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 group management is only supported on Linux",
                incompatible_os_kind
            ))),
        }
    }
}

impl<Handler: HostHandler> ReachCompliance<Handler> for GroupApiCall {
    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 (Linux)
        if let Some(props) = host_properties {
            self.check_host_compatibility(props)?;
        }

        let (cmd, privilege) = match &self.api_call {
            GroupModuleInternalApiCall::Add {
                groupname,
                gid,
                members,
                system,
                local,
            } => {
                let base = if *local { "lgroupadd" } else { "groupadd" };
                let mut args: Vec<String> = Vec::new();
                if let Some(g) = gid {
                    args.push(format!("-g {}", g));
                }
                if *system {
                    args.push("-r".to_string());
                }

                let mut cmds = Vec::new();
                // Create the group
                cmds.push(format!("{} {} {}", base, args.join(" "), groupname));

                // Add members if specified
                if let Some(member_list) = members {
                    for member in member_list {
                        cmds.push(format!("usermod -aG {} {}", groupname, member));
                    }
                }

                (cmds.join(" && "), &self.privilege)
            }
            GroupModuleInternalApiCall::ModifyGid { groupname, gid } => (
                format!("groupmod -g {} {}", gid, groupname),
                &self.privilege,
            ),
            GroupModuleInternalApiCall::ModifyMembers { groupname, members } => {
                // Get current members to calculate differences
                let current_members = match get_group_members(host_handler, groupname).await {
                    Ok(m) => m,
                    Err(e) => {
                        return Ok(InternalApiCallOutcome::Failure(format!(
                            "Failed to get current group members: {}",
                            e
                        )));
                    }
                };

                // Convert to sets for easier difference calculation
                use std::collections::HashSet;
                let expected_set: HashSet<&str> = members.iter().map(|s| s.as_str()).collect();
                let current_set: HashSet<&str> =
                    current_members.iter().map(|s| s.as_str()).collect();

                // Calculate users to add and remove
                let users_to_add: Vec<&str> =
                    expected_set.difference(&current_set).cloned().collect();
                let users_to_remove: Vec<&str> =
                    current_set.difference(&expected_set).cloned().collect();

                let mut cmds = Vec::new();

                // Add users who should be in the group but aren't
                for user in users_to_add {
                    cmds.push(format!("usermod -aG {} {}", groupname, user));
                }

                // Remove users who shouldn't be in the group
                // Note: Removing users from a group requires gpasswd or similar
                // For now, we'll use gpasswd --delete to remove users
                for user in users_to_remove {
                    cmds.push(format!("gpasswd --delete {} {}", user, groupname));
                }

                if cmds.is_empty() {
                    // No changes needed
                    return Ok(InternalApiCallOutcome::Success(None));
                }

                (cmds.join(" && "), &self.privilege)
            }
            GroupModuleInternalApiCall::Delete { groupname, local } => {
                let base = if *local { "lgroupdel" } else { "groupdel" };
                (format!("{} {}", base, groupname), &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
            )))
        }
    }
}

async fn group_exists<Handler: HostHandler>(
    host_handler: &mut Handler,
    groupname: &str,
) -> Result<bool, String> {
    match host_handler
        .run_command(&format!("getent group {}", groupname), &Privilege::None)
        .await
    {
        Ok(result) => Ok(result.return_code == 0),
        Err(e) => Err(format!("Unable to check if group exists: {:?}", e)),
    }
}

async fn get_group_gid<Handler: HostHandler>(
    host_handler: &mut Handler,
    groupname: &str,
) -> Result<u32, String> {
    match host_handler
        .run_command(&format!("getent group {}", groupname), &Privilege::None)
        .await
    {
        Ok(result) => {
            if result.return_code != 0 {
                return Err(format!("getent group failed for group {}", groupname));
            }
            // Format: groupname:x:gid:members
            let fields: Vec<&str> = result.stdout.trim().splitn(4, ':').collect();
            if fields.len() < 3 {
                return Err(format!(
                    "Unexpected getent group output for {}: {}",
                    groupname, result.stdout
                ));
            }
            fields[2]
                .parse::<u32>()
                .map_err(|e| format!("Invalid GID '{}': {}", fields[2], e))
        }
        Err(e) => Err(format!(
            "Unable to get GID for group {}: {:?}",
            groupname, e
        )),
    }
}

async fn get_group_members<Handler: HostHandler>(
    host_handler: &mut Handler,
    groupname: &str,
) -> Result<Vec<String>, String> {
    match host_handler
        .run_command(&format!("getent group {}", groupname), &Privilege::None)
        .await
    {
        Ok(result) => {
            if result.return_code != 0 {
                return Err(format!("getent group failed for group {}", groupname));
            }
            // Format: groupname:x:gid:members
            let fields: Vec<&str> = result.stdout.trim().splitn(4, ':').collect();
            if fields.len() < 4 {
                // No members field, return empty vector
                return Ok(Vec::new());
            }
            // Split members by comma and filter out empty strings
            Ok(fields[3]
                .split(',')
                .filter(|s| !s.trim().is_empty())
                .map(|s| s.trim().to_string())
                .collect())
        }
        Err(e) => Err(format!(
            "Unable to get members for group {}: {:?}",
            groupname, e
        )),
    }
}

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

    #[test]
    fn parsing_group_module_block_from_yaml_str() {
        let raw_attributes = "---
- Name: developers
  State: !Present
  Gid: 1500

- Name: oldgroup
  State: !Absent
        ";

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

    #[test]
    fn check_rejects_absent_with_gid() {
        let result = GroupBlockExpectedState::builder("testgroup")
            .with_state(GroupExpectedState::Absent)
            .with_gid(1500)
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn check_rejects_absent_with_system() {
        let result = GroupBlockExpectedState::builder("testgroup")
            .with_state(GroupExpectedState::Absent)
            .with_system(true)
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn check_accepts_absent_with_local() {
        let result = GroupBlockExpectedState::builder("testgroup")
            .with_state(GroupExpectedState::Absent)
            .with_local(true)
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn check_accepts_present_with_all_properties() {
        let result = GroupBlockExpectedState::builder("testgroup")
            .with_state(GroupExpectedState::Present)
            .with_gid(1500)
            .with_system(false)
            .with_local(false)
            .build();
        assert!(result.is_ok());
    }
}