Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/shadow-core/src/login_defs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,24 @@ impl LoginDefs {
pub fn get_i64(&self, key: &str) -> Option<i64> {
self.entries.get(key).and_then(|v| v.parse().ok())
}

/// Insert or replace a configuration value for later `get` / `get_i64` calls.
///
/// Used when a tool accepts runtime overrides of login.defs defaults
/// (for example `useradd -K KEY=VALUE`).
pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
self.entries.insert(key.into(), value.into());
}

/// Apply several `KEY=VALUE` overrides; later entries win on duplicate keys.
pub fn apply_overrides<'a, I>(&mut self, overrides: I)
where
I: IntoIterator<Item = (&'a str, &'a str)>,
{
for (key, value) in overrides {
self.set(key, value);
}
}
}

#[cfg(test)]
Expand Down Expand Up @@ -138,6 +156,32 @@ mod tests {
assert_eq!(defs.get_i64("ENCRYPT_METHOD"), None);
}

#[test]
fn test_set_overrides_existing_and_inserts_new() {
let dir = tempfile::tempdir().unwrap();
let path = write_login_defs(dir.path(), "UID_MIN 1000\n");
let mut defs = LoginDefs::load(&path).unwrap();
assert_eq!(defs.get_i64("UID_MIN"), Some(1000));

defs.set("UID_MIN", "9100");
defs.set("PASS_MAX_DAYS", "-1");
assert_eq!(defs.get_i64("UID_MIN"), Some(9100));
assert_eq!(defs.get("PASS_MAX_DAYS"), Some("-1"));
}

#[test]
fn test_apply_overrides() {
let mut defs = LoginDefs::load(Path::new("/nonexistent")).unwrap();
defs.apply_overrides([
("UID_MIN", "2000"),
("UID_MAX", "2000"),
("UID_MIN", "3000"),
]);
// Later duplicate wins.
assert_eq!(defs.get("UID_MIN"), Some("3000"));
assert_eq!(defs.get("UID_MAX"), Some("2000"));
}

// -------------------------------------------------------------------
// Issue #16: parser edge case tests
// -------------------------------------------------------------------
Expand Down
Loading