moshpits 0.15.0

moshpits server (mps) — server daemon for moshpit remote terminal sessions
// Copyright (c) 2025 moshpit developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Validate the client-forwarded `LANG`/`LC_ALL`/`LC_CTYPE` environment against the
//! server's actually-installed, actually-UTF-8 locales before they're applied to the
//! spawned shell.
//!
//! Unlike a plain string heuristic ("does the value contain `UTF-8`?"), this
//! corroborates the requested locale against the server's real locale database (via
//! `locale -a`) — catching a locale that simply isn't installed on this server, or a
//! `C`/`POSIX` locale masquerading as valid — without any unsafe `setlocale`/
//! `nl_langinfo` FFI. When `locale -a` itself is unavailable (e.g. a minimal musl
//! container), falls back to the plain heuristic so validation degrades gracefully
//! rather than failing closed.

use std::sync::OnceLock;

use tracing::warn;

/// Outcome of validating a client-requested locale against the server's installed
/// locale list.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum LocaleValidation {
    /// The effective requested locale (POSIX precedence `LC_ALL` > `LC_CTYPE` > `LANG`)
    /// is installed and resolves to a UTF-8 codeset — nothing needs to change.
    Accepted,
    /// The effective requested locale is not installed, or not UTF-8. `fallback` is
    /// `Some("C.UTF-8")` when that locale is installed on this server (the caller
    /// should force it via `LC_ALL`); `None` means no known-good fallback is
    /// available, so the caller should strip the client's `LANG`/`LC_*`/`LC_ALL` entirely
    /// and let the server's own inherited locale stand.
    Rejected {
        fallback: Option<String>,
        reason: String,
    },
}

/// Look up `key` in `env` (a flat list of `(name, value)` pairs, as forwarded over the
/// wire), returning its value if present and non-empty.
fn extract<'a>(env: &'a [(String, String)], key: &str) -> Option<&'a str> {
    env.iter()
        .find(|(k, _)| k == key)
        .map(|(_, v)| v.as_str())
        .filter(|v| !v.is_empty())
}

/// Resolve the effective locale from POSIX precedence: `LC_ALL` overrides `LC_CTYPE`,
/// which overrides `LANG`. Returns `None` if none of the three are set.
fn effective_locale<'a>(
    lang: Option<&'a str>,
    lc_ctype: Option<&'a str>,
    lc_all: Option<&'a str>,
) -> Option<&'a str> {
    lc_all.or(lc_ctype).or(lang)
}

/// Normalize a locale name for comparison: lowercase, and fold `utf-8`/`UTF-8` to
/// `utf8` so `en_US.UTF-8` (a common client-side spelling) compares equal to
/// `en_us.utf8` (glibc's own `locale -a` spelling).
fn normalize(locale: &str) -> String {
    locale.to_lowercase().replace("utf-8", "utf8")
}

/// Whether a normalized locale name resolves to a UTF-8 codeset.
fn is_utf8_codeset(normalized: &str) -> bool {
    normalized.ends_with("utf8")
}

/// Pure core: given the server's installed-locale list (as returned by `locale -a`,
/// in any casing/spelling — normalized internally) and the client's requested
/// `LANG`/`LC_CTYPE`/`LC_ALL` values, decide whether the effective locale is
/// installed and UTF-8.
pub(crate) fn validate_locale_core(
    installed: &[String],
    lang: Option<&str>,
    lc_ctype: Option<&str>,
    lc_all: Option<&str>,
) -> LocaleValidation {
    let Some(effective) = effective_locale(lang, lc_ctype, lc_all) else {
        return LocaleValidation::Accepted;
    };
    let normalized = normalize(effective);
    let is_installed = installed.iter().any(|l| normalize(l) == normalized);

    if is_installed && is_utf8_codeset(&normalized) {
        return LocaleValidation::Accepted;
    }

    let reason = if is_installed {
        format!("locale '{effective}' is installed but is not a UTF-8 codeset")
    } else {
        format!("locale '{effective}' is not installed on this server")
    };
    let fallback = installed
        .iter()
        .any(|l| normalize(l) == "c.utf8")
        .then(|| "C.UTF-8".to_string());
    LocaleValidation::Rejected { fallback, reason }
}

/// Shell out to `locale -a` once per process (cached) and return the server's
/// installed locale names, or `None` if the command is unavailable or fails (e.g. a
/// minimal musl-based system without a locale database).
fn installed_locales() -> Option<&'static [String]> {
    static CACHE: OnceLock<Option<Vec<String>>> = OnceLock::new();
    CACHE
        .get_or_init(|| {
            std::process::Command::new("locale")
                .arg("-a")
                .output()
                .ok()
                .filter(|output| output.status.success())
                .map(|output| {
                    String::from_utf8_lossy(&output.stdout)
                        .lines()
                        .map(str::trim)
                        .filter(|line| !line.is_empty())
                        .map(str::to_string)
                        .collect()
                })
        })
        .as_deref()
}

/// Validate and, if necessary, adjust the `LANG`/`LC_ALL`/`LC_CTYPE` entries in `env`
/// (the client-forwarded, allow-list-filtered environment about to be applied to the
/// spawned shell) against the server's real locale database.
///
/// On rejection, strips all three keys from `env` and — if `C.UTF-8` is installed on
/// this server — re-adds `LC_ALL=C.UTF-8` to force UTF-8 behavior; otherwise leaves
/// them stripped so the server's own inherited locale environment applies unchanged.
/// Logs a `tracing::warn!` describing what was adjusted and why. A no-op if the
/// client didn't forward any of the three variables.
pub(crate) fn validate_and_adjust_locale_env(env: &mut Vec<(String, String)>) {
    let lang = extract(env, "LANG").map(str::to_string);
    let lc_ctype = extract(env, "LC_CTYPE").map(str::to_string);
    let lc_all = extract(env, "LC_ALL").map(str::to_string);

    let Some(effective) = effective_locale(lang.as_deref(), lc_ctype.as_deref(), lc_all.as_deref())
    else {
        return;
    };
    let effective = effective.to_string();

    let validation = match installed_locales() {
        Some(installed) => validate_locale_core(
            installed,
            lang.as_deref(),
            lc_ctype.as_deref(),
            lc_all.as_deref(),
        ),
        None => {
            // `locale -a` unavailable — fall back to a plain UTF-8-suffix heuristic
            // with no installed-list corroboration.
            if is_utf8_codeset(&normalize(&effective)) {
                LocaleValidation::Accepted
            } else {
                LocaleValidation::Rejected {
                    fallback: None,
                    reason: format!(
                        "locale '{effective}' does not look like a UTF-8 locale (full \
                         validation unavailable: `locale -a` failed or is not installed)"
                    ),
                }
            }
        }
    };

    if let LocaleValidation::Rejected { fallback, reason } = validation {
        warn!(
            locale = %effective,
            fallback = ?fallback,
            %reason,
            "invalid locale forwarded by client; adjusting"
        );
        env.retain(|(k, _)| k != "LANG" && k != "LC_CTYPE" && k != "LC_ALL");
        if let Some(value) = fallback {
            env.push(("LC_ALL".to_string(), value));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{LocaleValidation, validate_locale_core};

    fn installed() -> Vec<String> {
        vec![
            "C".to_string(),
            "C.utf8".to_string(),
            "en_US.utf8".to_string(),
            "POSIX".to_string(),
            "en_US".to_string(),
        ]
    }

    #[test]
    fn nothing_requested_is_accepted() {
        assert_eq!(
            validate_locale_core(&installed(), None, None, None),
            LocaleValidation::Accepted
        );
    }

    #[test]
    fn exact_match_is_accepted() {
        assert_eq!(
            validate_locale_core(&installed(), Some("en_US.utf8"), None, None),
            LocaleValidation::Accepted
        );
    }

    #[test]
    fn case_and_dash_insensitive_match_is_accepted() {
        assert_eq!(
            validate_locale_core(&installed(), Some("en_US.UTF-8"), None, None),
            LocaleValidation::Accepted
        );
    }

    #[test]
    fn lc_all_overrides_lc_ctype_overrides_lang() {
        // LANG is bogus, LC_CTYPE is installed-but-non-UTF8, LC_ALL is valid — LC_ALL wins.
        assert_eq!(
            validate_locale_core(
                &installed(),
                Some("nonexistent.utf8"),
                Some("en_US"),
                Some("en_US.utf8"),
            ),
            LocaleValidation::Accepted
        );
        // LC_ALL absent: LC_CTYPE (installed, non-UTF8) wins over LANG, and is rejected.
        let result = validate_locale_core(&installed(), Some("en_US.utf8"), Some("en_US"), None);
        assert!(matches!(result, LocaleValidation::Rejected { .. }));
    }

    #[test]
    fn not_installed_falls_back_to_c_utf8() {
        let result = validate_locale_core(&installed(), Some("xx_XX.UTF-8"), None, None);
        assert_eq!(
            result,
            LocaleValidation::Rejected {
                fallback: Some("C.UTF-8".to_string()),
                reason: "locale 'xx_XX.UTF-8' is not installed on this server".to_string(),
            }
        );
    }

    #[test]
    fn not_installed_and_no_c_utf8_available_has_no_fallback() {
        let installed = vec!["C".to_string(), "POSIX".to_string()];
        let result = validate_locale_core(&installed, Some("xx_XX.UTF-8"), None, None);
        assert_eq!(
            result,
            LocaleValidation::Rejected {
                fallback: None,
                reason: "locale 'xx_XX.UTF-8' is not installed on this server".to_string(),
            }
        );
    }

    #[test]
    fn installed_but_non_utf8_is_rejected() {
        let result = validate_locale_core(&installed(), Some("en_US"), None, None);
        assert_eq!(
            result,
            LocaleValidation::Rejected {
                fallback: Some("C.UTF-8".to_string()),
                reason: "locale 'en_US' is installed but is not a UTF-8 codeset".to_string(),
            }
        );
    }

    #[test]
    fn posix_locale_is_rejected() {
        let result = validate_locale_core(&installed(), Some("POSIX"), None, None);
        assert!(matches!(result, LocaleValidation::Rejected { .. }));
    }
}

#[cfg(test)]
mod io_tests {
    use super::installed_locales;

    #[test]
    fn installed_locales_never_panics() {
        // Environment-dependent: assert only that it doesn't panic and returns a
        // sensible shape either way.
        if let Some(list) = installed_locales() {
            assert!(list.iter().all(|l| !l.is_empty()));
        }
    }
}

#[cfg(test)]
mod adjust_tests {
    use super::validate_and_adjust_locale_env;

    #[test]
    fn no_locale_vars_is_noop() {
        let mut env = vec![("FOO".to_string(), "bar".to_string())];
        let before = env.clone();
        validate_and_adjust_locale_env(&mut env);
        assert_eq!(env, before);
    }

    #[test]
    fn unrelated_vars_survive_rejection() {
        // Even if LANG gets stripped/replaced, unrelated forwarded vars must be untouched.
        //
        // Deliberately doesn't end in "utf8"/"UTF-8": on platforms without `locale -a`
        // (e.g. Windows), validation falls back to a naive UTF-8-suffix heuristic
        // (`is_utf8_codeset`), and a value crafted to satisfy that heuristic would be
        // wrongly accepted there even though it's rejected via the full `locale -a`
        // corroboration on Linux/macOS. This value fails both paths, so the rejection
        // this test exercises is platform-independent.
        let mut env = vec![
            (
                "LANG".to_string(),
                "definitely-not-a-real-locale".to_string(),
            ),
            ("TZ".to_string(), "UTC".to_string()),
        ];
        validate_and_adjust_locale_env(&mut env);
        assert!(env.contains(&("TZ".to_string(), "UTC".to_string())));
        assert!(!env.iter().any(|(k, _)| k == "LANG"));
    }
}