forge
ExploreLog in

Tahinli/forge

public
0 watching
★ 0
16.8 KiB
1//! Fork a repo: `POST /{owner}/{repo}/fork`. The viewer must be signed in, must be able to read the
2//! source (otherwise 404, as for any hidden repo) and must send a valid CSRF token. The fork is
3//! owned by the viewer and named like the source, or `name-1`, `name-2`, ... when the viewer already
4//! has a repo with that name. A viewer who already has a fork of this repo is sent to it, and the
5//! owner of a repo is sent back to it. The response is a 303 to the fork's home page.
6
7use forge_core::AuditAction;
8use forge_git::repo::{fork_bare, repo_path};
9use serde::Deserialize;
10use topcoat::Result;
11use topcoat::context::{Cx, app_context};
12use topcoat::router::content::Form;
13use topcoat::router::error::{SeeOther, see_other};
14use topcoat::router::{path_param, route};
15
16use crate::audit::{self, Actor, Target};
17use crate::auth::require_csrf;
18use crate::pages::repo_ctx::load_repo;
19use crate::state::AppState;
20use crate::views::repo_href;
21
22path_param!(owner);
23path_param!(repo);
24
25#[derive(Deserialize)]
26struct ForkForm {
27 #[serde(default)]
28 csrf: String,
29}
30
31#[route(POST "/{owner}/{repo}/fork")]
32async fn fork_post(cx: &Cx, Form(form): Form<ForkForm>) -> Result<SeeOther> {
33 let owner = path_param::<Owner>(cx);
34 let name = path_param::<Repo>(cx);
35 let source = load_repo(cx, owner, name).await?;
36 let (viewer, _) = require_csrf(cx, &form.csrf).await?;
37 let state = app_context::<AppState>(cx);
38 let source_repo = &source.repo;
39
40 // Forking your own repo is a no-op: send the viewer back to it.
41 if source_repo.owner_id == viewer.id {
42 return Ok(see_other(repo_href(
43 &source_repo.owner_name,
44 &source_repo.name,
45 "",
46 "",
47 )));
48 }
49
50 // One fork per viewer and source: an existing one is reused.
51 let forks = state.store.list_forks(&source_repo.id).await?;
52 if let Some(existing) = forks.iter().find(|fork| fork.owner_id == viewer.id) {
53 return Ok(see_other(repo_href(
54 &existing.owner_name,
55 &existing.name,
56 "",
57 "",
58 )));
59 }
60
61 let fork_name = free_name(state, &viewer.username, &source_repo.name).await?;
62 let fork = state
63 .store
64 .create_fork(source_repo, &viewer.id, &fork_name)
65 .await?;
66 let dst = repo_path(&state.config.data_dir, &fork.id)?;
67 if let Err(e) = fork_bare(&state.git, &source.path, &dst).await {
68 // Without the directory the row would point at nothing, so drop it again.
69 let _ = state.store.delete_repo(&fork.id).await;
70 return Err(e.into());
71 }
72 // A fork gets the source's labels rather than the default set. The fork already exists, so a
73 // label failure is logged rather than failing the request.
74 match state.store.list_labels(&source_repo.id).await {
75 Ok(labels) => {
76 for label in labels {
77 if let Err(e) = state
78 .store
79 .create_label(&fork.id, &label.name, &label.color, &label.description)
80 .await
81 {
82 tracing::warn!(error = %e, repo_id = %fork.id, label = %label.name, "fork: could not copy label");
83 }
84 }
85 }
86 Err(e) => {
87 tracing::warn!(error = %e, repo_id = %fork.id, "fork: could not list source labels");
88 }
89 }
90 let full_name = format!("{}/{}", fork.owner_name, fork.name);
91 let source_name = format!("{}/{}", source_repo.owner_name, source_repo.name);
92 audit::record(
93 &state.store,
94 Some(cx),
95 Actor::User(&viewer),
96 AuditAction::RepoCreated,
97 Target {
98 kind: "repo",
99 id: &fork.id,
100 name: &full_name,
101 },
102 serde_json::json!({ "fork_of": source_name }),
103 )
104 .await;
105 Ok(see_other(repo_href(&fork.owner_name, &fork.name, "", "")))
106}
107
108/// `base` when `owner` has no repo of that name, else the first of `base-1`, `base-2`, ... that is
109/// free.
110async fn free_name(state: &AppState, owner: &str, base: &str) -> Result<String> {
111 let mut candidate = base.to_owned();
112 let mut suffix = 1u32;
113 while state
114 .store
115 .repo_by_owner_and_name(owner, &candidate)
116 .await?
117 .is_some()
118 {
119 candidate = format!("{base}-{suffix}");
120 suffix += 1;
121 }
122 Ok(candidate)
123}
124
125#[cfg(test)]
126mod tests {
127 use std::path::Path;
128 use std::process::Command;
129
130 use forge_core::{AuditAction, Store, Visibility};
131 use forge_git::repo::{init_bare, repo_path};
132 use topcoat::router::request::Request;
133 use topcoat::router::{Body, Router, to_bytes};
134
135 use crate::auth::SESSION_COOKIE;
136
137 const CSRF: &str = "fork-test-csrf";
138
139 struct Site {
140 router: Router,
141 store: Store,
142 dir: tempfile::TempDir,
143 }
144
145 struct Reply {
146 status: u16,
147 location: Option<String>,
148 body: String,
149 }
150
151 /// `alice/demo` (public, `main` with one commit), `alice/secret` (private, empty), and users
152 /// `alice`, `bob` and `carol`, each with a session. Returns the cookie header per user.
153 async fn site() -> (Site, [String; 3]) {
154 let dir = tempfile::tempdir().expect("tempdir");
155 let state = crate::test_support::test_state(dir.path()).await;
156 let store = state.store.clone();
157 let router = crate::test_support::app_router(state.clone());
158
159 let alice = store
160 .create_user("alice", None, "x", false)
161 .await
162 .expect("alice");
163 let bob = store
164 .create_user("bob", None, "x", false)
165 .await
166 .expect("bob");
167 let carol = store
168 .create_user("carol", None, "x", false)
169 .await
170 .expect("carol");
171 let demo = store
172 .create_repo(&alice.id, "demo", "A demo repo", Visibility::Public, "main")
173 .await
174 .expect("demo");
175 let secret = store
176 .create_repo(&alice.id, "secret", "", Visibility::Private, "main")
177 .await
178 .expect("secret");
179 for repo in [&demo, &secret] {
180 let path = repo_path(dir.path(), &repo.id).expect("path");
181 init_bare(&state.git, &path, "main").await.expect("init");
182 }
183
184 let work = dir.path().join("work");
185 std::fs::create_dir_all(&work).expect("work dir");
186 std::fs::write(work.join("README.md"), "# Demo\n").expect("write");
187 git(&work, &["init", "-q", "-b", "main"]);
188 git(&work, &["add", "-A"]);
189 git(&work, &["commit", "-q", "-m", "first commit"]);
190 git(&work, &["tag", "v1"]);
191 let demo_path = repo_path(dir.path(), &demo.id).expect("path");
192 git(
193 &work,
194 &[
195 "push",
196 "-q",
197 demo_path.to_str().expect("utf8"),
198 "main:main",
199 "v1",
200 ],
201 );
202
203 let cookies = [
204 sign_in(&store, &alice.id, "alice-token").await,
205 sign_in(&store, &bob.id, "bob-token").await,
206 sign_in(&store, &carol.id, "carol-token").await,
207 ];
208 (Site { router, store, dir }, cookies)
209 }
210
211 async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {
212 crate::test_support::create_session(store, user_id, token, CSRF).await;
213 format!("__Host-{SESSION_COOKIE}={token}")
214 }
215
216 fn git(dir: &Path, args: &[&str]) {
217 let status = Command::new("git")
218 .current_dir(dir)
219 .env("GIT_CONFIG_NOSYSTEM", "1")
220 .args([
221 "-c",
222 "user.name=Test",
223 "-c",
224 "user.email=test@example.com",
225 "-c",
226 "commit.gpgsign=false",
227 ])
228 .args(args)
229 .status()
230 .expect("git runs");
231 assert!(status.success(), "git {args:?} failed");
232 }
233
234 async fn send(
235 site: &Site,
236 method: &str,
237 uri: &str,
238 cookie: Option<&str>,
239 form: Option<String>,
240 ) -> Reply {
241 let mut builder = Request::builder().method(method).uri(uri);
242 if let Some(cookie) = cookie {
243 builder = builder.header("cookie", cookie);
244 }
245 let body = match form {
246 Some(form) => {
247 builder = builder.header("content-type", "application/x-www-form-urlencoded");
248 Body::from(form)
249 }
250 None => Body::empty(),
251 };
252 let res = site
253 .router
254 .handle(builder.body(body).expect("request"))
255 .await;
256 let status = res.status().as_u16();
257 let location = res
258 .headers()
259 .get("location")
260 .and_then(|v| v.to_str().ok())
261 .map(str::to_owned);
262 let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
263 Reply {
264 status,
265 location,
266 body: String::from_utf8_lossy(&bytes).into_owned(),
267 }
268 }
269
270 async fn fork(site: &Site, cookie: Option<&str>) -> Reply {
271 send(
272 site,
273 "POST",
274 "/alice/demo/fork",
275 cookie,
276 Some(format!("csrf={CSRF}")),
277 )
278 .await
279 }
280
281 #[tokio::test]
282 async fn fork_copies_source_labels_and_adds_no_defaults() {
283 let (site, [_, bob, _]) = site().await;
284 let demo = site
285 .store
286 .repo_by_owner_and_name("alice", "demo")
287 .await
288 .expect("query")
289 .expect("demo");
290 site.store
291 .create_label(&demo.id, "triage-me", "#123456", "only here")
292 .await
293 .expect("label");
294 let reply = fork(&site, Some(&bob)).await;
295 assert_eq!(reply.status, 303);
296 let fork = site
297 .store
298 .repo_by_owner_and_name("bob", "demo")
299 .await
300 .expect("query")
301 .expect("fork");
302 let labels: Vec<(String, String, String)> = site
303 .store
304 .list_labels(&fork.id)
305 .await
306 .expect("labels")
307 .into_iter()
308 .map(|l| (l.name, l.color, l.description))
309 .collect();
310 assert_eq!(
311 labels,
312 vec![(
313 "triage-me".to_string(),
314 "#123456".to_string(),
315 "only here".to_string()
316 )]
317 );
318 }
319
320 #[tokio::test]
321 async fn fork_copies_branches_and_shows_the_source() {
322 let (site, [_, bob, _]) = site().await;
323 let reply = fork(&site, Some(&bob)).await;
324 assert_eq!(reply.status, 303);
325 assert_eq!(reply.location.as_deref(), Some("/bob/demo"));
326
327 let bob_id = site
328 .store
329 .user_by_username("bob")
330 .await
331 .expect("q")
332 .expect("bob")
333 .id;
334 let source = site
335 .store
336 .repo_by_owner_and_name("alice", "demo")
337 .await
338 .expect("q")
339 .expect("source");
340 let fork = site
341 .store
342 .repo_by_owner_and_name("bob", "demo")
343 .await
344 .expect("q")
345 .expect("fork row");
346 assert_eq!(fork.fork_of.as_deref(), Some(source.id.as_str()));
347 assert_eq!(fork.visibility, Visibility::Public);
348 assert_eq!(fork.owner_id, bob_id);
349
350 let forked = site
351 .store
352 .list_audit(
353 &forge_core::AuditFilter {
354 action: Some(AuditAction::RepoCreated),
355 ..Default::default()
356 },
357 None,
358 10,
359 )
360 .await
361 .expect("audit");
362 assert_eq!(forked.len(), 1, "one audit entry for the fork");
363 assert_eq!(forked[0].target_id, fork.id);
364 assert_eq!(forked[0].target_name, "bob/demo");
365 assert_eq!(forked[0].actor_id.as_deref(), Some(bob_id.as_str()));
366 let data: serde_json::Value = serde_json::from_str(&forked[0].data).expect("json");
367 assert_eq!(data, serde_json::json!({ "fork_of": "alice/demo" }));
368
369 let path = repo_path(site.dir.path(), &fork.id).expect("path");
370 let refs = Command::new("git")
371 .arg("--git-dir")
372 .arg(&path)
373 .args(["for-each-ref", "--format=%(refname)"])
374 .output()
375 .expect("git runs");
376 let refs = String::from_utf8_lossy(&refs.stdout).into_owned();
377 assert_eq!(
378 refs.lines().collect::<Vec<_>>(),
379 vec!["refs/heads/main", "refs/tags/v1"]
380 );
381
382 let page = send(&site, "GET", "/bob/demo", Some(&bob), None).await;
383 assert_eq!(page.status, 200);
384 assert!(page.body.contains("forked from"), "fork line shown");
385 assert!(
386 page.body.contains("href=\"/alice/demo\""),
387 "fork line links the source"
388 );
389 }
390
391 #[tokio::test]
392 async fn forking_twice_redirects_to_the_existing_fork() {
393 let (site, [_, bob, _]) = site().await;
394 assert_eq!(fork(&site, Some(&bob)).await.status, 303);
395 let again = fork(&site, Some(&bob)).await;
396 assert_eq!(again.status, 303);
397 assert_eq!(again.location.as_deref(), Some("/bob/demo"));
398 assert!(
399 site.store
400 .repo_by_owner_and_name("bob", "demo-1")
401 .await
402 .expect("q")
403 .is_none(),
404 "no second fork was created"
405 );
406 }
407
408 #[tokio::test]
409 async fn fork_name_gets_a_suffix_when_taken() {
410 let (site, [_, bob, _]) = site().await;
411 let bob_user = site
412 .store
413 .user_by_username("bob")
414 .await
415 .expect("q")
416 .expect("bob");
417 site.store
418 .create_repo(&bob_user.id, "demo", "", Visibility::Private, "main")
419 .await
420 .expect("bob's own demo");
421 let reply = fork(&site, Some(&bob)).await;
422 assert_eq!(reply.location.as_deref(), Some("/bob/demo-1"));
423 }
424
425 #[tokio::test]
426 async fn owner_forking_own_repo_is_a_no_op() {
427 let (site, [alice, _, _]) = site().await;
428 let reply = fork(&site, Some(&alice)).await;
429 assert_eq!(reply.status, 303);
430 assert_eq!(reply.location.as_deref(), Some("/alice/demo"));
431 assert!(
432 site.store
433 .repo_by_owner_and_name("alice", "demo-1")
434 .await
435 .expect("q")
436 .is_none()
437 );
438 }
439
440 #[tokio::test]
441 async fn hidden_repo_is_404_for_a_non_collaborator() {
442 let (site, [_, _, carol]) = site().await;
443 let reply = send(
444 &site,
445 "POST",
446 "/alice/secret/fork",
447 Some(&carol),
448 Some(format!("csrf={CSRF}")),
449 )
450 .await;
451 assert_eq!(reply.status, 404);
452 let reply = send(
453 &site,
454 "POST",
455 "/alice/secret/fork",
456 None,
457 Some(format!("csrf={CSRF}")),
458 )
459 .await;
460 assert_eq!(reply.status, 404, "anonymous viewers also get 404");
461 }
462
463 #[tokio::test]
464 async fn anonymous_viewer_is_sent_to_login() {
465 let (site, _) = site().await;
466 let reply = fork(&site, None).await;
467 assert_eq!(reply.status, 303);
468 assert!(
469 reply
470 .location
471 .as_deref()
472 .is_some_and(|l| l.starts_with("/login")),
473 "{:?}",
474 reply.location
475 );
476 }
477
478 #[tokio::test]
479 async fn missing_or_wrong_csrf_is_rejected() {
480 let (site, [_, bob, _]) = site().await;
481 let reply = send(
482 &site,
483 "POST",
484 "/alice/demo/fork",
485 Some(&bob),
486 Some(String::new()),
487 )
488 .await;
489 assert_eq!(reply.status, 403);
490 let reply = send(
491 &site,
492 "POST",
493 "/alice/demo/fork",
494 Some(&bob),
495 Some("csrf=wrong".into()),
496 )
497 .await;
498 assert_eq!(reply.status, 403);
499 assert!(
500 site.store
501 .repo_by_owner_and_name("bob", "demo")
502 .await
503 .expect("q")
504 .is_none(),
505 "nothing was created"
506 );
507 }
508
509 #[tokio::test]
510 async fn repo_header_shows_pull_requests_tab_and_fork_button() {
511 let (site, [_, bob, _]) = site().await;
512 let reply = send(&site, "GET", "/alice/demo", Some(&bob), None).await;
513 assert_eq!(reply.status, 200);
514 assert!(
515 reply.body.contains("href=\"/alice/demo/pulls\""),
516 "pulls tab"
517 );
518 assert!(reply.body.contains("Pull requests"));
519 assert!(
520 reply.body.contains("action=\"/alice/demo/fork\""),
521 "fork button"
522 );
523 let reply = send(&site, "GET", "/alice/demo", None, None).await;
524 assert!(
525 !reply.body.contains("action=\"/alice/demo/fork\""),
526 "no fork button when anonymous"
527 );
528 }
529}