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