forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

wiki_e2e.rs469 lines, 16.5 KiBHistoryRawDownload
1//! Black-box test for the repo wiki. It seeds users and a repo through the store, starts the real
2//! `forge` binary and drives the wiki pages, the HTTPS clone and push of `<repo>.wiki.git`, the
3//! read-only and stale-edit refusals, and the backup of the wiki.
4//!
5//! Cookies are handled by hand because the session cookie is `__Host-forge_session` with `Secure`,
6//! which a cookie jar would not send over plain http.
7
8use crate::common::{
9 Http, Resp, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,
10};
11use std::fs;
12use std::path::Path;
13use std::process::{Command, Output};
14use std::time::Duration;
15
16use forge_core::{Role, Store, Visibility};
17use reqwest::header::{COOKIE, LOCATION};
18
19const PW: &str = "tahinli-password-123";
20
21/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
22fn admin(config: &Path, args: &[&str]) {
23 let out = Command::new(bin())
24 .arg("--config")
25 .arg(config)
26 .arg("admin")
27 .args(args)
28 .env("FORGE_PASSWORD", PW)
29 .output()
30 .expect("run admin command");
31 assert!(
32 out.status.success(),
33 "admin {args:?} failed:\n{}",
34 describe(&out)
35 );
36}
37
38/// The session's CSRF token, read from a page every signed-in user can open.
39async fn csrf_for(http: &Http, session: &str) -> String {
40 let page = http.get("/settings/keys", Some(session)).await;
41 assert_eq!(page.status, 200, "GET /settings/keys");
42 input_value(&page.body, "csrf")
43}
44
45/// Creates an access token through `/settings/tokens` and returns the token shown once.
46async fn create_token(http: &Http, session: &str, name: &str) -> String {
47 let csrf = csrf_for(http, session).await;
48 let res = http
49 .post_form(
50 "/settings/tokens",
51 &[("csrf", &csrf), ("name", name), ("expires", "30")],
52 Some(session),
53 )
54 .await;
55 assert_eq!(res.status, 200, "create token: {}", res.body);
56 let doc = scraper::Html::parse_document(&res.body);
57 let selector = scraper::Selector::parse("pre.code code").expect("selector");
58 let token: String = doc
59 .select(&selector)
60 .next()
61 .expect("token shown after creation")
62 .text()
63 .collect();
64 let token = token.trim().to_owned();
65 assert!(token.starts_with("forge_"), "unexpected token shape");
66 token
67}
68
69/// Creates a bare git repo for `repo_id` at its data-dir location, as the create-repo page does.
70fn init_bare(data_dir: &Path, repo_id: &str) {
71 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");
72 fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");
73 let out = Command::new("git")
74 .args(["init", "--bare", "--quiet", "--initial-branch=main"])
75 .arg(&path)
76 .output()
77 .expect("run git init");
78 assert!(out.status.success(), "git init --bare: {}", describe(&out));
79}
80
81fn git(cwd: &Path, args: &[&str]) -> Output {
82 Command::new("git")
83 .current_dir(cwd)
84 .args(["-c", "credential.helper="])
85 .args(args)
86 .env("GIT_TERMINAL_PROMPT", "0")
87 .output()
88 .expect("run git")
89}
90
91fn ok(out: &Output, what: &str) {
92 assert!(out.status.success(), "{what} failed:\n{}", describe(out));
93}
94
95fn path_str(path: &Path) -> &str {
96 path.to_str().expect("utf-8 path")
97}
98
99/// Writes a file under `repo` (creating its directory) and commits it as `bob`.
100fn commit_file(repo: &Path, name: &str, content: &str, message: &str) {
101 let file = repo.join(name);
102 fs::create_dir_all(file.parent().expect("parent")).expect("create dir");
103 fs::write(&file, content).expect("write file");
104 ok(&git(repo, &["config", "user.name", "bob"]), "set user.name");
105 ok(
106 &git(repo, &["config", "user.email", "bob@example.com"]),
107 "set user.email",
108 );
109 ok(&git(repo, &["add", name]), "git add");
110 ok(
111 &git(
112 repo,
113 &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message],
114 ),
115 "git commit",
116 );
117}
118
119/// Reads the wiki page `name` as the viewer, returns its body.
120async fn page_body(http: &Http, path: &str, session: Option<&str>) -> Resp {
121 let res = http.get(path, session).await;
122 assert_eq!(res.status, 200, "GET {path}: {}", res.body);
123 res
124}
125
126#[tokio::test]
127async fn wiki_end_to_end() {
128 if !tool_on_path("git") {
129 eprintln!("SKIP wiki_e2e: `git` was not found on PATH");
130 return;
131 }
132
133 // Keep the path short: the data dir holds a unix socket with a length limit.
134 let root = tempfile::Builder::new()
135 .prefix("fwk")
136 .tempdir_in("/tmp")
137 .expect("temp dir");
138 let dir = root.path().to_path_buf();
139 let ports = pick_ports();
140 let config = write_config(&dir, ports);
141
142 // Bob owns a public repo. Carol has Write on it. Dave has only the Read that a public repo gives.
143 admin(&config, &["create-user", "tahinli", "--admin"]);
144 for name in ["bob", "carol", "dave"] {
145 admin(&config, &["create-user", name]);
146 }
147 {
148 let store = Store::open(&dir.join("forge.db"))
149 .await
150 .expect("open store");
151 let bob = store.user_by_username("bob").await.unwrap().expect("bob");
152 let carol = store
153 .user_by_username("carol")
154 .await
155 .unwrap()
156 .expect("carol");
157 let repo = store
158 .create_repo(&bob.id, "proj", "", Visibility::Public, "main")
159 .await
160 .expect("repo");
161 store
162 .set_collaborator(&repo.id, &carol.id, Role::Write)
163 .await
164 .expect("carol write");
165 init_bare(&dir, &repo.id);
166 }
167
168 let (server, ports) = launch(&dir, ports).await;
169 let http = Http::new(ports.http);
170 let bob = login(&http, "bob", PW).await;
171 let carol = login(&http, "carol", PW).await;
172 let dave = login(&http, "dave", PW).await;
173
174 // The wiki starts empty, and the tab is there.
175 let empty = page_body(&http, "/bob/proj/wiki", Some(&bob)).await;
176 assert!(empty.body.contains("no pages yet"), "{}", empty.body);
177
178 // Bob creates Home on the web. The save redirects to the page.
179 let csrf = input_value(
180 &http.get("/bob/proj/wiki/-/new", Some(&bob)).await.body,
181 "csrf",
182 );
183 let saved = http
184 .post_form(
185 "/bob/proj/wiki/-/new",
186 &[
187 ("csrf", &csrf),
188 ("name", "Home"),
189 ("base", ""),
190 ("content", "# Welcome\n\nSee [[Getting Started]].\n"),
191 ("message", "first page"),
192 ],
193 Some(&bob),
194 )
195 .await;
196 assert_eq!(saved.status, 303, "create Home: {}", saved.body);
197 assert_eq!(
198 saved.header(LOCATION).as_deref(),
199 Some("/bob/proj/wiki/Home")
200 );
201 let home = page_body(&http, "/bob/proj/wiki/Home", Some(&bob)).await;
202 assert!(home.body.contains("Welcome"), "{}", home.body);
203 assert!(
204 home.body.contains("/bob/proj/wiki/Getting-Started"),
205 "wiki link should resolve: {}",
206 home.body
207 );
208
209 // Dave can read the page but not edit it.
210 page_body(&http, "/bob/proj/wiki/Home", Some(&dave)).await;
211 let refused = http.get("/bob/proj/wiki/Home/edit", Some(&dave)).await;
212 assert_eq!(refused.status, 403, "read-only user must not edit");
213
214 // Carol clones the wiki over HTTPS, sees Home, and pushes a change.
215 let carol_token = create_token(&http, &carol, "wiki-e2e").await;
216 let work = dir.join("wiki-work");
217 let url = format!(
218 "http://carol:{carol_token}@127.0.0.1:{}/bob/proj.wiki.git",
219 ports.http
220 );
221 ok(
222 &git(&dir, &["clone", "-q", &url, path_str(&work)]),
223 "clone wiki over HTTPS",
224 );
225 let text = fs::read_to_string(work.join("Home.md")).expect("Home.md in clone");
226 assert!(text.contains("Welcome"), "{text}");
227 commit_file(&work, "Home.md", "# Welcome again\n", "edit from git");
228 ok(
229 &git(&work, &["push", "-q", "origin", "HEAD:main"]),
230 "push wiki change over HTTPS",
231 );
232 let after_push = page_body(&http, "/bob/proj/wiki/Home", Some(&carol)).await;
233 assert!(
234 after_push.body.contains("Welcome again"),
235 "{}",
236 after_push.body
237 );
238 // The push is in the admin audit log (read over HTTP, the server holds the database open).
239 let tahinli = login(&http, "tahinli", PW).await;
240 let audit = http
241 .get("/admin/audit?action=wiki_pushed", Some(&tahinli))
242 .await;
243 assert_eq!(audit.status, 200, "audit page");
244 assert!(
245 audit.body.contains("data-action=\"wiki_pushed\""),
246 "the wiki push is audited: {}",
247 audit.body
248 );
249 assert!(audit.body.contains("carol"), "the pusher is named");
250 assert!(audit.body.contains("bob/proj"), "the repo is named");
251
252 // A save that started from the old head is refused with the conflict message, not applied.
253 let stale_csrf = input_value(
254 &http
255 .get("/bob/proj/wiki/Home/edit", Some(&carol))
256 .await
257 .body,
258 "csrf",
259 );
260 let stale = http
261 .post_form(
262 "/bob/proj/wiki/Home/edit",
263 &[
264 ("csrf", &stale_csrf),
265 ("base", "0000000000000000000000000000000000000000"),
266 ("content", "# Lost write\n"),
267 ("message", "stale"),
268 ],
269 Some(&carol),
270 )
271 .await;
272 assert_eq!(stale.status, 200, "{}", stale.body);
273 assert!(
274 stale.body.contains("while you were editing"),
275 "{}",
276 stale.body
277 );
278 let still = page_body(&http, "/bob/proj/wiki/Home", Some(&bob)).await;
279 assert!(still.body.contains("Welcome again"), "{}", still.body);
280
281 // The history lists both edits.
282 let history = page_body(&http, "/bob/proj/wiki/Home/history", Some(&bob)).await;
283 assert!(history.body.contains("first page"), "{}", history.body);
284 assert!(history.body.contains("edit from git"), "{}", history.body);
285
286 // Dave cannot push to the wiki.
287 let dave_token = create_token(&http, &dave, "wiki-e2e").await;
288 let dave_url = format!(
289 "http://dave:{dave_token}@127.0.0.1:{}/bob/proj.wiki.git",
290 ports.http
291 );
292 let dave_work = dir.join("wiki-dave");
293 ok(
294 &git(&dir, &["clone", "-q", &dave_url, path_str(&dave_work)]),
295 "dave clones the public wiki",
296 );
297 commit_file(&dave_work, "Hack.md", "x\n", "not allowed");
298 let denied = git(&dave_work, &["push", "-q", "origin", "HEAD:main"]);
299 assert!(!denied.status.success(), "read-only push must fail");
300
301 // Bob turns the wiki off on the settings page. Carol, who is not an admin, cannot.
302 let settings = page_body(&http, "/bob/proj/settings", Some(&bob)).await;
303 assert!(
304 settings.body.contains("action=\"/bob/proj/settings/wiki\""),
305 "{}",
306 settings.body
307 );
308 let forbidden_toggle = http.get("/bob/proj/settings", Some(&carol)).await;
309 assert_eq!(
310 forbidden_toggle.status, 403,
311 "only admins see wiki settings"
312 );
313 let off = http
314 .post_form(
315 "/bob/proj/settings/wiki",
316 &[("csrf", &input_value(&settings.body, "csrf"))],
317 Some(&bob),
318 )
319 .await;
320 assert_eq!(off.status, 303, "{}", off.body);
321 let hidden = http.get("/bob/proj/wiki", Some(&bob)).await;
322 assert_eq!(hidden.status, 404, "disabled wiki must be hidden");
323 commit_file(&work, "Other.md", "x\n", "after disable");
324 let refused_push = git(&work, &["push", "-q", "origin", "HEAD:main"]);
325 assert!(
326 !refused_push.status.success(),
327 "push to a disabled wiki must fail"
328 );
329
330 drop(server);
331}
332
333/// Opens a wiki stream as `cookie` (or anonymously) and reads its `retry` field.
334async fn open_wiki_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response {
335 let mut req = http.client.get(format!("{}{path}", http.base));
336 if let Some(cookie) = cookie {
337 req = req.header(COOKIE, cookie);
338 }
339 let mut res = req.send().await.expect("stream request");
340 assert_eq!(res.status().as_u16(), 200, "stream {path}");
341 let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk())
342 .await
343 .expect("the retry field")
344 .expect("stream chunk")
345 .expect("stream still open");
346 assert!(String::from_utf8_lossy(&retry).contains("retry: 1000"));
347 res
348}
349
350/// Waits for the next event of a wiki stream, which must be `changed`.
351async fn next_wiki_change(res: &mut reqwest::Response, what: &str) {
352 let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())
353 .await
354 .unwrap_or_else(|_| panic!("no event after {what}"))
355 .expect("stream chunk")
356 .expect("stream still open");
357 let text = String::from_utf8_lossy(&chunk);
358 assert!(text.contains("event: changed"), "{what}: {text}");
359}
360
361/// The wiki pages render their streams. A save from the web and a push from the wiki repo each
362/// wake the wiki streams, and a viewer who cannot read the repo gets 404 from them.
363#[tokio::test]
364async fn wiki_streams_follow_saves_and_pushes() {
365 if !tool_on_path("git") {
366 eprintln!("SKIP wiki live: `git` was not found on PATH");
367 return;
368 }
369
370 let root = tempfile::Builder::new()
371 .prefix("fwl")
372 .tempdir_in("/tmp")
373 .expect("temp dir");
374 let dir = root.path().to_path_buf();
375 let ports = pick_ports();
376 let config = write_config(&dir, ports);
377
378 admin(&config, &["create-user", "tahinli", "--admin"]);
379 for name in ["bob", "dave"] {
380 admin(&config, &["create-user", name]);
381 }
382 {
383 let store = Store::open(&dir.join("forge.db"))
384 .await
385 .expect("open store");
386 let bob = store.user_by_username("bob").await.unwrap().expect("bob");
387 let proj = store
388 .create_repo(&bob.id, "proj", "", Visibility::Public, "main")
389 .await
390 .expect("repo");
391 init_bare(&dir, &proj.id);
392 let vault = store
393 .create_repo(&bob.id, "vault", "", Visibility::Private, "main")
394 .await
395 .expect("private repo");
396 init_bare(&dir, &vault.id);
397 }
398
399 let (server, ports) = launch(&dir, ports).await;
400 let http = Http::new(ports.http);
401 let bob = login(&http, "bob", PW).await;
402 let dave = login(&http, "dave", PW).await;
403
404 // The page list follows the wiki stream.
405 let listing = page_body(&http, "/bob/proj/wiki/-/pages", Some(&bob)).await;
406 assert!(
407 listing
408 .body
409 .contains(r#"data-live="/bob/proj/wiki/-/events""#),
410 "page list follows the wiki stream"
411 );
412
413 // Bob opens the wiki stream, then creates Home on the web: the stream wakes.
414 let mut wiki_events = open_wiki_stream(&http, "/bob/proj/wiki/-/events", Some(&bob)).await;
415 let csrf = input_value(
416 &http.get("/bob/proj/wiki/-/new", Some(&bob)).await.body,
417 "csrf",
418 );
419 let created = http
420 .post_form(
421 "/bob/proj/wiki/-/new",
422 &[
423 ("csrf", &csrf),
424 ("name", "Home"),
425 ("base", ""),
426 ("content", "# Welcome\n"),
427 ("message", "first page"),
428 ],
429 Some(&bob),
430 )
431 .await;
432 assert_eq!(created.status, 303, "create Home: {}", created.body);
433 next_wiki_change(&mut wiki_events, "a web save").await;
434
435 // The page's own stream follows Home, and a push from git wakes it.
436 let home = page_body(&http, "/bob/proj/wiki/Home", Some(&bob)).await;
437 assert!(
438 home.body
439 .contains(r#"data-live="/bob/proj/wiki/Home/events""#),
440 "wiki page follows its stream"
441 );
442 let mut home_events = open_wiki_stream(&http, "/bob/proj/wiki/Home/events", Some(&bob)).await;
443 let token = create_token(&http, &bob, "wiki-live").await;
444 let work = dir.join("wiki-live-work");
445 let url = format!(
446 "http://bob:{token}@127.0.0.1:{}/bob/proj.wiki.git",
447 ports.http
448 );
449 ok(
450 &git(&dir, &["clone", "-q", &url, path_str(&work)]),
451 "clone wiki over HTTPS",
452 );
453 commit_file(&work, "Home.md", "# Pushed\n", "edit from git");
454 ok(
455 &git(&work, &["push", "-q", "origin", "HEAD:main"]),
456 "push to wiki",
457 );
458 next_wiki_change(&mut home_events, "a push to the wiki").await;
459
460 // A viewer who cannot read the private repo gets 404 from its streams.
461 for path in ["/bob/vault/wiki/-/events", "/bob/vault/wiki/Home/events"] {
462 let res = http.get(path, Some(&dave)).await;
463 assert_eq!(res.status, 404, "{path} for a non-member");
464 let anon = http.get(path, None).await;
465 assert_eq!(anon.status, 404, "{path} anonymously");
466 }
467
468 drop(server);
469}