OXYGENHUB
◆ v0.5.1 oxygenhub / crates / hub / src / config.rs
13.2 KiB · Rust · last changed Alerts: a failed run tells its pusher and watchers; an erroring runner is drained 21 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
}
27
28
/// Backups (docs/backups.md, oxygenhub#169): the directories on this host
29
/// an owner may back up to. Empty, only GCS destinations can be chosen.
30
#[derive(Clone, Debug, Deserialize)]
31
#[serde(default, deny_unknown_fields)]
32
pub struct Backups {
33
    pub directories: Vec<PathBuf>,
34
    /// Google's token exchange and Cloud Storage, for GCS destinations;
35
    /// set only to point them elsewhere (tests, a private endpoint).
36
    pub sts_url: String,
37
    pub storage_url: String,
38
    /// AWS STS and S3, for S3 destinations; `{bucket}` and `{region}` in
39
    /// `s3_url` are filled in. Set only to point them elsewhere.
40
    pub aws_sts_url: String,
41
    pub s3_url: String,
42
}
43
44
impl Default for Backups {
45
    fn default() -> Self {
46
        Backups {
47
            directories: Vec::new(),
48
            sts_url: "https://sts.googleapis.com".into(),
49
            storage_url: "https://storage.googleapis.com".into(),
50
            aws_sts_url: "https://sts.amazonaws.com".into(),
51
            s3_url: "https://{bucket}.s3.{region}.amazonaws.com".into(),
52
        }
53
    }
54
}
55
56
/// Diffusion (#148, docs/diffusion.md §4.2): the site's default for
57
/// repositories that say nothing.
58
#[derive(Clone, Debug, Deserialize)]
59
#[serde(default, deny_unknown_fields)]
60
pub struct Diffusion {
61
    /// `off`, `green` or `any`.
62
    pub follow: String,
63
}
64
65
impl Default for Diffusion {
66
    fn default() -> Self {
67
        Diffusion { follow: "off".into() }
68
    }
69
}
70
71
/// The apt repository at `/apt` (oxygenhub#85): the `.deb` assets of these
72
/// public repositories' releases, signed with the key in `gnupg_home`.
73
#[derive(Clone, Debug, Deserialize)]
74
#[serde(default, deny_unknown_fields)]
75
pub struct Apt {
76
    /// `owner/name` of each repository whose release `.deb`s are served;
77
    /// none turns `/apt` off.
78
    pub repos: Vec<String>,
79
    /// The suite apt's `sources` names.
80
    pub suite: String,
81
    pub component: String,
82
    /// GnuPG home holding the signing key (relative to the data directory).
83
    pub gnupg_home: String,
84
    /// Architectures the index lists, each with its Packages file.
85
    pub architectures: Vec<String>,
86
}
87
88
impl Default for Apt {
89
    fn default() -> Self {
90
        Apt {
91
            repos: vec![],
92
            suite: "stable".into(),
93
            component: "main".into(),
94
            gnupg_home: "apt-gnupg".into(),
95
            architectures: vec!["amd64".into(), "arm64".into(), "riscv64".into()],
96
        }
97
    }
98
}
99
100
/// OxygenFlow runs (hub spec §13.2).
101
#[derive(Clone, Debug, Deserialize)]
102
#[serde(default, deny_unknown_fields)]
103
pub struct Flow {
104
    /// Bearer tokens runners present to claim jobs.
105
    pub runner_tokens: Vec<String>,
106
    /// `owner/*` or `owner/name`: repositories whose pushes start runs.
107
    pub repos: Vec<String>,
108
    pub job_timeout_minutes: u64,
109
    /// A runner whose last this many jobs all ended in an infrastructure
110
    /// error (status `error`, not `failed`) is drained and the
111
    /// administrators told (oxygenflow#30); 0 never drains one.
112
    pub drain_after_errors: u32,
113
}
114
115
impl Default for Flow {
116
    fn default() -> Self {
117
        Flow { runner_tokens: vec![], repos: vec![], job_timeout_minutes: 60, drain_after_errors: 5 }
118
    }
119
}
120
121
impl Flow {
122
    /// Whether pushes to `owner/name` start runs.
123
    pub fn allows(&self, owner: &str, name: &str) -> bool {
124
        self.repos.iter().any(|p| match p.split_once('/') {
125
            Some((o, "*")) => o == owner,
126
            Some((o, n)) => o == owner && n == name,
127
            None => false,
128
        })
129
    }
130
}
131
132
#[derive(Clone, Debug, Default, Deserialize)]
133
#[serde(default, deny_unknown_fields)]
134
pub struct Email {
135
    /// `smtp://user:pass@host:port` or `smtps://…`; empty disables email.
136
    pub smtp: String,
137
    /// `OxygenHub <hub@example>`.
138
    pub from: String,
139
}
140
141
#[derive(Clone, Debug, Deserialize)]
142
#[serde(default, deny_unknown_fields)]
143
pub struct Registration {
144
    /// `open`, `invite` or `closed`; the admin page can override it.
145
    pub mode: String,
146
}
147
148
impl Default for Registration {
149
    fn default() -> Self {
150
        Registration { mode: "invite".into() }
151
    }
152
}
153
154
#[derive(Clone, Debug, Deserialize)]
155
#[serde(default, deny_unknown_fields)]
156
pub struct Site {
157
    pub name: String,
158
    pub description: String,
159
}
160
161
#[derive(Clone, Debug, Deserialize)]
162
#[serde(default, deny_unknown_fields)]
163
pub struct Server {
164
    /// Plain HTTP; empty disables it.
165
    pub bind: String,
166
    /// HTTPS; empty disables it. Needs `tls`.
167
    pub tls_bind: String,
168
    /// What links and clone URLs start with.
169
    pub base_url: String,
170
    /// Trust `X-Forwarded-*` from a terminating proxy.
171
    pub behind_proxy: bool,
172
}
173
174
#[derive(Clone, Debug, Deserialize)]
175
#[serde(default, deny_unknown_fields)]
176
pub struct Tls {
177
    /// Generate a certificate at `init` (developer edition).
178
    pub self_signed: bool,
179
    /// PEM files; relative paths are under the data directory.
180
    pub cert: String,
181
    pub key: String,
182
}
183
184
#[derive(Clone, Debug, Default, Deserialize)]
185
#[serde(default, deny_unknown_fields)]
186
pub struct Auth {
187
    /// Bearer tokens allowed to push until accounts exist (hub 0.2). Empty
188
    /// means every push is accepted, as `oxy serve` does.
189
    pub push_tokens: Vec<String>,
190
    /// For tests only: a base URL that stands in for every sign-in
191
    /// provider (`{base}/{provider}/authorize|token|userinfo`).
192
    pub signin_mock: Option<String>,
193
}
194
195
#[derive(Clone, Debug, Deserialize)]
196
#[serde(default, deny_unknown_fields)]
197
pub struct Limits {
198
    /// Largest file rendered in the browser, e.g. `2MiB`.
199
    pub render_limit: ByteSize,
200
    pub asset_limit: ByteSize,
201
    pub push_body_limit: ByteSize,
202
}
203
204
#[derive(Clone, Debug, Deserialize)]
205
#[serde(default, deny_unknown_fields)]
206
pub struct Retention {
207
    pub trash_days: u32,
208
    pub webhook_log_days: u32,
209
    /// The UTC hour at which every repository is garbage collected
210
    /// (spec §17.2); 24 or more turns the nightly gc off.
211
    pub gc_hour: u32,
212
}
213
214
/// A byte count written as `512`, `2MiB`, `4GiB`, `100kB`.
215
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
216
pub struct ByteSize(pub u64);
217
218
impl ByteSize {
219
    pub fn parse(s: &str) -> Option<ByteSize> {
220
        let s = s.trim();
221
        let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();
222
        let unit = s[digits.len()..].trim();
223
        let n: u64 = digits.parse().ok()?;
224
        let mult = match unit {
225
            "" | "B" => 1,
226
            "k" | "kB" | "KB" => 1000,
227
            "KiB" | "K" => 1 << 10,
228
            "M" | "MB" => 1_000_000,
229
            "MiB" => 1 << 20,
230
            "G" | "GB" => 1_000_000_000,
231
            "GiB" => 1 << 30,
232
            _ => return None,
233
        };
234
        Some(ByteSize(n.checked_mul(mult)?))
235
    }
236
}
237
238
impl<'de> Deserialize<'de> for ByteSize {
239
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<ByteSize, D::Error> {
240
        #[derive(Deserialize)]
241
        #[serde(untagged)]
242
        enum Raw {
243
            Number(u64),
244
            Text(String),
245
        }
246
        match Raw::deserialize(d)? {
247
            Raw::Number(n) => Ok(ByteSize(n)),
248
            Raw::Text(t) => ByteSize::parse(&t).ok_or_else(|| serde::de::Error::custom(format!("not a byte size: {t:?}"))),
249
        }
250
    }
251
}
252
253
impl Default for Site {
254
    fn default() -> Self {
255
        Site { name: "OxygenHub".into(), description: "Repositories, proposals and issues for Oxygen".into() }
256
    }
257
}
258
259
impl Default for Server {
260
    fn default() -> Self {
261
        Server { bind: "127.0.0.1:7300".into(), tls_bind: String::new(), base_url: "http://127.0.0.1:7300".into(), behind_proxy: false }
262
    }
263
}
264
265
impl Default for Tls {
266
    fn default() -> Self {
267
        Tls { self_signed: false, cert: "keys/tls.crt".into(), key: "keys/tls.key".into() }
268
    }
269
}
270
271
impl Default for Limits {
272
    fn default() -> Self {
273
        Limits { render_limit: ByteSize(2 << 20), asset_limit: ByteSize(512 << 20), push_body_limit: ByteSize(4 << 30) }
274
    }
275
}
276
277
impl Default for Retention {
278
    fn default() -> Self {
279
        Retention { trash_days: 30, webhook_log_days: 30, gc_hour: 3 }
280
    }
281
}
282
283
impl Default for Config {
284
    fn default() -> Self {
285
        Config {
286
            data: PathBuf::from("data"),
287
            site: Site::default(),
288
            server: Server::default(),
289
            tls: Tls::default(),
290
            auth: Auth::default(),
291
            registration: Registration::default(),
292
            email: Email::default(),
293
            limits: Limits::default(),
294
            retention: Retention::default(),
295
            flow: Flow::default(),
296
            apt: Apt::default(),
297
            diffusion: Diffusion::default(),
298
            backups: Backups::default(),
299
        }
300
    }
301
}
302
303
impl Config {
304
    /// Read `<data>/hub.toml` if present, then apply environment overrides.
305
    pub fn load(data: &Path) -> anyhow::Result<Config> {
306
        let path = data.join("hub.toml");
307
        let mut cfg = match std::fs::read_to_string(&path) {
308
            Ok(text) => Config::parse(&text)?,
309
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Config::default(),
310
            Err(e) => return Err(anyhow::anyhow!("reading {}: {e}", path.display())),
311
        };
312
        cfg.data = data.to_path_buf();
313
        cfg.apply_env(|k| std::env::var(k).ok());
314
        Ok(cfg)
315
    }
316
317
    pub fn parse(text: &str) -> anyhow::Result<Config> {
318
        Ok(toml::from_str(text)?)
319
    }
320
321
    /// `OXYHUB_SERVER_BIND`, `OXYHUB_SITE_NAME`, … override the file.
322
    pub fn apply_env(&mut self, get: impl Fn(&str) -> Option<String>) {
323
        if let Some(v) = get("OXYHUB_SITE_NAME") {
324
            self.site.name = v;
325
        }
326
        if let Some(v) = get("OXYHUB_SITE_DESCRIPTION") {
327
            self.site.description = v;
328
        }
329
        if let Some(v) = get("OXYHUB_SERVER_BIND") {
330
            self.server.bind = v;
331
        }
332
        if let Some(v) = get("OXYHUB_SERVER_TLS_BIND") {
333
            self.server.tls_bind = v;
334
        }
335
        if let Some(v) = get("OXYHUB_SERVER_BASE_URL") {
336
            self.server.base_url = v;
337
        }
338
        if let Some(v) = get("OXYHUB_SERVER_BEHIND_PROXY") {
339
            self.server.behind_proxy = matches!(v.as_str(), "1" | "true" | "yes");
340
        }
341
        if let Some(v) = get("OXYHUB_TLS_SELF_SIGNED") {
342
            self.tls.self_signed = matches!(v.as_str(), "1" | "true" | "yes");
343
        }
344
        if let Some(v) = get("OXYHUB_REGISTRATION_MODE") {
345
            self.registration.mode = v;
346
        }
347
        if let Some(v) = get("OXYHUB_AUTH_PUSH_TOKENS") {
348
            self.auth.push_tokens = v.split(',').map(str::trim).filter(|s| !s.is_empty()).map(String::from).collect();
349
        }
350
        if let Some(v) = get("OXYHUB_LIMITS_RENDER_LIMIT").and_then(|v| ByteSize::parse(&v)) {
351
            self.limits.render_limit = v;
352
        }
353
    }
354
355
    pub fn bind_addr(&self) -> anyhow::Result<Option<SocketAddr>> {
356
        parse_addr(&self.server.bind)
357
    }
358
359
    pub fn tls_bind_addr(&self) -> anyhow::Result<Option<SocketAddr>> {
360
        parse_addr(&self.server.tls_bind)
361
    }
362
363
    pub fn tls_cert(&self) -> PathBuf {
364
        self.data.join(&self.tls.cert)
365
    }
366
367
    pub fn tls_key(&self) -> PathBuf {
368
        self.data.join(&self.tls.key)
369
    }
370
371
    pub fn repos_dir(&self) -> PathBuf {
372
        self.data.join("repos")
373
    }
374
375
    pub fn keys_dir(&self) -> PathBuf {
376
        self.data.join("keys")
377
    }
378
379
    pub fn db_path(&self) -> PathBuf {
380
        self.data.join("hub.db")
381
    }
382
383
    /// The base URL without a trailing slash.
384
    pub fn base_url(&self) -> &str {
385
        self.server.base_url.trim_end_matches('/')
386
    }
387
}
388
389
fn parse_addr(s: &str) -> anyhow::Result<Option<SocketAddr>> {
390
    if s.trim().is_empty() {
391
        return Ok(None);
392
    }
393
    Ok(Some(s.parse().map_err(|e| anyhow::anyhow!("bind address {s:?}: {e}"))?))
394
}
395
396
#[cfg(test)]
397
mod tests {
398
    use super::*;
399
400
    #[test]
401
    fn byte_sizes() {
402
        assert_eq!(ByteSize::parse("2MiB"), Some(ByteSize(2 << 20)));
403
        assert_eq!(ByteSize::parse("512"), Some(ByteSize(512)));
404
        assert_eq!(ByteSize::parse("4 GiB"), Some(ByteSize(4 << 30)));
405
        assert_eq!(ByteSize::parse("100kB"), Some(ByteSize(100_000)));
406
        assert_eq!(ByteSize::parse("lots"), None);
407
    }
408
409
    #[test]
410
    fn file_then_environment() {
411
        let mut cfg = Config::parse("[server]\nbind = \"0.0.0.0:7300\"\n[limits]\nrender_limit = \"1MiB\"\n").unwrap();
412
        assert_eq!(cfg.server.bind, "0.0.0.0:7300");
413
        assert_eq!(cfg.limits.render_limit, ByteSize(1 << 20));
414
        assert_eq!(cfg.site.name, "OxygenHub");
415
        cfg.apply_env(|k| match k {
416
            "OXYHUB_SITE_NAME" => Some("Earth".into()),
417
            "OXYHUB_AUTH_PUSH_TOKENS" => Some("a, b".into()),
418
            _ => None,
419
        });
420
        assert_eq!(cfg.site.name, "Earth");
421
        assert_eq!(cfg.auth.push_tokens, ["a", "b"]);
422
        assert!(Config::parse("[nope]\nx = 1\n").is_err(), "unknown sections are errors, not silence");
423
    }
424
}