forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

stars_e2e.rs358 lines, 12.2 KiBHistoryRawDownload
1//! Black-box tests for stars, the explore page, the starred profile section and the archived
2//! banner. Like the other e2e tests, this starts the real `forge` binary and drives it over
3//! HTTP. Cookies are set by hand because the session cookie is `__Host-` and `Secure`.
4
5use crate::common::{
6 Http, Resp, Server, bin, describe, input_value, launch, login, pick_ports, tool_on_path,
7 write_config,
8};
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::process::{Command, Stdio};
12
13use forge_core::{Store, Visibility};
14use reqwest::header::LOCATION;
15
16const PW: &str = "tahinli-password-123";
17
18/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
19fn admin(config: &Path, args: &[&str]) {
20 let out = Command::new(bin())
21 .arg("--config")
22 .arg(config)
23 .arg("admin")
24 .args(args)
25 .env("FORGE_PASSWORD", PW)
26 .output()
27 .expect("run admin command");
28 assert!(
29 out.status.success(),
30 "admin {args:?} failed:\n{}",
31 describe(&out)
32 );
33}
34
35/// Creates a bare git repo for `repo_id` at its data-dir location, as the create-repo page does.
36fn init_bare(data_dir: &Path, repo_id: &str) {
37 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");
38 fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");
39 let out = Command::new("git")
40 .args(["init", "--bare", "--quiet", "--initial-branch=main"])
41 .arg(&path)
42 .output()
43 .expect("run git init");
44 assert!(out.status.success(), "git init --bare: {}", describe(&out));
45}
46
47/// A running server plus the data it was seeded with. The temp dir lives as long as the test.
48struct Env {
49 _root: tempfile::TempDir,
50 _server: Server,
51 http: Http,
52}
53
54/// Creates the users and config, then runs `seed` against the store before the server starts.
55/// The seed closure receives the data dir (for bare repos) and the open store.
56async fn start<F, Fut>(seed: F) -> Env
57where
58 F: FnOnce(PathBuf, Store) -> Fut,
59 Fut: std::future::Future<Output = ()>,
60{
61 let root = tempfile::Builder::new()
62 .prefix("fst")
63 .tempdir_in("/tmp")
64 .expect("temp dir");
65 let dir = root.path().to_path_buf();
66 let ports = pick_ports();
67 let config = write_config(&dir, ports);
68 admin(&config, &["create-user", "tahinli"]);
69 admin(&config, &["create-user", "bob"]);
70 let store = Store::open(&dir.join("forge.db"))
71 .await
72 .expect("open store");
73 seed(dir.clone(), store).await;
74 let (server, ports) = launch(&dir, ports).await;
75 let http = Http::new(ports.http);
76 Env {
77 _root: root,
78 _server: server,
79 http,
80 }
81}
82
83/// Tahinli owns `pub` (public), `priv` (private) and `pct%x` (public, for literal-search checks).
84async fn seed_repos(dir: PathBuf, store: Store) {
85 let tahinli = store
86 .user_by_username("tahinli")
87 .await
88 .unwrap()
89 .expect("tahinli");
90 for (name, vis) in [
91 ("pub", Visibility::Public),
92 ("priv", Visibility::Private),
93 ("pct%x", Visibility::Public),
94 ] {
95 let repo = store
96 .create_repo(&tahinli.id, name, "", vis, "main")
97 .await
98 .expect("create repo");
99 init_bare(&dir, &repo.id);
100 }
101}
102
103/// Writes one commit with a README to the bare repo's `main`, using plumbing only (no hooks).
104fn commit_main(data_dir: &Path, repo_id: &str) {
105 let id = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");
106 let blob = plumbing(&id, &["hash-object", "-w", "--stdin"], b"hello\n");
107 let tree = plumbing(
108 &id,
109 &["mktree"],
110 format!("100644 blob {blob}\tREADME.md\n").as_bytes(),
111 );
112 let commit = plumbing(&id, &["commit-tree", &tree, "-m", "init"], b"");
113 let _ = plumbing(&id, &["update-ref", "refs/heads/main", &commit], b"");
114}
115
116/// Runs git against the bare repo at `path` with fixed identities and returns trimmed stdout.
117fn plumbing(path: &Path, args: &[&str], stdin: &[u8]) -> String {
118 use std::io::Write;
119 let mut child = Command::new("git")
120 .arg("--git-dir")
121 .arg(path)
122 .args(args)
123 .env("GIT_AUTHOR_NAME", "t")
124 .env("GIT_AUTHOR_EMAIL", "t@example.com")
125 .env("GIT_COMMITTER_NAME", "t")
126 .env("GIT_COMMITTER_EMAIL", "t@example.com")
127 .stdin(Stdio::piped())
128 .stdout(Stdio::piped())
129 .stderr(Stdio::piped())
130 .spawn()
131 .expect("run git");
132 child
133 .stdin
134 .take()
135 .expect("stdin")
136 .write_all(stdin)
137 .expect("write stdin");
138 let out = child.wait_with_output().expect("git output");
139 assert!(out.status.success(), "git {args:?}: {}", describe(&out));
140 String::from_utf8_lossy(&out.stdout).trim().to_owned()
141}
142
143/// Text of every `.repo-name` link on a page, in document order.
144fn repo_names(body: &str) -> Vec<String> {
145 let doc = scraper::Html::parse_document(body);
146 let selector = scraper::Selector::parse(".repo-name").expect("selector");
147 doc.select(&selector)
148 .map(|el| el.text().collect::<String>().trim().to_owned())
149 .collect()
150}
151
152/// Sends a star POST with an optional Referer header.
153async fn post_star(
154 http: &Http,
155 path: &str,
156 csrf: &str,
157 cookie: Option<&str>,
158 referer: Option<&str>,
159) -> Resp {
160 let mut req = http
161 .client
162 .post(format!("{}{path}", http.base))
163 .form(&[("csrf", csrf)]);
164 if let Some(referer) = referer {
165 req = req.header(reqwest::header::REFERER, referer);
166 }
167 http.send(req, cookie).await
168}
169
170#[tokio::test]
171async fn star_round_trip_shows_the_count() {
172 if !tool_on_path("git") {
173 eprintln!("SKIP stars_e2e: `git` was not found on PATH");
174 return;
175 }
176 let env = start(seed_repos).await;
177 let bob = login(&env.http, "bob", PW).await;
178
179 let page = env.http.get("/tahinli/pub", Some(&bob)).await;
180 assert_eq!(page.status, 200, "repo page");
181 assert!(
182 page.body.contains("Star 0"),
183 "star button with zero: {}",
184 page.body
185 );
186 let csrf = input_value(&page.body, "csrf");
187
188 let res = post_star(&env.http, "/tahinli/pub/star", &csrf, Some(&bob), None).await;
189 assert_eq!(res.status, 303, "star: {}", res.body);
190 assert_eq!(res.header(LOCATION).as_deref(), Some("/tahinli/pub"));
191 let page = env.http.get("/tahinli/pub", Some(&bob)).await;
192 assert!(page.body.contains("Unstar 1"), "after star: {}", page.body);
193
194 // Back to the tree page through the Referer, when it is a same-origin path.
195 let referer = format!("{}/tahinli/pub/tree/main", env.http.base);
196 let res = post_star(
197 &env.http,
198 "/tahinli/pub/unstar",
199 &csrf,
200 Some(&bob),
201 Some(&referer),
202 )
203 .await;
204 assert_eq!(res.status, 303, "unstar: {}", res.body);
205 assert_eq!(
206 res.header(LOCATION).as_deref(),
207 Some("/tahinli/pub/tree/main")
208 );
209 let page = env.http.get("/tahinli/pub", Some(&bob)).await;
210 assert!(page.body.contains("Star 0"), "after unstar: {}", page.body);
211
212 // A Referer on another host is ignored.
213 let foreign = "https://evil.example/tahinli/pub";
214 let res = post_star(
215 &env.http,
216 "/tahinli/pub/star",
217 &csrf,
218 Some(&bob),
219 Some(foreign),
220 )
221 .await;
222 assert_eq!(res.header(LOCATION).as_deref(), Some("/tahinli/pub"));
223}
224
225#[tokio::test]
226async fn anonymous_star_redirects_to_login() {
227 let env = start(seed_repos).await;
228 let res = post_star(&env.http, "/tahinli/pub/star", "anything", None, None).await;
229 assert_eq!(res.status, 303);
230 let location = res.header(LOCATION).unwrap_or_default();
231 assert!(
232 location.starts_with("/login"),
233 "redirect to login, got {location}"
234 );
235}
236
237#[tokio::test]
238async fn star_without_a_valid_csrf_token_is_403() {
239 let env = start(seed_repos).await;
240 let bob = login(&env.http, "bob", PW).await;
241 let res = post_star(&env.http, "/tahinli/pub/star", "wrong", Some(&bob), None).await;
242 assert_eq!(res.status, 403);
243 let page = env.http.get("/tahinli/pub", Some(&bob)).await;
244 assert!(page.body.contains("Star 0"), "nothing was starred");
245}
246
247#[tokio::test]
248async fn star_on_a_private_repo_is_404_for_a_non_reader() {
249 let env = start(seed_repos).await;
250 let bob = login(&env.http, "bob", PW).await;
251 let res = post_star(
252 &env.http,
253 "/tahinli/priv/star",
254 "anything",
255 Some(&bob),
256 None,
257 )
258 .await;
259 assert_eq!(res.status, 404);
260}
261
262#[tokio::test]
263async fn explore_lists_public_repos_and_searches_literally() {
264 let env = start(seed_repos).await;
265
266 let page = env.http.get("/explore", None).await;
267 assert_eq!(page.status, 200, "explore");
268 let names = repo_names(&page.body);
269 assert!(names.contains(&"tahinli/pub".to_owned()), "{names:?}");
270 assert!(names.contains(&"tahinli/pct%x".to_owned()), "{names:?}");
271 assert!(
272 !names.contains(&"tahinli/priv".to_owned()),
273 "private hidden: {names:?}"
274 );
275
276 // `%` in the search is a literal percent sign, so only `pct%x` matches.
277 let page = env.http.get("/explore?q=%25", None).await;
278 assert_eq!(repo_names(&page.body), vec!["tahinli/pct%x".to_owned()]);
279
280 // Sorting by stars puts a starred repo first; the default (name) puts `pct%x` first.
281 let bob = login(&env.http, "bob", PW).await;
282 let page = env.http.get("/tahinli/pub", Some(&bob)).await;
283 let csrf = input_value(&page.body, "csrf");
284 let res = post_star(&env.http, "/tahinli/pub/star", &csrf, Some(&bob), None).await;
285 assert_eq!(res.status, 303);
286 let by_name = repo_names(&env.http.get("/explore?sort=name", None).await.body);
287 assert_eq!(
288 by_name,
289 vec!["tahinli/pct%x".to_owned(), "tahinli/pub".to_owned()]
290 );
291 let by_stars = repo_names(&env.http.get("/explore?sort=stars", None).await.body);
292 assert_eq!(
293 by_stars,
294 vec!["tahinli/pub".to_owned(), "tahinli/pct%x".to_owned()]
295 );
296}
297
298#[tokio::test]
299async fn profile_stars_tab_hides_repos_the_viewer_cannot_read() {
300 let env = start(|dir, store| async move {
301 seed_repos(dir, store.clone()).await;
302 let tahinli = store
303 .user_by_username("tahinli")
304 .await
305 .unwrap()
306 .expect("tahinli");
307 let bob = store.user_by_username("bob").await.unwrap().expect("bob");
308 let repos = store.list_repos_by_owner(&tahinli.id).await.unwrap();
309 let find = |name: &str| repos.iter().find(|r| r.name == name).unwrap().id.clone();
310 // Bob stars a public repo and a private one he cannot read.
311 store.star(&bob.id, &find("pub")).await.unwrap();
312 store.star(&bob.id, &find("priv")).await.unwrap();
313 })
314 .await;
315
316 let anon = env.http.get("/bob?tab=stars", None).await;
317 assert_eq!(anon.status, 200);
318 let starred = |body: &str| {
319 let doc = scraper::Html::parse_document(body);
320 let selector = scraper::Selector::parse(".repo-list .repo-name").expect("selector");
321 doc.select(&selector)
322 .map(|el| el.text().collect::<String>().trim().to_owned())
323 .collect::<Vec<_>>()
324 };
325 assert_eq!(starred(&anon.body), vec!["tahinli/pub".to_owned()]);
326
327 let tahinli = login(&env.http, "tahinli", PW).await;
328 let owner = env.http.get("/bob?tab=stars", Some(&tahinli)).await;
329 let mut names = starred(&owner.body);
330 names.sort();
331 assert_eq!(
332 names,
333 vec!["tahinli/priv".to_owned(), "tahinli/pub".to_owned()]
334 );
335}
336
337#[tokio::test]
338async fn archived_banner_shows_on_tree_and_issues_pages() {
339 let env = start(|dir, store| async move {
340 seed_repos(dir.clone(), store.clone()).await;
341 let repo = store
342 .repo_by_owner_and_name("tahinli", "pub")
343 .await
344 .unwrap()
345 .expect("pub");
346 commit_main(&dir, &repo.id);
347 store.set_repo_archived(&repo.id, true).await.unwrap();
348 })
349 .await;
350
351 let banner = "This repository is archived. It is read-only.";
352 let tree = env.http.get("/tahinli/pub/tree/main", None).await;
353 assert_eq!(tree.status, 200, "tree page");
354 assert!(tree.body.contains(banner), "banner on tree");
355 let issues = env.http.get("/tahinli/pub/issues", None).await;
356 assert_eq!(issues.status, 200, "issues page");
357 assert!(issues.body.contains(banner), "banner on issues");
358}