forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

browse_e2e.rs1004 lines, 35.7 KiBHistoryRawDownload
1//! Black-box browse test. It starts the real `forge` binary with three listeners (app, ssh and
2//! the raw user-content origin), pushes fixtures over HTTPS with a token, and checks the app pages
3//! and the raw origin with plain HTTP.
4//!
5//! Cookies are handled by hand, as in `git_e2e.rs`: the session cookie is `__Host-forge_session`
6//! with `Secure`, so a cookie jar would not send it over plain http.
7
8use crate::common::{bin, describe, input_value, launch, pick_ports, tool_on_path, write_config};
9use std::fs;
10use std::path::Path;
11use std::process::{Command, Output};
12use std::time::Duration;
13
14use reqwest::header::{
15 CONTENT_DISPOSITION, CONTENT_SECURITY_POLICY, CONTENT_TYPE, COOKIE, HeaderMap, HeaderName,
16 LOCATION, SET_COOKIE, X_CONTENT_TYPE_OPTIONS,
17};
18
19const TAHINLI_PW: &str = "tahinli-password-123";
20const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x00IEND\xaeB`\x82";
21
22/// A received HTTP response. The body is kept as bytes because the archive is binary.
23struct Resp {
24 status: u16,
25 headers: HeaderMap,
26 bytes: Vec<u8>,
27}
28
29impl Resp {
30 fn body(&self) -> String {
31 String::from_utf8_lossy(&self.bytes).into_owned()
32 }
33
34 fn header(&self, name: HeaderName) -> Option<String> {
35 self.headers
36 .get(name)
37 .and_then(|v| v.to_str().ok())
38 .map(str::to_owned)
39 }
40
41 fn set_cookies(&self) -> Vec<String> {
42 self.headers
43 .get_all(SET_COOKIE)
44 .iter()
45 .filter_map(|v| v.to_str().ok().map(str::to_owned))
46 .collect()
47 }
48}
49
50/// A client for one listener. `base` is the origin, e.g. `http://127.0.0.1:8080`.
51struct Http {
52 client: reqwest::Client,
53 base: String,
54}
55
56impl Http {
57 fn new(port: u16) -> Self {
58 let client = reqwest::Client::builder()
59 .redirect(reqwest::redirect::Policy::none())
60 .timeout(Duration::from_secs(60))
61 .build()
62 .expect("http client");
63 Self {
64 client,
65 base: format!("http://127.0.0.1:{port}"),
66 }
67 }
68
69 async fn get(&self, path: &str, cookie: Option<&str>) -> Resp {
70 self.send(self.client.get(format!("{}{path}", self.base)), cookie)
71 .await
72 }
73
74 async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp {
75 self.send(
76 self.client.post(format!("{}{path}", self.base)).form(form),
77 cookie,
78 )
79 .await
80 }
81
82 async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp {
83 let req = match cookie {
84 Some(cookie) => req.header(COOKIE, cookie),
85 None => req,
86 };
87 let res = req.send().await.expect("http request");
88 let status = res.status().as_u16();
89 let headers = res.headers().clone();
90 let bytes = res.bytes().await.expect("read body").to_vec();
91 Resp {
92 status,
93 headers,
94 bytes,
95 }
96 }
97}
98
99/// Returns `name=value` for the cookie whose name ends with `suffix`, e.g. `forge_session`
100/// matches `__Host-forge_session`. Cleared cookies (empty value) are ignored.
101fn cookie_named(resp: &Resp, suffix: &str) -> Option<String> {
102 resp.set_cookies().iter().find_map(|set| {
103 let pair = set.split(';').next()?;
104 let (name, value) = pair.split_once('=')?;
105 (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}"))
106 })
107}
108
109/// The values of `attr` on every element matching `selector`, in document order.
110fn attr_values(body: &str, selector: &str, attr: &str) -> Vec<String> {
111 let doc = scraper::Html::parse_document(body);
112 let selector = scraper::Selector::parse(selector).expect("selector");
113 doc.select(&selector)
114 .filter_map(|el| el.value().attr(attr).map(str::to_owned))
115 .collect()
116}
117
118/// The text of every element matching `selector`.
119fn element_texts(body: &str, selector: &str) -> Vec<String> {
120 let doc = scraper::Html::parse_document(body);
121 let selector = scraper::Selector::parse(selector).expect("selector");
122 doc.select(&selector)
123 .map(|el| el.text().collect::<String>())
124 .collect()
125}
126
127/// Checks the latest commit in a repo page's head line: its short sha linking to the commit, no
128/// subject, and the commit count label.
129fn assert_latest_bar(body: &str, what: &str, subject: &str, oid: &str, count: &str) {
130 assert_eq!(
131 element_texts(body, ".head-sub").len(),
132 1,
133 "{what}: one head line"
134 );
135 let shas = element_texts(body, ".head-sub a.mono");
136 assert_eq!(shas.len(), 1, "{what}: the head line must show the sha");
137 assert_eq!(shas[0].trim(), &oid[..7], "{what}: short sha");
138 let links = element_texts(body, ".head-sub a[href*=\"/commit/\"]");
139 assert!(
140 !links.iter().any(|l| l.trim() == subject),
141 "{what}: the head line must not show the subject {subject:?}, got {links:?}"
142 );
143 let parts = element_texts(body, ".head-sub span");
144 assert!(
145 parts.iter().any(|c| c.trim() == count),
146 "{what}: the head line must show {count:?}, got {parts:?}"
147 );
148}
149
150fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
151 let out = Command::new(bin())
152 .arg("--config")
153 .arg(config)
154 .args(["admin", "create-user", username])
155 .args(extra)
156 .env("FORGE_PASSWORD", password)
157 .output()
158 .expect("run admin create-user");
159 ok(&out, &format!("create-user {username}"));
160}
161
162fn ok(out: &Output, what: &str) {
163 assert!(out.status.success(), "{what} failed:\n{}", describe(out));
164}
165
166fn git(cwd: &Path, args: &[&str]) -> Output {
167 Command::new("git")
168 .current_dir(cwd)
169 .args(["-c", "credential.helper="])
170 .args(args)
171 .env("GIT_TERMINAL_PROMPT", "0")
172 .output()
173 .expect("run git")
174}
175
176fn path_str(path: &Path) -> &str {
177 path.to_str().expect("utf-8 path")
178}
179
180fn set_identity(repo: &Path) {
181 ok(
182 &git(repo, &["config", "user.name", "tahinli"]),
183 "set user.name",
184 );
185 ok(
186 &git(repo, &["config", "user.email", "tahinli@example.com"]),
187 "set user.email",
188 );
189}
190
191/// Writes the browse fixtures into `work`: a README with a heading, a relative link and a relative
192/// image, a Rust source file, a PNG, and an HTML file that must never render inline.
193fn write_fixtures(work: &Path) {
194 fs::create_dir_all(work.join("src")).expect("create src");
195 fs::write(
196 work.join("README.md"),
197 "# Browse Test\n\nSee [the code](src/main.rs).\n\n![logo](img.png)\n",
198 )
199 .expect("write README.md");
200 fs::write(work.join("src/main.rs"), "fn main() {}\n").expect("write main.rs");
201 fs::write(work.join("img.png"), PNG).expect("write img.png");
202 fs::write(work.join("evil.html"), "<script>alert(1)</script>\n").expect("write evil.html");
203 // A Git LFS pointer whose object is not stored, so the blob page says so.
204 fs::write(
205 work.join("weights.bin"),
206 "version https://git-lfs.github.com/spec/v1\noid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\nsize 1234\n",
207 )
208 .expect("write weights.bin");
209}
210
211/// Stages everything in `repo` and commits it with the repo's local identity.
212fn commit_all(repo: &Path, message: &str) {
213 set_identity(repo);
214 ok(&git(repo, &["add", "-A"]), "git add");
215 ok(
216 &git(
217 repo,
218 &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message],
219 ),
220 "git commit",
221 );
222}
223
224fn head_sha(repo: &Path) -> String {
225 let out = git(repo, &["rev-parse", "HEAD"]);
226 ok(&out, "rev-parse HEAD");
227 String::from_utf8_lossy(&out.stdout).trim().to_owned()
228}
229
230/// Clones the empty repo at `url` into `work`, pushes the fixtures to `main` and an extra commit to
231/// `feature/x`, and returns the commit oid of `main`.
232fn push_fixtures(dir: &Path, url: &str, work: &Path) -> String {
233 ok(&git(dir, &["clone", url, path_str(work)]), "https clone");
234 write_fixtures(work);
235 commit_all(work, "browse fixtures");
236 ok(&git(work, &["push", "origin", "HEAD:main"]), "push main");
237 let main_oid = head_sha(work);
238
239 ok(
240 &git(work, &["checkout", "-q", "-b", "feature/x"]),
241 "create feature/x",
242 );
243 fs::write(work.join("feature.txt"), "on a branch\n").expect("write feature.txt");
244 commit_all(work, "feature commit");
245 ok(
246 &git(work, &["push", "origin", "feature/x"]),
247 "push feature/x",
248 );
249 main_oid
250}
251
252/// Logs in through the real `/login` form and returns the `__Host-forge_session` cookie header.
253async fn login(http: &Http, username: &str, password: &str) -> String {
254 let page = http.get("/login", None).await;
255 assert_eq!(page.status, 200, "GET /login");
256 let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie");
257 let precsrf = input_value(&page.body(), "precsrf");
258 let res = http
259 .post_form(
260 "/login",
261 &[
262 ("username", username),
263 ("password", password),
264 ("next", "/"),
265 ("precsrf", &precsrf),
266 ],
267 Some(&precsrf_cookie),
268 )
269 .await;
270 assert_eq!(res.status, 303, "login as {username}: {}", res.body());
271 cookie_named(&res, "forge_session").expect("session cookie after login")
272}
273
274/// Creates an access token through `/settings/tokens` and returns the token shown once.
275async fn create_token(http: &Http, session: &str, name: &str) -> String {
276 let page = http.get("/settings/keys", Some(session)).await;
277 assert_eq!(page.status, 200, "GET /settings/keys");
278 let csrf = input_value(&page.body(), "csrf");
279 let res = http
280 .post_form(
281 "/settings/tokens",
282 &[("csrf", &csrf), ("name", name), ("expires", "30")],
283 Some(session),
284 )
285 .await;
286 assert_eq!(res.status, 200, "create token: {}", res.body());
287 let token = element_texts(&res.body(), "pre.code code")
288 .into_iter()
289 .next()
290 .expect("token shown after creation");
291 let token = token.trim().to_owned();
292 assert!(token.starts_with("forge_"), "unexpected token shape");
293 token
294}
295
296/// Creates a repo through `/new`.
297async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) {
298 let page = http.get("/new", Some(session)).await;
299 assert_eq!(page.status, 200, "GET /new");
300 let csrf = input_value(&page.body(), "csrf");
301 let res = http
302 .post_form(
303 "/new",
304 &[
305 ("csrf", &csrf),
306 ("name", name),
307 ("description", ""),
308 ("visibility", visibility),
309 ("default_branch", "main"),
310 ],
311 Some(session),
312 )
313 .await;
314 assert_eq!(res.status, 303, "create repo {name}: {}", res.body());
315 assert_eq!(
316 res.header(LOCATION).as_deref(),
317 Some(format!("/tahinli/{name}").as_str())
318 );
319}
320
321/// Asserts that a response on the raw origin sets no cookie.
322fn assert_no_cookie(resp: &Resp, what: &str) {
323 assert!(
324 resp.set_cookies().is_empty(),
325 "{what} must not set a cookie: {:?}",
326 resp.set_cookies()
327 );
328}
329
330#[tokio::test]
331async fn browse_end_to_end() {
332 if !tool_on_path("git") {
333 eprintln!("SKIP browse_e2e: `git` was not found on PATH, so the browse test is skipped");
334 return;
335 }
336
337 // Keep the path short, as in git_e2e.rs.
338 let root = tempfile::Builder::new()
339 .prefix("fbrw")
340 .tempdir_in("/tmp")
341 .expect("temp dir");
342 let dir = root.path().to_path_buf();
343
344 let ports = pick_ports();
345 let config = write_config(&dir, ports);
346
347 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
348
349 let (_server, ports) = launch(&dir, ports).await;
350 let http = Http::new(ports.http);
351 let raw = Http::new(ports.content);
352 let raw_base = raw.base.clone();
353
354 // Setup: tahinli logs in, makes a token and creates one public and one private repo.
355 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
356 let token = create_token(&http, &tahinli, "browse-token").await;
357 create_repo(&http, &tahinli, "pub", "public").await;
358 create_repo(&http, &tahinli, "priv", "private").await;
359
360 // Push the same fixtures to both repos over HTTPS with the token.
361 let pub_url = format!(
362 "http://tahinli:{token}@127.0.0.1:{}/tahinli/pub.git",
363 ports.http
364 );
365 let priv_url = format!(
366 "http://tahinli:{token}@127.0.0.1:{}/tahinli/priv.git",
367 ports.http
368 );
369 let pub_main = push_fixtures(&dir, &pub_url, &dir.join("pub-work"));
370 push_fixtures(&dir, &priv_url, &dir.join("priv-work"));
371
372 // A branch named `media` in the public repo, with its own README.md.
373 let pub_work = dir.join("pub-work");
374 ok(
375 &git(
376 &pub_work,
377 &["checkout", "-q", "-b", "media", pub_main.as_str()],
378 ),
379 "create media branch",
380 );
381 fs::write(pub_work.join("README.md"), "# On a media branch\n").expect("write media README");
382 commit_all(&pub_work, "media branch");
383 ok(&git(&pub_work, &["push", "origin", "media"]), "push media");
384
385 // App origin, anonymous, public repo.
386 let home = http.get("/tahinli/pub", None).await;
387 assert_eq!(home.status, 200, "anonymous home of public repo");
388 let csp = home
389 .header(CONTENT_SECURITY_POLICY)
390 .expect("CSP on app page");
391 let img_src = csp
392 .split(';')
393 .map(str::trim)
394 .find(|d| d.starts_with("img-src"))
395 .unwrap_or("");
396 assert!(
397 img_src.contains(&raw_base),
398 "app CSP img-src must include the raw origin: {csp}"
399 );
400
401 let home_body = home.body();
402 assert!(
403 element_texts(&home_body, "h1")
404 .iter()
405 .any(|t| t.contains("Browse Test")),
406 "README heading missing on home"
407 );
408 assert!(
409 attr_values(&home_body, "a", "href")
410 .iter()
411 .any(|h| h == "/tahinli/pub/blob/main/src/main.rs"),
412 "relative README link must point at the blob page"
413 );
414 let image_srcs = attr_values(&home_body, "img", "src");
415 assert!(
416 image_srcs
417 .iter()
418 .any(|s| s.starts_with(&format!("{raw_base}/tahinli/pub/main/"))
419 && s.ends_with("img.png")),
420 "README image must point at the raw origin: {image_srcs:?}"
421 );
422
423 // Latest commit bar: the root has one commit on main, so its subject, short sha and count.
424 assert_latest_bar(
425 &home_body,
426 "repo home",
427 "browse fixtures",
428 &pub_main,
429 "1 commit",
430 );
431
432 let tree = http.get("/tahinli/pub/tree/main/src", None).await;
433 assert_eq!(tree.status, 200, "tree of src");
434 assert!(tree.body().contains("main.rs"), "tree must list main.rs");
435 assert_latest_bar(
436 &tree.body(),
437 "tree of src",
438 "browse fixtures",
439 &pub_main,
440 "1 commit",
441 );
442
443 let blob = http.get("/tahinli/pub/blob/main/src/main.rs", None).await;
444 assert_eq!(blob.status, 200, "blob of main.rs");
445 let blob_body = blob.body();
446 assert!(blob_body.contains("id=\"L1\""), "blob needs L1 anchors");
447 assert!(
448 blob_body.contains("hl-"),
449 "blob needs hl- highlight classes"
450 );
451
452 let pointer = http.get("/tahinli/pub/blob/main/weights.bin", None).await;
453 assert_eq!(pointer.status, 200, "blob of an LFS pointer");
454 assert!(
455 pointer.body().contains("Stored with Git LFS ("),
456 "pointer blob must say it is stored with Git LFS"
457 );
458 assert!(
459 pointer
460 .body()
461 .contains("this forge does not have the object"),
462 "pointer without a stored object must say so"
463 );
464
465 let commits = http.get("/tahinli/pub/commits/main", None).await;
466 assert_eq!(commits.status, 200, "commits of main");
467 assert!(
468 commits.body().contains("browse fixtures"),
469 "commit list must show the commit"
470 );
471
472 let commit = http
473 .get(&format!("/tahinli/pub/commit/{pub_main}"), None)
474 .await;
475 assert_eq!(commit.status, 200, "commit page");
476 assert!(
477 commit.body().contains("src/main.rs"),
478 "commit page must show the diff of main.rs"
479 );
480
481 let branches = http.get("/tahinli/pub/branches", None).await;
482 assert_eq!(branches.status, 200, "branches");
483 assert!(
484 branches.body().contains("feature/x"),
485 "branches must list feature/x"
486 );
487
488 let feature_head = String::from_utf8_lossy(&git(&pub_work, &["rev-parse", "feature/x"]).stdout)
489 .trim()
490 .to_owned();
491 let feature_tree = http.get("/tahinli/pub/tree/feature/x", None).await;
492 assert_eq!(feature_tree.status, 200, "tree of feature/x");
493 assert!(
494 feature_tree.body().contains("feature.txt"),
495 "feature/x tree must list feature.txt"
496 );
497 // The feature commit is the newest on feature/x, on top of the two-commit history.
498 assert_latest_bar(
499 &feature_tree.body(),
500 "tree of feature/x",
501 "feature commit",
502 &feature_head,
503 "2 commits",
504 );
505
506 let archive = http.get("/tahinli/pub/archive/main.tar.gz", None).await;
507 assert_eq!(archive.status, 200, "tar.gz archive");
508 assert!(
509 archive.bytes.starts_with(&[0x1f, 0x8b]),
510 "archive must start with gzip magic bytes"
511 );
512
513 // App origin, private repo: anonymous gets 404 everywhere.
514 for path in [
515 "/tahinli/priv",
516 "/tahinli/priv/tree/main/src",
517 "/tahinli/priv/blob/main/src/main.rs",
518 ] {
519 let res = http.get(path, None).await;
520 assert_eq!(res.status, 404, "anonymous {path} on private repo");
521 }
522
523 // Logged in, the image blob page carries a signed raw URL.
524 let priv_img = http
525 .get("/tahinli/priv/blob/main/img.png", Some(&tahinli))
526 .await;
527 assert_eq!(priv_img.status, 200, "owner's blob page of img.png");
528 let priv_img_src = attr_values(&priv_img.body(), "img[src*=\"?token=\"]", "src")
529 .into_iter()
530 .next()
531 .expect("img.png page must embed a raw URL with ?token=");
532 assert!(
533 priv_img_src.starts_with(&format!("{raw_base}/tahinli/priv/main/img.png?token=")),
534 "signed raw URL shape: {priv_img_src}"
535 );
536
537 // Raw origin: the media route 404s when the repo does not link the object.
538 let media = raw.get("/tahinli/pub/-/media/main/weights.bin", None).await;
539 assert_eq!(media.status, 404, "media of an unstored LFS object");
540
541 // Raw origin: a branch named `media` is an ordinary raw path, not the media route.
542 let media_branch = raw.get("/tahinli/pub/media/README.md", None).await;
543 assert_eq!(
544 media_branch.status, 200,
545 "raw README.md on the media branch"
546 );
547 assert_eq!(media_branch.body(), "# On a media branch\n");
548
549 // Raw origin: `-` is never a ref name, so it is a 404 and not resolved.
550 let dash = raw.get("/tahinli/pub/-/README.md", None).await;
551 assert_eq!(dash.status, 404, "raw path with a `-` ref");
552
553 // Raw origin: public file.
554 let main_rs = raw.get("/tahinli/pub/main/src/main.rs", None).await;
555 assert_eq!(main_rs.status, 200, "raw public main.rs");
556 assert_eq!(
557 main_rs.header(CONTENT_TYPE).as_deref(),
558 Some("text/plain; charset=utf-8")
559 );
560 assert_eq!(
561 main_rs.header(X_CONTENT_TYPE_OPTIONS).as_deref(),
562 Some("nosniff")
563 );
564 let raw_csp = main_rs
565 .header(CONTENT_SECURITY_POLICY)
566 .expect("CSP on raw page");
567 assert!(
568 raw_csp.contains("sandbox"),
569 "raw CSP must sandbox: {raw_csp}"
570 );
571 assert_no_cookie(&main_rs, "raw public main.rs");
572
573 // Raw origin: HTML is served as a download, never inline.
574 let evil = raw.get("/tahinli/pub/main/evil.html", None).await;
575 assert_eq!(evil.status, 200, "raw evil.html");
576 assert!(
577 evil.header(CONTENT_DISPOSITION)
578 .is_some_and(|v| v.starts_with("attachment")),
579 "evil.html must be Content-Disposition: attachment"
580 );
581 assert_no_cookie(&evil, "raw evil.html");
582
583 // Raw origin: images keep their image type.
584 let img = raw.get("/tahinli/pub/main/img.png", None).await;
585 assert_eq!(img.status, 200, "raw img.png");
586 assert_eq!(img.header(CONTENT_TYPE).as_deref(), Some("image/png"));
587 assert_no_cookie(&img, "raw img.png");
588
589 // Raw origin: private repo needs a valid token.
590 let priv_no_token = raw.get("/tahinli/priv/main/img.png", None).await;
591 assert_eq!(priv_no_token.status, 404, "private raw without token");
592 assert_no_cookie(&priv_no_token, "raw private without token");
593
594 let priv_path = priv_img_src
595 .strip_prefix(&raw_base)
596 .expect("raw base prefix");
597 let priv_ok = raw.get(priv_path, None).await;
598 assert_eq!(priv_ok.status, 200, "private raw with the scraped token");
599 assert_no_cookie(&priv_ok, "raw private with token");
600
601 // Tampering with the signature (its first character) must fail. The first base64 character
602 // carries six significant bits, so flipping it always changes the signature.
603 let (file_part, query) = priv_path.split_once("?token=").expect("token query");
604 let (expires, sig) = query.split_once('.').expect("token shape");
605 let flipped = if sig.starts_with('A') { 'B' } else { 'A' };
606 let tampered_sig = format!("{flipped}{}", &sig[1..]);
607 let tampered = raw
608 .get(&format!("{file_part}?token={expires}.{tampered_sig}"), None)
609 .await;
610 assert_eq!(tampered.status, 404, "tampered token must be rejected");
611 assert_no_cookie(&tampered, "raw tampered token");
612
613 // Raw origin has no app routes.
614 let login_page = raw.get("/login", None).await;
615 assert_eq!(
616 login_page.status, 404,
617 "/login must not exist on raw origin"
618 );
619 assert_no_cookie(&login_page, "raw /login");
620}
621
622/// Opens a code view stream and returns the response with its body still unread.
623async fn open_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response {
624 let mut req = http.client.get(format!("{}{path}", http.base));
625 if let Some(cookie) = cookie {
626 req = req.header(COOKIE, cookie);
627 }
628 let mut res = req.send().await.expect("stream request");
629 // A stream that opens sends its `retry` field first. It is not an event, so it is read here.
630 if res.status().is_success() {
631 let retry = next_chunk(&mut res).await.expect("the retry field");
632 assert!(retry.contains("retry: 1000"), "{retry}");
633 }
634 res
635}
636
637/// The next chunk of a stream. None when nothing arrives within two seconds.
638async fn next_chunk(res: &mut reqwest::Response) -> Option<String> {
639 let chunk = tokio::time::timeout(Duration::from_secs(2), res.chunk())
640 .await
641 .ok()?
642 .expect("stream chunk")?;
643 Some(String::from_utf8_lossy(&chunk).into_owned())
644}
645
646#[tokio::test]
647async fn code_view_stream_follows_pushes() {
648 if !tool_on_path("git") {
649 eprintln!("SKIP browse_e2e: `git` was not found on PATH, so the stream test is skipped");
650 return;
651 }
652
653 let root = tempfile::Builder::new()
654 .prefix("fliv")
655 .tempdir_in("/tmp")
656 .expect("temp dir");
657 let dir = root.path().to_path_buf();
658 let ports = pick_ports();
659 let config = write_config(&dir, ports);
660 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
661 let (_server, ports) = launch(&dir, ports).await;
662 let http = Http::new(ports.http);
663
664 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
665 let token = create_token(&http, &tahinli, "live-token").await;
666 create_repo(&http, &tahinli, "pub", "public").await;
667 create_repo(&http, &tahinli, "priv", "private").await;
668 let pub_url = format!(
669 "http://tahinli:{token}@127.0.0.1:{}/tahinli/pub.git",
670 ports.http
671 );
672 let priv_url = format!(
673 "http://tahinli:{token}@127.0.0.1:{}/tahinli/priv.git",
674 ports.http
675 );
676 let pub_main = push_fixtures(&dir, &pub_url, &dir.join("pub-live"));
677 push_fixtures(&dir, &priv_url, &dir.join("priv-live"));
678 let work = dir.join("pub-live");
679
680 // The branch page follows its branch. A commit page does not, since a commit never moves.
681 let branch_page = http.get("/tahinli/pub/tree/main/", None).await;
682 assert_eq!(branch_page.status, 200);
683 assert!(
684 branch_page
685 .body()
686 .contains(r#"data-live="/tahinli/pub/events?ref_name=main""#),
687 "branch page follows main"
688 );
689 let commit_page = http
690 .get(&format!("/tahinli/pub/tree/{pub_main}/"), None)
691 .await;
692 assert_eq!(commit_page.status, 200);
693 assert!(
694 commit_page
695 .body()
696 .contains(r#"data-live="/tahinli/pub/events""#),
697 "a commit page follows the repo header"
698 );
699 assert!(
700 !commit_page.body().contains("events?ref_name="),
701 "a commit page does not follow a branch"
702 );
703
704 // Anyone can follow a public branch.
705 let mut stream = open_stream(&http, "/tahinli/pub/events?ref_name=main", None).await;
706 assert_eq!(stream.status().as_u16(), 200);
707 assert_eq!(
708 stream.headers().get(CONTENT_TYPE).unwrap(),
709 "text/event-stream"
710 );
711
712 // A push to another branch sends nothing: main did not move and no ref was created.
713 ok(
714 &git(&work, &["checkout", "-q", "feature/x"]),
715 "checkout feature/x",
716 );
717 fs::write(work.join("other.txt"), "other\n").expect("write other.txt");
718 commit_all(&work, "other branch commit");
719 ok(
720 &git(&work, &["push", "-q", "origin", "feature/x"]),
721 "push feature/x",
722 );
723 assert!(next_chunk(&mut stream).await.is_none(), "other branch sent");
724
725 // A push to main sends one `changed` event.
726 ok(&git(&work, &["checkout", "-q", "main"]), "checkout main");
727 fs::write(work.join("README.md"), "# Live\n\nChanged by a push.\n").expect("write README");
728 commit_all(&work, "change the README");
729 ok(&git(&work, &["push", "-q", "origin", "main"]), "push main");
730 let event = next_chunk(&mut stream).await.expect("event for main");
731 assert!(event.contains("event: changed"), "{event}");
732
733 // Creating and deleting a branch changes the branch list, so the page follows it too.
734 ok(
735 &git(&work, &["checkout", "-q", "-b", "topic"]),
736 "create topic",
737 );
738 ok(
739 &git(&work, &["push", "-q", "origin", "topic"]),
740 "push topic",
741 );
742 let created = next_chunk(&mut stream)
743 .await
744 .expect("event for a new branch");
745 assert!(created.contains("event: changed"), "{created}");
746 ok(
747 &git(&work, &["push", "-q", "origin", "--delete", "topic"]),
748 "delete topic",
749 );
750 let deleted = next_chunk(&mut stream)
751 .await
752 .expect("event for a deleted branch");
753 assert!(deleted.contains("event: changed"), "{deleted}");
754
755 // A private repo streams only to a viewer who can read it.
756 let private = "/tahinli/priv/events?ref_name=main";
757 let anonymous = open_stream(&http, private, None).await;
758 assert_eq!(
759 anonymous.status().as_u16(),
760 404,
761 "private stream without a session"
762 );
763 let member = open_stream(&http, private, Some(tahinli.as_str())).await;
764 assert_eq!(
765 member.status().as_u16(),
766 200,
767 "private stream for its owner"
768 );
769}
770
771/// Reads the next event of `stream` and checks it is a `changed` event for `what`.
772async fn assert_changed(stream: &mut reqwest::Response, what: &str) {
773 let event = next_chunk(stream)
774 .await
775 .unwrap_or_else(|| panic!("no event after {what}"));
776 assert!(event.contains("event: changed"), "{what}: {event}");
777}
778
779/// Posts a form that must succeed with a redirect.
780async fn post_redirect(http: &Http, path: &str, form: &[(&str, &str)], session: &str) {
781 let res = http.post_form(path, form, Some(session)).await;
782 assert_eq!(res.status, 303, "POST {path}: {}", res.body());
783}
784
785#[tokio::test]
786async fn issue_streams_follow_writes() {
787 if !tool_on_path("git") {
788 eprintln!("SKIP browse_e2e: `git` was not found on PATH, so the stream test is skipped");
789 return;
790 }
791
792 let root = tempfile::Builder::new()
793 .prefix("filive")
794 .tempdir_in("/tmp")
795 .expect("temp dir");
796 let dir = root.path().to_path_buf();
797 let ports = pick_ports();
798 let config = write_config(&dir, ports);
799 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
800 let (_server, ports) = launch(&dir, ports).await;
801 let http = Http::new(ports.http);
802
803 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
804 create_repo(&http, &tahinli, "pub", "public").await;
805 create_repo(&http, &tahinli, "priv", "private").await;
806
807 // The list follows the repo's issues. Anyone can follow a public repo.
808 let list_page = http.get("/tahinli/pub/issues", None).await;
809 assert!(
810 list_page
811 .body()
812 .contains(r#"data-live="/tahinli/pub/issues/live""#),
813 "the list follows the repo"
814 );
815 let mut list = open_stream(&http, "/tahinli/pub/issues/live", None).await;
816 assert_eq!(list.status().as_u16(), 200);
817
818 // Creating an issue wakes the list.
819 let new_page = http.get("/tahinli/pub/issues/new", Some(&tahinli)).await;
820 let csrf = input_value(&new_page.body(), "csrf");
821 post_redirect(
822 &http,
823 "/tahinli/pub/issues/new",
824 &[("csrf", &csrf), ("title", "First issue"), ("body", "Hello")],
825 &tahinli,
826 )
827 .await;
828 assert_changed(&mut list, "creating an issue").await;
829
830 // The issue page follows the issue, and the list stays subscribed to the repo's issues.
831 let mut issue = open_stream(&http, "/tahinli/pub/issues/1/live", None).await;
832 assert_eq!(issue.status().as_u16(), 200);
833 let view = http.get("/tahinli/pub/issues/1", Some(&tahinli)).await;
834 assert!(
835 view.body()
836 .contains(r#"data-live="/tahinli/pub/issues/1/live""#),
837 "the issue page follows the issue"
838 );
839 let target = input_value(&view.body(), "target_id");
840
841 type Write<'a> = (&'a str, &'a [(&'a str, &'a str)], &'a str);
842 let writes: [Write; 8] = [
843 (
844 "/tahinli/pub/issues/1/comment",
845 &[
846 ("csrf", &csrf),
847 ("action", "comment"),
848 ("body", "A comment"),
849 ],
850 "a comment",
851 ),
852 (
853 "/tahinli/pub/issues/1/edit",
854 &[
855 ("csrf", &csrf),
856 ("title", "First issue, edited"),
857 ("body", "Hello again"),
858 ],
859 "an edit of the issue",
860 ),
861 (
862 "/tahinli/pub/issues/1/comment",
863 &[("csrf", &csrf), ("action", "close_completed"), ("body", "")],
864 "closing the issue",
865 ),
866 (
867 "/tahinli/pub/issues/1/comment",
868 &[("csrf", &csrf), ("action", "reopen"), ("body", "")],
869 "reopening the issue",
870 ),
871 (
872 "/tahinli/pub/issues/1/pin",
873 &[("csrf", &csrf), ("pinned", "1")],
874 "pinning the issue",
875 ),
876 (
877 "/tahinli/pub/issues/1/reactions",
878 &[
879 ("csrf", &csrf),
880 ("target_kind", "issue"),
881 ("target_id", &target),
882 ("reaction", "heart"),
883 ],
884 "a reaction",
885 ),
886 (
887 "/tahinli/pub/labels",
888 &[("csrf", &csrf), ("name", "bug"), ("color", "#d73a4a")],
889 "a new label",
890 ),
891 (
892 "/tahinli/pub/milestones",
893 &[("csrf", &csrf), ("title", "v1")],
894 "a new milestone",
895 ),
896 ];
897 for (path, form, what) in writes {
898 post_redirect(&http, path, form, &tahinli).await;
899 assert_changed(&mut list, what).await;
900 assert_changed(&mut issue, what).await;
901 }
902
903 // A private repo streams only to a viewer who can read it.
904 let anonymous = open_stream(&http, "/tahinli/priv/issues/live", None).await;
905 assert_eq!(
906 anonymous.status().as_u16(),
907 404,
908 "private list without a session"
909 );
910 let anonymous_issue = open_stream(&http, "/tahinli/priv/issues/1/live", None).await;
911 assert_eq!(
912 anonymous_issue.status().as_u16(),
913 404,
914 "private issue without a session"
915 );
916 let member = open_stream(&http, "/tahinli/priv/issues/live", Some(tahinli.as_str())).await;
917 assert_eq!(member.status().as_u16(), 200, "private list for its owner");
918}
919
920#[tokio::test]
921async fn browsing_pages_stream_their_changes() {
922 if !tool_on_path("git") {
923 eprintln!("SKIP browse_e2e: `git` was not found on PATH, so the stream test is skipped");
924 return;
925 }
926
927 let root = tempfile::Builder::new()
928 .prefix("flive")
929 .tempdir_in("/tmp")
930 .expect("temp dir");
931 let dir = root.path().to_path_buf();
932 let ports = pick_ports();
933 let config = write_config(&dir, ports);
934 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
935 let (_server, ports) = launch(&dir, ports).await;
936 let http = Http::new(ports.http);
937
938 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
939 let token = create_token(&http, &tahinli, "live-pages-token").await;
940 create_repo(&http, &tahinli, "pub", "public").await;
941 let pub_url = format!(
942 "http://tahinli:{token}@127.0.0.1:{}/tahinli/pub.git",
943 ports.http
944 );
945 let pushed = push_fixtures(&dir, &pub_url, &dir.join("pub-pages"));
946
947 // The inbox needs a session. Without one it refuses, and no URL names another user's inbox:
948 // the viewer always comes from the session.
949 for path in [
950 "/notifications/events",
951 "/notifications/events?all=1&user=tahinli",
952 ] {
953 let anonymous = open_stream(&http, path, None).await;
954 assert_eq!(anonymous.status().as_u16(), 401, "anonymous {path}");
955 }
956 let inbox = open_stream(&http, "/notifications/events", Some(tahinli.as_str())).await;
957 assert_eq!(inbox.status().as_u16(), 200, "inbox stream for its owner");
958
959 // The header of a public repo streams to anyone. A star moves its count for every viewer.
960 let mut header = open_stream(&http, "/tahinli/pub/events", None).await;
961 assert_eq!(header.status().as_u16(), 200);
962 let page = http.get("/tahinli/pub", Some(&tahinli)).await;
963 let csrf = input_value(&page.body(), "csrf");
964 let star = http
965 .post_form("/tahinli/pub/star", &[("csrf", &csrf)], Some(&tahinli))
966 .await;
967 assert_eq!(star.status, 303, "star: {}", star.body());
968 let event = next_chunk(&mut header).await.expect("event for a star");
969 assert!(event.contains("event: changed"), "{event}");
970 let shown = http.get("/tahinli/pub", None).await;
971 assert!(
972 shown.body().contains("\u{2605} 1"),
973 "the header shows the star"
974 );
975
976 // A second push moves main.
977 let work = dir.join("pub-pages");
978 // push_fixtures leaves the clone on feature/x, so the new commit must go on main.
979 ok(&git(&work, &["checkout", "-q", "main"]), "checkout main");
980 fs::write(work.join("PUSH.txt"), "pushed again\n").expect("write PUSH.txt");
981 commit_all(&work, "a second push");
982 ok(&git(&work, &["push", "-q", "origin", "main"]), "push main");
983 assert_ne!(pushed, head_sha(&work), "the second push moved main");
984
985 // The explore listing streams to anyone, and a new public repo changes it.
986 let mut explore = open_stream(&http, "/explore/events", None).await;
987 assert_eq!(explore.status().as_u16(), 200);
988 create_repo(&http, &tahinli, "lib", "public").await;
989 let listed = next_chunk(&mut explore)
990 .await
991 .expect("event for a new public repo");
992 assert!(listed.contains("event: changed"), "{listed}");
993
994 // The profile streams to anyone, and an unknown name is not found.
995 let mut profile = open_stream(&http, "/users/tahinli/events", None).await;
996 assert_eq!(profile.status().as_u16(), 200);
997 create_repo(&http, &tahinli, "tools", "public").await;
998 let changed = next_chunk(&mut profile)
999 .await
1000 .expect("event for a new repo of the profile");
1001 assert!(changed.contains("event: changed"), "{changed}");
1002 let missing = open_stream(&http, "/users/nobody/events", None).await;
1003 assert_eq!(missing.status().as_u16(), 404, "profile of an unknown user");
1004}