phoebus_os/installer-rs/crates/phoebus-core/src/validate.rs
Phoebus 95e0d05344 fix(core): reject unimplemented secureboot/uki at validation
The installed boot path is plain unsigned BLS. kernel.uki=true and
kernel.secureboot=true are now rejected by validate_config (which the
CLI, TUI and GUI bridge all share) with errors naming the limitation.
The plan preview reports the real BLS path unconditionally and never
renders the requested flags as active. Golden plan updated; parsing,
validation and rendering regressions added.
2026-09-25 19:49:41 -07:00

385 lines
13 KiB
Rust

//! Configuration validation. Pure decision logic, testable without root.
use serde::{Deserialize, Serialize};
use crate::config::InstallConfig;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValidationIssue {
pub field: &'static str,
pub message: String,
}
impl ValidationIssue {
pub fn new(field: &'static str, message: impl Into<String>) -> Self {
Self {
field,
message: message.into(),
}
}
}
impl std::fmt::Display for ValidationIssue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.field, self.message)
}
}
pub fn validate_hostname(hostname: &str) -> Result<(), String> {
if hostname.is_empty() || hostname.len() > 63 {
return Err("hostname must be 1-63 characters".into());
}
let bytes = hostname.as_bytes();
let valid_start = bytes[0].is_ascii_alphanumeric();
let valid_end = bytes[hostname.len() - 1].is_ascii_alphanumeric();
let valid_chars = hostname
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-');
if !valid_start || !valid_end {
return Err("hostname must begin and end with an alphanumeric character".into());
}
if !valid_chars {
return Err("hostname may only contain letters, digits and internal hyphens".into());
}
Ok(())
}
pub fn validate_username(username: &str) -> Result<(), String> {
if username.is_empty() {
return Err("username is required".into());
}
if username == "root" {
return Err("refusing to create an account named root".into());
}
if username.len() > 32 {
return Err("username must be at most 32 characters".into());
}
let mut chars = username.chars();
let first = chars.next().unwrap();
if !(first.is_ascii_lowercase() || first == '_') {
return Err("username must start with a lowercase letter or underscore".into());
}
if !username
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
{
return Err("username may only contain lowercase letters, digits, `_` and `-`".into());
}
Ok(())
}
pub fn validate_timezone(timezone: &str) -> Result<(), String> {
if timezone.is_empty() {
return Err("timezone is required".into());
}
let zoneinfo = std::path::Path::new("/usr/share/zoneinfo");
if zoneinfo.is_dir() {
let candidate = zoneinfo.join(timezone);
if candidate.is_file() {
return Ok(());
}
return Err(format!("unknown timezone: {timezone}"));
}
Ok(())
}
pub fn validate_locale(locale: &str) -> Result<(), String> {
if locale.is_empty() {
return Err("locale is required".into());
}
let base = locale.split('.').next().unwrap_or(locale);
if std::path::Path::new("/usr/share/i18n/locales")
.join(base)
.is_file()
{
return Ok(());
}
if locale
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '-' || c == '@')
{
return Ok(());
}
Err(format!("locale looks malformed: {locale}"))
}
pub fn validate_keymap(keymap: &str) -> Result<(), String> {
if keymap.is_empty() {
Err("keymap is required".into())
} else {
Ok(())
}
}
/// Simple heuristic password strength: weak / fair / strong.
pub fn password_strength(password: &str) -> &'static str {
let mut score = 0;
if password.len() >= 8 {
score += 1;
}
if password.len() >= 12 {
score += 1;
}
if password.chars().any(|c| c.is_ascii_uppercase()) {
score += 1;
}
if password.chars().any(|c| c.is_ascii_lowercase()) {
score += 1;
}
if password.chars().any(|c| c.is_ascii_digit()) {
score += 1;
}
if password.chars().any(|c| !c.is_ascii_alphanumeric()) {
score += 1;
}
match score {
0..=2 => "weak",
3..=4 => "fair",
_ => "strong",
}
}
/// Validate a package atom: `category/name`, with only safe characters.
pub fn validate_package_atom(atom: &str) -> Result<(), String> {
if atom.split('/').count() != 2 || atom.is_empty() {
return Err(format!("package atom must be category/name: {atom}"));
}
if !atom
.chars()
.all(|c| c.is_ascii_alphanumeric() || "/*._+-".contains(c))
{
return Err(format!("invalid package atom: {atom}"));
}
Ok(())
}
/// Validate a USE flag. A leading `-` disables the flag; wildcards are refused
/// so a proposal cannot change flags across every package.
pub fn validate_use_flag(flag: &str) -> Result<(), String> {
if flag.contains('*') {
return Err("wildcard USE flags are not allowed".into());
}
let name = flag.strip_prefix('-').unwrap_or(flag);
if name.is_empty()
|| name.len() > 64
|| !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '+' || c == '@')
{
return Err(format!("invalid USE flag: {flag}"));
}
Ok(())
}
/// Validate the whole configuration. Disk protection is checked separately
/// against probed hardware at preflight time.
pub fn validate_config(config: &InstallConfig) -> Vec<ValidationIssue> {
let mut issues = Vec::new();
if let Err(e) = validate_hostname(&config.system.hostname) {
issues.push(ValidationIssue::new("hostname", e));
}
if let Err(e) = validate_username(&config.user.username) {
issues.push(ValidationIssue::new("username", e));
}
if let Err(e) = validate_locale(&config.system.locale) {
issues.push(ValidationIssue::new("locale", e));
}
if let Err(e) = validate_timezone(&config.system.timezone) {
issues.push(ValidationIssue::new("timezone", e));
}
if let Err(e) = validate_keymap(&config.system.keymap) {
issues.push(ValidationIssue::new("keymap", e));
}
if config.storage.disk.is_empty() {
issues.push(ValidationIssue::new(
"target_disk",
"no target disk selected",
));
} else if !config.storage.disk.starts_with("/dev/") {
issues.push(ValidationIssue::new(
"target_disk",
format!("target is not a device path: {}", config.storage.disk),
));
}
if config.storage.efi_size_mib < 256 {
issues.push(ValidationIssue::new(
"efi_size_mib",
"EFI System Partition should be at least 256 MiB",
));
}
if config.storage.subvols.is_empty() {
issues.push(ValidationIssue::new(
"subvols",
"at least one Btrfs subvolume is required",
));
}
if config.is_encrypted() && config.encryption.name.is_empty() {
issues.push(ValidationIssue::new(
"luks_name",
"LUKS mapper name is required when encryption is enabled",
));
}
if config.kernel.keep_kernels < 2 {
issues.push(ValidationIssue::new(
"keep_kernels",
"keep at least 2 kernels so a known-good kernel is available",
));
}
// Authenticated boot is not implemented: the installed boot path is
// plain BLS (systemd-boot + dracut, no signing, no UKI). Accepting these
// flags would imply a security property the system does not provide, so
// they are rejected here — before the CLI, TUI, GUI, or plan preview can
// present them as active. See the "UKI" row in docs/STATUS.md.
if config.kernel.uki {
issues.push(ValidationIssue::new(
"uki",
"Unified Kernel Images are not implemented; the installer uses plain BLS entries (uki must be false)",
));
}
if config.kernel.secureboot {
issues.push(ValidationIssue::new(
"secureboot",
"UEFI Secure Boot is not implemented; the boot chain is unsigned (secureboot must be false)",
));
}
if config.packages.accept_license.trim().is_empty() {
issues.push(ValidationIssue::new(
"accept_license",
"ACCEPT_LICENSE must not be empty",
));
}
if !config.desktop.flatpak {
issues.push(ValidationIssue::new(
"flatpak",
"Flatpak is a required Phoebus workstation subsystem and cannot be disabled",
));
}
if let Some(jobs) = config.packages.build_jobs {
if jobs == 0 || jobs > 256 {
issues.push(ValidationIssue::new(
"build_jobs",
"build jobs must be between 1 and 256",
));
}
}
for entry in &config.packages.package_use {
if let Err(e) = validate_package_atom(&entry.atom) {
issues.push(ValidationIssue::new("package_use", e));
}
if let Err(e) = validate_use_flag(&entry.flag) {
issues.push(ValidationIssue::new("package_use", e));
}
}
issues
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hostname_rules() {
assert!(validate_hostname("phoebus").is_ok());
assert!(validate_hostname("my-box").is_ok());
assert!(validate_hostname("").is_err());
assert!(validate_hostname("-bad").is_err());
assert!(validate_hostname("bad host").is_err());
assert!(validate_hostname("bad-").is_err());
}
#[test]
fn username_rules() {
assert!(validate_username("alice").is_ok());
assert!(validate_username("phoebus").is_ok());
assert!(validate_username("root").is_err());
assert!(validate_username("Alice").is_err());
assert!(validate_username("").is_err());
}
#[test]
fn password_strength_levels() {
assert_eq!(password_strength("abc"), "weak");
assert_eq!(password_strength("abcdefghij"), "weak");
assert_eq!(password_strength("Abcdefghij"), "fair");
assert_eq!(password_strength("Abcdef1!ghijk"), "strong");
}
#[test]
fn default_config_is_mostly_valid_but_missing_user_and_disk() {
let cfg = InstallConfig::default();
let issues = validate_config(&cfg);
let fields: Vec<&str> = issues.iter().map(|i| i.field).collect();
assert!(fields.contains(&"username"));
assert!(fields.contains(&"target_disk"));
}
#[test]
fn package_use_and_jobs_are_validated() {
assert!(validate_package_atom("www-client/firefox").is_ok());
assert!(validate_package_atom("firefox").is_err());
assert!(validate_package_atom("sys-fs/btrfs-progs").is_ok());
assert!(validate_use_flag("-man").is_ok());
assert!(validate_use_flag("systemd").is_ok());
assert!(validate_use_flag("*").is_err());
assert!(validate_use_flag("").is_err());
assert!(validate_use_flag("bad flag").is_err());
let mut cfg = InstallConfig::default();
cfg.packages.build_jobs = Some(0);
cfg.packages.package_use.push(crate::config::PackageUse {
atom: "notanatatom".into(),
flag: "*.x".into(),
enabled: true,
});
let fields: Vec<&str> = validate_config(&cfg).iter().map(|i| i.field).collect();
assert!(fields.contains(&"build_jobs"));
assert!(fields.contains(&"package_use"));
}
#[test]
fn complete_config_passes() {
let mut cfg = InstallConfig::default();
cfg.system.hostname = "phoebus".into();
cfg.system.timezone = "UTC".into();
cfg.user.username = "alice".into();
cfg.storage.disk = "/dev/vda".into();
assert!(validate_config(&cfg).iter().all(|i| i.field != "username"));
assert!(validate_config(&cfg)
.iter()
.all(|i| i.field != "target_disk"));
}
#[test]
fn unimplemented_boot_security_flags_are_rejected() {
// Parsing still accepts the legacy keys so the error names the field;
// validation rejects them because the boot path is plain unsigned BLS.
let mut cfg = InstallConfig::default();
cfg.system.hostname = "phoebus".into();
cfg.system.timezone = "UTC".into();
cfg.user.username = "alice".into();
cfg.storage.disk = "/dev/vda".into();
assert!(validate_config(&cfg).iter().all(|i| i.field != "uki"));
assert!(validate_config(&cfg)
.iter()
.all(|i| i.field != "secureboot"));
cfg.kernel.uki = true;
let issues = validate_config(&cfg);
let uki = issues
.iter()
.find(|i| i.field == "uki")
.expect("uki rejected");
assert!(uki.message.contains("not implemented"), "{uki}");
cfg.kernel.uki = false;
cfg.kernel.secureboot = true;
let issues = validate_config(&cfg);
let sb = issues
.iter()
.find(|i| i.field == "secureboot")
.expect("secureboot rejected");
assert!(sb.message.contains("not implemented"), "{sb}");
assert!(sb.message.contains("unsigned"), "{sb}");
}
}