forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

mirrors_e2e.rs437 lines, 15.6 KiBHistoryRawDownload
1//! End-to-end: pull and push mirrors against one real `forge` binary, talking to itself over
2//! HTTP smart git. The instance allows plain HTTP and allow-lists `127.0.0.1` in `[webhooks]`, so
3//! its own mirror worker may reach the loopback listener. Nothing else about the SSRF guard is
4//! relaxed.
5//!
6//! Scenarios:
7//! - pull mirror `dst` of `tahinli/src` (heads and tags) created through the new-repo form, then a
8//! second change picked up by "Sync now"; a push to `dst` is refused;
9//! - push mirror `pm` to `tahinli/target` (created empty) after a push to `pm`;
10//! - the mirror pages and the server log never contain the access token.
11
12use crate::common::{
13 Http, Server, bin, input_value, launch_with, login, pick_ports, tool_on_path, write_config_with,
14};
15use std::collections::BTreeSet;
16use std::fs;
17use std::path::{Path, PathBuf};
18use std::process::{Command, Output};
19use std::time::{Duration, Instant};
20
21const TAHINLI_PW: &str = "tahinli-password-123";
22const WEBHOOK_TOML: &str = "\n[webhooks]\nallow_http = true\nallowed_hosts = [\"127.0.0.1\"]\n\n[mirrors]\npush_debounce_secs = 0\n";
23const SYNC_TIMEOUT: Duration = Duration::from_secs(30);
24/// Push mirrors run after the push debounce, which this test sets to 0 (production: 10s). The
25/// worker wakes on the push itself, so this only needs room for the git sync.
26const PUSH_TIMEOUT: Duration = Duration::from_secs(90);
27
28/// The `action` of every form whose action ends with `suffix`, in page order.
29fn form_actions(body: &str, suffix: &str) -> Vec<String> {
30 let doc = scraper::Html::parse_document(body);
31 let selector = scraper::Selector::parse("form[action]").expect("selector");
32 doc.select(&selector)
33 .filter_map(|el| el.value().attr("action"))
34 .filter(|action| action.ends_with(suffix))
35 .map(str::to_owned)
36 .collect()
37}
38
39fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
40 let out = Command::new(bin())
41 .arg("--config")
42 .arg(config)
43 .args(["admin", "create-user", username])
44 .args(extra)
45 .env("FORGE_PASSWORD", password)
46 .output()
47 .expect("run admin create-user");
48 assert!(
49 out.status.success(),
50 "create-user {username} failed:\n{}",
51 String::from_utf8_lossy(&out.stderr)
52 );
53}
54
55/// Fixed identity and config isolation for every git this file spawns, so the result does not
56/// depend on the machine's global git config (a clean CI container has none).
57const GIT_HERMETIC_ENV: &[(&str, &str)] = &[
58 ("GIT_AUTHOR_NAME", "tahinli"),
59 ("GIT_AUTHOR_EMAIL", "tahinli@example.com"),
60 ("GIT_COMMITTER_NAME", "tahinli"),
61 ("GIT_COMMITTER_EMAIL", "tahinli@example.com"),
62 ("GIT_CONFIG_GLOBAL", "/dev/null"),
63 ("GIT_CONFIG_NOSYSTEM", "1"),
64];
65
66/// Runs git with credential helpers disabled and extra env. Returns the raw output.
67fn git_output(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
68 let mut cmd = Command::new("git");
69 cmd.current_dir(cwd)
70 .args(["-c", "credential.helper="])
71 .args(args)
72 .env("GIT_TERMINAL_PROMPT", "0");
73 for (key, value) in GIT_HERMETIC_ENV.iter().chain(env) {
74 cmd.env(key, value);
75 }
76 cmd.output().expect("run git")
77}
78
79/// Runs git, returning stdout trimmed. Panics on failure.
80fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String {
81 let out = git_output(cwd, args, env);
82 assert!(
83 out.status.success(),
84 "git {args:?} failed:\n{}",
85 String::from_utf8_lossy(&out.stderr)
86 );
87 String::from_utf8_lossy(&out.stdout).trim().to_owned()
88}
89
90fn git(cwd: &Path, args: &[&str]) -> String {
91 git_env(cwd, args, &[])
92}
93
94/// Writes `file`, commits it as `who` and returns the new HEAD.
95fn commit(repo: &Path, file: &str, contents: &str, message: &str) -> String {
96 fs::write(repo.join(file), contents).expect("write file");
97 git(repo, &["add", file]);
98 git_env(
99 repo,
100 &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message],
101 &[
102 ("GIT_AUTHOR_NAME", "tahinli"),
103 ("GIT_AUTHOR_EMAIL", "tahinli@example.test"),
104 ("GIT_COMMITTER_NAME", "tahinli"),
105 ("GIT_COMMITTER_EMAIL", "tahinli@example.test"),
106 ],
107 );
108 git(repo, &["rev-parse", "HEAD"])
109}
110
111/// Clones `url` into `into` (a path that does not exist yet) and returns it.
112fn clone(url: &str, into: &Path) -> PathBuf {
113 let parent = into.parent().expect("clone target has a parent");
114 git(
115 parent,
116 &["clone", "-q", url, into.to_str().expect("utf-8 path")],
117 );
118 into.to_path_buf()
119}
120
121/// The HTTPS remote for `owner/repo`, authenticated with a token.
122fn remote(port: u16, token: &str, owner: &str, repo: &str) -> String {
123 format!("http://tahinli:{token}@127.0.0.1:{port}/{owner}/{repo}.git")
124}
125
126/// The heads and tags a remote advertises, as sorted `sha refname` lines. HEAD is left out.
127/// Returns `None` if the remote cannot be listed.
128fn branches_and_tags(url: &str) -> Option<BTreeSet<String>> {
129 let out = git_output(&std::env::temp_dir(), &["ls-remote", url], &[]);
130 if !out.status.success() {
131 return None;
132 }
133 let text = String::from_utf8_lossy(&out.stdout);
134 Some(
135 text.lines()
136 .filter(|line| line.contains("refs/heads/") || line.contains("refs/tags/"))
137 .map(str::to_owned)
138 .collect(),
139 )
140}
141
142/// The sha a remote branch points at, if the branch exists.
143fn remote_head(url: &str, branch: &str) -> Option<String> {
144 let out = git_output(
145 &std::env::temp_dir(),
146 &["ls-remote", url, &format!("refs/heads/{branch}")],
147 &[],
148 );
149 if !out.status.success() {
150 return None;
151 }
152 String::from_utf8_lossy(&out.stdout)
153 .split_whitespace()
154 .next()
155 .map(str::to_owned)
156}
157
158/// Polls `check` every 200ms until it returns true, failing after `SYNC_TIMEOUT`.
159async fn wait_for(what: &str, check: impl Fn() -> bool) {
160 let deadline = Instant::now() + SYNC_TIMEOUT;
161 while !check() {
162 assert!(
163 Instant::now() < deadline,
164 "timed out after {SYNC_TIMEOUT:?} waiting for {what}"
165 );
166 tokio::time::sleep(Duration::from_millis(200)).await;
167 }
168}
169
170/// The session's CSRF token, scraped from the token settings page.
171async fn csrf_token(http: &Http, session: &str) -> String {
172 let page = http.get_cookie("/settings/keys", session).await;
173 assert_eq!(page.status, 200, "GET /settings/keys");
174 input_value(&page.body, "csrf")
175}
176
177/// Creates an access token through `/settings/tokens` and returns the token shown once.
178async fn create_token(http: &Http, session: &str, name: &str) -> String {
179 let csrf = csrf_token(http, session).await;
180 let res = http
181 .post_form(
182 "/settings/tokens",
183 &[("csrf", &csrf), ("name", name), ("expires", "30")],
184 Some(session),
185 )
186 .await;
187 assert_eq!(res.status, 200, "create token: {}", res.body);
188 let doc = scraper::Html::parse_document(&res.body);
189 let selector = scraper::Selector::parse("pre.code code").expect("selector");
190 let token: String = doc
191 .select(&selector)
192 .next()
193 .expect("token shown after creation")
194 .text()
195 .collect();
196 let token = token.trim().to_owned();
197 assert!(token.starts_with("forge_"), "unexpected token shape");
198 token
199}
200
201/// Submits the new-repo form. `mirror` adds the "Mirror an existing repository" fields.
202async fn new_repo(http: &Http, session: &str, name: &str, mirror: Option<(&str, &str, &str)>) {
203 let page = http.get_cookie("/new", session).await;
204 assert_eq!(page.status, 200, "GET /new");
205 let csrf = input_value(&page.body, "csrf");
206 let mut form = vec![
207 ("csrf", csrf.as_str()),
208 ("name", name),
209 ("description", ""),
210 ("visibility", "public"),
211 ("default_branch", "main"),
212 ];
213 if let Some((url, username, secret)) = mirror {
214 form.extend([
215 ("mirror_url", url),
216 ("mirror_username", username),
217 ("mirror_secret", secret),
218 ("mirror_interval", "60"),
219 ]);
220 }
221 let res = http.post_form("/new", &form, Some(session)).await;
222 assert_eq!(res.status, 303, "create repo {name}: {}", res.body);
223 assert_eq!(
224 res.location().as_deref(),
225 Some(format!("/tahinli/{name}").as_str())
226 );
227}
228
229/// Adds a push mirror to `tahinli/repo` through its settings page.
230async fn add_push_mirror(http: &Http, session: &str, repo: &str, url: &str, secret: &str) {
231 let path = format!("/tahinli/{repo}/settings/mirrors");
232 let page = http.get_cookie(&path, session).await;
233 assert_eq!(page.status, 200, "GET {path}");
234 let csrf = input_value(&page.body, "csrf");
235 let res = http
236 .post_form(
237 &path,
238 &[
239 ("csrf", &csrf),
240 ("url", url),
241 ("username", "tahinli"),
242 ("secret", secret),
243 ("interval", "60"),
244 ],
245 Some(session),
246 )
247 .await;
248 assert_eq!(res.status, 303, "add push mirror: {}", res.body);
249}
250
251/// Clicks "Sync now" on the first mirror of `tahinli/repo`.
252async fn sync_now(http: &Http, session: &str, repo: &str) {
253 let path = format!("/tahinli/{repo}/settings/mirrors");
254 let page = http.get_cookie(&path, session).await;
255 assert_eq!(page.status, 200, "GET {path}");
256 let action = form_actions(&page.body, "/sync")
257 .into_iter()
258 .next()
259 .expect("a sync form on the mirrors page");
260 let csrf = input_value(&page.body, "csrf");
261 let res = http
262 .post_form(&action, &[("csrf", &csrf)], Some(session))
263 .await;
264 assert_eq!(res.status, 303, "sync now: {}", res.body);
265}
266
267/// A running server with its own temp data dir. Field order matters: the server is dropped (and
268/// killed) before the temp dir is removed.
269struct Booted {
270 _server: Server,
271 _root: tempfile::TempDir,
272 dir: PathBuf,
273 http: Http,
274 http_port: u16,
275}
276
277/// Creates tahinli (admin) and boots the server with plain HTTP and loopback mirrors allowed.
278async fn boot() -> Booted {
279 if !tool_on_path("git") {
280 panic!("`git` was not found on PATH");
281 }
282 // Keep the path short: the internal unix socket path is limited to 108 bytes.
283 let root = tempfile::Builder::new()
284 .prefix("mr2e")
285 .tempdir_in("/tmp")
286 .expect("temp dir");
287 let dir = root.path().to_path_buf();
288 let ports = pick_ports();
289 let config = write_config_with(&dir, ports, WEBHOOK_TOML);
290
291 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
292 let (server, ports) = launch_with(&dir, ports, WEBHOOK_TOML).await;
293 Booted {
294 _server: server,
295 _root: root,
296 dir,
297 http: Http::new(ports.http),
298 http_port: ports.http,
299 }
300}
301
302/// The server log, for assertion messages and the token leak check.
303fn server_log(b: &Booted) -> String {
304 fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default()
305}
306
307#[tokio::test]
308async fn pull_and_push_mirrors_sync_over_smart_http() {
309 let b = boot().await;
310 let session = login(&b.http, "tahinli", TAHINLI_PW).await;
311 let token = create_token(&b.http, &session, "mirror-token").await;
312 let port = b.http_port;
313
314 // Source repo with a commit on main, a second branch and an annotated tag.
315 new_repo(&b.http, &session, "src", None).await;
316 let src_work = clone(
317 &remote(port, &token, "tahinli", "src"),
318 &b.dir.join("src-work"),
319 );
320 let first = commit(&src_work, "base.txt", "base\n", "base commit");
321 git(&src_work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
322 git(&src_work, &["tag", "-a", "v1", "-m", "release one"]);
323 git(&src_work, &["push", "-q", "origin", "refs/tags/v1"]);
324 git(
325 &src_work,
326 &["push", "-q", "origin", "HEAD:refs/heads/feature"],
327 );
328 let src_url = format!("http://127.0.0.1:{port}/tahinli/src.git");
329 let src_refs = branches_and_tags(&remote(port, &token, "tahinli", "src")).expect("list src");
330 assert!(src_refs.iter().any(|l| l.ends_with("refs/tags/v1")));
331 assert!(src_refs.iter().any(|l| l.ends_with("refs/heads/feature")));
332
333 // Pull mirror created through the new-repo form. Creation schedules the first sync now.
334 new_repo(
335 &b.http,
336 &session,
337 "dst",
338 Some((&src_url, "tahinli", &token)),
339 )
340 .await;
341 let dst_url = remote(port, &token, "tahinli", "dst");
342 wait_for("dst to hold src's heads and tags", || {
343 branches_and_tags(&dst_url).is_some_and(|refs| refs == src_refs)
344 })
345 .await;
346 assert_eq!(
347 remote_head(&dst_url, "main").as_deref(),
348 Some(first.as_str())
349 );
350
351 // A push to the pull mirror is refused by pre-receive.
352 let dst_work = clone(&dst_url, &b.dir.join("dst-work"));
353 commit(&dst_work, "local.txt", "local\n", "local change");
354 let refused = git_output(&dst_work, &["push", "origin", "HEAD:refs/heads/main"], &[]);
355 assert!(
356 !refused.status.success(),
357 "push to a pull mirror must be rejected"
358 );
359 let stderr = String::from_utf8_lossy(&refused.stderr);
360 assert!(
361 stderr.contains("pull mirror"),
362 "rejection should name the pull mirror:\n{stderr}"
363 );
364
365 // A new commit on src, picked up by "Sync now" on dst.
366 let second = commit(&src_work, "next.txt", "next\n", "second commit");
367 git(&src_work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
368 sync_now(&b.http, &session, "dst").await;
369 wait_for("dst main to follow src after sync now", || {
370 remote_head(&dst_url, "main").as_deref() == Some(second.as_str())
371 })
372 .await;
373
374 // Push mirror: an empty target repo receives pm's commit.
375 new_repo(&b.http, &session, "target", None).await;
376 new_repo(&b.http, &session, "pm", None).await;
377 let target_url = format!("http://127.0.0.1:{port}/tahinli/target.git");
378 add_push_mirror(&b.http, &session, "pm", &target_url, &token).await;
379 let pm_work = b.dir.join("pm-work");
380 fs::create_dir_all(&pm_work).expect("pm work dir");
381 git(&pm_work, &["init", "-q", "-b", "main"]);
382 let pushed = commit(&pm_work, "pm.txt", "pm\n", "pm commit");
383 git(
384 &pm_work,
385 &[
386 "push",
387 "-q",
388 &remote(port, &token, "tahinli", "pm"),
389 "HEAD:refs/heads/main",
390 ],
391 );
392 let target_remote = remote(port, &token, "tahinli", "target");
393 let delivered = {
394 let started = Instant::now();
395 let deadline = started + PUSH_TIMEOUT;
396 loop {
397 if remote_head(&target_remote, "main").as_deref() == Some(pushed.as_str()) {
398 eprintln!("push mirror delivered after {:?}", started.elapsed());
399 break true;
400 }
401 if Instant::now() >= deadline {
402 break false;
403 }
404 tokio::time::sleep(Duration::from_millis(200)).await;
405 }
406 };
407 if !delivered {
408 let page = b
409 .http
410 .get_cookie("/tahinli/pm/settings/mirrors", &session)
411 .await;
412 panic!(
413 "push mirror did not deliver {pushed} to target within {PUSH_TIMEOUT:?}\n\
414 pm mirrors page status {}:\n{}\nserver log:\n{}",
415 page.status,
416 page.body,
417 server_log(&b)
418 );
419 }
420
421 // The token never shows up in the mirror pages or the server log.
422 for repo in ["dst", "pm"] {
423 let page = b
424 .http
425 .get_cookie(&format!("/tahinli/{repo}/settings/mirrors"), &session)
426 .await;
427 assert_eq!(page.status, 200, "GET mirrors of {repo}");
428 assert!(
429 !page.body.contains(&token),
430 "the token leaked into the mirror page of {repo}"
431 );
432 }
433 assert!(
434 !server_log(&b).contains(&token),
435 "the token leaked into the server log"
436 );
437}