| 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 | func (s *Server) AfterPush(repo store.Repo, user store.User, before, after map[string]string) { |
| 23 | if after == nil { |
| 24 | return |
| 25 | } |
| 26 | actor := user.Username |
| 27 | for ref, sha := range after { |
| 28 | if before[ref] == sha { |
| 29 | continue |
| 30 | } |
| 31 | if isZero(sha) { |
| 32 | continue |
| 33 | } |
| 34 | if strings.HasPrefix(ref, "refs/tags/") { |
| 35 | s.startPipeline(context.Background(), repo, sha, ref, actor, "push", before[ref]) |
| 36 | continue |
| 37 | } |
| 38 | branch, ok := gitrepo.BranchOfRef(ref) |
| 39 | if !ok { |
| 40 | continue |
| 41 | } |
| 42 | s.recordPushContributions(repo, user, map[string]string{ref: before[ref]}, map[string]string{ref: sha}) |
| 43 | s.startPipeline(context.Background(), repo, sha, ref, actor, "push", before[ref]) |
| 44 | web := strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath() |
| 45 | s.Dispatch(repo.ID, webhook.Event{ |
| 46 | Type: webhook.EventPush, |
| 47 | Project: repo.FullPath(), |
| 48 | Branch: branch, |
| 49 | Commit: sha, |
| 50 | Summary: i18n.T(i18n.EN, "hook.push", actor, branch, repo.FullPath()), |
| 51 | URL: web, |
| 52 | Actor: actor, |
| 53 | }) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | func isZero(sha string) bool { |
| 58 | return strings.Trim(sha, "0") == "" |
| 59 | } |
| 60 | |
| 61 | func (s *Server) startPipeline(ctx context.Context, repo store.Repo, sha, ref, actor, source, before string) { |
| 62 | if !s.Cfg.CI.Enabled || s.StoragePath() == "" { |
| 63 | return |
| 64 | } |
| 65 | dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name) |
| 66 | raw, err := exec.CommandContext(ctx, s.Git, "-C", dir, "show", sha+":blue-ci-cd.yml").Output() |
| 67 | if err != nil { |
| 68 | return |
| 69 | } |
| 70 | read := func(path string) ([]byte, error) { |
| 71 | if path == "" || strings.Contains(path, "..") || strings.HasPrefix(path, "/") { |
| 72 | return nil, i18n.E("ci.err.rel", path) |
| 73 | } |
| 74 | return exec.CommandContext(ctx, s.Git, "-C", dir, "show", sha+":"+path).Output() |
| 75 | } |
| 76 | spec, err := ci.ParseIn(raw, read) |
| 77 | if err != nil { |
| 78 | _ = s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, err.Error()) |
| 79 | return |
| 80 | } |
| 81 | name, kind := ci.SplitRef(ref) |
| 82 | title := strings.TrimSpace(gitOne(ctx, s.Git, dir, "log", "-1", "--format=%s", sha)) |
| 83 | files := gitLines(ctx, s.Git, dir, "ls-tree", "-r", "--name-only", sha) |
| 84 | changed := changedFiles(ctx, s.Git, dir, sha, before, files) |
| 85 | env := ci.Variables(ci.Ref{ |
| 86 | SHA: sha, FullRef: ref, Name: name, Kind: kind, Title: title, |
| 87 | DefaultBranch: repo.DefaultBranch, Source: source, ProjectPath: repo.FullPath(), |
| 88 | }) |
| 89 | active, err := spec.Select(ci.Eval{Env: env, Changed: changed, Files: files}) |
| 90 | if err != nil { |
| 91 | _ = s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, err.Error()) |
| 92 | return |
| 93 | } |
| 94 | if len(active) == 0 { |
| 95 | return |
| 96 | } |
| 97 | var jobs []store.NewJob |
| 98 | for i, j := range active { |
| 99 | vars := map[string]string{} |
| 100 | for k, v := range spec.Variables { |
| 101 | vars[k] = v |
| 102 | } |
| 103 | for k, v := range j.Variables { |
| 104 | vars[k] = v |
| 105 | } |
| 106 | needs := j.Needs |
| 107 | if needs == nil { |
| 108 | needs = []string{} |
| 109 | } |
| 110 | paths := j.Artifacts.Paths |
| 111 | if paths == nil { |
| 112 | paths = []string{} |
| 113 | } |
| 114 | jobs = append(jobs, store.NewJob{ |
| 115 | Name: j.Name, Stage: j.Stage, Position: i, Image: j.Image, |
| 116 | Before: strings.Join(j.Before, "\n"), Script: strings.Join(j.Script, "\n"), After: strings.Join(j.After, "\n"), |
| 117 | Needs: needs, Optional: j.Optional, NeedsSet: j.NeedsSet, |
| 118 | Variables: vars, ArtifactPaths: paths, ArtifactExpire: j.Artifacts.ExpireIn, |
| 119 | AllowFailure: j.AllowFailure, When: j.When, Timeout: j.Timeout, Tags: j.Tags, |
| 120 | CachePaths: j.Cache.Paths, CacheKey: j.Cache.Key, ResourceGroup: j.ResourceGroup, |
| 121 | }) |
| 122 | } |
| 123 | if _, err := s.Store.CreatePipeline(ctx, repo.ID, sha, ref, source, actor, title, jobs); err != nil && s.Log != nil { |
| 124 | s.Log.Error("pipeline", "err", err) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | func gitOne(ctx context.Context, gitBin, dir string, args ...string) string { |
| 129 | out, err := exec.CommandContext(ctx, gitBin, append([]string{"-C", dir}, args...)...).Output() |
| 130 | if err != nil { |
| 131 | return "" |
| 132 | } |
| 133 | return strings.TrimSpace(string(out)) |
| 134 | } |
| 135 | |
| 136 | func gitLines(ctx context.Context, gitBin, dir string, args ...string) []string { |
| 137 | out := gitOne(ctx, gitBin, dir, args...) |
| 138 | if out == "" { |
| 139 | return []string{} |
| 140 | } |
| 141 | return strings.Split(out, "\n") |
| 142 | } |
| 143 | |
| 144 | func changedFiles(ctx context.Context, gitBin, dir, sha, before string, all []string) []string { |
| 145 | if before == "" || strings.Trim(before, "0") == "" { |
| 146 | parent := gitOne(ctx, gitBin, dir, "rev-parse", "--verify", sha+"^") |
| 147 | if parent == "" { |
| 148 | return all |
| 149 | } |
| 150 | before = parent |
| 151 | } |
| 152 | out, err := exec.CommandContext(ctx, gitBin, "-C", dir, "diff", "--name-only", before, sha).Output() |
| 153 | if err != nil { |
| 154 | return nil |
| 155 | } |
| 156 | text := strings.TrimSpace(string(out)) |
| 157 | if text == "" { |
| 158 | return []string{} |
| 159 | } |
| 160 | return strings.Split(text, "\n") |
| 161 | } |
| 162 | |
| 163 | func pushEvent(repo store.Repo, kind, branch, commit, actor, summary, path string) webhook.Event { |
| 164 | return webhook.Event{ |
| 165 | Type: kind, Project: repo.FullPath(), Branch: branch, Commit: commit, |
| 166 | Actor: actor, Summary: summary, URL: path, |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | func (s *Server) Dispatch(repoID int64, ev webhook.Event) { |
| 171 | ctx := context.Background() |
| 172 | repo, err := s.Store.RepoByID(ctx, repoID) |
| 173 | if err != nil { |
| 174 | return |
| 175 | } |
| 176 | if ev.Project == "" { |
| 177 | ev.Project = repo.FullPath() |
| 178 | } |
| 179 | if !strings.HasPrefix(ev.URL, "http") { |
| 180 | ev.URL = strings.TrimRight(s.Cfg.BaseURL, "/") + ev.URL |
| 181 | } |
| 182 | if repo.OwnerKind == "group" { |
| 183 | if g, err := s.Store.GroupByID(ctx, repo.OwnerID); err == nil { |
| 184 | ev.Group = g.Path |
| 185 | } |
| 186 | } |
| 187 | patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID) |
| 188 | protected := access.BranchProtected(patterns, ev.Branch) |
| 189 | s.deliver(ctx, "repo", repo.ID, ev, protected) |
| 190 | if repo.OwnerKind == "group" { |
| 191 | s.deliver(ctx, "group", repo.OwnerID, ev, protected) |
| 192 | } |
| 193 | if ev.Type == webhook.EventPipelineFailure { |
| 194 | s.queueFailureMail(repo, ev) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | func (s *Server) deliver(ctx context.Context, kind string, scopeID int64, ev webhook.Event, refProtected bool) { |
| 199 | hooks, err := s.Store.ListWebhooks(ctx, kind, scopeID) |
| 200 | if err != nil { |
| 201 | return |
| 202 | } |
| 203 | secrets, err := s.Store.SecretValues(ctx, kind, scopeID, refProtected) |
| 204 | if err != nil { |
| 205 | s.Log.Error("geheimen voor webhook", "err", err) |
| 206 | return |
| 207 | } |
| 208 | client := ssrf.NewClient(10 * time.Second) |
| 209 | for _, h := range hooks { |
| 210 | if !h.Active { |
| 211 | continue |
| 212 | } |
| 213 | ok, err := webhook.Allows(webhook.Hook{Preset: h.Preset, Events: h.Events, BranchFilter: h.BranchFilter}, ev) |
| 214 | if err != nil { |
| 215 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 216 | continue |
| 217 | } |
| 218 | if !ok { |
| 219 | continue |
| 220 | } |
| 221 | rawURL, err := webhook.Expand(h.URLTemplate, ev, secrets) |
| 222 | if err != nil { |
| 223 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 224 | continue |
| 225 | } |
| 226 | target, err := urlParse(rawURL) |
| 227 | if err != nil { |
| 228 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 229 | continue |
| 230 | } |
| 231 | if err := ssrf.ValidateURL(target); err != nil { |
| 232 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 233 | continue |
| 234 | } |
| 235 | headers, err := webhook.RenderHeaders(h.Preset, h.Headers, ev, secrets) |
| 236 | if err != nil { |
| 237 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 238 | continue |
| 239 | } |
| 240 | body, err := webhook.RenderBody(h.BodyTemplate, ev, secrets) |
| 241 | if err != nil { |
| 242 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 243 | continue |
| 244 | } |
| 245 | method := h.Method |
| 246 | if method == "" { |
| 247 | method = http.MethodPost |
| 248 | } |
| 249 | req, err := http.NewRequestWithContext(ctx, method, rawURL, bytes.NewReader(body)) |
| 250 | if err != nil { |
| 251 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 252 | continue |
| 253 | } |
| 254 | for k, v := range headers { |
| 255 | if strings.ContainsAny(k, "\r\n") || strings.ContainsAny(v, "\r\n") { |
| 256 | continue |
| 257 | } |
| 258 | req.Header.Set(k, v) |
| 259 | } |
| 260 | res, err := client.Do(req) |
| 261 | if err != nil { |
| 262 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 263 | continue |
| 264 | } |
| 265 | _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20)) |
| 266 | res.Body.Close() |
| 267 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, res.StatusCode, "") |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | func urlParse(raw string) (*url.URL, error) { |
| 272 | u, err := url.Parse(raw) |
| 273 | if err != nil { |
| 274 | return nil, i18n.E("err.whURL") |
| 275 | } |
| 276 | return u, nil |
| 277 | } |
| 278 | |
| 279 | func gitSHA(r *http.Request, gitBin, dir, rev string) (string, error) { |
| 280 | out, err := exec.CommandContext(r.Context(), gitBin, "-C", dir, "rev-parse", "--verify", rev+"^{commit}").Output() |
| 281 | if err != nil { |
| 282 | return "", err |
| 283 | } |
| 284 | return strings.TrimSpace(string(out)), nil |
| 285 | } |