BlueGit

timfa bluegit

Files

bluegit / internal / server / api.go

api.go

api.go 6.8 KiB Download Raw
1package server
2
3import (
4 "io"
5 "net/http"
6 "os"
7 "path/filepath"
8 "strconv"
9 "strings"
10
11 "gitlab.com/Timfa/bluegit/internal/access"
12 "gitlab.com/Timfa/bluegit/internal/ci"
13 "gitlab.com/Timfa/bluegit/internal/gitrepo"
14 "gitlab.com/Timfa/bluegit/internal/i18n"
15 "gitlab.com/Timfa/bluegit/internal/store"
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 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
32 if err != nil {
33 s.writeAPIErr(w, r, fail(http.StatusNotFound, i18n.E("err.notFound")))
34 return
35 }
36 token := tokenFrom(r)
37 var job store.Job
38 var author store.User
39 if strings.HasPrefix(token, "bgj_") {
40 job, err = s.Store.JobByToken(r.Context(), token)
41 if err != nil || job.RepoID != repo.ID || job.Status != "running" {
42 s.writeAPIErr(w, r, fail(http.StatusUnauthorized, i18n.E("err.jobToken")))
43 return
44 }
45 } else {
46 author = apiUser(r)
47 if author.ID == 0 {
48 s.writeAPIErr(w, r, fail(http.StatusUnauthorized, i18n.E("err.apiAuth")))
49 return
50 }
51 role, err := s.Store.EffectiveRole(r.Context(), author.ID, repo.ID)
52 if err == nil && !role.CanRead() && repo.Visibility != "public" {
53 s.writeAPIErr(w, r, fail(http.StatusNotFound, i18n.E("err.notFound")))
54 return
55 }
56 if err != nil || !role.AtLeast(access.RoleMaintainer) {
57 s.writeAPIErr(w, r, fail(http.StatusForbidden, i18n.E("err.onlyAdmin")))
58 return
59 }
60 }
61 var req releaseRequest
62 if err := readJSON(r, &req); err != nil {
63 s.writeAPIErr(w, r, fail(http.StatusBadRequest, i18n.E("err.json")))
64 return
65 }
66 id, err := s.opPublishRelease(r.Context(), repo, author, job, req)
67 if !s.apiOK(w, r, err) {
68 return
69 }
70 writeJSON(w, http.StatusCreated, map[string]any{"id": id, "tag": req.Tag, "commit": req.Commit})
71}
72
73func (s *Server) releaseAsset(w http.ResponseWriter, r *http.Request) {
74 _, repo, _, ok := s.guardReleases(w, r)
75 if !ok {
76 return
77 }
78 rel, err := s.Store.ReleaseByTag(r.Context(), repo.ID, r.PathValue("tag"))
79 if err != nil {
80 http.NotFound(w, r)
81 return
82 }
83 name := r.PathValue("name")
84 for _, a := range rel.Assets {
85 if a.Name == name {
86 w.Header().Set("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(name, "\"", "")+"\"")
87 http.ServeFile(w, r, a.StoragePath)
88 return
89 }
90 }
91 http.NotFound(w, r)
92}
93
94// jobLogAPI geeft de volledige console-output van een job, met geheimen gemaskeerd.
95// Een persoonlijk token is verplicht, ook bij een publieke repo. Job-tokens tellen niet.
96func (s *Server) jobLogAPI(w http.ResponseWriter, r *http.Request) {
97 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
98 if err != nil {
99 http.NotFound(w, r)
100 return
101 }
102 if !s.authorizeRepoRead(w, r, repo) {
103 return
104 }
105 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
106 if err != nil || id <= 0 {
107 http.NotFound(w, r)
108 return
109 }
110 job, err := s.Store.JobByID(r.Context(), repo.ID, id)
111 if err != nil {
112 http.NotFound(w, r)
113 return
114 }
115 text := ci.Mask(job.Log, s.maskSecrets(r.Context(), repo))
116 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
117 w.Header().Set("Cache-Control", "no-store")
118 _, _ = w.Write([]byte(text))
119}
120
121// authorizeRepoRead eist een persoonlijk token. Op een publieke repo volstaat
122// elk geldig token. Op een privérepo moet het token de repo mogen lezen.
123func (s *Server) authorizeRepoRead(w http.ResponseWriter, r *http.Request, repo store.Repo) bool {
124 token := bearer(r)
125 if token == "" {
126 http.Error(w, s.tr(r, "err.tokenAbsent"), http.StatusUnauthorized)
127 return false
128 }
129 if strings.HasPrefix(token, "bgj_") {
130 job, err := s.Store.JobByToken(r.Context(), token)
131 if err == nil && job.Status == "running" && job.RepoID == repo.ID {
132 return true
133 }
134 http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
135 return false
136 }
137 if !strings.HasPrefix(token, "bg_") {
138 http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
139 return false
140 }
141 u, err := s.Store.UserByToken(r.Context(), token)
142 if err != nil {
143 http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
144 return false
145 }
146 role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)
147 if err != nil {
148 http.Error(w, s.tr(r, "err.rights"), http.StatusInternalServerError)
149 return false
150 }
151 if !role.CanRead() && repo.Visibility != "public" {
152 http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
153 return false
154 }
155 return true
156}
157
158// commitDiffAPI geeft de unified diff van één commit.
159func (s *Server) commitDiffAPI(w http.ResponseWriter, r *http.Request) {
160 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
161 if err != nil {
162 http.NotFound(w, r)
163 return
164 }
165 if !s.authorizeRepoRead(w, r, repo) {
166 return
167 }
168 sha := r.PathValue("sha")
169 if !safeSHA(sha) || s.Git == "" || s.StoragePath() == "" {
170 http.NotFound(w, r)
171 return
172 }
173 text, err := gitrepo.CommitDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), sha)
174 if err != nil {
175 http.NotFound(w, r)
176 return
177 }
178 writePlain(w, text)
179}
180
181// mrDiffAPI geeft de three-dot diff van een merge request.
182func (s *Server) mrDiffAPI(w http.ResponseWriter, r *http.Request) {
183 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
184 if err != nil {
185 http.NotFound(w, r)
186 return
187 }
188 if !s.authorizeRepoRead(w, r, repo) {
189 return
190 }
191 number, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
192 if err != nil || number <= 0 || s.Git == "" || s.StoragePath() == "" {
193 http.NotFound(w, r)
194 return
195 }
196 mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, number)
197 if err != nil || safeRev(mr.SourceBranch, "") != mr.SourceBranch || safeRev(mr.TargetBranch, "") != mr.TargetBranch {
198 http.NotFound(w, r)
199 return
200 }
201 text, err := gitrepo.CompareDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), mr.TargetBranch, mr.SourceBranch)
202 if err != nil {
203 http.NotFound(w, r)
204 return
205 }
206 writePlain(w, text)
207}
208
209func writePlain(w http.ResponseWriter, text string) {
210 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
211 w.Header().Set("Cache-Control", "no-store")
212 _, _ = w.Write([]byte(text))
213}
214
215func bearer(r *http.Request) string {
216 h := r.Header.Get("Authorization")
217 if strings.HasPrefix(strings.ToLower(h), "bearer ") {
218 return strings.TrimSpace(h[7:])
219 }
220 return ""
221}
222
223func copyRelease(src, dst string) error {
224 if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
225 return err
226 }
227 in, err := os.Open(src)
228 if err != nil {
229 return err
230 }
231 defer in.Close()
232 out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
233 if err != nil {
234 return err
235 }
236 defer out.Close()
237 _, err = io.Copy(out, in)
238 return err
239}