pub(crate) const LOGIN_SHELL: &str = "if command -v bash >/dev/null 2>&1; then exec bash -l; else exec sh -l; fi";
pub(crate) const CONTAINER_SHELL: &str = "if command -v bash >/dev/null 2>&1; then exec bash; else exec sh; fi";
pub(crate) fn login_shell_as(user: &str) -> String {
format!("if [ $(id -un) = {user} ]; then {LOGIN_SHELL}; else exec sudo -iu {user}; fi")
}
pub(crate) fn container_shell_as() -> String {
format!("cd 2>/dev/null; {LOGIN_SHELL}")
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn the_scripts_as_an_account_are_sh() {
for script in [login_shell_as("user"), container_shell_as()] {
let parsed = std::process::Command::new("sh").args(["-n", "-c", &script]).status();
assert!(parsed.is_ok_and(|s| s.success()), "{script}");
}
}
#[cfg(unix)]
#[test]
fn from_another_account_the_login_is_sudo_as_the_account() {
use std::os::unix::fs::PermissionsExt;
let bin = tempfile::tempdir().unwrap();
for (tool, says) in [("id", "echo vagrant"), ("sudo", "echo \"sudo $*\"")] {
let path = bin.path().join(tool);
std::fs::write(&path, format!("#!/bin/sh\n{says}\n")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let path = format!("{}:{}", bin.path().display(), std::env::var("PATH").unwrap_or_default());
let out = std::process::Command::new("sh")
.args(["-c", &login_shell_as("user")])
.env("PATH", path)
.output()
.unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout), "sudo -iu user\n");
}
#[test]
fn a_login_as_an_account_is_a_sudo_login_unless_it_is_the_sessions() {
let script = login_shell_as("user");
assert_eq!(
script,
"if [ $(id -un) = user ]; then if command -v bash >/dev/null 2>&1; then exec bash -l; else exec sh -l; fi; else exec sudo -iu user; fi"
);
}
}