OXYGENHUB
# 5dead1f4f26d oxygenhub / crates / hub / src / config.rs
11.1 KiB · Rust · last changed Serve the releases' .debs as a signed apt repository at /apt 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
}
158
159
/// A byte count written as `512`, `2MiB`, `4GiB`, `100kB`.
160
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
161
pub struct ByteSize(pub u64);
162
163
impl ByteSize {
164
    pub fn parse(s: &str) -> Option<ByteSize> {
165
        let s = s.trim();
166
        let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();
167
        let unit = s[digits.len()..].trim();
168
        let n: u64 = digits.parse().ok()?;
169
        let mult = match unit {
170
            "" | "B" => 1,
171
            "k" | "kB" | "KB" => 1000,
172
            "KiB" | "K" => 1 << 10,
173
            "M" | "MB" => 1_000_000,
174
            "MiB" => 1 << 20,
175
            "G" | "GB" => 1_000_000_000,
176
            "GiB" => 1 << 30,
177
            _ => return None,
178
        };
179
        Some(ByteSize(n.checked_mul(mult)?))
180
    }
181
}
182
183
impl<'de> Deserialize<'de> for ByteSize {
184
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<ByteSize, D::Error> {
185
        #[derive(Deserialize)]
186
        #[serde(untagged)]
187
        enum Raw {
188
            Number(u64),
189
            Text(String),
190
        }
191
        match Raw::deserialize(d)? {
192
            Raw::Number(n) => Ok(ByteSize(n)),
193
            Raw::Text(t) => ByteSize::parse(&t).ok_or_else(|| serde::de::Error::custom(format!("not a byte size: {t:?}"))),
194
        }
195
    }
196
}
197
198
impl Default for Site {
199
    fn default() -> Self {
200
        Site { name: "OxygenHub".into(), description: "Repositories, proposals and issues for Oxygen".into() }
201
    }
202
}
203
204
impl Default for Server {
205
    fn default() -> Self {
206
        Server { bind: "127.0.0.1:7300".into(), tls_bind: String::new(), base_url: "http://127.0.0.1:7300".into(), behind_proxy: false }
207
    }
208
}
209
210
impl Default for Tls {
211
    fn default() -> Self {
212
        Tls { self_signed: false, cert: "keys/tls.crt".into(), key: "keys/tls.key".into() }
213
    }
214
}
215
216
impl Default for Limits {
217
    fn default() -> Self {
218
        Limits { render_limit: ByteSize(2 << 20), asset_limit: ByteSize(512 << 20), push_body_limit: ByteSize(4 << 30) }
219
    }
220
}
221
222
impl Default for Retention {
223
    fn default() -> Self {
224
        Retention { trash_days: 30, webhook_log_days: 30 }
225
    }
226
}
227
228
impl Default for Config {
229
    fn default() -> Self {
230
        Config {
231
            data: PathBuf::from("data"),
232
            site: Site::default(),
233
            server: Server::default(),
234
            tls: Tls::default(),
235
            auth: Auth::default(),
236
            registration: Registration::default(),
237
            email: Email::default(),
238
            limits: Limits::default(),
239
            retention: Retention::default(),
240
            flow: Flow::default(),
241
            apt: Apt::default(),
242
        }
243
    }
244
}
245
246
impl Config {
247
    /// Read `<data>/hub.toml` if present, then apply environment overrides.
248
    pub fn load(data: &Path) -> anyhow::Result<Config> {
249
        let path = data.join("hub.toml");
250
        let mut cfg = match std::fs::read_to_string(&path) {
251
            Ok(text) => Config::parse(&text)?,
252
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Config::default(),
253
            Err(e) => return Err(anyhow::anyhow!("reading {}: {e}", path.display())),
254
        };
255
        cfg.data = data.to_path_buf();
256
        cfg.apply_env(|k| std::env::var(k).ok());
257
        Ok(cfg)
258
    }
259
260
    pub fn parse(text: &str) -> anyhow::Result<Config> {
261
        Ok(toml::from_str(text)?)
262
    }
263
264
    /// `OXYHUB_SERVER_BIND`, `OXYHUB_SITE_NAME`, … override the file.
265
    pub fn apply_env(&mut self, get: impl Fn(&str) -> Option<String>) {
266
        if let Some(v) = get("OXYHUB_SITE_NAME") {
267
            self.site.name = v;
268
        }
269
        if let Some(v) = get("OXYHUB_SITE_DESCRIPTION") {
270
            self.site.description = v;
271
        }
272
        if let Some(v) = get("OXYHUB_SERVER_BIND") {
273
            self.server.bind = v;
274
        }
275
        if let Some(v) = get("OXYHUB_SERVER_TLS_BIND") {
276
            self.server.tls_bind = v;
277
        }
278
        if let Some(v) = get("OXYHUB_SERVER_BASE_URL") {
279
            self.server.base_url = v;
280
        }
281
        if let Some(v) = get("OXYHUB_SERVER_BEHIND_PROXY") {
282
            self.server.behind_proxy = matches!(v.as_str(), "1" | "true" | "yes");
283
        }
284
        if let Some(v) = get("OXYHUB_TLS_SELF_SIGNED") {
285
            self.tls.self_signed = matches!(v.as_str(), "1" | "true" | "yes");
286
        }
287
        if let Some(v) = get("OXYHUB_REGISTRATION_MODE") {
288
            self.registration.mode = v;
289
        }
290
        if let Some(v) = get("OXYHUB_AUTH_PUSH_TOKENS") {
291
            self.auth.push_tokens = v.split(',').map(str::trim).filter(|s| !s.is_empty()).map(String::from).collect();
292
        }
293
        if let Some(v) = get("OXYHUB_LIMITS_RENDER_LIMIT").and_then(|v| ByteSize::parse(&v)) {
294
            self.limits.render_limit = v;
295
        }
296
    }
297
298
    pub fn bind_addr(&self) -> anyhow::Result<Option<SocketAddr>> {
299
        parse_addr(&self.server.bind)
300
    }
301
302
    pub fn tls_bind_addr(&self) -> anyhow::Result<Option<SocketAddr>> {
303
        parse_addr(&self.server.tls_bind)
304
    }
305
306
    pub fn tls_cert(&self) -> PathBuf {
307
        self.data.join(&self.tls.cert)
308
    }
309
310
    pub fn tls_key(&self) -> PathBuf {
311
        self.data.join(&self.tls.key)
312
    }
313
314
    pub fn repos_dir(&self) -> PathBuf {
315
        self.data.join("repos")
316
    }
317
318
    pub fn keys_dir(&self) -> PathBuf {
319
        self.data.join("keys")
320
    }
321
322
    pub fn db_path(&self) -> PathBuf {
323
        self.data.join("hub.db")
324
    }
325
326
    /// The base URL without a trailing slash.
327
    pub fn base_url(&self) -> &str {
328
        self.server.base_url.trim_end_matches('/')
329
    }
330
}
331
332
fn parse_addr(s: &str) -> anyhow::Result<Option<SocketAddr>> {
333
    if s.trim().is_empty() {
334
        return Ok(None);
335
    }
336
    Ok(Some(s.parse().map_err(|e| anyhow::anyhow!("bind address {s:?}: {e}"))?))
337
}
338
339
#[cfg(test)]
340
mod tests {
341
    use super::*;
342
343
    #[test]
344
    fn byte_sizes() {
345
        assert_eq!(ByteSize::parse("2MiB"), Some(ByteSize(2 << 20)));
346
        assert_eq!(ByteSize::parse("512"), Some(ByteSize(512)));
347
        assert_eq!(ByteSize::parse("4 GiB"), Some(ByteSize(4 << 30)));
348
        assert_eq!(ByteSize::parse("100kB"), Some(ByteSize(100_000)));
349
        assert_eq!(ByteSize::parse("lots"), None);
350
    }
351
352
    #[test]
353
    fn file_then_environment() {
354
        let mut cfg = Config::parse("[server]\nbind = \"0.0.0.0:7300\"\n[limits]\nrender_limit = \"1MiB\"\n").unwrap();
355
        assert_eq!(cfg.server.bind, "0.0.0.0:7300");
356
        assert_eq!(cfg.limits.render_limit, ByteSize(1 << 20));
357
        assert_eq!(cfg.site.name, "OxygenHub");
358
        cfg.apply_env(|k| match k {
359
            "OXYHUB_SITE_NAME" => Some("Earth".into()),
360
            "OXYHUB_AUTH_PUSH_TOKENS" => Some("a, b".into()),
361
            _ => None,
362
        });
363
        assert_eq!(cfg.site.name, "Earth");
364
        assert_eq!(cfg.auth.push_tokens, ["a", "b"]);
365
        assert!(Config::parse("[nope]\nx = 1\n").is_err(), "unknown sections are errors, not silence");
366
    }
367
}