BlueGit

timfa bluegit

Files

bluegit / internal / server / api_http.go

api_http.go

feat: bied dezelfde acties als de UI aan via /api/v1
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
d89195e9 History
api_http.go 8.6 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.WriteHeader(status)
149 _ = json.NewEncoder(w).Encode(v)
150}
151
152func (s *Server) writeAPIErr(w http.ResponseWriter, r *http.Request, err error) {
153 writeJSON(w, statusOf(err), map[string]any{"message": s.trErr(r, err)})
154}
155
156func (s *Server) apiOK(w http.ResponseWriter, r *http.Request, err error) bool {
157 if err == nil {
158 return true
159 }
160 s.writeAPIErr(w, r, err)
161 return false
162}
163
164func pageQuery(r *http.Request) (page, per int) {
165 page, _ = strconv.Atoi(r.URL.Query().Get("page"))
166 per, _ = strconv.Atoi(r.URL.Query().Get("per_page"))
167 if page < 1 {
168 page = 1
169 }
170 if per < 1 {
171 per = 20
172 }
173 if per > 100 {
174 per = 100
175 }
176 return page, per
177}
178
179func writePage(w http.ResponseWriter, r *http.Request, items any, total, page, per int) {
180 w.Header().Set("X-Total", strconv.Itoa(total))
181 w.Header().Set("X-Page", strconv.Itoa(page))
182 w.Header().Set("X-Per-Page", strconv.Itoa(per))
183 next := ""
184 if page*per < total {
185 next = strconv.Itoa(page + 1)
186 }
187 w.Header().Set("X-Next-Page", next)
188 writeJSON(w, http.StatusOK, items)
189}
190
191func slicePage[T any](items []T, page, per int) []T {
192 if items == nil {
193 items = []T{}
194 }
195 start := (page - 1) * per
196 if start > len(items) {
197 start = len(items)
198 }
199 end := start + per
200 if end > len(items) {
201 end = len(items)
202 }
203 out := items[start:end]
204 if out == nil {
205 out = []T{}
206 }
207 return out
208}
209
210// CallAPI voert een API-verzoek uit als deze gebruiker, zonder cookie.
211// SSH gebruikt hetzelfde pad als een toegangstoken met scope api.
212func (s *Server) CallAPI(ctx context.Context, user store.User, method, path string, body []byte) (int, []byte) {
213 if !strings.HasPrefix(path, "/") {
214 path = "/" + path
215 }
216 if !strings.HasPrefix(path, "/api/") {
217 path = "/api/v1" + path
218 }
219 var rdr io.Reader = http.NoBody
220 if len(body) > 0 {
221 rdr = bytes.NewReader(body)
222 }
223 req := httptest.NewRequest(method, path, rdr).WithContext(context.WithValue(ctx, actorKey{}, apiActor{
224 User: user, Scopes: access.AllScopes(), Via: "ssh",
225 }))
226 req.Header.Set("Content-Type", "application/json")
227 rec := httptest.NewRecorder()
228 s.Handler().ServeHTTP(rec, req)
229 return rec.Code, rec.Body.Bytes()
230}
231
232func (s *Server) openAPI(w http.ResponseWriter, r *http.Request) {
233 writeJSON(w, http.StatusOK, openAPIDoc())
234}
235
236func openAPIDoc() map[string]any {
237 paths := map[string]map[string]any{}
238 for _, rt := range apiCatalog {
239 rel := strings.TrimPrefix(rt.Path, "/api/v1")
240 rel = openAPIPath(rel)
241 item := paths[rel]
242 if item == nil {
243 item = map[string]any{}
244 paths[rel] = item
245 }
246 op := map[string]any{
247 "summary": rt.Summary,
248 "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"}}}}},
249 }
250 if rt.Auth != authPublic {
251 op["security"] = []any{
252 map[string]any{"bearer": []any{}},
253 map[string]any{"privateToken": []any{}},
254 map[string]any{"basic": []any{}},
255 }
256 }
257 item[strings.ToLower(rt.Method)] = op
258 }
259 paths["/openapi.json"] = map[string]any{
260 "get": map[string]any{"summary": "OpenAPI document", "responses": map[string]any{"200": map[string]any{"description": "OK"}}},
261 }
262 out := map[string]any{}
263 for k, v := range paths {
264 out[k] = v
265 }
266 return map[string]any{
267 "openapi": "3.0.3",
268 "info": map[string]any{"title": "BlueGit", "version": "v1"},
269 "servers": []any{map[string]any{"url": "/api/v1"}},
270 "paths": out,
271 "components": map[string]any{
272 "securitySchemes": map[string]any{
273 "bearer": map[string]any{"type": "http", "scheme": "bearer"},
274 "privateToken": map[string]any{"type": "apiKey", "in": "header", "name": "PRIVATE-TOKEN"},
275 "basic": map[string]any{"type": "http", "scheme": "basic"},
276 },
277 "schemas": map[string]any{
278 "Error": map[string]any{"type": "object", "properties": map[string]any{"message": map[string]any{"type": "string"}}},
279 },
280 },
281 }
282}
283
284func openAPIPath(p string) string {
285 var b strings.Builder
286 for i := 0; i < len(p); i++ {
287 if p[i] == '{' {
288 j := strings.IndexByte(p[i:], '}')
289 if j < 0 {
290 b.WriteByte(p[i])
291 continue
292 }
293 name := p[i+1 : i+j]
294 name = strings.TrimSuffix(name, "...")
295 b.WriteByte('{')
296 b.WriteString(name)
297 b.WriteByte('}')
298 i += j
299 continue
300 }
301 b.WriteByte(p[i])
302 }
303 return b.String()
304}
305
306func apiIndex() []byte {
307 type row struct {
308 Method string `json:"method"`
309 Path string `json:"path"`
310 Summary string `json:"summary"`
311 Auth string `json:"auth"`
312 }
313 routes := []row{{Method: http.MethodGet, Path: "/api/v1/openapi.json", Summary: "OpenAPI document", Auth: "public"}}
314 for _, rt := range apiCatalog {
315 auth := "token"
316 if rt.Auth == authPublic {
317 auth = "public"
318 }
319 if rt.Auth == authRelease {
320 auth = "token_or_job"
321 }
322 routes = append(routes, row{Method: rt.Method, Path: rt.Path, Summary: rt.Summary, Auth: auth})
323 }
324 raw, _ := json.Marshal(map[string]any{
325 "openapi": "/api/v1/openapi.json",
326 "auth": []string{"Authorization: Bearer", "PRIVATE-TOKEN", "HTTP basic"},
327 "scopes": []string{access.ScopeAPI, access.ScopeReadAPI, access.ScopeReadRepo, access.ScopeWriteRepo},
328 "ssh": "ssh git@host api METHOD /api/v1/... ",
329 "routes": routes,
330 })
331 return raw
332}