summaryrefslogtreecommitdiffstats
path: root/tests/invariants.rs
blob: d5b37588ce9702af031ac0897617e7b4f4c4e107 (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
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
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::*;

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()
}

#[test]
fn i1_every_index_entry_traces_back_to_an_approval() {
    let (env, _fx) = env_with_fixture("plain-make");
    full_run(&env, "plain-make");

    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"
    );
    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);
}

#[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");

    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
    );
    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;
}

#[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();
    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())]
    );
    assert!(publish::reconcile(&env.cfg, &env.db).unwrap() >= 1);
    assert_eq!(std::fs::read(&db_file).unwrap(), old_bytes);
}

#[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, "makepkg", "");
    assert_eq!(builds_before, 2, "one build per attempted publish");

    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, "makepkg", ""),
        builds_before,
        "I5: resuming re-ran the build step"
    );
    assert_eq!(count(&env, "SELECT count(*) FROM release WHERE pkgver='2.0'"), 1);
    assert_eq!(
        count(&env, "SELECT count(*) FROM artifact"),
        count(&env, "SELECT count(DISTINCT digest) FROM artifact"),
        "I5: the resume recorded a duplicate artifact"
    );
    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");
}

#[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);
}

#[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");

    assert_eq!(
        count(&env, "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'"),
        0
    );
    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()]);
}

#[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",
        &params(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);
}

#[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())]
    );
}

#[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"
    );
}

#[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:?}");
    }
}

#[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)");
}

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
}

#[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();

    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}"
    );

    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");
    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
}