shep-daemon 0.22.0

The supervision engine behind shep: process spawning, restart policy, the log plane, watch and cron restarts, and the RPC server
Documentation
//! Privilege drop: resolving an app's requested `user`/`group` to numeric ids.
//!
//! `resolve` is the only entry point: given an [`AppConfig`], it returns the
//! [`Credentials`] a spawn should apply, or `None` when the app asked for
//! neither. It touches the OS passwd/group database, so [`crate::supervisor`]
//! resolves once per `Start` and stores the result on `ProcessEntry` rather
//! than re-touching it on every restart.
//!
//! [`Credentials`]/`PrivilegeError` stay plain data so they can live inside
//! the portable `SpawnSpec`/`ProcessEntry`.

use core::fmt;

use serde::{Deserialize, Serialize};
use shep_core::config::AppConfig;

/// Resolved unix credentials for a spawned sheep
// `uid`/`gid` are plain `pub` fields: already a zero-cost field access.
// `Serialize`/`Deserialize` support the handover blob, which carries
// resolved identity across an `execve` so a restart need not re-touch the
// passwd database.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Credentials {
    /// Numeric user id to run the child as
    pub uid: u32,
    /// Numeric group id to run the child as, when a `group` was requested
    pub gid: Option<u32>,
}

/// What identity an entry's next spawn will run under, and whether that
/// question has been asked yet.
///
/// Distinguishes "asked for nobody" from "not resolved yet": a plain
/// `Option<Credentials>` on `ProcessEntry` spelled both `None`.
///
/// `Serialize`/`Deserialize` are for the handover blob: this type's shape is part of its version-1 format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SpawnIdentity {
    /// `resolve` has never run for this entry.
    ///
    /// Two entries reach this: one registered at rest from the muster roll
    /// (a membership record, not a `Start`), and one registered `Errored`
    /// because its resolution failed. Neither may fall back to the
    /// shepherd's own identity.
    Unresolved,
    /// `resolve` has run, and this is what it said: `Some` when the app
    /// named a `user` or a `group`, `None` when it named neither.
    ///
    /// Settled for the entry's life, with one exception: a config load
    /// that parks a `user`/`group` change puts the entry back to
    /// [`Self::Unresolved`] first, so the next spawn resolves the new name.
    /// See `ProcessEntry::pending_reidentifies`.
    Resolved(Option<Credentials>),
}

impl SpawnIdentity {
    /// The credentials the next spawn runs under.
    ///
    /// `None` both for an identity that names nobody and for one `resolve`
    /// has never been asked about. Reading a value is not settling one:
    /// an `Unresolved` identity stays unresolved here, and only
    /// [`resolve`] answers it.
    #[must_use]
    pub(crate) const fn credentials(self) -> Option<Credentials> {
        match self {
            Self::Resolved(credentials) => credentials,
            Self::Unresolved => None,
        }
    }
}

/// Error resolving an app's `user`/`group` config to numeric ids
#[cfg_attr(windows, allow(dead_code))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PrivilegeError {
    /// No passwd entry for this user name
    UnknownUser(String),
    /// No group entry for this group name
    UnknownGroup(String),
    /// The passwd/group database could not be read
    Lookup(String),
    /// Credentials were requested but this daemon does not run as root, so
    /// it cannot change a child's identity
    NotPermitted {
        /// The requested user, if any
        user: Option<String>,
        /// The requested group, if any
        group: Option<String>,
    },
}

impl fmt::Display for PrivilegeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownUser(name) => write!(f, "unknown user {name:?}"),
            Self::UnknownGroup(name) => write!(f, "unknown group {name:?}"),
            Self::Lookup(msg) => write!(f, "passwd/group lookup failed: {msg}"),
            Self::NotPermitted { user, group } => write!(
                f,
                "cannot run as user={user:?} group={group:?}: not running as root"
            ),
        }
    }
}

impl core::error::Error for PrivilegeError {}

/// Resolves an app's `user`/`group` names to numeric ids
///
/// Returns `None` when the app asks for neither.
///
/// # Errors
/// - [`PrivilegeError::UnknownUser`]: no passwd entry for that name.
/// - [`PrivilegeError::UnknownGroup`]: no group entry for that name.
/// - [`PrivilegeError::Lookup`]: the passwd/group database could not be read.
/// - [`PrivilegeError::NotPermitted`]: credentials were requested but this
///   daemon does not run as root, so it cannot change a child's identity.
#[cfg(unix)]
pub(crate) fn resolve(app: &AppConfig) -> Result<Option<Credentials>, PrivilegeError> {
    if app.user.is_none() && app.group.is_none() {
        return Ok(None);
    }

    let own_uid = nix::unistd::geteuid().as_raw();
    let own_gid = nix::unistd::getegid().as_raw();

    let uid = match &app.user {
        Some(name) => resolve_user(name)?,
        None => own_uid,
    };
    let gid = match &app.group {
        Some(name) => Some(resolve_group(name)?),
        None => None,
    };

    // Changing identity to the one this process already has needs no
    // privilege, only a different uid/gid does: root can become anyone, a
    // non-root daemon only itself.
    let changing_identity = uid != own_uid || gid.is_some_and(|g| g != own_gid);
    if changing_identity && !nix::unistd::geteuid().is_root() {
        return Err(PrivilegeError::NotPermitted {
            user: app.user.clone(),
            group: app.group.clone(),
        });
    }

    Ok(Some(Credentials { uid, gid }))
}

/// Unix has no uid/gid concept off-platform: an explicit request is refused
/// outright rather than silently ignored (a config that asks for a user and
/// gets the daemon's own identity back with no error is a privilege-drop
/// footgun, not a graceful degradation).
#[cfg(not(unix))]
pub(crate) fn resolve(app: &AppConfig) -> Result<Option<Credentials>, PrivilegeError> {
    match (&app.user, &app.group) {
        (None, None) => Ok(None),
        _ => Err(PrivilegeError::Lookup(
            "uid/gid privilege drop is unix-only".to_string(),
        )),
    }
}

#[cfg(unix)]
fn resolve_user(name: &str) -> Result<u32, PrivilegeError> {
    match nix::unistd::User::from_name(name) {
        Ok(Some(user)) => Ok(user.uid.as_raw()),
        Ok(None) => Err(PrivilegeError::UnknownUser(name.to_string())),
        Err(errno) => Err(PrivilegeError::Lookup(errno.to_string())),
    }
}

#[cfg(unix)]
fn resolve_group(name: &str) -> Result<u32, PrivilegeError> {
    match nix::unistd::Group::from_name(name) {
        Ok(Some(group)) => Ok(group.gid.as_raw()),
        Ok(None) => Err(PrivilegeError::UnknownGroup(name.to_string())),
        Err(errno) => Err(PrivilegeError::Lookup(errno.to_string())),
    }
}

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

    fn own_user_name() -> String {
        nix::unistd::User::from_uid(nix::unistd::geteuid())
            .unwrap()
            .expect("this process has a passwd entry")
            .name
    }

    #[test]
    fn a_spawn_identity_yields_its_credentials_only_when_resolved() {
        let creds = Credentials {
            uid: 1000,
            gid: Some(1001),
        };

        assert_eq!(
            SpawnIdentity::Resolved(Some(creds)).credentials(),
            Some(creds)
        );
        assert_eq!(
            SpawnIdentity::Resolved(None).credentials(),
            None,
            "an app that named neither `user` nor `group` settles to nobody"
        );
        assert_eq!(
            SpawnIdentity::Unresolved.credentials(),
            None,
            "an identity never resolved yields nothing here; only `resolve` can settle it"
        );
    }

    #[test]
    fn no_user_or_group_means_no_credentials() {
        assert_eq!(resolve(&AppConfig::minimal("web", "./srv")).unwrap(), None);
    }

    #[test]
    fn a_real_user_name_resolves_to_its_uid() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.user = Some(own_user_name());
        let creds = resolve(&app).unwrap().expect("a user was requested");
        assert_eq!(creds.uid, nix::unistd::geteuid().as_raw());
        assert_eq!(creds.gid, None);
    }

    #[test]
    fn an_unknown_user_is_a_typed_error_naming_the_user() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.user = Some("definitely-not-a-real-shep-user".to_string());
        assert_eq!(
            resolve(&app).unwrap_err(),
            PrivilegeError::UnknownUser("definitely-not-a-real-shep-user".to_string())
        );
    }

    #[test]
    fn asking_for_another_user_without_root_is_refused_in_plain_english() {
        if nix::unistd::geteuid().is_root() {
            return; // the refusal cannot trigger as root
        }
        let mut app = AppConfig::minimal("web", "./srv");
        app.user = Some("root".to_string());
        let err = resolve(&app).unwrap_err();
        assert!(matches!(err, PrivilegeError::NotPermitted { .. }));
        assert!(
            err.to_string().contains("not running as root"),
            "the message must say what to do: {err}"
        );
    }
}