pg-embed-setup-unpriv 0.6.3

Initializes postgresql_embedded clusters with platform-appropriate setup
Documentation
//! Prepares filesystem state for the bootstrap flows.

use camino::{Utf8Path, Utf8PathBuf};
#[cfg(all(unix, privileged_unix_platform))]
use nix::unistd::{Uid, geteuid};
use postgresql_embedded::Settings;
use tracing::{debug, info};

use super::{
    env::{TestBootstrapEnvironment, XdgDirs, prepare_timezone_env},
    mode::{root_privilege_drop_supported, unsupported_root_privilege_drop_error},
};
#[cfg(all(unix, privileged_unix_platform))]
use crate::privileges::default_root_for;
use crate::{
    PgEnvCfg,
    error::{BootstrapError, BootstrapResult},
    fs::{ensure_dir_exists, set_permissions},
    observability::LOG_TARGET,
};

const PGPASS_MODE: u32 = 0o600;

mod cluster_slot;
pub(crate) use cluster_slot::{
    ClaimGuard,
    claim_guard_at,
    claim_guard_for,
    derived_slot_parent,
    has_live_peers,
    has_live_slots_in,
};
mod layout;
pub(super) use self::layout::DataLayout;
use self::layout::claim_derived_slot;
mod orphan;
mod password;
mod stale_password;
pub use password::{PasswordReuseOutcome, reuse_existing_password, stored_cluster_password};

/// Derives the default `install` and `data` directories under `root`.
///
/// The derived `data` path is the parent of one directory per cluster (ADR
/// 005): each bootstrap claims `data/<name>/` beneath it, so concurrent
/// processes sharing a root never share a data directory.
///
/// # Examples
/// ```
/// use camino::Utf8Path;
///
/// let (install, data) = pg_embedded_setup_unpriv::default_paths_under(Utf8Path::new("/srv/pg"));
/// assert_eq!(install.as_str(), "/srv/pg/install");
/// assert_eq!(data.as_str(), "/srv/pg/data");
/// ```
#[must_use]
pub fn default_paths_under(root: &Utf8Path) -> (Utf8PathBuf, Utf8PathBuf) {
    (root.join("install"), root.join("data"))
}

#[cfg(all(unix, privileged_unix_platform))]
mod root;
#[cfg(all(unix, privileged_unix_platform))]
use self::root::bootstrap_with_root;

pub(super) fn prepare_bootstrap(
    privileges: super::mode::ExecutionPrivileges,
    settings: Settings,
    cfg: &PgEnvCfg,
    layout: DataLayout,
) -> BootstrapResult<PreparedBootstrap> {
    if privileges == super::mode::ExecutionPrivileges::Root && !root_privilege_drop_supported() {
        return Err(unsupported_root_privilege_drop_error());
    }

    #[cfg(all(unix, privileged_unix_platform))]
    {
        match privileges {
            super::mode::ExecutionPrivileges::Root => bootstrap_with_root(settings, cfg, layout),
            super::mode::ExecutionPrivileges::Unprivileged => {
                bootstrap_unprivileged(settings, cfg, layout)
            }
        }
    }

    #[cfg(not(all(unix, privileged_unix_platform)))]
    {
        match privileges {
            super::mode::ExecutionPrivileges::Root => {
                unreachable!("root privilege drop support is checked before platform dispatch")
            }
            super::mode::ExecutionPrivileges::Unprivileged => {
                bootstrap_unprivileged(settings, cfg, layout)
            }
        }
    }
}

pub(super) struct PreparedBootstrap {
    pub(super) settings: Settings,
    pub(super) environment: TestBootstrapEnvironment,
}

fn bootstrap_unprivileged(
    mut settings: Settings,
    cfg: &PgEnvCfg,
    layout: DataLayout,
) -> BootstrapResult<PreparedBootstrap> {
    let mut paths = resolve_settings_paths_for_current_user(&mut settings, cfg)?;
    claim_derived_slot(&mut settings, &mut paths, layout)?;
    reuse_existing_password(
        &mut settings,
        &paths.data_dir,
        &paths.password_file,
        cfg.password.is_some(),
    )?;
    log_sanitized_settings(&settings);

    ensure_parents_for_paths(&paths, ensure_parent_exists)?;

    ensure_dir_with_mode(&paths.install_dir, 0o755)?;
    ensure_dir_with_mode(&paths.data_dir, 0o700)?;
    stale_password::discard_orphaned_password_file(&paths.data_dir, &paths.password_file)?;
    ensure_pgpass_permissions(&paths.password_file)?;

    let timezone = prepare_timezone_env()?;
    let xdg = prepare_xdg_dirs(&paths.install_dir)?;
    let environment = TestBootstrapEnvironment::from_components(xdg, paths.password_file, timezone);
    Ok(PreparedBootstrap {
        settings,
        environment,
    })
}

struct SettingsPaths {
    install_dir: Utf8PathBuf,
    data_dir: Utf8PathBuf,
    password_file: Utf8PathBuf,
    install_default: bool,
    data_default: bool,
}

#[cfg(all(unix, privileged_unix_platform))]
fn resolve_settings_paths_for_uid(
    settings: &mut Settings,
    cfg: &PgEnvCfg,
    uid: Uid,
) -> BootstrapResult<SettingsPaths> {
    let (root, root_source) = cfg.embed_root.clone().map_or_else(
        || (default_root_for(uid), RootSource::PerUserDefault),
        |root| (root, RootSource::Override),
    );
    let (default_install_dir, default_data_dir) = default_paths_under(&root);
    let mut install_default = false;
    let mut data_default = false;

    if cfg.runtime_dir.is_none() {
        settings.installation_dir = default_install_dir.clone().into_std_path_buf();
        install_default = true;
    }
    if cfg.data_dir.is_none() {
        settings.data_dir = default_data_dir.clone().into_std_path_buf();
        data_default = true;
    }

    let paths = settings_paths_from_settings(settings, install_default, data_default)?;
    log_settings_decision(root_source, &paths, settings);
    Ok(paths)
}

#[cfg(all(unix, privileged_unix_platform))]
fn resolve_settings_paths_for_current_user(
    settings: &mut Settings,
    cfg: &PgEnvCfg,
) -> BootstrapResult<SettingsPaths> {
    let uid = geteuid();
    resolve_settings_paths_for_uid(settings, cfg, uid)
}

/// Platforms without a per-user default tree keep the `Settings` defaults,
/// but `PG_EMBED_ROOT` still relocates both leaves when set.
#[cfg(not(all(unix, privileged_unix_platform)))]
fn resolve_settings_paths_for_current_user(
    settings: &mut Settings,
    cfg: &PgEnvCfg,
) -> BootstrapResult<SettingsPaths> {
    let Some(root) = cfg.embed_root.as_ref() else {
        let paths = settings_paths_from_settings(settings, false, false)?;
        log_settings_decision(RootSource::SettingsDefault, &paths, settings);
        return Ok(paths);
    };
    let (install_dir, data_dir) = default_paths_under(root);
    let mut install_default = false;
    let mut data_default = false;
    if cfg.runtime_dir.is_none() {
        settings.installation_dir = install_dir.into_std_path_buf();
        install_default = true;
    }
    if cfg.data_dir.is_none() {
        settings.data_dir = data_dir.into_std_path_buf();
        data_default = true;
    }
    let paths = settings_paths_from_settings(settings, install_default, data_default)?;
    log_settings_decision(RootSource::Override, &paths, settings);
    Ok(paths)
}

/// Where the base directory for the derived `install` and `data` leaves came
/// from; a bounded label for the `settings_decision` event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RootSource {
    /// `PG_EMBED_ROOT` was set.
    Override,
    /// The per-user `/var/tmp/pg-embed-{uid}` tree.
    #[cfg(all(unix, privileged_unix_platform))]
    PerUserDefault,
    /// No per-user tree on this platform; `Settings` defaults were kept.
    #[cfg(not(all(unix, privileged_unix_platform)))]
    SettingsDefault,
}

/// Records the resolved directories and connection cap once per bootstrap so
/// an operator can see which override won without reading the settings dump.
///
/// `max_connections` is read from the resolved settings rather than from
/// `PgEnvCfg`, because the two differ: a test bootstrap that sets no
/// `PG_MAX_CONNECTIONS` still runs the server at 20, which `apply_worker_limits`
/// put into the configuration. Logging the configured option would report
/// nothing for the case an operator most needs to see. A plain bootstrap that
/// sets no limit leaves the key absent and the event says `server default`.
fn log_settings_decision(root_source: RootSource, paths: &SettingsPaths, settings: &Settings) {
    info!(
        target: LOG_TARGET,
        root_source = ?root_source,
        install_dir = %paths.install_dir,
        install_default = paths.install_default,
        data_dir = %paths.data_dir,
        data_default = paths.data_default,
        max_connections = settings
            .configuration
            .get("max_connections")
            .map_or("server default", String::as_str),
        "settings_decision"
    );
}

fn settings_paths_from_settings(
    settings: &mut Settings,
    install_default: bool,
    data_default: bool,
) -> BootstrapResult<SettingsPaths> {
    let install_dir = Utf8PathBuf::from_path_buf(settings.installation_dir.clone())
        .map_err(|_| color_eyre::eyre::eyre!("installation_dir must be valid UTF-8"))?;
    let data_dir = Utf8PathBuf::from_path_buf(settings.data_dir.clone())
        .map_err(|_| color_eyre::eyre::eyre!("data_dir must be valid UTF-8"))?;

    let password_file = install_dir.join(".pgpass");
    settings.password_file = password_file.clone().into_std_path_buf();

    Ok(SettingsPaths {
        install_dir,
        data_dir,
        password_file,
        install_default,
        data_default,
    })
}

fn ensure_parents_for_paths<F>(paths: &SettingsPaths, mut ensure_parent: F) -> BootstrapResult<()>
where
    F: FnMut(&Utf8PathBuf) -> BootstrapResult<()>,
{
    if paths.install_default {
        ensure_parent(&paths.install_dir)?;
    }
    if paths.data_default {
        ensure_parent(&paths.data_dir)?;
    }
    Ok(())
}

fn ensure_dir_with_mode(path: &Utf8Path, mode: u32) -> BootstrapResult<()> {
    ensure_dir_exists(path).map_err(BootstrapError::from)?;
    set_permissions(path, mode).map_err(BootstrapError::from)
}

fn ensure_pgpass_permissions(path: &Utf8PathBuf) -> BootstrapResult<()> {
    match set_permissions(path, PGPASS_MODE) {
        Ok(()) => Ok(()),
        Err(err) => {
            if let Some(io_err) = err.downcast_ref::<std::io::Error>()
                && io_err.kind() == std::io::ErrorKind::NotFound
            {
                return Ok(());
            }
            Err(BootstrapError::from(err))
        }
    }
}

/// Create the XDG cache and runtime directories with the expected
/// permissions.
///
/// The cache surface only stores extracted binaries and log files, so it
/// remains group/world-readable (0o755) to make debugging easier when the
/// helper runs inside CI sandboxes. The runtime directory, however, holds the
/// `PostgreSQL` socket, `postmaster.pid`, and `.pgpass`, so it is locked down
/// to user-only access (0o700) to avoid leaking credentials or allowing other
/// processes to tamper with the instance.
///
/// # Examples
///
/// ```ignore
/// use camino::Utf8PathBuf;
/// use crate::bootstrap::prepare::prepare_xdg_dirs;
///
/// let install_dir = Utf8PathBuf::from("/tmp/test-install");
/// let dirs = prepare_xdg_dirs(&install_dir).expect("xdg dirs");
/// assert_eq!(dirs.cache, install_dir.join("cache"));
/// assert_eq!(dirs.runtime, install_dir.join("run"));
/// ```
fn prepare_xdg_dirs(install_dir: &Utf8PathBuf) -> BootstrapResult<XdgDirs> {
    let cache = install_dir.join("cache");
    let runtime = install_dir.join("run");
    // Cache files are harmless to share, so grant read access for debugging.
    ensure_dir_with_mode(&cache, 0o755)?;
    // Runtime dir holds sockets/pids; clamp to user-only for safety.
    ensure_dir_with_mode(&runtime, 0o700)?;
    Ok(XdgDirs {
        home: install_dir.clone(),
        cache,
        runtime,
    })
}

fn ensure_parent_exists(path: &Utf8PathBuf) -> BootstrapResult<()> {
    if let Some(parent) = path.parent() {
        ensure_dir_exists(parent).map_err(BootstrapError::from)?;
    }
    Ok(())
}

fn log_sanitized_settings(settings: &Settings) {
    let configuration_keys = sorted_configuration_keys(settings);
    let timeout_secs = settings.timeout.map(|duration| duration.as_secs());

    debug!(
        target: LOG_TARGET,
        version = %settings.version,
        host = %settings.host,
        port = settings.port,
        installation_dir = %settings.installation_dir.display(),
        data_dir = %settings.data_dir.display(),
        password_file = %settings.password_file.display(),
        username = %settings.username,
        password = "<redacted>",
        temporary = settings.temporary,
        timeout_secs,
        trust_installation_dir = settings.trust_installation_dir,
        configuration_keys = ?configuration_keys,
        "prepared postgres settings"
    );
}

fn sorted_configuration_keys(settings: &Settings) -> Vec<&str> {
    let mut keys: Vec<&str> = settings.configuration.keys().map(String::as_str).collect();
    keys.sort_unstable();
    keys
}
#[cfg(test)]
mod property_tests;
#[cfg(test)]
mod tests;
#[cfg(all(unix, privileged_unix_platform))]
mod unix_user;