diff --git a/crates/forge-e2e/tests/e2e/account_mail_e2e.rs b/crates/forge-e2e/tests/e2e/account_mail_e2e.rs index 5098a49..f6e3f47 100644 --- a/crates/forge-e2e/tests/e2e/account_mail_e2e.rs +++ b/crates/forge-e2e/tests/e2e/account_mail_e2e.rs @@ -2,37 +2,18 @@ //! tests, this starts the real `forge` binary. The log transport writes each mail to //! `/mail-log/`, which is where the tests read the reset link from. -use crate::common::{Http, Resp, launch_with, pick_ports}; +use crate::common::{Http, Resp, cookie_named, input_value, launch_with, pick_ports}; use std::fs; use std::path::{Path, PathBuf}; use std::time::Duration; use forge_core::Store; use forge_core::password::hash_password; -use reqwest::header::SET_COOKIE; const LOG_TRANSPORT: &str = "\n[mail]\ntransport = \"log\"\n"; const OLD_PW: &str = "tahinli-old-password-1"; const NEW_PW: &str = "tahinli-new-password-2"; -/// The `name=value` pair of the Set-Cookie header whose name starts with `prefix`. -fn cookie_named(resp: &Resp, prefix: &str) -> Option { - resp.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok()) - .find(|raw| raw.starts_with(prefix)) - .map(|raw| raw.split(';').next().unwrap().to_owned()) -} - -/// The value of a hidden `` field. -fn input_value(html: &str, name: &str) -> String { - let marker = format!("name=\"{name}\" value=\""); - let start = html.find(&marker).unwrap_or_else(|| panic!("{name} field")) + marker.len(); - let end = html[start..].find('"').unwrap() + start; - html[start..end].to_owned() -} - /// Creates tahinli with a verified address. Bob has an address that is not verified. Runs before /// the server starts, like the other e2e tests. async fn seed(dir: &Path) { @@ -169,7 +150,7 @@ async fn reset_link_sets_a_new_password_once() { assert!(page.body.contains("Set a new password")); let cookie = cookie_named(&page, "__Host-forge_precsrf").expect("precsrf cookie"); - let precsrf = cookie.split_once('=').unwrap().1.to_owned(); + let precsrf = input_value(&page.body, "precsrf"); let form = [ ("precsrf", precsrf.as_str()), ("password", NEW_PW), diff --git a/crates/forge-e2e/tests/e2e/advisories_e2e.rs b/crates/forge-e2e/tests/e2e/advisories_e2e.rs index a05b676..7ecd336 100644 --- a/crates/forge-e2e/tests/e2e/advisories_e2e.rs +++ b/crates/forge-e2e/tests/e2e/advisories_e2e.rs @@ -9,7 +9,7 @@ //! - a reader without Write gets a 404 on the page. use crate::common::{ - Http, Resp, Server, bin, input_value, launch_with, login, pick_ports, tool_on_path, + Http, Resp, Server, input_value, launch_with, login, pick_ports, run_admin, tool_on_path, write_config_with, }; use std::fs; @@ -121,22 +121,6 @@ async fn boot() -> Booted { } } -fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { - let out = Command::new(bin()) - .arg("--config") - .arg(config) - .args(["admin", "create-user", username]) - .args(extra) - .env("FORGE_PASSWORD", password) - .output() - .expect("run admin create-user"); - assert!( - out.status.success(), - "create-user {username} failed:\n{}", - String::from_utf8_lossy(&out.stderr) - ); -} - async fn create_token(http: &Http, session: &str) -> String { let page = http.get_cookie("/settings/keys", session).await; assert_eq!(page.status, 200, "GET /settings/keys"); diff --git a/crates/forge-e2e/tests/e2e/branch_protection_e2e.rs b/crates/forge-e2e/tests/e2e/branch_protection_e2e.rs index 88a250d..cbf050c 100644 --- a/crates/forge-e2e/tests/e2e/branch_protection_e2e.rs +++ b/crates/forge-e2e/tests/e2e/branch_protection_e2e.rs @@ -3,7 +3,7 @@ //! while the server runs. Helpers mirror `git_e2e.rs`. use crate::common::{ - Http, Ports, Server, bin, describe, input_value, launch, login, pick_ports, relaunch, + Http, Ports, Server, describe, input_value, launch, login, pick_ports, relaunch, run_admin, tool_on_path, write_config, }; use std::fs; @@ -14,18 +14,6 @@ use forge_core::Store; const TAHINLI_PW: &str = "tahinli-password-123"; -fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { - let out = Command::new(bin()) - .arg("--config") - .arg(config) - .args(["admin", "create-user", username]) - .args(extra) - .env("FORGE_PASSWORD", password) - .output() - .expect("run admin create-user"); - ok(&out, &format!("create-user {username}")); -} - fn ok(out: &Output, what: &str) { assert!(out.status.success(), "{what} failed:\n{}", describe(out)); } @@ -233,10 +221,9 @@ async fn branch_protection_end_to_end() { }; let mut server = start_server(&ctx).await; - // Seed main, feature/x and release/1 with two commits on main. let url = format!( "http://tahinli:{token}@127.0.0.1:{}/tahinli/bp.git", - ctx.http.base.rsplit(':').next().expect("port") + ctx.ports.http ); let work = ctx.dir.join("work"); ok(&git(&ctx.dir, &["clone", &url, path_str(&work)]), "clone"); diff --git a/crates/forge-e2e/tests/e2e/browse_e2e.rs b/crates/forge-e2e/tests/e2e/browse_e2e.rs index 3e30798..3611b1e 100644 --- a/crates/forge-e2e/tests/e2e/browse_e2e.rs +++ b/crates/forge-e2e/tests/e2e/browse_e2e.rs @@ -5,7 +5,7 @@ //! Cookies are handled by hand, as in `git_e2e.rs`: the session cookie is `__Host-forge_session` //! with `Secure`, so a cookie jar would not send it over plain http. -use crate::common::{bin, describe, input_value, launch, pick_ports, tool_on_path, write_config}; +use crate::common::{boot_admin, describe, input_value, tool_on_path}; use std::fs; use std::path::Path; use std::process::{Command, Output}; @@ -147,18 +147,6 @@ fn assert_latest_bar(body: &str, what: &str, subject: &str, oid: &str, count: &s ); } -fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { - let out = Command::new(bin()) - .arg("--config") - .arg(config) - .args(["admin", "create-user", username]) - .args(extra) - .env("FORGE_PASSWORD", password) - .output() - .expect("run admin create-user"); - ok(&out, &format!("create-user {username}")); -} - fn ok(out: &Output, what: &str) { assert!(out.status.success(), "{what} failed:\n{}", describe(out)); } @@ -200,7 +188,6 @@ fn write_fixtures(work: &Path) { fs::write(work.join("src/main.rs"), "fn main() {}\n").expect("write main.rs"); fs::write(work.join("img.png"), PNG).expect("write img.png"); fs::write(work.join("evil.html"), "\n").expect("write evil.html"); - // A Git LFS pointer whose object is not stored, so the blob page says so. fs::write( work.join("weights.bin"), "version https://git-lfs.github.com/spec/v1\noid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\nsize 1234\n", @@ -334,30 +321,17 @@ async fn browse_end_to_end() { return; } - // Keep the path short, as in git_e2e.rs. - let root = tempfile::Builder::new() - .prefix("fbrw") - .tempdir_in("/tmp") - .expect("temp dir"); + let (root, _server, ports) = boot_admin("fbrw", TAHINLI_PW).await; let dir = root.path().to_path_buf(); - - let ports = pick_ports(); - let config = write_config(&dir, ports); - - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); - - let (_server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); let raw = Http::new(ports.content); let raw_base = raw.base.clone(); - // Setup: tahinli logs in, makes a token and creates one public and one private repo. let tahinli = login(&http, "tahinli", TAHINLI_PW).await; let token = create_token(&http, &tahinli, "browse-token").await; create_repo(&http, &tahinli, "pub", "public").await; create_repo(&http, &tahinli, "priv", "private").await; - // Push the same fixtures to both repos over HTTPS with the token. let pub_url = format!( "http://tahinli:{token}@127.0.0.1:{}/tahinli/pub.git", ports.http @@ -369,7 +343,6 @@ async fn browse_end_to_end() { let pub_main = push_fixtures(&dir, &pub_url, &dir.join("pub-work")); push_fixtures(&dir, &priv_url, &dir.join("priv-work")); - // A branch named `media` in the public repo, with its own README.md. let pub_work = dir.join("pub-work"); ok( &git( @@ -382,7 +355,6 @@ async fn browse_end_to_end() { commit_all(&pub_work, "media branch"); ok(&git(&pub_work, &["push", "origin", "media"]), "push media"); - // App origin, anonymous, public repo. let home = http.get("/tahinli/pub", None).await; assert_eq!(home.status, 200, "anonymous home of public repo"); let csp = home @@ -420,7 +392,6 @@ async fn browse_end_to_end() { "README image must point at the raw origin: {image_srcs:?}" ); - // Latest commit bar: the root has one commit on main, so its subject, short sha and count. assert_latest_bar( &home_body, "repo home", @@ -494,7 +465,6 @@ async fn browse_end_to_end() { feature_tree.body().contains("feature.txt"), "feature/x tree must list feature.txt" ); - // The feature commit is the newest on feature/x, on top of the two-commit history. assert_latest_bar( &feature_tree.body(), "tree of feature/x", @@ -510,7 +480,6 @@ async fn browse_end_to_end() { "archive must start with gzip magic bytes" ); - // App origin, private repo: anonymous gets 404 everywhere. for path in [ "/tahinli/priv", "/tahinli/priv/tree/main/src", @@ -520,7 +489,6 @@ async fn browse_end_to_end() { assert_eq!(res.status, 404, "anonymous {path} on private repo"); } - // Logged in, the image blob page carries a signed raw URL. let priv_img = http .get("/tahinli/priv/blob/main/img.png", Some(&tahinli)) .await; @@ -534,11 +502,9 @@ async fn browse_end_to_end() { "signed raw URL shape: {priv_img_src}" ); - // Raw origin: the media route 404s when the repo does not link the object. let media = raw.get("/tahinli/pub/-/media/main/weights.bin", None).await; assert_eq!(media.status, 404, "media of an unstored LFS object"); - // Raw origin: a branch named `media` is an ordinary raw path, not the media route. let media_branch = raw.get("/tahinli/pub/media/README.md", None).await; assert_eq!( media_branch.status, 200, @@ -546,11 +512,9 @@ async fn browse_end_to_end() { ); assert_eq!(media_branch.body(), "# On a media branch\n"); - // Raw origin: `-` is never a ref name, so it is a 404 and not resolved. let dash = raw.get("/tahinli/pub/-/README.md", None).await; assert_eq!(dash.status, 404, "raw path with a `-` ref"); - // Raw origin: public file. let main_rs = raw.get("/tahinli/pub/main/src/main.rs", None).await; assert_eq!(main_rs.status, 200, "raw public main.rs"); assert_eq!( @@ -570,7 +534,6 @@ async fn browse_end_to_end() { ); assert_no_cookie(&main_rs, "raw public main.rs"); - // Raw origin: HTML is served as a download, never inline. let evil = raw.get("/tahinli/pub/main/evil.html", None).await; assert_eq!(evil.status, 200, "raw evil.html"); assert!( @@ -580,13 +543,11 @@ async fn browse_end_to_end() { ); assert_no_cookie(&evil, "raw evil.html"); - // Raw origin: images keep their image type. let img = raw.get("/tahinli/pub/main/img.png", None).await; assert_eq!(img.status, 200, "raw img.png"); assert_eq!(img.header(CONTENT_TYPE).as_deref(), Some("image/png")); assert_no_cookie(&img, "raw img.png"); - // Raw origin: private repo needs a valid token. let priv_no_token = raw.get("/tahinli/priv/main/img.png", None).await; assert_eq!(priv_no_token.status, 404, "private raw without token"); assert_no_cookie(&priv_no_token, "raw private without token"); @@ -598,8 +559,6 @@ async fn browse_end_to_end() { assert_eq!(priv_ok.status, 200, "private raw with the scraped token"); assert_no_cookie(&priv_ok, "raw private with token"); - // Tampering with the signature (its first character) must fail. The first base64 character - // carries six significant bits, so flipping it always changes the signature. let (file_part, query) = priv_path.split_once("?token=").expect("token query"); let (expires, sig) = query.split_once('.').expect("token shape"); let flipped = if sig.starts_with('A') { 'B' } else { 'A' }; @@ -607,10 +566,12 @@ async fn browse_end_to_end() { let tampered = raw .get(&format!("{file_part}?token={expires}.{tampered_sig}"), None) .await; - assert_eq!(tampered.status, 404, "tampered token must be rejected"); + assert_eq!( + tampered.status, 404, + "tampered token must be rejected: the first base64 char carries six bits, so the flip always changes the signature" + ); assert_no_cookie(&tampered, "raw tampered token"); - // Raw origin has no app routes. let login_page = raw.get("/login", None).await; assert_eq!( login_page.status, 404, @@ -626,7 +587,6 @@ async fn open_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest:: req = req.header(COOKIE, cookie); } let mut res = req.send().await.expect("stream request"); - // A stream that opens sends its `retry` field first. It is not an event, so it is read here. if res.status().is_success() { let retry = next_chunk(&mut res).await.expect("the retry field"); assert!(retry.contains("retry: 1000"), "{retry}"); @@ -650,15 +610,8 @@ async fn code_view_stream_follows_pushes() { return; } - let root = tempfile::Builder::new() - .prefix("fliv") - .tempdir_in("/tmp") - .expect("temp dir"); + let (root, _server, ports) = boot_admin("fliv", TAHINLI_PW).await; let dir = root.path().to_path_buf(); - let ports = pick_ports(); - let config = write_config(&dir, ports); - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); - let (_server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); let tahinli = login(&http, "tahinli", TAHINLI_PW).await; @@ -677,7 +630,6 @@ async fn code_view_stream_follows_pushes() { push_fixtures(&dir, &priv_url, &dir.join("priv-live")); let work = dir.join("pub-live"); - // The branch page follows its branch. A commit page does not, since a commit never moves. let branch_page = http.get("/tahinli/pub/tree/main/", None).await; assert_eq!(branch_page.status, 200); assert!( @@ -701,7 +653,6 @@ async fn code_view_stream_follows_pushes() { "a commit page does not follow a branch" ); - // Anyone can follow a public branch. let mut stream = open_stream(&http, "/tahinli/pub/events?ref_name=main", None).await; assert_eq!(stream.status().as_u16(), 200); assert_eq!( @@ -709,7 +660,6 @@ async fn code_view_stream_follows_pushes() { "text/event-stream" ); - // A push to another branch sends nothing: main did not move and no ref was created. ok( &git(&work, &["checkout", "-q", "feature/x"]), "checkout feature/x", @@ -722,7 +672,6 @@ async fn code_view_stream_follows_pushes() { ); assert!(next_chunk(&mut stream).await.is_none(), "other branch sent"); - // A push to main sends one `changed` event. ok(&git(&work, &["checkout", "-q", "main"]), "checkout main"); fs::write(work.join("README.md"), "# Live\n\nChanged by a push.\n").expect("write README"); commit_all(&work, "change the README"); @@ -730,7 +679,6 @@ async fn code_view_stream_follows_pushes() { let event = next_chunk(&mut stream).await.expect("event for main"); assert!(event.contains("event: changed"), "{event}"); - // Creating and deleting a branch changes the branch list, so the page follows it too. ok( &git(&work, &["checkout", "-q", "-b", "topic"]), "create topic", @@ -752,7 +700,6 @@ async fn code_view_stream_follows_pushes() { .expect("event for a deleted branch"); assert!(deleted.contains("event: changed"), "{deleted}"); - // A private repo streams only to a viewer who can read it. let private = "/tahinli/priv/events?ref_name=main"; let anonymous = open_stream(&http, private, None).await; assert_eq!( @@ -789,22 +736,13 @@ async fn issue_streams_follow_writes() { return; } - let root = tempfile::Builder::new() - .prefix("filive") - .tempdir_in("/tmp") - .expect("temp dir"); - let dir = root.path().to_path_buf(); - let ports = pick_ports(); - let config = write_config(&dir, ports); - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); - let (_server, ports) = launch(&dir, ports).await; + let (_root, _server, ports) = boot_admin("filive", TAHINLI_PW).await; let http = Http::new(ports.http); let tahinli = login(&http, "tahinli", TAHINLI_PW).await; create_repo(&http, &tahinli, "pub", "public").await; create_repo(&http, &tahinli, "priv", "private").await; - // The list follows the repo's issues. Anyone can follow a public repo. let list_page = http.get("/tahinli/pub/issues", None).await; assert!( list_page @@ -815,7 +753,6 @@ async fn issue_streams_follow_writes() { let mut list = open_stream(&http, "/tahinli/pub/issues/live", None).await; assert_eq!(list.status().as_u16(), 200); - // Creating an issue wakes the list. let new_page = http.get("/tahinli/pub/issues/new", Some(&tahinli)).await; let csrf = input_value(&new_page.body(), "csrf"); post_redirect( @@ -827,7 +764,6 @@ async fn issue_streams_follow_writes() { .await; assert_changed(&mut list, "creating an issue").await; - // The issue page follows the issue, and the list stays subscribed to the repo's issues. let mut issue = open_stream(&http, "/tahinli/pub/issues/1/live", None).await; assert_eq!(issue.status().as_u16(), 200); let view = http.get("/tahinli/pub/issues/1", Some(&tahinli)).await; @@ -900,7 +836,6 @@ async fn issue_streams_follow_writes() { assert_changed(&mut issue, what).await; } - // A private repo streams only to a viewer who can read it. let anonymous = open_stream(&http, "/tahinli/priv/issues/live", None).await; assert_eq!( anonymous.status().as_u16(), @@ -924,15 +859,8 @@ async fn browsing_pages_stream_their_changes() { return; } - let root = tempfile::Builder::new() - .prefix("flive") - .tempdir_in("/tmp") - .expect("temp dir"); + let (root, _server, ports) = boot_admin("flive", TAHINLI_PW).await; let dir = root.path().to_path_buf(); - let ports = pick_ports(); - let config = write_config(&dir, ports); - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); - let (_server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); let tahinli = login(&http, "tahinli", TAHINLI_PW).await; @@ -944,8 +872,6 @@ async fn browsing_pages_stream_their_changes() { ); let pushed = push_fixtures(&dir, &pub_url, &dir.join("pub-pages")); - // The inbox needs a session. Without one it refuses, and no URL names another user's inbox: - // the viewer always comes from the session. for path in [ "/notifications/events", "/notifications/events?all=1&user=tahinli", @@ -956,7 +882,6 @@ async fn browsing_pages_stream_their_changes() { let inbox = open_stream(&http, "/notifications/events", Some(tahinli.as_str())).await; assert_eq!(inbox.status().as_u16(), 200, "inbox stream for its owner"); - // The header of a public repo streams to anyone. A star moves its count for every viewer. let mut header = open_stream(&http, "/tahinli/pub/events", None).await; assert_eq!(header.status().as_u16(), 200); let page = http.get("/tahinli/pub", Some(&tahinli)).await; @@ -973,16 +898,13 @@ async fn browsing_pages_stream_their_changes() { "the header shows the star" ); - // A second push moves main. let work = dir.join("pub-pages"); - // push_fixtures leaves the clone on feature/x, so the new commit must go on main. ok(&git(&work, &["checkout", "-q", "main"]), "checkout main"); fs::write(work.join("PUSH.txt"), "pushed again\n").expect("write PUSH.txt"); commit_all(&work, "a second push"); ok(&git(&work, &["push", "-q", "origin", "main"]), "push main"); assert_ne!(pushed, head_sha(&work), "the second push moved main"); - // The explore listing streams to anyone, and a new public repo changes it. let mut explore = open_stream(&http, "/explore/events", None).await; assert_eq!(explore.status().as_u16(), 200); create_repo(&http, &tahinli, "lib", "public").await; @@ -991,7 +913,6 @@ async fn browsing_pages_stream_their_changes() { .expect("event for a new public repo"); assert!(listed.contains("event: changed"), "{listed}"); - // The profile streams to anyone, and an unknown name is not found. let mut profile = open_stream(&http, "/users/tahinli/events", None).await; assert_eq!(profile.status().as_u16(), 200); create_repo(&http, &tahinli, "tools", "public").await; diff --git a/crates/forge-e2e/tests/e2e/ci_e2e.rs b/crates/forge-e2e/tests/e2e/ci_e2e.rs index c32e335..5fdaf4b 100644 --- a/crates/forge-e2e/tests/e2e/ci_e2e.rs +++ b/crates/forge-e2e/tests/e2e/ci_e2e.rs @@ -11,7 +11,7 @@ //! - a live log: `log.txt` streams while a job runs and ends when the job finishes. use crate::common::{ - FAST_CLAIMS, Http, Server, bin, input_value, launch_with, login, pick_ports, write_config, + FAST_CLAIMS, Http, Server, input_value, launch_with, login, pick_ports, run_admin, write_config, }; use forge_ci::proto::{JobAssignment, Outcome, RegisterRequest}; use forge_runner::client::ForgeClient; @@ -21,7 +21,7 @@ use forge_runner::runner::{RunOptions, Runner}; use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; +use std::process::Command; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio_util::sync::CancellationToken; @@ -103,26 +103,6 @@ fn first_text(body: &str, selector: &str) -> String { .to_owned() } -fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { - let out = Command::new(bin()) - .arg("--config") - .arg(config) - .args(["admin", "create-user", username]) - .args(extra) - .env("FORGE_PASSWORD", password) - .output() - .expect("run admin create-user"); - ok(&out, &format!("create-user {username}")); -} - -fn ok(out: &Output, what: &str) { - assert!( - out.status.success(), - "{what} failed:\n{}", - String::from_utf8_lossy(&out.stderr) - ); -} - /// Runs git in `cwd` with `env` applied on top of the inherited environment. Returns stdout. fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String { let mut cmd = Command::new("git"); diff --git a/crates/forge-e2e/tests/e2e/common/http.rs b/crates/forge-e2e/tests/e2e/common/http.rs index 2c0cf03..4147198 100644 --- a/crates/forge-e2e/tests/e2e/common/http.rs +++ b/crates/forge-e2e/tests/e2e/common/http.rs @@ -153,6 +153,11 @@ pub fn cookie_named(resp: &Resp, suffix: &str) -> Option { }) } +pub fn with_cookie(session: &str, res: &Resp, notice: &str) -> String { + let cookie = cookie_named(res, notice).expect("notice cookie"); + format!("{session}; {cookie}") +} + /// Signs in as `username` through the `/login` form and returns the session cookie. pub async fn login(http: &Http, username: &str, password: &str) -> String { let page = http.get("/login", None).await; diff --git a/crates/forge-e2e/tests/e2e/common/mod.rs b/crates/forge-e2e/tests/e2e/common/mod.rs index 06e8b13..f5b56d5 100644 --- a/crates/forge-e2e/tests/e2e/common/mod.rs +++ b/crates/forge-e2e/tests/e2e/common/mod.rs @@ -1,14 +1,11 @@ //! Helpers shared by the forge-web e2e tests. `main.rs` declares this module once, and each test -//! module imports what it needs from `crate::common`. Items a given test does not use are allowed -//! to be dead code. +//! module imports what it needs from `crate::common`. //! //! The server is started with `launch`, which waits for the three listeners (HTTP, user content //! and SSH) with backoff. A connection that is refused just means "not yet". If the child exits //! first, the panic carries its captured log. A port picked with `pick_ports` is only free until //! the server binds it, so `launch` retries on fresh ports when the server reports a bind conflict. -#![allow(dead_code)] - use std::fs; use std::net::TcpStream; use std::path::{Path, PathBuf}; @@ -16,9 +13,11 @@ use std::process::{Child, Command, ExitStatus, Output, Stdio}; use std::sync::OnceLock; use std::time::{Duration, Instant}; +use tempfile::TempDir; + mod http; -pub use http::{Http, Resp, cookie_named, login}; +pub use http::{Http, Resp, cookie_named, login, with_cookie}; /// The forge binary the tests start. `env!("CARGO_BIN_EXE_forge")` would only work in the package /// that owns the binary, and these tests live in `forge-e2e`, which does not depend on forge-web. @@ -97,6 +96,13 @@ pub fn input_value(body: &str, name: &str) -> String { .to_owned() } +pub fn temp_dir(prefix: &str) -> tempfile::TempDir { + tempfile::Builder::new() + .prefix(prefix) + .tempdir_in("/tmp") + .expect("temp dir") +} + /// A port the kernel handed out for a moment. It is free only until something binds it. pub fn free_port() -> u16 { std::net::TcpListener::bind("127.0.0.1:0") @@ -167,6 +173,98 @@ pub fn write_config_with(dir: &Path, ports: Ports, extra: &str) -> PathBuf { /// before it answers 204, and the production default is 25 s, so the test server answers at once. pub const FAST_CLAIMS: &str = "[ci]\nclaim_wait_ms = 50\n"; +pub fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output { + let mut cmd = Command::new("git"); + cmd.current_dir(cwd) + .args(["-c", "credential.helper="]) + .args(args) + .env("GIT_TERMINAL_PROMPT", "0"); + for (key, value) in env { + cmd.env(key, value); + } + cmd.output().expect("run git") +} + +/// Creates an access token through `/settings/tokens` and returns the token shown once. +pub async fn create_token(http: &Http, session: &str, name: &str) -> String { + let page = http.get_cookie("/settings/keys", session).await; + assert_eq!(page.status, 200, "GET /settings/keys"); + let csrf = input_value(&page.body, "csrf"); + let res = http + .post_form( + "/settings/tokens", + &[("csrf", &csrf), ("name", name), ("expires", "30")], + Some(session), + ) + .await; + assert_eq!(res.status, 200, "create token: {}", res.body); + let doc = scraper::Html::parse_document(&res.body); + let selector = scraper::Selector::parse("pre.code code").expect("selector"); + let token: String = doc + .select(&selector) + .next() + .expect("token shown after creation") + .text() + .collect(); + let token = token.trim().to_owned(); + assert!(token.starts_with("forge_"), "unexpected token shape"); + token +} + +/// Creates a repo through `/new`. +pub async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) { + let page = http.get_cookie("/new", session).await; + assert_eq!(page.status, 200, "GET /new"); + let csrf = input_value(&page.body, "csrf"); + let res = http + .post_form( + "/new", + &[ + ("csrf", &csrf), + ("name", name), + ("description", ""), + ("visibility", visibility), + ("default_branch", "main"), + ], + Some(session), + ) + .await; + assert_eq!(res.status, 303, "create repo {name}: {}", res.body); + assert_eq!( + res.location().as_deref(), + Some(format!("/tahinli/{name}").as_str()) + ); +} + +pub const PW: &str = "tahinli-password-123"; + +pub fn admin(config: &Path, args: &[&str]) { + let out = Command::new(bin()) + .arg("--config") + .arg(config) + .arg("admin") + .args(args) + .env("FORGE_PASSWORD", PW) + .output() + .expect("run admin command"); + assert!( + out.status.success(), + "admin {args:?} failed:\n{}", + describe(&out) + ); +} + +pub fn init_bare(data_dir: &Path, repo_id: &str) { + let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path"); + fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent"); + let out = Command::new("git") + .args(["init", "--bare", "--quiet", "--initial-branch=main"]) + .arg(&path) + .output() + .expect("run git init"); + assert!(out.status.success(), "git init --bare: {}", describe(&out)); +} + pub fn describe(out: &Output) -> String { format!( "status: {}\nstdout: {}\nstderr: {}", @@ -176,6 +274,47 @@ pub fn describe(out: &Output) -> String { ) } +/// Waits for the next event of a stream, which must be `changed`. +pub async fn next_changed(res: &mut reqwest::Response, what: &str) { + let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk()) + .await + .unwrap_or_else(|_| panic!("no event after {what}")) + .expect("stream chunk") + .expect("stream still open"); + let text = String::from_utf8_lossy(&chunk); + assert!(text.contains("event: changed"), "{what}: {text}"); +} + +pub fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { + let out = Command::new(bin()) + .arg("--config") + .arg(config) + .args(["admin", "create-user", username]) + .args(extra) + .env("FORGE_PASSWORD", password) + .output() + .expect("run admin create-user"); + assert!( + out.status.success(), + "create-user {username} failed:\n{}", + describe(&out) + ); +} + +/// A fresh server with `tahinli` as its only user, an admin. The temp dir is under `/tmp` so the +/// socket paths stay under the 108-byte unix limit. Returns the dir, the server and its ports. +pub async fn boot_admin(prefix: &str, password: &str) -> (TempDir, Server, Ports) { + let root = tempfile::Builder::new() + .prefix(prefix) + .tempdir_in("/tmp") + .expect("temp dir"); + let ports = pick_ports(); + let config = write_config(root.path(), ports); + run_admin(&config, "tahinli", &["--admin"], password); + let (server, ports) = launch(root.path(), ports).await; + (root, server, ports) +} + /// Starts `forge serve` on `ports` and returns once all three listeners answer. The config is /// written to `dir/forge.toml` and the log to `dir/serve.log`. /// diff --git a/crates/forge-e2e/tests/e2e/discussions_e2e.rs b/crates/forge-e2e/tests/e2e/discussions_e2e.rs index 67ea2dd..4372eb9 100644 --- a/crates/forge-e2e/tests/e2e/discussions_e2e.rs +++ b/crates/forge-e2e/tests/e2e/discussions_e2e.rs @@ -4,30 +4,12 @@ //! owner can still write. use crate::common::{ - Http, bin, input_value, launch, login, pick_ports, tool_on_path, write_config, + Http, input_value, launch, login, pick_ports, run_admin, tool_on_path, write_config, }; -use std::path::Path; -use std::process::Command; const TAHINLI_PW: &str = "tahinli-password-123"; const BOB_PW: &str = "bob-password-4567"; -fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { - let out = Command::new(bin()) - .arg("--config") - .arg(config) - .args(["admin", "create-user", username]) - .args(extra) - .env("FORGE_PASSWORD", password) - .output() - .expect("run admin create-user"); - assert!( - out.status.success(), - "create-user {username} failed:\n{}", - String::from_utf8_lossy(&out.stderr) - ); -} - /// Creates a public repo through `/new`. async fn create_repo(http: &Http, session: &str, name: &str) { let page = http.get("/new", Some(session)).await; diff --git a/crates/forge-e2e/tests/e2e/git_e2e.rs b/crates/forge-e2e/tests/e2e/git_e2e.rs index 235bc8d..18edc86 100644 --- a/crates/forge-e2e/tests/e2e/git_e2e.rs +++ b/crates/forge-e2e/tests/e2e/git_e2e.rs @@ -5,7 +5,8 @@ //! cookie jar would not send it over plain http. The test parses `Set-Cookie` and sends `Cookie`. use crate::common::{ - Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config, + Http, create_repo, create_token, describe, git, input_value, launch, login, pick_ports, + run_admin, tool_on_path, write_config, }; use std::fs; use std::path::{Path, PathBuf}; @@ -16,18 +17,6 @@ use reqwest::header::WWW_AUTHENTICATE; const TAHINLI_PW: &str = "tahinli-password-123"; const BOB_PW: &str = "bob-password-4567"; -fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { - let out = Command::new(bin()) - .arg("--config") - .arg(config) - .args(["admin", "create-user", username]) - .args(extra) - .env("FORGE_PASSWORD", password) - .output() - .expect("run admin create-user"); - ok(&out, &format!("create-user {username}")); -} - fn ok(out: &Output, what: &str) { assert!(out.status.success(), "{what} failed:\n{}", describe(out)); } @@ -42,18 +31,6 @@ fn rejected(out: &Output, what: &str) -> String { describe(out) } -fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output { - let mut cmd = Command::new("git"); - cmd.current_dir(cwd) - .args(["-c", "credential.helper="]) - .args(args) - .env("GIT_TERMINAL_PROMPT", "0"); - for (key, value) in env { - cmd.env(key, value); - } - cmd.output().expect("run git") -} - fn path_str(path: &Path) -> &str { path.to_str().expect("utf-8 path") } @@ -140,32 +117,6 @@ fn read(path: PathBuf) -> String { fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())) } -/// Creates an access token through `/settings/tokens` and returns the token shown once. -async fn create_token(http: &Http, session: &str, name: &str) -> String { - let page = http.get_cookie("/settings/keys", session).await; - assert_eq!(page.status, 200, "GET /settings/keys"); - let csrf = input_value(&page.body, "csrf"); - let res = http - .post_form( - "/settings/tokens", - &[("csrf", &csrf), ("name", name), ("expires", "30")], - Some(session), - ) - .await; - assert_eq!(res.status, 200, "create token: {}", res.body); - let doc = scraper::Html::parse_document(&res.body); - let selector = scraper::Selector::parse("pre.code code").expect("selector"); - let token: String = doc - .select(&selector) - .next() - .expect("token shown after creation") - .text() - .collect(); - let token = token.trim().to_owned(); - assert!(token.starts_with("forge_"), "unexpected token shape"); - token -} - /// Adds a public key through `/settings/keys`. async fn add_key(http: &Http, session: &str, public_key: &str) { let page = http.get_cookie("/settings/keys", session).await; @@ -185,31 +136,6 @@ async fn add_key(http: &Http, session: &str, public_key: &str) { assert_eq!(res.status, 303, "add SSH key: {}", res.body); } -/// Creates a repo through `/new`. -async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) { - let page = http.get_cookie("/new", session).await; - assert_eq!(page.status, 200, "GET /new"); - let csrf = input_value(&page.body, "csrf"); - let res = http - .post_form( - "/new", - &[ - ("csrf", &csrf), - ("name", name), - ("description", ""), - ("visibility", visibility), - ("default_branch", "main"), - ], - Some(session), - ) - .await; - assert_eq!(res.status, 303, "create repo {name}: {}", res.body); - assert_eq!( - res.location().as_deref(), - Some(format!("/tahinli/{name}").as_str()) - ); -} - #[tokio::test] async fn git_end_to_end() { for tool in ["git", "ssh", "ssh-keygen"] { diff --git a/crates/forge-e2e/tests/e2e/i18n_e2e.rs b/crates/forge-e2e/tests/e2e/i18n_e2e.rs index c5d055e..80b777c 100644 --- a/crates/forge-e2e/tests/e2e/i18n_e2e.rs +++ b/crates/forge-e2e/tests/e2e/i18n_e2e.rs @@ -1,7 +1,7 @@ //! End-to-end checks for the interface language. Anonymous pages follow `Accept-Language`; a //! signed-in user's stored language beats the browser; `` matches the language used. -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::Command; use crate::common::{ @@ -38,7 +38,7 @@ struct Env { /// Creates tahinli, then runs `seed` against the store before the server starts. async fn start(seed: F) -> Env where - F: FnOnce(PathBuf, Store) -> Fut, + F: FnOnce(Store) -> Fut, Fut: std::future::Future, { let root = tempfile::tempdir().expect("temp dir"); @@ -49,7 +49,7 @@ where let store = Store::open(&dir.join("forge.db")) .await .expect("open store"); - seed(dir.clone(), store).await; + seed(store).await; let (server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); Env { @@ -61,7 +61,7 @@ where #[tokio::test] async fn anonymous_pages_follow_the_browser_language() { - let env = start(|_, _| async {}).await; + let env = start(|_| async {}).await; let turkish = env .http @@ -101,7 +101,7 @@ async fn anonymous_pages_follow_the_browser_language() { #[tokio::test] async fn stored_language_beats_the_browser_for_a_signed_in_user() { - let env = start(|_, store| async move { + let env = start(|store| async move { let tahinli = store .user_by_username("tahinli") .await @@ -128,7 +128,7 @@ async fn stored_language_beats_the_browser_for_a_signed_in_user() { #[tokio::test] async fn releases_page_follows_the_stored_turkish_language() { - let env = start(|_, store| async move { + let env = start(|store| async move { let tahinli = store .user_by_username("tahinli") .await diff --git a/crates/forge-e2e/tests/e2e/issue_close_e2e.rs b/crates/forge-e2e/tests/e2e/issue_close_e2e.rs index 7b786e6..bca14b3 100644 --- a/crates/forge-e2e/tests/e2e/issue_close_e2e.rs +++ b/crates/forge-e2e/tests/e2e/issue_close_e2e.rs @@ -4,7 +4,8 @@ //! file, and every push is a real `git push` through the git HTTP endpoints. use crate::common::{ - Http, bin, input_value, launch, login, pick_ports, relaunch, tool_on_path, write_config, + Http, input_value, launch, login, pick_ports, relaunch, run_admin, tool_on_path, + write_config, }; use std::fs; use std::future::Future; @@ -17,22 +18,6 @@ use forge_core::Store; const TAHINLI_PW: &str = "tahinli-password-123"; const BOB_PW: &str = "bob-password-4567"; -fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { - let out = Command::new(bin()) - .arg("--config") - .arg(config) - .args(["admin", "create-user", username]) - .args(extra) - .env("FORGE_PASSWORD", password) - .output() - .expect("run admin create-user"); - assert!( - out.status.success(), - "create-user {username} failed:\n{}", - String::from_utf8_lossy(&out.stderr) - ); -} - /// Runs git with credential helpers disabled and returns stdout, trimmed. Panics on failure. fn git(cwd: &Path, args: &[&str]) -> String { let out = git_output(cwd, args, &[]); diff --git a/crates/forge-e2e/tests/e2e/lfs_e2e.rs b/crates/forge-e2e/tests/e2e/lfs_e2e.rs index 9c627a6..6e259f7 100644 --- a/crates/forge-e2e/tests/e2e/lfs_e2e.rs +++ b/crates/forge-e2e/tests/e2e/lfs_e2e.rs @@ -5,7 +5,7 @@ //! Git config is isolated from the developer's machine: `HOME` and `GIT_CONFIG_GLOBAL` point into //! the test's temp dir. -use crate::common::{Http, bin, describe, input_value, launch, login, pick_ports, write_config}; +use crate::common::{Http, describe, input_value, launch, login, pick_ports, run_admin, write_config}; use std::fs; use std::path::Path; use std::process::{Command, Output}; @@ -13,18 +13,6 @@ use std::process::{Command, Output}; const TAHINLI_PW: &str = "tahinli-password-123"; const FILE_SIZE: usize = 100 * 1024; -fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { - let out = Command::new(bin()) - .arg("--config") - .arg(config) - .args(["admin", "create-user", username]) - .args(extra) - .env("FORGE_PASSWORD", password) - .output() - .expect("run admin create-user"); - ok(&out, &format!("create-user {username}")); -} - fn ok(out: &Output, what: &str) { assert!(out.status.success(), "{what} failed:\n{}", describe(out)); } diff --git a/crates/forge-e2e/tests/e2e/merge_queue_e2e.rs b/crates/forge-e2e/tests/e2e/merge_queue_e2e.rs index e318796..03a63b8 100644 --- a/crates/forge-e2e/tests/e2e/merge_queue_e2e.rs +++ b/crates/forge-e2e/tests/e2e/merge_queue_e2e.rs @@ -1,17 +1,6 @@ -//! End-to-end: the merge queue on a protected branch, against the real `forge` binary and the -//! real `forge-runner` library (see `ci_e2e.rs` for the harness). -//! -//! Scenarios: -//! - two pull requests queue; the first lands on a tested candidate, the second is removed with -//! a comment linking its failing run, and `main` only ever holds the tested commit; -//! - a new commit on a queued pull request's head removes it from the queue. - -// The harness helpers are the same ones `ci_e2e.rs` uses. This file uses a subset of them. -#![allow(dead_code)] - use crate::common::{ - FAST_CLAIMS, Http, Server, bin, input_value, launch_with, login, pick_ports, tool_on_path, - write_config, + FAST_CLAIMS, Http, Server, input_value, launch_with, login, pick_ports, run_admin, + tool_on_path, write_config, }; use forge_ci::proto::{JobAssignment, RegisterRequest}; use forge_runner::client::ForgeClient; @@ -21,18 +10,15 @@ use forge_runner::runner::{RunOptions, Runner}; use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; +use std::process::Command; use std::sync::Arc; -use std::time::{Duration, Instant}; use tokio_util::sync::CancellationToken; const TAHINLI_PW: &str = "tahinli-password-123"; const BOB_PW: &str = "bob-password-4567"; -const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1"; const REPO_PATH: &str = "/tahinli/r"; const LABELS: &[&str] = &["linux"]; -/// The text of the first element matching `selector`. fn first_text(body: &str, selector: &str) -> String { let doc = scraper::Html::parse_document(body); let selector = scraper::Selector::parse(selector).expect("selector"); @@ -45,27 +31,6 @@ fn first_text(body: &str, selector: &str) -> String { .to_owned() } -fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { - let out = Command::new(bin()) - .arg("--config") - .arg(config) - .args(["admin", "create-user", username]) - .args(extra) - .env("FORGE_PASSWORD", password) - .output() - .expect("run admin create-user"); - ok(&out, &format!("create-user {username}")); -} - -fn ok(out: &Output, what: &str) { - assert!( - out.status.success(), - "{what} failed:\n{}", - String::from_utf8_lossy(&out.stderr) - ); -} - -/// Runs git in `cwd` with `env` applied on top of the inherited environment. Returns stdout. fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String { let mut cmd = Command::new("git"); cmd.current_dir(cwd) @@ -88,8 +53,6 @@ fn git(cwd: &Path, args: &[&str]) -> String { git_env(cwd, args, &[]) } -/// Writes `file` (creating its directory), commits it with `who` as author and committer, and -/// returns the new HEAD. fn commit( repo: &Path, file: &str, @@ -117,7 +80,6 @@ fn commit( git(repo, &["rev-parse", "HEAD"]) } -/// Clones `url` into `into` (a path that does not exist yet) and returns it. fn clone(url: &str, into: &Path) -> PathBuf { let parent = into.parent().expect("clone target has a parent"); git( @@ -127,19 +89,16 @@ fn clone(url: &str, into: &Path) -> PathBuf { into.to_path_buf() } -/// The HTTPS remote for `owner/repo`, authenticated with a token. fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String { format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git") } -/// The CSRF token shown on any settings page of the signed-in user. async fn csrf_from(http: &Http, path: &str, session: &str) -> String { let page = http.get(path, Some(session)).await; assert_eq!(page.status, 200, "GET {path}"); input_value(&page.body, "csrf") } -/// Creates an access token through `/settings/tokens` and returns the token shown once. async fn create_token(http: &Http, session: &str, name: &str) -> String { let csrf = csrf_from(http, "/settings/keys", session).await; let res = http @@ -155,7 +114,6 @@ async fn create_token(http: &Http, session: &str, name: &str) -> String { token } -/// Creates a public repo `name` owned by tahinli through `/new`. async fn create_repo(http: &Http, session: &str, name: &str) { let page = http.get("/new", Some(session)).await; assert_eq!(page.status, 200, "GET /new"); @@ -180,21 +138,6 @@ async fn create_repo(http: &Http, session: &str, name: &str) { ); } -/// Adds or replaces a repo secret through the settings form. -async fn set_secret(http: &Http, session: &str, name: &str, value: &str) { - let csrf = csrf_from(http, &format!("{REPO_PATH}/settings/secrets"), session).await; - let res = http - .post_form( - &format!("{REPO_PATH}/settings/secrets"), - &[("csrf", &csrf), ("name", name), ("value", value)], - Some(session), - ) - .await; - assert_eq!(res.status, 303, "set secret {name}: {}", res.body); -} - -/// A running server with its own temp data dir. Field order matters: the server is dropped (and -/// killed) before the temp dir is removed. struct Booted { _server: Server, _root: tempfile::TempDir, @@ -204,14 +147,11 @@ struct Booted { port: u16, } -/// The server's log, for assertion messages. fn server_log(b: &Booted) -> String { fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default() } -/// Creates tahinli (admin) and bob, then boots the server on fresh ports. async fn boot() -> Booted { - // Keep the path short: the internal unix socket path is limited to 108 bytes. let root = tempfile::Builder::new() .prefix("ci2e") .tempdir_in("/tmp") @@ -233,7 +173,6 @@ async fn boot() -> Booted { } } -/// A registered runner and the secret it claims with. struct Worker { runner: Runner, secret: String, @@ -241,7 +180,6 @@ struct Worker { } impl Worker { - /// One claim. `None` means the forge had nothing for this runner (after its long poll). async fn claim(&self) -> Option { self.runner .client() @@ -251,7 +189,6 @@ impl Worker { .job } - /// Claims and runs jobs until the forge has nothing left. Returns how many ran. async fn drain(&self) -> usize { let mut ran = 0; while let Some(job) = self.claim().await { @@ -262,7 +199,6 @@ impl Worker { } } -/// Registers a runner through the admin page and the runner API. The admin is `admin_session`. async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker { let page = b.http.get("/admin/runners", Some(admin_session)).await; assert_eq!(page.status, 200, "GET /admin/runners"); @@ -300,7 +236,6 @@ async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker images: forge_runner::config::ImagesConfig::default(), sandbox: forge_runner::config::SandboxConfig::default(), registries: Vec::new(), - // The e2e runner must not replace the test binary under itself. auto_update: false, cache_max_gib: 0, }; @@ -313,15 +248,11 @@ async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker } } -/// One commit status as the status API reports it. #[derive(Debug, Clone)] struct Status { state: String, - description: String, - target_url: String, } -/// The statuses on `sha` of tahinli/r, keyed by context. async fn statuses(http: &Http, token: &str, sha: &str) -> BTreeMap { let res = http .get_bearer( @@ -341,62 +272,12 @@ async fn statuses(http: &Http, token: &str, sha: &str) -> BTreeMap BTreeMap { - let deadline = Instant::now() + Duration::from_secs(20); - loop { - let found = statuses(http, token, sha).await; - if contexts.iter().all(|c| found.contains_key(*c)) { - return found; - } - assert!( - Instant::now() < deadline, - "statuses never showed {contexts:?}; got {found:?}" - ); - tokio::time::sleep(Duration::from_millis(100)).await; - } -} - -/// The job id at the end of a status `target_url` (`.../ci/jobs/`). -fn job_id_of(status: &Status) -> String { - status - .target_url - .rsplit('/') - .next() - .filter(|id| !id.is_empty()) - .unwrap_or_else(|| panic!("no job id in {:?}", status.target_url)) - .to_owned() -} - -/// Pushes `.forge/ci.toml` (with `contents`) to `main` as tahinli. Returns the pushed commit. -fn push_ci_config(work: &Path, contents: &str) -> String { - let sha = commit( - work, - ".forge/ci.toml", - contents, - "add ci", - "tahinli", - "tahinli@example.test", - ); - git(work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); - sha -} - -/// The queue's workflow. Only the queue runs it (`merge_queue = true`), never the push to main. -/// The job fails when a candidate holds both files, which is what a semantic conflict looks like. const CI_TOML_QUEUE: &str = r#"[on] merge_queue = true @@ -405,7 +286,6 @@ image = "docker.io/library/alpine:3" run = "if [ -f a.txt ] && [ -f b.txt ]; then echo both files present; exit 1; fi" "#; -/// Turns the merge queue on for `main` through the branch rule form. async fn require_merge_queue(http: &Http, session: &str) { let csrf = csrf_from(http, &format!("{REPO_PATH}/settings"), session).await; let res = http @@ -428,8 +308,6 @@ async fn require_merge_queue(http: &Http, session: &str) { ); } -/// Pushes one new file on a branch cut from `origin/main`, opens a pull request for it and -/// returns the pull request number. async fn open_pull(http: &Http, session: &str, work: &Path, branch: &str, file: &str) -> i64 { git(work, &["fetch", "-q", "origin"]); let start = "origin/main"; @@ -469,7 +347,6 @@ async fn open_pull(http: &Http, session: &str, work: &Path, branch: &str, file: .expect("pull number in location") } -/// Queues a pull request with the merge style `merge`. async fn enqueue(http: &Http, session: &str, number: i64) { let csrf = csrf_from(http, &format!("{REPO_PATH}/pulls/{number}"), session).await; let res = http @@ -482,7 +359,6 @@ async fn enqueue(http: &Http, session: &str, number: i64) { assert_eq!(res.status, 303, "enqueue #{number}: {}", res.body); } -/// The body of a pull request page, lowercased for loose text checks. async fn pull_page(http: &Http, session: &str, number: i64) -> String { let res = http .get(&format!("{REPO_PATH}/pulls/{number}"), Some(session)) @@ -491,8 +367,6 @@ async fn pull_page(http: &Http, session: &str, number: i64) -> String { res.body } -/// Pushes the queue workflow to `main` and runs its push-less base state to completion, so the -/// only runs from here on are queue candidates. async fn setup_queue_repo(b: &Booted, tahinli: &str, token: &str) -> (Worker, PathBuf) { create_repo(&b.http, tahinli, "r").await; require_merge_queue(&b.http, tahinli).await; @@ -537,8 +411,6 @@ async fn merge_queue_lands_the_first_pull_and_kicks_out_the_conflicting_second() server_log(&b) ); - // The first candidate passes and lands. The second candidate is then built on the new tip, - // holds both files, and fails. let ran = worker.drain().await; assert_eq!(ran, 2, "one candidate run each: {}", server_log(&b)); @@ -551,7 +423,6 @@ async fn merge_queue_lands_the_first_pull_and_kicks_out_the_conflicting_second() "second pull did not land: {files}" ); - // The target only points at a tested commit: the candidate carries its passing run. let found = statuses(&b.http, &token, &main_tip).await; assert_eq!( found["ci/test"].state, "success", @@ -602,7 +473,6 @@ async fn pushing_to_a_queued_pull_removes_it_from_the_queue() { let queued = pull_page(&b.http, &tahinli, number).await; assert!(queued.contains("Position 1 in the merge queue"), "queued"); - // A new commit on the pull request head: the entry no longer tests what it was queued for. commit( &work, "c.txt", diff --git a/crates/forge-e2e/tests/e2e/mirrors_e2e.rs b/crates/forge-e2e/tests/e2e/mirrors_e2e.rs index 1d3bcd9..59f0f10 100644 --- a/crates/forge-e2e/tests/e2e/mirrors_e2e.rs +++ b/crates/forge-e2e/tests/e2e/mirrors_e2e.rs @@ -10,7 +10,8 @@ //! - the mirror pages and the server log never contain the access token. use crate::common::{ - Http, Server, bin, input_value, launch_with, login, pick_ports, tool_on_path, write_config_with, + Http, Server, input_value, launch_with, login, pick_ports, run_admin, tool_on_path, + write_config_with, }; use std::collections::BTreeSet; use std::fs; @@ -36,22 +37,6 @@ fn form_actions(body: &str, suffix: &str) -> Vec { .collect() } -fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { - let out = Command::new(bin()) - .arg("--config") - .arg(config) - .args(["admin", "create-user", username]) - .args(extra) - .env("FORGE_PASSWORD", password) - .output() - .expect("run admin create-user"); - assert!( - out.status.success(), - "create-user {username} failed:\n{}", - String::from_utf8_lossy(&out.stderr) - ); -} - /// Fixed identity and config isolation for every git this file spawns, so the result does not /// depend on the machine's global git config (a clean CI container has none). const GIT_HERMETIC_ENV: &[(&str, &str)] = &[ diff --git a/crates/forge-e2e/tests/e2e/oci_e2e.rs b/crates/forge-e2e/tests/e2e/oci_e2e.rs index efdd7e0..bb022e1 100644 --- a/crates/forge-e2e/tests/e2e/oci_e2e.rs +++ b/crates/forge-e2e/tests/e2e/oci_e2e.rs @@ -186,10 +186,25 @@ async fn user(store: &Store, name: &str) -> User { .expect("user exists") } +async fn start_with_packages_token() -> (Env, String) { + let token = generate_token(); + let seeded = token.clone(); + let env = start(move |store| async move { + let tahinli = user(&store, "tahinli").await; + grant(&store, &tahinli, &["packages"], &seeded).await; + }) + .await; + (env, token) +} + fn sha256_digest(bytes: &[u8]) -> String { format!("sha256:{}", hex::encode(Sha256::digest(bytes))) } +fn blob_path(bytes: &[u8]) -> String { + format!("/v2/tahinli/app/blobs/{}", sha256_digest(bytes)) +} + /// The bearer header a client gets from the token endpoint with Basic `tahinli:`. async fn bearer_for(http: &Http, token: &str) -> String { let res = http @@ -298,13 +313,7 @@ async fn put_manifest(http: &Http, repo: &str, reference: &str, auth: &str, body #[tokio::test] async fn probe_challenges_and_the_token_endpoint_issues_a_bearer_token() { - let token = generate_token(); - let seeded = token.clone(); - let env = start(move |store| async move { - let tahinli = user(&store, "tahinli").await; - grant(&store, &tahinli, &["packages"], &seeded).await; - }) - .await; + let (env, token) = start_with_packages_token().await; let port = env.port; let probe = env.http.get("/v2/", None).await; @@ -334,13 +343,7 @@ async fn probe_challenges_and_the_token_endpoint_issues_a_bearer_token() { #[tokio::test] async fn push_by_monolithic_and_chunked_upload_then_pull_by_tag_and_digest() { - let token = generate_token(); - let seeded = token.clone(); - let env = start(move |store| async move { - let tahinli = user(&store, "tahinli").await; - grant(&store, &tahinli, &["packages"], &seeded).await; - }) - .await; + let (env, token) = start_with_packages_token().await; let http = &env.http; let auth = bearer_for(http, &token).await; @@ -364,13 +367,13 @@ async fn push_by_monolithic_and_chunked_upload_then_pull_by_tag_and_digest() { assert_eq!(res.status, 201, "{}", res.text()); assert_eq!( res.header("location"), - Some(format!("/v2/tahinli/app/blobs/{}", sha256_digest(&layer_two)).as_str()) + Some(blob_path(&layer_two).as_str()) ); let head = http .send( reqwest::Method::HEAD, - &format!("/v2/tahinli/app/blobs/{}", sha256_digest(&layer_two)), + &blob_path(&layer_two), Some(&auth), &[], None, @@ -380,7 +383,7 @@ async fn push_by_monolithic_and_chunked_upload_then_pull_by_tag_and_digest() { assert_eq!(head.header("content-length"), Some("3000")); let blob = http .get( - &format!("/v2/tahinli/app/blobs/{}", sha256_digest(&layer_two)), + &blob_path(&layer_two), Some(&auth), ) .await; @@ -421,13 +424,7 @@ async fn push_by_monolithic_and_chunked_upload_then_pull_by_tag_and_digest() { #[tokio::test] async fn the_tag_list_pages_with_n_and_last() { - let token = generate_token(); - let seeded = token.clone(); - let env = start(move |store| async move { - let tahinli = user(&store, "tahinli").await; - grant(&store, &tahinli, &["packages"], &seeded).await; - }) - .await; + let (env, token) = start_with_packages_token().await; let http = &env.http; let auth = bearer_for(http, &token).await; let config = b"{}".to_vec(); @@ -467,13 +464,7 @@ async fn the_tag_list_pages_with_n_and_last() { #[tokio::test] async fn bad_digests_and_missing_blobs_are_refused_with_oci_codes() { - let token = generate_token(); - let seeded = token.clone(); - let env = start(move |store| async move { - let tahinli = user(&store, "tahinli").await; - grant(&store, &tahinli, &["packages"], &seeded).await; - }) - .await; + let (env, token) = start_with_packages_token().await; let http = &env.http; let auth = bearer_for(http, &token).await; let config = b"{}".to_vec(); @@ -516,7 +507,7 @@ async fn bad_digests_and_missing_blobs_are_refused_with_oci_codes() { let res = http .get( - &format!("/v2/tahinli/app/blobs/{}", sha256_digest(b"absent")), + &blob_path(b"absent"), Some(&auth), ) .await; @@ -526,13 +517,7 @@ async fn bad_digests_and_missing_blobs_are_refused_with_oci_codes() { #[tokio::test] async fn an_aborted_chunked_upload_is_gone_after_a_bad_digest() { - let token = generate_token(); - let seeded = token.clone(); - let env = start(move |store| async move { - let tahinli = user(&store, "tahinli").await; - grant(&store, &tahinli, &["packages"], &seeded).await; - }) - .await; + let (env, token) = start_with_packages_token().await; let http = &env.http; let auth = bearer_for(http, &token).await; @@ -621,7 +606,7 @@ async fn a_public_image_pulls_anonymously_and_a_private_one_does_not() { assert_eq!(anon.body, image); let anon_blob = http .get( - &format!("/v2/tahinli/app/blobs/{}", sha256_digest(&config)), + &blob_path(&config), None, ) .await; @@ -710,13 +695,7 @@ async fn bearer_for_as(http: &Http, who: &str, token: &str) -> String { #[tokio::test] async fn mount_copies_a_blob_across_repositories() { - let token = generate_token(); - let seeded = token.clone(); - let env = start(move |store| async move { - let tahinli = user(&store, "tahinli").await; - grant(&store, &tahinli, &["packages"], &seeded).await; - }) - .await; + let (env, token) = start_with_packages_token().await; let http = &env.http; let auth = bearer_for(http, &token).await; let layer = b"shared layer bytes".to_vec(); @@ -757,13 +736,7 @@ async fn mount_copies_a_blob_across_repositories() { #[tokio::test] async fn deleting_tags_and_manifests_keeps_fresh_blobs_for_the_grace_period() { - let token = generate_token(); - let seeded = token.clone(); - let env = start(move |store| async move { - let tahinli = user(&store, "tahinli").await; - grant(&store, &tahinli, &["packages"], &seeded).await; - }) - .await; + let (env, token) = start_with_packages_token().await; let http = &env.http; let auth = bearer_for(http, &token).await; let config = b"{\"shared\":true}".to_vec(); @@ -790,7 +763,6 @@ async fn deleting_tags_and_manifests_keeps_fresh_blobs_for_the_grace_period() { 201 ); - let blob_url = |bytes: &[u8]| format!("/v2/tahinli/app/blobs/{}", sha256_digest(bytes)); let res = http .send( reqwest::Method::DELETE, @@ -809,9 +781,9 @@ async fn deleting_tags_and_manifests_keeps_fresh_blobs_for_the_grace_period() { ); // The blobs were pushed just now: the sweep keeps a link newer than the grace period, since a // push can still be on its way to a manifest. The store test covers the sweep after it. - assert_eq!(http.get(&blob_url(&layer_b), Some(&auth)).await.status, 200); - assert_eq!(http.get(&blob_url(&layer_a), Some(&auth)).await.status, 200); - assert_eq!(http.get(&blob_url(&config), Some(&auth)).await.status, 200); + assert_eq!(http.get(&blob_path(&layer_b), Some(&auth)).await.status, 200); + assert_eq!(http.get(&blob_path(&layer_a), Some(&auth)).await.status, 200); + assert_eq!(http.get(&blob_path(&config), Some(&auth)).await.status, 200); let v1_digest = sha256_digest(&v1); let res = http @@ -824,21 +796,15 @@ async fn deleting_tags_and_manifests_keeps_fresh_blobs_for_the_grace_period() { ) .await; assert_eq!(res.status, 202); - assert_eq!(http.get(&blob_url(&layer_a), Some(&auth)).await.status, 200); - assert_eq!(http.get(&blob_url(&config), Some(&auth)).await.status, 200); + assert_eq!(http.get(&blob_path(&layer_a), Some(&auth)).await.status, 200); + assert_eq!(http.get(&blob_path(&config), Some(&auth)).await.status, 200); let tags = http.get("/v2/tahinli/app/tags/list", Some(&auth)).await; assert_eq!(tags.json()["tags"], serde_json::json!([])); } #[tokio::test] async fn a_blob_a_manifest_uses_cannot_be_deleted_and_an_unused_one_can() { - let token = generate_token(); - let seeded = token.clone(); - let env = start(move |store| async move { - let tahinli = user(&store, "tahinli").await; - grant(&store, &tahinli, &["packages"], &seeded).await; - }) - .await; + let (env, token) = start_with_packages_token().await; let http = &env.http; let auth = bearer_for(http, &token).await; let config = b"{}".to_vec(); @@ -869,11 +835,10 @@ async fn a_blob_a_manifest_uses_cannot_be_deleted_and_an_unused_one_can() { 201 ); - let delete = |bytes: &[u8]| format!("/v2/tahinli/app/blobs/{}", sha256_digest(bytes)); let refused = http .send( reqwest::Method::DELETE, - &delete(&layer), + &blob_path(&layer), Some(&auth), &[], None, @@ -885,14 +850,14 @@ async fn a_blob_a_manifest_uses_cannot_be_deleted_and_an_unused_one_can() { let gone = http .send( reqwest::Method::DELETE, - &delete(&spare), + &blob_path(&spare), Some(&auth), &[], None, ) .await; assert_eq!(gone.status, 202); - assert_eq!(http.get(&delete(&spare), Some(&auth)).await.status, 404); + assert_eq!(http.get(&blob_path(&spare), Some(&auth)).await.status, 404); } #[tokio::test] @@ -902,13 +867,7 @@ async fn podman_logs_in_pushes_and_pulls_an_image() { eprintln!("podman is not installed; skipping"); return; } - let token = generate_token(); - let seeded = token.clone(); - let env = start(move |store| async move { - let tahinli = user(&store, "tahinli").await; - grant(&store, &tahinli, &["packages"], &seeded).await; - }) - .await; + let (env, token) = start_with_packages_token().await; let host = format!("127.0.0.1:{}", env.port); let work = tempfile::tempdir().expect("work dir"); let dir = work.path(); diff --git a/crates/forge-e2e/tests/e2e/orgs_core_e2e.rs b/crates/forge-e2e/tests/e2e/orgs_core_e2e.rs index 57e993b..5928d99 100644 --- a/crates/forge-e2e/tests/e2e/orgs_core_e2e.rs +++ b/crates/forge-e2e/tests/e2e/orgs_core_e2e.rs @@ -7,7 +7,7 @@ use crate::common::{ Http, Resp, Server, bin, cookie_named, describe, input_value, launch, pick_ports, write_config, }; use std::future::Future; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::Command; use std::time::Duration; @@ -69,7 +69,7 @@ struct Env { /// the store before the server starts. async fn start(seed: F) -> Env where - F: FnOnce(PathBuf, Store) -> Fut, + F: FnOnce(Store) -> Fut, Fut: Future, { let root = tempfile::tempdir().expect("temp dir"); @@ -82,7 +82,7 @@ where let store = Store::open(&dir.join("forge.db")) .await .expect("open store"); - seed(dir.clone(), store).await; + seed(store).await; let (server, ports) = launch(&dir, ports).await; Env { _root: root, @@ -93,7 +93,7 @@ where /// `acme` is an org owned by tahinli, with a public repo, a session row, and an API token. None of /// them may authenticate. -async fn seed_org(_dir: PathBuf, store: Store) { +async fn seed_org(store: Store) { let tahinli = store .user_by_username("tahinli") .await @@ -129,20 +129,15 @@ async fn seed_org(_dir: PathBuf, store: Store) { } #[tokio::test] -async fn an_org_cannot_sign_in_with_a_password() { +async fn org_credentials_never_authenticate() { let _guard = SERIAL.lock().await; let env = start(seed_org).await; + let res = try_login(&env.http, "acme").await; assert_ne!(res.status, 303, "org login must not redirect: {}", res.body); assert!(cookie_named(&res, "forge_session").is_none()); -} -#[tokio::test] -async fn an_org_session_signs_nobody_in() { - let _guard = SERIAL.lock().await; - let env = start(seed_org).await; let cookie = format!("__Host-forge_session={ORG_SESSION}"); - // A page that needs a person answers the same with the org session as with no cookie. let with_org = env.http.get("/new", Some(&cookie)).await; let without = env.http.get("/new", None).await; assert_eq!(with_org.status, without.status); @@ -152,12 +147,7 @@ async fn an_org_session_signs_nobody_in() { "a person is required: {}", with_org.body ); -} -#[tokio::test] -async fn an_org_api_token_is_refused() { - let _guard = SERIAL.lock().await; - let env = start(seed_org).await; let res = env .http .client @@ -171,12 +161,7 @@ async fn an_org_api_token_is_refused() { .await .expect("api request"); assert_eq!(res.status().as_u16(), 401, "org API token must be refused"); -} -#[tokio::test] -async fn an_org_token_cannot_use_git_over_http_basic() { - let _guard = SERIAL.lock().await; - let env = start(seed_org).await; let res = env .http .client diff --git a/crates/forge-e2e/tests/e2e/orgs_ui_e2e.rs b/crates/forge-e2e/tests/e2e/orgs_ui_e2e.rs index 38280a8..14ac6b0 100644 --- a/crates/forge-e2e/tests/e2e/orgs_ui_e2e.rs +++ b/crates/forge-e2e/tests/e2e/orgs_ui_e2e.rs @@ -4,8 +4,8 @@ //! handled by hand, as in `repo_collaborators_e2e.rs`. use crate::common::{ - Http, Resp, bin, describe, input_value, launch, launch_with, login, pick_ports, tool_on_path, - write_config, + Http, Resp, bin, describe, input_value, launch, launch_with, login, pick_ports, temp_dir, + tool_on_path, write_config, }; use std::fs; use std::path::Path; @@ -84,14 +84,6 @@ fn notice_location(redirect: &Resp) -> String { redirect.header(LOCATION).expect("notice redirect") } -/// A temp dir short enough for the unix socket path limit. -fn short_temp_dir() -> tempfile::TempDir { - tempfile::Builder::new() - .prefix("forg") - .tempdir_in("/tmp") - .expect("temp dir") -} - #[tokio::test] async fn org_members_teams_and_access_end_to_end() { let _guard = SERIAL.lock().await; @@ -99,7 +91,7 @@ async fn org_members_teams_and_access_end_to_end() { eprintln!("SKIP orgs_ui_e2e: `git` was not found on PATH"); return; } - let root = short_temp_dir(); + let root = temp_dir("forg"); let dir = root.path().to_path_buf(); let ports = pick_ports(); let config = write_config(&dir, ports); @@ -329,7 +321,7 @@ async fn org_settings_delete_and_audit_end_to_end() { eprintln!("SKIP orgs_ui_e2e: `git` was not found on PATH"); return; } - let root = short_temp_dir(); + let root = temp_dir("forg"); let dir = root.path().to_path_buf(); let ports = pick_ports(); let config = write_config(&dir, ports); @@ -484,7 +476,7 @@ async fn org_settings_delete_and_audit_end_to_end() { #[tokio::test] async fn org_creation_can_be_limited_to_admins() { let _guard = SERIAL.lock().await; - let root = short_temp_dir(); + let root = temp_dir("forg"); let dir = root.path().to_path_buf(); let ports = pick_ports(); let config = write_config(&dir, ports); @@ -630,7 +622,7 @@ async fn org_member_pushes_over_https_through_a_write_team() { eprintln!("SKIP orgs_ui_e2e: `git` was not found on PATH"); return; } - let root = short_temp_dir(); + let root = temp_dir("forg"); let dir = root.path().to_path_buf(); let ports = pick_ports(); let config = write_config(&dir, ports); diff --git a/crates/forge-e2e/tests/e2e/pulls_e2e.rs b/crates/forge-e2e/tests/e2e/pulls_e2e.rs index d4e9d4e..43cb530 100644 --- a/crates/forge-e2e/tests/e2e/pulls_e2e.rs +++ b/crates/forge-e2e/tests/e2e/pulls_e2e.rs @@ -6,7 +6,8 @@ //! a fork pull merged by squash, and a conflict that blocks the merge. use crate::common::{ - Http, Resp, Server, bin, input_value, launch, login, pick_ports, tool_on_path, write_config, + Http, Resp, Server, create_token, input_value, launch, login, pick_ports, run_admin, + tool_on_path, write_config, }; use std::fs; use std::path::{Path, PathBuf}; @@ -19,6 +20,8 @@ const TAHINLI_PW: &str = "tahinli-password-123"; const BOB_PW: &str = "bob-password-4567"; const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1"; const REPO_PATH: &str = "/tahinli/r"; +const TAHINLI: (&str, &str) = ("tahinli", "tahinli@example.test"); +const BOB: (&str, &str) = ("bob", BOB_EMAIL); /// Text of the first state badge on a page, e.g. `Open`, `Closed` or `Merged`. fn state_badge(body: &str) -> String { @@ -31,22 +34,6 @@ fn state_badge(body: &str) -> String { .unwrap_or_default() } -fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { - let out = Command::new(bin()) - .arg("--config") - .arg(config) - .args(["admin", "create-user", username]) - .args(extra) - .env("FORGE_PASSWORD", password) - .output() - .expect("run admin create-user"); - assert!( - out.status.success(), - "create-user {username} failed:\n{}", - String::from_utf8_lossy(&out.stderr) - ); -} - /// Runs git with credential helpers disabled and extra env, returning stdout trimmed. Panics on /// failure. fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String { @@ -72,23 +59,17 @@ fn git(cwd: &Path, args: &[&str]) -> String { } /// Writes `file`, commits it with `who` as author and committer, and returns the new HEAD. -fn commit( - repo: &Path, - file: &str, - contents: &str, - message: &str, - who: &str, - email: &str, -) -> String { +fn commit(repo: &Path, file: &str, contents: &str, message: &str, who: (&str, &str)) -> String { + let (name, email) = who; fs::write(repo.join(file), contents).expect("write file"); git(repo, &["add", file]); git_env( repo, &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], &[ - ("GIT_AUTHOR_NAME", who), + ("GIT_AUTHOR_NAME", name), ("GIT_AUTHOR_EMAIL", email), - ("GIT_COMMITTER_NAME", who), + ("GIT_COMMITTER_NAME", name), ("GIT_COMMITTER_EMAIL", email), ], ); @@ -132,30 +113,6 @@ async fn csrf_token(http: &Http, session: &str) -> String { input_value(&page.body, "csrf") } -/// Creates an access token through `/settings/tokens` and returns the token shown once. -async fn create_token(http: &Http, session: &str, name: &str) -> String { - let csrf = csrf_token(http, session).await; - let res = http - .post_form( - "/settings/tokens", - &[("csrf", &csrf), ("name", name), ("expires", "30")], - Some(session), - ) - .await; - assert_eq!(res.status, 200, "create token: {}", res.body); - let doc = scraper::Html::parse_document(&res.body); - let selector = scraper::Selector::parse("pre.code code").expect("selector"); - let token: String = doc - .select(&selector) - .next() - .expect("token shown after creation") - .text() - .collect(); - let token = token.trim().to_owned(); - assert!(token.starts_with("forge_"), "unexpected token shape"); - token -} - /// Creates a public repo `name` owned by tahinli through `/new`. async fn create_repo(http: &Http, session: &str, name: &str) { let page = http.get_cookie("/new", session).await; @@ -236,8 +193,7 @@ async fn tahinli_repo_with_main(b: &Booted) -> (String, String, PathBuf) { "base.txt", "base\n", "base commit", - "tahinli", - "tahinli@example.test", + TAHINLI, ); git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); (tahinli, token, work) @@ -343,8 +299,7 @@ async fn same_repo_pull_merges_and_closes_issue() { "x.txt", "x\n", "Add x\n\nFixes #1", - "tahinli", - "tahinli@example.test", + TAHINLI, ); git(&work, &["push", "-q", "origin", "HEAD:refs/heads/feature"]); @@ -410,8 +365,7 @@ async fn push_to_head_branch_updates_open_pull() { "one.txt", "1\n", "first on feature2", - "tahinli", - "tahinli@example.test", + TAHINLI, ); git(&work, &["push", "-q", "origin", "HEAD:refs/heads/feature2"]); let number = open_pull(&b.http, &tahinli, "main", "feature2", "Feature two").await; @@ -421,8 +375,7 @@ async fn push_to_head_branch_updates_open_pull() { "two.txt", "2\n", "second on feature2", - "tahinli", - "tahinli@example.test", + TAHINLI, ); git(&work, &["push", "-q", "origin", "HEAD:refs/heads/feature2"]); @@ -496,8 +449,7 @@ async fn pull_pages_follow_writes_live() { "live.txt", "live\n", "first on live", - "tahinli", - "tahinli@example.test", + TAHINLI, ); git(&work, &["push", "-q", "origin", "HEAD:refs/heads/live"]); let number = open_pull(&b.http, &tahinli, "main", "live", "Live pull").await; @@ -567,8 +519,7 @@ async fn pull_pages_follow_writes_live() { "second.txt", "2\n", "second on live", - "tahinli", - "tahinli@example.test", + TAHINLI, ); git(&work, &["push", "-q", "origin", "HEAD:refs/heads/live"]); next_changed(&mut pull_events, "a push to the head").await; @@ -647,8 +598,7 @@ async fn fork_pull_squash_merge_credits_contributor() { "bob.txt", "bob\n", "Bob change", - "bob", - BOB_EMAIL, + BOB, ); git( &bob_work, @@ -688,8 +638,7 @@ async fn conflicting_pull_cannot_merge() { "shared.txt", "branch side\n", "branch edit", - "tahinli", - "tahinli@example.test", + TAHINLI, ); git(&work, &["push", "-q", "origin", "HEAD:refs/heads/conflict"]); let number = open_pull(&b.http, &tahinli, "main", "conflict", "Conflicting").await; @@ -700,8 +649,7 @@ async fn conflicting_pull_cannot_merge() { "shared.txt", "main side\n", "main edit", - "tahinli", - "tahinli@example.test", + TAHINLI, ); git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); diff --git a/crates/forge-e2e/tests/e2e/repo_collaborators_e2e.rs b/crates/forge-e2e/tests/e2e/repo_collaborators_e2e.rs index 6fd5b50..2c2ec3f 100644 --- a/crates/forge-e2e/tests/e2e/repo_collaborators_e2e.rs +++ b/crates/forge-e2e/tests/e2e/repo_collaborators_e2e.rs @@ -3,7 +3,7 @@ //! its POST forms over HTTP. Cookies are handled by hand (see `repo_settings_e2e.rs`). use crate::common::{ - Http, Resp, bin, cookie_named, describe, input_value, launch, login, pick_ports, tool_on_path, + Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, with_cookie, write_config, }; use std::fs; @@ -69,12 +69,6 @@ async fn shown_role(http: &Http, session: &str, username: &str) -> Option String { - let notice = cookie_named(redirect, "forge_collab_notice").expect("notice cookie"); - format!("{session}; {notice}") -} - #[tokio::test] async fn repo_collaborators_end_to_end() { if !tool_on_path("git") { @@ -249,7 +243,9 @@ async fn repo_collaborators_end_to_end() { ) .await; assert_eq!(res.status, 303, "unknown user redirects with a notice"); - let notice_page = http.get(page, Some(&with_notice(&olivia, &res))).await; + let notice_page = http + .get(page, Some(&with_cookie(&olivia, &res, "forge_collab_notice"))) + .await; assert!( notice_page.body.contains("No user has that username."), "unknown user notice missing" @@ -261,7 +257,9 @@ async fn repo_collaborators_end_to_end() { Some(&olivia), ) .await; - let notice_page = http.get(page, Some(&with_notice(&olivia, &res))).await; + let notice_page = http + .get(page, Some(&with_cookie(&olivia, &res, "forge_collab_notice"))) + .await; assert!( notice_page .body diff --git a/crates/forge-e2e/tests/e2e/repo_settings_e2e.rs b/crates/forge-e2e/tests/e2e/repo_settings_e2e.rs index 7642592..6601760 100644 --- a/crates/forge-e2e/tests/e2e/repo_settings_e2e.rs +++ b/crates/forge-e2e/tests/e2e/repo_settings_e2e.rs @@ -1,12 +1,6 @@ -//! Black-box test for repo deletion. It starts the real `forge` binary, seeds repos through the -//! store before the server starts, and then drives the settings page and the delete form over HTTP. -//! -//! Cookies are handled by hand because the session cookie is `__Host-forge_session` with `Secure`, -//! which a cookie jar would not send over plain http. - use crate::common::{ - Http, Resp, bin, cookie_named, describe, input_value, launch, login, pick_ports, tool_on_path, - write_config, + Http, bin, cookie_named, describe, input_value, launch, login, pick_ports, tool_on_path, + with_cookie, write_config, }; use std::fs; use std::path::{Path, PathBuf}; @@ -17,7 +11,6 @@ use reqwest::header::LOCATION; const PW: &str = "tahinli-password-123"; -/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded. fn admin(config: &Path, args: &[&str]) -> Output { let out = Command::new(bin()) .arg("--config") @@ -35,14 +28,12 @@ fn admin(config: &Path, args: &[&str]) -> Output { out } -/// The session's CSRF token, read from a page every signed-in user can open. async fn csrf_for(http: &Http, session: &str) -> String { let page = http.get("/settings/keys", Some(session)).await; assert_eq!(page.status, 200, "GET /settings/keys"); input_value(&page.body, "csrf") } -/// Creates a bare git repo for `repo_id` at its data-dir location, as the create-repo page does. fn init_bare(data_dir: &Path, repo_id: &str) { let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path"); fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent"); @@ -54,7 +45,6 @@ fn init_bare(data_dir: &Path, repo_id: &str) { assert!(out.status.success(), "git init --bare: {}", describe(&out)); } -/// Directories in `data_dir/trash` for the repo `id` (lowercase, as the trash names them). fn trash_entries(data_dir: &Path, repo_id: &str) -> Vec { let prefix = format!("{}-", repo_id.to_ascii_lowercase()); let Ok(read) = fs::read_dir(data_dir.join(forge_git::repo::TRASH_DIR)) else { @@ -77,7 +67,6 @@ async fn repo_settings_end_to_end() { return; } - // Keep the path short: the data dir holds a unix socket with a length limit. let root = tempfile::Builder::new() .prefix("frs") .tempdir_in("/tmp") @@ -87,8 +76,6 @@ async fn repo_settings_end_to_end() { let ports = pick_ports(); let config = write_config(&dir, ports); - // The first user is an admin. Bob owns the repos, carol is an admin collaborator on the private - // one, and tahinli (admin) must still be able to delete bob's repo. admin(&config, &["create-user", "tahinli", "--admin"]); admin(&config, &["create-user", "bob"]); admin(&config, &["create-user", "carol"]); @@ -127,12 +114,9 @@ async fn repo_settings_end_to_end() { let carol = login(&http, "carol", PW).await; let tahinli = login(&http, "tahinli", PW).await; - // Anonymous on a private repo: 404, the same as a missing repo. let anon = http.get("/bob/priv/settings", None).await; assert_eq!(anon.status, 404, "anonymous settings on private repo"); - // A collaborator with the Admin role gets the settings page (branch rules) but no danger zone, - // and a POST to the delete form is 403. The repo stays. let carol_page = http .get("/bob/priv/settings?section=danger", Some(&carol)) .await; @@ -152,7 +136,6 @@ async fn repo_settings_end_to_end() { assert_eq!(carol_delete.status, 403, "collaborator delete"); assert_eq!(http.get("/bob/priv", Some(&carol)).await.status, 200); - // The owner sees the danger zone, and the Settings tab appears on the repo header. let owner_page = http .get("/bob/pub/settings?section=danger", Some(&bob)) .await; @@ -173,7 +156,6 @@ async fn repo_settings_end_to_end() { "Settings tab shows to an Admin collaborator" ); - // A wrong confirmation is an error and keeps the repo. let owner_csrf = csrf_for(&http, &bob).await; let wrong = http .post_form( @@ -197,7 +179,6 @@ async fn repo_settings_end_to_end() { "nothing trashed on mismatch" ); - // No CSRF token is rejected, even with the right confirmation. let no_csrf = http .post_form( "/bob/pub/settings/delete", @@ -212,7 +193,6 @@ async fn repo_settings_end_to_end() { "repo kept without CSRF" ); - // The owner deletes: redirect home with a notice, the repo is gone, the directory is trashed. let deleted = http .post_form( "/bob/pub/settings/delete", @@ -246,7 +226,6 @@ async fn repo_settings_end_to_end() { "trash entry is a bare repo" ); - // The home page is the signed-in viewer's own page, not a redirect. let home = http.get("/", Some(&bob)).await; assert_eq!(home.status, 200, "home page for a signed-in viewer"); assert!( @@ -254,7 +233,6 @@ async fn repo_settings_end_to_end() { "home lists their repositories" ); - // An admin who does not own the repo can delete it. let admin_page = http.get("/bob/priv/settings", Some(&tahinli)).await; assert_eq!(admin_page.status, 200, "admin settings page"); let admin_csrf = csrf_for(&http, &tahinli).await; @@ -277,7 +255,6 @@ async fn repo_settings_end_to_end() { "admin delete is trashed" ); - // The admin CLI lists both trash entries, then purges them. let listed = String::from_utf8_lossy(&admin(&config, &["trash-list"]).stdout).into_owned(); assert!( listed.contains(&public_id.to_ascii_lowercase()), @@ -298,8 +275,6 @@ async fn repo_settings_end_to_end() { drop(server); } -/// A repo whose bare directory was removed by hand can still be deleted from the UI: the DB rows -/// go, nothing is trashed, and the request succeeds. #[tokio::test] async fn repo_settings_deletes_rows_when_repo_dir_is_missing() { if !tool_on_path("git") { @@ -327,7 +302,6 @@ async fn repo_settings_deletes_rows_when_repo_dir_is_missing() { .expect("repo"); init_bare(&dir, &repo.id); let bare = forge_git::repo::repo_path(&dir, &repo.id).expect("repo path"); - // Simulate the broken state: the DB row exists but the bare directory is gone. fs::remove_dir_all(&bare).expect("remove bare dir by hand"); (repo.id, bare) }; @@ -362,7 +336,6 @@ async fn repo_settings_deletes_rows_when_repo_dir_is_missing() { trash_entries(&dir, &repo_id).is_empty(), "nothing to trash when the dir is missing" ); - // Stop the server first: the database file is locked while it runs. drop(server); let store = Store::open(&dir.join("forge.db")) .await @@ -378,12 +351,8 @@ async fn repo_settings_deletes_rows_when_repo_dir_is_missing() { ); } -/// The rule rows of the branch rules list in page order, each as its pattern followed by the texts -/// of its summary pills. The built-in default-branch row has no rule behind it, so it is skipped. fn branch_rows(body: &str) -> Vec> { let doc = scraper::Html::parse_document(body); - // Every rule row is a `details` with the pattern in its summary's name; the "Add rule" row - // has no pattern there, so it drops out. let cards = scraper::Selector::parse("details.row-open").expect("selector"); let pattern = scraper::Selector::parse("summary .name code").expect("selector"); let pills = scraper::Selector::parse("summary .rule-pills span").expect("selector"); @@ -398,15 +367,12 @@ fn branch_rows(body: &str) -> Vec> { .collect() } -/// The row for `pattern` as its cells (see `branch_rows`), if the list has one. fn rule_row(body: &str, pattern: &str) -> Option> { branch_rows(body) .into_iter() .find(|cells| cells.first().is_some_and(|c| c == pattern)) } -/// Owner adds, updates, invalidates and removes branch rules. A Write collaborator and an Admin -/// collaborator get the right access: the Admin can manage rules but sees no danger zone. #[tokio::test] async fn branch_protection_end_to_end() { if !tool_on_path("git") { @@ -422,7 +388,6 @@ async fn branch_protection_end_to_end() { let ports = pick_ports(); let config = write_config(&dir, ports); - // The first user is an instance admin, so bob (the owner) is an ordinary user. admin(&config, &["create-user", "tahinli", "--admin"]); admin(&config, &["create-user", "bob"]); admin(&config, &["create-user", "carol"]); @@ -460,7 +425,6 @@ async fn branch_protection_end_to_end() { let carol = login(&http, "carol", PW).await; let dan = login(&http, "dan", PW).await; - // Owner: the built-in row is there before any rule, and the danger zone is shown. let page = http .get("/bob/app/settings?section=branches", Some(&bob)) .await; @@ -484,7 +448,6 @@ async fn branch_protection_end_to_end() { ); let owner_csrf = csrf_for(&http, &bob).await; - // Adding main with force push allowed: it appears, and the built-in row disappears. let added = http .post_form( "/bob/app/settings/branches", @@ -522,7 +485,6 @@ async fn branch_protection_end_to_end() { "built-in row must disappear once a rule matches" ); - // Updating the same pattern toggles the value and does not add a second row. let updated = http .post_form( "/bob/app/settings/branches", @@ -536,7 +498,6 @@ async fn branch_protection_end_to_end() { .await; assert_eq!(updated.status, 303, "update rule: {}", updated.body); - // Adding a new rule for a pattern that has one is refused instead of overwriting it. let duplicate = http .post_form( "/bob/app/settings/branches", @@ -563,7 +524,6 @@ async fn branch_protection_end_to_end() { "update must not add a row" ); - // An invalid pattern is refused inline and nothing is saved. let invalid = http .post_form( "/bob/app/settings/branches", @@ -592,7 +552,6 @@ async fn branch_protection_end_to_end() { "invalid rule must not be saved" ); - // No CSRF token is rejected. let no_csrf = http .post_form( "/bob/app/settings/branches", @@ -621,7 +580,6 @@ async fn branch_protection_end_to_end() { "main kept without CSRF" ); - // Remove works: the row goes and the built-in row comes back. let rule_id = input_value(&page.body, "rule_id"); let removed = http .post_form( @@ -640,7 +598,6 @@ async fn branch_protection_end_to_end() { "built-in row back after remove" ); - // A Write collaborator cannot open the settings or post rules. let dan_page = http .get("/bob/app/settings?section=branches", Some(&dan)) .await; @@ -662,7 +619,6 @@ async fn branch_protection_end_to_end() { "write collaborator must not change rules" ); - // An Admin collaborator manages rules, sees no danger zone and cannot delete the repo. let carol_page = http .get("/bob/app/settings?section=branches", Some(&carol)) .await; @@ -744,7 +700,6 @@ async fn branch_protection_end_to_end() { drop(server); } -/// Creates commits in a scratch work tree and pushes them as `branches` into the bare repo. fn seed_branches(dir: &Path, repo_id: &str, branches: &[&str]) { let bare = forge_git::repo::repo_path(dir, repo_id).expect("repo path"); let work = dir.join(format!("seed-{repo_id}")); @@ -778,7 +733,6 @@ fn seed_branches(dir: &Path, repo_id: &str, branches: &[&str]) { run(&push); } -/// The symbolic target of HEAD in the bare repo, e.g. `refs/heads/dev`. fn git_head(data_dir: &Path, repo_id: &str) -> String { let bare = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path"); let out = Command::new("git") @@ -791,7 +745,6 @@ fn git_head(data_dir: &Path, repo_id: &str) -> String { String::from_utf8_lossy(&out.stdout).trim().to_owned() } -/// The value of the `selected` option of the default-branch select, if the page has one. fn selected_branch(body: &str) -> Option { let doc = scraper::Html::parse_document(body); let selector = @@ -802,14 +755,6 @@ fn selected_branch(body: &str) -> Option { .map(str::to_owned) } -/// Cookie header with the session plus a one-shot settings notice set by the previous response. -fn with_notice(session: &str, res: &Resp) -> String { - match cookie_named(res, "forge_settings_notice") { - Some(notice) => format!("{session}; {notice}"), - None => session.to_owned(), - } -} - #[tokio::test] async fn general_settings_end_to_end() { if !tool_on_path("git") { @@ -862,7 +807,6 @@ async fn general_settings_end_to_end() { let bob = login(&http, "bob", PW).await; let carol = login(&http, "carol", PW).await; - // The General section is the first card on the page, with the sub-navigation above it. let page = http.get("/bob/gen/settings", Some(&bob)).await; assert_eq!(page.status, 200, "owner settings page"); assert!( @@ -879,7 +823,6 @@ async fn general_settings_end_to_end() { .contains("href=\"/bob/gen/settings?section=danger\"") ); - // Description: control characters are stripped and it shows on the repo header. let csrf = csrf_for(&http, &bob).await; let saved = http .post_form( @@ -899,7 +842,6 @@ async fn general_settings_end_to_end() { "description not on header" ); - // Default branch: an existing branch updates the DB value and git HEAD. let switched = http .post_form( "/bob/gen/settings/general", @@ -916,7 +858,6 @@ async fn general_settings_end_to_end() { let after = http.get("/bob/gen/settings", Some(&bob)).await; assert_eq!(selected_branch(&after.body).as_deref(), Some("dev")); - // A nonexistent branch is rejected: HEAD and the DB keep dev. let missing = http .post_form( "/bob/gen/settings/general", @@ -930,7 +871,7 @@ async fn general_settings_end_to_end() { .await; assert_eq!(missing.status, 303); let notice_page = http - .get("/bob/gen/settings", Some(&with_notice(&bob, &missing))) + .get("/bob/gen/settings", Some(&with_cookie(&bob, &missing, "forge_settings_notice"))) .await; assert!( notice_page.body.contains("That branch does not exist"), @@ -942,7 +883,6 @@ async fn general_settings_end_to_end() { Some("dev") ); - // Over-long description is rejected. let long = "x".repeat(351); let too_long = http .post_form( @@ -957,11 +897,10 @@ async fn general_settings_end_to_end() { .await; assert_eq!(too_long.status, 303); let long_page = http - .get("/bob/gen/settings", Some(&with_notice(&bob, &too_long))) + .get("/bob/gen/settings", Some(&with_cookie(&bob, &too_long, "forge_settings_notice"))) .await; assert!(long_page.body.contains("at most 350 characters")); - // Visibility: changing to private needs "I understand"; then anonymous gets 404. let vis_csrf = csrf_for(&http, &bob).await; let no_ack = http .post_form( @@ -1016,7 +955,6 @@ async fn general_settings_end_to_end() { "anonymous on public" ); - // Archive, then unarchive. The banner shows only while archived. let arch_csrf = csrf_for(&http, &bob).await; let archive = http .post_form( @@ -1050,7 +988,6 @@ async fn general_settings_end_to_end() { "banner after unarchive" ); - // A Write collaborator cannot reach the settings: GET and every POST are 403. let carol_page = http.get("/bob/gen/settings", Some(&carol)).await; assert_eq!(carol_page.status, 403, "write collaborator settings page"); let carol_csrf = csrf_for(&http, &carol).await; @@ -1080,7 +1017,6 @@ async fn general_settings_end_to_end() { "HEAD untouched by carol" ); - // No CSRF token, or a wrong one, is rejected on every General POST. let no_csrf = http .post_form( "/bob/gen/settings/general", @@ -1107,7 +1043,6 @@ async fn general_settings_end_to_end() { "visibility unchanged" ); - // An empty repo says so and keeps the current value. let empty_page = http.get("/bob/empty/settings", Some(&bob)).await; assert!( empty_page.body.contains("No branches yet"), diff --git a/crates/forge-e2e/tests/e2e/section_nav_e2e.rs b/crates/forge-e2e/tests/e2e/section_nav_e2e.rs index 276b9e9..a336650 100644 --- a/crates/forge-e2e/tests/e2e/section_nav_e2e.rs +++ b/crates/forge-e2e/tests/e2e/section_nav_e2e.rs @@ -1,97 +1,9 @@ -//! Black-box tests for the admin and settings section tabs: every page under `/admin` and -//! `/settings` shows the section's own tab row above the page, marks the current tab with -//! `aria-current="page"`, and has no " ยท "-joined link row. - -#![allow(dead_code)] - use crate::common::{Http, Server, bin, describe, launch, login, pick_ports, write_config}; use std::path::Path; use std::process::Command; const PW: &str = "tahinli-password-123"; -/// The `data-theme` attribute of ``, if the page sets one. -fn html_theme(body: &str) -> Option { - let doc = scraper::Html::parse_document(body); - doc.root_element().attr("data-theme").map(str::to_owned) -} - -/// The value of attribute `name` on ``, if the page sets it. -fn html_attr(body: &str, name: &str) -> Option { - let doc = scraper::Html::parse_document(body); - doc.root_element().attr(name).map(str::to_owned) -} - -/// The four colour attributes of ``, in the order light accent, dark accent, light base, -/// dark base. -fn html_colours(body: &str) -> [Option; 4] { - [ - html_attr(body, "data-accent-light"), - html_attr(body, "data-accent-dark"), - html_attr(body, "data-base-light"), - html_attr(body, "data-base-dark"), - ] -} - -/// The checked radio of each colour group, in the same order as `html_colours`. -fn checked_colours(body: &str) -> [Option; 4] { - [ - checked_radio(body, "accent_light"), - checked_radio(body, "accent_dark"), - checked_radio(body, "base_light"), - checked_radio(body, "base_dark"), - ] -} - -/// The value of the checked radio button in the group `name` on a page. -fn checked_radio(body: &str, name: &str) -> Option { - let doc = scraper::Html::parse_document(body); - let selector = - scraper::Selector::parse(&format!("input[type=\"radio\"][name=\"{name}\"][checked]")) - .expect("selector"); - doc.select(&selector) - .next() - .and_then(|el| el.value().attr("value")) - .map(str::to_owned) -} - -/// The option value that is selected in the `