regent-sdk 0.8.2

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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
//! User account management attribute
//!
//! This module provides the `UserBlockExpectedState` type for managing user accounts
//! on Unix-like systems.
//!
//! # Examples
//!
//! ## Rust API
//!
//! ```no_run
//! use regent_sdk::state::attribute::system::user::{UserBlockExpectedState, UserExpectedState};
//! use regent_sdk::{Attribute, ExpectedState, Privilege};
//!
//! // Create a user with specific properties
//! let alice = UserBlockExpectedState::builder("alice")
//!     .with_state(UserExpectedState::Present)
//!     .with_uid(1001)
//!     .with_shell("/bin/bash")
//!     .with_home("/home/alice")
//!     .with_comment("Alice Smith")
//!     .build()
//!     .unwrap();
//!
//! let expected_state = ExpectedState::new()
//!     .with_attribute(Attribute::user(alice, Privilege::WithSudo, None))
//!     .build();
//! ```
//!
//! ## YAML API
//!
//! ```yaml
//! Attributes:
//!   - Detail: !User
//!       Name: alice
//!       State: !Present
//!       Uid: 1001
//!       Shell: /bin/bash
//!       Home: /home/alice
//!       Comment: Alice Smith
//!       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;
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 user account
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum UserExpectedState {
    /// User should exist
    Present,
    /// User should not exist
    Absent,
}

/// Configuration for a user account
///
/// Use the builder pattern to create and manage user accounts with various properties.
/// When state is Present, you can specify user properties like UID, shell, home directory, etc.
/// When state is Absent, the user will be removed (and optionally their home directory).
///
/// The `append` field controls whether supplementary groups are appended to existing groups
/// or replaced entirely.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "PascalCase")]
pub struct UserBlockExpectedState {
    /// Username
    name: String,
    /// Desired state of the user (defaults to Present if not specified)
    state: Option<UserExpectedState>,
    /// User ID
    uid: Option<u32>,
    /// Primary group name
    group: Option<String>,
    /// Supplementary groups the user should belong to
    groups: Option<Vec<String>>,
    /// Whether to append to existing supplementary groups instead of replacing them
    append: Option<bool>,
    /// Login shell
    shell: Option<String>,
    /// Home directory path
    home: Option<String>,
    /// GECOS comment field
    comment: Option<String>,
    /// Hashed password
    password: Option<String>,
    /// Whether this is a system user (no login shell, no home directory by default)
    system: Option<bool>,
    /// Whether to create home directory when creating user
    create_home: Option<bool>,
    /// Whether to remove home directory when deleting user
    remove_home: Option<bool>,
}

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

impl UserBlockExpectedState {
    pub fn builder(username: &str) -> UserBlockExpectedState {
        UserBlockExpectedState {
            name: username.to_string(),
            state: None,
            uid: None,
            group: None,
            groups: None,
            append: None,
            shell: None,
            home: None,
            comment: None,
            password: None,
            system: None,
            create_home: None,
            remove_home: None,
        }
    }

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

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

    pub fn with_group(&mut self, group: &str) -> &mut Self {
        self.group = Some(group.to_string());
        self
    }

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

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

    pub fn with_shell(&mut self, shell: &str) -> &mut Self {
        self.shell = Some(shell.to_string());
        self
    }

    pub fn with_home(&mut self, home: &str) -> &mut Self {
        self.home = Some(home.to_string());
        self
    }

    pub fn with_comment(&mut self, comment: &str) -> &mut Self {
        self.comment = Some(comment.to_string());
        self
    }

    pub fn with_password(&mut self, password: &str) -> &mut Self {
        self.password = Some(password.to_string());
        self
    }

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

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

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

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

impl Check for UserBlockExpectedState {
    fn check(&self) -> Result<(), RegentError> {
        if let Some(UserExpectedState::Absent) = &self.state {
            let has_incompatible = self.uid.is_some()
                || self.group.is_some()
                || self.groups.is_some()
                || self.append.is_some()
                || self.shell.is_some()
                || self.home.is_some()
                || self.comment.is_some()
                || self.password.is_some()
                || self.system.is_some()
                || self.create_home.is_some();
            if has_incompatible {
                return Err(RegentError::IncoherentExpectedState(
                    "User property specifications are incompatible with state Absent.".to_string(),
                ));
            }
        }
        Ok(())
    }
}

impl<Handler: HostHandler> AssessCompliance<Handler> for UserBlockExpectedState {
    async fn assess_compliance(
        &self,
        host_handler: &mut Handler,
        _host_properties: &Option<HostProperties>,
        privilege: &Privilege,
        _optional_secret_provider: &Option<SecretProvidersPool>,
    ) -> Result<AttributeComplianceAssessment, RegentError> {
        let expected_state = self.state.as_ref().unwrap_or(&UserExpectedState::Present);

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

        match expected_state {
            UserExpectedState::Absent => {
                if !user_exists {
                    return Ok(AttributeComplianceAssessment::Compliant);
                }
                return Ok(AttributeComplianceAssessment::NonCompliant(vec![
                    Remediation::User(UserApiCall::from(
                        UserModuleInternalApiCall::Delete {
                            username: self.name.clone(),
                            remove_home: self.remove_home.unwrap_or(false),
                        },
                        privilege.clone(),
                    )),
                ]));
            }
            UserExpectedState::Present => {
                if !user_exists {
                    return Ok(AttributeComplianceAssessment::NonCompliant(vec![
                        Remediation::User(UserApiCall::from(
                            UserModuleInternalApiCall::Add {
                                username: self.name.clone(),
                                uid: self.uid,
                                group: self.group.clone(),
                                groups: self.groups.clone(),
                                shell: self.shell.clone(),
                                home: self.home.clone(),
                                comment: self.comment.clone(),
                                password: self.password.clone(),
                                system: self.system.unwrap_or(false),
                                create_home: self.create_home.unwrap_or(true),
                            },
                            privilege.clone(),
                        )),
                    ]));
                }

                // User exists: determine which properties need updating
                let mut mod_uid: Option<u32> = None;
                let mut mod_group: Option<String> = None;
                let mut mod_groups: Option<Vec<String>> = None;
                let mut mod_shell: Option<String> = None;
                let mut mod_home: Option<String> = None;
                let mut mod_comment: Option<String> = None;
                // Password hash cannot be read without root access; always enforce if specified.
                let mod_password = self.password.clone();
                let append = self.append.unwrap_or(false);

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

                if let Some(expected_uid) = self.uid {
                    if passwd_entry.uid != expected_uid {
                        mod_uid = Some(expected_uid);
                    }
                }

                if let Some(ref expected_shell) = self.shell {
                    if &passwd_entry.shell != expected_shell {
                        mod_shell = Some(expected_shell.clone());
                    }
                }

                if let Some(ref expected_home) = self.home {
                    if &passwd_entry.home != expected_home {
                        mod_home = Some(expected_home.clone());
                    }
                }

                if let Some(ref expected_comment) = self.comment {
                    if &passwd_entry.comment != expected_comment {
                        mod_comment = Some(expected_comment.clone());
                    }
                }

                if let Some(ref expected_group) = self.group {
                    let current_group = match get_primary_group(host_handler, &self.name).await {
                        Ok(g) => g,
                        Err(e) => return Err(RegentError::FailedDryRunEvaluation(e)),
                    };
                    if &current_group != expected_group {
                        mod_group = Some(expected_group.clone());
                    }
                }

                if let Some(ref expected_groups) = self.groups {
                    let current_supp_groups =
                        match get_supplementary_groups(host_handler, &self.name).await {
                            Ok(g) => g,
                            Err(e) => return Err(RegentError::FailedDryRunEvaluation(e)),
                        };

                    let groups_compliant = if append {
                        // All expected groups must already be present
                        expected_groups
                            .iter()
                            .all(|g| current_supp_groups.contains(g))
                    } else {
                        // Exact match required
                        let mut expected_sorted = expected_groups.clone();
                        let mut current_sorted = current_supp_groups.clone();
                        expected_sorted.sort();
                        current_sorted.sort();
                        expected_sorted == current_sorted
                    };

                    if !groups_compliant {
                        mod_groups = Some(expected_groups.clone());
                    }
                }

                let needs_modification = mod_uid.is_some()
                    || mod_group.is_some()
                    || mod_groups.is_some()
                    || mod_shell.is_some()
                    || mod_home.is_some()
                    || mod_comment.is_some()
                    || mod_password.is_some();

                if needs_modification {
                    return Ok(AttributeComplianceAssessment::NonCompliant(vec![
                        Remediation::User(UserApiCall::from(
                            UserModuleInternalApiCall::Modify {
                                username: self.name.clone(),
                                uid: mod_uid,
                                group: mod_group,
                                groups: mod_groups,
                                append,
                                shell: mod_shell,
                                home: mod_home,
                                comment: mod_comment,
                                password: mod_password,
                            },
                            privilege.clone(),
                        )),
                    ]));
                }

                Ok(AttributeComplianceAssessment::Compliant)
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum UserModuleInternalApiCall {
    Add {
        username: String,
        uid: Option<u32>,
        group: Option<String>,
        groups: Option<Vec<String>>,
        shell: Option<String>,
        home: Option<String>,
        comment: Option<String>,
        password: Option<String>,
        system: bool,
        create_home: bool,
    },
    Modify {
        username: String,
        uid: Option<u32>,
        group: Option<String>,
        groups: Option<Vec<String>>,
        append: bool,
        shell: Option<String>,
        home: Option<String>,
        comment: Option<String>,
        password: Option<String>,
    },
    Delete {
        username: String,
        remove_home: bool,
    },
}

impl std::fmt::Display for UserModuleInternalApiCall {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UserModuleInternalApiCall::Add { username, .. } => {
                write!(f, "add user {}", username)
            }
            UserModuleInternalApiCall::Modify { username, .. } => {
                write!(f, "modify user {}", username)
            }
            UserModuleInternalApiCall::Delete { username, .. } => {
                write!(f, "delete user {}", username)
            }
        }
    }
}

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

impl UserApiCall {
    pub fn display(&self) -> String {
        match &self.api_call {
            UserModuleInternalApiCall::Add { username, .. } => format!("Add user {}", username),
            UserModuleInternalApiCall::Modify { username, .. } => {
                format!("Modify user {}", username)
            }
            UserModuleInternalApiCall::Delete { username, .. } => {
                format!("Delete user {}", username)
            }
        }
    }

    fn from(api_call: UserModuleInternalApiCall, privilege: Privilege) -> UserApiCall {
        UserApiCall {
            api_call,
            privilege,
        }
    }
}

impl<Handler: HostHandler> ReachCompliance<Handler> for UserApiCall {
    async fn call(
        &self,
        host_handler: &mut Handler,
        _host_properties: &Option<HostProperties>,
        _optional_secret_provider: &Option<SecretProvidersPool>,
    ) -> Result<InternalApiCallOutcome, RegentError> {
        let (cmd, privilege) = match &self.api_call {
            UserModuleInternalApiCall::Add {
                username,
                uid,
                group,
                groups,
                shell,
                home,
                comment,
                password,
                system,
                create_home,
            } => {
                let mut args: Vec<String> = Vec::new();
                if let Some(u) = uid {
                    args.push(format!("-u {}", u));
                }
                if let Some(g) = group {
                    args.push(format!("-g {}", g));
                }
                if let Some(gs) = groups {
                    if !gs.is_empty() {
                        args.push(format!("-G {}", gs.join(",")));
                    }
                }
                if let Some(s) = shell {
                    args.push(format!("-s {}", s));
                }
                if let Some(h) = home {
                    args.push(format!("-d {}", h));
                }
                if let Some(c) = comment {
                    args.push(format!("-c '{}'", c));
                }
                if let Some(p) = password {
                    args.push(format!("-p '{}'", p));
                }
                if *system {
                    args.push("-r".to_string());
                }
                if *create_home {
                    args.push("-m".to_string());
                } else {
                    args.push("-M".to_string());
                }
                (
                    format!("useradd {} {}", args.join(" "), username),
                    &self.privilege,
                )
            }
            UserModuleInternalApiCall::Modify {
                username,
                uid,
                group,
                groups,
                append,
                shell,
                home,
                comment,
                password,
            } => {
                let mut args: Vec<String> = Vec::new();
                if let Some(u) = uid {
                    args.push(format!("-u {}", u));
                }
                if let Some(g) = group {
                    args.push(format!("-g {}", g));
                }
                if let Some(gs) = groups {
                    // Quote the value to handle empty list (removes all supplementary groups)
                    args.push(format!("-G \"{}\"", gs.join(",")));
                    if *append && !gs.is_empty() {
                        args.push("-a".to_string());
                    }
                }
                if let Some(s) = shell {
                    args.push(format!("-s {}", s));
                }
                if let Some(h) = home {
                    args.push(format!("-d {}", h));
                }
                if let Some(c) = comment {
                    args.push(format!("-c '{}'", c));
                }
                if let Some(p) = password {
                    args.push(format!("-p '{}'", p));
                }
                (
                    format!("usermod {} {}", args.join(" "), username),
                    &self.privilege,
                )
            }
            UserModuleInternalApiCall::Delete {
                username,
                remove_home,
            } => {
                let flags = if *remove_home { "-r " } else { "" };
                (format!("userdel {}{}", flags, username), &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
            )))
        }
    }
}

struct PasswdEntry {
    uid: u32,
    comment: String,
    home: String,
    shell: String,
}

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

async fn get_passwd_entry<Handler: HostHandler>(
    host_handler: &mut Handler,
    username: &str,
) -> Result<PasswdEntry, String> {
    match host_handler
        .run_command(&format!("getent passwd {}", username), &Privilege::None)
        .await
    {
        Ok(result) => {
            if result.return_code != 0 {
                return Err(format!("getent passwd failed for user {}", username));
            }
            // Format: username:x:uid:gid:comment:home:shell
            let fields: Vec<&str> = result.stdout.trim().splitn(7, ':').collect();
            if fields.len() < 7 {
                return Err(format!(
                    "Unexpected getent passwd output for {}: {}",
                    username, result.stdout
                ));
            }
            let uid = fields[2]
                .parse::<u32>()
                .map_err(|e| format!("Invalid UID '{}': {}", fields[2], e))?;
            Ok(PasswdEntry {
                uid,
                comment: fields[4].to_string(),
                home: fields[5].to_string(),
                shell: fields[6].to_string(),
            })
        }
        Err(e) => Err(format!(
            "Unable to get passwd entry for {}: {:?}",
            username, e
        )),
    }
}

async fn get_primary_group<Handler: HostHandler>(
    host_handler: &mut Handler,
    username: &str,
) -> Result<String, String> {
    match host_handler
        .run_command(&format!("id -gn {}", username), &Privilege::None)
        .await
    {
        Ok(result) => {
            if result.return_code != 0 {
                return Err(format!("id -gn failed for user {}", username));
            }
            Ok(result.stdout.trim().to_string())
        }
        Err(e) => Err(format!(
            "Unable to get primary group for {}: {:?}",
            username, e
        )),
    }
}

async fn get_supplementary_groups<Handler: HostHandler>(
    host_handler: &mut Handler,
    username: &str,
) -> Result<Vec<String>, String> {
    let primary_group = get_primary_group(host_handler, username).await?;

    match host_handler
        .run_command(&format!("id -Gn {}", username), &Privilege::None)
        .await
    {
        Ok(result) => {
            if result.return_code != 0 {
                return Err(format!("id -Gn failed for user {}", username));
            }
            // id -Gn returns all groups (primary + supplementary); subtract primary
            Ok(result
                .stdout
                .trim()
                .split_whitespace()
                .map(|s| s.to_string())
                .filter(|g| g != &primary_group)
                .collect())
        }
        Err(e) => Err(format!(
            "Unable to get supplementary groups for {}: {:?}",
            username, e
        )),
    }
}

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

    #[test]
    fn parsing_user_module_block_from_yaml_str() {
        let raw_attributes = "---
- Name: alice
  State: !Present
  Shell: /bin/bash
  Comment: Alice Smith
  Groups:
    - sudo
    - docker

- Name: bob
  State: !Absent
        ";

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

    #[test]
    fn check_rejects_absent_with_properties() {
        let result = UserBlockExpectedState::builder("testuser")
            .with_state(UserExpectedState::Absent)
            .with_shell("/bin/bash")
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn check_accepts_absent_without_properties() {
        let result = UserBlockExpectedState::builder("testuser")
            .with_state(UserExpectedState::Absent)
            .build();
        assert!(result.is_ok());
    }

    #[test]
    fn check_accepts_present_with_properties() {
        let result = UserBlockExpectedState::builder("testuser")
            .with_state(UserExpectedState::Present)
            .with_uid(1001)
            .with_shell("/bin/bash")
            .with_comment("Test User")
            .build();
        assert!(result.is_ok());
    }
}