forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

server_settings.rs1467 lines, 45.0 KiBHistoryRawDownload
1//! Admin-editable server settings, layered on the config file.
2//!
3//! Precedence per field: a UI override (table `server_settings`), then the config file, then the
4//! built-in default. The config file is never rewritten. Every field has a [`Kind`]:
5//!
6//! - `Live`: applied to the running process at once. Consumers read [`Live::current`].
7//! - `Restart`: saved and shown as pending until the process restarts. Boot layers the stored
8//! overrides on the file config, so they take effect then.
9//! - `ReadOnly`: shown, never editable (listen addresses, database path, data dir).
10//!
11//! A secret field is write-only: the page shows whether it is set, never the value, and the stored
12//! value is sealed with the instance key.
13//!
14//! Values travel as canonical strings (`true`, `42`, `a, b`) so one table holds every field and a
15//! new field needs no migration. [`get`] and [`set`] convert between those strings and [`Config`].
16
17use std::collections::{BTreeMap, BTreeSet};
18use std::net::IpAddr;
19use std::sync::{Arc, RwLock};
20
21use ipnet::IpNet;
22
23use crate::config::{Config, MailTransport, OrgCreation, Registration, StorageBackend};
24use crate::error::{Error, Result};
25
26/// How a field reaches the running process.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Kind {
29 Live,
30 Restart,
31 ReadOnly,
32}
33
34/// The page tab a field belongs to.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Group {
37 General,
38 Limits,
39 Storage,
40 Backups,
41 Integrations,
42 Alerts,
43}
44
45impl Group {
46 pub const ALL: [Group; 6] = [
47 Group::General,
48 Group::Limits,
49 Group::Storage,
50 Group::Backups,
51 Group::Integrations,
52 Group::Alerts,
53 ];
54
55 pub fn slug(self) -> &'static str {
56 match self {
57 Group::General => "general",
58 Group::Limits => "limits",
59 Group::Storage => "storage",
60 Group::Backups => "backups",
61 Group::Integrations => "integrations",
62 Group::Alerts => "alerts",
63 }
64 }
65
66 pub fn parse(slug: &str) -> Option<Group> {
67 Group::ALL.into_iter().find(|g| g.slug() == slug)
68 }
69}
70
71/// The value type of a field, which decides the input and the server-side check.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Ty {
74 Bool,
75 /// Whole number in `min..=max`.
76 Uint(u64, u64),
77 Text,
78 /// A filesystem path. Empty is allowed and usually means "off".
79 Path,
80 Choice(&'static [&'static str]),
81 /// Comma separated entries.
82 List,
83 /// Write-only text.
84 Secret,
85 /// Socket address (read-only fields only).
86 Addr,
87}
88
89#[derive(Debug, Clone, Copy)]
90pub struct Field {
91 pub key: &'static str,
92 pub group: Group,
93 pub kind: Kind,
94 pub ty: Ty,
95 pub label: &'static str,
96 pub help: &'static str,
97}
98
99impl Field {
100 pub fn is_secret(&self) -> bool {
101 self.ty == Ty::Secret
102 }
103}
104
105const fn f(
106 key: &'static str,
107 group: Group,
108 kind: Kind,
109 ty: Ty,
110 label: &'static str,
111 help: &'static str,
112) -> Field {
113 Field {
114 key,
115 group,
116 kind,
117 ty,
118 label,
119 help,
120 }
121}
122
123use Group::{Alerts, Backups, General, Integrations, Limits, Storage};
124use Kind::{Live as L, ReadOnly as R, Restart as X};
125
126const REGISTRATION: &[&str] = &["closed", "invite", "open"];
127const BANNER_LEVEL: &[&str] = &["info", "warning"];
128const ORG_CREATION: &[&str] = &["all", "admin"];
129const MAIL_TRANSPORT: &[&str] = &["smtp", "log"];
130const BACKEND: &[&str] = &["fs", "s3", "r2"];
131const JURISDICTION: &[&str] = &["", "eu", "fedramp"];
132const MB: Ty = Ty::Uint(1, 1_048_576);
133const PORT: Ty = Ty::Uint(1, 65_535);
134
135/// Every setting, in display order.
136pub static FIELDS: &[Field] = &[
137 f(
138 "registration",
139 General,
140 L,
141 Ty::Choice(REGISTRATION),
142 "Registration",
143 "Who may create an account: closed, invite only, or open.",
144 ),
145 f(
146 "orgs.creation",
147 General,
148 L,
149 Ty::Choice(ORG_CREATION),
150 "Organization creation",
151 "Who may create an organization: all signed-in people, or admins only.",
152 ),
153 f(
154 "banner.message",
155 General,
156 L,
157 Ty::Text,
158 "Announcement banner",
159 "One line shown under the header on every page. Empty hides it.",
160 ),
161 f(
162 "banner.level",
163 General,
164 L,
165 Ty::Choice(BANNER_LEVEL),
166 "Banner level",
167 "Info or warning.",
168 ),
169 f(
170 "banner.expires",
171 General,
172 L,
173 Ty::Text,
174 "Banner expires (UTC)",
175 "As YYYY-MM-DD HH:MM. Empty keeps the banner until it is cleared.",
176 ),
177 f(
178 "trusted_proxies",
179 General,
180 L,
181 Ty::List,
182 "Trusted proxies",
183 "Addresses or CIDR networks whose X-Forwarded-For header is trusted. Comma separated.",
184 ),
185 f(
186 "base_url",
187 General,
188 X,
189 Ty::Text,
190 "Base URL",
191 "Public URL used in links and clone URLs.",
192 ),
193 f(
194 "user_content_base_url",
195 General,
196 X,
197 Ty::Text,
198 "User content URL",
199 "Separate origin that serves raw user files.",
200 ),
201 f(
202 "ssh_public_host",
203 General,
204 X,
205 Ty::Text,
206 "SSH host shown",
207 "Host in SSH clone URLs.",
208 ),
209 f(
210 "ssh_public_port",
211 General,
212 X,
213 PORT,
214 "SSH port shown",
215 "Port in SSH clone URLs.",
216 ),
217 f(
218 "listen",
219 General,
220 R,
221 Ty::Addr,
222 "HTTP listen address",
223 "Set in the config file.",
224 ),
225 f(
226 "user_content_listen",
227 General,
228 R,
229 Ty::Addr,
230 "User content listen address",
231 "Set in the config file.",
232 ),
233 f(
234 "ssh_listen",
235 General,
236 R,
237 Ty::Addr,
238 "SSH listen address",
239 "Set in the config file.",
240 ),
241 f(
242 "database",
243 General,
244 R,
245 Ty::Path,
246 "Database file",
247 "Set in the config file.",
248 ),
249 f(
250 "data_dir",
251 General,
252 R,
253 Ty::Path,
254 "Data directory",
255 "Set in the config file.",
256 ),
257 f(
258 "ci.enabled",
259 Limits,
260 L,
261 Ty::Bool,
262 "CI enabled",
263 "When off, pushes and pull requests create no runs.",
264 ),
265 f(
266 "ci.max_log_mb",
267 Limits,
268 L,
269 MB,
270 "Largest job log (MiB)",
271 "A longer log is truncated.",
272 ),
273 f(
274 "ci.max_artifact_mb",
275 Limits,
276 L,
277 MB,
278 "Largest artifact (MiB)",
279 "",
280 ),
281 f(
282 "ci.max_artifacts_per_job",
283 Limits,
284 L,
285 Ty::Uint(1, 100_000),
286 "Artifacts per job",
287 "",
288 ),
289 f(
290 "ci.max_job_artifacts_mb",
291 Limits,
292 L,
293 MB,
294 "Largest total of one job's artifacts (MiB)",
295 "",
296 ),
297 f(
298 "ci.log_retention_days",
299 Limits,
300 L,
301 Ty::Uint(1, 36_500),
302 "Log retention (days)",
303 "",
304 ),
305 f(
306 "ci.artifact_retention_days",
307 Limits,
308 L,
309 Ty::Uint(1, 36_500),
310 "Artifact retention (days)",
311 "",
312 ),
313 f(
314 "ci.artifact_keep_runs",
315 Limits,
316 L,
317 Ty::Uint(0, 100_000),
318 "Artifact runs kept per repo",
319 "0 keeps all.",
320 ),
321 f(
322 "ci.artifact_max_total_mb",
323 Limits,
324 L,
325 Ty::Uint(0, 100_000_000),
326 "Artifact disk limit (MiB)",
327 "Oldest runs' artifacts go first. 0 is no limit.",
328 ),
329 f(
330 "ci.registration_token_hours",
331 Limits,
332 L,
333 Ty::Uint(1, 8_760),
334 "Runner token lifetime (hours)",
335 "How long a runner registration token stays valid.",
336 ),
337 f(
338 "lfs.max_object_mb",
339 Limits,
340 L,
341 MB,
342 "Largest LFS object (MiB)",
343 "",
344 ),
345 f(
346 "releases.max_asset_mb",
347 Limits,
348 L,
349 MB,
350 "Largest release asset (MiB)",
351 "",
352 ),
353 f(
354 "storage.backend",
355 Storage,
356 X,
357 Ty::Choice(BACKEND),
358 "Backend",
359 "Where release assets and CI artifacts live: fs, r2 or s3.",
360 ),
361 f(
362 "storage.r2.account_id",
363 Storage,
364 X,
365 Ty::Text,
366 "R2 account id",
367 "32 character hex string from the Cloudflare dashboard.",
368 ),
369 f("storage.r2.bucket", Storage, X, Ty::Text, "R2 bucket", ""),
370 f(
371 "storage.r2.jurisdiction",
372 Storage,
373 X,
374 Ty::Choice(JURISDICTION),
375 "R2 jurisdiction",
376 "eu, fedramp, or empty for the global default.",
377 ),
378 f(
379 "storage.r2.prefix",
380 Storage,
381 X,
382 Ty::Text,
383 "R2 key prefix",
384 "",
385 ),
386 f(
387 "storage.r2.access_key_id",
388 Storage,
389 X,
390 Ty::Text,
391 "R2 access key id",
392 "",
393 ),
394 f(
395 "storage.r2.secret_access_key_file",
396 Storage,
397 X,
398 Ty::Path,
399 "R2 secret key file",
400 "Path of the file that holds the secret access key. The key itself is never read here.",
401 ),
402 f("storage.s3.bucket", Storage, X, Ty::Text, "S3 bucket", ""),
403 f("storage.s3.region", Storage, X, Ty::Text, "S3 region", ""),
404 f(
405 "storage.s3.endpoint",
406 Storage,
407 X,
408 Ty::Text,
409 "S3 endpoint",
410 "Leave empty for AWS.",
411 ),
412 f(
413 "storage.s3.prefix",
414 Storage,
415 X,
416 Ty::Text,
417 "S3 key prefix",
418 "",
419 ),
420 f(
421 "storage.s3.access_key_id",
422 Storage,
423 X,
424 Ty::Text,
425 "S3 access key id",
426 "",
427 ),
428 f(
429 "storage.s3.secret_access_key_file",
430 Storage,
431 X,
432 Ty::Path,
433 "S3 secret key file",
434 "Path of the file that holds the secret access key.",
435 ),
436 f(
437 "storage.s3.allow_http",
438 Storage,
439 X,
440 Ty::Bool,
441 "S3 allow http",
442 "",
443 ),
444 f(
445 "storage.s3.virtual_hosted_style",
446 Storage,
447 X,
448 Ty::Bool,
449 "S3 virtual hosted style",
450 "",
451 ),
452 f(
453 "backup.dir",
454 Backups,
455 X,
456 Ty::Path,
457 "Backup directory",
458 "Empty turns scheduled backups off.",
459 ),
460 f(
461 "backup.interval_hours",
462 Backups,
463 X,
464 Ty::Uint(1, 8_760),
465 "Backup interval (hours)",
466 "",
467 ),
468 f(
469 "backup.keep",
470 Backups,
471 X,
472 Ty::Uint(1, 10_000),
473 "Backup sets kept",
474 "",
475 ),
476 f(
477 "backup.fsck_interval_days",
478 Backups,
479 X,
480 Ty::Uint(1, 3_650),
481 "fsck interval (days)",
482 "",
483 ),
484 f(
485 "backup.healthcheck_url",
486 Backups,
487 X,
488 Ty::Secret,
489 "Backup healthcheck URL",
490 "May hold a token, so it is write-only.",
491 ),
492 f(
493 "replication.target",
494 Backups,
495 X,
496 Ty::Text,
497 "Replication target",
498 "Empty turns standby replication off.",
499 ),
500 f(
501 "replication.ssh_port",
502 Backups,
503 X,
504 PORT,
505 "Replication SSH port",
506 "",
507 ),
508 f(
509 "replication.identity_file",
510 Backups,
511 X,
512 Ty::Path,
513 "Replication identity file",
514 "",
515 ),
516 f(
517 "replication.known_hosts_file",
518 Backups,
519 X,
520 Ty::Path,
521 "Replication known hosts file",
522 "",
523 ),
524 f(
525 "replication.db_snapshot_minutes",
526 Backups,
527 X,
528 Ty::Uint(1, 525_600),
529 "Database snapshot (minutes)",
530 "",
531 ),
532 f(
533 "replication.reconcile_minutes",
534 Backups,
535 X,
536 Ty::Uint(1, 525_600),
537 "Reconcile (minutes)",
538 "",
539 ),
540 f(
541 "replication.healthcheck_url",
542 Backups,
543 X,
544 Ty::Secret,
545 "Replication healthcheck URL",
546 "May hold a token, so it is write-only.",
547 ),
548 f(
549 "webhooks.allow_http",
550 Integrations,
551 X,
552 Ty::Bool,
553 "Allow http webhooks",
554 "Permit http:// hook URLs besides https://.",
555 ),
556 f(
557 "webhooks.allowed_hosts",
558 Integrations,
559 X,
560 Ty::List,
561 "Webhook allowed hosts",
562 "Hostnames or CIDR networks reachable even when they resolve to internal addresses. Comma separated.",
563 ),
564 f(
565 "mail.transport",
566 Integrations,
567 X,
568 Ty::Choice(MAIL_TRANSPORT),
569 "Mail transport",
570 "smtp sends mail, log writes it to a directory. The SMTP account is on the Mail page.",
571 ),
572 f(
573 "advisories.enabled",
574 Integrations,
575 X,
576 Ty::Bool,
577 "Security advisories",
578 "Download OSV dumps and scan lockfiles.",
579 ),
580 f(
581 "advisories.ecosystems",
582 Integrations,
583 X,
584 Ty::List,
585 "Advisory ecosystems",
586 "Any of crates.io, npm, Go. Comma separated.",
587 ),
588 f(
589 "advisories.refresh_hours",
590 Integrations,
591 X,
592 Ty::Uint(1, 8_760),
593 "Advisory refresh (hours)",
594 "",
595 ),
596 f(
597 "self_update.enabled",
598 Integrations,
599 X,
600 Ty::Bool,
601 "Self-update",
602 "Deploy the artifact of a green run of the forge's own repo.",
603 ),
604 f(
605 "self_update.repo",
606 Integrations,
607 X,
608 Ty::Text,
609 "Self-update repo",
610 "As owner/name.",
611 ),
612 f(
613 "self_update.branch",
614 Integrations,
615 X,
616 Ty::Text,
617 "Self-update branch",
618 "",
619 ),
620 f(
621 "self_update.job",
622 Integrations,
623 X,
624 Ty::Text,
625 "Self-update job",
626 "",
627 ),
628 f(
629 "self_update.artifact",
630 Integrations,
631 X,
632 Ty::Text,
633 "Self-update artifact",
634 "{target} becomes this server's arch-os, e.g. forge-{target} is forge-x86_64-linux.",
635 ),
636 f(
637 "alerts.enabled",
638 Alerts,
639 L,
640 Ty::Bool,
641 "Admin alerts",
642 "Master switch. Off raises and sends nothing.",
643 ),
644 f(
645 "alerts.email",
646 Alerts,
647 L,
648 Ty::Bool,
649 "Email alerts",
650 "Also email the admins who have a verified address.",
651 ),
652 f(
653 "alerts.runner_offline_minutes",
654 Alerts,
655 L,
656 Ty::Uint(1, 1_440),
657 "Runner offline after (minutes)",
658 "A runner with no heartbeat for this long raises an alert.",
659 ),
660 f(
661 "alerts.disk_free_percent",
662 Alerts,
663 L,
664 Ty::Uint(1, 90),
665 "Low disk space (percent free)",
666 "Alert when the data directory has less than this free.",
667 ),
668 f(
669 "alerts.disk_free_gib",
670 Alerts,
671 L,
672 Ty::Uint(0, 100_000),
673 "Low disk space (GiB free)",
674 "Also alert under this many GiB. 0 turns this check off.",
675 ),
676 f(
677 "alerts.on_runner_offline",
678 Alerts,
679 L,
680 Ty::Bool,
681 "Runner offline alerts",
682 "",
683 ),
684 f(
685 "alerts.on_backup",
686 Alerts,
687 L,
688 Ty::Bool,
689 "Backup alerts",
690 "Failed, unverified or overdue backups, and failed fsck runs.",
691 ),
692 f(
693 "alerts.on_disk",
694 Alerts,
695 L,
696 Ty::Bool,
697 "Disk space alerts",
698 "",
699 ),
700 f(
701 "alerts.on_ci_killed",
702 Alerts,
703 L,
704 Ty::Bool,
705 "Killed CI job alerts",
706 "Jobs killed by SIGKILL or the OOM killer, once per run.",
707 ),
708 f(
709 "alerts.on_self_update",
710 Alerts,
711 L,
712 Ty::Bool,
713 "Self-update alerts",
714 "Deployed, failed, and server restarted.",
715 ),
716 f(
717 "alerts.on_replication",
718 Alerts,
719 L,
720 Ty::Bool,
721 "Replication alerts",
722 "Standby failing or lagging.",
723 ),
724];
725
726/// The field for a dotted key.
727pub fn field(key: &str) -> Option<&'static Field> {
728 FIELDS.iter().find(|f| f.key == key)
729}
730
731fn invalid(field: &Field, why: &str) -> Error {
732 Error::Invalid(format!("{}: {why}", field.label))
733}
734
735fn split_list(raw: &str) -> Vec<String> {
736 raw.split([',', '\n', '\r'])
737 .map(str::trim)
738 .filter(|s| !s.is_empty())
739 .map(str::to_owned)
740 .collect()
741}
742
743/// Checks `raw` against the field's type and returns its canonical string.
744pub fn normalize(field: &Field, raw: &str) -> Result<String> {
745 let raw = raw.trim();
746 match field.ty {
747 Ty::Bool => match raw {
748 "true" | "on" => Ok("true".into()),
749 "false" | "off" | "" => Ok("false".into()),
750 _ => Err(invalid(field, "must be on or off")),
751 },
752 Ty::Uint(min, max) => {
753 let n: u64 = raw
754 .parse()
755 .map_err(|_| invalid(field, "must be a whole number"))?;
756 if n < min || n > max {
757 return Err(invalid(field, &format!("must be between {min} and {max}")));
758 }
759 Ok(n.to_string())
760 }
761 Ty::Choice(options) => {
762 if options.contains(&raw) {
763 Ok(raw.to_owned())
764 } else {
765 let shown: Vec<&str> = options
766 .iter()
767 .map(|o| if o.is_empty() { "(empty)" } else { o })
768 .collect();
769 Err(invalid(
770 field,
771 &format!("must be one of {}", shown.join(", ")),
772 ))
773 }
774 }
775 Ty::Text | Ty::Path | Ty::Secret | Ty::Addr => {
776 if raw.len() > 1024 || raw.chars().any(char::is_control) {
777 return Err(invalid(
778 field,
779 "must be one line of at most 1024 characters",
780 ));
781 }
782 if field.key == "banner.expires"
783 && !raw.is_empty()
784 && crate::config::parse_banner_expiry(raw).is_none()
785 {
786 return Err(invalid(field, "must look like 2026-12-31 18:00"));
787 }
788 if field.key == "banner.message" && raw.chars().count() > 300 {
789 return Err(invalid(field, "must be at most 300 characters"));
790 }
791 Ok(raw.to_owned())
792 }
793 Ty::List => {
794 let items = split_list(raw);
795 if items
796 .iter()
797 .any(|i| i.len() > 253 || i.chars().any(char::is_control))
798 {
799 return Err(invalid(field, "has an entry that is too long"));
800 }
801 if field.key == "trusted_proxies" {
802 for item in &items {
803 if item.parse::<IpNet>().is_err() && item.parse::<IpAddr>().is_err() {
804 return Err(invalid(field, &format!("invalid trusted proxy `{item}`")));
805 }
806 }
807 }
808 if field.key == "advisories.ecosystems" {
809 for item in &items {
810 if !matches!(item.as_str(), "crates.io" | "npm" | "Go") {
811 return Err(invalid(field, &format!("unknown ecosystem `{item}`")));
812 }
813 }
814 }
815 Ok(items.join(", "))
816 }
817 }
818}
819
820fn b(v: &str) -> bool {
821 v == "true"
822}
823
824fn n(v: &str) -> u64 {
825 v.parse().unwrap_or_default()
826}
827
828fn choice<T: Copy>(v: &str, table: &[(&str, T)], fallback: T) -> T {
829 table
830 .iter()
831 .find(|(name, _)| *name == v)
832 .map_or(fallback, |(_, t)| *t)
833}
834
835fn backend_name(b: StorageBackend) -> &'static str {
836 match b {
837 StorageBackend::Fs => "fs",
838 StorageBackend::S3 => "s3",
839 StorageBackend::R2 => "r2",
840 }
841}
842
843/// The canonical string of a field's value in `cfg`. Secrets return their real value, so callers
844/// that render must not call this for a secret field.
845pub fn get(cfg: &Config, key: &str) -> String {
846 let path = |p: &std::path::Path| p.to_string_lossy().into_owned();
847 let list = |v: &[String]| v.join(", ");
848 match key {
849 "registration" => match cfg.registration {
850 Registration::Closed => "closed",
851 Registration::Invite => "invite",
852 Registration::Open => "open",
853 }
854 .into(),
855 "orgs.creation" => match cfg.orgs.creation {
856 OrgCreation::All => "all",
857 OrgCreation::Admin => "admin",
858 }
859 .into(),
860 "trusted_proxies" => cfg
861 .trusted_proxies
862 .iter()
863 .map(ToString::to_string)
864 .collect::<Vec<_>>()
865 .join(", "),
866 "banner.message" => cfg.banner.message.clone(),
867 "banner.level" => cfg.banner.level.clone(),
868 "banner.expires" => cfg.banner.expires.clone(),
869 "alerts.enabled" => cfg.alerts.enabled.to_string(),
870 "alerts.email" => cfg.alerts.email.to_string(),
871 "alerts.runner_offline_minutes" => cfg.alerts.runner_offline_minutes.to_string(),
872 "alerts.disk_free_percent" => cfg.alerts.disk_free_percent.to_string(),
873 "alerts.disk_free_gib" => cfg.alerts.disk_free_gib.to_string(),
874 "alerts.on_runner_offline" => cfg.alerts.on_runner_offline.to_string(),
875 "alerts.on_backup" => cfg.alerts.on_backup.to_string(),
876 "alerts.on_disk" => cfg.alerts.on_disk.to_string(),
877 "alerts.on_ci_killed" => cfg.alerts.on_ci_killed.to_string(),
878 "alerts.on_self_update" => cfg.alerts.on_self_update.to_string(),
879 "alerts.on_replication" => cfg.alerts.on_replication.to_string(),
880 "base_url" => cfg.base_url.clone(),
881 "user_content_base_url" => cfg.user_content_base_url.clone(),
882 "ssh_public_host" => cfg.ssh_public_host.clone(),
883 "ssh_public_port" => cfg.ssh_public_port.to_string(),
884 "listen" => cfg.listen.to_string(),
885 "user_content_listen" => cfg.user_content_listen.to_string(),
886 "ssh_listen" => cfg.ssh_listen.to_string(),
887 "database" => path(&cfg.database),
888 "data_dir" => path(&cfg.data_dir),
889 "ci.enabled" => cfg.ci.enabled.to_string(),
890 "ci.max_log_mb" => cfg.ci.max_log_mb.to_string(),
891 "ci.max_artifact_mb" => cfg.ci.max_artifact_mb.to_string(),
892 "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job.to_string(),
893 "ci.max_job_artifacts_mb" => cfg.ci.max_job_artifacts_mb.to_string(),
894 "ci.log_retention_days" => cfg.ci.log_retention_days.to_string(),
895 "ci.artifact_retention_days" => cfg.ci.artifact_retention_days.to_string(),
896 "ci.artifact_keep_runs" => cfg.ci.artifact_keep_runs.to_string(),
897 "ci.artifact_max_total_mb" => cfg.ci.artifact_max_total_mb.to_string(),
898 "ci.registration_token_hours" => cfg.ci.registration_token_hours.to_string(),
899 "lfs.max_object_mb" => cfg.lfs.max_object_mb.to_string(),
900 "releases.max_asset_mb" => cfg.releases.max_asset_mb.to_string(),
901 "storage.backend" => backend_name(cfg.storage.backend).into(),
902 "storage.r2.account_id" => cfg.storage.r2.account_id.clone(),
903 "storage.r2.bucket" => cfg.storage.r2.bucket.clone(),
904 "storage.r2.jurisdiction" => cfg.storage.r2.jurisdiction.clone(),
905 "storage.r2.prefix" => cfg.storage.r2.prefix.clone(),
906 "storage.r2.access_key_id" => cfg.storage.r2.access_key_id.clone(),
907 "storage.r2.secret_access_key_file" => path(&cfg.storage.r2.secret_access_key_file),
908 "storage.s3.bucket" => cfg.storage.s3.bucket.clone(),
909 "storage.s3.region" => cfg.storage.s3.region.clone(),
910 "storage.s3.endpoint" => cfg.storage.s3.endpoint.clone(),
911 "storage.s3.prefix" => cfg.storage.s3.prefix.clone(),
912 "storage.s3.access_key_id" => cfg.storage.s3.access_key_id.clone(),
913 "storage.s3.secret_access_key_file" => path(&cfg.storage.s3.secret_access_key_file),
914 "storage.s3.allow_http" => cfg.storage.s3.allow_http.to_string(),
915 "storage.s3.virtual_hosted_style" => cfg.storage.s3.virtual_hosted_style.to_string(),
916 "backup.dir" => path(&cfg.backup.dir),
917 "backup.interval_hours" => cfg.backup.interval_hours.to_string(),
918 "backup.keep" => cfg.backup.keep.to_string(),
919 "backup.fsck_interval_days" => cfg.backup.fsck_interval_days.to_string(),
920 "backup.healthcheck_url" => cfg.backup.healthcheck_url.clone(),
921 "replication.target" => cfg.replication.target.clone(),
922 "replication.ssh_port" => cfg.replication.ssh_port.to_string(),
923 "replication.identity_file" => path(&cfg.replication.identity_file),
924 "replication.known_hosts_file" => path(&cfg.replication.known_hosts_file),
925 "replication.db_snapshot_minutes" => cfg.replication.db_snapshot_minutes.to_string(),
926 "replication.reconcile_minutes" => cfg.replication.reconcile_minutes.to_string(),
927 "replication.healthcheck_url" => cfg.replication.healthcheck_url.clone(),
928 "webhooks.allow_http" => cfg.webhooks.allow_http.to_string(),
929 "webhooks.allowed_hosts" => list(&cfg.webhooks.allowed_hosts),
930 "mail.transport" => match cfg.mail.transport {
931 MailTransport::Smtp => "smtp",
932 MailTransport::Log => "log",
933 }
934 .into(),
935 "advisories.enabled" => cfg.advisories.enabled.to_string(),
936 "advisories.ecosystems" => list(&cfg.advisories.ecosystems),
937 "advisories.refresh_hours" => cfg.advisories.refresh_hours.to_string(),
938 "self_update.enabled" => cfg.self_update.enabled.to_string(),
939 "self_update.repo" => cfg.self_update.repo.clone(),
940 "self_update.branch" => cfg.self_update.branch.clone(),
941 "self_update.job" => cfg.self_update.job.clone(),
942 "self_update.artifact" => cfg.self_update.artifact.clone(),
943 _ => String::new(),
944 }
945}
946
947/// Checks `raw` and stores it into `cfg`. A read-only or unknown key is refused.
948pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> {
949 let field = field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?;
950 if field.kind == Kind::ReadOnly {
951 return Err(invalid(field, "is read-only"));
952 }
953 let v = normalize(field, raw)?;
954 let v = v.as_str();
955 let p = || std::path::PathBuf::from(v);
956 let s = || v.to_owned();
957 match key {
958 "registration" => {
959 cfg.registration = choice(
960 v,
961 &[
962 ("closed", Registration::Closed),
963 ("invite", Registration::Invite),
964 ("open", Registration::Open),
965 ],
966 Registration::Closed,
967 )
968 }
969 "orgs.creation" => {
970 cfg.orgs.creation = choice(
971 v,
972 &[("all", OrgCreation::All), ("admin", OrgCreation::Admin)],
973 OrgCreation::All,
974 )
975 }
976 "trusted_proxies" => {
977 cfg.trusted_proxies = split_list(v)
978 .iter()
979 .filter_map(|e| {
980 e.parse::<IpNet>()
981 .ok()
982 .or_else(|| e.parse::<IpAddr>().ok().map(IpNet::from))
983 })
984 .collect()
985 }
986 "banner.message" => cfg.banner.message = s(),
987 "banner.level" => cfg.banner.level = s(),
988 "banner.expires" => cfg.banner.expires = s(),
989 "alerts.enabled" => cfg.alerts.enabled = b(v),
990 "alerts.email" => cfg.alerts.email = b(v),
991 "alerts.runner_offline_minutes" => cfg.alerts.runner_offline_minutes = n(v),
992 "alerts.disk_free_percent" => cfg.alerts.disk_free_percent = n(v),
993 "alerts.disk_free_gib" => cfg.alerts.disk_free_gib = n(v),
994 "alerts.on_runner_offline" => cfg.alerts.on_runner_offline = b(v),
995 "alerts.on_backup" => cfg.alerts.on_backup = b(v),
996 "alerts.on_disk" => cfg.alerts.on_disk = b(v),
997 "alerts.on_ci_killed" => cfg.alerts.on_ci_killed = b(v),
998 "alerts.on_self_update" => cfg.alerts.on_self_update = b(v),
999 "alerts.on_replication" => cfg.alerts.on_replication = b(v),
1000 "base_url" => cfg.base_url = s(),
1001 "user_content_base_url" => cfg.user_content_base_url = s(),
1002 "ssh_public_host" => cfg.ssh_public_host = s(),
1003 "ssh_public_port" => cfg.ssh_public_port = n(v) as u16,
1004 "ci.enabled" => cfg.ci.enabled = b(v),
1005 "ci.max_log_mb" => cfg.ci.max_log_mb = n(v),
1006 "ci.max_artifact_mb" => cfg.ci.max_artifact_mb = n(v),
1007 "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job = n(v) as u32,
1008 "ci.max_job_artifacts_mb" => cfg.ci.max_job_artifacts_mb = n(v),
1009 "ci.log_retention_days" => cfg.ci.log_retention_days = n(v),
1010 "ci.artifact_retention_days" => cfg.ci.artifact_retention_days = n(v),
1011 "ci.artifact_keep_runs" => cfg.ci.artifact_keep_runs = n(v) as u32,
1012 "ci.artifact_max_total_mb" => cfg.ci.artifact_max_total_mb = n(v),
1013 "ci.registration_token_hours" => cfg.ci.registration_token_hours = n(v) as u32,
1014 "lfs.max_object_mb" => cfg.lfs.max_object_mb = n(v),
1015 "releases.max_asset_mb" => cfg.releases.max_asset_mb = n(v),
1016 "storage.backend" => {
1017 cfg.storage.backend = choice(
1018 v,
1019 &[
1020 ("fs", StorageBackend::Fs),
1021 ("s3", StorageBackend::S3),
1022 ("r2", StorageBackend::R2),
1023 ],
1024 StorageBackend::Fs,
1025 )
1026 }
1027 "storage.r2.account_id" => cfg.storage.r2.account_id = s(),
1028 "storage.r2.bucket" => cfg.storage.r2.bucket = s(),
1029 "storage.r2.jurisdiction" => cfg.storage.r2.jurisdiction = s(),
1030 "storage.r2.prefix" => cfg.storage.r2.prefix = s(),
1031 "storage.r2.access_key_id" => cfg.storage.r2.access_key_id = s(),
1032 "storage.r2.secret_access_key_file" => cfg.storage.r2.secret_access_key_file = p(),
1033 "storage.s3.bucket" => cfg.storage.s3.bucket = s(),
1034 "storage.s3.region" => cfg.storage.s3.region = s(),
1035 "storage.s3.endpoint" => cfg.storage.s3.endpoint = s(),
1036 "storage.s3.prefix" => cfg.storage.s3.prefix = s(),
1037 "storage.s3.access_key_id" => cfg.storage.s3.access_key_id = s(),
1038 "storage.s3.secret_access_key_file" => cfg.storage.s3.secret_access_key_file = p(),
1039 "storage.s3.allow_http" => cfg.storage.s3.allow_http = b(v),
1040 "storage.s3.virtual_hosted_style" => cfg.storage.s3.virtual_hosted_style = b(v),
1041 "backup.dir" => cfg.backup.dir = p(),
1042 "backup.interval_hours" => cfg.backup.interval_hours = n(v),
1043 "backup.keep" => cfg.backup.keep = n(v) as usize,
1044 "backup.fsck_interval_days" => cfg.backup.fsck_interval_days = n(v),
1045 "backup.healthcheck_url" => cfg.backup.healthcheck_url = s(),
1046 "replication.target" => cfg.replication.target = s(),
1047 "replication.ssh_port" => cfg.replication.ssh_port = n(v) as u16,
1048 "replication.identity_file" => cfg.replication.identity_file = p(),
1049 "replication.known_hosts_file" => cfg.replication.known_hosts_file = p(),
1050 "replication.db_snapshot_minutes" => cfg.replication.db_snapshot_minutes = n(v),
1051 "replication.reconcile_minutes" => cfg.replication.reconcile_minutes = n(v),
1052 "replication.healthcheck_url" => cfg.replication.healthcheck_url = s(),
1053 "webhooks.allow_http" => cfg.webhooks.allow_http = b(v),
1054 "webhooks.allowed_hosts" => cfg.webhooks.allowed_hosts = split_list(v),
1055 "mail.transport" => {
1056 cfg.mail.transport = choice(
1057 v,
1058 &[("smtp", MailTransport::Smtp), ("log", MailTransport::Log)],
1059 MailTransport::Smtp,
1060 )
1061 }
1062 "advisories.enabled" => cfg.advisories.enabled = b(v),
1063 "advisories.ecosystems" => cfg.advisories.ecosystems = split_list(v),
1064 "advisories.refresh_hours" => cfg.advisories.refresh_hours = n(v),
1065 "self_update.enabled" => cfg.self_update.enabled = b(v),
1066 "self_update.repo" => cfg.self_update.repo = s(),
1067 "self_update.branch" => cfg.self_update.branch = s(),
1068 "self_update.job" => cfg.self_update.job = s(),
1069 "self_update.artifact" => cfg.self_update.artifact = s(),
1070 _ => return Err(Error::Invalid(format!("unknown setting `{key}`"))),
1071 }
1072 Ok(())
1073}
1074
1075/// `file` with every override applied. Read-only keys in `overrides` are ignored. Does not
1076/// validate the result; see [`Config::validate`].
1077pub fn apply(file: &Config, overrides: &BTreeMap<String, String>) -> Result<Config> {
1078 let mut cfg = file.clone();
1079 for (key, value) in overrides {
1080 if field(key).is_some_and(|f| f.kind != Kind::ReadOnly) {
1081 set(&mut cfg, key, value)?;
1082 }
1083 }
1084 Ok(cfg)
1085}
1086
1087/// The config boot runs with: the file plus every stored override. If that combination no longer
1088/// validates (say the file changed under an override), the overrides are dropped and the error is
1089/// returned beside the file config so the caller can log it.
1090pub fn boot_config(file: &Config, overrides: &BTreeMap<String, String>) -> (Config, Option<Error>) {
1091 match apply(file, overrides).and_then(|c| c.validate().map(|()| c)) {
1092 Ok(config) => (config, None),
1093 Err(e) => (file.clone(), Some(e)),
1094 }
1095}
1096
1097/// `boot` with the `Live` fields taken from `pending`: what the running process uses.
1098pub fn live_view(boot: &Config, pending: &Config) -> Config {
1099 let mut cfg = boot.clone();
1100 for f in FIELDS.iter().filter(|f| f.kind == Kind::Live) {
1101 // Values from `get` always pass `normalize`, so this cannot fail.
1102 let _ = set(&mut cfg, f.key, &get(pending, f.key));
1103 }
1104 cfg
1105}
1106
1107/// Where a field's effective value comes from.
1108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1109pub enum Source {
1110 Default,
1111 File,
1112 Ui,
1113}
1114
1115/// One field as the page shows it.
1116#[derive(Debug, Clone)]
1117pub struct FieldView {
1118 pub field: &'static Field,
1119 /// Effective value. Empty for a secret.
1120 pub value: String,
1121 /// The value the file (or default) gives. Empty for a secret.
1122 pub file_value: String,
1123 pub source: Source,
1124 /// For a secret: whether a value is set.
1125 pub secret_set: bool,
1126 /// Saved but not yet running: a restart field whose value differs from the running one.
1127 pub restart_pending: bool,
1128}
1129
1130/// The process-wide settings handle: the file config, the config boot ran with, and the live view
1131/// consumers read.
1132pub struct Live {
1133 file: Arc<Config>,
1134 file_keys: BTreeSet<String>,
1135 boot: Arc<Config>,
1136 current: RwLock<Arc<Config>>,
1137}
1138
1139impl Live {
1140 pub fn new(file: Arc<Config>, file_keys: BTreeSet<String>, boot: Arc<Config>) -> Live {
1141 Live {
1142 current: RwLock::new(boot.clone()),
1143 file,
1144 file_keys,
1145 boot,
1146 }
1147 }
1148
1149 /// The config the running process uses right now.
1150 pub fn current(&self) -> Arc<Config> {
1151 self.current
1152 .read()
1153 .unwrap_or_else(|poisoned| poisoned.into_inner())
1154 .clone()
1155 }
1156
1157 pub fn file(&self) -> &Config {
1158 &self.file
1159 }
1160
1161 pub fn boot(&self) -> &Config {
1162 &self.boot
1163 }
1164
1165 /// Validates `file + overrides`, then publishes its live fields. Nothing changes on error.
1166 pub fn publish(&self, overrides: &BTreeMap<String, String>) -> Result<()> {
1167 let pending = apply(&self.file, overrides)?;
1168 pending.validate()?;
1169 let live = live_view(&self.boot, &pending);
1170 *self
1171 .current
1172 .write()
1173 .unwrap_or_else(|poisoned| poisoned.into_inner()) = Arc::new(live);
1174 Ok(())
1175 }
1176
1177 /// Every field with its effective value and source.
1178 pub fn views(&self, overrides: &BTreeMap<String, String>) -> Vec<FieldView> {
1179 let pending = apply(&self.file, overrides).unwrap_or_else(|_| (*self.file).clone());
1180 FIELDS
1181 .iter()
1182 .map(|field| {
1183 let secret = field.is_secret();
1184 let shown = |cfg: &Config| {
1185 if secret {
1186 String::new()
1187 } else {
1188 get(cfg, field.key)
1189 }
1190 };
1191 let editable = field.kind != Kind::ReadOnly;
1192 let source = if editable && overrides.contains_key(field.key) {
1193 Source::Ui
1194 } else if self.file_keys.contains(field.key) {
1195 Source::File
1196 } else {
1197 Source::Default
1198 };
1199 let effective = if editable { &pending } else { &*self.boot };
1200 FieldView {
1201 field,
1202 value: shown(effective),
1203 file_value: shown(&self.file),
1204 source,
1205 secret_set: secret && !get(effective, field.key).is_empty(),
1206 restart_pending: field.kind == Kind::Restart
1207 && get(&pending, field.key) != get(&self.boot, field.key),
1208 }
1209 })
1210 .collect()
1211 }
1212
1213 /// Plans a save of one tab. `submitted` maps key to the raw form value. Returns the keys to
1214 /// store, the keys to clear (submitted equal to the file value), and the validated result.
1215 /// A blank secret keeps what is stored. Nothing is stored on error.
1216 pub fn plan_save(
1217 &self,
1218 existing: &BTreeMap<String, String>,
1219 group: Group,
1220 submitted: &BTreeMap<String, String>,
1221 ) -> Result<SavePlan> {
1222 let before = apply(&self.file, existing)?;
1223 let mut sets = Vec::new();
1224 let mut clears = Vec::new();
1225 let mut next = existing.clone();
1226 for field in FIELDS
1227 .iter()
1228 .filter(|f| f.group == group && f.kind != Kind::ReadOnly)
1229 {
1230 let Some(raw) = submitted.get(field.key) else {
1231 continue;
1232 };
1233 if field.is_secret() && raw.trim().is_empty() {
1234 continue;
1235 }
1236 let value = normalize(field, raw)?;
1237 if field.is_secret() {
1238 sets.push((field.key.to_owned(), value.clone()));
1239 next.insert(field.key.to_owned(), value);
1240 continue;
1241 }
1242 let has_override = existing.contains_key(field.key);
1243 if value == get(&before, field.key) {
1244 continue;
1245 }
1246 if value == get(&self.file, field.key) {
1247 if has_override {
1248 clears.push(field.key.to_owned());
1249 next.remove(field.key);
1250 }
1251 continue;
1252 }
1253 sets.push((field.key.to_owned(), value.clone()));
1254 next.insert(field.key.to_owned(), value);
1255 }
1256 let pending = apply(&self.file, &next)?;
1257 pending.validate()?;
1258 Ok(SavePlan {
1259 sets,
1260 clears,
1261 overrides: next,
1262 })
1263 }
1264
1265 /// The overrides after dropping `key`, validated.
1266 pub fn plan_reset(
1267 &self,
1268 existing: &BTreeMap<String, String>,
1269 key: &str,
1270 ) -> Result<BTreeMap<String, String>> {
1271 field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?;
1272 let mut next = existing.clone();
1273 next.remove(key);
1274 apply(&self.file, &next)?.validate()?;
1275 Ok(next)
1276 }
1277}
1278
1279/// The outcome of [`Live::plan_save`].
1280#[derive(Debug)]
1281pub struct SavePlan {
1282 pub sets: Vec<(String, String)>,
1283 pub clears: Vec<String>,
1284 /// All overrides once the plan is applied.
1285 pub overrides: BTreeMap<String, String>,
1286}
1287
1288#[cfg(test)]
1289mod tests {
1290 use super::*;
1291
1292 fn base() -> Config {
1293 toml::from_str(
1294 r#"
1295database = "/tmp/f.db"
1296data_dir = "/tmp"
1297listen = "127.0.0.1:1"
1298base_url = "http://x"
1299user_content_base_url = "http://y"
1300ssh_listen = "127.0.0.1:2"
1301ssh_public_host = "h"
1302ssh_public_port = 22
1303registration = "closed"
1304[ci]
1305max_log_mb = 20
1306"#,
1307 )
1308 .expect("config")
1309 }
1310
1311 fn live() -> Live {
1312 let file = Arc::new(base());
1313 let keys = ["registration", "ci.max_log_mb"]
1314 .into_iter()
1315 .map(String::from)
1316 .collect();
1317 Live::new(file.clone(), keys, file)
1318 }
1319
1320 fn form(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
1321 pairs
1322 .iter()
1323 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
1324 .collect()
1325 }
1326
1327 #[test]
1328 fn every_field_round_trips_through_get_and_set() {
1329 let cfg = base();
1330 for f in FIELDS.iter().filter(|f| f.kind != Kind::ReadOnly) {
1331 let mut copy = cfg.clone();
1332 set(&mut copy, f.key, &get(&cfg, f.key)).unwrap_or_else(|e| panic!("{}: {e}", f.key));
1333 assert_eq!(get(&copy, f.key), get(&cfg, f.key), "{}", f.key);
1334 }
1335 }
1336
1337 #[test]
1338 fn precedence_ui_over_file_over_default() {
1339 let live = live();
1340 let views = live.views(&BTreeMap::new());
1341 let find = |views: &[FieldView], key: &str| {
1342 views.iter().find(|v| v.field.key == key).cloned().unwrap()
1343 };
1344 assert_eq!(find(&views, "ci.max_log_mb").source, Source::File);
1345 assert_eq!(find(&views, "ci.max_log_mb").value, "20");
1346 assert_eq!(find(&views, "ci.max_artifact_mb").source, Source::Default);
1347 assert_eq!(find(&views, "ci.max_artifact_mb").value, "512");
1348
1349 let over = form(&[("ci.max_log_mb", "99")]);
1350 let views = live.views(&over);
1351 let v = find(&views, "ci.max_log_mb");
1352 assert_eq!(
1353 (v.source, v.value.as_str(), v.file_value.as_str()),
1354 (Source::Ui, "99", "20")
1355 );
1356 }
1357
1358 #[test]
1359 fn live_fields_apply_and_reset_restores_the_file_value() {
1360 let live = live();
1361 assert_eq!(live.current().ci.max_log_mb, 20);
1362 live.publish(&form(&[("ci.max_log_mb", "99"), ("registration", "open")]))
1363 .unwrap();
1364 assert_eq!(live.current().ci.max_log_mb, 99);
1365 assert_eq!(live.current().registration, Registration::Open);
1366 let next = live
1367 .plan_reset(&form(&[("ci.max_log_mb", "99")]), "ci.max_log_mb")
1368 .unwrap();
1369 live.publish(&next).unwrap();
1370 assert_eq!(live.current().ci.max_log_mb, 20);
1371 }
1372
1373 #[test]
1374 fn restart_fields_do_not_apply_until_boot() {
1375 let live = live();
1376 let over = form(&[("base_url", "https://new.example")]);
1377 live.publish(&over).unwrap();
1378 assert_eq!(live.current().base_url, "http://x");
1379 let v = live.views(&over);
1380 let v = v.iter().find(|v| v.field.key == "base_url").unwrap();
1381 assert!(v.restart_pending);
1382 let (boot, err) = boot_config(live.file(), &over);
1383 assert!(err.is_none());
1384 assert_eq!(boot.base_url, "https://new.example");
1385 let after = Live::new(Arc::new(base()), Default::default(), Arc::new(boot));
1386 assert!(!after.views(&over).iter().any(|v| v.restart_pending));
1387 }
1388
1389 #[test]
1390 fn validation_rejects_bad_values() {
1391 let live = live();
1392 for (key, value) in [
1393 ("registration", "everyone"),
1394 ("ci.max_log_mb", "0"),
1395 ("ci.max_log_mb", "lots"),
1396 ("trusted_proxies", "not-an-ip"),
1397 ("ssh_public_port", "70000"),
1398 ("advisories.ecosystems", "pip"),
1399 ("storage.r2.jurisdiction", "mars"),
1400 ("listen", "0.0.0.0:1"),
1401 ] {
1402 let mut cfg = base();
1403 assert!(set(&mut cfg, key, value).is_err(), "{key}={value}");
1404 }
1405 // Cross-field loader rules apply to a whole save.
1406 let group_form = form(&[("storage.backend", "r2")]);
1407 assert!(
1408 live.plan_save(&BTreeMap::new(), Group::Storage, &group_form)
1409 .is_err()
1410 );
1411 let group_form = form(&[("backup.dir", "/var/backups"), ("backup.keep", "5")]);
1412 assert!(
1413 live.plan_save(&BTreeMap::new(), Group::Backups, &group_form)
1414 .is_ok()
1415 );
1416 }
1417
1418 #[test]
1419 fn save_skips_unchanged_values_and_clears_when_back_at_the_file_value() {
1420 let live = live();
1421 let plan = live
1422 .plan_save(
1423 &BTreeMap::new(),
1424 Group::Limits,
1425 &form(&[
1426 ("ci.max_log_mb", "20"),
1427 ("ci.max_artifact_mb", "512"),
1428 ("ci.enabled", "false"),
1429 ]),
1430 )
1431 .unwrap();
1432 assert_eq!(
1433 plan.sets,
1434 vec![("ci.enabled".to_owned(), "false".to_owned())]
1435 );
1436 let existing = form(&[("ci.max_log_mb", "99")]);
1437 let plan = live
1438 .plan_save(&existing, Group::Limits, &form(&[("ci.max_log_mb", "20")]))
1439 .unwrap();
1440 assert_eq!(plan.clears, vec!["ci.max_log_mb".to_owned()]);
1441 assert!(plan.overrides.is_empty());
1442 }
1443
1444 #[test]
1445 fn secrets_are_never_in_a_view_and_blank_keeps_the_stored_value() {
1446 let live = live();
1447 let existing = form(&[("backup.healthcheck_url", "https://hc.example/token-123")]);
1448 let views = live.views(&existing);
1449 let v = views
1450 .iter()
1451 .find(|v| v.field.key == "backup.healthcheck_url")
1452 .unwrap();
1453 assert!(v.secret_set && v.value.is_empty() && v.file_value.is_empty());
1454 let plan = live
1455 .plan_save(
1456 &existing,
1457 Group::Backups,
1458 &form(&[("backup.healthcheck_url", "")]),
1459 )
1460 .unwrap();
1461 assert!(plan.sets.is_empty());
1462 assert_eq!(plan.overrides, existing);
1463 for view in &views {
1464 assert!(!view.value.contains("token-123"));
1465 }
1466 }
1467}