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