//! The web tests' own helpers: a running `gitv-web` with its own account, and a minimal HTTP //! client. use std::collections::HashMap; use std::fs; use std::io::{BufRead, BufReader, Read, Write}; use std::net::TcpStream; use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; use super::{GITV_WEB, NO_CONFIG, TEST_HOST, scratch, stderr, stdout}; /// A web account made by `gitv-web setup`: where it's stored, and what it printed. #[derive(Clone)] pub struct Account { pub file: PathBuf, pub password: String, pub secret: Vec, } impl Account { /// Run `gitv-web setup` for a new account in `dir`. pub fn create(dir: &Path) -> Account { let file = dir.join("login"); let out = Command::new(&*GITV_WEB).args(["setup", "--user", "Um9i"]).env("GITV_WEB_AUTH", &file).output().unwrap(); assert!(out.status.success(), "setup failed: {}", stderr(&out)); let printed = stdout(&out); let field = |label: &str| { printed .lines() .find_map(|l| l.trim().strip_prefix(label)) .map(|v| v.trim().to_string()) .unwrap_or_else(|| panic!("no {label} in: {printed}")) }; let password = field("Password:"); let secret = data_encoding::BASE32_NOPAD.decode(field("2FA secret:").as_bytes()).unwrap(); Account { file, password, secret } } /// The authenticator code `offset` steps from now. pub fn code(&self, offset: i64) -> String { let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); let step = gitv_web::auth::totp_step(now).saturating_add_signed(offset); format!("{:06}", gitv_web::auth::totp_code(&self.secret, step)) } } /// A fresh, private directory for one server's account. fn account_dir() -> PathBuf { static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); scratch(&format!("web-account-{}-{n}", std::process::id())) } /// A running `gitv-web`, stopped when dropped. Unless started signed out, it has its own /// account and a signed-in session, which [`Server::get`] uses. pub struct Server { pub child: Child, pub port: u16, pub account: Account, pub cookie: Option, /// Where the server's stderr (its log) goes. pub log: PathBuf, } impl Server { /// A server with its own account, already signed in. pub fn start(repos: &Path) -> Server { let mut server = Server::start_with(repos, None); server.sign_in_now(); server } /// Like [`Server::start`], with at most `limit` open file descriptors. pub fn start_limited(repos: &Path, limit: u64) -> Server { let mut server = Server::start_with(repos, Some(limit)); server.sign_in_now(); server } /// A server with its own account, not signed in. pub fn start_signed_out(repos: &Path) -> Server { Server::start_with(repos, None) } /// A server using an existing account (another server's, say), not signed in. pub fn start_signed_out_as(repos: &Path, account: Account) -> Server { Server::launch(repos, None, account) } /// Sign in with the account's password and the current code, keeping the cookie. pub fn sign_in_now(&mut self) { let code = self.account.code(0); let password = self.account.password.clone(); let response = self .post_signed_out("/login", &[("user", "Um9i"), ("password", &password), ("code", &code), ("next", "/")]); assert_eq!(response.status, 303, "sign-in failed: {}", response.text()); self.cookie = Some(session_cookie(&response).expect("a session cookie")); } fn start_with(repos: &Path, limit: Option) -> Server { Server::launch(repos, limit, Account::create(&account_dir())) } fn launch(repos: &Path, limit: Option, account: Account) -> Server { let mut command = Command::new(&*GITV_WEB); if let Some(limit) = limit { use std::os::unix::process::CommandExt; // SAFETY: setrlimit is async-signal-safe and the closure does nothing else. unsafe { command.pre_exec(move || { nix::sys::resource::setrlimit(nix::sys::resource::Resource::RLIMIT_NOFILE, limit, limit) .map_err(std::io::Error::from) }); } } static LAUNCHED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let number = LAUNCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let log = account.file.with_file_name(format!("server-{}-{number}.log", std::process::id())); let mut child = command .args(["serve", "--port", "0"]) .env("GITV_HOST", TEST_HOST) .env("GITV_CONFIG", NO_CONFIG) .env("GITV_REPOS", repos) .env("GITV_WEB_AUTH", &account.file) .stdout(Stdio::piped()) .stderr(fs::File::create(&log).unwrap()) .spawn() .unwrap(); let mut line = String::new(); BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap(); let port = line .split("http://127.0.0.1:") .nth(1) .and_then(|rest| rest.split_whitespace().next()) .and_then(|p| p.parse().ok()) .unwrap_or_else(|| panic!("unexpected startup line: {line}")); Server { child, port, account, cookie: None, log } } /// What the server has logged so far. pub fn logged(&self) -> String { fs::read_to_string(&self.log).unwrap_or_default() } /// GET with the session cookie, if signed in. pub fn get(&self, path: &str) -> Response { request(self.port, "GET", path, self.cookie.as_deref(), None) } /// GET without any cookie. pub fn get_signed_out(&self, path: &str) -> Response { request(self.port, "GET", path, None, None) } /// POST a form with the session cookie, if signed in. pub fn post(&self, path: &str, form: &[(&str, &str)]) -> Response { request(self.port, "POST", path, self.cookie.as_deref(), Some(&form_body(form))) } /// POST a form without any cookie. pub fn post_signed_out(&self, path: &str, form: &[(&str, &str)]) -> Response { request(self.port, "POST", path, None, Some(&form_body(form))) } /// POST a form without any cookie, as Caddy forwards one from the client at `address`. pub fn post_signed_out_from(&self, address: &str, path: &str, form: &[(&str, &str)]) -> Response { let extra = [("X-Forwarded-For", address)]; request_with(self.port, "POST", path, None, Some(&form_body(form)), &extra) } /// Like [`Server::post_signed_out_from`], from a browser carrying the trusted-device token /// `device`. pub fn post_from_device(&self, address: &str, device: &str, path: &str, form: &[(&str, &str)]) -> Response { let cookie = format!("__Host-gitv-device={device}"); let extra = [("X-Forwarded-For", address), ("Cookie", cookie.as_str())]; request_with(self.port, "POST", path, None, Some(&form_body(form)), &extra) } } /// The session token a response's `Set-Cookie` gives, if any. pub fn session_cookie(response: &Response) -> Option { set_cookie(response, "__Host-gitv") } /// The value a response's `Set-Cookie` headers give the cookie `name`, if any. pub fn set_cookie(response: &Response, name: &str) -> Option { response .header("set-cookie") .lines() .find_map(|line| line.strip_prefix(name)?.strip_prefix('='))? .split(';') .next() .filter(|t| !t.is_empty()) .map(String::from) } /// `application/x-www-form-urlencoded`, as a browser sends a form. fn form_body(form: &[(&str, &str)]) -> String { let encode = |v: &str| -> String { v.bytes() .map(|b| match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(), _ => format!("%{b:02X}"), }) .collect() }; form.iter().map(|(k, v)| format!("{}={}", encode(k), encode(v))).collect::>().join("&") } impl Drop for Server { fn drop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); } } pub struct Response { pub status: u16, pub headers: HashMap, pub body: Vec, } impl Response { pub fn text(&self) -> String { String::from_utf8_lossy(&self.body).into_owned() } pub fn header(&self, name: &str) -> &str { self.headers.get(name).map_or("", String::as_str) } } /// A plain HTTP/1.1 request, enough for testing a local server. fn request(port: u16, method: &str, path: &str, cookie: Option<&str>, form: Option<&str>) -> Response { request_with(port, method, path, cookie, form, &[]) } fn request_with( port: u16, method: &str, path: &str, cookie: Option<&str>, form: Option<&str>, extra: &[(&str, &str)], ) -> Response { let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); let mut head = format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n"); for (name, value) in extra { head += &format!("{name}: {value}\r\n"); } if let Some(cookie) = cookie { head += &format!("Cookie: __Host-gitv={cookie}\r\n"); } let body = form.unwrap_or(""); if form.is_some() { head += &format!("Content-Type: application/x-www-form-urlencoded\r\nContent-Length: {}\r\n", body.len()); } write!(stream, "{head}\r\n{body}").unwrap(); let mut raw = Vec::new(); stream.read_to_end(&mut raw).unwrap(); let split = raw.windows(4).position(|w| w == b"\r\n\r\n").expect("no header end"); let head = String::from_utf8_lossy(&raw[..split]).into_owned(); let mut lines = head.lines(); let status = lines.next().and_then(|l| l.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap(); // A repeated header (Set-Cookie, say) keeps every value, one per line. let mut headers: HashMap = HashMap::new(); for (name, value) in lines.filter_map(|l| l.split_once(':')) { let entry = headers.entry(name.trim().to_ascii_lowercase()).or_default(); if !entry.is_empty() { entry.push('\n'); } entry.push_str(value.trim()); } let mut body = raw[split + 4..].to_vec(); if headers.get("transfer-encoding").is_some_and(|v| v.eq_ignore_ascii_case("chunked")) { body = dechunk(&body); } Response { status, headers, body } } fn dechunk(mut data: &[u8]) -> Vec { let mut out = Vec::new(); while let Some(end) = data.windows(2).position(|w| w == b"\r\n") { let size = usize::from_str_radix(String::from_utf8_lossy(&data[..end]).trim(), 16).unwrap_or(0); if size == 0 { break; } out.extend_from_slice(&data[end + 2..end + 2 + size]); data = &data[end + 2 + size + 2..]; } out }