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