summaryrefslogtreecommitdiffstats
path: root/tests/approve.rs
blob: 61e42c2db4adddac7c038590234ab0943be994b9 (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
//! Approval semantics (§7.1, §7.1a, §7.2) and the CLI approval path (P0).
//!
//! The rule these tests exist to protect: **we build exactly what was displayed,
//! or nothing.** An approval that does not match the hashes of what the reviewer
//! was shown is refused, never retargeted.

mod common;

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

/// Detect, open the review, and render it the way a reviewer opening the page
/// would — returning the candidate plus the two hashes an approval must echo.
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);
    // The row itself records them, so "the human approved *this* diff" is
    // provable later (§7.2).
    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);
    // Approvals are append-only: the audit trigger rejects any edit (§10 I10).
    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");
    // And the human action is in the audit log.
    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");
    // AUR moves while the reviewer is reading: the candidate collapses in place
    // and its identity changes under them.
    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"
    );
    // Approving with the *current* identity succeeds: the reviewer just has to
    // look at what is on screen now.
    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() {
    // What this pins: every failure inside the approval transaction used to be
    // mapped into `Stale::NotPending`, so a SQLite error reached the reviewer as
    // "review is no longer pending (state: sqlite: …)" — the one message that
    // tells them to look again when the truth is that the write failed (§6 M-3).
    let (env, _fx) = env_with_fixture("plain-make");
    let (c, dd) = open_review(&env, "plain-make");
    // Make the write impossible halfway through the transaction: the approval
    // row and the candidate update succeed, then the audit append has nowhere
    // to go.
    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}");
    // And the refusal is atomic: the half-written approval rolled back with it.
    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, "pending_review", "a failed approval must not resolve the review");
}

#[test]
fn bulk_refusals_are_their_own_reasons() {
    // Bulk used to bend `Stale::NotPending` into "high risk", "unknown decision"
    // and "the database failed", and to hand back a fabricated `Approval { id: 0 }`
    // for a rejection that recorded no approval at all (§6 M-3).
    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())];

    // High risk without the individual confirmation: the reason is the risk.
    let out = bulk(&env.db, "tester", &items, "approve", &[]).unwrap();
    assert!(
        matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::HighRiskUnconfirmed)),
        "{:?}",
        out[0].outcome
    );
    // A decision the form should never have sent is its own reason.
    let out = bulk(&env.db, "tester", &items, "ship-it", &[]).unwrap();
    assert!(
        matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::UnknownDecision(_))),
        "{:?}",
        out[0].outcome
    );
    // Confirming it individually is the answer to the first refusal.
    let out = bulk(&env.db, "tester", &items, "approve", &[c.id]).unwrap();
    assert!(matches!(out[0].outcome, BulkOutcome::Approved(_)), "{:?}", out[0].outcome);
    // Now it is no longer pending, and *that* is a staleness — the two reasons
    // stay distinguishable in both directions.
    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);
    // A rejection records a `rejected` row; there is no approval to return, and
    // the old `Approval { id: 0 }` sentinel is gone.
    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");

    // Nobody has looked at it: the new upstream state collapses *into* the open
    // review instead of queueing beside it (§7.1).
    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 (I7)");
    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, candidate_state::SUPERSEDED);
    // The frozen one can no longer be approved: approving it would build a
    // version nobody is looking at.
    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();
    // Same upstream state, polled again: nothing new to review.
    aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
    assert!(candidates::pending_candidates(&env.db).unwrap().is_empty());
    // A different identity is a different question, and gets its own review.
    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}");
}

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

/// Drive the real binary the way an operator would. This is the P0 approval
/// path: `init`, `subscribe`, `detect`, `show`, `approve --yes`.
#[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);

    // `show` renders the panels and the hashes; `approve` without --yes refuses
    // to act, which is the CLI's version of "look before you approve".
    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}");

    // Approving the same review again is refused with a non-zero status.
    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(),
    }
}

/// A local git repo standing in for AUR, so the CLI test needs no network.
fn cli_fixture(root: &std::path::Path, name: &str) -> (std::path::PathBuf, Fixture) {
    let fx = materialize_fixture(root, name);
    (fx.aur.clone(), fx)
}

/// Query the CLI's own database through a throwaway read connection.
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()
}