cindy 0.2.1

Managing infrastructure at breakneck speed.
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
//! Manage a Unix user account on the remote machine via
//! `useradd`/`usermod`/`userdel`.
//!
//! Current state is read back through `nix` (`/etc/passwd` via NSS) plus
//! a group-membership scan for supplementary groups, so the module is
//! idempotent: it only invokes the `user*` tools when the live account
//! diverges from the desired [`State`].
//!
//! Passwords are handled as **pre-hashed** crypt(3) strings only
//! ([`Presence::Present::password`]); this module never accepts or
//! transmits a cleartext password. Pair it with [`crate::Secret`] to
//! keep the hash out of plaintext inventory.

use std::process::Command;

use crate as cindy;
use crate::Context;

/// Desired supplementary-group membership.
///
/// `None` on the `groups` field means "don't touch membership at all".
/// When set, this picks the reconciliation strategy:
#[derive(Clone, PartialEq, Eq)]
#[crate::wire]
pub enum Groups {
    /// Membership is made to match this set **exactly**: groups not
    /// listed are removed (`usermod --groups a,b,c`). Use when you own
    /// the user's full supplementary membership.
    Exact(Vec<String>),
    /// Ensure the user is in **at least** these groups, leaving any
    /// other existing memberships intact (`usermod --append --groups
    /// a,b,c`). Use when several plays each manage one group and must
    /// not stomp each other.
    Append(Vec<String>),
}

/// Whether the account should exist, and its desired attributes.
#[derive(Clone, PartialEq, Eq)]
#[crate::wire]
pub enum Presence {
    /// `userdel`: ensure the account does not exist. Idempotent over
    /// the already-absent case. See [`State::remove_home`] for whether
    /// the home directory is deleted too.
    Absent,
    /// `useradd` / `usermod`: ensure the account exists with these
    /// attributes. Every field is "don't care" when `None`/empty:
    /// on create the system default is used; on an existing account the
    /// attribute is left untouched.
    Present {
        /// Numeric UID. `None` ⇒ system-allocated on create, untouched
        /// otherwise.
        uid: Option<u32>,
        /// Primary group name. `None` ⇒ distro default (usually a
        /// per-user group) on create, untouched otherwise.
        group: Option<String>,
        /// Supplementary group membership. `None` ⇒ leave membership
        /// alone. See [`Groups`] for the `Exact` (replace) vs `Append`
        /// (add without removing) strategies.
        groups: Option<Groups>,
        /// Login shell, e.g. `/bin/bash`. `None` ⇒ default / untouched.
        shell: Option<std::path::PathBuf>,
        /// Home directory path. `None` ⇒ default / untouched. Changing
        /// it on an existing user moves the directory (`usermod -m`).
        home: Option<std::path::PathBuf>,
        /// GECOS / comment field (full name etc.). `None` ⇒ untouched.
        comment: Option<String>,
        /// Pre-hashed crypt(3) password (the `usermod -p` / `useradd -p`
        /// value). `None` ⇒ untouched. NEVER a cleartext password.
        password: Option<String>,
        /// Create as a system account (UID from the system range, no
        /// per-user group skeleton by default). Only consulted when the
        /// account is **created** — an account's system-ness is fixed by
        /// its UID at creation and isn't migratable without delete +
        /// recreate (which would orphan its files), so this module never
        /// changes it on an existing account. It *observes* system-ness
        /// from the live UID (against the host's `SYS_UID_MAX`) for an
        /// honest diff, but reports a mismatch rather than "fixing" it.
        system: bool,
    },
}

impl Default for Presence {
    fn default() -> Self {
        Self::Present {
            uid: None,
            group: None,
            groups: None,
            shell: None,
            home: None,
            comment: None,
            password: None,
            system: false,
        }
    }
}

#[derive(Clone, Default, PartialEq, Eq)]
#[crate::wire]
pub struct State {
    /// Login name.
    pub name: String,
    /// Desired presence and attributes.
    pub presence: Presence,
    /// When removing the account (`Presence::Absent`), also delete the
    /// home directory and mail spool (`userdel --remove`). Ignored when
    /// the account is present.
    pub remove_home: bool,
}

/// Default `{:#?}`-based struct diff. The password hash is deliberately
/// kept out of the diff view (it's unobservable on the "old" side and
/// rendered as untouched on the "new" side); keep it in a
/// [`crate::Secret`] if it matters for your logs regardless.
impl crate::Diff for State {}

/// Read the supplementary groups (by name) that `name` is a member of,
/// excluding the user's primary group.
fn supplementary_groups(name: &str, primary_gid: nix::unistd::Gid) -> crate::Result<Vec<String>> {
    // `getgrouplist(3)` resolves the full set of groups for `name`
    // through NSS, so it's correct for LDAP/SSSD-backed hosts as well
    // as local `/etc/group` (unlike a flat-file scan). It returns the
    // primary group too, so we filter it out to leave only the
    // supplementary set — the thing `usermod --groups` manages.
    let cname = std::ffi::CString::new(name).context("User name contains an interior NUL byte")?;
    let gids = nix::unistd::getgrouplist(&cname, primary_gid)
        .context("getgrouplist failed for the user")?;

    let mut out = Vec::new();
    for gid in gids {
        if gid == primary_gid {
            continue;
        }
        // Map each GID back to a name; fall back to the numeric GID so
        // a group without an NSS entry still shows up rather than being
        // silently dropped.
        let name = nix::unistd::Group::from_gid(gid)
            .ok()
            .flatten()
            .map(|g| g.name)
            .unwrap_or_else(|| gid.as_raw().to_string());
        out.push(name);
    }
    out.sort();
    out.dedup();
    Ok(out)
}

/// The highest UID considered a "system" account on this host, read
/// from `SYS_UID_MAX` in `/etc/login.defs` (the value `useradd --system`
/// honours). Falls back to 999 when the file is absent or unparseable.
fn sys_uid_max() -> u32 {
    const DEFAULT_SYS_UID_MAX: u32 = 999;
    let Ok(contents) = std::fs::read_to_string("/etc/login.defs") else {
        return DEFAULT_SYS_UID_MAX;
    };
    contents
        .lines()
        .find_map(|line| {
            let rest = line.trim().strip_prefix("SYS_UID_MAX")?;
            rest.trim().parse::<u32>().ok()
        })
        .unwrap_or(DEFAULT_SYS_UID_MAX)
}

/// What we observed about the account, normalized into a `Presence`.
fn observe(name: &str) -> crate::Result<Presence> {
    let Some(user) = nix::unistd::User::from_name(name).context("User lookup failed")? else {
        return Ok(Presence::Absent);
    };

    // Map the primary GID back to a group name for a readable diff;
    // fall back to the numeric GID string if the group has no entry.
    let group = nix::unistd::Group::from_gid(user.gid)
        .ok()
        .flatten()
        .map(|g| g.name)
        .unwrap_or_else(|| user.gid.as_raw().to_string());

    let groups = supplementary_groups(name, user.gid)?;
    let comment = user.gecos.to_string_lossy().into_owned();

    Ok(Presence::Present {
        uid: Some(user.uid.as_raw()),
        group: Some(group),
        // We observe the user's full supplementary set, so the live
        // membership is naturally an `Exact` view for diffing.
        groups: Some(Groups::Exact(groups)),
        shell: Some(user.shell),
        home: Some(user.dir),
        comment: if comment.is_empty() {
            None
        } else {
            Some(comment)
        },
        // The stored hash is in `/etc/shadow`, not reachable via this
        // NSS lookup; treat it as unobservable so we never diff or
        // "reconcile" a password we can't see. A requested password is
        // therefore always (re)applied below.
        password: None,
        // Inferred from the live UID against the host's `SYS_UID_MAX`,
        // for an honest diff. Like `group`, we never migrate an existing
        // account between system and non-system (the UID range is fixed
        // at creation); a mismatch is reported, not "fixed".
        system: user.uid.as_raw() <= sys_uid_max(),
    })
}

/// Reconcile the desired `Present` attributes against the observed
/// ones, returning the `usermod` flags needed to close the gap.
///
/// This is the single source of truth for "what changed on an existing
/// account": every field is compared exactly once. The returned
/// argument vector drives the `usermod` call, and the [`reconciled`]
/// `Presence` (desired values back-filled with observed ones) is what
/// the struct diff is rendered against — so the diff and the command
/// can never disagree.
///
/// [`reconciled`]: ReconcileResult::desired
struct ReconcileResult {
    args: Vec<std::ffi::OsString>,
    desired: Presence,
}

/// Compare one `Option` attribute, pushing its `usermod` flag(s) when it
/// differs and yielding the value the account will end up with (desired
/// if set, else the observed fallback) for the diff view.
fn reconcile_field<T: Clone + PartialEq>(
    args: &mut Vec<std::ffi::OsString>,
    flag: &str,
    want: &Option<T>,
    have: &Option<T>,
    arg_value: impl Fn(&T) -> std::ffi::OsString,
) -> Option<T> {
    if let Some(w) = want
        && want != have
    {
        args.push(flag.into());
        args.push(arg_value(w));
    }
    want.clone().or_else(|| have.clone())
}

fn reconcile(want: &Presence, have: &Presence) -> ReconcileResult {
    let (
        Presence::Present {
            uid,
            group,
            groups,
            shell,
            home,
            comment,
            password,
            system,
        },
        Presence::Present {
            uid: o_uid,
            group: o_group,
            groups: o_groups,
            shell: o_shell,
            home: o_home,
            comment: o_comment,
            ..
        },
    ) = (want, have)
    else {
        // Only ever called with two `Present` values.
        unreachable!("reconcile expects two Present presences");
    };

    let mut args = Vec::new();

    let uid = reconcile_field(&mut args, "--uid", uid, o_uid, |u| u.to_string().into());
    let group = reconcile_field(&mut args, "--gid", group, o_group, |g| g.clone().into());
    let shell = reconcile_field(&mut args, "--shell", shell, o_shell, |s| s.clone().into());
    let comment = reconcile_field(&mut args, "--comment", comment, o_comment, |c| {
        c.clone().into()
    });

    // Home moves take two flags (`--home` + `--move-home`), so it can't
    // go through the scalar helper.
    let home = if let Some(h) = home {
        if Some(h) != o_home.as_ref() {
            args.push("--home".into());
            args.push(h.into());
            args.push("--move-home".into());
        }
        Some(h.clone())
    } else {
        o_home.clone()
    };

    // The observed side is always an `Exact` snapshot of the current
    // supplementary set (see `observe`).
    let observed_groups: &[String] = match o_groups {
        Some(Groups::Exact(g)) => g,
        // `Append` never appears on the observed side, and `None` means
        // we didn't look — treat both as "no known membership".
        Some(Groups::Append(_)) | None => &[],
    };
    let sorted = |gs: &[String]| {
        let mut v = gs.to_vec();
        v.sort();
        v.dedup();
        v
    };
    let groups = match groups {
        // Replace: make membership exactly this set.
        Some(Groups::Exact(want)) => {
            if sorted(want) != sorted(observed_groups) {
                args.push("--groups".into());
                args.push(want.join(",").into());
            }
            Some(Groups::Exact(want.clone()))
        }
        // Append: add only the groups not already present, leaving the
        // rest of the membership untouched (`usermod --append`).
        Some(Groups::Append(want)) => {
            let observed: std::collections::BTreeSet<&str> =
                observed_groups.iter().map(String::as_str).collect();
            let missing: Vec<String> = want
                .iter()
                .filter(|g| !observed.contains(g.as_str()))
                .cloned()
                .collect();
            if !missing.is_empty() {
                args.push("--append".into());
                args.push("--groups".into());
                args.push(missing.join(",").into());
            }
            // Diff view: the resulting membership is the union.
            let mut union = observed_groups.to_vec();
            union.extend(want.iter().cloned());
            Some(Groups::Exact(sorted(&union)))
        }
        None => o_groups.clone(),
    };

    // The password is applied separately via `chpasswd` over stdin (see
    // `set_password`) so the crypt hash never lands on a process's argv,
    // where `ps` could read it. It's also unobservable, so it's left out of
    // the diff view.
    let _ = password;

    ReconcileResult {
        args,
        desired: Presence::Present {
            uid,
            group,
            groups,
            shell,
            home,
            comment,
            // Keep the observed (`None`) password so the diff doesn't
            // surface an unobservable secret as a change.
            password: None,
            system: *system,
        },
    }
}

/// Append the `useradd` flags for every set attribute (used only when
/// creating an account from scratch — there's nothing to compare against).
fn useradd_args(want: &Presence) -> Vec<std::ffi::OsString> {
    let Presence::Present {
        uid,
        group,
        groups,
        shell,
        home,
        comment,
        password,
        system,
    } = want
    else {
        return Vec::new();
    };

    let mut args: Vec<std::ffi::OsString> = Vec::new();
    if *system {
        args.push("--system".into());
    }
    if let Some(uid) = uid {
        args.push("--uid".into());
        args.push(uid.to_string().into());
    }
    if let Some(group) = group {
        args.push("--gid".into());
        args.push(group.into());
    }
    if let Some(shell) = shell {
        args.push("--shell".into());
        args.push(shell.into());
    }
    if let Some(home) = home {
        args.push("--home-dir".into());
        args.push(home.into());
    }
    if let Some(comment) = comment {
        args.push("--comment".into());
        args.push(comment.into());
    }
    // Password is applied via `chpasswd` (see `set_password`), not argv.
    let _ = password;
    // On create there's no prior membership, so `Exact` and `Append`
    // are equivalent — both just seed the initial supplementary set.
    let initial_groups: &[String] = match groups {
        Some(Groups::Exact(g)) | Some(Groups::Append(g)) => g,
        None => &[],
    };
    if !initial_groups.is_empty() {
        args.push("--groups".into());
        args.push(initial_groups.join(",").into());
    }
    args
}

/// Render a `State` struct diff to stderr (informational; write errors
/// ignored), matching the other builtins.
fn show_diff(name: &str, old: Presence, new: Presence, remove_home: bool) {
    let old_view = State {
        name: name.to_owned(),
        presence: old,
        remove_home,
    };
    let new_view = State {
        name: name.to_owned(),
        presence: new,
        remove_home,
    };
    if old_view != new_view {
        let _ = <State as crate::Diff>::diff(&old_view, &new_view, &mut std::io::stderr().lock());
    }
}

/// Set a user's password from a pre-hashed crypt(3) string by feeding
/// `chpasswd -e` over **stdin**, so the hash never appears on any process's
/// argv (where `ps` could capture it for offline cracking).
fn set_password(name: &str, hash: &str) -> crate::Result<()> {
    use std::io::Write as _;
    use std::process::Stdio;

    let mut child = Command::new("chpasswd")
        .arg("-e")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .context("Failed to spawn chpasswd")?;

    // `name:hash\n`, the format `chpasswd` expects. The hash flows over the
    // pipe, never argv.
    child
        .stdin
        .take()
        .expect("chpasswd stdin was piped")
        .write_all(format!("{name}:{hash}\n").as_bytes())
        .context("Failed to write to chpasswd stdin")?;

    let out = child.wait_with_output().context("chpasswd failed")?;
    if !out.status.success() {
        crate::bail!(
            "chpasswd failed with {:?}:\n{}",
            out.status,
            String::from_utf8_lossy(&out.stderr),
        );
    }
    Ok(())
}

/// Manage a single Unix user account on the remote machine.
#[crate::remote]
pub fn user(state: State) -> crate::Result<super::Return> {
    let observed = observe(&state.name)?;

    let changed = match (&state.presence, &observed) {
        // Absent, and already gone.
        (Presence::Absent, Presence::Absent) => false,

        // Remove an existing account.
        (Presence::Absent, Presence::Present { .. }) => {
            show_diff(
                &state.name,
                observed.clone(),
                Presence::Absent,
                state.remove_home,
            );
            let mut cmd = Command::new("userdel");
            if state.remove_home {
                cmd.arg("--remove");
            }
            super::run_check(cmd.args(["--", &state.name]))?;
            true
        }

        // Create a new account: every requested attribute applies.
        (want @ Presence::Present { .. }, Presence::Absent) => {
            show_diff(
                &state.name,
                Presence::Absent,
                want.clone(),
                state.remove_home,
            );
            let mut cmd = Command::new("useradd");
            cmd.args(useradd_args(want)).args(["--", &state.name]);
            super::run_check(&mut cmd)?;
            if let Presence::Present {
                password: Some(hash),
                ..
            } = want
            {
                set_password(&state.name, hash)?;
            }
            true
        }

        // Reconcile an existing account: a single comparison pass builds
        // both the struct diff and the `usermod` argv.
        (want @ Presence::Present { .. }, have @ Presence::Present { .. }) => {
            let ReconcileResult { args, desired } = reconcile(want, have);
            show_diff(&state.name, observed.clone(), desired, state.remove_home);

            let mut changed = false;
            if !args.is_empty() {
                let mut cmd = Command::new("usermod");
                cmd.args(&args).args(["--", &state.name]);
                super::run_check(&mut cmd)?;
                changed = true;
            }
            // The stored hash is unobservable, so a requested password is
            // always (re)applied — over stdin, never on argv.
            if let Presence::Present {
                password: Some(hash),
                ..
            } = want
            {
                set_password(&state.name, hash)?;
                changed = true;
            }
            changed
        }
    };

    Ok(super::Return::from_changed(changed))
}