BlueGit

timfa bluegit

Files

bluegit / internal / server / api.go

api.go

api.go 6.6 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_") || !strings.HasPrefix(token, "bg_") {
130 http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
131 return false
132 }
133 u, err := s.Store.UserByToken(r.Context(), token)
134 if err != nil {
135 http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
136 return false
137 }
138 role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)
139 if err != nil {
140 http.Error(w, s.tr(r, "err.rights"), http.StatusInternalServerError)
141 return false
142 }
143 if !role.CanRead() && repo.Visibility != "public" {
144 http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
145 return false
146 }
147 return true
148}
149
150// commitDiffAPI geeft de unified diff van één commit.
151func (s *Server) commitDiffAPI(w http.ResponseWriter, r *http.Request) {
152 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
153 if err != nil {
154 http.NotFound(w, r)
155 return
156 }
157 if !s.authorizeRepoRead(w, r, repo) {
158 return
159 }
160 sha := r.PathValue("sha")
161 if !safeSHA(sha) || s.Git == "" || s.StoragePath() == "" {
162 http.NotFound(w, r)
163 return
164 }
165 text, err := gitrepo.CommitDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), sha)
166 if err != nil {
167 http.NotFound(w, r)
168 return
169 }
170 writePlain(w, text)
171}
172
173// mrDiffAPI geeft de three-dot diff van een merge request.
174func (s *Server) mrDiffAPI(w http.ResponseWriter, r *http.Request) {
175 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
176 if err != nil {
177 http.NotFound(w, r)
178 return
179 }
180 if !s.authorizeRepoRead(w, r, repo) {
181 return
182 }
183 number, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
184 if err != nil || number <= 0 || s.Git == "" || s.StoragePath() == "" {
185 http.NotFound(w, r)
186 return
187 }
188 mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, number)
189 if err != nil || safeRev(mr.SourceBranch, "") != mr.SourceBranch || safeRev(mr.TargetBranch, "") != mr.TargetBranch {
190 http.NotFound(w, r)
191 return
192 }
193 text, err := gitrepo.CompareDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), mr.TargetBranch, mr.SourceBranch)
194 if err != nil {
195 http.NotFound(w, r)
196 return
197 }
198 writePlain(w, text)
199}
200
201func writePlain(w http.ResponseWriter, text string) {
202 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
203 w.Header().Set("Cache-Control", "no-store")
204 _, _ = w.Write([]byte(text))
205}
206
207func bearer(r *http.Request) string {
208 h := r.Header.Get("Authorization")
209 if strings.HasPrefix(strings.ToLower(h), "bearer ") {
210 return strings.TrimSpace(h[7:])
211 }
212 return ""
213}
214
215func copyRelease(src, dst string) error {
216 if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
217 return err
218 }
219 in, err := os.Open(src)
220 if err != nil {
221 return err
222 }
223 defer in.Close()
224 out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
225 if err != nil {
226 return err
227 }
228 defer out.Close()
229 _, err = io.Copy(out, in)
230 return err
231}