summaryrefslogtreecommitdiffstats
path: root/tests/approve.rs
blob: 6e0ac1b50f3e8b43e787868202d37a4cd382e66e (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
mod common;

use aur_build::db::model::*;
use aur_build::review::{approve::Stale, approve::*, candidates, diff};
use common::*;

fn open_review(env: &Env, name: &str) -> (CandidateRow, String) {
    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();
    (c, dd)
}

#[test]
fn approve_writes_an_immutable_row_carrying_both_hashes() {
    let (env, _fx) = env_with_fixture("plain-make");
    let (c, dd) = open_review(&env, "plain-make");
    let a = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
    assert_eq!(a.decision, "approved");
    assert_eq!(a.identity_hash, c.identity_hash);
    assert_eq!(a.diff_digest, dd);
    let stored: (String, String, Option<String>) = env
        .db
        .read(|c| {
            Ok(c.query_row(
                "SELECT identity_hash, diff_digest, note FROM approval WHERE id=?1",
                rusqlite::params![a.id],
                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
            )?)
        })
        .unwrap();
    assert_eq!(stored.0, c.identity_hash);
    assert_eq!(stored.1, dd);
    let err = env
        .db
        .writer
        .tx_for_tests(move |tx| {
            tx.execute("UPDATE approval SET note='rewritten' WHERE id=1", [])?;
            Ok(())
        })
        .err();
    assert!(err.is_some(), "approval rows must be immutable");
    let actions: Vec<String> = env
        .db
        .read(|c| {
            let mut st = c.prepare("SELECT action FROM audit ORDER BY id")?;
            let rows = st.query_map([], |r| r.get::<_, String>(0))?;
            Ok(rows.filter_map(|r| r.ok()).collect())
        })
        .unwrap();
    assert!(actions.iter().any(|a| a == "approve"), "{actions:?}");
}

#[test]
fn a_stale_identity_hash_is_refused() {
    let (env, fx) = env_with_fixture("plain-make");
    let (c, dd) = open_review(&env, "plain-make");
    fx.bump(&[("pkgver", "2.0")]);
    aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
    let now = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
    assert_ne!(now.identity_hash, c.identity_hash, "identity should have moved");

    let err = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap_err();
    assert!(matches!(err, ApproveError::Stale(Stale::Identity { .. })), "{err:?}");
    assert_eq!(
        env.query_i64("SELECT count(*) FROM approval", &[]),
        Some(0),
        "a refused approval must leave nothing behind"
    );
    let dd2 = diff::render_and_store(&env.db, &env.cfg, &now).unwrap();
    approve(&env.db, "tester", c.id, &now.identity_hash, &dd2, None).unwrap();
}

#[test]
fn a_stale_diff_digest_is_refused() {
    let (env, _fx) = env_with_fixture("plain-make");
    let (c, dd) = open_review(&env, "plain-make");
    let err = approve(&env.db, "tester", c.id, &c.identity_hash, "sha256:whatever", None).unwrap_err();
    assert!(matches!(err, ApproveError::Stale(Stale::Diff { .. })), "{err:?}");
    assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(0));
    let _ = dd;
}

#[test]
fn approving_twice_is_refused_not_duplicated() {
    let (env, _fx) = env_with_fixture("plain-make");
    let (c, dd) = open_review(&env, "plain-make");
    approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
    let err = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap_err();
    assert!(matches!(err, ApproveError::Stale(Stale::NotPending { .. })), "{err:?}");
    assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
}

#[test]
fn a_broken_database_is_not_reported_as_a_stale_review() {
    let (env, _fx) = env_with_fixture("plain-make");
    let (c, dd) = open_review(&env, "plain-make");
    env.exec("DROP TABLE audit", &[]);
    let err = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap_err();
    assert!(matches!(err, ApproveError::System(_)), "a broken database was reported as a stale review: {err:?}");
    assert!(err.to_string().contains("could not be recorded"), "the message hides the cause: {err}");
    assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(0));
    let after = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
    assert_eq!(after.state, CandidateState::PendingReview, "a failed approval must not resolve the review");
}

#[test]
fn bulk_refusals_are_their_own_reasons() {
    let (env, _fx) = env_with_fixture("plain-make");
    let (c, dd) = open_review(&env, "plain-make");
    candidates::set_risk(&env.db, c.id, "high", &["new source host".into()]).unwrap();
    let items = [(c.id, c.identity_hash.clone(), dd.clone())];

    let out = bulk(&env.db, "tester", &items, "approve", &[]).unwrap();
    assert!(
        matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::HighRiskUnconfirmed)),
        "{:?}",
        out[0].outcome
    );
    let out = bulk(&env.db, "tester", &items, "ship-it", &[]).unwrap();
    assert!(
        matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::UnknownDecision(_))),
        "{:?}",
        out[0].outcome
    );
    let out = bulk(&env.db, "tester", &items, "approve", &[c.id]).unwrap();
    assert!(matches!(out[0].outcome, BulkOutcome::Approved(_)), "{:?}", out[0].outcome);
    let out = bulk(&env.db, "tester", &items, "approve", &[c.id]).unwrap();
    assert!(matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::Stale(_))), "{:?}", out[0].outcome);
    assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
}

#[test]
fn a_bulk_rejection_hands_back_no_invented_approval() {
    let (env, _fx) = env_with_fixture("plain-make");
    let (c, dd) = open_review(&env, "plain-make");
    let out = bulk(&env.db, "tester", &[(c.id, c.identity_hash.clone(), dd)], "reject", &[]).unwrap();
    assert!(matches!(out[0].outcome, BulkOutcome::Rejected), "{:?}", out[0].outcome);
    assert_eq!(env.query_i64("SELECT count(*) FROM approval WHERE decision='rejected'", &[]), Some(1));
    assert_eq!(env.query_i64("SELECT count(*) FROM approval WHERE decision='approved'", &[]), Some(0));
}

#[test]
fn collapse_in_place_bumps_revision_without_a_new_row() {
    let (env, fx) = env_with_fixture("plain-make");
    let (c, _dd) = open_review(&env, "plain-make");
    let first = c.revision;
    assert!(c.viewed_at.is_none(), "render_and_store must not mark it viewed");

    fx.bump(&[("pkgver", "2.0")]);
    aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
    let after = candidates::pending_candidates(&env.db).unwrap();
    assert_eq!(after.len(), 1, "still exactly one open review");
    assert_eq!(after[0].id, c.id, "same row, not a new one");
    assert!(after[0].revision > first, "revision bumped: {}", after[0].revision);
    assert_eq!(after[0].pkgver, "2.0");
    assert_eq!(
        env.query_i64("SELECT count(*) FROM candidate WHERE pkgbase_id=?1", &params(vec![after[0].pkgbase_id])),
        Some(1)
    );
}

#[test]
fn once_viewed_a_new_state_freezes_the_old_one_as_superseded() {
    let (env, fx) = env_with_fixture("plain-make");
    let (c, _dd) = open_review(&env, "plain-make");
    candidates::mark_viewed(&env.db, c.id).unwrap();

    fx.bump(&[("pkgver", "3.0")]);
    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);
    assert_ne!(open[0].id, c.id, "a fresh review was opened");
    let frozen = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
    assert_eq!(frozen.state, CandidateState::Superseded);
    let err = approve(&env.db, "tester", c.id, &frozen.identity_hash, &frozen.diff_digest, None).unwrap_err();
    assert!(matches!(err, ApproveError::Stale(Stale::NotPending { .. })), "{err:?}");
}

#[test]
fn a_rejected_identity_is_not_re_raised() {
    let (env, _fx) = env_with_fixture("plain-make");
    let (c, _dd) = open_review(&env, "plain-make");
    reject(&env.db, "tester", c.id, "not this").unwrap();
    aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
    assert!(candidates::pending_candidates(&env.db).unwrap().is_empty());
    let err = approve(&env.db, "tester", c.id, &c.identity_hash, &c.diff_digest, None).unwrap_err();
    assert!(matches!(err, ApproveError::Stale(Stale::NotPending { .. })));
}

#[test]
fn reject_requires_a_reason_and_records_it() {
    let (env, _fx) = env_with_fixture("plain-make");
    let (c, _dd) = open_review(&env, "plain-make");
    reject(&env.db, "tester", c.id, "upstream dropped the license we rely on").unwrap();
    let cid = c.id;
    let note: String = env
        .db
        .read(|c| {
            Ok(c.query_row(
                "SELECT note FROM approval WHERE candidate_id=?1",
                rusqlite::params![cid],
                |r| r.get(0),
            )?)
        })
        .unwrap();
    assert!(note.contains("license"), "{note}");

    let (actor_kind, detail): (String, String) = env
        .db
        .read(|c| {
            Ok(c.query_row(
                "SELECT actor_kind, detail_json FROM audit WHERE action='reject' AND entity_id=?1",
                rusqlite::params![cid.to_string()],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )?)
        })
        .unwrap();
    assert_eq!(actor_kind, "human");
    assert!(
        detail.contains(&c.identity_hash),
        "the audit row does not say which review bytes were rejected: {detail}"
    );
}

// ------------------------------------------------------------- the CLI path --

#[test]
fn cli_end_to_end_approves_and_queues_a_build() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("root");
    let (aur, _fx) = cli_fixture(tmp.path(), "plain-make");
    let bin = env!("CARGO_BIN_EXE_aur-build");

    let out = cli(bin, &root, &["init", "--repo", "aurbuild"]);
    assert!(out.status.success(), "init: {}", out.stderr);
    assert!(root.join("config.json").exists());

    let url = format!("file://{}", aur.display());
    let out = cli(bin, &root, &["subscribe", "plain-make", "--url", &url]);
    assert!(out.status.success(), "subscribe: {}", out.stderr);

    let out = cli(bin, &root, &["detect", "plain-make"]);
    assert!(out.status.success(), "detect: {}", out.stderr);

    let out = cli(bin, &root, &["reviews"]);
    assert!(out.stdout.contains("#1"), "reviews: {}", out.stdout);

    let out = cli(bin, &root, &["show", "1"]);
    assert!(out.stdout.contains("identity_hash"), "show: {}", out.stdout);
    let shown = out.stdout.clone();

    let out = cli(bin, &root, &["approve", "1"]);
    assert!(out.stdout.contains("not approved"), "approve w/o --yes: {}", out.stdout);
    assert_eq!(cli_count(&root, "approval"), 0);

    let out = cli(bin, &root, &["approve", "1", "--yes", "--note", "looked at it"]);
    assert!(out.status.success(), "approve: {}", out.stderr);
    assert!(out.stdout.contains("approved #1"), "approve: {}", out.stdout);
    assert!(out.stdout.contains("queued build"), "approve should queue: {}", out.stdout);
    assert_eq!(cli_count(&root, "approval"), 1);
    assert_eq!(cli_count(&root, "build"), 1);
    assert!(shown.contains("PKGBUILD") || shown.contains("pkgver"), "diff pane: {shown}");

    let out = cli(bin, &root, &["approve", "1", "--yes"]);
    assert_eq!(out.code, Some(2), "stale approval should exit 2: {:?}", out);
}

#[test]
fn cli_approve_refuses_a_hash_that_was_never_shown() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("root");
    let (aur, _fx) = cli_fixture(tmp.path(), "plain-make");
    let bin = env!("CARGO_BIN_EXE_aur-build");
    cli(bin, &root, &["init"]);
    let url = format!("file://{}", aur.display());
    cli(bin, &root, &["subscribe", "plain-make", "--url", &url]);
    cli(bin, &root, &["detect", "plain-make"]);
    let out = cli(bin, &root, &["approve", "1", "--yes", "--identity", "sha256:invented", "--diff", "sha256:invented"]);
    assert_eq!(out.code, Some(2), "must refuse: {:?}", out);
    assert!(out.stderr.contains("refused"), "stderr: {}", out.stderr);
    assert_eq!(cli_count(&root, "approval"), 0);
}

#[derive(Debug)]
struct Out {
    status: std::process::ExitStatus,
    stdout: String,
    stderr: String,
    code: Option<i32>,
}

fn cli(bin: &str, root: &std::path::Path, args: &[&str]) -> Out {
    let out = std::process::Command::new(bin)
        .arg("--root")
        .arg(root)
        .args(args)
        .output()
        .expect("run aur-build");
    Out {
        code: out.status.code(),
        status: out.status,
        stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
    }
}

fn cli_fixture(root: &std::path::Path, name: &str) -> (std::path::PathBuf, Fixture) {
    let fx = materialize_fixture(root, name);
    (fx.aur.clone(), fx)
}

fn cli_count(root: &std::path::Path, table: &str) -> i64 {
    let conn = rusqlite::Connection::open_with_flags(
        root.join("aur-build.db"),
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
    )
    .expect("open cli db");
    conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get::<_, i64>(0))
        .unwrap()
}