BlueGit

timfa bluegit

Files

bluegit / internal / server / events.go

events.go

feat: sta gemengde secretnamen toe en kies ze bij een webhook
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
c102b10c History
events.go 8.9 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
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.
25func (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.
46func (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 for ref, sha := range after {
52 if before[ref] == sha || isZero(sha) {
53 continue
54 }
55 commit := s.peeled(repo, sha)
56 if strings.HasPrefix(ref, "refs/tags/") {
57 name := strings.TrimPrefix(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, name, commit)
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 s.rerunMergeRequestsOnTarget(context.Background(), repo, branch, actor)
72 s.pushHook(repo, actor, branch, commit)
73 }
74}
75
76func (s *Server) pushHook(repo store.Repo, actor, branch, commit string) {
77 s.Dispatch(repo.ID, webhook.Event{
78 Type: webhook.EventPush,
79 Project: repo.FullPath(),
80 Branch: branch,
81 Commit: commit,
82 Summary: i18n.T(i18n.EN, "hook.push", actor, branch, repo.FullPath()),
83 URL: strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath(),
84 Actor: actor,
85 })
86}
87
88func (s *Server) peeled(repo store.Repo, sha string) string {
89 if s.StoragePath() == "" || sha == "" {
90 return sha
91 }
92 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
93 if commit := gitOne(context.Background(), s.Git, dir, "rev-parse", "--verify", sha+"^{commit}"); commit != "" {
94 return commit
95 }
96 return sha
97}
98
99func isZero(sha string) bool {
100 return strings.Trim(sha, "0") == ""
101}
102
103func (s *Server) startPipeline(ctx context.Context, repo store.Repo, sha, ref, actor, source, before string, mr *ci.MRInfo) int64 {
104 if !s.Cfg.CI.Enabled || s.StoragePath() == "" {
105 return 0
106 }
107 title, jobs, broken := s.planPipeline(ctx, repo, sha, ref, source, before, mr)
108 if broken != nil {
109 id, err := s.Store.RecordConfigFailure(ctx, repo.ID, sha, ref, broken.Error())
110 if err != nil && s.Log != nil {
111 s.Log.Error("pipeline", "err", err)
112 }
113 if mr != nil && id != 0 {
114 _ = s.Store.AttachPipelineMR(ctx, id, mr.ID)
115 }
116 if id != 0 {
117 s.cancelOlder(ctx, repo.ID, ref, id)
118 }
119 return id
120 }
121 if len(jobs) == 0 {
122 return 0
123 }
124 id, err := s.Store.CreatePipeline(ctx, repo.ID, sha, ref, source, actor, title, jobs)
125 if err != nil {
126 if s.Log != nil {
127 s.Log.Error("pipeline", "err", err)
128 }
129 return 0
130 }
131 if mr != nil {
132 _ = s.Store.AttachPipelineMR(ctx, id, mr.ID)
133 }
134 s.cancelOlder(ctx, repo.ID, ref, id)
135 return id
136}
137
138func (s *Server) cancelOlder(ctx context.Context, repoID int64, ref string, keep int64) {
139 running, pipes, err := s.Store.CancelInterruptible(ctx, repoID, ref, keep)
140 if err != nil {
141 if s.Log != nil {
142 s.Log.Error("interruptible", "err", err)
143 }
144 return
145 }
146 if s.Runner != nil {
147 s.Runner.Interrupt(running)
148 }
149 for _, id := range pipes {
150 if _, err := s.Store.RefreshPipelineStatus(ctx, id); err != nil && s.Log != nil {
151 s.Log.Error("pipelinestatus", "err", err)
152 }
153 }
154}
155
156func gitOne(ctx context.Context, gitBin, dir string, args ...string) string {
157 out, err := exec.CommandContext(ctx, gitBin, append([]string{"-C", dir}, args...)...).Output()
158 if err != nil {
159 return ""
160 }
161 return strings.TrimSpace(string(out))
162}
163
164func gitLines(ctx context.Context, gitBin, dir string, args ...string) []string {
165 out := gitOne(ctx, gitBin, dir, args...)
166 if out == "" {
167 return []string{}
168 }
169 return strings.Split(out, "\n")
170}
171
172func changedFiles(ctx context.Context, gitBin, dir, sha, before string, all []string) []string {
173 if before == "" || strings.Trim(before, "0") == "" {
174 parent := gitOne(ctx, gitBin, dir, "rev-parse", "--verify", sha+"^")
175 if parent == "" {
176 return all
177 }
178 before = parent
179 }
180 out, err := exec.CommandContext(ctx, gitBin, "-C", dir, "diff", "--name-only", before, sha).Output()
181 if err != nil {
182 return nil
183 }
184 text := strings.TrimSpace(string(out))
185 if text == "" {
186 return []string{}
187 }
188 return strings.Split(text, "\n")
189}
190
191func pushEvent(repo store.Repo, kind, branch, commit, actor, summary, path string) webhook.Event {
192 return webhook.Event{
193 Type: kind, Project: repo.FullPath(), Branch: branch, Commit: commit,
194 Actor: actor, Summary: summary, URL: path,
195 }
196}
197
198func (s *Server) Dispatch(repoID int64, ev webhook.Event) {
199 ctx := context.Background()
200 repo, err := s.Store.RepoByID(ctx, repoID)
201 if err != nil {
202 return
203 }
204 if ev.Project == "" {
205 ev.Project = repo.FullPath()
206 }
207 if !strings.HasPrefix(ev.URL, "http") {
208 ev.URL = strings.TrimRight(s.Cfg.BaseURL, "/") + ev.URL
209 }
210 if repo.OwnerKind == "group" {
211 if g, err := s.Store.GroupByID(ctx, repo.OwnerID); err == nil {
212 ev.Group = g.Path
213 }
214 }
215 patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID)
216 protected := access.BranchProtected(patterns, ev.Branch)
217 s.deliver(ctx, "repo", repo.ID, ev, protected, repo)
218 if repo.OwnerKind == "group" {
219 s.deliver(ctx, "group", repo.OwnerID, ev, protected, repo)
220 }
221 if ev.Type == webhook.EventPipelineFailure {
222 s.queueFailureMail(repo, ev)
223 }
224}
225
226func (s *Server) deliver(ctx context.Context, kind string, scopeID int64, ev webhook.Event, refProtected bool, repo store.Repo) {
227 hooks, err := s.Store.ListWebhooks(ctx, kind, scopeID)
228 if err != nil {
229 return
230 }
231 secrets, err := s.hookSecrets(ctx, kind, scopeID, refProtected, repo)
232 if err != nil {
233 s.Log.Error("geheimen voor webhook", "err", err)
234 return
235 }
236 client := ssrf.NewClient(10 * time.Second)
237 for _, h := range hooks {
238 if !h.Active {
239 continue
240 }
241 ok, err := webhook.Allows(webhook.Hook{Preset: h.Preset, Events: h.Events, BranchFilter: h.BranchFilter}, ev)
242 if err != nil {
243 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
244 continue
245 }
246 if !ok {
247 continue
248 }
249 rawURL, err := webhook.Expand(h.URLTemplate, ev, secrets)
250 if err != nil {
251 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
252 continue
253 }
254 target, err := urlParse(rawURL)
255 if err != nil {
256 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
257 continue
258 }
259 if err := ssrf.ValidateURL(target); err != nil {
260 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
261 continue
262 }
263 headers, err := webhook.RenderHeaders(h.Preset, h.Headers, ev, secrets)
264 if err != nil {
265 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
266 continue
267 }
268 body, err := webhook.RenderBody(h.BodyTemplate, ev, secrets)
269 if err != nil {
270 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
271 continue
272 }
273 method := h.Method
274 if method == "" {
275 method = http.MethodPost
276 }
277 req, err := http.NewRequestWithContext(ctx, method, rawURL, bytes.NewReader(body))
278 if err != nil {
279 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
280 continue
281 }
282 for k, v := range headers {
283 if strings.ContainsAny(k, "\r\n") || strings.ContainsAny(v, "\r\n") {
284 continue
285 }
286 req.Header.Set(k, v)
287 }
288 res, err := client.Do(req)
289 if err != nil {
290 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
291 continue
292 }
293 _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20))
294 res.Body.Close()
295 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, res.StatusCode, "")
296 }
297}
298
299func urlParse(raw string) (*url.URL, error) {
300 u, err := url.Parse(raw)
301 if err != nil {
302 return nil, i18n.E("err.whURL")
303 }
304 return u, nil
305}
306
307func gitSHA(r *http.Request, gitBin, dir, rev string) (string, error) {
308 out, err := exec.CommandContext(r.Context(), gitBin, "-C", dir, "rev-parse", "--verify", rev+"^{commit}").Output()
309 if err != nil {
310 return "", err
311 }
312 return strings.TrimSpace(string(out)), nil
313}