forge
Explore
Log in

Don't you dare go Hollow

Fork works in dev and test builds

Browse files at this commit

e2a1952f2e2c291166aa86774682cfafe16a5553Ahmet Kaan GümüşParent: ac8a15b
  • fix
    • fork works in dev and test builds
    • its route lived alone in a module nothing referenced, so the linker dropped it and POST /fork answered 404
Show full message
🐛 fix: fork works in dev and test builds; its route lived alone in a module nothing referenced, so the linker dropped it and POST /fork answered 404
crates/forge-web-repo/src/pages/compare.rsmodified+134 -5
@@ -1,20 +1,23 @@
1 use std::path::PathBuf;1 use std::path::PathBuf;
2 2
3-use forge_core::{Action, NewPull, Repo as RepoRecord, authorize, validate_body, validate_title};3+use forge_core::{
4+ Action, AuditAction, NewPull, Repo as RepoRecord, authorize, validate_body, validate_title,
5+};
4 use forge_git::browse::{self, CommitInfo, RefKind};6 use forge_git::browse::{self, CommitInfo, RefKind};
5 use forge_git::command::ObjectSource;7 use forge_git::command::ObjectSource;
6 use forge_git::history;8 use forge_git::history;
7 use forge_git::pulls;9 use forge_git::pulls;
8-use forge_git::repo::repo_path;10+use forge_git::repo::{fork_bare, repo_path};
9 use serde::Deserialize;11 use serde::Deserialize;
10 use topcoat::Result;12 use topcoat::Result;
11 use topcoat::context::{Cx, context};13 use topcoat::context::{Cx, context};
12 use topcoat::router::content::Form;14 use topcoat::router::content::Form;
13-use topcoat::router::error::{bad_request, not_found, see_other};15+use topcoat::router::error::{SeeOther, bad_request, not_found, see_other};
14-use topcoat::router::{page, path_param, query_params};16+use topcoat::router::{page, path_param, query_params, route};
15 use topcoat::view::{View, view};17 use topcoat::view::{View, view};
16 18
17-use crate::auth::require_user;19+use crate::audit::{self, Actor, Target};
20+use crate::auth::{require_csrf, require_user};
18 use crate::i18n;21 use crate::i18n;
19 use crate::i18n::pulls::{self as g, K};22 use crate::i18n::pulls::{self as g, K};
20 use crate::notify::{self, Activity};23 use crate::notify::{self, Activity};
@@ -612,6 +615,132 @@ async fn pull_create(cx: &Cx, Form(form): Form<PullForm>) -> Result<impl View> {
612 Err(see_other(pull_href(&ctx, number)).into())615 Err(see_other(pull_href(&ctx, number)).into())
613 }616 }
614 617
618+#[derive(Deserialize)]
619+struct ForkForm {
620+ #[serde(default)]
621+ csrf: String,
622+}
623+
624+#[route(POST "/{owner}/{repo}/fork")]
625+async fn fork_post(cx: &Cx, Form(form): Form<ForkForm>) -> Result<SeeOther> {
626+ let owner = owner(cx);
627+ let name = repo(cx);
628+ let source = load_repo(cx, owner, name).await?;
629+ let (viewer, _) = require_csrf(cx, &form.csrf).await?;
630+ let state = context::<AppState>(cx);
631+ let source_repo = &source.repo;
632+
633+ if source_repo.owner_id == viewer.id {
634+ return Ok(see_other(repo_href(
635+ &source_repo.owner_name,
636+ &source_repo.name,
637+ "",
638+ "",
639+ )));
640+ }
641+
642+ if let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? {
643+ return Ok(see_other(repo_href(
644+ &existing.owner_name,
645+ &existing.name,
646+ "",
647+ "",
648+ )));
649+ }
650+
651+ let fork_name = free_name(state, &viewer.username, &source_repo.name).await?;
652+ let fork = match state
653+ .store
654+ .create_fork(source_repo, &viewer.id, &fork_name)
655+ .await
656+ {
657+ Ok(fork) => fork,
658+ Err(e @ forge_core::Error::Conflict(_)) => {
659+ let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? else {
660+ return Err(e.into());
661+ };
662+ return Ok(see_other(repo_href(
663+ &existing.owner_name,
664+ &existing.name,
665+ "",
666+ "",
667+ )));
668+ }
669+ Err(e) => return Err(e.into()),
670+ };
671+ let dst = repo_path(&state.config.data_dir, &fork.id)?;
672+ if let Err(e) = fork_bare(&state.git, &source.path, &dst).await {
673+ let _ = state.store.delete_repo(&fork.id).await;
674+ return Err(e.into());
675+ }
676+ state.live.bump_repo(&fork.owner_id, &fork.id);
677+ state.live.bump_repo(&source_repo.owner_id, &source_repo.id);
678+ match state.store.list_labels(&source_repo.id).await {
679+ Ok(labels) => {
680+ for label in labels {
681+ if let Err(e) = state
682+ .store
683+ .create_label(&fork.id, &label.name, &label.color, &label.description)
684+ .await
685+ {
686+ tracing::warn!(error = %e, repo_id = %fork.id, label = %label.name, "fork: could not copy label");
687+ }
688+ }
689+ }
690+ Err(e) => {
691+ tracing::warn!(error = %e, repo_id = %fork.id, "fork: could not list source labels");
692+ }
693+ }
694+ let full_name = format!("{}/{}", fork.owner_name, fork.name);
695+ let source_name = format!("{}/{}", source_repo.owner_name, source_repo.name);
696+ audit::record(
697+ &state.store,
698+ Some(cx),
699+ Actor::User(&viewer),
700+ AuditAction::RepoCreated,
701+ Target {
702+ kind: "repo",
703+ id: &fork.id,
704+ name: &full_name,
705+ },
706+ serde_json::json!({ "fork_of": source_name }),
707+ )
708+ .await;
709+ Ok(see_other(repo_href(&fork.owner_name, &fork.name, "", "")))
710+}
711+
712+async fn viewer_fork(
713+ state: &AppState,
714+ source_id: &str,
715+ viewer_id: &str,
716+) -> Result<Option<forge_core::Repo>> {
717+ Ok(state
718+ .store
719+ .list_forks(source_id)
720+ .await?
721+ .into_iter()
722+ .find(|fork| fork.owner_id == viewer_id))
723+}
724+
725+async fn free_name(state: &AppState, owner: &str, base: &str) -> Result<String> {
726+ let mut candidate = base.to_owned();
727+ let mut suffix = 1u32;
728+ while state
729+ .store
730+ .repo_by_owner_and_name(owner, &candidate)
731+ .await?
732+ .is_some()
733+ {
734+ candidate = format!("{base}-{suffix}");
735+ suffix += 1;
736+ }
737+ Ok(candidate)
738+}
739+
740+#[cfg(test)]
741+#[path = "fork_tests.rs"]
742+mod fork_tests;
743+
615 #[cfg(test)]744 #[cfg(test)]
616 mod tests {745 mod tests {
617 use std::path::{Path, PathBuf};746 use std::path::{Path, PathBuf};
crates/forge-web-repo/src/pages/fork.rsdeleted+0 -483
@@ -1,483 +0,0 @@
1-use forge_core::AuditAction;
2-use forge_git::repo::{fork_bare, repo_path};
3-use serde::Deserialize;
4-use topcoat::Result;
5-use topcoat::context::{Cx, context};
6-use topcoat::router::content::Form;
7-use topcoat::router::error::{SeeOther, see_other};
8-use topcoat::router::{path_param, route};
9-
10-use crate::audit::{self, Actor, Target};
11-use crate::auth::require_csrf;
12-use crate::pages::repo_ctx::load_repo;
13-use crate::state::AppState;
14-use crate::views::repo_href;
15-
16-path_param!(owner);
17-path_param!(repo);
18-
19-#[derive(Deserialize)]
20-struct ForkForm {
21- #[serde(default)]
22- csrf: String,
23-}
24-
25-#[route(POST "/{owner}/{repo}/fork")]
26-async fn fork_post(cx: &Cx, Form(form): Form<ForkForm>) -> Result<SeeOther> {
27- let owner = owner(cx);
28- let name = repo(cx);
29- let source = load_repo(cx, owner, name).await?;
30- let (viewer, _) = require_csrf(cx, &form.csrf).await?;
31- let state = context::<AppState>(cx);
32- let source_repo = &source.repo;
33-
34- if source_repo.owner_id == viewer.id {
35- return Ok(see_other(repo_href(
36- &source_repo.owner_name,
37- &source_repo.name,
38- "",
39- "",
40- )));
41- }
42-
43- if let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? {
44- return Ok(see_other(repo_href(
45- &existing.owner_name,
46- &existing.name,
47- "",
48- "",
49- )));
50- }
51-
52- let fork_name = free_name(state, &viewer.username, &source_repo.name).await?;
53- let fork = match state
54- .store
55- .create_fork(source_repo, &viewer.id, &fork_name)
56- .await
57- {
58- Ok(fork) => fork,
59- Err(e @ forge_core::Error::Conflict(_)) => {
60- let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? else {
61- return Err(e.into());
62- };
63- return Ok(see_other(repo_href(
64- &existing.owner_name,
65- &existing.name,
66- "",
67- "",
68- )));
69- }
70- Err(e) => return Err(e.into()),
71- };
72- let dst = repo_path(&state.config.data_dir, &fork.id)?;
73- if let Err(e) = fork_bare(&state.git, &source.path, &dst).await {
74- let _ = state.store.delete_repo(&fork.id).await;
75- return Err(e.into());
76- }
77- state.live.bump_repo(&fork.owner_id, &fork.id);
78- state.live.bump_repo(&source_repo.owner_id, &source_repo.id);
79- match state.store.list_labels(&source_repo.id).await {
80- Ok(labels) => {
81- for label in labels {
82- if let Err(e) = state
83- .store
84- .create_label(&fork.id, &label.name, &label.color, &label.description)
85- .await
86- {
87- tracing::warn!(error = %e, repo_id = %fork.id, label = %label.name, "fork: could not copy label");
88- }
89- }
90- }
91- Err(e) => {
92- tracing::warn!(error = %e, repo_id = %fork.id, "fork: could not list source labels");
93- }
94- }
95- let full_name = format!("{}/{}", fork.owner_name, fork.name);
96- let source_name = format!("{}/{}", source_repo.owner_name, source_repo.name);
97- audit::record(
98- &state.store,
99- Some(cx),
100- Actor::User(&viewer),
101- AuditAction::RepoCreated,
102- Target {
103- kind: "repo",
104- id: &fork.id,
105- name: &full_name,
106- },
107- serde_json::json!({ "fork_of": source_name }),
108- )
109- .await;
110- Ok(see_other(repo_href(&fork.owner_name, &fork.name, "", "")))
111-}
112-
113-async fn viewer_fork(
114- state: &AppState,
115- source_id: &str,
116- viewer_id: &str,
117-) -> Result<Option<forge_core::Repo>> {
118- Ok(state
119- .store
120- .list_forks(source_id)
121- .await?
122- .into_iter()
123- .find(|fork| fork.owner_id == viewer_id))
124-}
125-
126-async fn free_name(state: &AppState, owner: &str, base: &str) -> Result<String> {
127- let mut candidate = base.to_owned();
128- let mut suffix = 1u32;
129- while state
130- .store
131- .repo_by_owner_and_name(owner, &candidate)
132- .await?
133- .is_some()
134- {
135- candidate = format!("{base}-{suffix}");
136- suffix += 1;
137- }
138- Ok(candidate)
139-}
140-
141-#[cfg(test)]
142-mod tests {
143- use std::path::Path;
144- use std::process::Command;
145-
146- use crate::test_support::fixture::{Reply, send_form};
147- use forge_core::{AuditAction, Store, Visibility};
148- use forge_git::repo::{init_bare, repo_path};
149- use topcoat::router::Router;
150-
151- use crate::auth::SESSION_COOKIE;
152-
153- const CSRF: &str = "fork-test-csrf";
154-
155- struct Site {
156- router: Router,
157- store: Store,
158- dir: tempfile::TempDir,
159- }
160-
161- async fn site() -> (Site, [String; 3]) {
162- let dir = tempfile::tempdir().expect("tempdir");
163- let state = crate::test_support::test_state(dir.path()).await;
164- let store = state.store.clone();
165- let router = crate::test_support::app_router(state.clone());
166-
167- let tahinli = store
168- .create_user("tahinli", None, "x", false)
169- .await
170- .expect("tahinli");
171- let bob = store
172- .create_user("bob", None, "x", false)
173- .await
174- .expect("bob");
175- let carol = store
176- .create_user("carol", None, "x", false)
177- .await
178- .expect("carol");
179- let demo = store
180- .create_repo(
181- &tahinli.id,
182- "demo",
183- "A demo repo",
184- Visibility::Public,
185- "main",
186- )
187- .await
188- .expect("demo");
189- let secret = store
190- .create_repo(&tahinli.id, "secret", "", Visibility::Private, "main")
191- .await
192- .expect("secret");
193- for repo in [&demo, &secret] {
194- let path = repo_path(dir.path(), &repo.id).expect("path");
195- init_bare(&state.git, &path, "main").await.expect("init");
196- }
197-
198- let work = dir.path().join("work");
199- std::fs::create_dir_all(&work).expect("work dir");
200- std::fs::write(work.join("README.md"), "# Demo\n").expect("write");
201- git(&work, &["init", "-q", "-b", "main"]);
202- git(&work, &["add", "-A"]);
203- git(&work, &["commit", "-q", "-m", "first commit"]);
204- git(&work, &["tag", "v1"]);
205- let demo_path = repo_path(dir.path(), &demo.id).expect("path");
206- git(
207- &work,
208- &[
209- "push",
210- "-q",
211- demo_path.to_str().expect("utf8"),
212- "main:main",
213- "v1",
214- ],
215- );
216-
217- let cookies = [
218- sign_in(&store, &tahinli.id, "tahinli-token").await,
219- sign_in(&store, &bob.id, "bob-token").await,
220- sign_in(&store, &carol.id, "carol-token").await,
221- ];
222- (Site { router, store, dir }, cookies)
223- }
224-
225- async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {
226- crate::test_support::create_session(store, user_id, token, CSRF).await;
227- format!("__Host-{SESSION_COOKIE}={token}")
228- }
229-
230- fn git(dir: &Path, args: &[&str]) {
231- let status = Command::new("git")
232- .current_dir(dir)
233- .env("GIT_CONFIG_NOSYSTEM", "1")
234- .args([
235- "-c",
236- "user.name=Test",
237- "-c",
238- "user.email=test@example.com",
239- "-c",
240- "commit.gpgsign=false",
241- ])
242- .args(args)
243- .status()
244- .expect("git runs");
245- assert!(status.success(), "git {args:?} failed");
246- }
247-
248- async fn send(
249- site: &Site,
250- method: &str,
251- uri: &str,
252- cookie: Option<&str>,
253- form: Option<String>,
254- ) -> Reply {
255- send_form(&site.router, method, uri, cookie, form).await
256- }
257-
258- async fn fork(site: &Site, cookie: Option<&str>) -> Reply {
259- send(
260- site,
261- "POST",
262- "/tahinli/demo/fork",
263- cookie,
264- Some(format!("csrf={CSRF}")),
265- )
266- .await
267- }
268-
269- async fn scenario_refusals(site: &Site, tahinli: &str, bob: &str, carol: &str) {
270- let reply = send(
271- site,
272- "POST",
273- "/tahinli/demo/fork",
274- Some(bob),
275- Some(String::new()),
276- )
277- .await;
278- assert_eq!(reply.status, 403);
279- let reply = send(
280- site,
281- "POST",
282- "/tahinli/demo/fork",
283- Some(bob),
284- Some("csrf=wrong".into()),
285- )
286- .await;
287- assert_eq!(reply.status, 403);
288- assert!(
289- site.store
290- .repo_by_owner_and_name("bob", "demo")
291- .await
292- .expect("q")
293- .is_none(),
294- "nothing was created"
295- );
296-
297- let reply = fork(site, None).await;
298- assert_eq!(reply.status, 303);
299- assert!(
300- reply
301- .location
302- .as_deref()
303- .is_some_and(|l| l.starts_with("/login")),
304- "{:?}",
305- reply.location
306- );
307-
308- let reply = send(
309- site,
310- "POST",
311- "/tahinli/secret/fork",
312- Some(carol),
313- Some(format!("csrf={CSRF}")),
314- )
315- .await;
316- assert_eq!(reply.status, 404);
317- let reply = send(
318- site,
319- "POST",
320- "/tahinli/secret/fork",
321- None,
322- Some(format!("csrf={CSRF}")),
323- )
324- .await;
325- assert_eq!(reply.status, 404, "anonymous viewers also get 404");
326-
327- let reply = fork(site, Some(tahinli)).await;
328- assert_eq!(reply.status, 303);
329- assert_eq!(reply.location.as_deref(), Some("/tahinli/demo"));
330- assert!(
331- site.store
332- .repo_by_owner_and_name("tahinli", "demo-1")
333- .await
334- .expect("q")
335- .is_none()
336- );
337-
338- let reply = send(site, "GET", "/tahinli/demo", Some(carol), None).await;
339- assert_eq!(reply.status, 200);
340- assert!(
341- reply.body.contains("href=\"/tahinli/demo/pulls\""),
342- "pulls tab"
343- );
344- assert!(reply.body.contains("Pull requests"));
345- assert!(
346- reply.body.contains("action=\"/tahinli/demo/fork\""),
347- "fork button"
348- );
349- let reply = send(site, "GET", "/tahinli/demo", None, None).await;
350- assert!(
351- !reply.body.contains("action=\"/tahinli/demo/fork\""),
352- "no fork button when anonymous"
353- );
354- }
355-
356- async fn scenario_fork_copies(site: &Site, bob: &str) {
357- let demo = site
358- .store
359- .repo_by_owner_and_name("tahinli", "demo")
360- .await
361- .expect("query")
362- .expect("demo");
363- site.store
364- .create_label(&demo.id, "triage-me", "#123456", "only here")
365- .await
366- .expect("label");
367- let reply = fork(site, Some(bob)).await;
368- assert_eq!(reply.status, 303);
369- assert_eq!(reply.location.as_deref(), Some("/bob/demo"));
370-
371- let bob_id = site
372- .store
373- .user_by_username("bob")
374- .await
375- .expect("q")
376- .expect("bob")
377- .id;
378- let fork = site
379- .store
380- .repo_by_owner_and_name("bob", "demo")
381- .await
382- .expect("q")
383- .expect("fork row");
384- assert_eq!(fork.fork_of.as_deref(), Some(demo.id.as_str()));
385- assert_eq!(fork.visibility, Visibility::Public);
386- assert_eq!(fork.owner_id, bob_id);
387- let labels: Vec<(String, String, String)> = site
388- .store
389- .list_labels(&fork.id)
390- .await
391- .expect("labels")
392- .into_iter()
393- .map(|l| (l.name, l.color, l.description))
394- .collect();
395- assert_eq!(
396- labels,
397- vec![(
398- "triage-me".to_string(),
399- "#123456".to_string(),
400- "only here".to_string()
401- )]
402- );
403-
404- let forked = site
405- .store
406- .list_audit(
407- &forge_core::AuditFilter {
408- action: Some(AuditAction::RepoCreated),
409- ..Default::default()
410- },
411- None,
412- 10,
413- )
414- .await
415- .expect("audit");
416- assert_eq!(forked.len(), 1, "one audit entry for the fork");
417- assert_eq!(forked[0].target_id, fork.id);
418- assert_eq!(forked[0].target_name, "bob/demo");
419- assert_eq!(forked[0].actor_id.as_deref(), Some(bob_id.as_str()));
420- let data: serde_json::Value = serde_json::from_str(&forked[0].data).expect("json");
421- assert_eq!(data, serde_json::json!({ "fork_of": "tahinli/demo" }));
422-
423- let path = repo_path(site.dir.path(), &fork.id).expect("path");
424- let refs = Command::new("git")
425- .arg("--git-dir")
426- .arg(&path)
427- .args(["for-each-ref", "--format=%(refname)"])
428- .output()
429- .expect("git runs");
430- let refs = String::from_utf8_lossy(&refs.stdout).into_owned();
431- assert_eq!(
432- refs.lines().collect::<Vec<_>>(),
433- vec!["refs/heads/main", "refs/tags/v1"]
434- );
435-
436- let page = send(site, "GET", "/bob/demo", Some(bob), None).await;
437- assert_eq!(page.status, 200);
438- assert!(page.body.contains("forked from"), "fork line shown");
439- assert!(
440- page.body.contains("href=\"/tahinli/demo\""),
441- "fork line links the source"
442- );
443- }
444-
445- async fn scenario_fork_again(site: &Site, bob: &str) {
446- assert_eq!(fork(site, Some(bob)).await.status, 303);
447- let again = fork(site, Some(bob)).await;
448- assert_eq!(again.status, 303);
449- assert_eq!(again.location.as_deref(), Some("/bob/demo"));
450- assert!(
451- site.store
452- .repo_by_owner_and_name("bob", "demo-1")
453- .await
454- .expect("q")
455- .is_none(),
456- "no second fork was created"
457- );
458- }
459-
460- async fn scenario_suffix(site: &Site) {
461- let erin = site
462- .store
463- .create_user("erin", None, "x", false)
464- .await
465- .expect("erin");
466- let erin_cookie = sign_in(&site.store, &erin.id, "erin-token").await;
467- site.store
468- .create_repo(&erin.id, "demo", "", Visibility::Private, "main")
469- .await
470- .expect("erin's own demo");
471- let reply = fork(site, Some(&erin_cookie)).await;
472- assert_eq!(reply.location.as_deref(), Some("/erin/demo-1"));
473- }
474-
475- #[tokio::test]
476- async fn fork_flows() {
477- let (site, [tahinli, bob, carol]) = site().await;
478- scenario_refusals(&site, &tahinli, &bob, &carol).await;
479- scenario_fork_copies(&site, &bob).await;
480- scenario_fork_again(&site, &bob).await;
481- scenario_suffix(&site).await;
482- }
483-}
crates/forge-web-repo/src/pages/fork_tests.rsadded+340 -0
@@ -0,0 +1,340 @@
1+use std::path::Path;
2+use std::process::Command;
3+
4+use crate::test_support::fixture::{Reply, send_form};
5+use forge_core::{AuditAction, Store, Visibility};
6+use forge_git::repo::{init_bare, repo_path};
7+use topcoat::router::Router;
8+
9+use crate::auth::SESSION_COOKIE;
10+
11+const CSRF: &str = "fork-test-csrf";
12+
13+struct Site {
14+ router: Router,
15+ store: Store,
16+ dir: tempfile::TempDir,
17+}
18+
19+async fn site() -> (Site, [String; 3]) {
20+ let dir = tempfile::tempdir().expect("tempdir");
21+ let state = crate::test_support::test_state(dir.path()).await;
22+ let store = state.store.clone();
23+ let router = crate::test_support::app_router(state.clone());
24+
25+ let tahinli = store
26+ .create_user("tahinli", None, "x", false)
27+ .await
28+ .expect("tahinli");
29+ let bob = store
30+ .create_user("bob", None, "x", false)
31+ .await
32+ .expect("bob");
33+ let carol = store
34+ .create_user("carol", None, "x", false)
35+ .await
36+ .expect("carol");
37+ let demo = store
38+ .create_repo(
39+ &tahinli.id,
40+ "demo",
41+ "A demo repo",
42+ Visibility::Public,
43+ "main",
44+ )
45+ .await
46+ .expect("demo");
47+ let secret = store
48+ .create_repo(&tahinli.id, "secret", "", Visibility::Private, "main")
49+ .await
50+ .expect("secret");
51+ for repo in [&demo, &secret] {
52+ let path = repo_path(dir.path(), &repo.id).expect("path");
53+ init_bare(&state.git, &path, "main").await.expect("init");
54+ }
55+
56+ let work = dir.path().join("work");
57+ std::fs::create_dir_all(&work).expect("work dir");
58+ std::fs::write(work.join("README.md"), "# Demo\n").expect("write");
59+ git(&work, &["init", "-q", "-b", "main"]);
60+ git(&work, &["add", "-A"]);
61+ git(&work, &["commit", "-q", "-m", "first commit"]);
62+ git(&work, &["tag", "v1"]);
63+ let demo_path = repo_path(dir.path(), &demo.id).expect("path");
64+ git(
65+ &work,
66+ &[
67+ "push",
68+ "-q",
69+ demo_path.to_str().expect("utf8"),
70+ "main:main",
71+ "v1",
72+ ],
73+ );
74+
75+ let cookies = [
76+ sign_in(&store, &tahinli.id, "tahinli-token").await,
77+ sign_in(&store, &bob.id, "bob-token").await,
78+ sign_in(&store, &carol.id, "carol-token").await,
79+ ];
80+ (Site { router, store, dir }, cookies)
81+}
82+
83+async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {
84+ crate::test_support::create_session(store, user_id, token, CSRF).await;
85+ format!("__Host-{SESSION_COOKIE}={token}")
86+}
87+
88+fn git(dir: &Path, args: &[&str]) {
89+ let status = Command::new("git")
90+ .current_dir(dir)
91+ .env("GIT_CONFIG_NOSYSTEM", "1")
92+ .args([
93+ "-c",
94+ "user.name=Test",
95+ "-c",
96+ "user.email=test@example.com",
97+ "-c",
98+ "commit.gpgsign=false",
99+ ])
100+ .args(args)
101+ .status()
102+ .expect("git runs");
103+ assert!(status.success(), "git {args:?} failed");
104+}
105+
106+async fn send(
107+ site: &Site,
108+ method: &str,
109+ uri: &str,
110+ cookie: Option<&str>,
111+ form: Option<String>,
112+) -> Reply {
113+ send_form(&site.router, method, uri, cookie, form).await
114+}
115+
116+async fn fork(site: &Site, cookie: Option<&str>) -> Reply {
117+ send(
118+ site,
119+ "POST",
120+ "/tahinli/demo/fork",
121+ cookie,
122+ Some(format!("csrf={CSRF}")),
123+ )
124+ .await
125+}
126+
127+async fn scenario_refusals(site: &Site, tahinli: &str, bob: &str, carol: &str) {
128+ let reply = send(
129+ site,
130+ "POST",
131+ "/tahinli/demo/fork",
132+ Some(bob),
133+ Some(String::new()),
134+ )
135+ .await;
136+ assert_eq!(reply.status, 403);
137+ let reply = send(
138+ site,
139+ "POST",
140+ "/tahinli/demo/fork",
141+ Some(bob),
142+ Some("csrf=wrong".into()),
143+ )
144+ .await;
145+ assert_eq!(reply.status, 403);
146+ assert!(
147+ site.store
148+ .repo_by_owner_and_name("bob", "demo")
149+ .await
150+ .expect("q")
151+ .is_none(),
152+ "nothing was created"
153+ );
154+
155+ let reply = fork(site, None).await;
156+ assert_eq!(reply.status, 303);
157+ assert!(
158+ reply
159+ .location
160+ .as_deref()
161+ .is_some_and(|l| l.starts_with("/login")),
162+ "{:?}",
163+ reply.location
164+ );
165+
166+ let reply = send(
167+ site,
168+ "POST",
169+ "/tahinli/secret/fork",
170+ Some(carol),
171+ Some(format!("csrf={CSRF}")),
172+ )
173+ .await;
174+ assert_eq!(reply.status, 404);
175+ let reply = send(
176+ site,
177+ "POST",
178+ "/tahinli/secret/fork",
179+ None,
180+ Some(format!("csrf={CSRF}")),
181+ )
182+ .await;
183+ assert_eq!(reply.status, 404, "anonymous viewers also get 404");
184+
185+ let reply = fork(site, Some(tahinli)).await;
186+ assert_eq!(reply.status, 303);
187+ assert_eq!(reply.location.as_deref(), Some("/tahinli/demo"));
188+ assert!(
189+ site.store
190+ .repo_by_owner_and_name("tahinli", "demo-1")
191+ .await
192+ .expect("q")
193+ .is_none()
194+ );
195+
196+ let reply = send(site, "GET", "/tahinli/demo", Some(carol), None).await;
197+ assert_eq!(reply.status, 200);
198+ assert!(
199+ reply.body.contains("href=\"/tahinli/demo/pulls\""),
200+ "pulls tab"
201+ );
202+ assert!(reply.body.contains("Pull requests"));
203+ assert!(
204+ reply.body.contains("action=\"/tahinli/demo/fork\""),
205+ "fork button"
206+ );
207+ let reply = send(site, "GET", "/tahinli/demo", None, None).await;
208+ assert!(
209+ !reply.body.contains("action=\"/tahinli/demo/fork\""),
210+ "no fork button when anonymous"
211+ );
212+}
213+
214+async fn scenario_fork_copies(site: &Site, bob: &str) {
215+ let demo = site
216+ .store
217+ .repo_by_owner_and_name("tahinli", "demo")
218+ .await
219+ .expect("query")
220+ .expect("demo");
221+ site.store
222+ .create_label(&demo.id, "triage-me", "#123456", "only here")
223+ .await
224+ .expect("label");
225+ let reply = fork(site, Some(bob)).await;
226+ assert_eq!(reply.status, 303);
227+ assert_eq!(reply.location.as_deref(), Some("/bob/demo"));
228+
229+ let bob_id = site
230+ .store
231+ .user_by_username("bob")
232+ .await
233+ .expect("q")
234+ .expect("bob")
235+ .id;
236+ let fork = site
237+ .store
238+ .repo_by_owner_and_name("bob", "demo")
239+ .await
240+ .expect("q")
241+ .expect("fork row");
242+ assert_eq!(fork.fork_of.as_deref(), Some(demo.id.as_str()));
243+ assert_eq!(fork.visibility, Visibility::Public);
244+ assert_eq!(fork.owner_id, bob_id);
245+ let labels: Vec<(String, String, String)> = site
246+ .store
247+ .list_labels(&fork.id)
248+ .await
249+ .expect("labels")
250+ .into_iter()
251+ .map(|l| (l.name, l.color, l.description))
252+ .collect();
253+ assert_eq!(
254+ labels,
255+ vec![(
256+ "triage-me".to_string(),
257+ "#123456".to_string(),
258+ "only here".to_string()
259+ )]
260+ );
261+
262+ let forked = site
263+ .store
264+ .list_audit(
265+ &forge_core::AuditFilter {
266+ action: Some(AuditAction::RepoCreated),
267+ ..Default::default()
268+ },
269+ None,
270+ 10,
271+ )
272+ .await
273+ .expect("audit");
274+ assert_eq!(forked.len(), 1, "one audit entry for the fork");
275+ assert_eq!(forked[0].target_id, fork.id);
276+ assert_eq!(forked[0].target_name, "bob/demo");
277+ assert_eq!(forked[0].actor_id.as_deref(), Some(bob_id.as_str()));
278+ let data: serde_json::Value = serde_json::from_str(&forked[0].data).expect("json");
279+ assert_eq!(data, serde_json::json!({ "fork_of": "tahinli/demo" }));
280+
281+ let path = repo_path(site.dir.path(), &fork.id).expect("path");
282+ let refs = Command::new("git")
283+ .arg("--git-dir")
284+ .arg(&path)
285+ .args(["for-each-ref", "--format=%(refname)"])
286+ .output()
287+ .expect("git runs");
288+ let refs = String::from_utf8_lossy(&refs.stdout).into_owned();
289+ assert_eq!(
290+ refs.lines().collect::<Vec<_>>(),
291+ vec!["refs/heads/main", "refs/tags/v1"]
292+ );
293+
294+ let page = send(site, "GET", "/bob/demo", Some(bob), None).await;
295+ assert_eq!(page.status, 200);
296+ assert!(page.body.contains("forked from"), "fork line shown");
297+ assert!(
298+ page.body.contains("href=\"/tahinli/demo\""),
299+ "fork line links the source"
300+ );
301+}
302+
303+async fn scenario_fork_again(site: &Site, bob: &str) {
304+ assert_eq!(fork(site, Some(bob)).await.status, 303);
305+ let again = fork(site, Some(bob)).await;
306+ assert_eq!(again.status, 303);
307+ assert_eq!(again.location.as_deref(), Some("/bob/demo"));
308+ assert!(
309+ site.store
310+ .repo_by_owner_and_name("bob", "demo-1")
311+ .await
312+ .expect("q")
313+ .is_none(),
314+ "no second fork was created"
315+ );
316+}
317+
318+async fn scenario_suffix(site: &Site) {
319+ let erin = site
320+ .store
321+ .create_user("erin", None, "x", false)
322+ .await
323+ .expect("erin");
324+ let erin_cookie = sign_in(&site.store, &erin.id, "erin-token").await;
325+ site.store
326+ .create_repo(&erin.id, "demo", "", Visibility::Private, "main")
327+ .await
328+ .expect("erin's own demo");
329+ let reply = fork(site, Some(&erin_cookie)).await;
330+ assert_eq!(reply.location.as_deref(), Some("/erin/demo-1"));
331+}
332+
333+#[tokio::test]
334+async fn fork_flows() {
335+ let (site, [tahinli, bob, carol]) = site().await;
336+ scenario_refusals(&site, &tahinli, &bob, &carol).await;
337+ scenario_fork_copies(&site, &bob).await;
338+ scenario_fork_again(&site, &bob).await;
339+ scenario_suffix(&site).await;
340+}
crates/forge-web-repo/src/pages/mod.rsmodified+0 -1
@@ -17,7 +17,6 @@ pub mod commit;
17 pub mod commits;17 pub mod commits;
18 pub mod compare;18 pub mod compare;
19 #[cfg(test)]19 #[cfg(test)]
20-pub mod fork;
21 #[cfg(test)]20 #[cfg(test)]
22 mod issue_meta_tests;21 mod issue_meta_tests;
23 pub mod issue_pin;22 pub mod issue_pin;