| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "os" |
| 8 | "strings" |
| 9 | "syscall" |
| 10 | |
| 11 | "gitlab.com/Timfa/bluegit/internal/access" |
| 12 | "gitlab.com/Timfa/bluegit/internal/gitrepo" |
| 13 | "gitlab.com/Timfa/bluegit/internal/i18n" |
| 14 | "gitlab.com/Timfa/bluegit/internal/state" |
| 15 | "gitlab.com/Timfa/bluegit/internal/store" |
| 16 | ) |
| 17 | |
| 18 | // forkReserveBytes: zoveel moet er naast de upstream-grootte vrij blijven. |
| 19 | const forkReserveBytes = 512 << 20 |
| 20 | |
| 21 | // canReadRepo: openbaar, of de gebruiker heeft minstens leesrechten. |
| 22 | func (s *Server) canReadRepo(ctx context.Context, userID int64, repo store.Repo) bool { |
| 23 | if repo.Visibility == "public" { |
| 24 | return true |
| 25 | } |
| 26 | if userID == 0 { |
| 27 | return false |
| 28 | } |
| 29 | role, err := s.Store.EffectiveRole(ctx, userID, repo.ID) |
| 30 | return err == nil && role.CanRead() |
| 31 | } |
| 32 | |
| 33 | // ForkInfo is wat de repo-pagina over de fork-relatie toont. |
| 34 | type ForkInfo struct { |
| 35 | IsFork bool |
| 36 | Upstream *store.Repo // nil als de kijker upstream niet mag zien |
| 37 | Forks int // zichtbare forks van deze repo |
| 38 | } |
| 39 | |
| 40 | func (s *Server) forkInfo(ctx context.Context, userID int64, repo store.Repo) ForkInfo { |
| 41 | var fi ForkInfo |
| 42 | if up, _ := s.Store.ForkOf(ctx, repo.ID); up != 0 { |
| 43 | fi.IsFork = true |
| 44 | if u, err := s.Store.RepoByID(ctx, up); err == nil && s.canReadRepo(ctx, userID, u) { |
| 45 | fi.Upstream = &u |
| 46 | } |
| 47 | } |
| 48 | fi.Forks = len(s.visibleForks(ctx, userID, repo)) |
| 49 | return fi |
| 50 | } |
| 51 | |
| 52 | func (s *Server) visibleForks(ctx context.Context, userID int64, repo store.Repo) []store.Repo { |
| 53 | ids, _ := s.Store.ForkIDs(ctx, repo.ID) |
| 54 | if len(ids) == 0 { |
| 55 | return nil |
| 56 | } |
| 57 | list, _ := s.Store.ReposByIDs(ctx, ids) |
| 58 | var out []store.Repo |
| 59 | for _, f := range list { |
| 60 | if s.canReadRepo(ctx, userID, f) { |
| 61 | out = append(out, f) |
| 62 | } |
| 63 | } |
| 64 | return out |
| 65 | } |
| 66 | |
| 67 | // ForkTarget is een plek waar de gebruiker een fork mag maken. |
| 68 | type ForkTarget struct { |
| 69 | Value string // "" = eigen account, anders groepspad |
| 70 | Label string |
| 71 | } |
| 72 | |
| 73 | func (s *Server) forkTargets(ctx context.Context, user store.User) []ForkTarget { |
| 74 | out := []ForkTarget{{Value: "", Label: user.Username}} |
| 75 | groups, _ := s.Store.ListGroups(ctx, user.ID) |
| 76 | for _, g := range groups { |
| 77 | if role, err := s.Store.GroupRole(ctx, g.ID, user.ID); err == nil && role.CanWriteCode() { |
| 78 | out = append(out, ForkTarget{Value: g.Path, Label: g.Path}) |
| 79 | } |
| 80 | } |
| 81 | return out |
| 82 | } |
| 83 | |
| 84 | // opForkRepo maakt een fork met alle branches en tags. Doel: eigen account |
| 85 | // of een groep waar de gebruiker minstens developer is. Een fork van een |
| 86 | // privé repo is privé. |
| 87 | func (s *Server) opForkRepo(ctx context.Context, user store.User, upstream store.Repo, groupPath, rawName string) (store.Repo, error) { |
| 88 | if s.StoragePath() == "" { |
| 89 | return store.Repo{}, fail(503, i18n.E("err.noStorage")) |
| 90 | } |
| 91 | if !s.canReadRepo(ctx, user.ID, upstream) { |
| 92 | return store.Repo{}, fail(404, i18n.E("err.notFound")) |
| 93 | } |
| 94 | if strings.TrimSpace(rawName) == "" { |
| 95 | rawName = upstream.Name |
| 96 | } |
| 97 | name, err := slugKind("repo", rawName) |
| 98 | if err != nil { |
| 99 | return store.Repo{}, fail(400, err) |
| 100 | } |
| 101 | ownerKind, ownerID, ownerPath := "user", user.ID, user.Username |
| 102 | if gp := strings.TrimSpace(groupPath); gp != "" { |
| 103 | g, err := s.Store.GroupByPath(ctx, gp) |
| 104 | if err != nil { |
| 105 | return store.Repo{}, fail(404, i18n.E("err.groupMissing")) |
| 106 | } |
| 107 | role, err := s.Store.GroupRole(ctx, g.ID, user.ID) |
| 108 | if err != nil || !role.AtLeast(access.RoleDeveloper) { |
| 109 | return store.Repo{}, fail(403, i18n.E("err.forbidden")) |
| 110 | } |
| 111 | ownerKind, ownerID, ownerPath = "group", g.ID, g.Path |
| 112 | } |
| 113 | if _, err := s.Store.RepoByPath(ctx, ownerPath, name); err == nil { |
| 114 | return store.Repo{}, fail(409, i18n.E("err.forkExists", ownerPath+"/"+name)) |
| 115 | } |
| 116 | src := gitrepo.Dir(s.StoragePath(), upstream.OwnerPath, upstream.Name) |
| 117 | if size, err := state.DirSize(ctx, src); err == nil { |
| 118 | var st syscall.Statfs_t |
| 119 | if syscall.Statfs(s.StoragePath(), &st) == nil && st.Bavail*uint64(st.Bsize) < size+forkReserveBytes { |
| 120 | return store.Repo{}, fail(507, i18n.E("err.forkDisk")) |
| 121 | } |
| 122 | } |
| 123 | repo, err := s.Store.CreateRepo(ctx, ownerKind, ownerID, name, upstream.Description, upstream.DefaultBranch, upstream.Visibility) |
| 124 | if err != nil { |
| 125 | return store.Repo{}, fail(400, err) |
| 126 | } |
| 127 | dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name) |
| 128 | if err := gitrepo.Fork(s.Git, src, dir, s.HookBin); err != nil { |
| 129 | _ = s.Store.DeleteRepo(ctx, repo.ID) |
| 130 | _ = os.RemoveAll(dir) |
| 131 | return store.Repo{}, fail(500, i18n.E("err.forkGit", err.Error())) |
| 132 | } |
| 133 | if err := s.Store.SetForkOf(ctx, repo.ID, upstream.ID); err != nil { |
| 134 | return store.Repo{}, fail(500, err) |
| 135 | } |
| 136 | s.syncRepos(ctx, []int64{repo.ID}) |
| 137 | return repo, nil |
| 138 | } |
| 139 | |
| 140 | // forkMustStayPrivate: een fork van een privé upstream mag niet openbaar. |
| 141 | func (s *Server) forkMustStayPrivate(ctx context.Context, repo store.Repo) bool { |
| 142 | up, _ := s.Store.ForkOf(ctx, repo.ID) |
| 143 | if up == 0 { |
| 144 | return false |
| 145 | } |
| 146 | u, err := s.Store.RepoByID(ctx, up) |
| 147 | return err == nil && u.Visibility != "public" |
| 148 | } |
| 149 | |
| 150 | func (s *Server) forkPost(w http.ResponseWriter, r *http.Request) { |
| 151 | u, repo, _, ok := s.guard(w, r, access.RoleReadonly) |
| 152 | if !ok || !s.csrfOK(w, r) { |
| 153 | return |
| 154 | } |
| 155 | if u.ID == 0 { |
| 156 | http.Redirect(w, r, "/login", http.StatusSeeOther) |
| 157 | return |
| 158 | } |
| 159 | fork, err := s.opForkRepo(r.Context(), u, repo, r.FormValue("namespace"), r.FormValue("name")) |
| 160 | if !s.uiOK(w, r, repoURL(repo), err) { |
| 161 | return |
| 162 | } |
| 163 | s.redirect(w, r, repoURL(fork), s.tr(r, "flash.forked"), "") |
| 164 | } |
| 165 | |
| 166 | func (s *Server) forksPage(w http.ResponseWriter, r *http.Request) { |
| 167 | u, repo, role, ok := s.guard(w, r, access.RoleReadonly) |
| 168 | if !ok { |
| 169 | return |
| 170 | } |
| 171 | v := s.repoView(w, r, repo, role, s.tr(r, "fork.listTitle")) |
| 172 | v.ForkList = s.visibleForks(r.Context(), u.ID, repo) |
| 173 | v.Fork = s.forkInfo(r.Context(), u.ID, repo) |
| 174 | s.render(w, "forks", v) |
| 175 | } |
| 176 | |
| 177 | func forkJSON(fork store.Repo, upstream store.Repo) map[string]any { |
| 178 | out := projectJSON(fork) |
| 179 | out["forked_from"] = upstream.FullPath() |
| 180 | return out |
| 181 | } |
| 182 | |
| 183 | func (s *Server) apiForkProject(w http.ResponseWriter, r *http.Request) { |
| 184 | repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) |
| 185 | if !ok { |
| 186 | return |
| 187 | } |
| 188 | var body struct { |
| 189 | Namespace string `json:"namespace"` |
| 190 | Name string `json:"name"` |
| 191 | } |
| 192 | if err := readJSON(r, &body); err != nil { |
| 193 | s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) |
| 194 | return |
| 195 | } |
| 196 | fork, err := s.opForkRepo(r.Context(), apiUser(r), repo, body.Namespace, body.Name) |
| 197 | if !s.apiOK(w, r, err) { |
| 198 | return |
| 199 | } |
| 200 | writeJSON(w, http.StatusCreated, forkJSON(fork, repo)) |
| 201 | } |
| 202 | |
| 203 | func (s *Server) apiListForks(w http.ResponseWriter, r *http.Request) { |
| 204 | repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) |
| 205 | if !ok { |
| 206 | return |
| 207 | } |
| 208 | s.writeProjects(w, r, s.visibleForks(r.Context(), apiUser(r).ID, repo)) |
| 209 | } |
| 210 | |
| 211 | // SyncResult is de uitkomst van een upstream-synchronisatie. |
| 212 | type SyncResult struct { |
| 213 | Branch string `json:"branch"` |
| 214 | Before string `json:"before"` |
| 215 | After string `json:"after"` |
| 216 | UpToDate bool `json:"up_to_date"` |
| 217 | } |
| 218 | |
| 219 | // opSyncUpstream zet branch (standaard de standaardbranch) van upstream |
| 220 | // fast-forward door naar de fork. Geen force: bij afwijking 409. Vereist |
| 221 | // schrijfrechten op de fork en leesrechten op upstream; zonder leesrechten |
| 222 | // noemt de fout de upstream niet. |
| 223 | func (s *Server) opSyncUpstream(ctx context.Context, user store.User, fork store.Repo, branch string) (SyncResult, error) { |
| 224 | role, err := s.Store.EffectiveRole(ctx, user.ID, fork.ID) |
| 225 | if err != nil || !role.CanWriteCode() { |
| 226 | return SyncResult{}, fail(403, i18n.E("err.forbidden")) |
| 227 | } |
| 228 | upID, _ := s.Store.ForkOf(ctx, fork.ID) |
| 229 | if upID == 0 { |
| 230 | return SyncResult{}, fail(400, i18n.E("err.notFork")) |
| 231 | } |
| 232 | up, err := s.Store.RepoByID(ctx, upID) |
| 233 | if err != nil || !s.canReadRepo(ctx, user.ID, up) { |
| 234 | return SyncResult{}, fail(403, i18n.E("err.upstreamNoAccess")) |
| 235 | } |
| 236 | branch = strings.TrimSpace(branch) |
| 237 | if branch == "" { |
| 238 | branch = fork.DefaultBranch |
| 239 | } |
| 240 | if !safeBranchName(branch) { |
| 241 | return SyncResult{}, fail(400, i18n.E("err.upstreamBranch", branch)) |
| 242 | } |
| 243 | updir := gitrepo.Dir(s.StoragePath(), up.OwnerPath, up.Name) |
| 244 | dir := gitrepo.Dir(s.StoragePath(), fork.OwnerPath, fork.Name) |
| 245 | upSHA := gitOne(ctx, s.Git, updir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch) |
| 246 | if !shaLike(upSHA) { |
| 247 | return SyncResult{}, fail(404, i18n.E("err.upstreamBranch", branch)) |
| 248 | } |
| 249 | res := SyncResult{Branch: branch, Before: gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch)} |
| 250 | if res.Before == upSHA { |
| 251 | res.After, res.UpToDate = upSHA, true |
| 252 | return res, nil |
| 253 | } |
| 254 | patterns, _ := s.Store.ProtectedPatterns(ctx, fork.ID) |
| 255 | env := append(os.Environ(), gitrepo.PushEnv(role, patterns, nil)...) |
| 256 | if err := s.postReceive(ctx, fork, user, dir, func() error { |
| 257 | return gitrepo.PushBranch(ctx, s.Git, updir, dir, branch, env) |
| 258 | }); err != nil { |
| 259 | if errors.Is(err, gitrepo.ErrNotFastForward) { |
| 260 | return res, fail(409, i18n.E("err.syncNotFF", branch)) |
| 261 | } |
| 262 | return res, fail(400, err) |
| 263 | } |
| 264 | res.After = gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch) |
| 265 | return res, nil |
| 266 | } |
| 267 | |
| 268 | func safeBranchName(b string) bool { |
| 269 | return b != "" && !strings.HasPrefix(b, "-") && !strings.Contains(b, "..") && !strings.ContainsAny(b, " ~^:?*[\\") |
| 270 | } |
| 271 | |
| 272 | func (s *Server) syncUpstreamPost(w http.ResponseWriter, r *http.Request) { |
| 273 | u, repo, _, ok := s.guard(w, r, access.RoleDeveloper) |
| 274 | if !ok || !s.csrfOK(w, r) { |
| 275 | return |
| 276 | } |
| 277 | res, err := s.opSyncUpstream(r.Context(), u, repo, r.FormValue("branch")) |
| 278 | if !s.uiOK(w, r, repoURL(repo), err) { |
| 279 | return |
| 280 | } |
| 281 | msg := "flash.synced" |
| 282 | if res.UpToDate { |
| 283 | msg = "flash.syncUpToDate" |
| 284 | } |
| 285 | s.redirect(w, r, repoURL(repo), s.tr(r, msg, res.Branch), "") |
| 286 | } |
| 287 | |
| 288 | func (s *Server) apiSyncUpstream(w http.ResponseWriter, r *http.Request) { |
| 289 | repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper) |
| 290 | if !ok { |
| 291 | return |
| 292 | } |
| 293 | var body struct { |
| 294 | Branch string `json:"branch"` |
| 295 | } |
| 296 | if err := readJSON(r, &body); err != nil { |
| 297 | s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) |
| 298 | return |
| 299 | } |
| 300 | res, err := s.opSyncUpstream(r.Context(), apiUser(r), repo, body.Branch) |
| 301 | if !s.apiOK(w, r, err) { |
| 302 | return |
| 303 | } |
| 304 | writeJSON(w, http.StatusOK, res) |
| 305 | } |