OXYGENHUB
# 33d98147511b oxygenhub / crates / hub / src / config.rs
21.6 KiB · Rust · last changed Run the hub as web and worker processes, singletons under a leader lock 17 days ago source blame history raw
1
//! Configuration (hub spec §17.1): `hub.toml` in the data directory, every
2
//! key overridable by `OXYHUB_<SECTION>_<KEY>`.
3
4
use serde::Deserialize;
5
use std::net::SocketAddr;
6
use std::path::{Path, PathBuf};
7
8
#[derive(Clone, Debug, Deserialize)]
9
#[serde(default, deny_unknown_fields)]
10
pub struct Config {
11
    /// Set from the command line, never from the file.
12
    #[serde(skip)]
13
    pub data: PathBuf,
14
    pub site: Site,
15
    pub server: Server,
16
    pub tls: Tls,
17
    pub auth: Auth,
18
    pub registration: Registration,
19
    pub email: Email,
20
    pub limits: Limits,
21
    pub retention: Retention,
22
    pub flow: Flow,
23
    pub apt: Apt,
24
    pub diffusion: Diffusion,
25
    pub backups: Backups,
26
    pub outbound: Outbound,
27
    pub database: Database,
28
    pub tlog: Tlog,
29
}
30
31
/// Where a hub built with the `postgres` feature keeps its tables (#211); a
32
/// SQLite build keeps them in `<data>/hub.db` and ignores this.
33
#[derive(Clone, Debug, Default, Deserialize)]
34
#[serde(default, deny_unknown_fields)]
35
pub struct Database {
36
    /// `postgres://user@host/db`; the password from the URL or `PGPASSWORD`.
37
    pub url: String,
38
    /// The schema to use, made if missing; empty for `public`, `*` for one
39
    /// per data directory (named after it), as the tests use.
40
    pub schema: String,
41
}
42
43
/// Outbound requests to addresses people give (oxygenhub#219): private
44
/// and local addresses are refused unless listed here, as `scheme://host`
45
/// (any port) or `scheme://host:port`, e.g. a local Ollama:
46
/// `allow = ["http://127.0.0.1:11434"]`.
47
#[derive(Clone, Debug, Default, Deserialize)]
48
#[serde(default, deny_unknown_fields)]
49
pub struct Outbound {
50
    pub allow: Vec<String>,
51
}
52
53
/// The transparency log's witnesses (docs/transparency.md, #238): who
54
/// cosigns this hub's checkpoints, and whose logs this hub cosigns.
55
#[derive(Clone, Debug, Default, Deserialize)]
56
#[serde(default, deny_unknown_fields)]
57
pub struct Tlog {
58
    pub witnesses: Vec<TlogWitness>,
59
    pub witness_for: Vec<TlogWitnessed>,
60
}
61
62
/// A witness this hub's log asks: its name in cosignatures, its
63
/// add-checkpoint address (`https://HUB/log/witness/add-checkpoint` for
64
/// another hub), and its identity object in base64 (another hub's
65
/// `/.well-known/oxyhub-key`).
66
#[derive(Clone, Debug, Deserialize)]
67
#[serde(deny_unknown_fields)]
68
pub struct TlogWitness {
69
    pub name: String,
70
    pub url: String,
71
    pub key: String,
72
}
73
74
/// A log this hub witnesses: its origin (`HOST/log`) and its key, an
75
/// identity object in base64.
76
#[derive(Clone, Debug, Deserialize)]
77
#[serde(deny_unknown_fields)]
78
pub struct TlogWitnessed {
79
    pub origin: String,
80
    pub key: String,
81
}
82
83
/// Backups (docs/backups.md, oxygenhub#169): the directories on this host
84
/// an owner may back up to. Empty, only GCS destinations can be chosen.
85
#[derive(Clone, Debug, Deserialize)]
86
#[serde(default, deny_unknown_fields)]
87
pub struct Backups {
88
    pub directories: Vec<PathBuf>,
89
    /// Google's token exchange and Cloud Storage, for GCS destinations;
90
    /// set only to point them elsewhere (tests, a private endpoint).
91
    pub sts_url: String,
92
    pub storage_url: String,
93
    /// AWS STS and S3, for S3 destinations; `{bucket}` and `{region}` in
94
    /// `s3_url` are filled in. Set only to point them elsewhere.
95
    pub aws_sts_url: String,
96
    pub s3_url: String,
97
}
98
99
impl Default for Backups {
100
    fn default() -> Self {
101
        Backups {
102
            directories: Vec::new(),
103
            sts_url: "https://sts.googleapis.com".into(),
104
            storage_url: "https://storage.googleapis.com".into(),
105
            aws_sts_url: "https://sts.amazonaws.com".into(),
106
            s3_url: "https://{bucket}.s3.{region}.amazonaws.com".into(),
107
        }
108
    }
109
}
110
111
/// Diffusion (#148, docs/diffusion.md §4.2): the site's default for
112
/// repositories that say nothing.
113
#[derive(Clone, Debug, Deserialize)]
114
#[serde(default, deny_unknown_fields)]
115
pub struct Diffusion {
116
    /// `off`, `green` or `any`.
117
    pub follow: String,
118
}
119
120
impl Default for Diffusion {
121
    fn default() -> Self {
122
        Diffusion { follow: "off".into() }
123
    }
124
}
125
126
/// The apt repository at `/apt` (oxygenhub#85): the `.deb` assets of these
127
/// public repositories' releases, signed with the key in `gnupg_home`.
128
#[derive(Clone, Debug, Deserialize)]
129
#[serde(default, deny_unknown_fields)]
130
pub struct Apt {
131
    /// `owner/name` of each repository whose release `.deb`s are served;
132
    /// none turns `/apt` off.
133
    pub repos: Vec<String>,
134
    /// The suite apt's `sources` names.
135
    pub suite: String,
136
    pub component: String,
137
    /// GnuPG home holding the signing key (relative to the data directory).
138
    pub gnupg_home: String,
139
    /// Architectures the index lists, each with its Packages file.
140
    pub architectures: Vec<String>,
141
}
142
143
impl Default for Apt {
144
    fn default() -> Self {
145
        Apt {
146
            repos: vec![],
147
            suite: "stable".into(),
148
            component: "main".into(),
149
            gnupg_home: "apt-gnupg".into(),
150
            architectures: vec!["amd64".into(), "arm64".into(), "riscv64".into()],
151
        }
152
    }
153
}
154
155
/// OxygenFlow runs (hub spec §13.2).
156
#[derive(Clone, Debug, Deserialize)]
157
#[serde(default, deny_unknown_fields)]
158
pub struct Flow {
159
    /// Bearer tokens runners present to claim jobs.
160
    pub runner_tokens: Vec<String>,
161
    /// `owner/*` or `owner/name`: repositories whose pushes start runs.
162
    pub repos: Vec<String>,
163
    pub job_timeout_minutes: u64,
164
    /// A runner whose last this many jobs all ended in an infrastructure
165
    /// error (status `error`, not `failed`) is drained and the
166
    /// administrators told (oxygenflow#30); 0 never drains one.
167
    pub drain_after_errors: u32,
168
}
169
170
impl Default for Flow {
171
    fn default() -> Self {
172
        Flow { runner_tokens: vec![], repos: vec![], job_timeout_minutes: 60, drain_after_errors: 5 }
173
    }
174
}
175
176
impl Flow {
177
    /// Whether pushes to `owner/name` start runs.
178
    pub fn allows(&self, owner: &str, name: &str) -> bool {
179
        self.repos.iter().any(|p| match p.split_once('/') {
180
            Some((o, "*")) => o == owner,
181
            Some((o, n)) => o == owner && n == name,
182
            None => false,
183
        })
184
    }
185
}
186
187
#[derive(Clone, Debug, Default, Deserialize)]
188
#[serde(default, deny_unknown_fields)]
189
pub struct Email {
190
    /// `smtp://user:pass@host:port` or `smtps://…`; empty disables email.
191
    pub smtp: String,
192
    /// `OxygenHub <hub@example>`.
193
    pub from: String,
194
}
195
196
#[derive(Clone, Debug, Deserialize)]
197
#[serde(default, deny_unknown_fields)]
198
pub struct Registration {
199
    /// `open`, `invite` or `closed`; the admin page can override it.
200
    pub mode: String,
201
    /// The setup code the first account must bring (oxygenhub#245), for
202
    /// automation; empty, the hub makes one and keeps it in
203
    /// `<data>/setup-code`.
204
    pub setup_code: String,
205
}
206
207
impl Default for Registration {
208
    fn default() -> Self {
209
        Registration { mode: "invite".into(), setup_code: String::new() }
210
    }
211
}
212
213
#[derive(Clone, Debug, Deserialize)]
214
#[serde(default, deny_unknown_fields)]
215
pub struct Site {
216
    pub name: String,
217
    pub description: String,
218
}
219
220
#[derive(Clone, Debug, Deserialize)]
221
#[serde(default, deny_unknown_fields)]
222
pub struct Server {
223
    /// Plain HTTP; empty disables it.
224
    pub bind: String,
225
    /// HTTPS; empty disables it. Needs `tls`.
226
    pub tls_bind: String,
227
    /// What links and clone URLs start with.
228
    pub base_url: String,
229
    /// Trust `X-Forwarded-*` from a terminating proxy.
230
    pub behind_proxy: bool,
231
    /// Strict-Transport-Security's max-age in seconds, sent when
232
    /// `base_url` is https; 0 sends none (oxygenhub#231). Raise it in
233
    /// stages: browsers keep it, so it is hard to take back.
234
    pub hsts_max_age: u64,
235
    /// The bearer token `/metrics` asks for (oxygenhub#212); empty, the
236
    /// metrics are off.
237
    pub metrics_token: String,
238
    /// A Grafana for this hub's metrics, linked from Insights (oxygenhub#257)
239
    /// for charts of one's own; empty, no link.
240
    pub grafana_url: String,
241
    /// What this process does (docs/roles.md, #272): `web` (pages, the
242
    /// API, the wire protocol, the runner API) and `worker` (the background
243
    /// tasks). Empty, both. `serve --role` overrides it.
244
    pub roles: Vec<String>,
245
}
246
247
/// One part of the hub's work a process can take (docs/roles.md, #272).
248
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249
pub enum Role {
250
    /// Pages, the JSON API, the wire protocol, live pages and the runner
251
    /// API, and the transparency log they append to.
252
    Web,
253
    /// The background tasks: webhooks, Flow's scheduler, reaper and
254
    /// placement pass, nightly upkeep, backups and Diffusion's index.
255
    Worker,
256
}
257
258
impl Role {
259
    pub const ALL: [Role; 2] = [Role::Web, Role::Worker];
260
261
    pub fn name(self) -> &'static str {
262
        match self {
263
            Role::Web => "web",
264
            Role::Worker => "worker",
265
        }
266
    }
267
}
268
269
impl std::str::FromStr for Role {
270
    type Err = String;
271
272
    fn from_str(s: &str) -> Result<Role, String> {
273
        match s.trim().to_ascii_lowercase().as_str() {
274
            "web" => Ok(Role::Web),
275
            "worker" => Ok(Role::Worker),
276
            _ => Err(format!("unknown role {:?}: the roles are web and worker", s.trim())),
277
        }
278
    }
279
}
280
281
/// The roles one process takes: every role unless some are named.
282
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
283
pub struct Roles {
284
    pub web: bool,
285
    pub worker: bool,
286
}
287
288
impl Default for Roles {
289
    fn default() -> Self {
290
        Roles { web: true, worker: true }
291
    }
292
}
293
294
impl Roles {
295
    /// The roles named, each `web` or `worker`; none named is every role.
296
    pub fn from_names<S: AsRef<str>>(names: &[S]) -> Result<Roles, String> {
297
        let names: Vec<&str> = names.iter().map(|s| s.as_ref().trim()).filter(|s| !s.is_empty()).collect();
298
        if names.is_empty() {
299
            return Ok(Roles::default());
300
        }
301
        let mut roles = Roles { web: false, worker: false };
302
        for n in names {
303
            match n.parse::<Role>()? {
304
                Role::Web => roles.web = true,
305
                Role::Worker => roles.worker = true,
306
            }
307
        }
308
        Ok(roles)
309
    }
310
311
    pub fn has(self, role: Role) -> bool {
312
        match role {
313
            Role::Web => self.web,
314
            Role::Worker => self.worker,
315
        }
316
    }
317
318
    /// The roles' names, in a fixed order: what `/health` reports.
319
    pub fn names(self) -> Vec<&'static str> {
320
        Role::ALL.into_iter().filter(|r| self.has(*r)).map(Role::name).collect()
321
    }
322
}
323
324
#[derive(Clone, Debug, Deserialize)]
325
#[serde(default, deny_unknown_fields)]
326
pub struct Tls {
327
    /// Generate a certificate at `init` (developer edition).
328
    pub self_signed: bool,
329
    /// PEM files; relative paths are under the data directory.
330
    pub cert: String,
331
    pub key: String,
332
}
333
334
#[derive(Clone, Debug, Default, Deserialize)]
335
#[serde(default, deny_unknown_fields)]
336
pub struct Auth {
337
    /// Bearer tokens allowed to push until accounts exist (hub 0.2). Empty
338
    /// means every push is accepted, as `oxy serve` does.
339
    pub push_tokens: Vec<String>,
340
    /// For tests only: a base URL that stands in for every sign-in
341
    /// provider (`{base}/{provider}/authorize|token|userinfo`).
342
    pub signin_mock: Option<String>,
343
}
344
345
#[derive(Clone, Debug, Deserialize)]
346
#[serde(default, deny_unknown_fields)]
347
pub struct Limits {
348
    /// Largest file rendered in the browser, e.g. `2MiB`.
349
    pub render_limit: ByteSize,
350
    pub asset_limit: ByteSize,
351
    pub push_body_limit: ByteSize,
352
}
353
354
#[derive(Clone, Debug, Deserialize)]
355
#[serde(default, deny_unknown_fields)]
356
pub struct Retention {
357
    pub trash_days: u32,
358
    pub webhook_log_days: u32,
359
    /// The UTC hour at which every repository is garbage collected
360
    /// (spec §17.2); 24 or more turns the nightly gc off.
361
    pub gc_hour: u32,
362
}
363
364
/// A byte count written as `512`, `2MiB`, `4GiB`, `100kB`.
365
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
366
pub struct ByteSize(pub u64);
367
368
impl ByteSize {
369
    pub fn parse(s: &str) -> Option<ByteSize> {
370
        let s = s.trim();
371
        let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();
372
        let unit = s[digits.len()..].trim();
373
        let n: u64 = digits.parse().ok()?;
374
        let mult = match unit {
375
            "" | "B" => 1,
376
            "k" | "kB" | "KB" => 1000,
377
            "KiB" | "K" => 1 << 10,
378
            "M" | "MB" => 1_000_000,
379
            "MiB" => 1 << 20,
380
            "G" | "GB" => 1_000_000_000,
381
            "GiB" => 1 << 30,
382
            _ => return None,
383
        };
384
        Some(ByteSize(n.checked_mul(mult)?))
385
    }
386
}
387
388
impl<'de> Deserialize<'de> for ByteSize {
389
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<ByteSize, D::Error> {
390
        #[derive(Deserialize)]
391
        #[serde(untagged)]
392
        enum Raw {
393
            Number(u64),
394
            Text(String),
395
        }
396
        match Raw::deserialize(d)? {
397
            Raw::Number(n) => Ok(ByteSize(n)),
398
            Raw::Text(t) => ByteSize::parse(&t).ok_or_else(|| serde::de::Error::custom(format!("not a byte size: {t:?}"))),
399
        }
400
    }
401
}
402
403
impl Default for Site {
404
    fn default() -> Self {
405
        Site { name: "OxygenHub".into(), description: "Repositories, proposals and issues for Oxygen".into() }
406
    }
407
}
408
409
impl Default for Server {
410
    fn default() -> Self {
411
        Server {
412
            bind: "127.0.0.1:7300".into(),
413
            tls_bind: String::new(),
414
            base_url: "http://127.0.0.1:7300".into(),
415
            behind_proxy: false,
416
            hsts_max_age: 0,
417
            metrics_token: String::new(),
418
            grafana_url: String::new(),
419
            roles: Vec::new(),
420
        }
421
    }
422
}
423
424
impl Default for Tls {
425
    fn default() -> Self {
426
        Tls { self_signed: false, cert: "keys/tls.crt".into(), key: "keys/tls.key".into() }
427
    }
428
}
429
430
impl Default for Limits {
431
    fn default() -> Self {
432
        Limits { render_limit: ByteSize(2 << 20), asset_limit: ByteSize(512 << 20), push_body_limit: ByteSize(4 << 30) }
433
    }
434
}
435
436
impl Default for Retention {
437
    fn default() -> Self {
438
        Retention { trash_days: 30, webhook_log_days: 30, gc_hour: 3 }
439
    }
440
}
441
442
impl Default for Config {
443
    fn default() -> Self {
444
        Config {
445
            data: PathBuf::from("data"),
446
            site: Site::default(),
447
            server: Server::default(),
448
            tls: Tls::default(),
449
            auth: Auth::default(),
450
            registration: Registration::default(),
451
            email: Email::default(),
452
            limits: Limits::default(),
453
            retention: Retention::default(),
454
            flow: Flow::default(),
455
            apt: Apt::default(),
456
            diffusion: Diffusion::default(),
457
            backups: Backups::default(),
458
            outbound: Outbound::default(),
459
            database: Database::default(),
460
            tlog: Tlog::default(),
461
        }
462
    }
463
}
464
465
impl Config {
466
    /// Read `<data>/hub.toml` if present, then apply environment overrides.
467
    pub fn load(data: &Path) -> anyhow::Result<Config> {
468
        let path = data.join("hub.toml");
469
        let mut cfg = match std::fs::read_to_string(&path) {
470
            Ok(text) => Config::parse(&text)?,
471
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Config::default(),
472
            Err(e) => return Err(anyhow::anyhow!("reading {}: {e}", path.display())),
473
        };
474
        cfg.data = data.to_path_buf();
475
        cfg.apply_env(|k| std::env::var(k).ok());
476
        cfg.roles()?;
477
        Ok(cfg)
478
    }
479
480
    pub fn parse(text: &str) -> anyhow::Result<Config> {
481
        Ok(toml::from_str(text)?)
482
    }
483
484
    /// `OXYHUB_SERVER_BIND`, `OXYHUB_SITE_NAME`, … override the file.
485
    pub fn apply_env(&mut self, get: impl Fn(&str) -> Option<String>) {
486
        if let Some(v) = get("OXYHUB_DATABASE_URL") {
487
            self.database.url = v;
488
        }
489
        if let Some(v) = get("OXYHUB_DATABASE_SCHEMA") {
490
            self.database.schema = v;
491
        }
492
        if let Some(v) = get("OXYHUB_SITE_NAME") {
493
            self.site.name = v;
494
        }
495
        if let Some(v) = get("OXYHUB_SITE_DESCRIPTION") {
496
            self.site.description = v;
497
        }
498
        if let Some(v) = get("OXYHUB_SERVER_BIND") {
499
            self.server.bind = v;
500
        }
501
        if let Some(v) = get("OXYHUB_SERVER_TLS_BIND") {
502
            self.server.tls_bind = v;
503
        }
504
        if let Some(v) = get("OXYHUB_SERVER_BASE_URL") {
505
            self.server.base_url = v;
506
        }
507
        if let Some(v) = get("OXYHUB_SERVER_BEHIND_PROXY") {
508
            self.server.behind_proxy = matches!(v.as_str(), "1" | "true" | "yes");
509
        }
510
        if let Some(v) = get("OXYHUB_SERVER_HSTS_MAX_AGE") {
511
            self.server.hsts_max_age = v.parse().unwrap_or(0);
512
        }
513
        // The VM's setup gives these (oxygenhub-gcp#12): the token its
514
        // collector scrapes /metrics with, and its Grafana for Insights' link.
515
        if let Some(v) = get("OXYHUB_SERVER_METRICS_TOKEN") {
516
            self.server.metrics_token = v;
517
        }
518
        if let Some(v) = get("OXYHUB_SERVER_GRAFANA_URL") {
519
            self.server.grafana_url = v;
520
        }
521
        if let Some(v) = get("OXYHUB_SERVER_ROLES") {
522
            self.server.roles = v.split(',').map(str::trim).filter(|s| !s.is_empty()).map(String::from).collect();
523
        }
524
        if let Some(v) = get("OXYHUB_TLS_SELF_SIGNED") {
525
            self.tls.self_signed = matches!(v.as_str(), "1" | "true" | "yes");
526
        }
527
        if let Some(v) = get("OXYHUB_REGISTRATION_MODE") {
528
            self.registration.mode = v;
529
        }
530
        if let Some(v) = get("OXYHUB_REGISTRATION_SETUP_CODE") {
531
            self.registration.setup_code = v;
532
        }
533
        if let Some(v) = get("OXYHUB_AUTH_PUSH_TOKENS") {
534
            self.auth.push_tokens = v.split(',').map(str::trim).filter(|s| !s.is_empty()).map(String::from).collect();
535
        }
536
        if let Some(v) = get("OXYHUB_LIMITS_RENDER_LIMIT").and_then(|v| ByteSize::parse(&v)) {
537
            self.limits.render_limit = v;
538
        }
539
    }
540
541
    /// This process's roles (`[server] roles`); an unknown name is an error.
542
    pub fn roles(&self) -> anyhow::Result<Roles> {
543
        Roles::from_names(&self.server.roles).map_err(|e| anyhow::anyhow!("[server] roles: {e}"))
544
    }
545
546
    pub fn bind_addr(&self) -> anyhow::Result<Option<SocketAddr>> {
547
        parse_addr(&self.server.bind)
548
    }
549
550
    pub fn tls_bind_addr(&self) -> anyhow::Result<Option<SocketAddr>> {
551
        parse_addr(&self.server.tls_bind)
552
    }
553
554
    pub fn tls_cert(&self) -> PathBuf {
555
        self.data.join(&self.tls.cert)
556
    }
557
558
    pub fn tls_key(&self) -> PathBuf {
559
        self.data.join(&self.tls.key)
560
    }
561
562
    pub fn repos_dir(&self) -> PathBuf {
563
        self.data.join("repos")
564
    }
565
566
    pub fn keys_dir(&self) -> PathBuf {
567
        self.data.join("keys")
568
    }
569
570
    pub fn db_path(&self) -> PathBuf {
571
        self.data.join("hub.db")
572
    }
573
574
    /// The base URL without a trailing slash.
575
    pub fn base_url(&self) -> &str {
576
        self.server.base_url.trim_end_matches('/')
577
    }
578
}
579
580
fn parse_addr(s: &str) -> anyhow::Result<Option<SocketAddr>> {
581
    if s.trim().is_empty() {
582
        return Ok(None);
583
    }
584
    Ok(Some(s.parse().map_err(|e| anyhow::anyhow!("bind address {s:?}: {e}"))?))
585
}
586
587
#[cfg(test)]
588
mod tests {
589
    use super::*;
590
591
    #[test]
592
    fn byte_sizes() {
593
        assert_eq!(ByteSize::parse("2MiB"), Some(ByteSize(2 << 20)));
594
        assert_eq!(ByteSize::parse("512"), Some(ByteSize(512)));
595
        assert_eq!(ByteSize::parse("4 GiB"), Some(ByteSize(4 << 30)));
596
        assert_eq!(ByteSize::parse("100kB"), Some(ByteSize(100_000)));
597
        assert_eq!(ByteSize::parse("lots"), None);
598
    }
599
600
    #[test]
601
    fn file_then_environment() {
602
        let mut cfg = Config::parse("[server]\nbind = \"0.0.0.0:7300\"\n[limits]\nrender_limit = \"1MiB\"\n").unwrap();
603
        assert_eq!(cfg.server.bind, "0.0.0.0:7300");
604
        assert_eq!(cfg.limits.render_limit, ByteSize(1 << 20));
605
        assert_eq!(cfg.site.name, "OxygenHub");
606
        cfg.apply_env(|k| match k {
607
            "OXYHUB_SITE_NAME" => Some("Earth".into()),
608
            "OXYHUB_AUTH_PUSH_TOKENS" => Some("a, b".into()),
609
            "OXYHUB_SERVER_METRICS_TOKEN" => Some("m".into()),
610
            "OXYHUB_SERVER_GRAFANA_URL" => Some("https://grafana.example".into()),
611
            _ => None,
612
        });
613
        assert_eq!(cfg.site.name, "Earth");
614
        assert_eq!(cfg.auth.push_tokens, ["a", "b"]);
615
        assert_eq!((cfg.server.metrics_token.as_str(), cfg.server.grafana_url.as_str()), ("m", "https://grafana.example"));
616
        assert!(Config::parse("[nope]\nx = 1\n").is_err(), "unknown sections are errors, not silence");
617
    }
618
619
    #[test]
620
    fn roles_default_to_all_and_unknown_names_are_errors() {
621
        let cfg = Config::default();
622
        assert_eq!(cfg.roles().unwrap(), Roles { web: true, worker: true });
623
        assert_eq!(cfg.roles().unwrap().names(), ["web", "worker"]);
624
        assert_eq!(Roles::from_names(&["worker"]).unwrap(), Roles { web: false, worker: true });
625
        assert_eq!(Roles::from_names(&[" Web ", "web"]).unwrap().names(), ["web"]);
626
        assert_eq!(Roles::from_names(&["worker", "web"]).unwrap().names(), ["web", "worker"]);
627
        assert_eq!(Roles::from_names::<&str>(&[]).unwrap(), Roles::default());
628
        let e = Roles::from_names(&["web", "edge"]).unwrap_err();
629
        assert_eq!(e, "unknown role \"edge\": the roles are web and worker");
630
631
        let mut cfg = Config::parse("[server]\nroles = [\"worker\"]\n").unwrap();
632
        assert_eq!(cfg.roles().unwrap().names(), ["worker"]);
633
        cfg.apply_env(|k| (k == "OXYHUB_SERVER_ROLES").then(|| "web, worker".into()));
634
        assert_eq!(cfg.roles().unwrap(), Roles::default());
635
        cfg.apply_env(|k| (k == "OXYHUB_SERVER_ROLES").then(|| "store".into()));
636
        assert!(cfg.roles().unwrap_err().to_string().contains("unknown role \"store\""));
637
    }
638
639
    #[test]
640
    fn an_unknown_role_in_hub_toml_stops_loading() {
641
        let dir = tempfile::tempdir().unwrap();
642
        std::fs::write(dir.path().join("hub.toml"), "[server]\nroles = [\"wrker\"]\n").unwrap();
643
        let e = Config::load(dir.path()).unwrap_err().to_string();
644
        assert!(e.contains("unknown role \"wrker\""), "{e}");
645
    }
646
}