summaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: 8e303d451e9b7f1fe838d26dcb6d3673450805cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
//! Filesystem layout and runtime configuration.
//!
//! Everything the server owns lives under one root directory so a test can point
//! the whole application at a `tempdir` and get an isolated instance. The heavy
//! bytes (packages, logs, mirrors) live on the filesystem and are referenced by
//! path from the DB (DESIGN.md §11a).

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

/// Runtime configuration. Persisted as `<root>/config.json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    /// Root directory holding db, mirrors, caches, store, repo and logs.
    pub root: PathBuf,
    /// Name of the single pacman repo we publish (DESIGN.md §9, decision 4).
    pub repo_name: String,
    /// Architecture, fixed to x86_64 by decision 17.
    pub arch: String,
    /// GPG key id used to sign packages *and* the database (decision 22).
    pub signing_key_id: String,
    /// Address the HTTP UI binds to. Default is loopback only (§14).
    pub bind: String,
    /// Shared credential for the UI. Single user, one credential, no user table.
    pub password: String,
    /// Public base URL used in consumer-facing snippets.
    pub base_url: String,
    /// devtools build profile (§8.3).
    pub build_profile: String,
    /// Path to the git executable.
    pub git_bin: String,
    /// Path to the makepkg executable.
    pub makepkg_bin: String,
    /// Path to makechrootpkg.
    pub makechrootpkg_bin: String,
    /// Path to mkarchroot.
    pub mkarchroot_bin: String,
    /// Package list handed to `mkarchroot` after the working directory, i.e.
    /// what goes into the warm root. The default is the real devtools usage
    /// (`mkarchroot <dir> base`); there is no `-N` flag on the real tool, so
    /// hardcoding one would make the first real-chroot run fail on its first
    /// step. Kept configurable because a site may want a smaller seed.
    #[serde(default = "default_mkarchroot_args")]
    pub mkarchroot_args: Vec<String>,
    /// Path to repo-add.
    pub repo_add_bin: String,
    /// Path to gpg.
    pub gpg_bin: String,
    /// Unprivileged user that runs PKGBUILD code (§14). Empty = current user.
    pub build_user: String,
    /// Test-only hooks (§16a). Not part of the production configuration at all
    /// unless the crate is built with `test-support` — see [`TestHooks`].
    #[cfg(feature = "test-support")]
    #[serde(default, skip_serializing_if = "TestHooks::is_empty")]
    pub hooks: TestHooks,
    /// How many builds may run at once (§8.2 backpressure). Default 1, which
    /// also means the chroot pool only needs one warm root.
    pub max_concurrent_builds: usize,
    /// Seconds of lease a worker takes when it claims a build (§8.2).
    pub lease_secs: i64,
    /// A build is not admitted unless at least this much free space remains
    /// on the filesystem holding `root` (§8.2 disk headroom).
    pub min_free_disk_mb: u64,
    /// Transient step failures are retried up to this many attempts; a
    /// deterministic build failure is never retried (§8.4).
    pub max_transient_attempts: i64,
    /// Seconds between dispatcher passes.
    pub dispatch_tick_secs: u64,
}

/// The test harness's handles on a real pipeline (§16a), grouped into one
/// submodule so the production configuration says what it is.
///
/// Each of these exists because a *fake* pipeline would test something else:
/// I4 (atomic publish) needs a process that really dies between the tmp write
/// and the rename; I5 needs a step that really dies mid-child; I9 needs a
/// PKGBUILD that really reaches outside its staging dir. The alternative was a
/// mock that asserts the mock's own behaviour.
///
/// They are compiled out entirely unless the crate is built with the
/// `test-support` feature (the same feature that gates the shims, §6 M-4), so a
/// production binary has no fault-injection branch in its publish path and no
/// shim protocol in its child environment. The test suite enables the feature
/// through a dev-dependency on this crate, and nothing else does.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct TestHooks {
    /// Directory prepended to PATH for child processes: the toolchain shims.
    pub path_prepend: Option<PathBuf>,
    /// Fixture manifest the shims should obey, exported as `AUR_SHIM_MANIFEST`.
    pub shim_manifest: Option<PathBuf>,
    /// Where shims record their invocations, exported as `AUR_SHIM_DIR`.
    pub shim_dir: Option<PathBuf>,
    /// Abort publish at a named point so I4 (atomic publish) can be exercised
    /// for real: `before-rename` or `after-rename`.
    pub publish_fault: Option<String>,
    /// The named shim must fail, e.g. `makechrootpkg`.
    pub shim_fail: Option<String>,
    /// The named shim SIGKILLs its parent — the process running the pipeline —
    /// mid-step. This is how a real crash is reproduced for I5: not a caught
    /// error, an uncatchable death.
    pub shim_kill_parent: Option<String>,
    /// Make the build shim plant a symlink to this path in its srcdir, so a test
    /// can act out the I9 attack: an untrusted PKGBUILD smuggling bytes in from
    /// outside its own staging dir.
    pub shim_plant_link: Option<String>,
}

impl TestHooks {
    /// True when nothing is hooked — the state every real process runs in.
    pub fn is_empty(&self) -> bool {
        self.path_prepend.is_none()
            && self.shim_manifest.is_none()
            && self.shim_dir.is_none()
            && self.publish_fault.is_none()
            && self.shim_fail.is_none()
            && self.shim_kill_parent.is_none()
            && self.shim_plant_link.is_none()
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            root: PathBuf::from("/var/lib/aur-build"),
            repo_name: "aur-build".into(),
            arch: "x86_64".into(),
            signing_key_id: String::new(),
            bind: "127.0.0.1:8484".into(),
            password: String::new(),
            base_url: "http://127.0.0.1:8484".into(),
            build_profile: "extra-x86_64".into(),
            git_bin: "git".into(),
            makepkg_bin: "makepkg".into(),
            makechrootpkg_bin: "makechrootpkg".into(),
            mkarchroot_bin: "mkarchroot".into(),
            mkarchroot_args: default_mkarchroot_args(),
            repo_add_bin: "repo-add".into(),
            gpg_bin: "gpg".into(),
            build_user: String::new(),
            #[cfg(feature = "test-support")]
            hooks: TestHooks::default(),
            max_concurrent_builds: 1,
            lease_secs: 90,
            min_free_disk_mb: 1024,
            max_transient_attempts: 3,
            dispatch_tick_secs: 2,
        }
    }
}

impl Config {
    /// Read `<root>/config.json`.
    ///
    /// The crate's own error type, like everything else that can fail (m-15):
    /// `anyhow::Result` here meant two error vocabularies in one crate, and the
    /// one thing a caller can actually branch on — "there is no config yet, run
    /// init" — arrived as an opaque string.
    pub fn load(root: &Path) -> crate::error::Result<Self> {
        let p = root.join("config.json");
        if !p.exists() {
            return Err(crate::error::Error::not_found(format!(
                "no config at {}; run `aur-build init`",
                p.display()
            )));
        }
        let s = std::fs::read_to_string(&p)?;
        let mut cfg: Config = serde_json::from_str(&s)?;
        // root inside the config file is relative to the config's directory
        // unless it is absolute; that keeps a moved tree usable.
        if !cfg.root.is_absolute() {
            cfg.root = root.join(&cfg.root);
        }
        Ok(cfg)
    }

    pub fn save(&self) -> crate::error::Result<()> {
        std::fs::create_dir_all(&self.root)?;
        std::fs::write(
            self.root.join("config.json"),
            serde_json::to_string_pretty(self)? + "\n",
        )?;
        Ok(())
    }

    /// Environment for a child process: PATH with the shims in front, plus the
    /// shim protocol variables (§16a).
    #[cfg_attr(not(feature = "test-support"), allow(unused_variables))]
    pub fn child_env(&self, cmd: &mut std::process::Command) {
        // Without `test-support` there is no shim protocol to export and no
        // PATH to rewrite: the child inherits the real environment, which is
        // what a real build needs (§16a).
        #[cfg(feature = "test-support")]
        {
            let h = &self.hooks;
            if let Some(dir) = &h.path_prepend {
                let path = std::env::var("PATH").unwrap_or_default();
                cmd.env("PATH", format!("{}:{path}", dir.display()));
            }
            if let Some(m) = &h.shim_manifest {
                cmd.env("AUR_SHIM_MANIFEST", m);
            }
            if let Some(d) = &h.shim_dir {
                cmd.env("AUR_SHIM_DIR", d);
            }
            if let Some(f) = &h.shim_fail {
                cmd.env("AUR_SHIM_FAIL", f);
            }
            if let Some(k) = &h.shim_kill_parent {
                cmd.env("AUR_SHIM_KILL_PARENT", k);
            }
            if let Some(l) = &h.shim_plant_link {
                cmd.env("AUR_SHIM_PLANT_LINK", l);
            }
        }
    }

    /// Create the directory tree the server needs. Idempotent.
    pub fn ensure_dirs(&self) -> crate::error::Result<()> {
        for d in [
            self.root.clone(),
            self.mirrors_dir(),
            self.vcs_cache_dir(),
            self.source_cache_dir(),
            self.staging_dir(),
            self.store_dir(),
            self.log_dir(),
            self.repo_dir(),
            self.chroot_dir(),
        ] {
            std::fs::create_dir_all(d)?;
        }
        std::fs::create_dir_all(self.repo_arch_dir())?;
        Ok(())
    }

    pub fn db_path(&self) -> PathBuf {
        self.root.join("aur-build.db")
    }
    /// Local AUR git mirrors, one clone per pkgbase (§5.1). Load-bearing, not a
    /// cache: it is what makes historical releases rebuildable (§5.1a).
    pub fn mirrors_dir(&self) -> PathBuf {
        self.root.join("mirrors")
    }
    pub fn mirror_path(&self, pkgbase: &str) -> PathBuf {
        self.mirrors_dir().join(format!("{pkgbase}.git"))
    }
    /// Persistent upstream VCS clones (§5.2 cost control).
    pub fn vcs_cache_dir(&self) -> PathBuf {
        self.root.join("vcs_cache")
    }
    pub fn vcs_cache_path(&self, url: &str) -> PathBuf {
        let h = crate::hash::short(url.as_bytes(), 16);
        self.vcs_cache_dir().join(format!("{}-{}.git", slug(url), h))
    }
    /// Content-addressed download cache reused by the build (§5.3).
    pub fn source_cache_dir(&self) -> PathBuf {
        self.root.join("source_cache")
    }
    pub fn source_cache_path(&self, digest: &str) -> PathBuf {
        self.source_cache_dir().join(&digest[..2.min(digest.len())]).join(digest)
    }
    /// Disposable per-build workspace (§8.2).
    pub fn staging_dir(&self) -> PathBuf {
        self.root.join("staging")
    }
    pub fn staging_build_dir(&self, build_id: &str) -> PathBuf {
        self.staging_dir().join(build_id)
    }
    /// Content-addressed artifact store.
    pub fn store_dir(&self) -> PathBuf {
        self.root.join("store")
    }
    pub fn store_path(&self, digest: &str) -> PathBuf {
        self.store_dir().join(&digest[..2.min(digest.len())]).join(digest)
    }
    pub fn log_dir(&self) -> PathBuf {
        self.root.join("logs")
    }
    pub fn build_log_path(&self, build_id: &str) -> PathBuf {
        self.log_dir().join(format!("{build_id}.log"))
    }
    /// The served repo tree: `<repo>/<name>/os/<arch>/` (§9).
    pub fn repo_dir(&self) -> PathBuf {
        self.root.join("repo")
    }
    pub fn repo_arch_dir(&self) -> PathBuf {
        self.repo_dir()
            .join(&self.repo_name)
            .join("os")
            .join(&self.arch)
    }
    pub fn repo_db_name(&self) -> String {
        format!("{}.db", self.repo_name)
    }
    /// Warm chroot seeds, one per profile (§8.3).
    pub fn chroot_dir(&self) -> PathBuf {
        self.root.join("chroot")
    }
    pub fn chroot_seed(&self, profile: &str) -> PathBuf {
        self.chroot_dir().join(profile)
    }
}

/// Filesystem-safe slug for a URL, used in cache filenames.
fn default_mkarchroot_args() -> Vec<String> {
    vec!["base".to_string()]
}

pub fn slug(url: &str) -> String {
    url.chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '-'
            }
        })
        .collect::<String>()
        .trim_matches('-')
        .chars()
        .take(32)
        .collect()
}