| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "os/exec" |
| 10 | "strings" |
| 11 | "time" |
| 12 | |
| 13 | "gitlab.com/Timfa/bluegit/internal/access" |
| 14 | "gitlab.com/Timfa/bluegit/internal/ci" |
| 15 | "gitlab.com/Timfa/bluegit/internal/gitrepo" |
| 16 | "gitlab.com/Timfa/bluegit/internal/i18n" |
| 17 | "gitlab.com/Timfa/bluegit/internal/ssrf" |
| 18 | "gitlab.com/Timfa/bluegit/internal/store" |
| 19 | "gitlab.com/Timfa/bluegit/internal/webhook" |
| 20 | ) |
| 21 | |
| 22 | // postReceive is de enige route voor een ref-wijziging die BlueGit zelf maakt: |
| 23 | // de Pipeline Editor, suggesties, een merge en een tag. mutate schrijft de refs. |
| 24 | // Daarna geldt hetzelfde als na een git push: pipeline, webhook en activity. |
| 25 | func (s *Server) postReceive(ctx context.Context, repo store.Repo, user store.User, dir string, mutate func() error) error { |
| 26 | before, err := gitrepo.Refs(ctx, s.Git, dir) |
| 27 | if err != nil { |
| 28 | before = map[string]string{} |
| 29 | } |
| 30 | if err := mutate(); err != nil { |
| 31 | return err |
| 32 | } |
| 33 | after, err := gitrepo.Refs(ctx, s.Git, dir) |
| 34 | if err != nil { |
| 35 | if s.Log != nil { |
| 36 | s.Log.Error("post-receive", "err", err) |
| 37 | } |
| 38 | return nil |
| 39 | } |
| 40 | s.AfterPush(repo, user, before, after) |
| 41 | return nil |
| 42 | } |
| 43 | |
| 44 | // AfterPush behandelt elke nieuwe ref zoals een git push. |
| 45 | // git http, SSH en postReceive zijn de enige aanroepers. |
| 46 | func (s *Server) AfterPush(repo store.Repo, user store.User, before, after map[string]string) { |
| 47 | s.refsChanged(repo) |
| 48 | for ref, sha := range after { |
| 49 | if b, ok := strings.CutPrefix(ref, "refs/heads/"); ok && before[ref] != sha && !isZero(sha) && s.Store != nil { |
| 50 | s.refreshForkMRs(repo, user, b) |
| 51 | } |
| 52 | } |
| 53 | if s.Store != nil && refsMoved(before, after) { |
| 54 | _ = s.Store.TouchPushed(context.Background(), repo.ID, time.Now()) |
| 55 | } |
| 56 | if after == nil { |
| 57 | return |
| 58 | } |
| 59 | actor := user.Username |
| 60 | var drop []mergedSource |
| 61 | for ref, sha := range after { |
| 62 | if before[ref] == sha || isZero(sha) { |
| 63 | continue |
| 64 | } |
| 65 | commit := s.peeled(repo, sha) |
| 66 | if strings.HasPrefix(ref, "refs/tags/") { |
| 67 | s.startPipeline(context.Background(), repo, commit, ref, actor, "push", before[ref], nil) |
| 68 | s.recordContribution(user.ID, repo.ID, "tag", ref, time.Now().UTC()) |
| 69 | s.pushHook(repo, actor, ref, before[ref], sha) |
| 70 | continue |
| 71 | } |
| 72 | branch, ok := gitrepo.BranchOfRef(ref) |
| 73 | if !ok { |
| 74 | continue |
| 75 | } |
| 76 | s.recordPushContributions(repo, user, map[string]string{ref: before[ref]}, map[string]string{ref: sha}) |
| 77 | s.startPipeline(context.Background(), repo, commit, ref, actor, "push", before[ref], nil) |
| 78 | s.startMergeRequestPipelines(context.Background(), repo, commit, branch, actor, before[ref]) |
| 79 | s.recordMRPushes(repo, user, branch, before[ref], sha) |
| 80 | drop = append(drop, s.markContainedMRs(repo, user, branch, sha)...) |
| 81 | s.rerunMergeRequestsOnTarget(context.Background(), repo, branch, actor) |
| 82 | s.pushHook(repo, actor, ref, before[ref], sha) |
| 83 | if branch == repo.DefaultBranch { |
| 84 | s.closeIssuesOnPush(repo, user, before[ref], sha) |
| 85 | } |
| 86 | } |
| 87 | // Een ref die in before staat en in after weg is, is verwijderd. |
| 88 | // Daar hoort een push-webhook bij, zonder pipeline of activity. |
| 89 | for ref, old := range before { |
| 90 | if sha, ok := after[ref]; ok && !isZero(sha) { |
| 91 | continue |
| 92 | } |
| 93 | if isZero(old) { |
| 94 | continue |
| 95 | } |
| 96 | s.pushHook(repo, actor, ref, old, strings.Repeat("0", 40)) |
| 97 | } |
| 98 | // Pas na de push zelf de bronbranch weghalen. Doen we dat midden in de |
| 99 | // lus, dan kan dezelfde push de tak nog als nieuwe ref behandelen. |
| 100 | s.dropMergedSources(repo, drop) |
| 101 | } |
| 102 | |
| 103 | func (s *Server) pushHook(repo store.Repo, actor, ref, before, after string) { |
| 104 | if isZero(before) { |
| 105 | before = strings.Repeat("0", 40) |
| 106 | } |
| 107 | commit := after |
| 108 | if isZero(commit) { |
| 109 | commit = "" |
| 110 | } |
| 111 | name := refName(ref) |
| 112 | s.Dispatch(repo.ID, webhook.Event{ |
| 113 | Type: webhook.EventPush, |
| 114 | Project: repo.FullPath(), |
| 115 | Branch: name, |
| 116 | Ref: ref, |
| 117 | Before: before, |
| 118 | After: after, |
| 119 | Commit: commit, |
| 120 | Summary: i18n.T(i18n.EN, "hook.push", actor, name, repo.FullPath()), |
| 121 | URL: strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath(), |
| 122 | Actor: actor, |
| 123 | }) |
| 124 | } |
| 125 | |
| 126 | func (s *Server) peeled(repo store.Repo, sha string) string { |
| 127 | if s.StoragePath() == "" || sha == "" { |
| 128 | return sha |
| 129 | } |
| 130 | dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name) |
| 131 | if commit := gitOne(context.Background(), s.Git, dir, "rev-parse", "--verify", sha+"^{commit}"); commit != "" { |
| 132 | return commit |
| 133 | } |
| 134 | return sha |
| 135 | } |
| 136 | |
| 137 | func isZero(sha string) bool { |
| 138 | return strings.Trim(sha, "0") == "" |
| 139 | } |
| 140 | |
| 141 | func (s *Server) startPipeline(ctx context.Context, repo store.Repo, sha, ref, actor, source, before string, mr *ci.MRInfo) int64 { |
| 142 | if !s.Cfg.CI.Enabled || s.StoragePath() == "" { |
| 143 | return 0 |
| 144 | } |
| 145 | title, jobs, broken := s.planPipeline(ctx, repo, sha, ref, source, before, mr) |
| 146 | mrID, target := int64(0), "" |
| 147 | if mr != nil { |
| 148 | mrID, target = mr.ID, mr.TargetSHA |
| 149 | } |
| 150 | if broken != nil { |
| 151 | id, created, err := s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, source, broken.Error(), mrID, target) |
| 152 | if err != nil && s.Log != nil { |
| 153 | s.Log.Error("pipeline", "err", err) |
| 154 | } |
| 155 | if created && id != 0 { |
| 156 | s.cancelOlder(ctx, repo.ID, ref, id) |
| 157 | } |
| 158 | return id |
| 159 | } |
| 160 | if len(jobs) == 0 { |
| 161 | return 0 |
| 162 | } |
| 163 | id, created, err := s.Store.OpenPipeline(ctx, repo.ID, sha, ref, source, actor, title, target, mrID, jobs) |
| 164 | if err != nil { |
| 165 | if s.Log != nil { |
| 166 | s.Log.Error("pipeline", "err", err) |
| 167 | } |
| 168 | return 0 |
| 169 | } |
| 170 | if created { |
| 171 | s.cancelOlder(ctx, repo.ID, ref, id) |
| 172 | s.expireSuperseded(ctx, repo.ID, ref, id) |
| 173 | } |
| 174 | return id |
| 175 | } |
| 176 | |
| 177 | func (s *Server) cancelOlder(ctx context.Context, repoID int64, ref string, keep int64) { |
| 178 | running, pipes, err := s.Store.CancelInterruptible(ctx, repoID, ref, keep) |
| 179 | if err != nil { |
| 180 | if s.Log != nil { |
| 181 | s.Log.Error("interruptible", "err", err) |
| 182 | } |
| 183 | return |
| 184 | } |
| 185 | if s.Runner != nil { |
| 186 | s.Runner.Interrupt(running) |
| 187 | } |
| 188 | for _, id := range pipes { |
| 189 | if _, err := s.Store.RefreshPipelineStatus(ctx, id); err != nil && s.Log != nil { |
| 190 | s.Log.Error("pipelinestatus", "err", err) |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | func gitOne(ctx context.Context, gitBin, dir string, args ...string) string { |
| 196 | out, err := exec.CommandContext(ctx, gitBin, append([]string{"-C", dir}, args...)...).Output() |
| 197 | if err != nil { |
| 198 | return "" |
| 199 | } |
| 200 | return strings.TrimSpace(string(out)) |
| 201 | } |
| 202 | |
| 203 | func gitLines(ctx context.Context, gitBin, dir string, args ...string) []string { |
| 204 | out := gitOne(ctx, gitBin, dir, args...) |
| 205 | if out == "" { |
| 206 | return []string{} |
| 207 | } |
| 208 | return strings.Split(out, "\n") |
| 209 | } |
| 210 | |
| 211 | func changedFiles(ctx context.Context, gitBin, dir, sha, before string, all []string) []string { |
| 212 | if before == "" || strings.Trim(before, "0") == "" { |
| 213 | parent := gitOne(ctx, gitBin, dir, "rev-parse", "--verify", sha+"^") |
| 214 | if parent == "" { |
| 215 | return all |
| 216 | } |
| 217 | before = parent |
| 218 | } |
| 219 | out, err := exec.CommandContext(ctx, gitBin, "-C", dir, "diff", "--name-only", before, sha).Output() |
| 220 | if err != nil { |
| 221 | return nil |
| 222 | } |
| 223 | text := strings.TrimSpace(string(out)) |
| 224 | if text == "" { |
| 225 | return []string{} |
| 226 | } |
| 227 | return strings.Split(text, "\n") |
| 228 | } |
| 229 | |
| 230 | func (s *Server) Dispatch(repoID int64, ev webhook.Event) { |
| 231 | ctx := context.Background() |
| 232 | repo, err := s.Store.RepoByID(ctx, repoID) |
| 233 | if err != nil { |
| 234 | return |
| 235 | } |
| 236 | if ev.Project == "" { |
| 237 | ev.Project = repo.FullPath() |
| 238 | } |
| 239 | if !strings.HasPrefix(ev.URL, "http") { |
| 240 | ev.URL = strings.TrimRight(s.Cfg.BaseURL, "/") + ev.URL |
| 241 | } |
| 242 | if repo.OwnerKind == "group" { |
| 243 | if g, err := s.Store.GroupByID(ctx, repo.OwnerID); err == nil { |
| 244 | ev.Group = g.Path |
| 245 | } |
| 246 | } |
| 247 | ev = s.enrichEvent(ctx, repo, ev) |
| 248 | patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID) |
| 249 | protected := access.BranchProtected(patterns, ev.Branch) |
| 250 | s.deliver(ctx, "repo", repo.ID, ev, protected, repo) |
| 251 | if repo.OwnerKind == "group" { |
| 252 | s.deliver(ctx, "group", repo.OwnerID, ev, protected, repo) |
| 253 | } |
| 254 | if ev.Type == webhook.EventPipelineFailure { |
| 255 | s.queueFailureMail(repo, ev) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | func (s *Server) deliver(ctx context.Context, kind string, scopeID int64, ev webhook.Event, refProtected bool, repo store.Repo) { |
| 260 | hooks, err := s.Store.ListWebhooks(ctx, kind, scopeID) |
| 261 | if err != nil { |
| 262 | return |
| 263 | } |
| 264 | secrets, err := s.hookSecrets(ctx, kind, scopeID, refProtected, repo) |
| 265 | if err != nil { |
| 266 | s.Log.Error("geheimen voor webhook", "err", err) |
| 267 | return |
| 268 | } |
| 269 | client := ssrf.NewClient(10 * time.Second) |
| 270 | for _, h := range hooks { |
| 271 | if !h.Active { |
| 272 | continue |
| 273 | } |
| 274 | ok, err := webhook.Allows(webhook.Hook{Preset: h.Preset, Events: h.Events, BranchFilter: h.BranchFilter}, ev) |
| 275 | if err != nil { |
| 276 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 277 | continue |
| 278 | } |
| 279 | if !ok { |
| 280 | continue |
| 281 | } |
| 282 | rawURL, err := webhook.Expand(h.URLTemplate, ev, secrets) |
| 283 | if err != nil { |
| 284 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 285 | continue |
| 286 | } |
| 287 | target, err := urlParse(rawURL) |
| 288 | if err != nil { |
| 289 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 290 | continue |
| 291 | } |
| 292 | if err := ssrf.ValidateURL(target); err != nil { |
| 293 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 294 | continue |
| 295 | } |
| 296 | headers, err := webhook.RenderHeaders(h.Preset, h.Headers, ev, secrets) |
| 297 | if err != nil { |
| 298 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 299 | continue |
| 300 | } |
| 301 | body, err := webhook.RenderBody(h.BodyTemplate, ev, secrets) |
| 302 | if err != nil { |
| 303 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 304 | continue |
| 305 | } |
| 306 | if s.hookSink != nil { |
| 307 | s.hookSink(body) |
| 308 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, "") |
| 309 | continue |
| 310 | } |
| 311 | method := h.Method |
| 312 | if method == "" { |
| 313 | method = http.MethodPost |
| 314 | } |
| 315 | req, err := http.NewRequestWithContext(ctx, method, rawURL, bytes.NewReader(body)) |
| 316 | if err != nil { |
| 317 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 318 | continue |
| 319 | } |
| 320 | for k, v := range headers { |
| 321 | if strings.ContainsAny(k, "\r\n") || strings.ContainsAny(v, "\r\n") { |
| 322 | continue |
| 323 | } |
| 324 | req.Header.Set(k, v) |
| 325 | } |
| 326 | res, err := client.Do(req) |
| 327 | if err != nil { |
| 328 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 329 | continue |
| 330 | } |
| 331 | _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20)) |
| 332 | res.Body.Close() |
| 333 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, res.StatusCode, "") |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | func urlParse(raw string) (*url.URL, error) { |
| 338 | u, err := url.Parse(raw) |
| 339 | if err != nil { |
| 340 | return nil, i18n.E("err.whURL") |
| 341 | } |
| 342 | return u, nil |
| 343 | } |
| 344 | |
| 345 | // markContainedMRs zet open merge requests op merged wanneer de bron-head |
| 346 | // al in de zojuist gepushte doelbranch zit. Dat is dezelfde regel als GitLab |
| 347 | // na een merge die buiten de knop om is gepusht. |
| 348 | func (s *Server) markContainedMRs(repo store.Repo, user store.User, branch, sha string) []mergedSource { |
| 349 | if s.Store == nil || s.StoragePath() == "" || branch == "" || isZero(sha) { |
| 350 | return nil |
| 351 | } |
| 352 | ctx := context.Background() |
| 353 | mrs, err := s.Store.OpenMergeRequestsByTarget(ctx, repo.ID, branch) |
| 354 | if err != nil { |
| 355 | return nil |
| 356 | } |
| 357 | dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name) |
| 358 | var drop []mergedSource |
| 359 | for _, mr := range mrs { |
| 360 | if item, ok := s.markIfContained(ctx, repo, user, dir, mr, sha, true); ok { |
| 361 | drop = append(drop, item) |
| 362 | } |
| 363 | } |
| 364 | return drop |
| 365 | } |
| 366 | |
| 367 | // absorbMergedMRs doet dezelfde controle bij het openen van een pagina, |
| 368 | // zodat een merge die al gepusht was voordat deze code draaide alsnog merged wordt. |
| 369 | func (s *Server) absorbMergedMRs(ctx context.Context, repo store.Repo) { |
| 370 | if s.Store == nil || s.StoragePath() == "" { |
| 371 | return |
| 372 | } |
| 373 | mrs, err := s.Store.ListMergeRequests(ctx, repo.ID) |
| 374 | if err != nil { |
| 375 | return |
| 376 | } |
| 377 | dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name) |
| 378 | for _, mr := range mrs { |
| 379 | if mr.Status != "open" { |
| 380 | continue |
| 381 | } |
| 382 | s.markIfContained(ctx, repo, store.User{}, dir, mr, "", false) |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | func (s *Server) markIfContained(ctx context.Context, repo store.Repo, user store.User, dir string, mr store.MergeRequest, targetSHA string, deferDrop bool) (mergedSource, bool) { |
| 387 | if targetSHA == "" { |
| 388 | targetSHA = gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "refs/heads/"+mr.TargetBranch) |
| 389 | } |
| 390 | src := gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "refs/heads/"+mr.SourceBranch) |
| 391 | if src == "" || targetSHA == "" || !gitrepo.IsAncestor(ctx, s.Git, dir, src, targetSHA) { |
| 392 | return mergedSource{}, false |
| 393 | } |
| 394 | if user.ID == 0 { |
| 395 | if pushers, err := s.Store.PushersBySHA(ctx, repo.ID, []string{targetSHA}); err == nil { |
| 396 | if p, ok := pushers[targetSHA]; ok && p.UserID != 0 { |
| 397 | user = store.User{ID: p.UserID, Username: p.Username} |
| 398 | } |
| 399 | } |
| 400 | } |
| 401 | if err := s.Store.SetMergeRequestStatus(ctx, mr.ID, "merged"); err != nil { |
| 402 | return mergedSource{}, false |
| 403 | } |
| 404 | body := "" |
| 405 | if shaLike(targetSHA) { |
| 406 | body = targetSHA |
| 407 | } |
| 408 | _ = s.Store.AddMREvent(ctx, repo.ID, mr.ID, user.ID, "merged", body) |
| 409 | mr.Status = "merged" |
| 410 | s.mrHook(repo, mr, user.Username, "merged", "") |
| 411 | s.closeMergedMR(ctx, repo, user, mr) |
| 412 | plan, ok := s.mergedSourcePlan(ctx, repo, user, mr) |
| 413 | if !ok { |
| 414 | return mergedSource{}, false |
| 415 | } |
| 416 | if _, merging := s.mergingMR.Load(mr.ID); merging { |
| 417 | return mergedSource{}, false |
| 418 | } |
| 419 | if deferDrop { |
| 420 | return plan, true |
| 421 | } |
| 422 | s.deleteMergedSource(ctx, plan.user, plan.role, repo, plan.name) |
| 423 | return mergedSource{}, false |
| 424 | } |
| 425 | |
| 426 | func (s *Server) closeMergedMR(ctx context.Context, repo store.Repo, user store.User, mr store.MergeRequest) { |
| 427 | texts := []string{mr.Description} |
| 428 | if s.StoragePath() != "" { |
| 429 | dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name) |
| 430 | commits, err := gitrepo.RangeLog(ctx, s.Git, dir, mr.TargetBranch, mr.SourceBranch) |
| 431 | if err == nil { |
| 432 | for i, c := range commits { |
| 433 | if i >= 50 { |
| 434 | break |
| 435 | } |
| 436 | texts = append(texts, commitText(c)) |
| 437 | } |
| 438 | } |
| 439 | } |
| 440 | s.closeIssueNumbers(ctx, repo, user, closingNumbers(texts...)) |
| 441 | } |
| 442 | |
| 443 | func gitSHA(r *http.Request, gitBin, dir, rev string) (string, error) { |
| 444 | out, err := exec.CommandContext(r.Context(), gitBin, "-C", dir, "rev-parse", "--verify", rev+"^{commit}").Output() |
| 445 | if err != nil { |
| 446 | return "", err |
| 447 | } |
| 448 | return strings.TrimSpace(string(out)), nil |
| 449 | } |
| 450 | |
| 451 | // refsMoved meldt of een push werkelijk een ref veranderde. |
| 452 | func refsMoved(before, after map[string]string) bool { |
| 453 | for ref, sha := range after { |
| 454 | if before[ref] != sha { |
| 455 | return true |
| 456 | } |
| 457 | } |
| 458 | for ref := range before { |
| 459 | if _, ok := after[ref]; !ok && after != nil { |
| 460 | return true |
| 461 | } |
| 462 | } |
| 463 | return false |
| 464 | } |