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