//! Fork a repo: `POST /{owner}/{repo}/fork`. The viewer must be signed in, must be able to read the //! source (otherwise 404, as for any hidden repo) and must send a valid CSRF token. The fork is //! owned by the viewer and named like the source, or `name-1`, `name-2`, ... when the viewer already //! has a repo with that name. A viewer who already has a fork of this repo is sent to it, and the //! owner of a repo is sent back to it. The response is a 303 to the fork's home page. use forge_core::AuditAction; use forge_git::repo::{fork_bare, repo_path}; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{SeeOther, see_other}; use topcoat::router::{path_param, route}; use crate::audit::{self, Actor, Target}; use crate::auth::require_csrf; use crate::pages::repo_ctx::load_repo; use crate::state::AppState; use crate::views::repo_href; path_param!(owner); path_param!(repo); #[derive(Deserialize)] struct ForkForm { #[serde(default)] csrf: String, } #[route(POST "/{owner}/{repo}/fork")] async fn fork_post(cx: &Cx, Form(form): Form) -> Result { let owner = path_param::(cx); let name = path_param::(cx); let source = load_repo(cx, owner, name).await?; let (viewer, _) = require_csrf(cx, &form.csrf).await?; let state = app_context::(cx); let source_repo = &source.repo; // Forking your own repo is a no-op: send the viewer back to it. if source_repo.owner_id == viewer.id { return Ok(see_other(repo_href( &source_repo.owner_name, &source_repo.name, "", "", ))); } // One fork per viewer and source: an existing one is reused. let forks = state.store.list_forks(&source_repo.id).await?; if let Some(existing) = forks.iter().find(|fork| fork.owner_id == viewer.id) { return Ok(see_other(repo_href( &existing.owner_name, &existing.name, "", "", ))); } let fork_name = free_name(state, &viewer.username, &source_repo.name).await?; let fork = state .store .create_fork(source_repo, &viewer.id, &fork_name) .await?; let dst = repo_path(&state.config.data_dir, &fork.id)?; if let Err(e) = fork_bare(&state.git, &source.path, &dst).await { // Without the directory the row would point at nothing, so drop it again. let _ = state.store.delete_repo(&fork.id).await; return Err(e.into()); } // A fork gets the source's labels rather than the default set. The fork already exists, so a // label failure is logged rather than failing the request. match state.store.list_labels(&source_repo.id).await { Ok(labels) => { for label in labels { if let Err(e) = state .store .create_label(&fork.id, &label.name, &label.color, &label.description) .await { tracing::warn!(error = %e, repo_id = %fork.id, label = %label.name, "fork: could not copy label"); } } } Err(e) => { tracing::warn!(error = %e, repo_id = %fork.id, "fork: could not list source labels"); } } let full_name = format!("{}/{}", fork.owner_name, fork.name); let source_name = format!("{}/{}", source_repo.owner_name, source_repo.name); audit::record( &state.store, Some(cx), Actor::User(&viewer), AuditAction::RepoCreated, Target { kind: "repo", id: &fork.id, name: &full_name, }, serde_json::json!({ "fork_of": source_name }), ) .await; Ok(see_other(repo_href(&fork.owner_name, &fork.name, "", ""))) } /// `base` when `owner` has no repo of that name, else the first of `base-1`, `base-2`, ... that is /// free. async fn free_name(state: &AppState, owner: &str, base: &str) -> Result { let mut candidate = base.to_owned(); let mut suffix = 1u32; while state .store .repo_by_owner_and_name(owner, &candidate) .await? .is_some() { candidate = format!("{base}-{suffix}"); suffix += 1; } Ok(candidate) } #[cfg(test)] mod tests { use std::path::Path; use std::process::Command; use forge_core::{AuditAction, Store, Visibility}; use forge_git::repo::{init_bare, repo_path}; use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; use crate::auth::SESSION_COOKIE; const CSRF: &str = "fork-test-csrf"; struct Site { router: Router, store: Store, dir: tempfile::TempDir, } struct Reply { status: u16, location: Option, body: String, } /// `alice/demo` (public, `main` with one commit), `alice/secret` (private, empty), and users /// `alice`, `bob` and `carol`, each with a session. Returns the cookie header per user. async fn site() -> (Site, [String; 3]) { let dir = tempfile::tempdir().expect("tempdir"); let state = crate::test_support::test_state(dir.path()).await; let store = state.store.clone(); let router = crate::test_support::app_router(state.clone()); let alice = store .create_user("alice", None, "x", false) .await .expect("alice"); let bob = store .create_user("bob", None, "x", false) .await .expect("bob"); let carol = store .create_user("carol", None, "x", false) .await .expect("carol"); let demo = store .create_repo(&alice.id, "demo", "A demo repo", Visibility::Public, "main") .await .expect("demo"); let secret = store .create_repo(&alice.id, "secret", "", Visibility::Private, "main") .await .expect("secret"); for repo in [&demo, &secret] { let path = repo_path(dir.path(), &repo.id).expect("path"); init_bare(&state.git, &path, "main").await.expect("init"); } let work = dir.path().join("work"); std::fs::create_dir_all(&work).expect("work dir"); std::fs::write(work.join("README.md"), "# Demo\n").expect("write"); git(&work, &["init", "-q", "-b", "main"]); git(&work, &["add", "-A"]); git(&work, &["commit", "-q", "-m", "first commit"]); git(&work, &["tag", "v1"]); let demo_path = repo_path(dir.path(), &demo.id).expect("path"); git( &work, &[ "push", "-q", demo_path.to_str().expect("utf8"), "main:main", "v1", ], ); let cookies = [ sign_in(&store, &alice.id, "alice-token").await, sign_in(&store, &bob.id, "bob-token").await, sign_in(&store, &carol.id, "carol-token").await, ]; (Site { router, store, dir }, cookies) } async fn sign_in(store: &Store, user_id: &str, token: &str) -> String { crate::test_support::create_session(store, user_id, token, CSRF).await; format!("__Host-{SESSION_COOKIE}={token}") } fn git(dir: &Path, args: &[&str]) { let status = Command::new("git") .current_dir(dir) .env("GIT_CONFIG_NOSYSTEM", "1") .args([ "-c", "user.name=Test", "-c", "user.email=test@example.com", "-c", "commit.gpgsign=false", ]) .args(args) .status() .expect("git runs"); assert!(status.success(), "git {args:?} failed"); } async fn send( site: &Site, method: &str, uri: &str, cookie: Option<&str>, form: Option, ) -> Reply { let mut builder = Request::builder().method(method).uri(uri); if let Some(cookie) = cookie { builder = builder.header("cookie", cookie); } let body = match form { Some(form) => { builder = builder.header("content-type", "application/x-www-form-urlencoded"); Body::from(form) } None => Body::empty(), }; let res = site .router .handle(builder.body(body).expect("request")) .await; let status = res.status().as_u16(); let location = res .headers() .get("location") .and_then(|v| v.to_str().ok()) .map(str::to_owned); let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); Reply { status, location, body: String::from_utf8_lossy(&bytes).into_owned(), } } async fn fork(site: &Site, cookie: Option<&str>) -> Reply { send( site, "POST", "/alice/demo/fork", cookie, Some(format!("csrf={CSRF}")), ) .await } #[tokio::test] async fn fork_copies_source_labels_and_adds_no_defaults() { let (site, [_, bob, _]) = site().await; let demo = site .store .repo_by_owner_and_name("alice", "demo") .await .expect("query") .expect("demo"); site.store .create_label(&demo.id, "triage-me", "#123456", "only here") .await .expect("label"); let reply = fork(&site, Some(&bob)).await; assert_eq!(reply.status, 303); let fork = site .store .repo_by_owner_and_name("bob", "demo") .await .expect("query") .expect("fork"); let labels: Vec<(String, String, String)> = site .store .list_labels(&fork.id) .await .expect("labels") .into_iter() .map(|l| (l.name, l.color, l.description)) .collect(); assert_eq!( labels, vec![( "triage-me".to_string(), "#123456".to_string(), "only here".to_string() )] ); } #[tokio::test] async fn fork_copies_branches_and_shows_the_source() { let (site, [_, bob, _]) = site().await; let reply = fork(&site, Some(&bob)).await; assert_eq!(reply.status, 303); assert_eq!(reply.location.as_deref(), Some("/bob/demo")); let bob_id = site .store .user_by_username("bob") .await .expect("q") .expect("bob") .id; let source = site .store .repo_by_owner_and_name("alice", "demo") .await .expect("q") .expect("source"); let fork = site .store .repo_by_owner_and_name("bob", "demo") .await .expect("q") .expect("fork row"); assert_eq!(fork.fork_of.as_deref(), Some(source.id.as_str())); assert_eq!(fork.visibility, Visibility::Public); assert_eq!(fork.owner_id, bob_id); let forked = site .store .list_audit( &forge_core::AuditFilter { action: Some(AuditAction::RepoCreated), ..Default::default() }, None, 10, ) .await .expect("audit"); assert_eq!(forked.len(), 1, "one audit entry for the fork"); assert_eq!(forked[0].target_id, fork.id); assert_eq!(forked[0].target_name, "bob/demo"); assert_eq!(forked[0].actor_id.as_deref(), Some(bob_id.as_str())); let data: serde_json::Value = serde_json::from_str(&forked[0].data).expect("json"); assert_eq!(data, serde_json::json!({ "fork_of": "alice/demo" })); let path = repo_path(site.dir.path(), &fork.id).expect("path"); let refs = Command::new("git") .arg("--git-dir") .arg(&path) .args(["for-each-ref", "--format=%(refname)"]) .output() .expect("git runs"); let refs = String::from_utf8_lossy(&refs.stdout).into_owned(); assert_eq!( refs.lines().collect::>(), vec!["refs/heads/main", "refs/tags/v1"] ); let page = send(&site, "GET", "/bob/demo", Some(&bob), None).await; assert_eq!(page.status, 200); assert!(page.body.contains("forked from"), "fork line shown"); assert!( page.body.contains("href=\"/alice/demo\""), "fork line links the source" ); } #[tokio::test] async fn forking_twice_redirects_to_the_existing_fork() { let (site, [_, bob, _]) = site().await; assert_eq!(fork(&site, Some(&bob)).await.status, 303); let again = fork(&site, Some(&bob)).await; assert_eq!(again.status, 303); assert_eq!(again.location.as_deref(), Some("/bob/demo")); assert!( site.store .repo_by_owner_and_name("bob", "demo-1") .await .expect("q") .is_none(), "no second fork was created" ); } #[tokio::test] async fn fork_name_gets_a_suffix_when_taken() { let (site, [_, bob, _]) = site().await; let bob_user = site .store .user_by_username("bob") .await .expect("q") .expect("bob"); site.store .create_repo(&bob_user.id, "demo", "", Visibility::Private, "main") .await .expect("bob's own demo"); let reply = fork(&site, Some(&bob)).await; assert_eq!(reply.location.as_deref(), Some("/bob/demo-1")); } #[tokio::test] async fn owner_forking_own_repo_is_a_no_op() { let (site, [alice, _, _]) = site().await; let reply = fork(&site, Some(&alice)).await; assert_eq!(reply.status, 303); assert_eq!(reply.location.as_deref(), Some("/alice/demo")); assert!( site.store .repo_by_owner_and_name("alice", "demo-1") .await .expect("q") .is_none() ); } #[tokio::test] async fn hidden_repo_is_404_for_a_non_collaborator() { let (site, [_, _, carol]) = site().await; let reply = send( &site, "POST", "/alice/secret/fork", Some(&carol), Some(format!("csrf={CSRF}")), ) .await; assert_eq!(reply.status, 404); let reply = send( &site, "POST", "/alice/secret/fork", None, Some(format!("csrf={CSRF}")), ) .await; assert_eq!(reply.status, 404, "anonymous viewers also get 404"); } #[tokio::test] async fn anonymous_viewer_is_sent_to_login() { let (site, _) = site().await; let reply = fork(&site, None).await; assert_eq!(reply.status, 303); assert!( reply .location .as_deref() .is_some_and(|l| l.starts_with("/login")), "{:?}", reply.location ); } #[tokio::test] async fn missing_or_wrong_csrf_is_rejected() { let (site, [_, bob, _]) = site().await; let reply = send( &site, "POST", "/alice/demo/fork", Some(&bob), Some(String::new()), ) .await; assert_eq!(reply.status, 403); let reply = send( &site, "POST", "/alice/demo/fork", Some(&bob), Some("csrf=wrong".into()), ) .await; assert_eq!(reply.status, 403); assert!( site.store .repo_by_owner_and_name("bob", "demo") .await .expect("q") .is_none(), "nothing was created" ); } #[tokio::test] async fn repo_header_shows_pull_requests_tab_and_fork_button() { let (site, [_, bob, _]) = site().await; let reply = send(&site, "GET", "/alice/demo", Some(&bob), None).await; assert_eq!(reply.status, 200); assert!( reply.body.contains("href=\"/alice/demo/pulls\""), "pulls tab" ); assert!(reply.body.contains("Pull requests")); assert!( reply.body.contains("action=\"/alice/demo/fork\""), "fork button" ); let reply = send(&site, "GET", "/alice/demo", None, None).await; assert!( !reply.body.contains("action=\"/alice/demo/fork\""), "no fork button when anonymous" ); } }