//! Admin-editable server settings, layered on the config file. //! //! Precedence per field: a UI override (table `server_settings`), then the config file, then the //! built-in default. The config file is never rewritten. Every field has a [`Kind`]: //! //! - `Live`: applied to the running process at once. Consumers read [`Live::current`]. //! - `Restart`: saved and shown as pending until the process restarts. Boot layers the stored //! overrides on the file config, so they take effect then. //! - `ReadOnly`: shown, never editable (listen addresses, database path, data dir). //! //! A secret field is write-only: the page shows whether it is set, never the value, and the stored //! value is sealed with the instance key. //! //! Values travel as canonical strings (`true`, `42`, `a, b`) so one table holds every field and a //! new field needs no migration. [`get`] and [`set`] convert between those strings and [`Config`]. use std::collections::{BTreeMap, BTreeSet}; use std::net::IpAddr; use std::sync::{Arc, RwLock}; use ipnet::IpNet; use crate::config::{Config, MailTransport, OrgCreation, Registration, StorageBackend}; use crate::error::{Error, Result}; /// How a field reaches the running process. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { Live, Restart, ReadOnly, } /// The page tab a field belongs to. #[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, ]; pub fn slug(self) -> &'static str { match self { Group::General => "general", Group::Limits => "limits", Group::Storage => "storage", Group::Backups => "backups", Group::Integrations => "integrations", Group::Alerts => "alerts", } } pub fn parse(slug: &str) -> Option { Group::ALL.into_iter().find(|g| g.slug() == slug) } } /// The value type of a field, which decides the input and the server-side check. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Ty { Bool, /// Whole number in `min..=max`. Uint(u64, u64), Text, /// A filesystem path. Empty is allowed and usually means "off". Path, Choice(&'static [&'static str]), /// Comma separated entries. List, /// Write-only text. Secret, /// Socket address (read-only fields only). 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, } impl Field { pub fn is_secret(&self) -> bool { self.ty == Ty::Secret } } const fn f( key: &'static str, group: Group, kind: Kind, ty: Ty, label: &'static str, help: &'static str, ) -> Field { Field { key, group, kind, ty, label, help, } } use Group::{Alerts, Backups, General, Integrations, Limits, Storage}; use Kind::{Live as L, ReadOnly as R, Restart as X}; const REGISTRATION: &[&str] = &["closed", "invite", "open"]; const BANNER_LEVEL: &[&str] = &["info", "warning"]; const ORG_CREATION: &[&str] = &["all", "admin"]; const MAIL_TRANSPORT: &[&str] = &["smtp", "log"]; const BACKEND: &[&str] = &["fs", "s3", "r2"]; const JURISDICTION: &[&str] = &["", "eu", "fedramp"]; const MB: Ty = Ty::Uint(1, 1_048_576); const PORT: Ty = Ty::Uint(1, 65_535); /// Every setting, in display order. pub static FIELDS: &[Field] = &[ f( "registration", General, L, Ty::Choice(REGISTRATION), "Registration", "Who may create an account: closed, invite only, or open.", ), f( "orgs.creation", General, L, Ty::Choice(ORG_CREATION), "Organization creation", "Who may create an organization: all signed-in people, or admins only.", ), f( "banner.message", General, L, Ty::Text, "Announcement banner", "One line shown under the header on every page. Empty hides it.", ), f( "banner.level", General, L, Ty::Choice(BANNER_LEVEL), "Banner level", "info or warning.", ), f( "banner.expires", General, L, Ty::Text, "Banner expires (UTC)", "As YYYY-MM-DD HH:MM. Empty keeps the banner until it is cleared.", ), f( "trusted_proxies", General, L, Ty::List, "Trusted proxies", "Addresses or CIDR networks whose X-Forwarded-For header is trusted. Comma separated.", ), f( "base_url", General, X, Ty::Text, "Base URL", "Public URL used in links and clone URLs.", ), f( "user_content_base_url", General, X, Ty::Text, "User content URL", "Separate origin that serves raw user files.", ), f( "ssh_public_host", General, X, Ty::Text, "SSH host shown", "Host in SSH clone URLs.", ), f( "ssh_public_port", General, X, PORT, "SSH port shown", "Port in SSH clone URLs.", ), f( "listen", General, R, Ty::Addr, "HTTP listen address", "Set in the config file.", ), f( "user_content_listen", General, R, Ty::Addr, "User content listen address", "Set in the config file.", ), f( "ssh_listen", General, R, Ty::Addr, "SSH listen address", "Set in the config file.", ), f( "database", General, R, Ty::Path, "Database file", "Set in the config file.", ), f( "data_dir", General, R, Ty::Path, "Data directory", "Set in the config file.", ), f( "ci.enabled", Limits, L, Ty::Bool, "CI enabled", "When off, pushes and pull requests create no runs.", ), f( "ci.max_log_mb", Limits, L, MB, "Largest job log (MiB)", "A longer log is truncated.", ), f( "ci.max_artifact_mb", Limits, L, MB, "Largest artifact (MiB)", "", ), f( "ci.max_artifacts_per_job", Limits, L, Ty::Uint(1, 100_000), "Artifacts per job", "", ), f( "ci.log_retention_days", Limits, L, Ty::Uint(1, 36_500), "Log retention (days)", "", ), f( "ci.artifact_retention_days", Limits, L, Ty::Uint(1, 36_500), "Artifact retention (days)", "", ), f( "ci.registration_token_hours", Limits, L, Ty::Uint(1, 8_760), "Runner token lifetime (hours)", "How long a runner registration token stays valid.", ), f( "lfs.max_object_mb", Limits, L, MB, "Largest LFS object (MiB)", "", ), f( "releases.max_asset_mb", Limits, L, MB, "Largest release asset (MiB)", "", ), f( "storage.backend", Storage, X, Ty::Choice(BACKEND), "Backend", "Where release assets and CI artifacts live: fs, r2 or s3.", ), f( "storage.r2.account_id", Storage, X, Ty::Text, "R2 account id", "32 character hex string from the Cloudflare dashboard.", ), f("storage.r2.bucket", Storage, X, Ty::Text, "R2 bucket", ""), f( "storage.r2.jurisdiction", Storage, X, Ty::Choice(JURISDICTION), "R2 jurisdiction", "eu, fedramp, or empty for the global default.", ), f( "storage.r2.prefix", Storage, X, Ty::Text, "R2 key prefix", "", ), f( "storage.r2.access_key_id", Storage, X, Ty::Text, "R2 access key id", "", ), 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.", ), f("storage.s3.bucket", Storage, X, Ty::Text, "S3 bucket", ""), f("storage.s3.region", Storage, X, Ty::Text, "S3 region", ""), f( "storage.s3.endpoint", Storage, X, Ty::Text, "S3 endpoint", "Leave empty for AWS.", ), f( "storage.s3.prefix", Storage, X, Ty::Text, "S3 key prefix", "", ), f( "storage.s3.access_key_id", Storage, X, Ty::Text, "S3 access key id", "", ), 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.", ), f( "storage.s3.allow_http", Storage, X, Ty::Bool, "S3 allow http", "", ), f( "storage.s3.virtual_hosted_style", Storage, X, Ty::Bool, "S3 virtual hosted style", "", ), f( "backup.dir", Backups, X, Ty::Path, "Backup directory", "Empty turns scheduled backups off.", ), f( "backup.interval_hours", Backups, X, Ty::Uint(1, 8_760), "Backup interval (hours)", "", ), f( "backup.keep", Backups, X, Ty::Uint(1, 10_000), "Backup sets kept", "", ), f( "backup.fsck_interval_days", Backups, X, Ty::Uint(1, 3_650), "fsck interval (days)", "", ), f( "backup.healthcheck_url", Backups, X, Ty::Secret, "Backup healthcheck URL", "May hold a token, so it is write-only.", ), f( "replication.target", Backups, X, Ty::Text, "Replication target", "Empty turns standby replication off.", ), f( "replication.ssh_port", Backups, X, PORT, "Replication SSH port", "", ), f( "replication.identity_file", Backups, X, Ty::Path, "Replication identity file", "", ), f( "replication.known_hosts_file", Backups, X, Ty::Path, "Replication known hosts file", "", ), f( "replication.db_snapshot_minutes", Backups, X, Ty::Uint(1, 525_600), "Database snapshot (minutes)", "", ), f( "replication.reconcile_minutes", Backups, X, Ty::Uint(1, 525_600), "Reconcile (minutes)", "", ), f( "replication.healthcheck_url", Backups, X, Ty::Secret, "Replication healthcheck URL", "May hold a token, so it is write-only.", ), f( "webhooks.allow_http", Integrations, X, Ty::Bool, "Allow http webhooks", "Permit http:// hook URLs besides https://.", ), 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.", ), 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.", ), f( "advisories.enabled", Integrations, X, Ty::Bool, "Security advisories", "Download OSV dumps and scan lockfiles.", ), f( "advisories.ecosystems", Integrations, X, Ty::List, "Advisory ecosystems", "Any of crates.io, npm, Go. Comma separated.", ), f( "advisories.refresh_hours", Integrations, X, Ty::Uint(1, 8_760), "Advisory refresh (hours)", "", ), f( "self_update.enabled", Integrations, X, Ty::Bool, "Self-update", "Deploy the artifact of a green run of the forge's own repo.", ), f( "self_update.repo", Integrations, X, Ty::Text, "Self-update repo", "As owner/name.", ), f( "self_update.branch", Integrations, X, Ty::Text, "Self-update branch", "", ), f( "self_update.job", Integrations, X, Ty::Text, "Self-update job", "", ), f( "self_update.artifact", Integrations, X, Ty::Text, "Self-update artifact", "", ), f( "alerts.enabled", Alerts, L, Ty::Bool, "Admin alerts", "Master switch. Off raises and sends nothing.", ), f( "alerts.email", Alerts, L, Ty::Bool, "Email alerts", "Also email the admins who have a verified address.", ), 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.", ), 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.", ), 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.", ), f( "alerts.on_runner_offline", Alerts, L, Ty::Bool, "Runner offline alerts", "", ), f( "alerts.on_backup", Alerts, L, Ty::Bool, "Backup alerts", "Failed, unverified or overdue backups, and failed fsck runs.", ), f( "alerts.on_disk", Alerts, L, Ty::Bool, "Disk space alerts", "", ), f( "alerts.on_ci_killed", Alerts, L, Ty::Bool, "Killed CI job alerts", "Jobs killed by SIGKILL or the OOM killer, once per run.", ), f( "alerts.on_self_update", Alerts, L, Ty::Bool, "Self-update alerts", "Deployed, failed, and server restarted.", ), f( "alerts.on_replication", Alerts, L, Ty::Bool, "Replication alerts", "Standby failing or lagging.", ), ]; /// The field for a dotted key. 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() } /// Checks `raw` against the field's type and returns its canonical string. 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 field.key == "banner.expires" && !raw.is_empty() && crate::config::parse_banner_expiry(raw).is_none() { return Err(invalid(field, "must look like 2026-12-31 18:00")); } if field.key == "banner.message" && raw.chars().count() > 300 { return Err(invalid(field, "must be at most 300 characters")); } 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 field.key == "trusted_proxies" { for item in &items { if item.parse::().is_err() && item.parse::().is_err() { return Err(invalid(field, &format!("invalid trusted proxy `{item}`"))); } } } if field.key == "advisories.ecosystems" { for item in &items { if !matches!(item.as_str(), "crates.io" | "npm" | "Go") { return Err(invalid(field, &format!("unknown ecosystem `{item}`"))); } } } Ok(items.join(", ")) } } } fn b(v: &str) -> bool { v == "true" } fn n(v: &str) -> u64 { v.parse().unwrap_or_default() } fn choice(v: &str, table: &[(&str, T)], fallback: T) -> T { table .iter() .find(|(name, _)| *name == v) .map_or(fallback, |(_, t)| *t) } fn backend_name(b: StorageBackend) -> &'static str { match b { StorageBackend::Fs => "fs", StorageBackend::S3 => "s3", StorageBackend::R2 => "r2", } } /// The canonical string of a field's value in `cfg`. Secrets return their real value, so callers /// that render must not call this for a secret field. pub fn get(cfg: &Config, key: &str) -> String { let path = |p: &std::path::Path| p.to_string_lossy().into_owned(); let list = |v: &[String]| v.join(", "); match key { "registration" => match cfg.registration { Registration::Closed => "closed", Registration::Invite => "invite", Registration::Open => "open", } .into(), "orgs.creation" => match cfg.orgs.creation { OrgCreation::All => "all", OrgCreation::Admin => "admin", } .into(), "trusted_proxies" => cfg .trusted_proxies .iter() .map(ToString::to_string) .collect::>() .join(", "), "banner.message" => cfg.banner.message.clone(), "banner.level" => cfg.banner.level.clone(), "banner.expires" => cfg.banner.expires.clone(), "alerts.enabled" => cfg.alerts.enabled.to_string(), "alerts.email" => cfg.alerts.email.to_string(), "alerts.runner_offline_minutes" => cfg.alerts.runner_offline_minutes.to_string(), "alerts.disk_free_percent" => cfg.alerts.disk_free_percent.to_string(), "alerts.disk_free_gib" => cfg.alerts.disk_free_gib.to_string(), "alerts.on_runner_offline" => cfg.alerts.on_runner_offline.to_string(), "alerts.on_backup" => cfg.alerts.on_backup.to_string(), "alerts.on_disk" => cfg.alerts.on_disk.to_string(), "alerts.on_ci_killed" => cfg.alerts.on_ci_killed.to_string(), "alerts.on_self_update" => cfg.alerts.on_self_update.to_string(), "alerts.on_replication" => cfg.alerts.on_replication.to_string(), "base_url" => cfg.base_url.clone(), "user_content_base_url" => cfg.user_content_base_url.clone(), "ssh_public_host" => cfg.ssh_public_host.clone(), "ssh_public_port" => cfg.ssh_public_port.to_string(), "listen" => cfg.listen.to_string(), "user_content_listen" => cfg.user_content_listen.to_string(), "ssh_listen" => cfg.ssh_listen.to_string(), "database" => path(&cfg.database), "data_dir" => path(&cfg.data_dir), "ci.enabled" => cfg.ci.enabled.to_string(), "ci.max_log_mb" => cfg.ci.max_log_mb.to_string(), "ci.max_artifact_mb" => cfg.ci.max_artifact_mb.to_string(), "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job.to_string(), "ci.log_retention_days" => cfg.ci.log_retention_days.to_string(), "ci.artifact_retention_days" => cfg.ci.artifact_retention_days.to_string(), "ci.registration_token_hours" => cfg.ci.registration_token_hours.to_string(), "lfs.max_object_mb" => cfg.lfs.max_object_mb.to_string(), "releases.max_asset_mb" => cfg.releases.max_asset_mb.to_string(), "storage.backend" => backend_name(cfg.storage.backend).into(), "storage.r2.account_id" => cfg.storage.r2.account_id.clone(), "storage.r2.bucket" => cfg.storage.r2.bucket.clone(), "storage.r2.jurisdiction" => cfg.storage.r2.jurisdiction.clone(), "storage.r2.prefix" => cfg.storage.r2.prefix.clone(), "storage.r2.access_key_id" => cfg.storage.r2.access_key_id.clone(), "storage.r2.secret_access_key_file" => path(&cfg.storage.r2.secret_access_key_file), "storage.s3.bucket" => cfg.storage.s3.bucket.clone(), "storage.s3.region" => cfg.storage.s3.region.clone(), "storage.s3.endpoint" => cfg.storage.s3.endpoint.clone(), "storage.s3.prefix" => cfg.storage.s3.prefix.clone(), "storage.s3.access_key_id" => cfg.storage.s3.access_key_id.clone(), "storage.s3.secret_access_key_file" => path(&cfg.storage.s3.secret_access_key_file), "storage.s3.allow_http" => cfg.storage.s3.allow_http.to_string(), "storage.s3.virtual_hosted_style" => cfg.storage.s3.virtual_hosted_style.to_string(), "backup.dir" => path(&cfg.backup.dir), "backup.interval_hours" => cfg.backup.interval_hours.to_string(), "backup.keep" => cfg.backup.keep.to_string(), "backup.fsck_interval_days" => cfg.backup.fsck_interval_days.to_string(), "backup.healthcheck_url" => cfg.backup.healthcheck_url.clone(), "replication.target" => cfg.replication.target.clone(), "replication.ssh_port" => cfg.replication.ssh_port.to_string(), "replication.identity_file" => path(&cfg.replication.identity_file), "replication.known_hosts_file" => path(&cfg.replication.known_hosts_file), "replication.db_snapshot_minutes" => cfg.replication.db_snapshot_minutes.to_string(), "replication.reconcile_minutes" => cfg.replication.reconcile_minutes.to_string(), "replication.healthcheck_url" => cfg.replication.healthcheck_url.clone(), "webhooks.allow_http" => cfg.webhooks.allow_http.to_string(), "webhooks.allowed_hosts" => list(&cfg.webhooks.allowed_hosts), "mail.transport" => match cfg.mail.transport { MailTransport::Smtp => "smtp", MailTransport::Log => "log", } .into(), "advisories.enabled" => cfg.advisories.enabled.to_string(), "advisories.ecosystems" => list(&cfg.advisories.ecosystems), "advisories.refresh_hours" => cfg.advisories.refresh_hours.to_string(), "self_update.enabled" => cfg.self_update.enabled.to_string(), "self_update.repo" => cfg.self_update.repo.clone(), "self_update.branch" => cfg.self_update.branch.clone(), "self_update.job" => cfg.self_update.job.clone(), "self_update.artifact" => cfg.self_update.artifact.clone(), _ => String::new(), } } /// Checks `raw` and stores it into `cfg`. A read-only or unknown key is refused. 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)?; let v = v.as_str(); let p = || std::path::PathBuf::from(v); let s = || v.to_owned(); match key { "registration" => { cfg.registration = choice( v, &[ ("closed", Registration::Closed), ("invite", Registration::Invite), ("open", Registration::Open), ], Registration::Closed, ) } "orgs.creation" => { cfg.orgs.creation = choice( v, &[("all", OrgCreation::All), ("admin", OrgCreation::Admin)], OrgCreation::All, ) } "trusted_proxies" => { cfg.trusted_proxies = split_list(v) .iter() .filter_map(|e| { e.parse::() .ok() .or_else(|| e.parse::().ok().map(IpNet::from)) }) .collect() } "banner.message" => cfg.banner.message = s(), "banner.level" => cfg.banner.level = s(), "banner.expires" => cfg.banner.expires = s(), "alerts.enabled" => cfg.alerts.enabled = b(v), "alerts.email" => cfg.alerts.email = b(v), "alerts.runner_offline_minutes" => cfg.alerts.runner_offline_minutes = n(v), "alerts.disk_free_percent" => cfg.alerts.disk_free_percent = n(v), "alerts.disk_free_gib" => cfg.alerts.disk_free_gib = n(v), "alerts.on_runner_offline" => cfg.alerts.on_runner_offline = b(v), "alerts.on_backup" => cfg.alerts.on_backup = b(v), "alerts.on_disk" => cfg.alerts.on_disk = b(v), "alerts.on_ci_killed" => cfg.alerts.on_ci_killed = b(v), "alerts.on_self_update" => cfg.alerts.on_self_update = b(v), "alerts.on_replication" => cfg.alerts.on_replication = b(v), "base_url" => cfg.base_url = s(), "user_content_base_url" => cfg.user_content_base_url = s(), "ssh_public_host" => cfg.ssh_public_host = s(), "ssh_public_port" => cfg.ssh_public_port = n(v) as u16, "ci.enabled" => cfg.ci.enabled = b(v), "ci.max_log_mb" => cfg.ci.max_log_mb = n(v), "ci.max_artifact_mb" => cfg.ci.max_artifact_mb = n(v), "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job = n(v) as u32, "ci.log_retention_days" => cfg.ci.log_retention_days = n(v), "ci.artifact_retention_days" => cfg.ci.artifact_retention_days = n(v), "ci.registration_token_hours" => cfg.ci.registration_token_hours = n(v) as u32, "lfs.max_object_mb" => cfg.lfs.max_object_mb = n(v), "releases.max_asset_mb" => cfg.releases.max_asset_mb = n(v), "storage.backend" => { cfg.storage.backend = choice( v, &[ ("fs", StorageBackend::Fs), ("s3", StorageBackend::S3), ("r2", StorageBackend::R2), ], StorageBackend::Fs, ) } "storage.r2.account_id" => cfg.storage.r2.account_id = s(), "storage.r2.bucket" => cfg.storage.r2.bucket = s(), "storage.r2.jurisdiction" => cfg.storage.r2.jurisdiction = s(), "storage.r2.prefix" => cfg.storage.r2.prefix = s(), "storage.r2.access_key_id" => cfg.storage.r2.access_key_id = s(), "storage.r2.secret_access_key_file" => cfg.storage.r2.secret_access_key_file = p(), "storage.s3.bucket" => cfg.storage.s3.bucket = s(), "storage.s3.region" => cfg.storage.s3.region = s(), "storage.s3.endpoint" => cfg.storage.s3.endpoint = s(), "storage.s3.prefix" => cfg.storage.s3.prefix = s(), "storage.s3.access_key_id" => cfg.storage.s3.access_key_id = s(), "storage.s3.secret_access_key_file" => cfg.storage.s3.secret_access_key_file = p(), "storage.s3.allow_http" => cfg.storage.s3.allow_http = b(v), "storage.s3.virtual_hosted_style" => cfg.storage.s3.virtual_hosted_style = b(v), "backup.dir" => cfg.backup.dir = p(), "backup.interval_hours" => cfg.backup.interval_hours = n(v), "backup.keep" => cfg.backup.keep = n(v) as usize, "backup.fsck_interval_days" => cfg.backup.fsck_interval_days = n(v), "backup.healthcheck_url" => cfg.backup.healthcheck_url = s(), "replication.target" => cfg.replication.target = s(), "replication.ssh_port" => cfg.replication.ssh_port = n(v) as u16, "replication.identity_file" => cfg.replication.identity_file = p(), "replication.known_hosts_file" => cfg.replication.known_hosts_file = p(), "replication.db_snapshot_minutes" => cfg.replication.db_snapshot_minutes = n(v), "replication.reconcile_minutes" => cfg.replication.reconcile_minutes = n(v), "replication.healthcheck_url" => cfg.replication.healthcheck_url = s(), "webhooks.allow_http" => cfg.webhooks.allow_http = b(v), "webhooks.allowed_hosts" => cfg.webhooks.allowed_hosts = split_list(v), "mail.transport" => { cfg.mail.transport = choice( v, &[("smtp", MailTransport::Smtp), ("log", MailTransport::Log)], MailTransport::Smtp, ) } "advisories.enabled" => cfg.advisories.enabled = b(v), "advisories.ecosystems" => cfg.advisories.ecosystems = split_list(v), "advisories.refresh_hours" => cfg.advisories.refresh_hours = n(v), "self_update.enabled" => cfg.self_update.enabled = b(v), "self_update.repo" => cfg.self_update.repo = s(), "self_update.branch" => cfg.self_update.branch = s(), "self_update.job" => cfg.self_update.job = s(), "self_update.artifact" => cfg.self_update.artifact = s(), _ => return Err(Error::Invalid(format!("unknown setting `{key}`"))), } Ok(()) } /// `file` with every override applied. Read-only keys in `overrides` are ignored. Does not /// validate the result; see [`Config::validate`]. 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) } /// The config boot runs with: the file plus every stored override. If that combination no longer /// validates (say the file changed under an override), the overrides are dropped and the error is /// returned beside the file config so the caller can log it. 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)), } } /// `boot` with the `Live` fields taken from `pending`: what the running process uses. 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) { // Values from `get` always pass `normalize`, so this cannot fail. let _ = set(&mut cfg, f.key, &get(pending, f.key)); } cfg } /// Where a field's effective value comes from. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Source { Default, File, Ui, } /// One field as the page shows it. #[derive(Debug, Clone)] pub struct FieldView { pub field: &'static Field, /// Effective value. Empty for a secret. pub value: String, /// The value the file (or default) gives. Empty for a secret. pub file_value: String, pub source: Source, /// For a secret: whether a value is set. pub secret_set: bool, /// Saved but not yet running: a restart field whose value differs from the running one. pub restart_pending: bool, } /// The process-wide settings handle: the file config, the config boot ran with, and the live view /// consumers read. 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, } } /// The config the running process uses right now. pub fn current(&self) -> Arc { self.current .read() .unwrap_or_else(|poisoned| poisoned.into_inner()) .clone() } pub fn file(&self) -> &Config { &self.file } pub fn boot(&self) -> &Config { &self.boot } /// Validates `file + overrides`, then publishes its live fields. Nothing changes on error. 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(()) } /// Every field with its effective value and source. 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() } /// Plans a save of one tab. `submitted` maps key to the raw form value. Returns the keys to /// store, the keys to clear (submitted equal to the file value), and the validated result. /// A blank secret keeps what is stored. Nothing is stored on error. 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, }) } /// The overrides after dropping `key`, validated. 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) } } /// The outcome of [`Live::plan_save`]. #[derive(Debug)] pub struct SavePlan { pub sets: Vec<(String, String)>, pub clears: Vec, /// All overrides once the plan is applied. 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(live.file(), &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"), ("advisories.ecosystems", "pip"), ("storage.r2.jurisdiction", "mars"), ("listen", "0.0.0.0:1"), ] { let mut cfg = base(); assert!(set(&mut cfg, key, value).is_err(), "{key}={value}"); } // Cross-field loader rules apply to a whole save. 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")); } } }