BlueGit

timfa bluegit

Files

bluegit / internal / server / api.go

api.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
api.go 5.4 KiB Download Raw
1package server
2
3import (
4 "encoding/json"
5 "io"
6 "net/http"
7 "os"
8 "path/filepath"
9 "strings"
10
11 "gitlab.com/Timfa/bluegit/internal/access"
12 "gitlab.com/Timfa/bluegit/internal/gitrepo"
13 "gitlab.com/Timfa/bluegit/internal/names"
14 "gitlab.com/Timfa/bluegit/internal/store"
15 "gitlab.com/Timfa/bluegit/internal/webhook"
16)
17
18type releaseRequest struct {
19 Tag string `json:"tag"`
20 Commit string `json:"commit"`
21 Name string `json:"name"`
22 Body string `json:"body"`
23 Assets []struct {
24 Job string `json:"job"`
25 Path string `json:"path"`
26 Name string `json:"name"`
27 } `json:"assets"`
28}
29
30func (s *Server) createRelease(w http.ResponseWriter, r *http.Request) {
31 if s.StoragePath() == "" {
32 http.Error(w, noStorageMsg, http.StatusServiceUnavailable)
33 return
34 }
35 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
36 if err != nil {
37 http.NotFound(w, r)
38 return
39 }
40 token := bearer(r)
41 var job store.Job
42 var author int64
43 if strings.HasPrefix(token, "bgj_") {
44 job, err = s.Store.JobByToken(r.Context(), token)
45 if err != nil || job.RepoID != repo.ID || job.Status != "running" {
46 http.Error(w, "job-token ongeldig", http.StatusUnauthorized)
47 return
48 }
49 } else if strings.HasPrefix(token, "bg_") {
50 u, err := s.Store.UserByToken(r.Context(), token)
51 if err != nil {
52 http.Error(w, "token ongeldig", http.StatusUnauthorized)
53 return
54 }
55 role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)
56 if err != nil || !role.AtLeast(access.RoleMaintainer) {
57 http.Error(w, "alleen een beheerder", http.StatusForbidden)
58 return
59 }
60 author = u.ID
61 } else {
62 http.Error(w, "token ontbreekt", http.StatusUnauthorized)
63 return
64 }
65 var req releaseRequest
66 if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req); err != nil {
67 http.Error(w, "json", http.StatusBadRequest)
68 return
69 }
70 if err := names.ValidTag(req.Tag); err != nil {
71 http.Error(w, err.Error(), http.StatusBadRequest)
72 return
73 }
74 if !safeSHA(req.Commit) {
75 http.Error(w, "commit ontbreekt", http.StatusBadRequest)
76 return
77 }
78 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
79 if !gitrepo.HasCommit(r.Context(), s.Git, dir, req.Commit) {
80 http.Error(w, "commit niet in deze repository", http.StatusBadRequest)
81 return
82 }
83 if req.Name == "" {
84 req.Name = req.Tag
85 }
86 if job.ID == 0 && len(req.Assets) > 0 {
87 http.Error(w, "assets horen bij een job-token", http.StatusBadRequest)
88 return
89 }
90 var assets []store.ReleaseAsset
91 for _, a := range req.Assets {
92 if a.Name == "" {
93 a.Name = filepath.Base(a.Path)
94 }
95 if err := names.ValidRepoName(strings.ReplaceAll(a.Name, ".", "x")); err != nil && strings.Contains(a.Name, "..") {
96 http.Error(w, "assetnaam", http.StatusBadRequest)
97 return
98 }
99 if strings.Contains(a.Name, "/") || strings.Contains(a.Name, "..") || a.Path == "" {
100 http.Error(w, "assetnaam", http.StatusBadRequest)
101 return
102 }
103 src, err := s.Store.ArtifactPath(r.Context(), job.PipelineID, a.Job, a.Path)
104 if err != nil {
105 http.Error(w, "artifact niet gevonden: "+a.Job+" "+a.Path, http.StatusBadRequest)
106 return
107 }
108 info, err := os.Stat(src)
109 if err != nil {
110 http.Error(w, "artifact ontbreekt op schijf", http.StatusBadRequest)
111 return
112 }
113 dst := filepath.Join(s.StoragePath(), "releases", repo.OwnerPath, repo.Name, req.Tag, a.Name)
114 if err := copyRelease(src, dst); err != nil {
115 http.Error(w, "asset kopiëren", http.StatusInternalServerError)
116 return
117 }
118 assets = append(assets, store.ReleaseAsset{Name: a.Name, StoragePath: dst, Size: info.Size()})
119 }
120 if err := gitrepo.Tag(r.Context(), s.Git, dir, req.Tag, req.Commit, req.Name); err != nil {
121 http.Error(w, "tag: "+err.Error(), http.StatusBadRequest)
122 return
123 }
124 id, err := s.Store.CreateRelease(r.Context(), repo.ID, req.Tag, req.Commit, req.Name, req.Body, author, job.ID, assets)
125 if err != nil {
126 http.Error(w, err.Error(), http.StatusBadRequest)
127 return
128 }
129 s.Dispatch(repo.ID, webhook.Event{
130 Type: webhook.EventRelease, Project: repo.FullPath(), Commit: req.Commit,
131 ReleaseTag: req.Tag, Summary: "release " + req.Tag + " van " + repo.FullPath() + " gepubliceerd",
132 URL: strings.TrimRight(s.Cfg.BaseURL, "/") + repoURL(repo) + "/-/releases",
133 })
134 w.Header().Set("Content-Type", "application/json")
135 w.WriteHeader(http.StatusCreated)
136 _ = json.NewEncoder(w).Encode(map[string]any{"id": id, "tag": req.Tag, "commit": req.Commit})
137}
138
139func (s *Server) releaseAsset(w http.ResponseWriter, r *http.Request) {
140 _, repo, _, ok := s.guard(w, r, access.RoleReadonly)
141 if !ok {
142 return
143 }
144 rel, err := s.Store.ReleaseByTag(r.Context(), repo.ID, r.PathValue("tag"))
145 if err != nil {
146 http.NotFound(w, r)
147 return
148 }
149 name := r.PathValue("name")
150 for _, a := range rel.Assets {
151 if a.Name == name {
152 w.Header().Set("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(name, "\"", "")+"\"")
153 http.ServeFile(w, r, a.StoragePath)
154 return
155 }
156 }
157 http.NotFound(w, r)
158}
159
160func bearer(r *http.Request) string {
161 h := r.Header.Get("Authorization")
162 if strings.HasPrefix(strings.ToLower(h), "bearer ") {
163 return strings.TrimSpace(h[7:])
164 }
165 return ""
166}
167
168func copyRelease(src, dst string) error {
169 if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
170 return err
171 }
172 in, err := os.Open(src)
173 if err != nil {
174 return err
175 }
176 defer in.Close()
177 out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
178 if err != nil {
179 return err
180 }
181 defer out.Close()
182 _, err = io.Copy(out, in)
183 return err
184}