use std::collections::{BTreeMap, BTreeSet}; use std::net::IpAddr; use std::sync::{Arc, RwLock}; use ipnet::IpNet; use crate::config::{ BannerLevel, Config, MailTransport, OrgCreation, R2Jurisdiction, Registration, StorageBackend, }; use crate::error::{Error, Result}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { Live, Restart, ReadOnly, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Group { General, Limits, Storage, Backups, Integrations, Alerts, } impl Group { pub const ALL: [Group; 6] = [ Group::General, Group::Limits, Group::Storage, Group::Backups, Group::Integrations, Group::Alerts, ]; } string_enum!(Group { General = "general", Limits = "limits", Storage = "storage", Backups = "backups", Integrations = "integrations", Alerts = "alerts", }); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Ty { Bool, Uint(u64, u64), Text, Path, Choice(&'static [&'static str]), List, Secret, Addr, } #[derive(Debug, Clone, Copy)] pub struct Field { pub key: &'static str, pub group: Group, pub kind: Kind, pub ty: Ty, pub label: &'static str, pub help: &'static str, get: fn(&Config) -> String, set: fn(&mut Config, &str), check: fn(&str) -> Option, } impl Field { pub fn is_secret(&self) -> bool { self.ty == Ty::Secret } } fn no_check(_: &str) -> Option { None } fn expires_check(raw: &str) -> Option { (!raw.is_empty() && crate::config::parse_banner_expiry(raw).is_none()) .then(|| "must look like 2026-12-31 18:00".to_owned()) } fn message_check(raw: &str) -> Option { (raw.chars().count() > 300).then(|| "must be at most 300 characters".to_owned()) } fn proxies_check(raw: &str) -> Option { split_list(raw) .into_iter() .find(|item| item.parse::().is_err() && item.parse::().is_err()) .map(|item| format!("invalid trusted proxy `{item}`")) } #[allow(clippy::too_many_arguments)] const fn f( key: &'static str, group: Group, kind: Kind, ty: Ty, label: &'static str, help: &'static str, get: fn(&Config) -> String, set: fn(&mut Config, &str), ) -> Field { Field { key, group, kind, ty, label, help, get, set, check: no_check, } } use Group::{Alerts, Backups, General, Integrations, Limits, Storage}; use Kind::{Live as L, ReadOnly as R, Restart as X}; const REGISTRATION: &[&str] = &[ Registration::Closed.as_str(), Registration::Invite.as_str(), Registration::Open.as_str(), ]; const BANNER_LEVEL: &[&str] = &[BannerLevel::Info.as_str(), BannerLevel::Warning.as_str()]; const ORG_CREATION: &[&str] = &[OrgCreation::All.as_str(), OrgCreation::Admin.as_str()]; const MAIL_TRANSPORT: &[&str] = &[MailTransport::Smtp.as_str(), MailTransport::Log.as_str()]; const BACKEND: &[&str] = &[ StorageBackend::Fs.as_str(), StorageBackend::S3.as_str(), StorageBackend::R2.as_str(), ]; const JURISDICTION: &[&str] = &[ R2Jurisdiction::Global.as_str(), R2Jurisdiction::Eu.as_str(), R2Jurisdiction::Fedramp.as_str(), ]; const MB: Ty = Ty::Uint(1, 1_048_576); const PORT: Ty = Ty::Uint(1, 65_535); pub static FIELDS: &[Field] = &[ f( "registration", General, L, Ty::Choice(REGISTRATION), "Registration", "Who may create an account: closed, invite only, or open.", |c| c.registration.as_str().into(), |c, v| c.registration = v.parse().unwrap_or_default(), ), f( "orgs.creation", General, L, Ty::Choice(ORG_CREATION), "Organization creation", "Who may create an organization: all signed-in people, or admins only.", |c| c.orgs.creation.as_str().into(), |c, v| c.orgs.creation = v.parse().unwrap_or_default(), ), Field { check: message_check, ..f( "banner.message", General, L, Ty::Text, "Announcement banner", "One line shown under the header on every page. Empty hides it.", |c| c.banner.message.clone(), |c, v| c.banner.message = v.to_owned(), ) }, f( "banner.level", General, L, Ty::Choice(BANNER_LEVEL), "Banner level", "Info or warning.", |c| c.banner.level.as_str().into(), |c, v| c.banner.level = v.parse().unwrap_or_default(), ), Field { check: expires_check, ..f( "banner.expires", General, L, Ty::Text, "Banner expires (UTC)", "As YYYY-MM-DD HH:MM. Empty keeps the banner until it is cleared.", |c| c.banner.expires.clone(), |c, v| c.banner.expires = v.to_owned(), ) }, Field { check: proxies_check, ..f( "trusted_proxies", General, L, Ty::List, "Trusted proxies", "Addresses or CIDR networks whose X-Forwarded-For header is trusted. Comma separated.", |c| { c.trusted_proxies .iter() .map(ToString::to_string) .collect::>() .join(", ") }, |c, v| { c.trusted_proxies = split_list(v) .iter() .filter_map(|e| { e.parse::() .ok() .or_else(|| e.parse::().ok().map(IpNet::from)) }) .collect() }, ) }, f( "base_url", General, X, Ty::Text, "Base URL", "Public URL used in links and clone URLs.", |c| c.base_url.clone(), |c, v| c.base_url = v.to_owned(), ), f( "user_content_base_url", General, X, Ty::Text, "User content URL", "Separate origin that serves raw user files.", |c| c.user_content_base_url.clone(), |c, v| c.user_content_base_url = v.to_owned(), ), f( "ssh_public_host", General, X, Ty::Text, "SSH host shown", "Host in SSH clone URLs.", |c| c.ssh_public_host.clone(), |c, v| c.ssh_public_host = v.to_owned(), ), f( "ssh_public_port", General, X, PORT, "SSH port shown", "Port in SSH clone URLs.", |c| c.ssh_public_port.to_string(), |c, v| c.ssh_public_port = n(v) as u16, ), f( "listen", General, R, Ty::Addr, "HTTP listen address", "Set in the config file.", |c| c.listen.to_string(), |_, _| {}, ), f( "user_content_listen", General, R, Ty::Addr, "User content listen address", "Set in the config file.", |c| c.user_content_listen.to_string(), |_, _| {}, ), f( "ssh_listen", General, R, Ty::Addr, "SSH listen address", "Set in the config file.", |c| c.ssh_listen.to_string(), |_, _| {}, ), f( "database", General, R, Ty::Path, "Database file", "Set in the config file.", |c| c.database.to_string_lossy().into_owned(), |_, _| {}, ), f( "data_dir", General, R, Ty::Path, "Data directory", "Set in the config file.", |c| c.data_dir.to_string_lossy().into_owned(), |_, _| {}, ), f( "ci.enabled", Limits, L, Ty::Bool, "CI enabled", "When off, pushes and pull requests create no runs.", |c| c.ci.enabled.to_string(), |c, v| c.ci.enabled = b(v), ), f( "ci.max_log_mb", Limits, L, MB, "Largest job log (MiB)", "A longer log is truncated.", |c| c.ci.max_log_mb.to_string(), |c, v| c.ci.max_log_mb = n(v), ), f( "ci.max_artifact_mb", Limits, L, MB, "Largest artifact (MiB)", "", |c| c.ci.max_artifact_mb.to_string(), |c, v| c.ci.max_artifact_mb = n(v), ), f( "ci.max_artifacts_per_job", Limits, L, Ty::Uint(1, 100_000), "Artifacts per job", "", |c| c.ci.max_artifacts_per_job.to_string(), |c, v| c.ci.max_artifacts_per_job = n(v) as u32, ), f( "ci.max_job_artifacts_mb", Limits, L, MB, "Largest total of one job's artifacts (MiB)", "", |c| c.ci.max_job_artifacts_mb.to_string(), |c, v| c.ci.max_job_artifacts_mb = n(v), ), f( "ci.log_retention_days", Limits, L, Ty::Uint(1, 36_500), "Log retention (days)", "", |c| c.ci.log_retention_days.to_string(), |c, v| c.ci.log_retention_days = n(v), ), f( "ci.artifact_retention_days", Limits, L, Ty::Uint(1, 36_500), "Artifact retention (days)", "", |c| c.ci.artifact_retention_days.to_string(), |c, v| c.ci.artifact_retention_days = n(v), ), f( "ci.artifact_keep_runs", Limits, L, Ty::Uint(0, 100_000), "Artifact runs kept per repo", "0 keeps all.", |c| c.ci.artifact_keep_runs.to_string(), |c, v| c.ci.artifact_keep_runs = n(v) as u32, ), f( "ci.artifact_max_total_mb", Limits, L, Ty::Uint(0, 100_000_000), "Artifact disk limit (MiB)", "Oldest runs' artifacts go first. 0 is no limit.", |c| c.ci.artifact_max_total_mb.to_string(), |c, v| c.ci.artifact_max_total_mb = n(v), ), f( "ci.registration_token_hours", Limits, L, Ty::Uint(1, 8_760), "Runner token lifetime (hours)", "How long a runner registration token stays valid.", |c| c.ci.registration_token_hours.to_string(), |c, v| c.ci.registration_token_hours = n(v) as u32, ), f( "lfs.max_object_mb", Limits, L, MB, "Largest LFS object (MiB)", "", |c| c.lfs.max_object_mb.to_string(), |c, v| c.lfs.max_object_mb = n(v), ), f( "releases.max_asset_mb", Limits, L, MB, "Largest release asset (MiB)", "", |c| c.releases.max_asset_mb.to_string(), |c, v| c.releases.max_asset_mb = n(v), ), f( "storage.backend", Storage, X, Ty::Choice(BACKEND), "Backend", "Where release assets and CI artifacts live: fs, r2 or s3.", |c| c.storage.backend.as_str().into(), |c, v| c.storage.backend = v.parse().unwrap_or_default(), ), f( "storage.r2.account_id", Storage, X, Ty::Text, "R2 account id", "32 character hex string from the Cloudflare dashboard.", |c| c.storage.r2.account_id.clone(), |c, v| c.storage.r2.account_id = v.to_owned(), ), f( "storage.r2.bucket", Storage, X, Ty::Text, "R2 bucket", "", |c| c.storage.r2.bucket.clone(), |c, v| c.storage.r2.bucket = v.to_owned(), ), f( "storage.r2.jurisdiction", Storage, X, Ty::Choice(JURISDICTION), "R2 jurisdiction", "eu, fedramp, or empty for the global default.", |c| c.storage.r2.jurisdiction.as_str().into(), |c, v| c.storage.r2.jurisdiction = v.parse().unwrap_or_default(), ), f( "storage.r2.prefix", Storage, X, Ty::Text, "R2 key prefix", "", |c| c.storage.r2.prefix.clone(), |c, v| c.storage.r2.prefix = v.to_owned(), ), f( "storage.r2.access_key_id", Storage, X, Ty::Text, "R2 access key id", "", |c| c.storage.r2.access_key_id.clone(), |c, v| c.storage.r2.access_key_id = v.to_owned(), ), f( "storage.r2.secret_access_key_file", Storage, X, Ty::Path, "R2 secret key file", "Path of the file that holds the secret access key. The key itself is never read here.", |c| { c.storage .r2 .secret_access_key_file .to_string_lossy() .into_owned() }, |c, v| c.storage.r2.secret_access_key_file = v.into(), ), f( "storage.s3.bucket", Storage, X, Ty::Text, "S3 bucket", "", |c| c.storage.s3.bucket.clone(), |c, v| c.storage.s3.bucket = v.to_owned(), ), f( "storage.s3.region", Storage, X, Ty::Text, "S3 region", "", |c| c.storage.s3.region.clone(), |c, v| c.storage.s3.region = v.to_owned(), ), f( "storage.s3.endpoint", Storage, X, Ty::Text, "S3 endpoint", "Leave empty for AWS.", |c| c.storage.s3.endpoint.clone(), |c, v| c.storage.s3.endpoint = v.to_owned(), ), f( "storage.s3.prefix", Storage, X, Ty::Text, "S3 key prefix", "", |c| c.storage.s3.prefix.clone(), |c, v| c.storage.s3.prefix = v.to_owned(), ), f( "storage.s3.access_key_id", Storage, X, Ty::Text, "S3 access key id", "", |c| c.storage.s3.access_key_id.clone(), |c, v| c.storage.s3.access_key_id = v.to_owned(), ), f( "storage.s3.secret_access_key_file", Storage, X, Ty::Path, "S3 secret key file", "Path of the file that holds the secret access key.", |c| { c.storage .s3 .secret_access_key_file .to_string_lossy() .into_owned() }, |c, v| c.storage.s3.secret_access_key_file = v.into(), ), f( "storage.s3.allow_http", Storage, X, Ty::Bool, "S3 allow http", "", |c| c.storage.s3.allow_http.to_string(), |c, v| c.storage.s3.allow_http = b(v), ), f( "storage.s3.virtual_hosted_style", Storage, X, Ty::Bool, "S3 virtual hosted style", "", |c| c.storage.s3.virtual_hosted_style.to_string(), |c, v| c.storage.s3.virtual_hosted_style = b(v), ), f( "backup.dir", Backups, X, Ty::Path, "Backup directory", "Empty turns scheduled backups off.", |c| c.backup.dir.to_string_lossy().into_owned(), |c, v| c.backup.dir = v.into(), ), f( "backup.interval_hours", Backups, X, Ty::Uint(1, 8_760), "Backup interval (hours)", "", |c| c.backup.interval_hours.to_string(), |c, v| c.backup.interval_hours = n(v), ), f( "backup.keep", Backups, X, Ty::Uint(1, 10_000), "Backup sets kept", "", |c| c.backup.keep.to_string(), |c, v| c.backup.keep = n(v) as usize, ), f( "backup.fsck_interval_days", Backups, X, Ty::Uint(1, 3_650), "fsck interval (days)", "", |c| c.backup.fsck_interval_days.to_string(), |c, v| c.backup.fsck_interval_days = n(v), ), f( "backup.healthcheck_url", Backups, X, Ty::Secret, "Backup healthcheck URL", "May hold a token, so it is write-only.", |c| c.backup.healthcheck_url.clone(), |c, v| c.backup.healthcheck_url = v.to_owned(), ), f( "replication.target", Backups, X, Ty::Text, "Replication target", "Empty turns standby replication off.", |c| c.replication.target.clone(), |c, v| c.replication.target = v.to_owned(), ), f( "replication.ssh_port", Backups, X, PORT, "Replication SSH port", "", |c| c.replication.ssh_port.to_string(), |c, v| c.replication.ssh_port = n(v) as u16, ), f( "replication.identity_file", Backups, X, Ty::Path, "Replication identity file", "", |c| c.replication.identity_file.to_string_lossy().into_owned(), |c, v| c.replication.identity_file = v.into(), ), f( "replication.known_hosts_file", Backups, X, Ty::Path, "Replication known hosts file", "", |c| { c.replication .known_hosts_file .to_string_lossy() .into_owned() }, |c, v| c.replication.known_hosts_file = v.into(), ), f( "replication.db_snapshot_minutes", Backups, X, Ty::Uint(1, 525_600), "Database snapshot (minutes)", "", |c| c.replication.db_snapshot_minutes.to_string(), |c, v| c.replication.db_snapshot_minutes = n(v), ), f( "replication.reconcile_minutes", Backups, X, Ty::Uint(1, 525_600), "Reconcile (minutes)", "", |c| c.replication.reconcile_minutes.to_string(), |c, v| c.replication.reconcile_minutes = n(v), ), f( "replication.healthcheck_url", Backups, X, Ty::Secret, "Replication healthcheck URL", "May hold a token, so it is write-only.", |c| c.replication.healthcheck_url.clone(), |c, v| c.replication.healthcheck_url = v.to_owned(), ), f( "webhooks.allow_http", Integrations, X, Ty::Bool, "Allow http webhooks", "Permit http:// hook URLs besides https://.", |c| c.webhooks.allow_http.to_string(), |c, v| c.webhooks.allow_http = b(v), ), f( "webhooks.allowed_hosts", Integrations, X, Ty::List, "Webhook allowed hosts", "Hostnames or CIDR networks reachable even when they resolve to internal addresses. Comma separated.", |c| c.webhooks.allowed_hosts.join(", "), |c, v| c.webhooks.allowed_hosts = split_list(v), ), f( "mail.transport", Integrations, X, Ty::Choice(MAIL_TRANSPORT), "Mail transport", "smtp sends mail, log writes it to a directory. The SMTP account is on the Mail page.", |c| c.mail.transport.as_str().into(), |c, v| c.mail.transport = v.parse().unwrap_or_default(), ), f( "self_update.enabled", Integrations, X, Ty::Bool, "Self-update", "Deploy the artifact of a green run of the forge's own repo.", |c| c.self_update.enabled.to_string(), |c, v| c.self_update.enabled = b(v), ), f( "self_update.repo", Integrations, X, Ty::Text, "Self-update repo", "As owner/name.", |c| c.self_update.repo.clone(), |c, v| c.self_update.repo = v.to_owned(), ), f( "self_update.branch", Integrations, X, Ty::Text, "Self-update branch", "", |c| c.self_update.branch.clone(), |c, v| c.self_update.branch = v.to_owned(), ), f( "self_update.job", Integrations, X, Ty::Text, "Self-update job", "", |c| c.self_update.job.clone(), |c, v| c.self_update.job = v.to_owned(), ), f( "self_update.artifact", Integrations, X, Ty::Text, "Self-update artifact", "{target} becomes this server's arch-os, e.g. forge-{target} is forge-x86_64-linux.", |c| c.self_update.artifact.clone(), |c, v| c.self_update.artifact = v.to_owned(), ), f( "alerts.enabled", Alerts, L, Ty::Bool, "Admin alerts", "Master switch. Off raises and sends nothing.", |c| c.alerts.enabled.to_string(), |c, v| c.alerts.enabled = b(v), ), f( "alerts.email", Alerts, L, Ty::Bool, "Email alerts", "Also email the admins who have a verified address.", |c| c.alerts.email.to_string(), |c, v| c.alerts.email = b(v), ), f( "alerts.runner_offline_minutes", Alerts, L, Ty::Uint(1, 1_440), "Runner offline after (minutes)", "A runner with no heartbeat for this long raises an alert.", |c| c.alerts.runner_offline_minutes.to_string(), |c, v| c.alerts.runner_offline_minutes = n(v), ), f( "alerts.disk_free_percent", Alerts, L, Ty::Uint(1, 90), "Low disk space (percent free)", "Alert when the data directory has less than this free.", |c| c.alerts.disk_free_percent.to_string(), |c, v| c.alerts.disk_free_percent = n(v), ), f( "alerts.disk_free_gib", Alerts, L, Ty::Uint(0, 100_000), "Low disk space (GiB free)", "Also alert under this many GiB. 0 turns this check off.", |c| c.alerts.disk_free_gib.to_string(), |c, v| c.alerts.disk_free_gib = n(v), ), f( "alerts.on_runner_offline", Alerts, L, Ty::Bool, "Runner offline alerts", "", |c| c.alerts.on_runner_offline.to_string(), |c, v| c.alerts.on_runner_offline = b(v), ), f( "alerts.on_backup", Alerts, L, Ty::Bool, "Backup alerts", "Failed, unverified or overdue backups, and failed fsck runs.", |c| c.alerts.on_backup.to_string(), |c, v| c.alerts.on_backup = b(v), ), f( "alerts.on_disk", Alerts, L, Ty::Bool, "Disk space alerts", "", |c| c.alerts.on_disk.to_string(), |c, v| c.alerts.on_disk = b(v), ), f( "alerts.on_ci_killed", Alerts, L, Ty::Bool, "Killed CI job alerts", "Jobs killed by SIGKILL or the OOM killer, once per run.", |c| c.alerts.on_ci_killed.to_string(), |c, v| c.alerts.on_ci_killed = b(v), ), f( "alerts.on_self_update", Alerts, L, Ty::Bool, "Self-update alerts", "Deployed, failed, and server restarted.", |c| c.alerts.on_self_update.to_string(), |c, v| c.alerts.on_self_update = b(v), ), f( "alerts.on_replication", Alerts, L, Ty::Bool, "Replication alerts", "Standby failing or lagging.", |c| c.alerts.on_replication.to_string(), |c, v| c.alerts.on_replication = b(v), ), ]; pub fn field(key: &str) -> Option<&'static Field> { FIELDS.iter().find(|f| f.key == key) } fn invalid(field: &Field, why: &str) -> Error { Error::Invalid(format!("{}: {why}", field.label)) } fn split_list(raw: &str) -> Vec { raw.split([',', '\n', '\r']) .map(str::trim) .filter(|s| !s.is_empty()) .map(str::to_owned) .collect() } pub fn normalize(field: &Field, raw: &str) -> Result { let raw = raw.trim(); match field.ty { Ty::Bool => match raw { "true" | "on" => Ok("true".into()), "false" | "off" | "" => Ok("false".into()), _ => Err(invalid(field, "must be on or off")), }, Ty::Uint(min, max) => { let n: u64 = raw .parse() .map_err(|_| invalid(field, "must be a whole number"))?; if n < min || n > max { return Err(invalid(field, &format!("must be between {min} and {max}"))); } Ok(n.to_string()) } Ty::Choice(options) => { if options.contains(&raw) { Ok(raw.to_owned()) } else { let shown: Vec<&str> = options .iter() .map(|o| if o.is_empty() { "(empty)" } else { o }) .collect(); Err(invalid( field, &format!("must be one of {}", shown.join(", ")), )) } } Ty::Text | Ty::Path | Ty::Secret | Ty::Addr => { if raw.len() > 1024 || raw.chars().any(char::is_control) { return Err(invalid( field, "must be one line of at most 1024 characters", )); } if let Some(why) = (field.check)(raw) { return Err(invalid(field, &why)); } Ok(raw.to_owned()) } Ty::List => { let items = split_list(raw); if items .iter() .any(|i| i.len() > 253 || i.chars().any(char::is_control)) { return Err(invalid(field, "has an entry that is too long")); } if let Some(why) = (field.check)(raw) { return Err(invalid(field, &why)); } Ok(items.join(", ")) } } } fn b(v: &str) -> bool { v == "true" } fn n(v: &str) -> u64 { v.parse().unwrap_or_default() } pub fn get(cfg: &Config, key: &str) -> String { field(key).map_or_else(String::new, |f| (f.get)(cfg)) } pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { let field = field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?; if field.kind == Kind::ReadOnly { return Err(invalid(field, "is read-only")); } let v = normalize(field, raw)?; (field.set)(cfg, &v); Ok(()) } pub fn apply(file: &Config, overrides: &BTreeMap) -> Result { let mut cfg = file.clone(); for (key, value) in overrides { if field(key).is_some_and(|f| f.kind != Kind::ReadOnly) { set(&mut cfg, key, value)?; } } Ok(cfg) } pub fn boot_config(file: &Config, overrides: &BTreeMap) -> (Config, Option) { match apply(file, overrides).and_then(|c| c.validate().map(|()| c)) { Ok(config) => (config, None), Err(e) => (file.clone(), Some(e)), } } pub fn live_view(boot: &Config, pending: &Config) -> Config { let mut cfg = boot.clone(); for f in FIELDS.iter().filter(|f| f.kind == Kind::Live) { let _ = set(&mut cfg, f.key, &get(pending, f.key)); } cfg } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Source { Default, File, Ui, } #[derive(Debug, Clone)] pub struct FieldView { pub field: &'static Field, pub value: String, pub file_value: String, pub source: Source, pub secret_set: bool, pub restart_pending: bool, } pub struct Live { file: Arc, file_keys: BTreeSet, boot: Arc, current: RwLock>, } impl Live { pub fn new(file: Arc, file_keys: BTreeSet, boot: Arc) -> Live { Live { current: RwLock::new(boot.clone()), file, file_keys, boot, } } pub fn current(&self) -> Arc { self.current .read() .unwrap_or_else(|poisoned| poisoned.into_inner()) .clone() } pub fn publish(&self, overrides: &BTreeMap) -> Result<()> { let pending = apply(&self.file, overrides)?; pending.validate()?; let live = live_view(&self.boot, &pending); *self .current .write() .unwrap_or_else(|poisoned| poisoned.into_inner()) = Arc::new(live); Ok(()) } pub fn views(&self, overrides: &BTreeMap) -> Vec { let pending = apply(&self.file, overrides).unwrap_or_else(|_| (*self.file).clone()); FIELDS .iter() .map(|field| { let secret = field.is_secret(); let shown = |cfg: &Config| { if secret { String::new() } else { get(cfg, field.key) } }; let editable = field.kind != Kind::ReadOnly; let source = if editable && overrides.contains_key(field.key) { Source::Ui } else if self.file_keys.contains(field.key) { Source::File } else { Source::Default }; let effective = if editable { &pending } else { &*self.boot }; FieldView { field, value: shown(effective), file_value: shown(&self.file), source, secret_set: secret && !get(effective, field.key).is_empty(), restart_pending: field.kind == Kind::Restart && get(&pending, field.key) != get(&self.boot, field.key), } }) .collect() } pub fn plan_save( &self, existing: &BTreeMap, group: Group, submitted: &BTreeMap, ) -> Result { let before = apply(&self.file, existing)?; let mut sets = Vec::new(); let mut clears = Vec::new(); let mut next = existing.clone(); for field in FIELDS .iter() .filter(|f| f.group == group && f.kind != Kind::ReadOnly) { let Some(raw) = submitted.get(field.key) else { continue; }; if field.is_secret() && raw.trim().is_empty() { continue; } let value = normalize(field, raw)?; if field.is_secret() { sets.push((field.key.to_owned(), value.clone())); next.insert(field.key.to_owned(), value); continue; } let has_override = existing.contains_key(field.key); if value == get(&before, field.key) { continue; } if value == get(&self.file, field.key) { if has_override { clears.push(field.key.to_owned()); next.remove(field.key); } continue; } sets.push((field.key.to_owned(), value.clone())); next.insert(field.key.to_owned(), value); } let pending = apply(&self.file, &next)?; pending.validate()?; Ok(SavePlan { sets, clears, overrides: next, }) } pub fn plan_reset( &self, existing: &BTreeMap, key: &str, ) -> Result> { field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?; let mut next = existing.clone(); next.remove(key); apply(&self.file, &next)?.validate()?; Ok(next) } } #[derive(Debug)] pub struct SavePlan { pub sets: Vec<(String, String)>, pub clears: Vec, pub overrides: BTreeMap, } #[cfg(test)] mod tests { use super::*; fn base() -> Config { toml::from_str( r#" database = "/tmp/f.db" data_dir = "/tmp" listen = "127.0.0.1:1" base_url = "http://x" user_content_base_url = "http://y" ssh_listen = "127.0.0.1:2" ssh_public_host = "h" ssh_public_port = 22 registration = "closed" [ci] max_log_mb = 20 "#, ) .expect("config") } fn live() -> Live { let file = Arc::new(base()); let keys = ["registration", "ci.max_log_mb"] .into_iter() .map(String::from) .collect(); Live::new(file.clone(), keys, file) } fn form(pairs: &[(&str, &str)]) -> BTreeMap { pairs .iter() .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) .collect() } #[test] fn every_field_round_trips_through_get_and_set() { let cfg = base(); for f in FIELDS.iter().filter(|f| f.kind != Kind::ReadOnly) { let mut copy = cfg.clone(); set(&mut copy, f.key, &get(&cfg, f.key)).unwrap_or_else(|e| panic!("{}: {e}", f.key)); assert_eq!(get(©, f.key), get(&cfg, f.key), "{}", f.key); } } #[test] fn precedence_ui_over_file_over_default() { let live = live(); let views = live.views(&BTreeMap::new()); let find = |views: &[FieldView], key: &str| { views.iter().find(|v| v.field.key == key).cloned().unwrap() }; assert_eq!(find(&views, "ci.max_log_mb").source, Source::File); assert_eq!(find(&views, "ci.max_log_mb").value, "20"); assert_eq!(find(&views, "ci.max_artifact_mb").source, Source::Default); assert_eq!(find(&views, "ci.max_artifact_mb").value, "512"); let over = form(&[("ci.max_log_mb", "99")]); let views = live.views(&over); let v = find(&views, "ci.max_log_mb"); assert_eq!( (v.source, v.value.as_str(), v.file_value.as_str()), (Source::Ui, "99", "20") ); } #[test] fn live_fields_apply_and_reset_restores_the_file_value() { let live = live(); assert_eq!(live.current().ci.max_log_mb, 20); live.publish(&form(&[("ci.max_log_mb", "99"), ("registration", "open")])) .unwrap(); assert_eq!(live.current().ci.max_log_mb, 99); assert_eq!(live.current().registration, Registration::Open); let next = live .plan_reset(&form(&[("ci.max_log_mb", "99")]), "ci.max_log_mb") .unwrap(); live.publish(&next).unwrap(); assert_eq!(live.current().ci.max_log_mb, 20); } #[test] fn restart_fields_do_not_apply_until_boot() { let live = live(); let over = form(&[("base_url", "https://new.example")]); live.publish(&over).unwrap(); assert_eq!(live.current().base_url, "http://x"); let v = live.views(&over); let v = v.iter().find(|v| v.field.key == "base_url").unwrap(); assert!(v.restart_pending); let (boot, err) = boot_config(&base(), &over); assert!(err.is_none()); assert_eq!(boot.base_url, "https://new.example"); let after = Live::new(Arc::new(base()), Default::default(), Arc::new(boot)); assert!(!after.views(&over).iter().any(|v| v.restart_pending)); } #[test] fn validation_rejects_bad_values() { let live = live(); for (key, value) in [ ("registration", "everyone"), ("ci.max_log_mb", "0"), ("ci.max_log_mb", "lots"), ("trusted_proxies", "not-an-ip"), ("ssh_public_port", "70000"), ("storage.r2.jurisdiction", "mars"), ("listen", "0.0.0.0:1"), ] { let mut cfg = base(); assert!(set(&mut cfg, key, value).is_err(), "{key}={value}"); } let group_form = form(&[("storage.backend", "r2")]); assert!( live.plan_save(&BTreeMap::new(), Group::Storage, &group_form) .is_err() ); let group_form = form(&[("backup.dir", "/var/backups"), ("backup.keep", "5")]); assert!( live.plan_save(&BTreeMap::new(), Group::Backups, &group_form) .is_ok() ); } #[test] fn save_skips_unchanged_values_and_clears_when_back_at_the_file_value() { let live = live(); let plan = live .plan_save( &BTreeMap::new(), Group::Limits, &form(&[ ("ci.max_log_mb", "20"), ("ci.max_artifact_mb", "512"), ("ci.enabled", "false"), ]), ) .unwrap(); assert_eq!( plan.sets, vec![("ci.enabled".to_owned(), "false".to_owned())] ); let existing = form(&[("ci.max_log_mb", "99")]); let plan = live .plan_save(&existing, Group::Limits, &form(&[("ci.max_log_mb", "20")])) .unwrap(); assert_eq!(plan.clears, vec!["ci.max_log_mb".to_owned()]); assert!(plan.overrides.is_empty()); } #[test] fn secrets_are_never_in_a_view_and_blank_keeps_the_stored_value() { let live = live(); let existing = form(&[("backup.healthcheck_url", "https://hc.example/token-123")]); let views = live.views(&existing); let v = views .iter() .find(|v| v.field.key == "backup.healthcheck_url") .unwrap(); assert!(v.secret_set && v.value.is_empty() && v.file_value.is_empty()); let plan = live .plan_save( &existing, Group::Backups, &form(&[("backup.healthcheck_url", "")]), ) .unwrap(); assert!(plan.sets.is_empty()); assert_eq!(plan.overrides, existing); for view in &views { assert!(!view.value.contains("token-123")); } } }