BlueGit

timfa bluegit

Files

bluegit / internal / server / api_http.go

api_http.go

feat: bewaar squash en bronbranch op een merge request
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
Passed 0a53b47c History
api_http.go 11.0 KiB Download Raw
1package server
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "io"
8 "net/http"
9 "net/http/httptest"
10 "strconv"
11 "strings"
12
13 "gitlab.com/Timfa/bluegit/internal/access"
14 "gitlab.com/Timfa/bluegit/internal/i18n"
15 "gitlab.com/Timfa/bluegit/internal/store"
16)
17
18type actorKey struct{}
19
20type apiActor struct {
21 User store.User
22 Scopes access.Scopes
23 Via string
24}
25
26type apiAuth int
27
28const (
29 authUser apiAuth = iota
30 authPublic
31 authRelease
32)
33
34type apiHandler func(*Server, http.ResponseWriter, *http.Request)
35
36type apiRoute struct {
37 Method string
38 Path string
39 Class access.ScopeClass
40 Auth apiAuth
41 Summary string
42 Handler apiHandler
43}
44
45// apiRouteTaken zegt of server.go die methode en dat pad al registreert.
46// ServeMux weigert hetzelfde patroon twee keer. De expliciete handlers
47// blijven, de catalogus noemt het pad nog voor OpenAPI.
48func apiRouteTaken(method, path string) bool {
49 switch method + " " + path {
50 case "POST /api/v1/repos/{owner}/{repo}/releases",
51 "GET /api/v1/groups/{path}/secrets",
52 "POST /api/v1/groups/{path}/secrets",
53 "DELETE /api/v1/groups/{path}/secrets/{name}":
54 return true
55 default:
56 return false
57 }
58}
59
60func (s *Server) mountAPI(mux *http.ServeMux) {
61 mux.HandleFunc("GET /api/v1/openapi.json", func(w http.ResponseWriter, r *http.Request) {
62 s.serveAPI(w, r, apiRoute{Method: http.MethodGet, Path: "/api/v1/openapi.json", Class: access.ScopePublic, Auth: authPublic, Summary: "OpenAPI document", Handler: (*Server).openAPI})
63 })
64 for _, rt := range apiCatalog {
65 rt := rt
66 if apiRouteTaken(rt.Method, rt.Path) {
67 continue
68 }
69 mux.HandleFunc(rt.Method+" "+rt.Path, func(w http.ResponseWriter, r *http.Request) {
70 s.serveAPI(w, r, rt)
71 })
72 }
73}
74
75func (s *Server) serveAPI(w http.ResponseWriter, r *http.Request, rt apiRoute) {
76 w.Header().Set("Cache-Control", "no-store")
77 if rt.Auth == authPublic {
78 rt.Handler(s, w, r)
79 return
80 }
81 if rt.Auth == authRelease {
82 tok := tokenFrom(r)
83 if strings.HasPrefix(tok, "bgj_") {
84 rt.Handler(s, w, r)
85 return
86 }
87 }
88 actor, ok := r.Context().Value(actorKey{}).(apiActor)
89 if !ok {
90 tok := tokenFrom(r)
91 if tok == "" || !strings.HasPrefix(tok, "bg_") {
92 s.writeAPIErr(w, r, fail(http.StatusUnauthorized, i18n.E("err.apiAuth")))
93 return
94 }
95 auth, err := s.Store.AuthenticateToken(r.Context(), tok)
96 if err != nil {
97 s.writeAPIErr(w, r, fail(http.StatusUnauthorized, err))
98 return
99 }
100 actor = apiActor{User: auth.User, Scopes: access.StoredScopes(auth.Token.Scopes), Via: "token"}
101 }
102 if !actor.Scopes.Allows(rt.Class) {
103 s.writeAPIErr(w, r, fail(http.StatusForbidden, i18n.E("err.apiScope")))
104 return
105 }
106 ctx := context.WithValue(r.Context(), ctxKey{}, principal{User: actor.User, OK: true})
107 ctx = context.WithValue(ctx, actorKey{}, actor)
108 rt.Handler(s, w, r.WithContext(ctx))
109}
110
111func tokenFrom(r *http.Request) string {
112 if t := strings.TrimSpace(r.Header.Get("PRIVATE-TOKEN")); t != "" {
113 return t
114 }
115 if t := bearer(r); t != "" {
116 return t
117 }
118 _, pass, ok := r.BasicAuth()
119 if ok {
120 return pass
121 }
122 return ""
123}
124
125func apiUser(r *http.Request) store.User {
126 a, _ := r.Context().Value(actorKey{}).(apiActor)
127 return a.User
128}
129
130func readJSON(r *http.Request, dst any) error {
131 if r.Body == nil {
132 return nil
133 }
134 dec := json.NewDecoder(io.LimitReader(r.Body, 1<<20))
135 err := dec.Decode(dst)
136 if err == io.EOF {
137 return nil
138 }
139 return err
140}
141
142func writeJSON(w http.ResponseWriter, status int, v any) {
143 if status == http.StatusNoContent {
144 w.WriteHeader(status)
145 return
146 }
147 w.Header().Set("Content-Type", "application/json; charset=utf-8")
148 w.Header().Set("Cache-Control", "no-store")
149 w.WriteHeader(status)
150 _ = json.NewEncoder(w).Encode(v)
151}
152
153func (s *Server) writeAPIErr(w http.ResponseWriter, r *http.Request, err error) {
154 writeJSON(w, statusOf(err), map[string]any{"message": s.trErr(r, err)})
155}
156
157func (s *Server) apiOK(w http.ResponseWriter, r *http.Request, err error) bool {
158 if err == nil {
159 return true
160 }
161 s.writeAPIErr(w, r, err)
162 return false
163}
164
165func pageQuery(r *http.Request) (page, per int) {
166 page, _ = strconv.Atoi(r.URL.Query().Get("page"))
167 per, _ = strconv.Atoi(r.URL.Query().Get("per_page"))
168 if page < 1 {
169 page = 1
170 }
171 if per < 1 {
172 per = 20
173 }
174 if per > 100 {
175 per = 100
176 }
177 return page, per
178}
179
180func writePage(w http.ResponseWriter, r *http.Request, items any, total, page, per int) {
181 w.Header().Set("X-Total", strconv.Itoa(total))
182 w.Header().Set("X-Page", strconv.Itoa(page))
183 w.Header().Set("X-Per-Page", strconv.Itoa(per))
184 next := ""
185 if page*per < total {
186 next = strconv.Itoa(page + 1)
187 }
188 w.Header().Set("X-Next-Page", next)
189 writeJSON(w, http.StatusOK, items)
190}
191
192func slicePage[T any](items []T, page, per int) []T {
193 if items == nil {
194 items = []T{}
195 }
196 start := (page - 1) * per
197 if start > len(items) {
198 start = len(items)
199 }
200 end := start + per
201 if end > len(items) {
202 end = len(items)
203 }
204 out := items[start:end]
205 if out == nil {
206 out = []T{}
207 }
208 return out
209}
210
211// CallAPI voert een API-verzoek uit als deze gebruiker, zonder cookie.
212// SSH gebruikt hetzelfde pad als een toegangstoken met scope api.
213func (s *Server) CallAPI(ctx context.Context, user store.User, method, path string, body []byte) (int, []byte) {
214 if !strings.HasPrefix(path, "/") {
215 path = "/" + path
216 }
217 if !strings.HasPrefix(path, "/api/") {
218 path = "/api/v1" + path
219 }
220 var rdr io.Reader = http.NoBody
221 if len(body) > 0 {
222 rdr = bytes.NewReader(body)
223 }
224 req := httptest.NewRequest(method, path, rdr).WithContext(context.WithValue(ctx, actorKey{}, apiActor{
225 User: user, Scopes: access.AllScopes(), Via: "ssh",
226 }))
227 req.Header.Set("Content-Type", "application/json")
228 rec := httptest.NewRecorder()
229 s.Handler().ServeHTTP(rec, req)
230 return rec.Code, rec.Body.Bytes()
231}
232
233func (s *Server) openAPI(w http.ResponseWriter, r *http.Request) {
234 writeJSON(w, http.StatusOK, openAPIDoc())
235}
236
237func openAPIDoc() map[string]any {
238 paths := map[string]map[string]any{}
239 for _, rt := range apiCatalog {
240 rel := strings.TrimPrefix(rt.Path, "/api/v1")
241 rel = openAPIPath(rel)
242 item := paths[rel]
243 if item == nil {
244 item = map[string]any{}
245 paths[rel] = item
246 }
247 op := map[string]any{
248 "summary": rt.Summary,
249 "responses": map[string]any{"200": map[string]any{"description": "OK"}, "default": map[string]any{"description": "Error", "content": map[string]any{"application/json": map[string]any{"schema": map[string]any{"$ref": "#/components/schemas/Error"}}}}},
250 }
251 if rt.Auth != authPublic {
252 op["security"] = []any{
253 map[string]any{"bearer": []any{}},
254 map[string]any{"privateToken": []any{}},
255 map[string]any{"basic": []any{}},
256 }
257 }
258 item[strings.ToLower(rt.Method)] = op
259 }
260 attachMergeOptionDocs(paths)
261 paths["/openapi.json"] = map[string]any{
262 "get": map[string]any{"summary": "OpenAPI document", "responses": map[string]any{"200": map[string]any{"description": "OK"}}},
263 }
264 out := map[string]any{}
265 for k, v := range paths {
266 out[k] = v
267 }
268 return map[string]any{
269 "openapi": "3.0.3",
270 "info": map[string]any{"title": "BlueGit", "version": "v1"},
271 "servers": []any{map[string]any{"url": "/api/v1"}},
272 "paths": out,
273 "components": map[string]any{
274 "securitySchemes": map[string]any{
275 "bearer": map[string]any{"type": "http", "scheme": "bearer"},
276 "privateToken": map[string]any{"type": "apiKey", "in": "header", "name": "PRIVATE-TOKEN"},
277 "basic": map[string]any{"type": "http", "scheme": "basic"},
278 },
279 "schemas": map[string]any{
280 "Error": map[string]any{"type": "object", "properties": map[string]any{"message": map[string]any{"type": "string"}}},
281 },
282 },
283 }
284}
285
286func attachMergeOptionDocs(paths map[string]map[string]any) {
287 opts := map[string]any{
288 "remove_source_branch": map[string]any{
289 "type": "boolean",
290 "description": "Delete the source branch after a successful merge. Omitted on create means true. Omitted on merge keeps the stored value.",
291 },
292 "squash": map[string]any{
293 "type": "boolean",
294 "description": "Combine the commits into one. Omitted on create means false. Omitted on merge keeps the stored value.",
295 },
296 "squash_commit_message": map[string]any{
297 "type": "string",
298 "description": "Message of the squash commit. An empty message uses the merge request title.",
299 },
300 }
301 body := func(extra map[string]any) map[string]any {
302 props := map[string]any{}
303 for k, v := range opts {
304 props[k] = v
305 }
306 for k, v := range extra {
307 props[k] = v
308 }
309 return map[string]any{
310 "content": map[string]any{
311 "application/json": map[string]any{"schema": map[string]any{"type": "object", "properties": props}},
312 },
313 }
314 }
315 str := func(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }
316 boolean := map[string]any{"type": "boolean"}
317 if item := paths["/projects/{owner}/{repo}/merge_requests"]; item != nil {
318 if op, ok := item["post"].(map[string]any); ok {
319 op["requestBody"] = body(map[string]any{
320 "title": str("Title"),
321 "description": str("Description"),
322 "source_branch": str("Source branch"),
323 "target_branch": str("Target branch"),
324 "draft": boolean,
325 })
326 }
327 }
328 if item := paths["/projects/{owner}/{repo}/merge_requests/{number}"]; item != nil {
329 if op, ok := item["put"].(map[string]any); ok {
330 op["requestBody"] = body(map[string]any{
331 "title": str("Title"),
332 "description": str("Description"),
333 "labels": str("Labels"),
334 })
335 }
336 }
337 if item := paths["/projects/{owner}/{repo}/merge_requests/{number}/merge"]; item != nil {
338 if op, ok := item["post"].(map[string]any); ok {
339 op["requestBody"] = body(nil)
340 responses, _ := op["responses"].(map[string]any)
341 if responses != nil {
342 responses["200"] = map[string]any{"description": "Merged. source_branch_removed says whether the source branch was deleted. source_branch_skip is empty, disabled, protected, default, forbidden, missing or error."}
343 }
344 }
345 }
346}
347
348func openAPIPath(p string) string {
349 var b strings.Builder
350 for i := 0; i < len(p); i++ {
351 if p[i] == '{' {
352 j := strings.IndexByte(p[i:], '}')
353 if j < 0 {
354 b.WriteByte(p[i])
355 continue
356 }
357 name := p[i+1 : i+j]
358 name = strings.TrimSuffix(name, "...")
359 b.WriteByte('{')
360 b.WriteString(name)
361 b.WriteByte('}')
362 i += j
363 continue
364 }
365 b.WriteByte(p[i])
366 }
367 return b.String()
368}
369
370func apiIndex() []byte {
371 type row struct {
372 Method string `json:"method"`
373 Path string `json:"path"`
374 Summary string `json:"summary"`
375 Auth string `json:"auth"`
376 }
377 routes := []row{{Method: http.MethodGet, Path: "/api/v1/openapi.json", Summary: "OpenAPI document", Auth: "public"}}
378 for _, rt := range apiCatalog {
379 auth := "token"
380 if rt.Auth == authPublic {
381 auth = "public"
382 }
383 if rt.Auth == authRelease {
384 auth = "token_or_job"
385 }
386 routes = append(routes, row{Method: rt.Method, Path: rt.Path, Summary: rt.Summary, Auth: auth})
387 }
388 raw, _ := json.Marshal(map[string]any{
389 "openapi": "/api/v1/openapi.json",
390 "auth": []string{"Authorization: Bearer", "PRIVATE-TOKEN", "HTTP basic"},
391 "scopes": []string{access.ScopeAPI, access.ScopeReadAPI, access.ScopeReadRepo, access.ScopeWriteRepo},
392 "ssh": "ssh git@host api METHOD /api/v1/... ",
393 "routes": routes,
394 })
395 return raw
396}