BlueGit

timfa bluegit

Files

bluegit / internal / server / events.go

events.go

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