forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiB2e29cbcTahinli6 hours ago333 commits

git_e2e.rs408 lines, 12.5 KiBHistoryRawDownload
1use crate::common::{
2 BOB_CMD, Http, PW, TAHINLI_CMD, boot_forge, commit_file, create_repo, create_token, csrf_for,
3 describe, git, git_env, head_sha, login, ok, path_str, set_identity, tool_on_path,
4};
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::process::{Command, Output};
8
9use reqwest::header::WWW_AUTHENTICATE;
10
11fn rejected(out: &Output, what: &str) -> String {
12 assert!(
13 !out.status.success(),
14 "{what} unexpectedly succeeded:\n{}",
15 describe(out)
16 );
17 describe(out)
18}
19
20fn ssh_opts(key: &Path, ssh_port: u16) -> Vec<String> {
21 [
22 "-i",
23 path_str(key),
24 "-o",
25 "IdentitiesOnly=yes",
26 "-o",
27 "StrictHostKeyChecking=no",
28 "-o",
29 "UserKnownHostsFile=/dev/null",
30 "-o",
31 "BatchMode=yes",
32 "-o",
33 "LogLevel=ERROR",
34 "-p",
35 ]
36 .iter()
37 .map(|s| (*s).to_owned())
38 .chain(std::iter::once(ssh_port.to_string()))
39 .collect()
40}
41
42fn ssh_command(key: &Path, ssh_port: u16) -> String {
43 format!("ssh {}", ssh_opts(key, ssh_port).join(" "))
44}
45
46fn gen_key(path: &Path) {
47 let out = Command::new("ssh-keygen")
48 .args(["-t", "ed25519", "-N", "", "-q", "-f"])
49 .arg(path)
50 .output()
51 .expect("run ssh-keygen");
52 ok(&out, "ssh-keygen");
53}
54
55fn find_file(dir: &Path, name: &str) -> bool {
56 std::fs::read_dir(dir).is_ok_and(|entries| {
57 entries.flatten().any(|entry| {
58 entry.file_name() == name || (entry.path().is_dir() && find_file(&entry.path(), name))
59 })
60 })
61}
62
63fn read(path: PathBuf) -> String {
64 fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()))
65}
66
67async fn add_key(http: &Http, session: &str, public_key: &str) {
68 let csrf = csrf_for(http, "/settings/keys", session).await;
69 let res = http
70 .post_form(
71 "/settings/keys",
72 &[
73 ("csrf", &csrf),
74 ("title", "e2e"),
75 ("public_key", public_key),
76 ],
77 Some(session),
78 )
79 .await;
80 assert_eq!(res.status, 303, "add SSH key: {}", res.body);
81}
82
83#[tokio::test]
84async fn git_end_to_end() {
85 for tool in ["git", "ssh", "ssh-keygen"] {
86 if !tool_on_path(tool) {
87 eprintln!(
88 "SKIP git_e2e: `{tool}` was not found on PATH, so the end-to-end test is skipped"
89 );
90 return;
91 }
92 }
93
94 let root = crate::common::temp_dir("fe2e");
95 let dir = root.path().to_path_buf();
96 let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await;
97 let http = Http::new(ports.http);
98 let (http_port, ssh_port) = (ports.http, ports.ssh);
99
100 let tahinli = login(&http, "tahinli", PW).await;
101 let tahinli_token = create_token(&http, &tahinli, "e2e-token").await;
102
103 let key = dir.join("id");
104 gen_key(&key);
105 let public_key = fs::read_to_string(dir.join("id.pub")).expect("read id.pub");
106 add_key(&http, &tahinli, public_key.trim()).await;
107
108 create_repo(&http, &tahinli, "pub", "public").await;
109 create_repo(&http, &tahinli, "priv", "private").await;
110
111 let pub_url = format!("http://tahinli:{tahinli_token}@127.0.0.1:{http_port}/tahinli/pub.git");
112 let pub_work = dir.join("pub-work");
113 ok(
114 &git(&dir, &["clone", &pub_url, path_str(&pub_work)]),
115 "https clone of empty public repo",
116 );
117 commit_file(&pub_work, "hello.txt", "hello over https\n", "https commit");
118 ok(
119 &git(&pub_work, &["push", "origin", "HEAD:main"]),
120 "https push",
121 );
122 let pushed_main = head_sha(&pub_work);
123
124 let pub_verify = dir.join("pub-verify");
125 ok(
126 &git(&dir, &["clone", &pub_url, path_str(&pub_verify)]),
127 "https fresh clone",
128 );
129 assert_eq!(read(pub_verify.join("hello.txt")), "hello over https\n");
130
131 let anon_url = format!("http://127.0.0.1:{http_port}/tahinli/pub.git");
132 let pub_anon = dir.join("pub-anon");
133 ok(
134 &git(&dir, &["clone", &anon_url, path_str(&pub_anon)]),
135 "anonymous clone of public repo",
136 );
137 assert_eq!(read(pub_anon.join("hello.txt")), "hello over https\n");
138 let pub_shallow = dir.join("pub-shallow");
139 ok(
140 &git(
141 &dir,
142 &["clone", "--depth", "1", &anon_url, path_str(&pub_shallow)],
143 ),
144 "anonymous shallow clone",
145 );
146
147 let ssh_cmd = ssh_command(&key, ssh_port);
148 let ssh_env = [("GIT_SSH_COMMAND", ssh_cmd.as_str())];
149 let priv_ssh_url = format!("ssh://git@127.0.0.1:{ssh_port}/tahinli/priv.git");
150 let priv_work = dir.join("priv-work");
151 ok(
152 &git_env(
153 &dir,
154 &["clone", &priv_ssh_url, path_str(&priv_work)],
155 &ssh_env,
156 ),
157 "ssh clone of empty private repo",
158 );
159 commit_file(&priv_work, "secret.txt", "over ssh\n", "ssh commit");
160 ok(
161 &git_env(&priv_work, &["push", "origin", "HEAD:main"], &ssh_env),
162 "ssh push",
163 );
164 let priv_verify = dir.join("priv-verify");
165 ok(
166 &git_env(
167 &dir,
168 &["clone", &priv_ssh_url, path_str(&priv_verify)],
169 &ssh_env,
170 ),
171 "ssh fresh clone",
172 );
173 assert_eq!(read(priv_verify.join("secret.txt")), "over ssh\n");
174
175 let priv_https_anon = format!("http://127.0.0.1:{http_port}/tahinli/priv.git");
176 rejected(
177 &git(&dir, &["clone", &priv_https_anon, "anon-priv"]),
178 "anonymous clone of private repo",
179 );
180 let refs_path = "/tahinli/priv.git/info/refs?service=git-upload-pack";
181 let anon_refs = http.get(refs_path, None).await;
182 assert_eq!(anon_refs.status, 401, "anonymous info/refs on private repo");
183 assert!(
184 anon_refs.header(WWW_AUTHENTICATE).is_some(),
185 "401 must carry WWW-Authenticate"
186 );
187
188 let bob = login(&http, "bob", PW).await;
189 let bob_page = http.get_cookie("/tahinli/priv", &bob).await;
190 assert_eq!(bob_page.status, 404, "bob's web view of tahinli/priv");
191 let bob_token = create_token(&http, &bob, "bob-token").await;
192 let bob_refs = http.get_basic(refs_path, "bob", &bob_token).await;
193 assert_eq!(bob_refs.status, 404, "bob's info/refs on tahinli/priv");
194
195 let wrong = http
196 .get_basic(refs_path, "tahinli", "forge_notarealtoken")
197 .await;
198 assert_eq!(wrong.status, 401, "wrong token on info/refs");
199 let wrong_url =
200 format!("http://tahinli:forge_notarealtoken@127.0.0.1:{http_port}/tahinli/priv.git");
201 rejected(
202 &git(&dir, &["clone", &wrong_url, "wrong-token-clone"]),
203 "clone with wrong token",
204 );
205
206 let delete = git(&pub_verify, &["push", "origin", "--delete", "main"]);
207 let text = rejected(&delete, "deleting main");
208 assert!(
209 text.contains("deleting protected branch 'main' is not allowed"),
210 "delete message: {text}"
211 );
212
213 set_identity(&pub_verify);
214 ok(
215 &git(
216 &pub_verify,
217 &[
218 "-c",
219 "commit.gpgsign=false",
220 "commit",
221 "--amend",
222 "-q",
223 "-m",
224 "rewritten",
225 ],
226 ),
227 "amend commit",
228 );
229 let force = git(&pub_verify, &["push", "-f", "origin", "HEAD:main"]);
230 let text = rejected(&force, "force-push to main");
231 assert!(
232 text.contains("force-push to protected branch 'main' is not allowed"),
233 "force-push message: {text}"
234 );
235
236 let ls = git(&dir, &["ls-remote", &pub_url, "refs/heads/main"]);
237 ok(&ls, "ls-remote main");
238 let remote_main = String::from_utf8_lossy(&ls.stdout);
239 assert!(
240 remote_main.starts_with(&pushed_main),
241 "main moved after rejected pushes: {remote_main}"
242 );
243
244 ok(
245 &git(&pub_verify, &["push", "origin", "HEAD:refs/heads/scratch"]),
246 "push scratch",
247 );
248 let overwritten = head_sha(&pub_verify);
249 let page = format!("/tahinli/pub/commit/{overwritten}");
250 assert_eq!(
251 http.get(&page, None).await.status,
252 200,
253 "commit on a branch"
254 );
255 ok(
256 &git(
257 &pub_verify,
258 &[
259 "-c",
260 "commit.gpgsign=false",
261 "commit",
262 "--amend",
263 "-q",
264 "-m",
265 "rewritten again",
266 ],
267 ),
268 "amend again",
269 );
270 ok(
271 &git(&pub_verify, &["push", "-f", "origin", "HEAD:scratch"]),
272 "force-push scratch",
273 );
274 assert_eq!(
275 http.get(&page, None).await.status,
276 404,
277 "overwritten commit"
278 );
279 assert!(
280 find_file(&dir, "forge-prune-due"),
281 "the force push marks the repo for pruning"
282 );
283
284 let rogue = dir.join("rogue");
285 gen_key(&rogue);
286 let rogue_cmd = ssh_command(&rogue, ssh_port);
287 let rogue_env = [("GIT_SSH_COMMAND", rogue_cmd.as_str())];
288 let text = rejected(
289 &git_env(&dir, &["clone", &priv_ssh_url, "rogue-clone"], &rogue_env),
290 "clone with unregistered key",
291 );
292 assert!(
293 text.contains("Permission denied"),
294 "rogue key message: {text}"
295 );
296
297 let injected = Command::new("ssh")
298 .args(ssh_opts(&key, ssh_port))
299 .arg("git@127.0.0.1")
300 .arg("git-upload-pack '../../etc'")
301 .output()
302 .expect("run ssh");
303 rejected(&injected, "ssh exec with injected path");
304
305 let no_csrf = http
306 .post_form(
307 "/new",
308 &[
309 ("name", "nocsrf"),
310 ("visibility", "public"),
311 ("default_branch", "main"),
312 ],
313 Some(&tahinli),
314 )
315 .await;
316 assert_eq!(no_csrf.status, 403, "POST /new without csrf");
317
318 let dumb = http.get("/tahinli/pub.git/info/refs", None).await;
319 assert_eq!(dumb.status, 403, "info/refs without service");
320 assert!(
321 dumb.body.contains("dumb protocol"),
322 "dumb body: {}",
323 dumb.body
324 );
325}
326
327#[tokio::test]
328async fn suspended_user_token_is_refused_over_http_git() {
329 if !tool_on_path("git") {
330 eprintln!("SKIP git_e2e: `git` was not found on PATH");
331 return;
332 }
333 let root = crate::common::temp_dir("fe2s");
334 let dir = root.path().to_path_buf();
335 let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await;
336 let http = Http::new(ports.http);
337
338 let bob = login(&http, "bob", PW).await;
339 let bob_token = create_token(&http, &bob, "suspend-token").await;
340 let csrf = csrf_for(&http, "/new", &bob).await;
341 let created = http
342 .post_form(
343 "/new",
344 &[
345 ("csrf", &csrf),
346 ("name", "bobrepo"),
347 ("description", ""),
348 ("visibility", "private"),
349 ("default_branch", "main"),
350 ],
351 Some(&bob),
352 )
353 .await;
354 assert_eq!(created.status, 303, "create repo: {}", created.body);
355 let url = format!(
356 "http://bob:{bob_token}@127.0.0.1:{}/bob/bobrepo.git",
357 ports.http
358 );
359 let work = dir.join("work");
360 ok(
361 &git(&dir, &["clone", &url, path_str(&work)]),
362 "clone before suspension",
363 );
364 commit_file(&work, "a.txt", "one\n", "first");
365 ok(
366 &git(&work, &["push", "origin", "HEAD:main"]),
367 "push before suspension",
368 );
369
370 let tahinli = login(&http, "tahinli", PW).await;
371 let list = http.get_cookie("/admin/users", &tahinli).await;
372 assert_eq!(list.status, 200, "GET /admin/users");
373 let doc = scraper::Html::parse_document(&list.body);
374 let link = scraper::Selector::parse("a[href^=\"/admin/users/\"]").expect("selector");
375 let name = scraper::Selector::parse(".name").expect("selector");
376 let bob_href = doc
377 .select(&link)
378 .find(|a| {
379 a.select(&name)
380 .next()
381 .is_some_and(|n| n.text().collect::<String>().trim() == "bob")
382 })
383 .and_then(|a| a.value().attr("href"))
384 .expect("bob's admin link")
385 .to_owned();
386 let detail = http.get_cookie(&bob_href, &tahinli).await;
387 assert_eq!(detail.status, 200, "GET {bob_href}");
388 let csrf = csrf_for(&http, &bob_href, &tahinli).await;
389 let res = http
390 .post_form(
391 &format!("{bob_href}/suspend"),
392 &[("csrf", &csrf), ("reason", "e2e")],
393 Some(&tahinli),
394 )
395 .await;
396 assert_eq!(res.status, 303, "suspend bob: {}", res.body);
397
398 commit_file(&work, "b.txt", "two\n", "second");
399 rejected(
400 &git(&work, &["push", "origin", "HEAD:main"]),
401 "push with a suspended user's token",
402 );
403 let again = dir.join("again");
404 rejected(
405 &git(&dir, &["clone", &url, path_str(&again)]),
406 "clone with a suspended user's token",
407 );
408}