| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "net/http" |
| 9 | "net/url" |
| 10 | "os/exec" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "gitlab.com/Timfa/bluegit/internal/access" |
| 15 | "gitlab.com/Timfa/bluegit/internal/ci" |
| 16 | "gitlab.com/Timfa/bluegit/internal/gitrepo" |
| 17 | "gitlab.com/Timfa/bluegit/internal/store" |
| 18 | "gitlab.com/Timfa/bluegit/internal/webhook" |
| 19 | ) |
| 20 | |
| 21 | func (s *Server) AfterPush(repo store.Repo, user store.User, before, after map[string]string) { |
| 22 | if after == nil { |
| 23 | return |
| 24 | } |
| 25 | actor := user.Username |
| 26 | for ref, sha := range after { |
| 27 | if before[ref] == sha { |
| 28 | continue |
| 29 | } |
| 30 | branch, ok := gitrepo.BranchOfRef(ref) |
| 31 | if !ok || isZero(sha) { |
| 32 | continue |
| 33 | } |
| 34 | s.startPipeline(context.Background(), repo, sha, ref, actor) |
| 35 | web := strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath() |
| 36 | s.Dispatch(repo.ID, webhook.Event{ |
| 37 | Type: webhook.EventPush, |
| 38 | Project: repo.FullPath(), |
| 39 | Branch: branch, |
| 40 | Commit: sha, |
| 41 | Summary: fmt.Sprintf("%s pushte naar %s in %s", actor, branch, repo.FullPath()), |
| 42 | URL: web, |
| 43 | Actor: actor, |
| 44 | }) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | func isZero(sha string) bool { |
| 49 | return strings.Trim(sha, "0") == "" |
| 50 | } |
| 51 | |
| 52 | func (s *Server) startPipeline(ctx context.Context, repo store.Repo, sha, ref, actor string) { |
| 53 | if !s.Cfg.CI.Enabled { |
| 54 | return |
| 55 | } |
| 56 | dir := gitrepo.Dir(s.Cfg.StoragePath, repo.OwnerPath, repo.Name) |
| 57 | raw, err := exec.CommandContext(ctx, s.Git, "-C", dir, "show", sha+":blue-ci-cd.yml").Output() |
| 58 | if err != nil { |
| 59 | return |
| 60 | } |
| 61 | spec, err := ci.Parse(raw) |
| 62 | branch, _ := gitrepo.BranchOfRef(ref) |
| 63 | if branch == "" { |
| 64 | branch = ref |
| 65 | } |
| 66 | if err != nil { |
| 67 | _ = s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, "blue-ci-cd.yml: "+err.Error()) |
| 68 | return |
| 69 | } |
| 70 | env := map[string]string{"CI_COMMIT_BRANCH": branch, "CI_COMMIT_SHA": sha, "CI_COMMIT_REF": ref} |
| 71 | active, err := spec.ActiveJobs(env) |
| 72 | if err != nil { |
| 73 | _ = s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, err.Error()) |
| 74 | return |
| 75 | } |
| 76 | if len(active) == 0 { |
| 77 | return |
| 78 | } |
| 79 | var jobs []store.NewJob |
| 80 | for i, j := range active { |
| 81 | vars := map[string]string{} |
| 82 | for k, v := range spec.Variables { |
| 83 | vars[k] = v |
| 84 | } |
| 85 | for k, v := range j.Variables { |
| 86 | vars[k] = v |
| 87 | } |
| 88 | needs := j.Needs |
| 89 | if needs == nil { |
| 90 | needs = []string{} |
| 91 | } |
| 92 | paths := j.Artifacts.Paths |
| 93 | if paths == nil { |
| 94 | paths = []string{} |
| 95 | } |
| 96 | jobs = append(jobs, store.NewJob{ |
| 97 | Name: j.Name, Stage: j.Stage, Position: i, Image: j.Image, |
| 98 | Script: strings.Join(j.Script, "\n"), Needs: needs, NeedsSet: j.NeedsSet, |
| 99 | Variables: vars, ArtifactPaths: paths, ArtifactExpire: j.Artifacts.ExpireIn, |
| 100 | AllowFailure: j.AllowFailure, |
| 101 | }) |
| 102 | } |
| 103 | if _, err := s.Store.CreatePipeline(ctx, repo.ID, sha, ref, jobs); err != nil && s.Log != nil { |
| 104 | s.Log.Error("pipeline", "err", err) |
| 105 | } |
| 106 | _ = actor |
| 107 | } |
| 108 | |
| 109 | func pushEvent(repo store.Repo, kind, branch, commit, actor, summary, path string) webhook.Event { |
| 110 | return webhook.Event{ |
| 111 | Type: kind, Project: repo.FullPath(), Branch: branch, Commit: commit, |
| 112 | Actor: actor, Summary: summary, URL: path, |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | func (s *Server) Dispatch(repoID int64, ev webhook.Event) { |
| 117 | ctx := context.Background() |
| 118 | repo, err := s.Store.RepoByID(ctx, repoID) |
| 119 | if err != nil { |
| 120 | return |
| 121 | } |
| 122 | if ev.Project == "" { |
| 123 | ev.Project = repo.FullPath() |
| 124 | } |
| 125 | if !strings.HasPrefix(ev.URL, "http") { |
| 126 | ev.URL = strings.TrimRight(s.Cfg.BaseURL, "/") + ev.URL |
| 127 | } |
| 128 | if repo.OwnerKind == "group" { |
| 129 | if g, err := s.Store.GroupByID(ctx, repo.OwnerID); err == nil { |
| 130 | ev.Group = g.Path |
| 131 | } |
| 132 | } |
| 133 | patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID) |
| 134 | protected := access.BranchProtected(patterns, ev.Branch) |
| 135 | s.deliver(ctx, "repo", repo.ID, ev, protected) |
| 136 | if repo.OwnerKind == "group" { |
| 137 | s.deliver(ctx, "group", repo.OwnerID, ev, protected) |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | func (s *Server) deliver(ctx context.Context, kind string, scopeID int64, ev webhook.Event, refProtected bool) { |
| 142 | hooks, err := s.Store.ListWebhooks(ctx, kind, scopeID) |
| 143 | if err != nil { |
| 144 | return |
| 145 | } |
| 146 | secrets, err := s.Store.SecretValues(ctx, kind, scopeID, refProtected) |
| 147 | if err != nil { |
| 148 | s.Log.Error("geheimen voor webhook", "err", err) |
| 149 | return |
| 150 | } |
| 151 | client := &http.Client{ |
| 152 | Timeout: 10 * time.Second, |
| 153 | CheckRedirect: func(req *http.Request, via []*http.Request) error { |
| 154 | return http.ErrUseLastResponse |
| 155 | }, |
| 156 | } |
| 157 | for _, h := range hooks { |
| 158 | if !h.Active { |
| 159 | continue |
| 160 | } |
| 161 | ok, err := webhook.Allows(webhook.Hook{Preset: h.Preset, Events: h.Events, BranchFilter: h.BranchFilter}, ev) |
| 162 | if err != nil { |
| 163 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 164 | continue |
| 165 | } |
| 166 | if !ok { |
| 167 | continue |
| 168 | } |
| 169 | rawURL, err := webhook.Expand(h.URLTemplate, ev, secrets) |
| 170 | if err != nil { |
| 171 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 172 | continue |
| 173 | } |
| 174 | if err := validateHookURL(rawURL); err != nil { |
| 175 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 176 | continue |
| 177 | } |
| 178 | headers, err := webhook.RenderHeaders(h.Preset, h.Headers, ev, secrets) |
| 179 | if err != nil { |
| 180 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 181 | continue |
| 182 | } |
| 183 | body, err := webhook.RenderBody(h.BodyTemplate, ev, secrets) |
| 184 | if err != nil { |
| 185 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 186 | continue |
| 187 | } |
| 188 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, bytes.NewReader(body)) |
| 189 | if err != nil { |
| 190 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 191 | continue |
| 192 | } |
| 193 | for k, v := range headers { |
| 194 | if strings.ContainsAny(k, "\r\n") || strings.ContainsAny(v, "\r\n") { |
| 195 | continue |
| 196 | } |
| 197 | req.Header.Set(k, v) |
| 198 | } |
| 199 | res, err := client.Do(req) |
| 200 | if err != nil { |
| 201 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error()) |
| 202 | continue |
| 203 | } |
| 204 | _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20)) |
| 205 | res.Body.Close() |
| 206 | _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, res.StatusCode, "") |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | func validateHookURL(raw string) error { |
| 211 | u, err := url.Parse(raw) |
| 212 | if err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") || u.User != nil { |
| 213 | return fmt.Errorf("webhook-URL is ongeldig") |
| 214 | } |
| 215 | return nil |
| 216 | } |
| 217 | |
| 218 | func gitSHA(r *http.Request, gitBin, dir, rev string) (string, error) { |
| 219 | out, err := exec.CommandContext(r.Context(), gitBin, "-C", dir, "rev-parse", "--verify", rev+"^{commit}").Output() |
| 220 | if err != nil { |
| 221 | return "", err |
| 222 | } |
| 223 | return strings.TrimSpace(string(out)), nil |
| 224 | } |