forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

snippets_e2e.rs517 lines, 15.6 KiBHistoryRawDownload
1//! Black-box tests for snippets. Like the other e2e tests, this starts the real `forge` binary and
2//! drives it over HTTP. Cookies are set by hand because the session cookie is `__Host-` and
3//! `Secure`. Files are fetched from the user-content listener, as a browser would.
4
5use crate::common::{
6 Http, Server, bin, describe, input_value, launch, login, pick_ports, write_config,
7};
8use std::path::{Path, PathBuf};
9use std::process::Command;
10use std::time::Duration;
11
12use reqwest::header::{CONTENT_TYPE, COOKIE, LOCATION};
13
14const PW: &str = "tahinli-password-123";
15
16/// The path and query of an absolute URL, so it can be requested through a base-bound client.
17fn path_of(url: &str) -> String {
18 let rest = url.split_once("//").map_or(url, |(_, r)| r);
19 match rest.find('/') {
20 Some(i) => rest[i..].to_owned(),
21 None => "/".to_owned(),
22 }
23}
24
25/// The href of the first link whose text is `text`.
26fn link_href(body: &str, text: &str) -> String {
27 let doc = scraper::Html::parse_document(body);
28 let selector = scraper::Selector::parse("a").expect("selector");
29 doc.select(&selector)
30 .find(|a| a.text().collect::<String>().trim() == text)
31 .and_then(|a| a.value().attr("href"))
32 .unwrap_or_else(|| panic!("no link {text:?} on page"))
33 .to_owned()
34}
35
36/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
37fn admin(config: &Path, args: &[&str]) {
38 let out = Command::new(bin())
39 .arg("--config")
40 .arg(config)
41 .arg("admin")
42 .args(args)
43 .env("FORGE_PASSWORD", PW)
44 .output()
45 .expect("run admin command");
46 assert!(
47 out.status.success(),
48 "admin {args:?} failed:\n{}",
49 describe(&out)
50 );
51}
52
53/// A running server. The temp dir lives as long as the test.
54struct Env {
55 _root: tempfile::TempDir,
56 _server: Server,
57 app: Http,
58 content: Http,
59}
60
61async fn start() -> Env {
62 let root = tempfile::tempdir().expect("temp dir");
63 let dir: PathBuf = root.path().to_path_buf();
64 let ports = pick_ports();
65 let config = write_config(&dir, ports);
66 admin(&config, &["create-user", "tahinli"]);
67 admin(&config, &["create-user", "bob"]);
68 let (server, ports) = launch(&dir, ports).await;
69 Env {
70 _root: root,
71 _server: server,
72 app: Http::with_base(format!("http://127.0.0.1:{}", ports.http)),
73 content: Http::with_base(format!("http://127.0.0.1:{}", ports.content)),
74 }
75}
76
77/// Creates a snippet as `cookie`'s user and returns its id.
78async fn create(
79 http: &Http,
80 cookie: &str,
81 title: &str,
82 visibility: &str,
83 files: &[(&str, &str)],
84) -> String {
85 let page = http.get("/snippets/new", Some(cookie)).await;
86 assert_eq!(page.status, 200, "GET /snippets/new");
87 let csrf = input_value(&page.body, "csrf");
88 let mut form: Vec<(String, String)> = vec![
89 ("csrf".into(), csrf),
90 ("title".into(), title.into()),
91 ("description".into(), String::new()),
92 ("visibility".into(), visibility.into()),
93 ];
94 for (i, (name, content)) in files.iter().enumerate() {
95 form.push((format!("name_{i}"), (*name).into()));
96 form.push((format!("content_{i}"), (*content).into()));
97 }
98 let borrowed: Vec<(&str, &str)> = form.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
99 let res = http
100 .post_form("/snippets/new", &borrowed, Some(cookie))
101 .await;
102 assert_eq!(res.status, 303, "create snippet: {}", res.body);
103 let location = res.header(LOCATION).expect("location");
104 location
105 .strip_prefix("/snippets/")
106 .expect("redirect to the snippet")
107 .to_owned()
108}
109
110/// Opens a live stream as `cookie` (or anonymously) and reads its `retry` field. Returns the
111/// status with the response, so a refused stream can be checked too.
112async fn open_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response {
113 let mut req = http.client.get(format!("{}{path}", http.base));
114 if let Some(cookie) = cookie {
115 req = req.header(COOKIE, cookie);
116 }
117 let mut res = req.send().await.expect("stream request");
118 if res.status().is_success() {
119 let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk())
120 .await
121 .expect("the retry field")
122 .expect("stream chunk")
123 .expect("stream still open");
124 assert!(String::from_utf8_lossy(&retry).contains("retry: 1000"));
125 }
126 res
127}
128
129/// Waits for the next event of a stream, which must be `changed`.
130async fn next_change(res: &mut reqwest::Response, what: &str) {
131 let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())
132 .await
133 .unwrap_or_else(|_| panic!("no event after {what}"))
134 .expect("stream chunk")
135 .expect("stream still open");
136 let text = String::from_utf8_lossy(&chunk);
137 assert!(text.contains("event: changed"), "{what}: {text}");
138}
139
140/// The list and the snippet page follow their streams. A create, an edit and a delete each wake
141/// them, and a private snippet's stream answers 404 to everyone but its owner.
142#[tokio::test]
143async fn snippet_streams_follow_writes() {
144 let env = start().await;
145 let tahinli = login(&env.app, "tahinli", PW).await;
146 let bob = login(&env.app, "bob", PW).await;
147
148 let id = create(
149 &env.app,
150 &tahinli,
151 "Live",
152 "public",
153 &[("live.txt", "one\n")],
154 )
155 .await;
156 let item = format!("/snippets/{id}/events");
157
158 // The pages render the streams they follow.
159 let listing = env.app.get("/snippets", Some(&tahinli)).await;
160 assert!(
161 listing.body.contains(r#"data-live="/snippets/events""#),
162 "list follows its stream"
163 );
164 let page = env
165 .app
166 .get(&format!("/snippets/{id}"), Some(&tahinli))
167 .await;
168 assert!(
169 page.body.contains(&format!(r#"data-live="{item}""#)),
170 "snippet page follows its stream"
171 );
172
173 let mut list_events = open_stream(&env.app, "/snippets/events", Some(&tahinli)).await;
174 assert_eq!(list_events.status().as_u16(), 200, "list stream");
175 let mut item_events = open_stream(&env.app, &item, Some(&tahinli)).await;
176 assert_eq!(item_events.status().as_u16(), 200, "snippet stream");
177
178 // An edit wakes both.
179 let edit_path = format!("/snippets/{id}/edit");
180 let csrf = input_value(&env.app.get(&edit_path, Some(&tahinli)).await.body, "csrf");
181 let saved = env
182 .app
183 .post_form(
184 &edit_path,
185 &[
186 ("csrf", &csrf),
187 ("title", "Live v2"),
188 ("description", ""),
189 ("visibility", "public"),
190 ("name_0", "live.txt"),
191 ("content_0", "two\n"),
192 ],
193 Some(&tahinli),
194 )
195 .await;
196 assert_eq!(saved.status, 303, "edit: {}", saved.body);
197 next_change(&mut list_events, "an edit").await;
198 next_change(&mut item_events, "an edit").await;
199
200 // A create wakes the list only.
201 let other = create(
202 &env.app,
203 &tahinli,
204 "Second",
205 "public",
206 &[("two.txt", "2\n")],
207 )
208 .await;
209 next_change(&mut list_events, "a create").await;
210
211 // A delete wakes the list, and the snippet's stream sends `changed` too: its page now 404s.
212 let csrf = input_value(
213 &env.app
214 .get(&format!("/snippets/{other}"), Some(&tahinli))
215 .await
216 .body,
217 "csrf",
218 );
219 let deleted = env
220 .app
221 .post_form(
222 &format!("/snippets/{other}/delete"),
223 &[("csrf", &csrf)],
224 Some(&tahinli),
225 )
226 .await;
227 assert_eq!(deleted.status, 303, "delete: {}", deleted.body);
228 next_change(&mut list_events, "a delete").await;
229
230 // A private snippet: the owner's stream opens, everyone else gets 404 (anonymous too).
231 let secret = create(
232 &env.app,
233 &tahinli,
234 "Secret",
235 "private",
236 &[("s.txt", "shh\n")],
237 )
238 .await;
239 let secret_item = format!("/snippets/{secret}/events");
240 assert_eq!(
241 open_stream(&env.app, &secret_item, Some(&tahinli))
242 .await
243 .status()
244 .as_u16(),
245 200,
246 "owner opens the private stream"
247 );
248 assert_eq!(
249 open_stream(&env.app, &secret_item, Some(&bob))
250 .await
251 .status()
252 .as_u16(),
253 404,
254 "others get 404"
255 );
256 assert_eq!(
257 open_stream(&env.app, &secret_item, None)
258 .await
259 .status()
260 .as_u16(),
261 404,
262 "anonymous gets 404"
263 );
264}
265
266#[tokio::test]
267async fn create_edit_and_revisions() {
268 let env = start().await;
269 let tahinli = login(&env.app, "tahinli", PW).await;
270 let id = create(
271 &env.app,
272 &tahinli,
273 "Greeting",
274 "public",
275 &[("hello.txt", "hello\n")],
276 )
277 .await;
278
279 let view = env.app.get(&format!("/snippets/{id}"), None).await;
280 assert_eq!(view.status, 200);
281 assert!(view.body.contains("hello"), "file contents are shown");
282
283 let edit_path = format!("/snippets/{id}/edit");
284 let page = env.app.get(&edit_path, Some(&tahinli)).await;
285 assert_eq!(page.status, 200, "GET edit");
286 let csrf = input_value(&page.body, "csrf");
287 let saved = env
288 .app
289 .post_form(
290 &edit_path,
291 &[
292 ("csrf", &csrf),
293 ("title", "Greeting v2"),
294 ("description", "two files now"),
295 ("visibility", "public"),
296 ("name_0", "hello.txt"),
297 ("content_0", "hello v2\n"),
298 ("name_1", "notes.md"),
299 ("content_1", "# Notes\n\nSome **bold** text.\n"),
300 ],
301 Some(&tahinli),
302 )
303 .await;
304 assert_eq!(saved.status, 303, "save edit: {}", saved.body);
305
306 let view = env.app.get(&format!("/snippets/{id}"), None).await;
307 assert!(view.body.contains("Greeting v2"));
308 assert!(view.body.contains("<strong>"), "markdown file is rendered");
309 assert!(
310 view.body.contains("<strong>bold</strong>"),
311 "markdown bold renders"
312 );
313
314 let history = env
315 .app
316 .get(&format!("/snippets/{id}/revisions"), Some(&tahinli))
317 .await;
318 assert_eq!(history.status, 200);
319 assert!(
320 history.body.contains("Revision 2"),
321 "second revision listed"
322 );
323 assert!(history.body.contains("Revision 1"), "first revision listed");
324}
325
326#[tokio::test]
327async fn private_snippet_is_hidden_from_others() {
328 let env = start().await;
329 let tahinli = login(&env.app, "tahinli", PW).await;
330 let bob = login(&env.app, "bob", PW).await;
331 let id = create(
332 &env.app,
333 &tahinli,
334 "Secret",
335 "private",
336 &[("s.txt", "shh\n")],
337 )
338 .await;
339
340 let owner = env
341 .app
342 .get(&format!("/snippets/{id}"), Some(&tahinli))
343 .await;
344 assert_eq!(owner.status, 200, "owner can read");
345 assert_eq!(
346 env.app
347 .get(&format!("/snippets/{id}"), Some(&bob))
348 .await
349 .status,
350 404
351 );
352 assert_eq!(
353 env.app.get(&format!("/snippets/{id}"), None).await.status,
354 404
355 );
356
357 let list = env.app.get("/snippets", Some(&bob)).await;
358 assert!(
359 !list.body.contains("Secret"),
360 "private snippet is not listed for bob"
361 );
362
363 // Bob cannot edit or delete it either.
364 let page = env
365 .app
366 .get(&format!("/snippets/{id}/edit"), Some(&bob))
367 .await;
368 assert_eq!(page.status, 404, "bob cannot open the editor");
369 let bob_page = env.app.get("/snippets/new", Some(&bob)).await;
370 let bob_csrf = input_value(&bob_page.body, "csrf");
371 let res = env
372 .app
373 .post_form(
374 &format!("/snippets/{id}/delete"),
375 &[("csrf", &bob_csrf)],
376 Some(&bob),
377 )
378 .await;
379 assert_eq!(res.status, 404, "bob cannot delete");
380 assert_eq!(
381 env.app
382 .get(&format!("/snippets/{id}"), Some(&tahinli))
383 .await
384 .status,
385 200
386 );
387}
388
389#[tokio::test]
390async fn raw_files_use_the_user_content_origin_and_private_tokens() {
391 let env = start().await;
392 let tahinli = login(&env.app, "tahinli", PW).await;
393 let public = create(
394 &env.app,
395 &tahinli,
396 "Pub",
397 "public",
398 &[("notes.md", "# Hi\n")],
399 )
400 .await;
401 let private = create(
402 &env.app,
403 &tahinli,
404 "Priv",
405 "private",
406 &[("data.json", "{\"a\":1}\n")],
407 )
408 .await;
409
410 let page = env.app.get(&format!("/snippets/{public}"), None).await;
411 let raw = link_href(&page.body, "Raw");
412 let res = env.content.get(&path_of(&raw), None).await;
413 assert_eq!(res.status, 200, "public raw: {raw}");
414 assert!(
415 res.header(CONTENT_TYPE)
416 .unwrap_or_default()
417 .starts_with("text/markdown"),
418 "markdown content type"
419 );
420 assert_eq!(res.body, "# Hi\n");
421
422 // Private raw links carry a signed token, and the bare path is refused.
423 let page = env
424 .app
425 .get(&format!("/snippets/{private}"), Some(&tahinli))
426 .await;
427 let raw = link_href(&page.body, "Raw");
428 assert!(raw.contains("token="), "private raw link is signed: {raw}");
429 let res = env.content.get(&path_of(&raw), None).await;
430 assert_eq!(res.status, 200, "private raw with token");
431 assert!(
432 res.header(CONTENT_TYPE)
433 .unwrap_or_default()
434 .starts_with("application/json")
435 );
436 let bare = raw.split('?').next().unwrap_or_default().to_owned();
437 assert_eq!(
438 env.content.get(&path_of(&bare), None).await.status,
439 404,
440 "no token, no file"
441 );
442
443 let missing = format!("/-/snippets/{public}/nope.txt");
444 assert_eq!(env.content.get(&missing, None).await.status, 404);
445}
446
447#[tokio::test]
448async fn unlisted_is_by_link_only_and_delete_removes_it() {
449 let env = start().await;
450 let tahinli = login(&env.app, "tahinli", PW).await;
451 let id = create(
452 &env.app,
453 &tahinli,
454 "Link only",
455 "unlisted",
456 &[("a.txt", "x\n")],
457 )
458 .await;
459
460 let list = env.app.get("/snippets", None).await;
461 assert!(!list.body.contains("Link only"), "unlisted is not listed");
462 assert_eq!(
463 env.app.get(&format!("/snippets/{id}"), None).await.status,
464 200
465 );
466
467 let page = env
468 .app
469 .get(&format!("/snippets/{id}"), Some(&tahinli))
470 .await;
471 let csrf = input_value(&page.body, "csrf");
472 let res = env
473 .app
474 .post_form(
475 &format!("/snippets/{id}/delete"),
476 &[("csrf", &csrf)],
477 Some(&tahinli),
478 )
479 .await;
480 assert_eq!(res.status, 303, "delete: {}", res.body);
481 assert_eq!(
482 env.app.get(&format!("/snippets/{id}"), None).await.status,
483 404
484 );
485}
486
487#[tokio::test]
488async fn bad_input_redisplays_the_form_with_an_error() {
489 let env = start().await;
490 let tahinli = login(&env.app, "tahinli", PW).await;
491 let page = env.app.get("/snippets/new", Some(&tahinli)).await;
492 let csrf = input_value(&page.body, "csrf");
493 let res = env
494 .app
495 .post_form(
496 "/snippets/new",
497 &[
498 ("csrf", &csrf),
499 ("title", "Bad"),
500 ("visibility", "public"),
501 ("name_0", "a/b.txt"),
502 ("content_0", "x"),
503 ],
504 Some(&tahinli),
505 )
506 .await;
507 assert_eq!(res.status, 200, "invalid input is not a redirect");
508 assert!(
509 res.body.contains("may only use"),
510 "error shown: {}",
511 res.body
512 );
513 assert!(
514 res.body.contains("a/b.txt") || res.body.contains("Bad"),
515 "input kept"
516 );
517}