//! Black-box tests for snippets. Like the other e2e 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`. Files are fetched from the user-content listener, as a browser would. mod common; use common::{BIN, Server, describe, launch, 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}; const PW: &str = "alice-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. fn input_value(body: &str, name: &str) -> String { let doc = scraper::Html::parse_document(body); let selector = scraper::Selector::parse(&format!("input[name=\"{name}\"]")).expect("selector"); doc.select(&selector) .next() .and_then(|el| el.value().attr("value")) .unwrap_or_else(|| panic!("no input named {name} on page")) .to_owned() } /// The path and query of an absolute URL, so it can be requested through a base-bound client. fn path_of(url: &str) -> String { let rest = url.split_once("//").map_or(url, |(_, r)| r); match rest.find('/') { Some(i) => rest[i..].to_owned(), None => "/".to_owned(), } } /// The href of the first link whose text is `text`. fn link_href(body: &str, text: &str) -> String { let doc = scraper::Html::parse_document(body); let selector = scraper::Selector::parse("a").expect("selector"); doc.select(&selector) .find(|a| a.text().collect::().trim() == text) .and_then(|a| a.value().attr("href")) .unwrap_or_else(|| panic!("no link {text:?} on page")) .to_owned() } /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded. fn admin(config: &Path, args: &[&str]) { let out = Command::new(BIN) .arg("--config") .arg(config) .arg("admin") .args(args) .env("FORGE_PASSWORD", PW) .output() .expect("run admin command"); assert!( out.status.success(), "admin {args:?} failed:\n{}", describe(&out) ); } 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, _server: Server, app: Http, content: Http, } async fn start() -> Env { let root = tempfile::tempdir().expect("temp dir"); let dir: PathBuf = root.path().to_path_buf(); let ports = pick_ports(); let config = write_config(&dir, ports); admin(&config, &["create-user", "alice"]); admin(&config, &["create-user", "bob"]); let (server, ports) = launch(&dir, ports).await; 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)), } } /// Creates a snippet as `cookie`'s user and returns its id. async fn create( http: &Http, cookie: &str, title: &str, visibility: &str, files: &[(&str, &str)], ) -> String { let page = http.get("/snippets/new", Some(cookie)).await; assert_eq!(page.status, 200, "GET /snippets/new"); let csrf = input_value(&page.body, "csrf"); let mut form: Vec<(String, String)> = vec![ ("csrf".into(), csrf), ("title".into(), title.into()), ("description".into(), String::new()), ("visibility".into(), visibility.into()), ]; for (i, (name, content)) in files.iter().enumerate() { form.push((format!("name_{i}"), (*name).into())); form.push((format!("content_{i}"), (*content).into())); } let borrowed: Vec<(&str, &str)> = form.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); let res = http .post_form("/snippets/new", &borrowed, Some(cookie)) .await; assert_eq!(res.status, 303, "create snippet: {}", res.body); let location = res.header(LOCATION).expect("location"); location .strip_prefix("/snippets/") .expect("redirect to the snippet") .to_owned() } #[tokio::test] async fn create_edit_and_revisions() { let env = start().await; let alice = login(&env.app, "alice").await; let id = create( &env.app, &alice, "Greeting", "public", &[("hello.txt", "hello\n")], ) .await; let view = env.app.get(&format!("/snippets/{id}"), None).await; assert_eq!(view.status, 200); assert!(view.body.contains("hello"), "file contents are shown"); let edit_path = format!("/snippets/{id}/edit"); let page = env.app.get(&edit_path, Some(&alice)).await; assert_eq!(page.status, 200, "GET edit"); let csrf = input_value(&page.body, "csrf"); let saved = env .app .post_form( &edit_path, &[ ("csrf", &csrf), ("title", "Greeting v2"), ("description", "two files now"), ("visibility", "public"), ("name_0", "hello.txt"), ("content_0", "hello v2\n"), ("name_1", "notes.md"), ("content_1", "# Notes\n\nSome **bold** text.\n"), ], Some(&alice), ) .await; assert_eq!(saved.status, 303, "save edit: {}", saved.body); let view = env.app.get(&format!("/snippets/{id}"), None).await; assert!(view.body.contains("Greeting v2")); assert!(view.body.contains(""), "markdown file is rendered"); assert!( view.body.contains("bold"), "markdown bold renders" ); let history = env .app .get(&format!("/snippets/{id}/revisions"), Some(&alice)) .await; assert_eq!(history.status, 200); assert!( history.body.contains("Revision 2"), "second revision listed" ); assert!(history.body.contains("Revision 1"), "first revision listed"); } #[tokio::test] async fn private_snippet_is_hidden_from_others() { let env = start().await; let alice = login(&env.app, "alice").await; let bob = login(&env.app, "bob").await; let id = create(&env.app, &alice, "Secret", "private", &[("s.txt", "shh\n")]).await; let owner = env.app.get(&format!("/snippets/{id}"), Some(&alice)).await; assert_eq!(owner.status, 200, "owner can read"); assert_eq!( env.app .get(&format!("/snippets/{id}"), Some(&bob)) .await .status, 404 ); assert_eq!( env.app.get(&format!("/snippets/{id}"), None).await.status, 404 ); let list = env.app.get("/snippets", Some(&bob)).await; assert!( !list.body.contains("Secret"), "private snippet is not listed for bob" ); // Bob cannot edit or delete it either. let page = env .app .get(&format!("/snippets/{id}/edit"), Some(&bob)) .await; assert_eq!(page.status, 404, "bob cannot open the editor"); let bob_page = env.app.get("/snippets/new", Some(&bob)).await; let bob_csrf = input_value(&bob_page.body, "csrf"); let res = env .app .post_form( &format!("/snippets/{id}/delete"), &[("csrf", &bob_csrf)], Some(&bob), ) .await; assert_eq!(res.status, 404, "bob cannot delete"); assert_eq!( env.app .get(&format!("/snippets/{id}"), Some(&alice)) .await .status, 200 ); } #[tokio::test] async fn raw_files_use_the_user_content_origin_and_private_tokens() { let env = start().await; let alice = login(&env.app, "alice").await; let public = create(&env.app, &alice, "Pub", "public", &[("notes.md", "# Hi\n")]).await; let private = create( &env.app, &alice, "Priv", "private", &[("data.json", "{\"a\":1}\n")], ) .await; let page = env.app.get(&format!("/snippets/{public}"), None).await; let raw = link_href(&page.body, "Raw"); let res = env.content.get(&path_of(&raw), None).await; assert_eq!(res.status, 200, "public raw: {raw}"); assert!( res.header(CONTENT_TYPE) .unwrap_or_default() .starts_with("text/markdown"), "markdown content type" ); assert_eq!(res.body, "# Hi\n"); // Private raw links carry a signed token, and the bare path is refused. let page = env .app .get(&format!("/snippets/{private}"), Some(&alice)) .await; let raw = link_href(&page.body, "Raw"); assert!(raw.contains("token="), "private raw link is signed: {raw}"); let res = env.content.get(&path_of(&raw), None).await; assert_eq!(res.status, 200, "private raw with token"); assert!( res.header(CONTENT_TYPE) .unwrap_or_default() .starts_with("application/json") ); let bare = raw.split('?').next().unwrap_or_default().to_owned(); assert_eq!( env.content.get(&path_of(&bare), None).await.status, 404, "no token, no file" ); let missing = format!("/-/snippets/{public}/nope.txt"); assert_eq!(env.content.get(&missing, None).await.status, 404); } #[tokio::test] async fn unlisted_is_by_link_only_and_delete_removes_it() { let env = start().await; let alice = login(&env.app, "alice").await; let id = create( &env.app, &alice, "Link only", "unlisted", &[("a.txt", "x\n")], ) .await; let list = env.app.get("/snippets", None).await; assert!(!list.body.contains("Link only"), "unlisted is not listed"); assert_eq!( env.app.get(&format!("/snippets/{id}"), None).await.status, 200 ); let page = env.app.get(&format!("/snippets/{id}"), Some(&alice)).await; let csrf = input_value(&page.body, "csrf"); let res = env .app .post_form( &format!("/snippets/{id}/delete"), &[("csrf", &csrf)], Some(&alice), ) .await; assert_eq!(res.status, 303, "delete: {}", res.body); assert_eq!( env.app.get(&format!("/snippets/{id}"), None).await.status, 404 ); } #[tokio::test] async fn bad_input_redisplays_the_form_with_an_error() { let env = start().await; let alice = login(&env.app, "alice").await; let page = env.app.get("/snippets/new", Some(&alice)).await; let csrf = input_value(&page.body, "csrf"); let res = env .app .post_form( "/snippets/new", &[ ("csrf", &csrf), ("title", "Bad"), ("visibility", "public"), ("name_0", "a/b.txt"), ("content_0", "x"), ], Some(&alice), ) .await; assert_eq!(res.status, 200, "invalid input is not a redirect"); assert!( res.body.contains("may only use"), "error shown: {}", res.body ); assert!( res.body.contains("a/b.txt") || res.body.contains("Bad"), "input kept" ); }