forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

git_e2e.rs583 lines, 19.0 KiBHistoryRawDownload
1//! Black-box end-to-end test. It starts the real `forge` binary and drives it with the real
2//! `git` and `ssh` clients over smart HTTP and SSH, plus raw HTTP requests for the negative cases.
3//!
4//! Cookies are handled by hand: the session cookie is `__Host-forge_session` with `Secure`, so a
5//! cookie jar would not send it over plain http. The test parses `Set-Cookie` and sends `Cookie`.
6
7use crate::common::{
8 Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,
9};
10use std::fs;
11use std::path::{Path, PathBuf};
12use std::process::{Command, Output};
13
14use reqwest::header::WWW_AUTHENTICATE;
15
16const TAHINLI_PW: &str = "tahinli-password-123";
17const BOB_PW: &str = "bob-password-4567";
18
19fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
20 let out = Command::new(bin())
21 .arg("--config")
22 .arg(config)
23 .args(["admin", "create-user", username])
24 .args(extra)
25 .env("FORGE_PASSWORD", password)
26 .output()
27 .expect("run admin create-user");
28 ok(&out, &format!("create-user {username}"));
29}
30
31fn ok(out: &Output, what: &str) {
32 assert!(out.status.success(), "{what} failed:\n{}", describe(out));
33}
34
35/// Asserts failure and returns the combined output for further checks.
36fn rejected(out: &Output, what: &str) -> String {
37 assert!(
38 !out.status.success(),
39 "{what} unexpectedly succeeded:\n{}",
40 describe(out)
41 );
42 describe(out)
43}
44
45fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
46 let mut cmd = Command::new("git");
47 cmd.current_dir(cwd)
48 .args(["-c", "credential.helper="])
49 .args(args)
50 .env("GIT_TERMINAL_PROMPT", "0");
51 for (key, value) in env {
52 cmd.env(key, value);
53 }
54 cmd.output().expect("run git")
55}
56
57fn path_str(path: &Path) -> &str {
58 path.to_str().expect("utf-8 path")
59}
60
61/// The ssh command git runs for SSH remotes. Host key checks are off because the host key is
62/// new on every run.
63fn ssh_opts(key: &Path, ssh_port: u16) -> Vec<String> {
64 [
65 "-i",
66 path_str(key),
67 "-o",
68 "IdentitiesOnly=yes",
69 "-o",
70 "StrictHostKeyChecking=no",
71 "-o",
72 "UserKnownHostsFile=/dev/null",
73 "-o",
74 "BatchMode=yes",
75 "-o",
76 "LogLevel=ERROR",
77 "-p",
78 ]
79 .iter()
80 .map(|s| (*s).to_owned())
81 .chain(std::iter::once(ssh_port.to_string()))
82 .collect()
83}
84
85fn ssh_command(key: &Path, ssh_port: u16) -> String {
86 format!("ssh {}", ssh_opts(key, ssh_port).join(" "))
87}
88
89fn gen_key(path: &Path) {
90 let out = Command::new("ssh-keygen")
91 .args(["-t", "ed25519", "-N", "", "-q", "-f"])
92 .arg(path)
93 .output()
94 .expect("run ssh-keygen");
95 ok(&out, "ssh-keygen");
96}
97
98fn set_identity(repo: &Path) {
99 ok(
100 &git(repo, &["config", "user.name", "tahinli"], &[]),
101 "set user.name",
102 );
103 ok(
104 &git(repo, &["config", "user.email", "tahinli@example.com"], &[]),
105 "set user.email",
106 );
107}
108
109/// Writes a file and commits it in `repo` with the repo's local identity.
110fn commit_file(repo: &Path, name: &str, content: &str, message: &str) {
111 fs::write(repo.join(name), content).expect("write file");
112 set_identity(repo);
113 ok(&git(repo, &["add", name], &[]), "git add");
114 ok(
115 &git(
116 repo,
117 &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message],
118 &[],
119 ),
120 "git commit",
121 );
122}
123
124fn head_sha(repo: &Path) -> String {
125 let out = git(repo, &["rev-parse", "HEAD"], &[]);
126 ok(&out, "rev-parse HEAD");
127 String::from_utf8_lossy(&out.stdout).trim().to_owned()
128}
129
130/// True when a file called `name` exists anywhere under `dir`.
131fn find_file(dir: &Path, name: &str) -> bool {
132 std::fs::read_dir(dir).is_ok_and(|entries| {
133 entries.flatten().any(|entry| {
134 entry.file_name() == name || (entry.path().is_dir() && find_file(&entry.path(), name))
135 })
136 })
137}
138
139fn read(path: PathBuf) -> String {
140 fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()))
141}
142
143/// Creates an access token through `/settings/tokens` and returns the token shown once.
144async fn create_token(http: &Http, session: &str, name: &str) -> String {
145 let page = http.get_cookie("/settings/keys", session).await;
146 assert_eq!(page.status, 200, "GET /settings/keys");
147 let csrf = input_value(&page.body, "csrf");
148 let res = http
149 .post_form(
150 "/settings/tokens",
151 &[("csrf", &csrf), ("name", name), ("expires", "30")],
152 Some(session),
153 )
154 .await;
155 assert_eq!(res.status, 200, "create token: {}", res.body);
156 let doc = scraper::Html::parse_document(&res.body);
157 let selector = scraper::Selector::parse("pre.code code").expect("selector");
158 let token: String = doc
159 .select(&selector)
160 .next()
161 .expect("token shown after creation")
162 .text()
163 .collect();
164 let token = token.trim().to_owned();
165 assert!(token.starts_with("forge_"), "unexpected token shape");
166 token
167}
168
169/// Adds a public key through `/settings/keys`.
170async fn add_key(http: &Http, session: &str, public_key: &str) {
171 let page = http.get_cookie("/settings/keys", session).await;
172 assert_eq!(page.status, 200, "GET /settings/keys");
173 let csrf = input_value(&page.body, "csrf");
174 let res = http
175 .post_form(
176 "/settings/keys",
177 &[
178 ("csrf", &csrf),
179 ("title", "e2e"),
180 ("public_key", public_key),
181 ],
182 Some(session),
183 )
184 .await;
185 assert_eq!(res.status, 303, "add SSH key: {}", res.body);
186}
187
188/// Creates a repo through `/new`.
189async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) {
190 let page = http.get_cookie("/new", session).await;
191 assert_eq!(page.status, 200, "GET /new");
192 let csrf = input_value(&page.body, "csrf");
193 let res = http
194 .post_form(
195 "/new",
196 &[
197 ("csrf", &csrf),
198 ("name", name),
199 ("description", ""),
200 ("visibility", visibility),
201 ("default_branch", "main"),
202 ],
203 Some(session),
204 )
205 .await;
206 assert_eq!(res.status, 303, "create repo {name}: {}", res.body);
207 assert_eq!(
208 res.location().as_deref(),
209 Some(format!("/tahinli/{name}").as_str())
210 );
211}
212
213#[tokio::test]
214async fn git_end_to_end() {
215 for tool in ["git", "ssh", "ssh-keygen"] {
216 if !tool_on_path(tool) {
217 eprintln!(
218 "SKIP git_e2e: `{tool}` was not found on PATH, so the end-to-end test is skipped"
219 );
220 return;
221 }
222 }
223
224 // Keep the path short: the internal unix socket path is limited to 108 bytes.
225 let root = tempfile::Builder::new()
226 .prefix("fe2e")
227 .tempdir_in("/tmp")
228 .expect("temp dir");
229 let dir = root.path().to_path_buf();
230 let ports = pick_ports();
231 let config = write_config(&dir, ports);
232
233 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
234 run_admin(&config, "bob", &[], BOB_PW);
235
236 let (_server, ports) = launch(&dir, ports).await;
237 let http = Http::new(ports.http);
238 let (http_port, ssh_port) = (ports.http, ports.ssh);
239
240 // Web setup: tahinli logs in, makes a token, adds an SSH key and creates both repos.
241 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
242 let tahinli_token = create_token(&http, &tahinli, "e2e-token").await;
243
244 let key = dir.join("id");
245 gen_key(&key);
246 let public_key = fs::read_to_string(dir.join("id.pub")).expect("read id.pub");
247 add_key(&http, &tahinli, public_key.trim()).await;
248
249 create_repo(&http, &tahinli, "pub", "public").await;
250 create_repo(&http, &tahinli, "priv", "private").await;
251
252 // HTTPS: push to the public repo with the token, then read it back.
253 let pub_url = format!("http://tahinli:{tahinli_token}@127.0.0.1:{http_port}/tahinli/pub.git");
254 let pub_work = dir.join("pub-work");
255 ok(
256 &git(&dir, &["clone", &pub_url, path_str(&pub_work)], &[]),
257 "https clone of empty public repo",
258 );
259 commit_file(&pub_work, "hello.txt", "hello over https\n", "https commit");
260 ok(
261 &git(&pub_work, &["push", "origin", "HEAD:main"], &[]),
262 "https push",
263 );
264 let pushed_main = head_sha(&pub_work);
265
266 let pub_verify = dir.join("pub-verify");
267 ok(
268 &git(&dir, &["clone", &pub_url, path_str(&pub_verify)], &[]),
269 "https fresh clone",
270 );
271 assert_eq!(read(pub_verify.join("hello.txt")), "hello over https\n");
272
273 // Anonymous clone of a public repo must succeed.
274 let anon_url = format!("http://127.0.0.1:{http_port}/tahinli/pub.git");
275 let pub_anon = dir.join("pub-anon");
276 ok(
277 &git(&dir, &["clone", &anon_url, path_str(&pub_anon)], &[]),
278 "anonymous clone of public repo",
279 );
280 assert_eq!(read(pub_anon.join("hello.txt")), "hello over https\n");
281 let pub_shallow = dir.join("pub-shallow");
282 ok(
283 &git(
284 &dir,
285 &["clone", "--depth", "1", &anon_url, path_str(&pub_shallow)],
286 &[],
287 ),
288 "anonymous shallow clone",
289 );
290
291 // SSH: push to the private repo with the registered key, then read it back.
292 let ssh_cmd = ssh_command(&key, ssh_port);
293 let ssh_env = [("GIT_SSH_COMMAND", ssh_cmd.as_str())];
294 let priv_ssh_url = format!("ssh://git@127.0.0.1:{ssh_port}/tahinli/priv.git");
295 let priv_work = dir.join("priv-work");
296 ok(
297 &git(
298 &dir,
299 &["clone", &priv_ssh_url, path_str(&priv_work)],
300 &ssh_env,
301 ),
302 "ssh clone of empty private repo",
303 );
304 commit_file(&priv_work, "secret.txt", "over ssh\n", "ssh commit");
305 ok(
306 &git(&priv_work, &["push", "origin", "HEAD:main"], &ssh_env),
307 "ssh push",
308 );
309 let priv_verify = dir.join("priv-verify");
310 ok(
311 &git(
312 &dir,
313 &["clone", &priv_ssh_url, path_str(&priv_verify)],
314 &ssh_env,
315 ),
316 "ssh fresh clone",
317 );
318 assert_eq!(read(priv_verify.join("secret.txt")), "over ssh\n");
319
320 // Negative: private repo without credentials.
321 let priv_https_anon = format!("http://127.0.0.1:{http_port}/tahinli/priv.git");
322 rejected(
323 &git(&dir, &["clone", &priv_https_anon, "anon-priv"], &[]),
324 "anonymous clone of private repo",
325 );
326 let refs_path = "/tahinli/priv.git/info/refs?service=git-upload-pack";
327 let anon_refs = http.get(refs_path, None).await;
328 assert_eq!(anon_refs.status, 401, "anonymous info/refs on private repo");
329 assert!(
330 anon_refs.header(WWW_AUTHENTICATE).is_some(),
331 "401 must carry WWW-Authenticate"
332 );
333
334 // Negative: bob is signed in but has no access, so the private repo looks absent.
335 let bob = login(&http, "bob", BOB_PW).await;
336 let bob_page = http.get_cookie("/tahinli/priv", &bob).await;
337 assert_eq!(bob_page.status, 404, "bob's web view of tahinli/priv");
338 let bob_token = create_token(&http, &bob, "bob-token").await;
339 let bob_refs = http.get_basic(refs_path, "bob", &bob_token).await;
340 assert_eq!(bob_refs.status, 404, "bob's info/refs on tahinli/priv");
341
342 // Negative: a wrong token is rejected.
343 let wrong = http
344 .get_basic(refs_path, "tahinli", "forge_notarealtoken")
345 .await;
346 assert_eq!(wrong.status, 401, "wrong token on info/refs");
347 let wrong_url =
348 format!("http://tahinli:forge_notarealtoken@127.0.0.1:{http_port}/tahinli/priv.git");
349 rejected(
350 &git(&dir, &["clone", &wrong_url, "wrong-token-clone"], &[]),
351 "clone with wrong token",
352 );
353
354 // Negative: deleting the default branch is rejected by pre-receive.
355 let delete = git(&pub_verify, &["push", "origin", "--delete", "main"], &[]);
356 let text = rejected(&delete, "deleting main");
357 assert!(
358 text.contains("deleting protected branch 'main' is not allowed"),
359 "delete message: {text}"
360 );
361
362 // Negative: a force-push to main after amending the commit is rejected.
363 set_identity(&pub_verify);
364 ok(
365 &git(
366 &pub_verify,
367 &[
368 "-c",
369 "commit.gpgsign=false",
370 "commit",
371 "--amend",
372 "-q",
373 "-m",
374 "rewritten",
375 ],
376 &[],
377 ),
378 "amend commit",
379 );
380 let force = git(&pub_verify, &["push", "-f", "origin", "HEAD:main"], &[]);
381 let text = rejected(&force, "force-push to main");
382 assert!(
383 text.contains("force-push to protected branch 'main' is not allowed"),
384 "force-push message: {text}"
385 );
386
387 // main must still point at the commit that was pushed.
388 let ls = git(&dir, &["ls-remote", &pub_url, "refs/heads/main"], &[]);
389 ok(&ls, "ls-remote main");
390 let remote_main = String::from_utf8_lossy(&ls.stdout);
391 assert!(
392 remote_main.starts_with(&pushed_main),
393 "main moved after rejected pushes: {remote_main}"
394 );
395
396 // A force push to another branch takes the old commit's page down and marks it for removal.
397 ok(
398 &git(
399 &pub_verify,
400 &["push", "origin", "HEAD:refs/heads/scratch"],
401 &[],
402 ),
403 "push scratch",
404 );
405 let overwritten = head_sha(&pub_verify);
406 let page = format!("/tahinli/pub/commit/{overwritten}");
407 assert_eq!(
408 http.get(&page, None).await.status,
409 200,
410 "commit on a branch"
411 );
412 ok(
413 &git(
414 &pub_verify,
415 &[
416 "-c",
417 "commit.gpgsign=false",
418 "commit",
419 "--amend",
420 "-q",
421 "-m",
422 "rewritten again",
423 ],
424 &[],
425 ),
426 "amend again",
427 );
428 ok(
429 &git(&pub_verify, &["push", "-f", "origin", "HEAD:scratch"], &[]),
430 "force-push scratch",
431 );
432 assert_eq!(
433 http.get(&page, None).await.status,
434 404,
435 "overwritten commit"
436 );
437 assert!(
438 find_file(&dir, "forge-prune-due"),
439 "the force push marks the repo for pruning"
440 );
441
442 // Negative: an SSH key that is not registered is refused.
443 let rogue = dir.join("rogue");
444 gen_key(&rogue);
445 let rogue_cmd = ssh_command(&rogue, ssh_port);
446 let rogue_env = [("GIT_SSH_COMMAND", rogue_cmd.as_str())];
447 let text = rejected(
448 &git(&dir, &["clone", &priv_ssh_url, "rogue-clone"], &rogue_env),
449 "clone with unregistered key",
450 );
451 assert!(
452 text.contains("Permission denied"),
453 "rogue key message: {text}"
454 );
455
456 // Negative: an injected path in an SSH exec request is refused by the strict parser.
457 let injected = Command::new("ssh")
458 .args(ssh_opts(&key, ssh_port))
459 .arg("git@127.0.0.1")
460 .arg("git-upload-pack '../../etc'")
461 .output()
462 .expect("run ssh");
463 rejected(&injected, "ssh exec with injected path");
464
465 // Negative: POST /new without a csrf field is forbidden.
466 let no_csrf = http
467 .post_form(
468 "/new",
469 &[
470 ("name", "nocsrf"),
471 ("visibility", "public"),
472 ("default_branch", "main"),
473 ],
474 Some(&tahinli),
475 )
476 .await;
477 assert_eq!(no_csrf.status, 403, "POST /new without csrf");
478
479 // Negative: the dumb protocol (info/refs without ?service=) is forbidden.
480 let dumb = http.get("/tahinli/pub.git/info/refs", None).await;
481 assert_eq!(dumb.status, 403, "info/refs without service");
482 assert!(
483 dumb.body.contains("dumb protocol"),
484 "dumb body: {}",
485 dumb.body
486 );
487}
488
489/// A suspended user's personal access token is refused over HTTP git: pushes and clones that
490/// worked a moment earlier fail once an admin suspends the account.
491#[tokio::test]
492async fn suspended_user_token_is_refused_over_http_git() {
493 if !tool_on_path("git") {
494 eprintln!("SKIP git_e2e: `git` was not found on PATH");
495 return;
496 }
497 let root = tempfile::Builder::new()
498 .prefix("fe2s")
499 .tempdir_in("/tmp")
500 .expect("temp dir");
501 let dir = root.path().to_path_buf();
502 let ports = pick_ports();
503 let config = write_config(&dir, ports);
504 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
505 run_admin(&config, "bob", &[], BOB_PW);
506 let (_server, ports) = launch(&dir, ports).await;
507 let http = Http::new(ports.http);
508
509 // Bob makes a token and a private repo (a public one would still clone anonymously) of his own, and can push to it.
510 let bob = login(&http, "bob", BOB_PW).await;
511 let bob_token = create_token(&http, &bob, "suspend-token").await;
512 let page = http.get_cookie("/new", &bob).await;
513 let csrf = input_value(&page.body, "csrf");
514 let created = http
515 .post_form(
516 "/new",
517 &[
518 ("csrf", &csrf),
519 ("name", "bobrepo"),
520 ("description", ""),
521 ("visibility", "private"),
522 ("default_branch", "main"),
523 ],
524 Some(&bob),
525 )
526 .await;
527 assert_eq!(created.status, 303, "create repo: {}", created.body);
528 let url = format!(
529 "http://bob:{bob_token}@127.0.0.1:{}/bob/bobrepo.git",
530 ports.http
531 );
532 let work = dir.join("work");
533 ok(
534 &git(&dir, &["clone", &url, path_str(&work)], &[]),
535 "clone before suspension",
536 );
537 commit_file(&work, "a.txt", "one\n", "first");
538 ok(
539 &git(&work, &["push", "origin", "HEAD:main"], &[]),
540 "push before suspension",
541 );
542
543 // An admin suspends bob from his account page.
544 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
545 let list = http.get_cookie("/admin/users", &tahinli).await;
546 assert_eq!(list.status, 200, "GET /admin/users");
547 let doc = scraper::Html::parse_document(&list.body);
548 let link = scraper::Selector::parse("a[href^=\"/admin/users/\"]").expect("selector");
549 let name = scraper::Selector::parse(".name").expect("selector");
550 let bob_href = doc
551 .select(&link)
552 .find(|a| {
553 a.select(&name)
554 .next()
555 .is_some_and(|n| n.text().collect::<String>().trim() == "bob")
556 })
557 .and_then(|a| a.value().attr("href"))
558 .expect("bob's admin link")
559 .to_owned();
560 let detail = http.get_cookie(&bob_href, &tahinli).await;
561 assert_eq!(detail.status, 200, "GET {bob_href}");
562 let csrf = input_value(&detail.body, "csrf");
563 let res = http
564 .post_form(
565 &format!("{bob_href}/suspend"),
566 &[("csrf", &csrf), ("reason", "e2e")],
567 Some(&tahinli),
568 )
569 .await;
570 assert_eq!(res.status, 303, "suspend bob: {}", res.body);
571
572 // The same token no longer works for a push or a clone.
573 commit_file(&work, "b.txt", "two\n", "second");
574 rejected(
575 &git(&work, &["push", "origin", "HEAD:main"], &[]),
576 "push with a suspended user's token",
577 );
578 let again = dir.join("again");
579 rejected(
580 &git(&dir, &["clone", &url, path_str(&again)], &[]),
581 "clone with a suspended user's token",
582 );
583}