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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
|
//! The §2 invariant index.
//!
//! Every invariant in DESIGN.md §2 gets a named test here, asserted as a
//! **post-condition on a real end-to-end run** rather than as a unit test of the
//! function that happens to maintain it. If one of these ever fails, the
//! property the whole design rests on is broken, not just some helper.
//!
//! Invariants whose mechanism lands in a later phase are named at the bottom
//! with the test that covers them once it does.
mod common;
use aur_build::db::{self, builds, model::*};
use aur_build::pipeline::{self, publish};
use aur_build::review::approve::approve as do_approve;
use aur_build::review::{candidates, diff};
use common::*;
/// subscribe → detect → render → approve → build → publish, in one call.
fn full_run(env: &Env, name: &str) -> CandidateRow {
aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap();
let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
let out = pipeline::run(&env.cfg, &env.db, &id).unwrap();
assert!(matches!(out, pipeline::Outcome::Succeeded { .. }), "{out:?}");
c
}
fn query_pairs(env: &Env, sql: &str) -> Vec<(String, String)> {
env.db
.read(move |c| {
let mut st = c.prepare(sql)?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
Ok(rows.filter_map(|r| r.ok()).collect())
})
.unwrap()
}
fn count(env: &Env, sql: &str) -> i64 {
env.db
.read(move |c| Ok(c.query_row(sql, [], |r| r.get::<_, i64>(0))?))
.unwrap()
}
/// **I1 — no artifact without an approval.** After a real publish, every entry
/// in the served index traces back through a release to an approval row.
#[test]
fn i1_every_index_entry_traces_back_to_an_approval() {
let (env, _fx) = env_with_fixture("plain-make");
full_run(&env, "plain-make");
// The §2 query, verbatim in spirit: index entry → release → approval.
assert_eq!(
count(
&env,
"SELECT count(*) FROM package p
LEFT JOIN release r ON r.id = p.release_id
WHERE p.state='in_index' AND (r.id IS NULL OR r.approval_id IS NULL)"
),
0,
"I1: an index entry exists that no human approved"
);
// And the reverse direction: nothing was approved and then quietly dropped.
assert_eq!(
count(&env, "SELECT count(*) FROM approval WHERE decision='approved'"),
1
);
assert_eq!(count(&env, "SELECT count(*) FROM release WHERE approval_id IS NULL"), 0);
}
/// **I2 — the diff base is the last accepted version, never the last seen one.**
/// Many detections arrive while nobody is looking; the review still compares
/// against the accepted release, not against whatever was polled last.
#[test]
fn i2_base_is_the_last_accepted_version_after_many_detections() {
let (env, fx) = env_with_fixture("plain-make");
let c = full_run(&env, "plain-make");
let accepted = db::accepted_release(&env.db, "plain-make").unwrap().unwrap();
assert_eq!(accepted.pkgver, "1.0");
// Five upstream moves with nobody reviewing.
for v in ["1.1", "1.2", "1.3", "1.4", "1.5"] {
fx.bump(&[("pkgver", v)]);
aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
}
let open = candidates::pending_candidates(&env.db).unwrap();
assert_eq!(open.len(), 1, "one open review, collapsed in place");
assert_eq!(open[0].pkgver, "1.5", "it shows the newest state");
assert_eq!(
open[0].base_release_id,
Some(accepted.id),
"I2: the diff base must be the accepted release ({}), not the last seen commit",
accepted.id
);
// And the rendered diff really compares against it.
let panels = diff::panels(&env.cfg, &env.db, &open[0], Some(&accepted)).unwrap();
let text = diff::render_text(&panels);
assert!(text.contains("1.0"), "diff should show the accepted version: {text}");
assert!(text.contains("1.5"), "diff should show the candidate: {text}");
let _ = c;
}
/// **I4 — publishing is atomic.** Kill the process mid-publish: the consumer-
/// visible index is either entirely the old one or entirely the new one.
#[test]
fn i4_kill_mid_publish_leaves_the_old_index_byte_identical() {
let (mut env, fx) = env_with_fixture("plain-make");
full_run(&env, "plain-make");
let db_file = env.cfg.repo_arch_dir().join("aur-build.db.tar.gz");
let old_bytes = std::fs::read(&db_file).unwrap();
fx.bump(&[("pkgver", "9.9")]);
aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
// Die after the new database is rendered to .tmp but before the rename.
env.set_publish_fault("before-rename");
assert!(matches!(
pipeline::run(&env.cfg, &env.db, &id).unwrap(),
pipeline::Outcome::Failed { .. }
));
assert_eq!(
std::fs::read(&db_file).unwrap(),
old_bytes,
"I4: the served index was torn by a crash"
);
assert_eq!(
query_pairs(&env, "SELECT name, version FROM package WHERE state='in_index'"),
vec![("plain-make".to_string(), "1.0-1".to_string())]
);
// Recovery re-materializes the index from the DB; it invents nothing.
assert!(publish::reconcile(&env.cfg, &env.db).unwrap() >= 1);
assert_eq!(std::fs::read(&db_file).unwrap(), old_bytes);
}
/// **I5 — a build resumes at the next incomplete step.** A worker that dies
/// mid-pipeline does not repeat the expensive work or double-publish.
#[test]
fn i5_resume_after_a_crash_repeats_no_completed_step() {
let (mut env, fx) = env_with_fixture("plain-make");
full_run(&env, "plain-make");
fx.bump(&[("pkgver", "2.0")]);
aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
env.set_publish_fault("before-rename");
assert!(matches!(
pipeline::run(&env.cfg, &env.db, &id).unwrap(),
pipeline::Outcome::Failed { .. }
));
let shim = env.cfg.hooks.shim_dir.clone().unwrap();
let builds_before = aur_build::shims::called_with(&shim, "makechrootpkg", "");
assert_eq!(builds_before, 2, "one build per attempted publish");
// "Restart" the worker on the same build row.
env.clear_publish_fault();
match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
pipeline::Outcome::Succeeded { release_id } => assert!(release_id > 0),
other => panic!("{other:?}"),
}
assert_eq!(
aur_build::shims::called_with(&shim, "makechrootpkg", ""),
builds_before,
"I5: resuming re-ran the build step"
);
// No duplicate side effects: one release row for the version, one artifact.
assert_eq!(count(&env, "SELECT count(*) FROM release WHERE pkgver='2.0'"), 1);
// Artifacts are content-addressed and persist across builds; what must not
// happen is the same bytes recorded twice.
assert_eq!(
count(&env, "SELECT count(*) FROM artifact"),
count(&env, "SELECT count(DISTINCT digest) FROM artifact"),
"I5: the resume recorded a duplicate artifact"
);
// Every step is checkpointed as succeeded or explicitly skipped.
let bad = env
.db
.read(|c| {
Ok(c.query_row(
"SELECT count(*) FROM build_step WHERE status NOT IN ('succeeded','skipped')",
[],
|r| r.get::<_, i64>(0),
)?)
})
.unwrap();
assert_eq!(bad, 0, "every step reached a terminal state");
}
/// **I7 — at most one open review per pkgbase.** Enforced by the partial unique
/// index, not by application politeness.
#[test]
fn i7_the_schema_refuses_a_second_open_review() {
let (env, _fx) = env_with_fixture("plain-make");
aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
let pb = c.pkgbase_id;
let snap = c.snapshot_id;
let err = env
.db
.writer
.tx_for_tests(move |tx| {
tx.execute(
"INSERT INTO candidate (pkgbase_id, kind, snapshot_id, epoch, pkgver, pkgrel,
upstream_pins_json, source_digests_json, identity_hash,
diff_digest, state, detected_at)
VALUES (?1,'new_version',?2,'0','9','1','[]','[]','other-hash','',?3,'now')",
rusqlite::params![pb, snap, CandidateState::PendingReview.as_str()],
)?;
Ok(())
})
.err();
assert!(err.is_some(), "I7: a second pending review was accepted");
assert_eq!(candidates::pending_candidates(&env.db).unwrap().len(), 1);
}
/// **I8 — the served index is exactly the set of accepted pointers.** Not a
/// superset (nothing stale lingers) and not a subset (nothing published is
/// missing). Checked against the files on disk as well as the rows.
#[test]
fn i8_index_equals_the_accepted_pointers() {
let (env, fx) = env_with_fixture("plain-make");
full_run(&env, "plain-make");
fx.bump(&[("pkgver", "2.0")]);
full_run(&env, "plain-make");
let pointers = query_pairs(
&env,
"SELECT p.name,
CASE WHEN r.epoch IN ('', '0') THEN '' ELSE r.epoch || ':' END
|| r.pkgver || '-' || r.pkgrel
FROM pkgbase p
JOIN release r ON r.id = p.current_accepted_release_id",
);
let index = query_pairs(
&env,
"SELECT name, version FROM package WHERE state='in_index'",
);
assert!(!pointers.is_empty());
assert_eq!(index, pointers, "I8: index and accepted pointers diverge");
// The superseded version is really gone, not merely hidden.
assert_eq!(
count(&env, "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'"),
0
);
// And the database file on disk lists the same set.
let db_file = env.cfg.repo_arch_dir().join("aur-build.db.tar.gz");
let names = index_db_names(&db_file);
assert_eq!(names, vec!["plain-make".to_string()]);
}
/// **I3 — the recipe is pinned to a commit.** Materializing anything other than
/// the approved tree fails closed before a build runs.
#[test]
fn i3_materialization_fails_closed_on_the_recipe_pin() {
let (env, _fx) = env_with_fixture("plain-make");
aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
env.exec(
"UPDATE snapshot SET recipe_hash='sha256:0000' WHERE id=?1",
¶ms(vec![c.snapshot_id]),
);
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
pipeline::Outcome::Failed { step, error, .. } => {
assert_eq!(step, "materialize");
assert!(error.contains("recipe_hash mismatch"), "{error}");
}
other => panic!("I3 requires a refusal, got {other:?}"),
}
assert_eq!(count(&env, "SELECT count(*) FROM release"), 0);
}
/// **I6 — a rebuild never needs a new approval.**
#[test]
fn i6_manual_rebuild_publishes_the_same_version_without_a_new_approval() {
let (env, _fx) = env_with_fixture("plain-make");
full_run(&env, "plain-make");
let approvals = count(&env, "SELECT count(*) FROM approval");
let id = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
assert!(matches!(
pipeline::run(&env.cfg, &env.db, &id).unwrap(),
pipeline::Outcome::Succeeded { .. }
));
assert_eq!(count(&env, "SELECT count(*) FROM approval"), approvals, "I6: a rebuild demanded a new approval");
assert_eq!(
query_pairs(&env, "SELECT name, version FROM package WHERE state='in_index'"),
vec![("plain-make".to_string(), "1.0-1".to_string())]
);
}
/// n-5: a manual rebuild's identity used to be a hand-rolled
/// `format!("{commit}|{hash}|manual}")` — a second, incompatible format for the
/// same concept, with a delimiter that can occur inside the values. It is now
/// derived through the same canonical-JSON hash as every other identity, and
/// what the change must not disturb is the two properties the queue depends on.
#[test]
fn a_manual_rebuild_is_deterministic_and_its_own_build() {
let (env, _fx) = env_with_fixture("plain-make");
full_run(&env, "plain-make");
let original = env
.query_str("SELECT id FROM build ORDER BY rowid LIMIT 1", &[])
.expect("the published build");
let a = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
let b = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
assert_eq!(a, b, "clicking rebuild twice is one build, not two (§8.2)");
assert_ne!(a, original, "a rebuild is a distinct build from the one that landed");
assert_eq!(
count(&env, "SELECT count(*) FROM build"),
2,
"the second call must not enqueue a third row"
);
}
/// **I10 — the audit log is append-only**, and every consequential action is in it.
#[test]
fn i10_audit_is_append_only_and_records_the_decisions() {
let (env, _fx) = env_with_fixture("plain-make");
full_run(&env, "plain-make");
for sql in [
"UPDATE audit SET action='x'",
"DELETE FROM audit",
"UPDATE approval SET note='x' WHERE id=1",
"DELETE FROM approval",
] {
let db = env.db.clone();
let s = sql.to_string();
assert!(
db.writer
.tx_for_tests(move |tx| {
tx.execute(&s, [])?;
Ok(())
})
.is_err(),
"{sql} should be refused"
);
}
let actions = env
.db
.read(|c| {
let mut st = c.prepare("SELECT action FROM audit")?;
let rows = st.query_map([], |r| r.get::<_, String>(0))?;
Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>())
})
.unwrap();
for want in ["approve", "publish", "build.start", "build.succeeded"] {
assert!(actions.iter().any(|a| a == want), "audit missing {want}: {actions:?}");
}
}
/// **I12 — every build records the world it was built against.**
#[test]
fn i12_every_build_records_a_world_snapshot() {
let (env, fx) = env_with_fixture("plain-make");
full_run(&env, "plain-make");
let mut m = fx.manifest_json();
m["installed"] = serde_json::json!([
{"name": "plain-make", "version": "1.0-1", "arch": "x86_64"},
{"name": "glibc", "version": "2.39-1", "arch": "x86_64"}
]);
std::fs::write(&fx.manifest, serde_json::to_string(&m).unwrap()).unwrap();
fx.bump(&[("pkgver", "3.0")]);
full_run(&env, "plain-make");
assert_eq!(
count(&env, "SELECT count(*) FROM build WHERE world_snapshot_id IS NULL AND state='succeeded'"),
0,
"I12: a succeeded build has no recorded world"
);
let members = env
.db
.read(|c| {
let json: String = c.query_row(
"SELECT w.members_json FROM world_snapshot w
JOIN build b ON b.world_snapshot_id = w.id ORDER BY b.rowid DESC LIMIT 1",
[],
|r| r.get(0),
)?;
Ok(json)
})
.unwrap();
assert!(members.contains("plain-make"), "our own package belongs in the world");
assert!(!members.contains("glibc"), "foreign packages must be filtered out (§10.1)");
}
// I9 (build isolation) is exercised by the chroot step and the real-chroot tier;
// I11 (non-publishable change becomes a notice, never a silent drop) is covered
// by `recipe_drift_under_a_static_version_is_a_notice_not_a_candidate` in
// tests/detect.rs and gets its full treatment with P1's upstream probes.
/// Read the package names out of a pacman-style database file (gzipped tar).
fn index_db_names(path: &std::path::Path) -> Vec<String> {
let file = std::fs::File::open(path).unwrap();
let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(file));
let mut names: Vec<String> = ar
.entries()
.unwrap()
.filter_map(|e| e.ok())
.filter_map(|e| {
let p = e.path().ok()?.to_string_lossy().into_owned();
p.split('/').next().map(|s| s.to_string())
})
.collect();
names.sort();
names.dedup();
names
}
/// I9: build hosts are treated as untrusted — a malicious PKGBUILD must not
/// reach the control plane's data or smuggle foreign bytes into what we publish.
///
/// The real enforcement is the chroot, and that tier is gated. What is *not*
/// gated, and what this pins, is the pipeline's own hygiene: `collect` scans the
/// srcdir for `*.pkg.tar.zst` and `ingest` copies whatever those paths point at
/// into the content-addressed store, from where the bytes are served from our
/// repo and signed with our key. If a build could make one of those paths be a
/// symlink to the signing keyring or the database, isolation would be the only
/// thing standing between a hostile AUR recipe and a signed artifact of our own
/// secret files. It must not be. So the pipeline refuses symlinks and refuses
/// anything that resolves outside the build's own staging directory, and this
/// test acts the attack out rather than arguing it away.
#[test]
fn i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir() {
let (mut env, _fx) = env_with_fixture("plain-make");
aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
do_approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap();
let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
// Something a build must never get to publish: our own database file.
let secret = env.cfg.db_path();
let store_before = dir_listing(&env.cfg.store_dir());
env.cfg.hooks.shim_plant_link = Some(secret.display().to_string());
let out = pipeline::run(&env.cfg, &env.db, &id);
env.cfg.hooks.shim_plant_link = None;
let (step, err) = match out {
Ok(pipeline::Outcome::Failed { step, error, .. }) => (step, error),
other => panic!("a build that smuggled in a symlink must fail closed, got {other:?}"),
};
assert_eq!(step, "collect", "it should be refused at collect, before anything is copied");
assert!(
err.contains("symlink") && err.contains("staging"),
"the failure should say why it refused: {err}"
);
// The refused bytes never reached the store, and nothing was published.
assert_eq!(
dir_listing(&env.cfg.store_dir()),
store_before,
"the store must be untouched by a refused build"
);
assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Failed);
assert!(db::index_version(&env.db, "plain-make").unwrap().is_none(), "nothing publishes from a failed build");
// And the database itself is intact — the build read it, it did not become it.
assert!(secret.exists());
}
fn dir_listing(dir: &std::path::Path) -> Vec<String> {
let mut out = Vec::new();
if let Ok(entries) = std::fs::read_dir(dir) {
for e in entries.flatten() {
out.push(e.path().display().to_string());
}
}
out.sort();
out
}
|