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