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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
|
//! The ten pipeline steps (§8.1).
//!
//! Every step is idempotent and records its result in one short transaction;
//! the long-running child process happens outside any transaction (§11a).
use std::path::Path;
use std::process::Command;
use crate::db::{self, builds, model::*};
use crate::error::{Error, Result};
use crate::git;
use crate::pipeline::{Collect, CollectedPkg, Ctx, StepResult};
use crate::watch::digests::cached_path;
pub fn run_step(ctx: &Ctx, step: &str) -> Result<StepResult> {
match step {
"materialize" => materialize(ctx),
"plan" => plan(ctx),
"chroot" => chroot(ctx),
"sources" => sources(ctx),
"pkgver" => pkgver(ctx),
"build" => build(ctx),
"collect" => collect(ctx),
"verify" => verify(ctx),
"ingest" => ingest(ctx),
"publish" => publish(ctx),
other => Err(Error::invalid(format!("unknown step {other}"))),
}
}
/// Step 0 — materialize from the local mirror only, never the network, and
/// re-hash what we got. This is the `aur_commit` pin doing its job: there is no
/// path from "AUR moved since the review" to "we built it anyway".
fn materialize(ctx: &Ctx) -> Result<StepResult> {
let mirror = ctx
.pb
.mirror_path
.as_ref()
.map(Path::new)
.map(|p| p.to_path_buf())
.unwrap_or_else(|| ctx.cfg.mirror_path(&ctx.pb.name));
if !mirror.exists() {
return Err(Error::fail_closed(format!(
"mirror {} missing; refusing to fetch a recipe from the network at build time",
mirror.display()
)));
}
if ctx.src.aur_commit.is_empty() {
return Err(Error::fail_closed("no aur_commit on the source identity"));
}
let _ = std::fs::remove_dir_all(&ctx.srcdir);
git::materialize(&mirror, &ctx.src.aur_commit, &ctx.srcdir)?;
let tree = crate::watch::mirror::read_tree(&mirror, &ctx.src.aur_commit)?;
let computed = tree.recipe_hash();
if !ctx.src.recipe_hash.is_empty() && computed != ctx.src.recipe_hash {
return Err(Error::fail_closed(format!(
"recipe_hash mismatch: approved {}, materialized {}",
ctx.src.recipe_hash, computed
)));
}
ctx.log_line(&format!(
" materialized {} at {} (recipe_hash {})",
ctx.pb.name,
short(&ctx.src.aur_commit),
short(&computed)
));
Ok(StepResult::Done(Some(computed)))
}
/// A display-safe prefix; hashes are 64 hex chars but world digests can be tiny.
fn short(s: &str) -> String {
s.chars().take(12).collect()
}
/// Step 1 — resolve dependencies against the current accepted index and compute
/// the intended world. Unresolvable means "a pkgbase we subscribe to that we have
/// not published yet": block and wait, do not fail (§10.4).
fn plan(ctx: &Ctx) -> Result<StepResult> {
let recipe = recipe_at(&ctx.srcdir)?;
let mut wanted: Vec<String> = Vec::new();
for list in [&recipe.depends, &recipe.makedepends, &recipe.checkdepends] {
wanted.extend(crate::pkgver::dep_names(list));
}
wanted.sort();
wanted.dedup();
let ours = db::our_package_names(&ctx.db)?;
let mut missing = Vec::new();
let mut official = 0;
for dep in &wanted {
if ours.contains(dep) || ctx.pb.name == *dep || recipe.pkgnames.contains(dep) {
continue; // satisfied by our own index, or by this very build
}
// Anything else is only a problem if we are supposed to be publishing it.
if db::get_subscription(&ctx.db, dep)?.is_some() || db::get_pkgbase(&ctx.db, dep)?.is_some() {
missing.push(dep.clone());
} else {
official += 1;
}
}
if !missing.is_empty() {
builds::set_blocked_on(&ctx.db, &ctx.build.id, &missing)?;
return Ok(StepResult::Blocked(missing));
}
let world = crate::pipeline::publish::index_world(&ctx.db)?;
let hash = crate::hash::canonical_json(&world)?;
ctx.log_line(&format!(
" deps: {} ours/official, {} from official repos, world {}",
wanted.len() - official,
official,
short(&hash)
));
Ok(StepResult::Done(Some(hash)))
}
/// Step 2 — warm chroot seed, created once per profile and never mutated; each
/// build gets a copy-on-write snapshot from it (§8.3).
fn chroot(ctx: &Ctx) -> Result<StepResult> {
let seed = ctx.cfg.chroot_seed(&ctx.profile);
if !seed.exists() {
std::fs::create_dir_all(seed.parent().unwrap_or(&ctx.cfg.chroot_dir()))?;
let mut cmd = Command::new(&ctx.cfg.mkarchroot_bin);
// Real devtools usage: `mkarchroot [options] <working-dir> <packages...>`.
cmd.arg(&seed).args(&ctx.cfg.mkarchroot_args);
ctx.cfg.child_env(&mut cmd);
let out = cmd.output()?;
if !out.status.success() {
return Err(Error::Subprocess {
cmd: ctx.cfg.mkarchroot_bin.clone(),
detail: String::from_utf8_lossy(&out.stderr).into_owned(),
});
}
ctx.log_line(&format!(" created chroot seed {}", seed.display()));
}
Ok(StepResult::Done(Some(seed.display().to_string())))
}
/// Step 3 — make sure every source we reviewed is on disk and hashes to what the
/// candidate recorded. For a `SKIP` source this is the only verification that
/// exists, and it closes the window between "we hashed it at review time" and
/// "makepkg downloaded something else just now" (§8.1).
fn sources(ctx: &Ctx) -> Result<StepResult> {
let digests: Vec<SourceDigest> = serde_json::from_str(&ctx.src.source_digests_json).unwrap_or_default();
let mut verified = 0;
for d in &digests {
match d.kind.as_str() {
// Already materialized from the mirror at the pinned commit.
"local" => verified += 1,
// VCS kinds (git/svn/hg/bzr): honouring upstream_pins at build time
// is deferred to P1 (§20); the pkgver assertion is the interim guard.
"vcs" | "git" | "svn" | "hg" | "bzr" => verified += 1,
_ => {
let (digest, _size) = match cached_path(&ctx.db, &d.url, &d.digest) {
Some(p) => crate::hash::digest_file(&p)?,
None => crate::watch::digests::download_and_cache(&ctx.cfg, &ctx.db, &d.url)?,
};
if digest != d.digest {
return Err(Error::fail_closed(format!(
"source {} hashed to {digest} but the candidate recorded {}",
d.url, d.digest
)));
}
verified += 1;
}
}
}
ctx.log_line(&format!(" {}/{} source digests verified", verified, digests.len()));
Ok(StepResult::Done(Some(crate::hash::hex_str(
&ctx.src.source_digests_json,
))))
}
/// Step 4 — the belt-and-braces assertion that what we build is what was
/// approved. If upstream moved between approval and build, fail with both
/// versions instead of silently shipping the new one (§8.1).
fn pkgver(ctx: &Ctx) -> Result<StepResult> {
let recipe = recipe_at(&ctx.srcdir)?;
let has_vcs = recipe.source_entries.iter().any(|s| s.is_vcs());
if !has_vcs {
let want = (ctx.src.pkgver.clone(), ctx.src.pkgrel.clone());
let got = (recipe.pkgver.clone(), recipe.pkgrel.clone());
if want != got {
return Err(Error::fail_closed(format!(
"approved {}-{} but the recipe says {}-{}",
want.0, want.1, got.0, got.1
)));
}
return Ok(StepResult::Skipped("no VCS sources; pkgver is static".into()));
}
let mut cmd = Command::new(&ctx.cfg.makepkg_bin);
cmd.current_dir(&ctx.srcdir).arg("--vercheck");
ctx.cfg.child_env(&mut cmd);
let out = cmd.output()?;
if !out.status.success() {
return Err(Error::Subprocess {
cmd: ctx.cfg.makepkg_bin.clone(),
detail: String::from_utf8_lossy(&out.stderr).into_owned(),
});
}
let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
let (got_ver, got_rel) = match text.rsplit_once('-') {
Some((v, r)) => (v.to_string(), r.to_string()),
None => (text.clone(), "1".into()),
};
if got_ver != ctx.src.pkgver || got_rel != ctx.src.pkgrel {
return Err(Error::fail_closed(format!(
"approved {}-{}, upstream now resolves to {got_ver}-{got_rel}",
ctx.src.pkgver, ctx.src.pkgrel
)));
}
ctx.log_line(&format!(" pkgver resolves as approved: {text}"));
Ok(StepResult::Done(Some(text)))
}
/// Step 5 — `makechrootpkg -c -r <chroot> -- -si<key> -f`, with the log going to
/// the file the SSE tail reads.
fn build(ctx: &Ctx) -> Result<StepResult> {
let seed = ctx.cfg.chroot_seed(&ctx.profile);
let mut cmd = Command::new(&ctx.cfg.makechrootpkg_bin);
cmd.current_dir(&ctx.srcdir);
cmd.args(["-c", "-r", &seed.display().to_string(), "--"]);
if !ctx.cfg.signing_key_id.is_empty() {
cmd.arg(format!("-si{}", ctx.cfg.signing_key_id));
}
cmd.arg("-f");
ctx.cfg.child_env(&mut cmd);
let out = cmd.output()?;
// Capture the child's output into the build log regardless of outcome.
if let Some(parent) = ctx.log.parent() {
let _ = std::fs::create_dir_all(parent);
}
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&ctx.log) {
let _ = f.write_all(&out.stdout);
let _ = f.write_all(&out.stderr);
}
if !out.status.success() {
return Err(Error::Subprocess {
cmd: ctx.cfg.makechrootpkg_bin.clone(),
detail: tail(&out.stderr),
});
}
Ok(StepResult::Done(Some(crate::hash::hex_str(&format!(
"build:{}",
ctx.build.id
)))))
}
fn tail(b: &[u8]) -> String {
let s = String::from_utf8_lossy(b).trim().to_string();
let lines: Vec<&str> = s.lines().collect();
lines[lines.len().saturating_sub(6)..].join(" | ")
}
/// Step 6 — parse `.PKGINFO`/`.BUILDINFO` out of the produced artifacts (§10.1:
/// plain text in a tar, no libalpm needed).
fn collect(ctx: &Ctx) -> Result<StepResult> {
let mut pkgs = Vec::new();
let mut entries: Vec<PathBuf> = std::fs::read_dir(&ctx.srcdir)?
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.to_string_lossy().ends_with(".pkg.tar.zst"))
.collect();
entries.sort();
// I9: the build is untrusted. In production it runs in a chroot, but the
// control plane must not *depend* on that for its own safety. Everything
// below takes a path that a PKGBUILD could have arranged to exist in the
// srcdir, and the next step copies whatever that path points at into the
// content-addressed store — from where it is served from our repo and signed
// with our key. A symlink to the signing keyring, the database, or anyone's
// home directory would otherwise become a signed artifact we publish. So:
// no symlinks, and the resolved target must live inside this build's own
// staging directory. Anything else fails the build closed.
let staging_root = ctx.staging.canonicalize()?;
for path in entries {
if std::fs::symlink_metadata(&path).map(|m| m.file_type().is_symlink()).unwrap_or(true) {
return Err(Error::fail_closed(format!(
"{} is a symlink; a build may not smuggle bytes in from outside its own staging dir (I9)",
path.display()
)));
}
let resolved = path.canonicalize()?;
if !resolved.starts_with(&staging_root) {
return Err(Error::fail_closed(format!(
"{} resolves outside this build's staging dir ({staging_root:?}); refusing to ingest it (I9)",
path.display()
)));
}
let path = resolved;
let bytes = std::fs::read(&path)?;
let (digest, size) = crate::hash::digest_file(&path)?;
// Read what the package says about itself out of the archive, rather
// than trusting what the build claimed on stdout (§10.1).
let pkginfo = crate::pkginfo::pkginfo_text(&bytes)
.map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?;
let meta = crate::pkginfo::parse_pkginfo(&pkginfo);
// `.BUILDINFO` is what the world snapshot is built from. Absent is not
// fatal — the snapshot is then simply empty for this package — but a
// present-but-unparseable one would be a lie we should not swallow.
let buildinfo = crate::pkginfo::buildinfo_text(&bytes).unwrap_or_default();
let sig = path.with_extension("pkg.tar.zst.sig");
pkgs.push(CollectedPkg {
name: meta.name.clone(),
version: meta.version.clone(),
arch: if meta.arch.is_empty() { ctx.cfg.arch.clone() } else { meta.arch.clone() },
path: path.display().to_string(),
digest,
size,
signature_path: sig.exists().then(|| sig.display().to_string()),
depends: meta.depends.clone(),
makedepends: meta.makedepends.clone(),
provides: meta.provides.clone(),
conflicts: meta.conflicts.clone(),
installed: crate::pkginfo::parse_installed(&buildinfo)
.into_iter()
.map(|i| (i.name, i.version))
.collect(),
});
}
if pkgs.is_empty() {
return Err(Error::invalid("build produced no packages"));
}
let collect = Collect { packages: pkgs.clone() };
collect.save(&ctx.collect_path)?;
// A split pkgbase is one approval and N index entries (§3).
ctx.log_line(&format!(" collected {}", pkgs.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>().join(", ")));
Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(&pkgs)?))))
}
/// Step 7 — signature present, dependencies satisfiable, no downgrade.
fn verify(ctx: &Ctx) -> Result<StepResult> {
let collect = Collect::load(&ctx.collect_path)?;
let ours = db::our_package_names(&ctx.db)?;
for p in &collect.packages {
if p.signature_path.is_none() && !ctx.cfg.signing_key_id.is_empty() {
return Err(Error::fail_closed(format!("{} has no signature", p.name)));
}
if crate::pkgver::is_downgrade(
&db::index_version(&ctx.db, &p.name)?.unwrap_or_else(|| "0".into()),
&p.version,
) {
// Downgrades are allowed but flagged (§16); the review already shows it.
ctx.log_line(&format!(" note: {} is a downgrade from what we serve", p.name));
}
let mut provided: std::collections::BTreeSet<String> = ours.clone();
provided.extend(collect.packages.iter().map(|q| q.name.clone()));
provided.extend(p.provides.iter().flat_map(|v| crate::pkgver::dep_names(std::slice::from_ref(v))));
for dep in crate::pkgver::dep_names(&p.depends) {
if !provided.contains(&dep) && db::get_pkgbase(&ctx.db, &dep)?.is_some() {
return Err(Error::fail_closed(format!(
"{} depends on {dep}, which is not satisfiable in the target repo",
p.name
)));
}
}
}
Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(
&collect.packages.iter().map(|p| (&p.name, &p.version)).collect::<Vec<_>>(),
)?))))
}
/// Step 8 — move artifacts into the content-addressed store and record rows.
/// Staging stays disposable; a GC pass sweeps abandoned directories (§8.2).
fn ingest(ctx: &Ctx) -> Result<StepResult> {
let mut collect = Collect::load(&ctx.collect_path)?;
for p in &mut collect.packages {
let from = Path::new(&p.path);
let dest = ctx.cfg.store_path(&p.digest);
if !dest.exists() {
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::copy(from, &dest)?;
}
p.path = dest.display().to_string();
if let Some(sig) = p.signature_path.clone() {
let sigdest = ctx.cfg.store_path(&format!("{}-sig", p.digest));
if !sigdest.exists() && Path::new(&sig).exists() {
std::fs::copy(&sig, &sigdest)?;
}
p.signature_path = Some(sigdest.display().to_string());
}
}
collect.save(&ctx.collect_path)?;
let at = crate::time::now();
let packages = collect.packages.clone();
let packages_for_db = packages.clone();
let build_id = ctx.build.id.clone();
let log_path = ctx.log.display().to_string();
ctx.db.writer.tx(move |tx| {
for p in &packages_for_db {
db::insert_artifact_in(
tx,
&db::NewArtifact {
digest: &p.digest,
size: p.size as i64,
path: &p.path,
signature_path: p.signature_path.as_deref(),
build_log_path: Some(&log_path),
build_id: &build_id,
at: &at,
},
)?;
}
Ok(())
})?;
// §10.1: the world snapshot is the build's installed set INTERSECTED with our
// own packages, filtered at ingest time, not at query time. Left unfiltered,
// every package would be permanently stale because Arch never stops moving.
let ours = db::our_package_names(&ctx.db)?;
let mut members: Vec<WorldMember> = Vec::new();
for p in &collect.packages {
for (name, version) in &p.installed {
if ours.contains(name) {
members.push(WorldMember { pkgbase: name.clone(), version: version.clone() });
}
}
}
let world_id = db::put_world_snapshot(&ctx.db.writer, &members)?;
builds::set_world(&ctx.db, &ctx.build.id, world_id)?;
ctx.log_line(&format!(" ingested {} artifact(s), world has {} of our packages", packages.len(), members.len()));
Ok(StepResult::Done(Some(crate::hash::hex_str(&format!(
"ingest:{}",
packages.len()
)))))
}
/// Step 9 — the only externally visible step, serialized per repo (§9).
fn publish(ctx: &Ctx) -> Result<StepResult> {
let release_id = crate::pipeline::publish::publish(ctx)?;
Ok(StepResult::Done(Some(format!("release:{release_id}"))))
}
// ---------------------------------------------------------------- helpers --
use std::path::PathBuf;
/// Read the recipe from a materialized tree, preferring `.SRCINFO`.
pub(crate) fn recipe_at(dir: &Path) -> Result<Recipe> {
let mut files = std::collections::BTreeMap::new();
for entry in walkdir::WalkDir::new(dir).max_depth(2).into_iter().filter_map(|e| e.ok()) {
let p = entry.path();
if !p.is_file() {
continue;
}
let rel = p.strip_prefix(dir).unwrap_or(p).display().to_string();
if let Ok(body) = std::fs::read_to_string(p) {
files.insert(rel, body);
}
}
crate::recipe::recipe_from_tree(&files)
}
|