summaryrefslogtreecommitdiffstats
path: root/tests/http.rs
blob: 20dcbcb52cce54f78b9854ca12dbf25cb28607aa (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
//! The web surface (§12, §13): routes render, the CSRF gate holds, and a stale
//! approval comes back as a 409 with the current diff instead of a silent
//! retarget.
//!
//! These drive a real `tiny_http` server on an ephemeral loopback port over a
//! real fixture corpus — no mocked transport, because the transport is part of
//! what we are claiming works.

mod common;

use aur_build::db::model::*;
use aur_build::http::{self, Server};
use aur_build::review::{candidates, diff};
use common::*;

struct Web {
    env: Env,
    fx: Fixture,
    #[allow(dead_code)]
    server: Server,
    cookie: String,
    csrf: String,
}

struct Page {
    status: u16,
    body: String,
}

impl Web {
    fn new(name: &str) -> Self {
        Self::with_password(name, "")
    }

    fn with_password(name: &str, password: &str) -> Self {
        let (mut env, fx) = env_with_fixture(name);
        env.cfg.bind = "127.0.0.1:0".into();
        env.cfg.password = password.into();
        let server = http::spawn(env.cfg.clone(), env.db.clone()).unwrap();
        let mut web = Self { env, fx, server, cookie: String::new(), csrf: String::new() };
        // First contact mints the session cookie and the CSRF token.
        let first = web.raw_get("/");
        web.cookie = first
            .0
            .iter()
            .find(|(k, _)| k == "set-cookie")
            .and_then(|(_, v)| v.split(';').next().map(|s| s.to_string()))
            .unwrap_or_default();
        let body = web.get("/");
        web.csrf = extract(&body.body, "name=\"csrf\" content=\"", "\"").unwrap_or_default();
        web
    }

    fn url(&self, path: &str) -> String {
        format!("http://{}{}", self.server.addr, path)
    }

    fn raw_get(&self, path: &str) -> (Vec<(String, String)>, String) {
        let resp = ureq::get(&self.url(path)).set("Cookie", &self.cookie).call();
        let r = match resp {
            Ok(r) => r,
            Err(ureq::Error::Status(_, r)) => r,
            Err(e) => panic!("GET {path}: {e}"),
        };
        let cookie = r.header("set-cookie").map(|s| s.to_string()).unwrap_or_default();
        (vec![("set-cookie".to_string(), cookie)], r.into_string().unwrap_or_default())
    }

    fn get(&self, path: &str) -> Page {
        let resp = ureq::get(&self.url(path)).set("Cookie", &self.cookie).call();
        self.finish(resp, path)
    }

    fn post(&self, path: &str, form: &[(&str, &str)]) -> Page {
        let resp = ureq::post(&self.url(path)).set("Cookie", &self.cookie).send_form(form);
        self.finish(resp, path)
    }

    fn finish(&self, resp: Result<ureq::Response, ureq::Error>, path: &str) -> Page {
        match resp {
            Ok(r) => Page { status: r.status(), body: r.into_string().unwrap_or_default() },
            Err(ureq::Error::Status(code, r)) => Page { status: code, body: r.into_string().unwrap_or_default() },
            Err(e) => panic!("{path}: {e}"),
        }
    }

    /// Subscribe, detect and render a review so an approval can be attempted.
    fn open_review(&self, name: &str) -> CandidateRow {
        aur_build::watch::detect::check_pkgbase(&self.env.cfg, &self.env.db, name).unwrap();
        let c = candidates::pending_candidates(&self.env.db).unwrap().remove(0);
        let dd = diff::render_and_store(&self.env.db, &self.env.cfg, &c).unwrap();
        let _ = dd;
        candidates::candidate_by_id(&self.env.db, c.id).unwrap().unwrap()
    }
}

fn extract(hay: &str, open: &str, close: &str) -> Option<String> {
    let i = hay.find(open)? + open.len();
    let rest = &hay[i..];
    let j = rest.find(close)?;
    Some(unescape(&rest[..j]))
}

/// Templates escape attribute values; a test comparing one back to a Rust
/// string has to undo that.
fn unescape(s: &str) -> String {
    s.replace("&amp;", "&")
        .replace("&quot;", "\"")
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&#39;", "'")
}

#[test]
fn every_surface_renders() {
    let web = Web::new("plain-make");
    web.open_review("plain-make");
    for path in [
        "/",
        "/reviews",
        "/reviews?state=pending",
        "/subscriptions",
        "/attention",
        "/packages",
        "/packages/plain-make",
        "/builds",
        "/audit",
        "/settings",
    ] {
        let page = web.get(path);
        assert_eq!(page.status, 200, "{path} did not render");
        assert!(page.body.contains("<!doctype html>"), "{path} is not a page");
        assert!(page.body.contains("aur-build"), "{path} has no chrome");
    }
}

#[test]
fn the_review_detail_shows_the_panels_and_the_hashes() {
    let web = Web::new("plain-make");
    // Publish a first version so the review has something to diff against;
    // every panel compares the accepted release to the candidate (§6).
    let first = web.open_review("plain-make");
    let page = web.get(&format!("/reviews/{}", first.id));
    let dd = extract(&page.body, "name=\"diff_digest\" value=\"", "\"").unwrap();
    web.post(
        &format!("/reviews/{}/approve", first.id),
        &[("csrf", &web.csrf), ("identity_hash", &first.identity_hash), ("diff_digest", &dd)],
    );
    let id = aur_build::pipeline::enqueue_for_candidate(&web.env.cfg, &web.env.db, &first).unwrap();
    aur_build::pipeline::run(&web.env.cfg, &web.env.db, &id).unwrap();
    web.fx.bump(&[("pkgver", "2.0")]);
    let c = web.open_review("plain-make");
    let page = web.get(&format!("/reviews/{}", c.id));
    assert_eq!(page.status, 200);
    // The panel set (§6), all comparing accepted → candidate.
    for want in ["Recipe diff", "Version delta", "Source digest delta", "Dependency delta", "Build-env delta"] {
        assert!(page.body.contains(want), "missing panel {want}");
    }
    assert!(page.body.contains("previous accepted release"), "no base shown");
    // The approve form carries both hashes (§7.1a) and is a plain POST form,
    // so it works with JavaScript switched off.
    assert!(page.body.contains("name=\"identity_hash\""));
    assert!(page.body.contains("name=\"diff_digest\""));
    assert!(page.body.contains("<form method=\"post\""));
    assert!(!page.body.contains("<script"), "P2 ships no JavaScript at all");
    // The aur_commit is shown and linked into AUR's cgit.
    assert!(page.body.contains("aur.archlinux.org/cgit/aur.git"), "no cgit link");
}

#[test]
fn a_first_introduction_shows_the_whole_recipe_not_a_diff() {
    let web = Web::new("plain-make");
    let c = web.open_review("plain-make");
    let page = web.get(&format!("/reviews/{}", c.id));
    assert!(page.body.contains("First build of this package here"), "no first-introduction card");
    assert!(page.body.contains("pkgbase=plain-make"), "the PKGBUILD was not shown");
    assert!(page.body.contains("Sources, as resolved"));
}

#[test]
fn risk_signals_are_shown_inline() {
    let web = Web::new("skip-checksum");
    let c = web.open_review("skip-checksum");
    let page = web.get(&format!("/reviews/{}", c.id));
    assert!(page.body.contains("Risk signals"), "no risk block");
    assert!(page.body.contains("skip-checksum:source-0"), "the SKIP signal is not shown");
    assert!(page.body.contains("risk-high"));
}

#[test]
fn every_post_requires_a_csrf_token() {
    let web = Web::new("plain-make");
    let c = web.open_review("plain-make");
    // A form post with no token at all is refused outright.
    let page = {
        let resp = ureq::post(&web.url(&format!("/reviews/{}/approve", c.id)))
            .set("Cookie", &web.cookie)
            .send_form(&[("identity_hash", "x"), ("diff_digest", "y")]);
        web.finish(resp, "approve")
    };
    assert_eq!(page.status, 403, "a POST without CSRF must be refused");
    // And so is one with a token from someone else's session.
    let page = web.post(&format!("/reviews/{}/approve", c.id), &[
        ("csrf", "not-the-token"),
        ("identity_hash", &c.identity_hash),
        ("diff_digest", &c.diff_digest),
    ]);
    assert_eq!(page.status, 403, "a forged CSRF token must be refused");
    assert_eq!(
        web.env.query_i64("SELECT count(*) FROM approval", &[]),
        Some(0),
        "a refused POST must not have written anything"
    );
}

#[test]
fn approve_carries_both_hashes_and_queues_a_build() {
    let web = Web::new("plain-make");
    let c = web.open_review("plain-make");
    let page = web.get(&format!("/reviews/{}", c.id));
    let shown_digest = extract(&page.body, "name=\"diff_digest\" value=\"", "\"").unwrap();
    let shown_identity = extract(&page.body, "name=\"identity_hash\" value=\"", "\"").unwrap();
    assert_eq!(shown_identity, c.identity_hash);

    let res = web.post(
        &format!("/reviews/{}/approve", c.id),
        &[("csrf", &web.csrf), ("identity_hash", &shown_identity), ("diff_digest", &shown_digest), ("note", "looked")],
    );
    assert_eq!(res.status, 200, "approve should succeed: {}", &res.body[..200.min(res.body.len())]);
    assert!(res.body.contains("approved"), "no confirmation: {}", &res.body[..200.min(res.body.len())]);
    assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
    assert_eq!(web.env.query_i64("SELECT count(*) FROM build", &[]), Some(1), "approval must queue the build");
}

#[test]
fn a_stale_approval_is_a_409_that_renders_the_current_diff() {
    let web = Web::new("plain-make");
    let c = web.open_review("plain-make");
    let page = web.get(&format!("/reviews/{}", c.id));
    let shown_digest = extract(&page.body, "name=\"diff_digest\" value=\"", "\"").unwrap();

    // Upstream moves while the reviewer is reading: the identity changes under
    // them (§7.1a).
    web.fx.bump(&[("pkgver", "9.9")]);
    aur_build::watch::detect::check_pkgbase(&web.env.cfg, &web.env.db, "plain-make").unwrap();

    let res = web.post(
        &format!("/reviews/{}/approve", c.id),
        &[("csrf", &web.csrf), ("identity_hash", &c.identity_hash), ("diff_digest", &shown_digest)],
    );
    assert_eq!(res.status, 409, "a stale approval must come back as 409");
    assert!(res.body.contains("refused"), "no explanation: {}", &res.body[..200.min(res.body.len())]);
    // Either way the reviewer is told the ground moved under them, and shown
    // the review as it is NOW rather than the one they asked to approve.
    assert!(
        res.body.contains("while you were looking") || res.body.contains("no longer pending"),
        "not a §7.1a explanation: {}",
        &res.body[..400.min(res.body.len())]
    );
    assert!(res.body.contains("9.9"), "the re-render does not show the new version");
    assert_eq!(
        web.env.query_i64("SELECT count(*) FROM approval", &[]),
        Some(0),
        "a refused approval must leave nothing behind"
    );
}

#[test]
fn reject_requires_a_note() {
    let web = Web::new("plain-make");
    let c = web.open_review("plain-make");
    let res = web.post(
        &format!("/reviews/{}/reject", c.id),
        &[("csrf", &web.csrf), ("note", "")],
    );
    assert_eq!(res.status, 400, "an empty note must be refused");
    assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(0));
    let res = web.post(
        &format!("/reviews/{}/reject", c.id),
        &[("csrf", &web.csrf), ("note", "upstream dropped our license")],
    );
    assert_eq!(res.status, 200);
    assert_eq!(web.env.query_i64("SELECT count(*) FROM approval WHERE decision='rejected'", &[]), Some(1));
}

#[test]
fn bulk_approve_refuses_high_risk_without_individual_confirmation() {
    let web = Web::new("skip-checksum");
    let c = web.open_review("skip-checksum");
    assert_eq!(c.risk_level, aur_build::review::risk::level::HIGH, "fixture should be high risk");
    let id = c.id.to_string();
    let res = web.post("/reviews/bulk", &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id)]);
    assert!(res.body.contains("refused"), "bulk approve accepted a high-risk item: {}", &res.body[..300.min(res.body.len())]);
    assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(0));

    // Confirming it individually lets it through — bulk is per-item, never
    // "approve everything forever" (§7.4).
    let res = web.post(
        "/reviews/bulk",
        &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id), ("confirm", &id)],
    );
    assert!(!res.body.contains("refused"), "confirmed item was still refused: {}", &res.body[..300.min(res.body.len())]);
    assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
}

#[test]
fn a_password_gate_redirects_anonymous_visitors() {
    let web = Web::with_password("plain-make", "s3cret");
    let page = web.get("/reviews");
    assert_eq!(page.status, 200);
    // The gate redirects; ureq follows, so we land on the login page.
    assert!(page.body.contains("Sign in"), "not the login page: {}", &page.body[..200.min(page.body.len())]);
    // Wrong password is refused, right password lets us through.
    let bad = web.post("/login", &[("csrf", &web.csrf), ("password", "nope")]);
    assert_eq!(bad.status, 401);
    assert!(web.get("/packages").body.contains("Sign in"), "still not gated");
}

#[test]
fn handlers_read_on_a_read_only_connection() {
    // The claim under test: a handler can never take the write lock, because
    // the connection it reads through is read-only at the SQLite level.
    let web = Web::new("plain-make");
    let err = web
        .env
        .db
        .read(|c| {
            c.execute("CREATE TABLE should_never_exist (x INTEGER)", [])?;
            Ok(())
        })
        .err();
    assert!(err.is_some(), "a read connection was able to write: the split is not real");
    // And the page still renders while that is true.
    assert_eq!(web.get("/").status, 200);
}

#[test]
fn the_index_page_tells_a_consumer_how_to_use_it() {
    let web = Web::new("plain-make");
    let page = web.get("/packages");
    assert!(page.body.contains("SigLevel = Required"), "no signing guidance");
    assert!(page.body.contains(&web.env.cfg.repo_name));
}

#[test]
fn attention_lists_blocked_builds_with_their_blocking_pkgbase() {
    let (env, _fx) = env_with_fixture("missing-dep");
    env.subscribe("dep-partner");
    aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "missing-dep").unwrap();
    let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
    let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
    aur_build::review::approve::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 = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
    aur_build::pipeline::run(&env.cfg, &env.db, &id).unwrap();

    let server = aur_build::http::spawn(env.cfg.clone(), env.db.clone()).unwrap();
    let url = format!("http://{}/attention", server.addr);
    let body = ureq::get(&url).call().unwrap().into_string().unwrap();
    assert!(body.contains("Blocked builds"), "no blocked section");
    assert!(body.contains("dep-partner"), "the blocking pkgbase is not named");
}

#[test]
fn unknown_paths_are_404_not_500() {
    let web = Web::new("plain-make");
    assert_eq!(web.get("/nope").status, 404);
    assert_eq!(web.get("/reviews/not-a-number").status, 404);
}