From 03e747925036c3eb45cdc42cd177ae21013f5d0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 23 Oct 2026 16:09:09 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20e2e=20tests=20?= =?UTF-8?q?share=20one=20http=20harness=20instead=20of=2028=20copies?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move the Http client, Resp, cookie_named and login into common/http.rs and re-export them from common. The shared Http covers get, get_cookie, get_bearer, get_basic, post_form, stream and get_language, and Resp exposes header, location and set_cookies. 25 modules drop their local copies. oci, packages and browse keep their own harness because their responses are raw bytes. account_mail keeps its own cookie_named because it matches by prefix. --- .../forge-web/tests/e2e/account_mail_e2e.rs | 57 +----- crates/forge-web/tests/e2e/advisories_e2e.rs | 91 +-------- .../tests/e2e/branch_protection_e2e.rs | 113 +---------- crates/forge-web/tests/e2e/ci_e2e.rs | 114 +----------- crates/forge-web/tests/e2e/common/http.rs | 176 ++++++++++++++++++ crates/forge-web/tests/e2e/common/mod.rs | 4 + crates/forge-web/tests/e2e/discussions_e2e.rs | 113 +---------- crates/forge-web/tests/e2e/git_e2e.rs | 147 +-------------- crates/forge-web/tests/e2e/i18n_e2e.rs | 124 ++---------- crates/forge-web/tests/e2e/issue_close_e2e.rs | 107 +---------- crates/forge-web/tests/e2e/lfs_e2e.rs | 105 +---------- crates/forge-web/tests/e2e/merge_queue_e2e.rs | 115 +----------- crates/forge-web/tests/e2e/mirrors_e2e.rs | 102 +--------- crates/forge-web/tests/e2e/orgs_core_e2e.rs | 79 +------- crates/forge-web/tests/e2e/orgs_live_e2e.rs | 135 +------------- crates/forge-web/tests/e2e/orgs_ui_e2e.rs | 133 ++----------- crates/forge-web/tests/e2e/pulls_e2e.rs | 118 +----------- .../tests/e2e/repo_collaborators_e2e.rs | 117 +----------- crates/forge-web/tests/e2e/repo_rename_e2e.rs | 116 +----------- .../forge-web/tests/e2e/repo_settings_e2e.rs | 127 ++----------- .../forge-web/tests/e2e/repo_transfer_e2e.rs | 116 +----------- crates/forge-web/tests/e2e/section_nav_e2e.rs | 110 +---------- crates/forge-web/tests/e2e/snippets_e2e.rs | 124 ++---------- crates/forge-web/tests/e2e/stars_e2e.rs | 117 +----------- crates/forge-web/tests/e2e/ui_prefs_e2e.rs | 132 ++----------- crates/forge-web/tests/e2e/user_delete_e2e.rs | 103 +--------- crates/forge-web/tests/e2e/wiki_e2e.rs | 119 +----------- 27 files changed, 371 insertions(+), 2643 deletions(-) create mode 100644 crates/forge-web/tests/e2e/common/http.rs diff --git a/crates/forge-web/tests/e2e/account_mail_e2e.rs b/crates/forge-web/tests/e2e/account_mail_e2e.rs index c37e107..5098a49 100644 --- a/crates/forge-web/tests/e2e/account_mail_e2e.rs +++ b/crates/forge-web/tests/e2e/account_mail_e2e.rs @@ -2,72 +2,19 @@ //! 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::{launch_with, pick_ports}; +use crate::common::{Http, Resp, 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::{COOKIE, HeaderMap, SET_COOKIE}; +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"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - let mut req = self.client.get(format!("{}{path}", self.base)); - if let Some(cookie) = cookie { - req = req.header(COOKIE, cookie); - } - Self::finish(req).await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - let mut req = self.client.post(format!("{}{path}", self.base)).form(form); - if let Some(cookie) = cookie { - req = req.header(COOKIE, cookie); - } - Self::finish(req).await - } - - async fn finish(req: reqwest::RequestBuilder) -> Resp { - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - /// The `name=value` pair of the Set-Cookie header whose name starts with `prefix`. fn cookie_named(resp: &Resp, prefix: &str) -> Option { resp.headers diff --git a/crates/forge-web/tests/e2e/advisories_e2e.rs b/crates/forge-web/tests/e2e/advisories_e2e.rs index 0776938..1ce5da9 100644 --- a/crates/forge-web/tests/e2e/advisories_e2e.rs +++ b/crates/forge-web/tests/e2e/advisories_e2e.rs @@ -9,7 +9,8 @@ //! - a reader without Write gets a 404 on the page. use crate::common::{ - BIN, Server, input_value, launch_with, pick_ports, tool_on_path, write_config_with, + BIN, Http, Resp, Server, input_value, launch_with, login, pick_ports, tool_on_path, + write_config_with, }; use std::fs; use std::io::{Cursor, Write}; @@ -37,73 +38,6 @@ const OSV_RECORD: &str = r#"{ const LOCK_OLD: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"1.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n"; const LOCK_FIXED: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"2.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n"; -struct Resp { - status: u16, - set_cookies: Vec, - body: String, -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get_cookie(&self, path: &str, cookie: &str) -> Resp { - let req = self - .client - .get(format!("{}{path}", self.base)) - .header(reqwest::header::COOKIE, cookie); - send(req).await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - let mut req = self.client.post(format!("{}{path}", self.base)).form(form); - if let Some(cookie) = cookie { - req = req.header(reqwest::header::COOKIE, cookie); - } - send(req).await - } -} - -async fn send(req: reqwest::RequestBuilder) -> Resp { - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let set_cookies = res - .headers() - .get_all(reqwest::header::SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect(); - let body = res.text().await.unwrap_or_default(); - Resp { - status, - set_cookies, - body, - } -} - -/// Returns `name=value` for the cookie whose name ends with `suffix`. Cleared cookies are ignored. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies.iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// Runs git with credential helpers disabled. Panics on failure and returns trimmed stdout. fn git(cwd: &Path, args: &[&str]) -> String { @@ -204,27 +138,6 @@ fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { ); } -async fn login(http: &Http, username: &str, password: &str) -> String { - let page = http.get_cookie("/login", "").await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", password), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - async fn create_token(http: &Http, session: &str) -> String { let page = http.get_cookie("/settings/tokens", session).await; assert_eq!(page.status, 200, "GET /settings/tokens"); diff --git a/crates/forge-web/tests/e2e/branch_protection_e2e.rs b/crates/forge-web/tests/e2e/branch_protection_e2e.rs index 283e7c4..7ee99dc 100644 --- a/crates/forge-web/tests/e2e/branch_protection_e2e.rs +++ b/crates/forge-web/tests/e2e/branch_protection_e2e.rs @@ -3,102 +3,17 @@ //! while the server runs. Helpers mirror `git_e2e.rs`. use crate::common::{ - BIN, Ports, Server, describe, input_value, launch, pick_ports, relaunch, tool_on_path, - write_config, + BIN, Http, Ports, Server, describe, input_value, launch, login, pick_ports, relaunch, + tool_on_path, write_config, }; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; -use std::time::Duration; use forge_core::Store; -use reqwest::header::{LOCATION, SET_COOKIE}; const TAHINLI_PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - location: Option, - set_cookies: Vec, - body: String, -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), None) - .await - } - - async fn get_cookie(&self, path: &str, cookie: &str) -> Resp { - self.send( - self.client.get(format!("{}{path}", self.base)), - Some(cookie), - ) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let mut req = req; - if let Some(cookie) = cookie { - req = req.header(reqwest::header::COOKIE, cookie); - } - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let location = res - .headers() - .get(LOCATION) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned); - let set_cookies = res - .headers() - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect(); - let body = res.text().await.unwrap_or_default(); - Resp { - status, - location, - set_cookies, - body, - } - } -} - -/// Returns `name=value` for the cookie whose name ends with `suffix`. Cleared cookies are ignored. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies.iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { let out = Command::new(BIN) @@ -183,28 +98,6 @@ fn remote_sha(repo: &Path, reference: &str) -> String { .to_owned() } -/// Logs in through the real `/login` form and returns the `__Host-forge_session` cookie header. -async fn login(http: &Http, username: &str, password: &str) -> String { - let page = http.get("/login").await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", password), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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/tokens", session).await; @@ -250,7 +143,7 @@ async fn create_repo(http: &Http, session: &str, name: &str) { .await; assert_eq!(res.status, 303, "create repo {name}: {}", res.body); assert_eq!( - res.location.as_deref(), + res.location().as_deref(), Some(format!("/tahinli/{name}").as_str()) ); } diff --git a/crates/forge-web/tests/e2e/ci_e2e.rs b/crates/forge-web/tests/e2e/ci_e2e.rs index d17b77f..0faa112 100644 --- a/crates/forge-web/tests/e2e/ci_e2e.rs +++ b/crates/forge-web/tests/e2e/ci_e2e.rs @@ -10,7 +10,9 @@ //! - a fork pull request: it waits for approval, then runs without secrets; //! - a live log: `log.txt` streams while a job runs and ends when the job finishes. -use crate::common::{BIN, FAST_CLAIMS, Server, input_value, launch_with, pick_ports, write_config}; +use crate::common::{ + BIN, FAST_CLAIMS, Http, Server, input_value, launch_with, login, pick_ports, write_config, +}; use forge_ci::proto::{JobAssignment, Outcome, RegisterRequest}; use forge_runner::client::ForgeClient; use forge_runner::config::{Limits, RunnerConfig}; @@ -24,8 +26,6 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use tokio_util::sync::CancellationToken; -use reqwest::header::{LOCATION, SET_COOKIE}; - 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"; @@ -90,90 +90,6 @@ run = "echo never" needs = ["broken"] "#; -/// A parsed HTTP response. Only the parts the test needs are kept. -struct Resp { - status: u16, - location: Option, - set_cookies: Vec, - body: String, -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn get_bearer(&self, path: &str, token: &str) -> Resp { - let req = self - .client - .get(format!("{}{path}", self.base)) - .bearer_auth(token); - self.send(req, None).await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(reqwest::header::COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let location = res - .headers() - .get(LOCATION) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned); - let set_cookies = res - .headers() - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect(); - let body = res.text().await.unwrap_or_default(); - Resp { - status, - location, - set_cookies, - body, - } - } -} - -/// Returns `name=value` for the cookie whose name ends with `suffix`. Cleared cookies are ignored. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies.iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// The text of the first element matching `selector`. fn first_text(body: &str, selector: &str) -> String { @@ -282,28 +198,6 @@ async fn csrf_from(http: &Http, path: &str, session: &str) -> String { input_value(&page.body, "csrf") } -/// Logs in through the real `/login` form and returns the `__Host-forge_session` cookie header. -async fn login(http: &Http, username: &str, password: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", password), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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/tokens", session).await; @@ -340,7 +234,7 @@ async fn create_repo(http: &Http, session: &str, name: &str) { .await; assert_eq!(res.status, 303, "create repo {name}: {}", res.body); assert_eq!( - res.location.as_deref(), + res.location().as_deref(), Some(format!("/tahinli/{name}").as_str()) ); } diff --git a/crates/forge-web/tests/e2e/common/http.rs b/crates/forge-web/tests/e2e/common/http.rs new file mode 100644 index 0000000..2c0cf03 --- /dev/null +++ b/crates/forge-web/tests/e2e/common/http.rs @@ -0,0 +1,176 @@ +//! The HTTP client the e2e tests use against a running `forge serve`. A request can carry a +//! cookie or a bearer or basic credential, and a response keeps its status, headers and body +//! text. The login flow every test starts with lives here too. + +use std::time::Duration; + +use reqwest::header::{COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE}; + +use super::input_value; + +/// A received response. Headers are kept whole, so a test can read any of them. +pub struct Resp { + pub status: u16, + pub headers: HeaderMap, + pub body: String, +} + +impl Resp { + /// The first value of a header, when it is valid text. + pub fn header(&self, name: HeaderName) -> Option { + self.headers + .get(name) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned) + } + + /// The `Location` header, when there is one. + pub fn location(&self) -> Option { + self.header(LOCATION) + } + + /// Every `Set-Cookie` value, in the order the server sent them. Cleared cookies included. + pub fn set_cookies(&self) -> Vec { + self.headers + .get_all(SET_COOKIE) + .iter() + .filter_map(|v| v.to_str().ok().map(str::to_owned)) + .collect() + } +} + +/// A client bound to one listener. It never follows redirects. +pub struct Http { + pub client: reqwest::Client, + pub base: String, +} + +impl Http { + pub fn new(port: u16) -> Self { + Self::with_base(format!("http://127.0.0.1:{port}")) + } + + /// A client for an explicit base URL, such as a listener reached through another host name. + pub fn with_base(base: String) -> Self { + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(60)) + .build() + .expect("http client"); + Self { client, base } + } + + pub async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { + self.get_language(path, cookie, None).await + } + + /// `get` with an optional `Accept-Language` value. + pub async fn get_language( + &self, + path: &str, + cookie: Option<&str>, + language: Option<&str>, + ) -> Resp { + let mut req = self.client.get(format!("{}{path}", self.base)); + if let Some(language) = language { + req = req.header(reqwest::header::ACCEPT_LANGUAGE, language); + } + self.send(req, cookie).await + } + + /// `get` with the cookie header set to `cookie` exactly, even when it is empty. + pub async fn get_cookie(&self, path: &str, cookie: &str) -> Resp { + self.get(path, Some(cookie)).await + } + + pub async fn get_bearer(&self, path: &str, token: &str) -> Resp { + let req = self + .client + .get(format!("{}{path}", self.base)) + .bearer_auth(token); + self.send(req, None).await + } + + pub async fn get_basic(&self, path: &str, user: &str, password: &str) -> Resp { + let req = self + .client + .get(format!("{}{path}", self.base)) + .basic_auth(user, Some(password)); + self.send(req, None).await + } + + pub async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { + self.send( + self.client.post(format!("{}{path}", self.base)).form(form), + cookie, + ) + .await + } + + /// Opens a live stream as `cookie`, or anonymously. A stream that opens sends its `retry` + /// field first, which is read here, not treated as an event. + pub async fn stream(&self, path: &str, cookie: Option<&str>) -> reqwest::Response { + let mut req = self.client.get(format!("{}{path}", self.base)); + if let Some(cookie) = cookie { + req = req.header(COOKIE, cookie); + } + let mut res = req.send().await.expect("stream request"); + if res.status().is_success() { + let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk()) + .await + .expect("the retry field") + .expect("stream chunk") + .expect("stream still open"); + assert!(String::from_utf8_lossy(&retry).contains("retry: 1000")); + } + res + } + + /// Sends a prepared request, with `cookie` as its Cookie header when there is one. + pub async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { + let req = match cookie { + Some(cookie) => req.header(COOKIE, cookie), + None => req, + }; + let res = req.send().await.expect("http request"); + let status = res.status().as_u16(); + let headers = res.headers().clone(); + let body = res.text().await.expect("read body"); + Resp { + status, + headers, + body, + } + } +} + +/// Returns `name=value` for the cookie whose name ends with `suffix`. Cleared cookies are ignored. +pub fn cookie_named(resp: &Resp, suffix: &str) -> Option { + resp.set_cookies().iter().find_map(|set| { + let pair = set.split(';').next()?; + let (name, value) = pair.split_once('=')?; + (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) + }) +} + +/// 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; + assert_eq!(page.status, 200, "GET /login"); + let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); + let precsrf = input_value(&page.body, "precsrf"); + let res = http + .post_form( + "/login", + &[ + ("username", username), + ("password", password), + ("next", "/"), + ("precsrf", &precsrf), + ], + Some(&precsrf_cookie), + ) + .await; + assert_eq!(res.status, 303, "login as {username}: {}", res.body); + cookie_named(&res, "forge_session").expect("session cookie after login") +} diff --git a/crates/forge-web/tests/e2e/common/mod.rs b/crates/forge-web/tests/e2e/common/mod.rs index 4e22707..3a42540 100644 --- a/crates/forge-web/tests/e2e/common/mod.rs +++ b/crates/forge-web/tests/e2e/common/mod.rs @@ -15,6 +15,10 @@ use std::path::{Path, PathBuf}; use std::process::{Child, Command, ExitStatus, Output, Stdio}; use std::time::{Duration, Instant}; +mod http; + +pub use http::{Http, Resp, cookie_named, login}; + pub const BIN: &str = env!("CARGO_BIN_EXE_forge"); /// How long a freshly spawned server gets to answer on all three listeners. diff --git a/crates/forge-web/tests/e2e/discussions_e2e.rs b/crates/forge-web/tests/e2e/discussions_e2e.rs index ee608e0..3642685 100644 --- a/crates/forge-web/tests/e2e/discussions_e2e.rs +++ b/crates/forge-web/tests/e2e/discussions_e2e.rs @@ -3,90 +3,15 @@ //! an answer in Q&A, and the lock: once locked, a plain viewer's comment is refused while the //! owner can still write. -use crate::common::{BIN, input_value, launch, pick_ports, tool_on_path, write_config}; +use crate::common::{ + BIN, Http, input_value, launch, login, pick_ports, tool_on_path, write_config, +}; use std::path::Path; use std::process::Command; -use std::time::Duration; - -use reqwest::header::{LOCATION, SET_COOKIE}; const TAHINLI_PW: &str = "tahinli-password-123"; const BOB_PW: &str = "bob-password-4567"; -struct Resp { - status: u16, - location: Option, - set_cookies: Vec, - body: String, -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - let mut req = self.client.get(format!("{}{path}", self.base)); - if let Some(cookie) = cookie { - req = req.header(reqwest::header::COOKIE, cookie); - } - send(req).await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - let mut req = self.client.post(format!("{}{path}", self.base)).form(form); - if let Some(cookie) = cookie { - req = req.header(reqwest::header::COOKIE, cookie); - } - send(req).await - } -} - -async fn send(req: reqwest::RequestBuilder) -> Resp { - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let location = res - .headers() - .get(LOCATION) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned); - let set_cookies = res - .headers() - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect(); - let body = res.text().await.unwrap_or_default(); - Resp { - status, - location, - set_cookies, - body, - } -} - -/// Returns `name=value` for the cookie whose name ends with `suffix`. Cleared cookies are ignored. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies.iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { let out = Command::new(BIN) @@ -104,27 +29,6 @@ fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { ); } -async fn login(http: &Http, username: &str, password: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", password), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(precsrf_cookie.as_str()), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// Creates a public repo through `/new`. async fn create_repo(http: &Http, session: &str, name: &str) { let page = http.get("/new", Some(session)).await; @@ -145,7 +49,7 @@ async fn create_repo(http: &Http, session: &str, name: &str) { .await; assert_eq!(res.status, 303, "create repo {name}: {}", res.body); assert_eq!( - res.location.as_deref(), + res.location().as_deref(), Some(format!("/tahinli/{name}").as_str()) ); } @@ -233,7 +137,10 @@ async fn discussions_create_reply_answer_lock_and_toggle() { ) .await; assert_eq!(res.status, 303, "create: {}", res.body); - assert_eq!(res.location.as_deref(), Some("/tahinli/pub/discussions/1")); + assert_eq!( + res.location().as_deref(), + Some("/tahinli/pub/discussions/1") + ); let discussion = "/tahinli/pub/discussions/1"; // Bob answers at the top level, then replies to that comment. @@ -248,7 +155,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() { ) .await; assert_eq!(res.status, 303, "top comment: {}", res.body); - let top = anchored_id(res.location.as_deref()); + let top = anchored_id(res.location().as_deref()); let res = http .post_form( @@ -262,7 +169,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() { ) .await; assert_eq!(res.status, 303, "reply: {}", res.body); - let reply = anchored_id(res.location.as_deref()); + let reply = anchored_id(res.location().as_deref()); // A reply to a reply is refused, and the page says why. let res = http diff --git a/crates/forge-web/tests/e2e/git_e2e.rs b/crates/forge-web/tests/e2e/git_e2e.rs index 588ec79..97dd090 100644 --- a/crates/forge-web/tests/e2e/git_e2e.rs +++ b/crates/forge-web/tests/e2e/git_e2e.rs @@ -4,127 +4,18 @@ //! Cookies are handled by hand: the session cookie is `__Host-forge_session` with `Secure`, so a //! cookie jar would not send it over plain http. The test parses `Set-Cookie` and sends `Cookie`. -use crate::common::{BIN, describe, input_value, launch, pick_ports, tool_on_path, write_config}; +use crate::common::{ + BIN, Http, describe, input_value, launch, login, pick_ports, tool_on_path, write_config, +}; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; -use std::time::Duration; -use reqwest::header::{LOCATION, SET_COOKIE, WWW_AUTHENTICATE}; +use reqwest::header::WWW_AUTHENTICATE; const TAHINLI_PW: &str = "tahinli-password-123"; const BOB_PW: &str = "bob-password-4567"; -/// A parsed HTTP response. Only the parts the test needs are kept. -struct Resp { - status: u16, - location: Option, - www_authenticate: Option, - set_cookies: Vec, - body: String, -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), None, None) - .await - } - - async fn get_cookie(&self, path: &str, cookie: &str) -> Resp { - self.send( - self.client.get(format!("{}{path}", self.base)), - Some(cookie), - None, - ) - .await - } - - async fn get_basic(&self, path: &str, user: &str, password: &str) -> Resp { - self.send( - self.client.get(format!("{}{path}", self.base)), - None, - Some((user, password)), - ) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - None, - ) - .await - } - - async fn send( - &self, - req: reqwest::RequestBuilder, - cookie: Option<&str>, - basic: Option<(&str, &str)>, - ) -> Resp { - let mut req = req; - if let Some(cookie) = cookie { - req = req.header(reqwest::header::COOKIE, cookie); - } - if let Some((user, password)) = basic { - req = req.basic_auth(user, Some(password)); - } - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let location = header_text(&res, LOCATION); - let www_authenticate = header_text(&res, WWW_AUTHENTICATE); - let set_cookies = res - .headers() - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect(); - let body = res.text().await.unwrap_or_default(); - Resp { - status, - location, - www_authenticate, - set_cookies, - body, - } - } -} - -fn header_text(res: &reqwest::Response, name: reqwest::header::HeaderName) -> Option { - res.headers() - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) -} - -/// Returns `name=value` for the cookie whose name ends with `suffix`, e.g. `forge_session` -/// matches `__Host-forge_session`. Cleared cookies (empty value) are ignored. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies.iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { let out = Command::new(BIN) @@ -241,28 +132,6 @@ fn read(path: PathBuf) -> String { fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())) } -/// Logs in through the real `/login` form and returns the `__Host-forge_session` cookie header. -async fn login(http: &Http, username: &str, password: &str) -> String { - let page = http.get("/login").await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", password), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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/tokens", session).await; @@ -328,7 +197,7 @@ async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) { .await; assert_eq!(res.status, 303, "create repo {name}: {}", res.body); assert_eq!( - res.location.as_deref(), + res.location().as_deref(), Some(format!("/tahinli/{name}").as_str()) ); } @@ -438,10 +307,10 @@ async fn git_end_to_end() { "anonymous clone of private repo", ); let refs_path = "/tahinli/priv.git/info/refs?service=git-upload-pack"; - let anon_refs = http.get(refs_path).await; + let anon_refs = http.get(refs_path, None).await; assert_eq!(anon_refs.status, 401, "anonymous info/refs on private repo"); assert!( - anon_refs.www_authenticate.is_some(), + anon_refs.header(WWW_AUTHENTICATE).is_some(), "401 must carry WWW-Authenticate" ); @@ -545,7 +414,7 @@ async fn git_end_to_end() { assert_eq!(no_csrf.status, 403, "POST /new without csrf"); // Negative: the dumb protocol (info/refs without ?service=) is forbidden. - let dumb = http.get("/tahinli/pub.git/info/refs").await; + let dumb = http.get("/tahinli/pub.git/info/refs", None).await; assert_eq!(dumb.status, 403, "info/refs without service"); assert!( dumb.body.contains("dumb protocol"), diff --git a/crates/forge-web/tests/e2e/i18n_e2e.rs b/crates/forge-web/tests/e2e/i18n_e2e.rs index 30deddc..f5678bc 100644 --- a/crates/forge-web/tests/e2e/i18n_e2e.rs +++ b/crates/forge-web/tests/e2e/i18n_e2e.rs @@ -3,90 +3,14 @@ use std::path::{Path, PathBuf}; use std::process::Command; -use std::time::Duration; -use crate::common::{BIN, Server, describe, input_value, launch, pick_ports, write_config}; +use crate::common::{ + BIN, Http, Server, describe, input_value, launch, login, pick_ports, write_config, +}; use forge_core::Store; -use reqwest::header::{ACCEPT_LANGUAGE, COOKIE, HeaderMap, SET_COOKIE}; const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>, language: Option<&str>) -> Resp { - let mut req = self.client.get(format!("{}{path}", self.base)); - if let Some(language) = language { - req = req.header(ACCEPT_LANGUAGE, language); - } - self.send(req, cookie).await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded. fn admin(config: &Path, args: &[&str]) { @@ -105,27 +29,6 @@ fn admin(config: &Path, args: &[&str]) { ); } -async fn login(http: &Http, username: &str) -> String { - let page = http.get("/login", None, None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", PW), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// A running server plus the temp dir it lives in. The dir lasts as long as the test. struct Env { _root: tempfile::TempDir, @@ -163,7 +66,7 @@ async fn anonymous_pages_follow_the_browser_language() { let turkish = env .http - .get("/login", None, Some("tr-TR,tr;q=0.9,en;q=0.8")) + .get_language("/login", None, Some("tr-TR,tr;q=0.9,en;q=0.8")) .await; assert_eq!(turkish.status, 200); assert!( @@ -180,7 +83,10 @@ async fn anonymous_pages_follow_the_browser_language() { "no English label left" ); - let english = env.http.get("/login", None, Some("en-US,en;q=0.9")).await; + let english = env + .http + .get_language("/login", None, Some("en-US,en;q=0.9")) + .await; assert!( english.body.contains(", - set_cookies: Vec, - body: String, -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get_cookie(&self, path: &str, cookie: &str) -> Resp { - let req = self - .client - .get(format!("{}{path}", self.base)) - .header(reqwest::header::COOKIE, cookie); - send(req).await - } - - async fn get(&self, path: &str) -> Resp { - send(self.client.get(format!("{}{path}", self.base))).await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - let mut req = self.client.post(format!("{}{path}", self.base)).form(form); - if let Some(cookie) = cookie { - req = req.header(reqwest::header::COOKIE, cookie); - } - send(req).await - } -} - -async fn send(req: reqwest::RequestBuilder) -> Resp { - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let location = res - .headers() - .get(LOCATION) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned); - let set_cookies = res - .headers() - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect(); - let body = res.text().await.unwrap_or_default(); - Resp { - status, - location, - set_cookies, - body, - } -} - -/// Returns `name=value` for the cookie whose name ends with `suffix`. Cleared cookies are ignored. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies.iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { let out = Command::new(BIN) @@ -156,28 +79,6 @@ fn commit_file(repo: &Path, name: &str, message: &str) -> String { git(repo, &["rev-parse", "HEAD"]) } -/// Logs in through the real `/login` form and returns the session cookie header. -async fn login(http: &Http, username: &str, password: &str) -> String { - let page = http.get("/login").await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", password), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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/tokens", session).await; @@ -224,7 +125,7 @@ async fn create_repo(http: &Http, session: &str, name: &str) { .await; assert_eq!(res.status, 303, "create repo {name}: {}", res.body); assert_eq!( - res.location.as_deref(), + res.location().as_deref(), Some(format!("/tahinli/{name}").as_str()) ); } diff --git a/crates/forge-web/tests/e2e/lfs_e2e.rs b/crates/forge-web/tests/e2e/lfs_e2e.rs index fbb3deb..5a17459 100644 --- a/crates/forge-web/tests/e2e/lfs_e2e.rs +++ b/crates/forge-web/tests/e2e/lfs_e2e.rs @@ -5,93 +5,14 @@ //! Git config is isolated from the developer's machine: `HOME` and `GIT_CONFIG_GLOBAL` point into //! the test's temp dir. -use crate::common::{BIN, describe, input_value, launch, pick_ports, write_config}; +use crate::common::{BIN, Http, describe, input_value, launch, login, pick_ports, write_config}; use std::fs; use std::path::Path; use std::process::{Command, Output}; -use std::time::Duration; - -use reqwest::header::{LOCATION, SET_COOKIE}; const TAHINLI_PW: &str = "tahinli-password-123"; const FILE_SIZE: usize = 100 * 1024; -/// A parsed HTTP response. Only the parts the test needs are kept. -struct Resp { - status: u16, - location: Option, - set_cookies: Vec, - body: String, -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(reqwest::header::COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let location = res - .headers() - .get(LOCATION) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned); - let set_cookies = res - .headers() - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect(); - let body = res.text().await.unwrap_or_default(); - Resp { - status, - location, - set_cookies, - body, - } - } -} - -/// Returns `name=value` for the cookie whose name ends with `suffix`. Cleared cookies are ignored. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies.iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { let out = Command::new(BIN) @@ -140,28 +61,6 @@ fn payload() -> Vec { .collect() } -/// Logs in through the real `/login` form and returns the `__Host-forge_session` cookie header. -async fn login(http: &Http, username: &str, password: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", password), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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("/settings/tokens", Some(session)).await; @@ -208,7 +107,7 @@ async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) { .await; assert_eq!(res.status, 303, "create repo {name}: {}", res.body); assert_eq!( - res.location.as_deref(), + res.location().as_deref(), Some(format!("/tahinli/{name}").as_str()) ); } diff --git a/crates/forge-web/tests/e2e/merge_queue_e2e.rs b/crates/forge-web/tests/e2e/merge_queue_e2e.rs index 0014a83..9455028 100644 --- a/crates/forge-web/tests/e2e/merge_queue_e2e.rs +++ b/crates/forge-web/tests/e2e/merge_queue_e2e.rs @@ -10,7 +10,8 @@ #![allow(dead_code)] use crate::common::{ - BIN, FAST_CLAIMS, Server, input_value, launch_with, pick_ports, tool_on_path, write_config, + BIN, FAST_CLAIMS, Http, Server, input_value, launch_with, login, pick_ports, tool_on_path, + write_config, }; use forge_ci::proto::{JobAssignment, RegisterRequest}; use forge_runner::client::ForgeClient; @@ -25,98 +26,12 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use tokio_util::sync::CancellationToken; -use reqwest::header::{LOCATION, SET_COOKIE}; - 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"]; -/// A parsed HTTP response. Only the parts the test needs are kept. -struct Resp { - status: u16, - location: Option, - set_cookies: Vec, - body: String, -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn get_bearer(&self, path: &str, token: &str) -> Resp { - let req = self - .client - .get(format!("{}{path}", self.base)) - .bearer_auth(token); - self.send(req, None).await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(reqwest::header::COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let location = res - .headers() - .get(LOCATION) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned); - let set_cookies = res - .headers() - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect(); - let body = res.text().await.unwrap_or_default(); - Resp { - status, - location, - set_cookies, - body, - } - } -} - -/// Returns `name=value` for the cookie whose name ends with `suffix`. Cleared cookies are ignored. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies.iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// The text of the first element matching `selector`. fn first_text(body: &str, selector: &str) -> String { @@ -225,28 +140,6 @@ async fn csrf_from(http: &Http, path: &str, session: &str) -> String { input_value(&page.body, "csrf") } -/// Logs in through the real `/login` form and returns the `__Host-forge_session` cookie header. -async fn login(http: &Http, username: &str, password: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", password), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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/tokens", session).await; @@ -283,7 +176,7 @@ async fn create_repo(http: &Http, session: &str, name: &str) { .await; assert_eq!(res.status, 303, "create repo {name}: {}", res.body); assert_eq!( - res.location.as_deref(), + res.location().as_deref(), Some(format!("/tahinli/{name}").as_str()) ); } @@ -569,7 +462,7 @@ async fn open_pull(http: &Http, session: &str, work: &Path, branch: &str, file: ) .await; assert_eq!(res.status, 303, "open pull for {branch}: {}", res.body); - let location = res.location.expect("pull location"); + let location = res.location().expect("pull location"); location .rsplit('/') .next() diff --git a/crates/forge-web/tests/e2e/mirrors_e2e.rs b/crates/forge-web/tests/e2e/mirrors_e2e.rs index a2931d0..ecbb98c 100644 --- a/crates/forge-web/tests/e2e/mirrors_e2e.rs +++ b/crates/forge-web/tests/e2e/mirrors_e2e.rs @@ -10,7 +10,7 @@ //! - the mirror pages and the server log never contain the access token. use crate::common::{ - BIN, Server, input_value, launch_with, pick_ports, tool_on_path, write_config_with, + BIN, Http, Server, input_value, launch_with, login, pick_ports, tool_on_path, write_config_with, }; use std::collections::BTreeSet; use std::fs; @@ -18,8 +18,6 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use std::time::{Duration, Instant}; -use reqwest::header::{LOCATION, SET_COOKIE}; - const TAHINLI_PW: &str = "tahinli-password-123"; const WEBHOOK_TOML: &str = "\n[webhooks]\nallow_http = true\nallowed_hosts = [\"127.0.0.1\"]\n\n[mirrors]\npush_debounce_secs = 0\n"; const SYNC_TIMEOUT: Duration = Duration::from_secs(30); @@ -27,80 +25,6 @@ const SYNC_TIMEOUT: Duration = Duration::from_secs(30); /// worker wakes on the push itself, so this only needs room for the git sync. const PUSH_TIMEOUT: Duration = Duration::from_secs(90); -struct Resp { - status: u16, - location: Option, - set_cookies: Vec, - body: String, -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get_cookie(&self, path: &str, cookie: &str) -> Resp { - let req = self - .client - .get(format!("{}{path}", self.base)) - .header(reqwest::header::COOKIE, cookie); - send(req).await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - let mut req = self.client.post(format!("{}{path}", self.base)).form(form); - if let Some(cookie) = cookie { - req = req.header(reqwest::header::COOKIE, cookie); - } - send(req).await - } -} - -async fn send(req: reqwest::RequestBuilder) -> Resp { - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let location = res - .headers() - .get(LOCATION) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned); - let set_cookies = res - .headers() - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect(); - let body = res.text().await.unwrap_or_default(); - Resp { - status, - location, - set_cookies, - body, - } -} - -/// Returns `name=value` for the cookie whose name ends with `suffix`. Cleared cookies are ignored. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies.iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// The `action` of every form whose action ends with `suffix`, in page order. fn form_actions(body: &str, suffix: &str) -> Vec { @@ -244,28 +168,6 @@ async fn wait_for(what: &str, check: impl Fn() -> bool) { } } -/// Logs in through the real `/login` form and returns the session cookie header. -async fn login(http: &Http, username: &str, password: &str) -> String { - let page = http.get_cookie("/login", "").await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", password), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// The session's CSRF token, scraped from the token settings page. async fn csrf_token(http: &Http, session: &str) -> String { let page = http.get_cookie("/settings/tokens", session).await; @@ -320,7 +222,7 @@ async fn new_repo(http: &Http, session: &str, name: &str, mirror: Option<(&str, let res = http.post_form("/new", &form, Some(session)).await; assert_eq!(res.status, 303, "create repo {name}: {}", res.body); assert_eq!( - res.location.as_deref(), + res.location().as_deref(), Some(format!("/tahinli/{name}").as_str()) ); } diff --git a/crates/forge-web/tests/e2e/orgs_core_e2e.rs b/crates/forge-web/tests/e2e/orgs_core_e2e.rs index 0988338..c6a4b0e 100644 --- a/crates/forge-web/tests/e2e/orgs_core_e2e.rs +++ b/crates/forge-web/tests/e2e/orgs_core_e2e.rs @@ -3,7 +3,9 @@ //! this starts the real `forge` binary and drives it over HTTP. The org rows and their credentials //! are written straight into the database before the server starts. -use crate::common::{BIN, Server, describe, input_value, launch, pick_ports, write_config}; +use crate::common::{ + BIN, Http, Resp, Server, cookie_named, describe, input_value, launch, pick_ports, write_config, +}; use std::future::Future; use std::path::{Path, PathBuf}; use std::process::Command; @@ -11,7 +13,6 @@ use std::time::Duration; use forge_core::token::hash_token; use forge_core::{Store, Visibility}; -use reqwest::header::{COOKIE, HeaderMap, SET_COOKIE}; /// Each test starts a server on ports picked just before, so the tests run one at a time. static SERIAL: std::sync::LazyLock> = @@ -22,80 +23,6 @@ const PW: &str = "tahinli-password-123"; const ORG_TOKEN: &str = "forge_org_token_for_tests_0123456789"; const ORG_SESSION: &str = "org-session-token-for-tests-0123456789"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - let req = self.client.get(format!("{}{path}", self.base)); - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - Self::finish(req).await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - let req = self.client.post(format!("{}{path}", self.base)).form(form); - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - Self::finish(req).await - } - - async fn finish(req: reqwest::RequestBuilder) -> Resp { - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded. fn admin(config: &Path, args: &[&str]) { diff --git a/crates/forge-web/tests/e2e/orgs_live_e2e.rs b/crates/forge-web/tests/e2e/orgs_live_e2e.rs index 06e0d2a..7510077 100644 --- a/crates/forge-web/tests/e2e/orgs_live_e2e.rs +++ b/crates/forge-web/tests/e2e/orgs_live_e2e.rs @@ -2,14 +2,15 @@ //! with a seeded org (owner tahinli, member bob, a team), and the test drives the writes over HTTP //! and reads each stream. It also checks that each stream refuses the viewers its page refuses. -use crate::common::{BIN, describe, input_value, launch, pick_ports, tool_on_path, write_config}; +use crate::common::{ + BIN, Http, describe, input_value, launch, login, pick_ports, tool_on_path, write_config, +}; use std::path::Path; use std::process::{Command, Output}; use std::time::Duration; use forge_core::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings}; use forge_core::{Role, Store, Visibility}; -use reqwest::header::{COOKIE, HeaderMap, LOCATION, SET_COOKIE}; /// Each test starts its own server, so the tests run one at a time. static SERIAL: std::sync::LazyLock> = @@ -17,105 +18,6 @@ static SERIAL: std::sync::LazyLock> = const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn location(&self) -> Option { - self.headers - .get(LOCATION) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } - - /// Opens a live stream as `cookie`, or anonymously. A stream that opens sends its `retry` - /// field first, which is read here, not treated as an event. - async fn stream(&self, path: &str, cookie: Option<&str>) -> reqwest::Response { - let mut req = self.client.get(format!("{}{path}", self.base)); - if let Some(cookie) = cookie { - req = req.header(COOKIE, cookie); - } - let mut res = req.send().await.expect("stream request"); - if res.status().is_success() { - let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk()) - .await - .expect("the retry field") - .expect("stream chunk") - .expect("stream still open"); - assert!(String::from_utf8_lossy(&retry).contains("retry: 1000")); - } - res - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// The `data-live` value of the first element that names a stream, if any. fn live_url(body: &str) -> Option { @@ -145,27 +47,6 @@ fn admin(config: &Path, args: &[&str]) -> Output { out } -async fn login(http: &Http, username: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", PW), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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/tokens", Some(session)).await; @@ -235,9 +116,9 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() { let (_server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); - let tahinli = login(&http, "tahinli").await; - let bob = login(&http, "bob").await; - let dana = login(&http, "dana").await; + let tahinli = login(&http, "tahinli", PW).await; + let bob = login(&http, "bob", PW).await; + let dana = login(&http, "dana", PW).await; let csrf = csrf_for(&http, &tahinli).await; // Each page names its stream, and the stream is served at that URL. @@ -438,8 +319,8 @@ async fn private_linked_repo_is_hidden_from_a_viewer_who_cannot_read_it() { let (_server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); - let tahinli = login(&http, "tahinli").await; - let bob = login(&http, "bob").await; + let tahinli = login(&http, "tahinli", PW).await; + let bob = login(&http, "bob", PW).await; let csrf = csrf_for(&http, &tahinli).await; let team_page = format!("/org/acme/teams/{team_id}"); diff --git a/crates/forge-web/tests/e2e/orgs_ui_e2e.rs b/crates/forge-web/tests/e2e/orgs_ui_e2e.rs index f76bda1..bf1068d 100644 --- a/crates/forge-web/tests/e2e/orgs_ui_e2e.rs +++ b/crates/forge-web/tests/e2e/orgs_ui_e2e.rs @@ -4,16 +4,16 @@ //! handled by hand, as in `repo_collaborators_e2e.rs`. use crate::common::{ - BIN, describe, input_value, launch, launch_with, pick_ports, tool_on_path, write_config, + BIN, Http, Resp, describe, input_value, launch, launch_with, login, pick_ports, tool_on_path, + write_config, }; use std::fs; use std::path::Path; use std::process::{Command, Output}; -use std::time::Duration; use forge_core::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings}; use forge_core::{Role, Store, Visibility}; -use reqwest::header::{COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE}; +use reqwest::header::LOCATION; /// Each test starts its own server, so the tests run one at a time. static SERIAL: std::sync::LazyLock> = @@ -21,86 +21,6 @@ static SERIAL: std::sync::LazyLock> = const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn header(&self, name: HeaderName) -> Option { - self.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// The value of the selected option of the `` on a page. /// Text of the first state badge on a page, e.g. `Open`, `Closed` or `Merged`. fn state_badge(body: &str) -> String { @@ -201,28 +125,6 @@ fn parent_count(dir: &Path, commit: &str) -> usize { line.split_whitespace().count() - 1 } -/// Logs in through the real `/login` form and returns the session cookie header. -async fn login(http: &Http, username: &str, password: &str) -> String { - let page = http.get("/login").await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", password), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// The session's CSRF token, scraped from the token settings page. async fn csrf_token(http: &Http, session: &str) -> String { let page = http.get_cookie("/settings/tokens", session).await; @@ -274,7 +176,7 @@ async fn create_repo(http: &Http, session: &str, name: &str) { .await; assert_eq!(res.status, 303, "create repo {name}: {}", res.body); assert_eq!( - res.location.as_deref(), + res.location().as_deref(), Some(format!("/tahinli/{name}").as_str()) ); } @@ -362,7 +264,7 @@ async fn open_pull(http: &Http, session: &str, base: &str, head: &str, title: &s ) .await; assert_eq!(res.status, 303, "open pull {head}: {}", res.body); - let location = res.location.expect("redirect to the pull"); + let location = res.location().expect("redirect to the pull"); location .rsplit('/') .next() @@ -385,7 +287,7 @@ async fn open_issue(http: &Http, session: &str, title: &str) -> u32 { ) .await; assert_eq!(res.status, 303, "create issue: {}", res.body); - let location = res.location.expect("redirect to the issue"); + let location = res.location().expect("redirect to the issue"); location .rsplit('/') .next() @@ -465,7 +367,7 @@ async fn same_repo_pull_merges_and_closes_issue() { let res = merge(&b.http, &tahinli, 2, "merge").await; assert_eq!(res.status, 303, "merge: {}", res.body); - assert_eq!(res.location.as_deref(), Some("/tahinli/r/pulls/2")); + assert_eq!(res.location().as_deref(), Some("/tahinli/r/pulls/2")); let url = remote(b.http_port, "tahinli", &token, "tahinli", "r"); let main_sha = remote_sha(&b.dir, &url, "main"); @@ -735,7 +637,7 @@ async fn fork_pull_squash_merge_credits_contributor() { .post_form(&format!("{REPO_PATH}/fork"), &[("csrf", &csrf)], Some(&bob)) .await; assert_eq!(fork.status, 303, "fork: {}\n{}", fork.body, server_log(&b)); - assert_eq!(fork.location.as_deref(), Some("/bob/r")); + assert_eq!(fork.location().as_deref(), Some("/bob/r")); let bob_url = remote(b.http_port, "bob", &bob_token, "bob", "r"); let bob_work = clone(&bob_url, &b.dir.join("bob-work")); @@ -823,7 +725,7 @@ async fn conflicting_pull_cannot_merge() { server_log(&b) ); assert_eq!( - res.location.as_deref(), + res.location().as_deref(), Some(format!("{REPO_PATH}/pulls/{number}?merge_error=conflict").as_str()), "refusal redirects back to the pull with the conflict code" ); diff --git a/crates/forge-web/tests/e2e/repo_collaborators_e2e.rs b/crates/forge-web/tests/e2e/repo_collaborators_e2e.rs index 8be1b7d..a24fe0c 100644 --- a/crates/forge-web/tests/e2e/repo_collaborators_e2e.rs +++ b/crates/forge-web/tests/e2e/repo_collaborators_e2e.rs @@ -2,97 +2,19 @@ //! seed users and repos through the store before the server starts, and then drive the page and //! its POST forms over HTTP. Cookies are handled by hand (see `repo_settings_e2e.rs`). -use crate::common::{BIN, describe, input_value, launch, pick_ports, tool_on_path, write_config}; +use crate::common::{ + BIN, Http, Resp, cookie_named, describe, input_value, launch, login, pick_ports, tool_on_path, + write_config, +}; use std::fs; use std::path::Path; use std::process::{Command, Output}; -use std::time::Duration; use forge_core::{Role, Store, Visibility}; -use reqwest::header::{COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE}; +use reqwest::header::LOCATION; const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn header(&self, name: HeaderName) -> Option { - self.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded. fn admin(config: &Path, args: &[&str]) -> Output { @@ -112,27 +34,6 @@ fn admin(config: &Path, args: &[&str]) -> Output { out } -async fn login(http: &Http, username: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", PW), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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/tokens", Some(session)).await; @@ -238,10 +139,10 @@ async fn repo_collaborators_end_to_end() { let (_server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); - let olivia = login(&http, "olivia").await; - let bob = login(&http, "bob").await; - let carol = login(&http, "carol").await; - let wendy = login(&http, "wendy").await; + let olivia = login(&http, "olivia", PW).await; + let bob = login(&http, "bob", PW).await; + let carol = login(&http, "carol", PW).await; + let wendy = login(&http, "wendy", PW).await; let page = "/olivia/priv/settings/collaborators"; let add = "/olivia/priv/settings/collaborators/add"; diff --git a/crates/forge-web/tests/e2e/repo_rename_e2e.rs b/crates/forge-web/tests/e2e/repo_rename_e2e.rs index 96b581d..021eac8 100644 --- a/crates/forge-web/tests/e2e/repo_rename_e2e.rs +++ b/crates/forge-web/tests/e2e/repo_rename_e2e.rs @@ -5,97 +5,18 @@ //! 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::{BIN, describe, input_value, launch, pick_ports, tool_on_path, write_config}; +use crate::common::{ + BIN, Http, Resp, describe, input_value, launch, login, pick_ports, tool_on_path, write_config, +}; use std::fs; use std::path::Path; use std::process::{Command, Output}; -use std::time::Duration; use forge_core::{Role, Store, Visibility}; -use reqwest::header::{COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE}; +use reqwest::header::LOCATION; const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn header(&self, name: HeaderName) -> Option { - self.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// The `action` of the first form on a page whose action ends with `suffix`. fn form_action(body: &str, suffix: &str) -> String { @@ -125,27 +46,6 @@ fn admin(config: &Path, args: &[&str]) { ); } -async fn login(http: &Http, username: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", PW), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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/tokens", Some(session)).await; @@ -306,10 +206,10 @@ async fn repo_rename_end_to_end() { let (server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); - let bob = login(&http, "bob").await; - let carol = login(&http, "carol").await; - let dave = login(&http, "dave").await; - let eve = login(&http, "eve").await; + let bob = login(&http, "bob", PW).await; + let carol = login(&http, "carol", PW).await; + let dave = login(&http, "dave", PW).await; + let eve = login(&http, "eve", PW).await; let bob_token = create_token(&http, &bob, "rename-e2e").await; // Bob pushes a commit with a `src` directory to the public repo, so the tree path can be checked. diff --git a/crates/forge-web/tests/e2e/repo_settings_e2e.rs b/crates/forge-web/tests/e2e/repo_settings_e2e.rs index 47a69f7..6c31652 100644 --- a/crates/forge-web/tests/e2e/repo_settings_e2e.rs +++ b/crates/forge-web/tests/e2e/repo_settings_e2e.rs @@ -4,97 +4,19 @@ //! 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::{BIN, describe, input_value, launch, pick_ports, tool_on_path, write_config}; +use crate::common::{ + BIN, Http, Resp, cookie_named, describe, input_value, launch, login, pick_ports, tool_on_path, + write_config, +}; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; -use std::time::Duration; use forge_core::{Role, Store, Visibility}; -use reqwest::header::{COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE}; +use reqwest::header::LOCATION; const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn header(&self, name: HeaderName) -> Option { - self.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded. fn admin(config: &Path, args: &[&str]) -> Output { @@ -114,27 +36,6 @@ fn admin(config: &Path, args: &[&str]) -> Output { out } -async fn login(http: &Http, username: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", PW), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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/tokens", Some(session)).await; @@ -223,9 +124,9 @@ async fn repo_settings_end_to_end() { let (server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); - let bob = login(&http, "bob").await; - let carol = login(&http, "carol").await; - let tahinli = login(&http, "tahinli").await; + let bob = login(&http, "bob", PW).await; + 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; @@ -424,7 +325,7 @@ async fn repo_settings_deletes_rows_when_repo_dir_is_missing() { let (server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); - let bob = login(&http, "bob").await; + let bob = login(&http, "bob", PW).await; let csrf = csrf_for(&http, &bob).await; let deleted = http .post_form( @@ -538,9 +439,9 @@ async fn branch_protection_end_to_end() { let (server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); - let bob = login(&http, "bob").await; - let carol = login(&http, "carol").await; - let dan = login(&http, "dan").await; + let bob = login(&http, "bob", PW).await; + 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", Some(&bob)).await; @@ -910,8 +811,8 @@ async fn general_settings_end_to_end() { let (server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); - let bob = login(&http, "bob").await; - let carol = login(&http, "carol").await; + 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; diff --git a/crates/forge-web/tests/e2e/repo_transfer_e2e.rs b/crates/forge-web/tests/e2e/repo_transfer_e2e.rs index 78c076f..47c7fd8 100644 --- a/crates/forge-web/tests/e2e/repo_transfer_e2e.rs +++ b/crates/forge-web/tests/e2e/repo_transfer_e2e.rs @@ -5,97 +5,18 @@ //! 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::{BIN, describe, input_value, launch, pick_ports, tool_on_path, write_config}; +use crate::common::{ + BIN, Http, Resp, describe, input_value, launch, login, pick_ports, tool_on_path, write_config, +}; use std::fs; use std::process::Command; -use std::time::Duration; use forge_core::store::orgs::OrgMemberRole; use forge_core::{Store, Visibility}; -use reqwest::header::{COOKIE, HeaderMap, LOCATION, SET_COOKIE}; +use reqwest::header::LOCATION; const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn header(&self, name: reqwest::header::HeaderName) -> Option { - self.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// The `action` of the first form on a page whose action ends with `suffix`. Panics when none. fn form_action(body: &str, suffix: &str) -> String { @@ -125,27 +46,6 @@ fn admin(config: &std::path::Path, args: &[&str]) { ); } -async fn login(http: &Http, username: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", PW), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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/tokens", Some(session)).await; @@ -237,10 +137,10 @@ async fn repo_transfer_offers_declines_cancels_and_org_targets() { let (_server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); - let bob = login(&http, "bob").await; - let carol = login(&http, "carol").await; - let dave = login(&http, "dave").await; - let eve = login(&http, "eve").await; + let bob = login(&http, "bob", PW).await; + let carol = login(&http, "carol", PW).await; + let dave = login(&http, "dave", PW).await; + let eve = login(&http, "eve", PW).await; // Offer, then decline as carol from the inbox. The repo stays with bob. let offered = offer(&http, &bob, "bob", "priv", "carol").await; diff --git a/crates/forge-web/tests/e2e/section_nav_e2e.rs b/crates/forge-web/tests/e2e/section_nav_e2e.rs index f317191..d2a630a 100644 --- a/crates/forge-web/tests/e2e/section_nav_e2e.rs +++ b/crates/forge-web/tests/e2e/section_nav_e2e.rs @@ -4,95 +4,12 @@ #![allow(dead_code)] -use crate::common::{BIN, Server, describe, input_value, launch, pick_ports, write_config}; +use crate::common::{BIN, Http, Server, describe, launch, login, pick_ports, write_config}; use std::path::Path; use std::process::Command; -use std::time::Duration; - -use reqwest::header::{COOKIE, HeaderMap, HeaderName, SET_COOKIE}; const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn header(&self, name: HeaderName) -> Option { - self.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// The `data-theme` attribute of ``, if the page sets one. fn html_theme(body: &str) -> Option { @@ -192,27 +109,6 @@ fn admin(config: &Path, args: &[&str]) { ); } -async fn login(http: &Http, username: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", PW), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// A running server with user `tahinli`. The temp dir lives as long as the test. struct Env { _root: tempfile::TempDir, @@ -267,7 +163,7 @@ fn assert_section(body: &str, current: &str, hrefs: &[&str]) { #[tokio::test] async fn admin_pages_get_the_admin_sidebar() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let want = [ "/admin/users", "/admin/invites", @@ -292,7 +188,7 @@ async fn admin_pages_get_the_admin_sidebar() { #[tokio::test] async fn settings_pages_get_the_settings_sidebar() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let want = [ "/settings/profile", "/settings/keys", diff --git a/crates/forge-web/tests/e2e/snippets_e2e.rs b/crates/forge-web/tests/e2e/snippets_e2e.rs index b3168f0..6e1ee47 100644 --- a/crates/forge-web/tests/e2e/snippets_e2e.rs +++ b/crates/forge-web/tests/e2e/snippets_e2e.rs @@ -2,92 +2,17 @@ //! drives it over HTTP. Cookies are set by hand because the session cookie is `__Host-` and //! `Secure`. Files are fetched from the user-content listener, as a browser would. -use crate::common::{BIN, Server, describe, input_value, launch, pick_ports, write_config}; +use crate::common::{ + BIN, Http, Server, describe, input_value, launch, login, pick_ports, write_config, +}; use std::path::{Path, PathBuf}; use std::process::Command; use std::time::Duration; -use reqwest::header::{CONTENT_TYPE, COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE}; +use reqwest::header::{CONTENT_TYPE, COOKIE, LOCATION}; const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn header(&self, name: HeaderName) -> Option { - self.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(base: String) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { client, base } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// The path and query of an absolute URL, so it can be requested through a base-bound client. fn path_of(url: &str) -> String { @@ -126,27 +51,6 @@ fn admin(config: &Path, args: &[&str]) { ); } -async fn login(http: &Http, username: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", PW), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// A running server. The temp dir lives as long as the test. struct Env { _root: tempfile::TempDir, @@ -166,8 +70,8 @@ async fn start() -> Env { Env { _root: root, _server: server, - app: Http::new(format!("http://127.0.0.1:{}", ports.http)), - content: Http::new(format!("http://127.0.0.1:{}", ports.content)), + app: Http::with_base(format!("http://127.0.0.1:{}", ports.http)), + content: Http::with_base(format!("http://127.0.0.1:{}", ports.content)), } } @@ -239,8 +143,8 @@ async fn next_change(res: &mut reqwest::Response, what: &str) { #[tokio::test] async fn snippet_streams_follow_writes() { let env = start().await; - let tahinli = login(&env.app, "tahinli").await; - let bob = login(&env.app, "bob").await; + let tahinli = login(&env.app, "tahinli", PW).await; + let bob = login(&env.app, "bob", PW).await; let id = create( &env.app, @@ -363,7 +267,7 @@ async fn snippet_streams_follow_writes() { #[tokio::test] async fn create_edit_and_revisions() { let env = start().await; - let tahinli = login(&env.app, "tahinli").await; + let tahinli = login(&env.app, "tahinli", PW).await; let id = create( &env.app, &tahinli, @@ -423,8 +327,8 @@ async fn create_edit_and_revisions() { #[tokio::test] async fn private_snippet_is_hidden_from_others() { let env = start().await; - let tahinli = login(&env.app, "tahinli").await; - let bob = login(&env.app, "bob").await; + let tahinli = login(&env.app, "tahinli", PW).await; + let bob = login(&env.app, "bob", PW).await; let id = create( &env.app, &tahinli, @@ -486,7 +390,7 @@ async fn private_snippet_is_hidden_from_others() { #[tokio::test] async fn raw_files_use_the_user_content_origin_and_private_tokens() { let env = start().await; - let tahinli = login(&env.app, "tahinli").await; + let tahinli = login(&env.app, "tahinli", PW).await; let public = create( &env.app, &tahinli, @@ -544,7 +448,7 @@ async fn raw_files_use_the_user_content_origin_and_private_tokens() { #[tokio::test] async fn unlisted_is_by_link_only_and_delete_removes_it() { let env = start().await; - let tahinli = login(&env.app, "tahinli").await; + let tahinli = login(&env.app, "tahinli", PW).await; let id = create( &env.app, &tahinli, @@ -584,7 +488,7 @@ async fn unlisted_is_by_link_only_and_delete_removes_it() { #[tokio::test] async fn bad_input_redisplays_the_form_with_an_error() { let env = start().await; - let tahinli = login(&env.app, "tahinli").await; + let tahinli = login(&env.app, "tahinli", PW).await; let page = env.app.get("/snippets/new", Some(&tahinli)).await; let csrf = input_value(&page.body, "csrf"); let res = env diff --git a/crates/forge-web/tests/e2e/stars_e2e.rs b/crates/forge-web/tests/e2e/stars_e2e.rs index fe534df..b22c6f1 100644 --- a/crates/forge-web/tests/e2e/stars_e2e.rs +++ b/crates/forge-web/tests/e2e/stars_e2e.rs @@ -3,98 +3,18 @@ //! HTTP. Cookies are set by hand because the session cookie is `__Host-` and `Secure`. use crate::common::{ - BIN, Server, describe, input_value, launch, pick_ports, tool_on_path, write_config, + BIN, Http, Resp, Server, describe, input_value, launch, login, pick_ports, tool_on_path, + write_config, }; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -use std::time::Duration; use forge_core::{Store, Visibility}; -use reqwest::header::{COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE}; +use reqwest::header::LOCATION; const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn header(&self, name: HeaderName) -> Option { - self.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded. fn admin(config: &Path, args: &[&str]) { @@ -113,27 +33,6 @@ fn admin(config: &Path, args: &[&str]) { ); } -async fn login(http: &Http, username: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", PW), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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"); @@ -276,7 +175,7 @@ async fn star_round_trip_shows_the_count() { return; } let env = start(seed_repos).await; - let bob = login(&env.http, "bob").await; + let bob = login(&env.http, "bob", PW).await; let page = env.http.get("/tahinli/pub", Some(&bob)).await; assert_eq!(page.status, 200, "repo page"); @@ -339,7 +238,7 @@ async fn anonymous_star_redirects_to_login() { #[tokio::test] async fn star_without_a_valid_csrf_token_is_403() { let env = start(seed_repos).await; - let bob = login(&env.http, "bob").await; + let bob = login(&env.http, "bob", PW).await; let res = post_star(&env.http, "/tahinli/pub/star", "wrong", Some(&bob), None).await; assert_eq!(res.status, 403); let page = env.http.get("/tahinli/pub", Some(&bob)).await; @@ -349,7 +248,7 @@ async fn star_without_a_valid_csrf_token_is_403() { #[tokio::test] async fn star_on_a_private_repo_is_404_for_a_non_reader() { let env = start(seed_repos).await; - let bob = login(&env.http, "bob").await; + let bob = login(&env.http, "bob", PW).await; let res = post_star( &env.http, "/tahinli/priv/star", @@ -380,7 +279,7 @@ async fn explore_lists_public_repos_and_searches_literally() { assert_eq!(repo_names(&page.body), vec!["tahinli/pct%x".to_owned()]); // Sorting by stars puts a starred repo first; the default (name) puts `pct%x` first. - let bob = login(&env.http, "bob").await; + let bob = login(&env.http, "bob", PW).await; let page = env.http.get("/tahinli/pub", Some(&bob)).await; let csrf = input_value(&page.body, "csrf"); let res = post_star(&env.http, "/tahinli/pub/star", &csrf, Some(&bob), None).await; @@ -426,7 +325,7 @@ async fn profile_stars_tab_hides_repos_the_viewer_cannot_read() { }; assert_eq!(starred(&anon.body), vec!["tahinli/pub".to_owned()]); - let tahinli = login(&env.http, "tahinli").await; + let tahinli = login(&env.http, "tahinli", PW).await; let owner = env.http.get("/bob?tab=stars", Some(&tahinli)).await; let mut names = starred(&owner.body); names.sort(); diff --git a/crates/forge-web/tests/e2e/ui_prefs_e2e.rs b/crates/forge-web/tests/e2e/ui_prefs_e2e.rs index 120c9a9..846d860 100644 --- a/crates/forge-web/tests/e2e/ui_prefs_e2e.rs +++ b/crates/forge-web/tests/e2e/ui_prefs_e2e.rs @@ -3,95 +3,14 @@ //! tests, this starts the real `forge` binary and drives it over HTTP. Cookies are set by hand //! because the session cookie is `__Host-` and `Secure`. -use crate::common::{BIN, Server, describe, input_value, launch, pick_ports, write_config}; +use crate::common::{ + BIN, Http, Server, cookie_named, describe, input_value, launch, login, pick_ports, write_config, +}; use std::path::Path; use std::process::Command; -use std::time::Duration; - -use reqwest::header::{COOKIE, HeaderMap, HeaderName, SET_COOKIE}; const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn header(&self, name: HeaderName) -> Option { - self.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// The `data-theme` attribute of ``, if the page sets one. fn html_theme(body: &str) -> Option { @@ -191,27 +110,6 @@ fn admin(config: &Path, args: &[&str]) { ); } -async fn login(http: &Http, username: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", PW), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// A running server with user `tahinli`. The temp dir lives as long as the test. struct Env { _root: tempfile::TempDir, @@ -237,7 +135,7 @@ async fn start() -> Env { #[tokio::test] async fn appearance_setting_persists_and_renders_the_html_attribute() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let page = env.http.get("/settings/appearance", Some(&session)).await; assert_eq!(page.status, 200); @@ -282,7 +180,7 @@ async fn appearance_setting_persists_and_renders_the_html_attribute() { #[tokio::test] async fn the_form_has_no_save_button_and_every_field_autosubmits() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let page = env.http.get("/settings/appearance", Some(&session)).await; let doc = scraper::Html::parse_document(&page.body); @@ -315,7 +213,7 @@ async fn the_form_has_no_save_button_and_every_field_autosubmits() { #[tokio::test] async fn light_and_dark_colours_save_independently_and_render_on_html() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let page = env.http.get("/settings/appearance", Some(&session)).await; let defaults = ["sage", "sage", "fern", "fern"].map(str::to_owned); @@ -442,7 +340,7 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() { #[tokio::test] async fn a_save_without_colour_fields_keeps_the_stored_colours() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let page = env.http.get("/settings/appearance", Some(&session)).await; let csrf = input_value(&page.body, "csrf"); @@ -489,7 +387,7 @@ async fn a_save_without_colour_fields_keeps_the_stored_colours() { #[tokio::test] async fn appearance_save_without_a_valid_csrf_token_is_403() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let res = env .http .post_form( @@ -510,7 +408,7 @@ async fn appearance_save_without_a_valid_csrf_token_is_403() { #[tokio::test] async fn unoffered_theme_or_language_is_rejected_and_nothing_is_saved() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let page = env.http.get("/settings/appearance", Some(&session)).await; let csrf = input_value(&page.body, "csrf"); for form in [ @@ -582,7 +480,7 @@ async fn anonymous_theme_cookie_ignores_unknown_values() { #[tokio::test] async fn signed_in_preference_wins_over_the_anonymous_cookie() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let page = env.http.get("/settings/appearance", Some(&session)).await; assert!( !page.body.contains("class=\"theme-picker\""), @@ -611,7 +509,7 @@ async fn appearance_page_needs_a_session() { #[tokio::test] async fn signed_in_toggle_saves_the_preference_and_returns_to_back() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let page = env.http.get("/settings/appearance", Some(&session)).await; let csrf = input_value(&page.body, "csrf"); let saved = env @@ -666,7 +564,7 @@ async fn signed_in_toggle_saves_the_preference_and_returns_to_back() { #[tokio::test] async fn theme_toggle_with_an_unsafe_back_returns_to_the_root() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let page = env.http.get("/settings/appearance", Some(&session)).await; let csrf = input_value(&page.body, "csrf"); for back in ["//evil.com", "https://evil.com", "/\\evil"] { @@ -690,7 +588,7 @@ async fn theme_toggle_with_an_unsafe_back_returns_to_the_root() { #[tokio::test] async fn signed_in_theme_toggle_without_a_valid_csrf_is_refused() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; for form in [ vec![("csrf", "forged"), ("theme", "dark")], vec![("theme", "dark")], @@ -725,7 +623,7 @@ async fn anonymous_theme_toggle_sets_the_cookie_and_returns_to_back() { #[tokio::test] async fn theme_button_cycles_light_dark_auto_light_for_signed_in_users() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let back = "/settings/appearance"; // A new user starts on light, the default, so the button offers dark next. @@ -823,7 +721,7 @@ async fn theme_button_cycles_for_anonymous_visitors_through_the_cookie() { #[tokio::test] async fn appearance_sidebar_side_saves_and_renders_on_html() { let env = start().await; - let session = login(&env.http, "tahinli").await; + let session = login(&env.http, "tahinli", PW).await; let page = env.http.get("/settings/appearance", Some(&session)).await; assert_eq!( diff --git a/crates/forge-web/tests/e2e/user_delete_e2e.rs b/crates/forge-web/tests/e2e/user_delete_e2e.rs index f7c3600..b09ae25 100644 --- a/crates/forge-web/tests/e2e/user_delete_e2e.rs +++ b/crates/forge-web/tests/e2e/user_delete_e2e.rs @@ -3,15 +3,17 @@ //! the real `forge` binary and drives it over HTTP. Cookies are set by hand because the //! session cookie is `__Host-` and `Secure`. -use crate::common::{BIN, Server, describe, input_value, launch, pick_ports, write_config}; +use crate::common::{ + BIN, Http, Resp, Server, cookie_named, describe, input_value, launch, login, pick_ports, + write_config, +}; use std::fs; use std::future::Future; use std::path::{Path, PathBuf}; use std::process::Command; -use std::time::Duration; use forge_core::{Store, Visibility}; -use reqwest::header::{COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE}; +use reqwest::header::LOCATION; /// Each test starts a server on ports picked just before, so the tests run one at a time. static SERIAL: std::sync::LazyLock> = @@ -19,86 +21,6 @@ static SERIAL: std::sync::LazyLock> = const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn header(&self, name: HeaderName) -> Option { - self.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded. fn admin(config: &Path, args: &[&str]) { @@ -136,13 +58,6 @@ async fn try_login(http: &Http, username: &str) -> Resp { .await } -/// Signs in and returns the session cookie. -async fn login(http: &Http, username: &str) -> String { - let res = try_login(http, username).await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// Creates the users (`dana` is the first user, so an administrator), then runs `seed` against /// the store before the server starts. `seed` gets the data dir and the open store. struct Env { @@ -211,7 +126,7 @@ async fn admin_delete_moves_content_to_ghost_and_pages_still_render() { let _serial = SERIAL.lock().await; let env = start(seed_issue_by_tahinli).await; let http = &env.http; - let dana = login(http, "dana").await; + let dana = login(http, "dana", PW).await; let tahinli_id = fs::read_to_string(env.dir.join("tahinli.id")).expect("tahinli id"); let path = format!("/admin/users/{tahinli_id}/delete"); @@ -264,7 +179,7 @@ async fn self_delete_refuses_wrong_password_and_owned_repos() { let http = &env.http; // Tahinli owns nothing: a wrong password is refused and the account stays. - let tahinli = login(http, "tahinli").await; + let tahinli = login(http, "tahinli", PW).await; let security = http.get("/settings/security", Some(&tahinli)).await; assert_eq!(security.status, 200); let csrf = input_value(&security.body, "csrf"); @@ -291,7 +206,7 @@ async fn self_delete_refuses_wrong_password_and_owned_repos() { ); // Bob owns `proj`: deletion is refused and the repo is named. - let bob = login(http, "bob").await; + let bob = login(http, "bob", PW).await; let security = http.get("/settings/security", Some(&bob)).await; let csrf = input_value(&security.body, "csrf"); let refused = http @@ -325,7 +240,7 @@ async fn self_delete_with_correct_password_signs_out_and_removes_login() { let _serial = SERIAL.lock().await; let env = start(seed_issue_by_tahinli).await; let http = &env.http; - let tahinli = login(http, "tahinli").await; + let tahinli = login(http, "tahinli", PW).await; let security = http.get("/settings/security", Some(&tahinli)).await; let csrf = input_value(&security.body, "csrf"); let done = http diff --git a/crates/forge-web/tests/e2e/wiki_e2e.rs b/crates/forge-web/tests/e2e/wiki_e2e.rs index 92da4d7..b7a6a06 100644 --- a/crates/forge-web/tests/e2e/wiki_e2e.rs +++ b/crates/forge-web/tests/e2e/wiki_e2e.rs @@ -5,97 +5,19 @@ //! 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::{BIN, describe, input_value, launch, pick_ports, tool_on_path, write_config}; +use crate::common::{ + BIN, Http, Resp, describe, input_value, launch, login, pick_ports, tool_on_path, write_config, +}; use std::fs; use std::path::Path; use std::process::{Command, Output}; use std::time::Duration; use forge_core::{Role, Store, Visibility}; -use reqwest::header::{COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE}; +use reqwest::header::{COOKIE, LOCATION}; const PW: &str = "tahinli-password-123"; -struct Resp { - status: u16, - headers: HeaderMap, - body: String, -} - -impl Resp { - fn header(&self, name: HeaderName) -> Option { - self.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - fn set_cookies(&self) -> Vec { - self.headers - .get_all(SET_COOKIE) - .iter() - .filter_map(|v| v.to_str().ok().map(str::to_owned)) - .collect() - } -} - -struct Http { - client: reqwest::Client, - base: String, -} - -impl Http { - fn new(port: u16) -> Self { - let client = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .timeout(Duration::from_secs(60)) - .build() - .expect("http client"); - Self { - client, - base: format!("http://127.0.0.1:{port}"), - } - } - - async fn get(&self, path: &str, cookie: Option<&str>) -> Resp { - self.send(self.client.get(format!("{}{path}", self.base)), cookie) - .await - } - - async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp { - self.send( - self.client.post(format!("{}{path}", self.base)).form(form), - cookie, - ) - .await - } - - async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { - let req = match cookie { - Some(cookie) => req.header(COOKIE, cookie), - None => req, - }; - let res = req.send().await.expect("http request"); - let status = res.status().as_u16(); - let headers = res.headers().clone(); - let body = res.text().await.expect("read body"); - Resp { - status, - headers, - body, - } - } -} - -/// `name=value` for the cookie whose name ends with `suffix`, ignoring cleared cookies. -fn cookie_named(resp: &Resp, suffix: &str) -> Option { - resp.set_cookies().iter().find_map(|set| { - let pair = set.split(';').next()?; - let (name, value) = pair.split_once('=')?; - (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}")) - }) -} - /// The value of the first `` on a page. /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded. fn admin(config: &Path, args: &[&str]) { @@ -114,27 +36,6 @@ fn admin(config: &Path, args: &[&str]) { ); } -async fn login(http: &Http, username: &str) -> String { - let page = http.get("/login", None).await; - assert_eq!(page.status, 200, "GET /login"); - let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie"); - let precsrf = input_value(&page.body, "precsrf"); - let res = http - .post_form( - "/login", - &[ - ("username", username), - ("password", PW), - ("next", "/"), - ("precsrf", &precsrf), - ], - Some(&precsrf_cookie), - ) - .await; - assert_eq!(res.status, 303, "login as {username}: {}", res.body); - cookie_named(&res, "forge_session").expect("session cookie after login") -} - /// 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/tokens", Some(session)).await; @@ -267,9 +168,9 @@ async fn wiki_end_to_end() { let (server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); - let bob = login(&http, "bob").await; - let carol = login(&http, "carol").await; - let dave = login(&http, "dave").await; + let bob = login(&http, "bob", PW).await; + let carol = login(&http, "carol", PW).await; + let dave = login(&http, "dave", PW).await; // The wiki starts empty, and the tab is there. let empty = page_body(&http, "/bob/proj/wiki", Some(&bob)).await; @@ -336,7 +237,7 @@ async fn wiki_end_to_end() { after_push.body ); // The push is in the admin audit log (read over HTTP, the server holds the database open). - let tahinli = login(&http, "tahinli").await; + let tahinli = login(&http, "tahinli", PW).await; let audit = http .get("/admin/audit?action=wiki_pushed", Some(&tahinli)) .await; @@ -498,8 +399,8 @@ async fn wiki_streams_follow_saves_and_pushes() { let (server, ports) = launch(&dir, ports).await; let http = Http::new(ports.http); - let bob = login(&http, "bob").await; - let dave = login(&http, "dave").await; + let bob = login(&http, "bob", PW).await; + let dave = login(&http, "dave", PW).await; // The page list follows the wiki stream. let listing = page_body(&http, "/bob/proj/wiki/-/pages", Some(&bob)).await;