| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "os" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | |
| 11 | "gitlab.com/Timfa/bluegit/internal/access" |
| 12 | "gitlab.com/Timfa/bluegit/internal/ci" |
| 13 | "gitlab.com/Timfa/bluegit/internal/diskusage" |
| 14 | "gitlab.com/Timfa/bluegit/internal/gitrepo" |
| 15 | "gitlab.com/Timfa/bluegit/internal/i18n" |
| 16 | "gitlab.com/Timfa/bluegit/internal/state" |
| 17 | "gitlab.com/Timfa/bluegit/internal/store" |
| 18 | ) |
| 19 | |
| 20 | // forkReserveBytes: zoveel moet er naast de upstream-grootte vrij blijven. |
| 21 | const forkReserveBytes = 512 << 20 |
| 22 | |
| 23 | // canReadRepo: openbaar, of de gebruiker heeft minstens leesrechten. |
| 24 | func (s *Server) canReadRepo(ctx context.Context, userID int64, repo store.Repo) bool { |
| 25 | if repo.Visibility == "public" { |
| 26 | return true |
| 27 | } |
| 28 | if userID == 0 { |
| 29 | return false |
| 30 | } |
| 31 | role, err := s.Store.EffectiveRole(ctx, userID, repo.ID) |
| 32 | return err == nil && role.CanRead() |
| 33 | } |
| 34 | |
| 35 | // ForkInfo is wat de repo-pagina over de fork-relatie toont. |
| 36 | type ForkInfo struct { |
| 37 | IsFork bool |
| 38 | Upstream *store.Repo // nil als de kijker upstream niet mag zien |
| 39 | Forks int // zichtbare forks van deze repo |
| 40 | } |
| 41 | |
| 42 | func (s *Server) forkInfo(ctx context.Context, userID int64, repo store.Repo) ForkInfo { |
| 43 | var fi ForkInfo |
| 44 | if up, _ := s.Store.ForkOf(ctx, repo.ID); up != 0 { |
| 45 | fi.IsFork = true |
| 46 | if u, err := s.Store.RepoByID(ctx, up); err == nil && s.canReadRepo(ctx, userID, u) { |
| 47 | fi.Upstream = &u |
| 48 | } |
| 49 | } |
| 50 | fi.Forks = len(s.visibleForks(ctx, userID, repo)) |
| 51 | return fi |
| 52 | } |
| 53 | |
| 54 | func (s *Server) visibleForks(ctx context.Context, userID int64, repo store.Repo) []store.Repo { |
| 55 | ids, _ := s.Store.ForkIDs(ctx, repo.ID) |
| 56 | if len(ids) == 0 { |
| 57 | return nil |
| 58 | } |
| 59 | list, _ := s.Store.ReposByIDs(ctx, ids) |
| 60 | var out []store.Repo |
| 61 | for _, f := range list { |
| 62 | if s.canReadRepo(ctx, userID, f) { |
| 63 | out = append(out, f) |
| 64 | } |
| 65 | } |
| 66 | return out |
| 67 | } |
| 68 | |
| 69 | // ForkTarget is een plek waar de gebruiker een fork mag maken. |
| 70 | type ForkTarget struct { |
| 71 | Value string // "" = eigen account, anders groepspad |
| 72 | Label string |
| 73 | } |
| 74 | |
| 75 | func (s *Server) forkTargets(ctx context.Context, user store.User) []ForkTarget { |
| 76 | out := []ForkTarget{{Value: "", Label: user.Username}} |
| 77 | groups, _ := s.Store.ListGroups(ctx, user.ID) |
| 78 | for _, g := range groups { |
| 79 | if role, err := s.Store.GroupRole(ctx, g.ID, user.ID); err == nil && role.CanWriteCode() { |
| 80 | out = append(out, ForkTarget{Value: g.Path, Label: g.Path}) |
| 81 | } |
| 82 | } |
| 83 | return out |
| 84 | } |
| 85 | |
| 86 | // opForkRepo maakt een fork met alle branches en tags. Doel: eigen account |
| 87 | // of een groep waar de gebruiker minstens developer is. Een fork van een |
| 88 | // privé repo is privé. |
| 89 | func (s *Server) opForkRepo(ctx context.Context, user store.User, upstream store.Repo, groupPath, rawName string) (store.Repo, error) { |
| 90 | if s.StoragePath() == "" { |
| 91 | return store.Repo{}, fail(503, i18n.E("err.noStorage")) |
| 92 | } |
| 93 | if !s.canReadRepo(ctx, user.ID, upstream) { |
| 94 | return store.Repo{}, fail(404, i18n.E("err.notFound")) |
| 95 | } |
| 96 | if strings.TrimSpace(rawName) == "" { |
| 97 | rawName = upstream.Name |
| 98 | } |
| 99 | name, err := slugKind("repo", rawName) |
| 100 | if err != nil { |
| 101 | return store.Repo{}, fail(400, err) |
| 102 | } |
| 103 | ownerKind, ownerID, ownerPath := "user", user.ID, user.Username |
| 104 | if gp := strings.TrimSpace(groupPath); gp != "" { |
| 105 | g, err := s.Store.GroupByPath(ctx, gp) |
| 106 | if err != nil { |
| 107 | return store.Repo{}, fail(404, i18n.E("err.groupMissing")) |
| 108 | } |
| 109 | role, err := s.Store.GroupRole(ctx, g.ID, user.ID) |
| 110 | if err != nil || !role.AtLeast(access.RoleDeveloper) { |
| 111 | return store.Repo{}, fail(403, i18n.E("err.forbidden")) |
| 112 | } |
| 113 | ownerKind, ownerID, ownerPath = "group", g.ID, g.Path |
| 114 | } |
| 115 | if _, err := s.Store.RepoByPath(ctx, ownerPath, name); err == nil { |
| 116 | return store.Repo{}, fail(409, i18n.E("err.forkExists", ownerPath+"/"+name)) |
| 117 | } |
| 118 | src := gitrepo.Dir(s.StoragePath(), upstream.OwnerPath, upstream.Name) |
| 119 | if size, err := state.DirSize(ctx, src); err == nil { |
| 120 | if du, err := diskusage.Usage(s.StoragePath()); err == nil && du.Free < size+forkReserveBytes { |
| 121 | return store.Repo{}, fail(507, i18n.E("err.forkDisk")) |
| 122 | } |
| 123 | } |
| 124 | repo, err := s.Store.CreateRepo(ctx, ownerKind, ownerID, name, upstream.Description, upstream.DefaultBranch, upstream.Visibility) |
| 125 | if err != nil { |
| 126 | return store.Repo{}, fail(400, err) |
| 127 | } |
| 128 | dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name) |
| 129 | if err := gitrepo.Fork(s.Git, src, dir, s.HookBin); err != nil { |
| 130 | _ = s.Store.DeleteRepo(ctx, repo.ID) |
| 131 | _ = os.RemoveAll(dir) |
| 132 | return store.Repo{}, fail(500, i18n.E("err.forkGit", err.Error())) |
| 133 | } |
| 134 | if err := s.Store.SetForkOf(ctx, repo.ID, upstream.ID); err != nil { |
| 135 | return store.Repo{}, fail(500, err) |
| 136 | } |
| 137 | s.syncRepos(ctx, []int64{repo.ID}) |
| 138 | return repo, nil |
| 139 | } |
| 140 | |
| 141 | // forkMustStayPrivate: een fork van een privé upstream mag niet openbaar. |
| 142 | func (s *Server) forkMustStayPrivate(ctx context.Context, repo store.Repo) bool { |
| 143 | up, _ := s.Store.ForkOf(ctx, repo.ID) |
| 144 | if up == 0 { |
| 145 | return false |
| 146 | } |
| 147 | u, err := s.Store.RepoByID(ctx, up) |
| 148 | return err == nil && u.Visibility != "public" |
| 149 | } |
| 150 | |
| 151 | func (s *Server) forkPost(w http.ResponseWriter, r *http.Request) { |
| 152 | u, repo, _, ok := s.guard(w, r, access.RoleReadonly) |
| 153 | if !ok || !s.csrfOK(w, r) { |
| 154 | return |
| 155 | } |
| 156 | if u.ID == 0 { |
| 157 | http.Redirect(w, r, "/login", http.StatusSeeOther) |
| 158 | return |
| 159 | } |
| 160 | fork, err := s.opForkRepo(r.Context(), u, repo, r.FormValue("namespace"), r.FormValue("name")) |
| 161 | if !s.uiOK(w, r, repoURL(repo), err) { |
| 162 | return |
| 163 | } |
| 164 | s.redirect(w, r, repoURL(fork), s.tr(r, "flash.forked"), "") |
| 165 | } |
| 166 | |
| 167 | func (s *Server) forksPage(w http.ResponseWriter, r *http.Request) { |
| 168 | u, repo, role, ok := s.guard(w, r, access.RoleReadonly) |
| 169 | if !ok { |
| 170 | return |
| 171 | } |
| 172 | v := s.repoView(w, r, repo, role, s.tr(r, "fork.listTitle")) |
| 173 | v.ForkList = s.visibleForks(r.Context(), u.ID, repo) |
| 174 | v.Fork = s.forkInfo(r.Context(), u.ID, repo) |
| 175 | s.render(w, "forks", v) |
| 176 | } |
| 177 | |
| 178 | func forkJSON(fork store.Repo, upstream store.Repo) map[string]any { |
| 179 | out := projectJSON(fork) |
| 180 | out["forked_from"] = upstream.FullPath() |
| 181 | return out |
| 182 | } |
| 183 | |
| 184 | func (s *Server) apiForkProject(w http.ResponseWriter, r *http.Request) { |
| 185 | repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) |
| 186 | if !ok { |
| 187 | return |
| 188 | } |
| 189 | var body struct { |
| 190 | Namespace string `json:"namespace"` |
| 191 | Name string `json:"name"` |
| 192 | } |
| 193 | if err := readJSON(r, &body); err != nil { |
| 194 | s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) |
| 195 | return |
| 196 | } |
| 197 | fork, err := s.opForkRepo(r.Context(), apiUser(r), repo, body.Namespace, body.Name) |
| 198 | if !s.apiOK(w, r, err) { |
| 199 | return |
| 200 | } |
| 201 | writeJSON(w, http.StatusCreated, forkJSON(fork, repo)) |
| 202 | } |
| 203 | |
| 204 | func (s *Server) apiListForks(w http.ResponseWriter, r *http.Request) { |
| 205 | repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) |
| 206 | if !ok { |
| 207 | return |
| 208 | } |
| 209 | s.writeProjects(w, r, s.visibleForks(r.Context(), apiUser(r).ID, repo)) |
| 210 | } |
| 211 | |
| 212 | // SyncResult is de uitkomst van een upstream-synchronisatie. |
| 213 | type SyncResult struct { |
| 214 | Branch string `json:"branch"` |
| 215 | Before string `json:"before"` |
| 216 | After string `json:"after"` |
| 217 | UpToDate bool `json:"up_to_date"` |
| 218 | } |
| 219 | |
| 220 | // opSyncUpstream zet branch (standaard de standaardbranch) van upstream |
| 221 | // fast-forward door naar de fork. Geen force: bij afwijking 409. Vereist |
| 222 | // schrijfrechten op de fork en leesrechten op upstream; zonder leesrechten |
| 223 | // noemt de fout de upstream niet. |
| 224 | func (s *Server) opSyncUpstream(ctx context.Context, user store.User, fork store.Repo, branch string) (SyncResult, error) { |
| 225 | role, err := s.Store.EffectiveRole(ctx, user.ID, fork.ID) |
| 226 | if err != nil || !role.CanWriteCode() { |
| 227 | return SyncResult{}, fail(403, i18n.E("err.forbidden")) |
| 228 | } |
| 229 | upID, _ := s.Store.ForkOf(ctx, fork.ID) |
| 230 | if upID == 0 { |
| 231 | return SyncResult{}, fail(400, i18n.E("err.notFork")) |
| 232 | } |
| 233 | up, err := s.Store.RepoByID(ctx, upID) |
| 234 | if err != nil || !s.canReadRepo(ctx, user.ID, up) { |
| 235 | return SyncResult{}, fail(403, i18n.E("err.upstreamNoAccess")) |
| 236 | } |
| 237 | branch = strings.TrimSpace(branch) |
| 238 | if branch == "" { |
| 239 | branch = fork.DefaultBranch |
| 240 | } |
| 241 | if !safeBranchName(branch) { |
| 242 | return SyncResult{}, fail(400, i18n.E("err.upstreamBranch", branch)) |
| 243 | } |
| 244 | updir := gitrepo.Dir(s.StoragePath(), up.OwnerPath, up.Name) |
| 245 | dir := gitrepo.Dir(s.StoragePath(), fork.OwnerPath, fork.Name) |
| 246 | upSHA := gitOne(ctx, s.Git, updir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch) |
| 247 | if !shaLike(upSHA) { |
| 248 | return SyncResult{}, fail(404, i18n.E("err.upstreamBranch", branch)) |
| 249 | } |
| 250 | res := SyncResult{Branch: branch, Before: gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch)} |
| 251 | if res.Before == upSHA { |
| 252 | res.After, res.UpToDate = upSHA, true |
| 253 | return res, nil |
| 254 | } |
| 255 | patterns, _ := s.Store.ProtectedPatterns(ctx, fork.ID) |
| 256 | env := append(os.Environ(), gitrepo.PushEnv(role, patterns, nil)...) |
| 257 | if err := s.postReceive(ctx, fork, user, dir, func() error { |
| 258 | return gitrepo.PushBranch(ctx, s.Git, updir, dir, branch, env) |
| 259 | }); err != nil { |
| 260 | if errors.Is(err, gitrepo.ErrNotFastForward) { |
| 261 | return res, fail(409, i18n.E("err.syncNotFF", branch)) |
| 262 | } |
| 263 | return res, fail(400, err) |
| 264 | } |
| 265 | res.After = gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch) |
| 266 | return res, nil |
| 267 | } |
| 268 | |
| 269 | func safeBranchName(b string) bool { |
| 270 | return b != "" && !strings.HasPrefix(b, "-") && !strings.Contains(b, "..") && !strings.ContainsAny(b, " ~^:?*[\\") |
| 271 | } |
| 272 | |
| 273 | func (s *Server) syncUpstreamPost(w http.ResponseWriter, r *http.Request) { |
| 274 | u, repo, _, ok := s.guard(w, r, access.RoleDeveloper) |
| 275 | if !ok || !s.csrfOK(w, r) { |
| 276 | return |
| 277 | } |
| 278 | res, err := s.opSyncUpstream(r.Context(), u, repo, r.FormValue("branch")) |
| 279 | if !s.uiOK(w, r, repoURL(repo), err) { |
| 280 | return |
| 281 | } |
| 282 | msg := "flash.synced" |
| 283 | if res.UpToDate { |
| 284 | msg = "flash.syncUpToDate" |
| 285 | } |
| 286 | s.redirect(w, r, repoURL(repo), s.tr(r, msg, res.Branch), "") |
| 287 | } |
| 288 | |
| 289 | func (s *Server) apiSyncUpstream(w http.ResponseWriter, r *http.Request) { |
| 290 | repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper) |
| 291 | if !ok { |
| 292 | return |
| 293 | } |
| 294 | var body struct { |
| 295 | Branch string `json:"branch"` |
| 296 | } |
| 297 | if err := readJSON(r, &body); err != nil { |
| 298 | s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) |
| 299 | return |
| 300 | } |
| 301 | res, err := s.opSyncUpstream(r.Context(), apiUser(r), repo, body.Branch) |
| 302 | if !s.apiOK(w, r, err) { |
| 303 | return |
| 304 | } |
| 305 | writeJSON(w, http.StatusOK, res) |
| 306 | } |
| 307 | |
| 308 | // forkMirror is de branch in upstream die een fork-branch spiegelt. |
| 309 | // Pipelines op forks/... krijgen nooit geheimen (zie runner). |
| 310 | func forkMirror(forkID int64, branch string) string { |
| 311 | return ci.ForkBranchPrefix + strconv.FormatInt(forkID, 10) + "/" + branch |
| 312 | } |
| 313 | |
| 314 | // opCreateForkMR maakt in upstream een MR met als bron een branch uit de |
| 315 | // fork. De bron wordt gespiegeld naar forks/<forkid>/<branch> in upstream |
| 316 | // (geen push-hook, dus geen push-pipeline). Vereist leesrechten op de fork |
| 317 | // en de rol die in upstream MR's mag maken. |
| 318 | func (s *Server) opCreateForkMR(ctx context.Context, user store.User, fork store.Repo, source, target, title, description string, draft bool) (store.Repo, store.MergeRequest, error) { |
| 319 | if !s.canReadRepo(ctx, user.ID, fork) { |
| 320 | return store.Repo{}, store.MergeRequest{}, fail(404, i18n.E("err.notFound")) |
| 321 | } |
| 322 | upID, _ := s.Store.ForkOf(ctx, fork.ID) |
| 323 | if upID == 0 { |
| 324 | return store.Repo{}, store.MergeRequest{}, fail(400, i18n.E("err.notFork")) |
| 325 | } |
| 326 | up, err := s.Store.RepoByID(ctx, upID) |
| 327 | if err != nil || !s.canReadRepo(ctx, user.ID, up) { |
| 328 | return store.Repo{}, store.MergeRequest{}, fail(403, i18n.E("err.upstreamNoAccess")) |
| 329 | } |
| 330 | role, err := s.Store.EffectiveRole(ctx, user.ID, up.ID) |
| 331 | if err != nil || !role.CanWriteCode() { |
| 332 | return store.Repo{}, store.MergeRequest{}, fail(403, i18n.E("err.upstreamMRRole")) |
| 333 | } |
| 334 | source = strings.TrimSpace(source) |
| 335 | target = strings.TrimSpace(target) |
| 336 | if target == "" { |
| 337 | target = up.DefaultBranch |
| 338 | } |
| 339 | if !safeBranchName(source) || !safeBranchName(target) { |
| 340 | return store.Repo{}, store.MergeRequest{}, fail(400, i18n.E("err.branches")) |
| 341 | } |
| 342 | dir := gitrepo.Dir(s.StoragePath(), fork.OwnerPath, fork.Name) |
| 343 | updir := gitrepo.Dir(s.StoragePath(), up.OwnerPath, up.Name) |
| 344 | if !shaLike(gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+source)) { |
| 345 | return store.Repo{}, store.MergeRequest{}, fail(404, i18n.E("err.upstreamBranch", source)) |
| 346 | } |
| 347 | if !shaLike(gitOne(ctx, s.Git, updir, "rev-parse", "--verify", "--quiet", "refs/heads/"+target)) { |
| 348 | return store.Repo{}, store.MergeRequest{}, fail(404, i18n.E("err.upstreamBranch", target)) |
| 349 | } |
| 350 | mirror := forkMirror(fork.ID, source) |
| 351 | if err := gitrepo.FetchBranch(ctx, s.Git, dir, updir, source, mirror); err != nil { |
| 352 | return store.Repo{}, store.MergeRequest{}, fail(500, err) |
| 353 | } |
| 354 | s.refsChanged(up) |
| 355 | mr, err := s.opCreateMR(ctx, user, up, title, description, mirror, target, draft) |
| 356 | if err != nil { |
| 357 | return store.Repo{}, store.MergeRequest{}, err |
| 358 | } |
| 359 | _ = s.Store.SetMRForkSource(ctx, mr.ID, fork.ID, source) |
| 360 | return up, mr, nil |
| 361 | } |
| 362 | |
| 363 | // refreshForkMRs: na een push in een fork de gespiegelde branches in |
| 364 | // upstream bijwerken; AfterPush van upstream start de MR-pipelines. |
| 365 | func (s *Server) refreshForkMRs(fork store.Repo, user store.User, branch string) { |
| 366 | ctx := context.Background() |
| 367 | list, err := s.Store.OpenForkMRs(ctx, fork.ID, branch) |
| 368 | if err != nil || len(list) == 0 { |
| 369 | return |
| 370 | } |
| 371 | dir := gitrepo.Dir(s.StoragePath(), fork.OwnerPath, fork.Name) |
| 372 | for _, m := range list { |
| 373 | up, err := s.Store.RepoByID(ctx, m.UpstreamID) |
| 374 | if err != nil || !s.canReadRepo(ctx, user.ID, up) { |
| 375 | continue |
| 376 | } |
| 377 | updir := gitrepo.Dir(s.StoragePath(), up.OwnerPath, up.Name) |
| 378 | _ = s.postReceive(ctx, up, user, updir, func() error { |
| 379 | return gitrepo.FetchBranch(ctx, s.Git, dir, updir, branch, m.Mirror) |
| 380 | }) |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | func (s *Server) forkMRPost(w http.ResponseWriter, r *http.Request) { |
| 385 | u, repo, _, ok := s.guard(w, r, access.RoleReadonly) |
| 386 | if !ok || !s.csrfOK(w, r) { |
| 387 | return |
| 388 | } |
| 389 | up, mr, err := s.opCreateForkMR(r.Context(), u, repo, r.FormValue("source"), r.FormValue("target"), r.FormValue("title"), r.FormValue("description"), r.FormValue("draft") == "1") |
| 390 | if !s.uiOK(w, r, repoURL(repo)+"/-/merge-requests/new", err) { |
| 391 | return |
| 392 | } |
| 393 | s.redirect(w, r, repoURL(up)+"/-/merge-requests/"+strconv.FormatInt(mr.Number, 10), s.tr(r, "flash.mrOpened"), "") |
| 394 | } |
| 395 | |
| 396 | func (s *Server) apiForkMR(w http.ResponseWriter, r *http.Request) { |
| 397 | repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) |
| 398 | if !ok { |
| 399 | return |
| 400 | } |
| 401 | var body struct { |
| 402 | Source string `json:"source_branch"` |
| 403 | Target string `json:"target_branch"` |
| 404 | Title string `json:"title"` |
| 405 | Description string `json:"description"` |
| 406 | Draft bool `json:"draft"` |
| 407 | } |
| 408 | if err := readJSON(r, &body); err != nil { |
| 409 | s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) |
| 410 | return |
| 411 | } |
| 412 | up, mr, err := s.opCreateForkMR(r.Context(), apiUser(r), repo, body.Source, body.Target, body.Title, body.Description, body.Draft) |
| 413 | if !s.apiOK(w, r, err) { |
| 414 | return |
| 415 | } |
| 416 | out := s.mrJSON(up, mr) |
| 417 | out["source_project"] = repo.FullPath() |
| 418 | out["source_project_branch"] = body.Source |
| 419 | writeJSON(w, http.StatusCreated, out) |
| 420 | } |