BlueGit

timfa bluegit

Files

bluegit / internal / server / events.go

events.go

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