BlueGit

timfa bluegit

Files

bluegit / internal / server / api_http.go

api_http.go

feat: beschrijf de API-objecten en geef ze een web_url
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
Passed 2f39b617 History
api_http.go 9.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 "GET /api/v1/repos/{owner}/{repo}/issues",
55 "POST /api/v1/repos/{owner}/{repo}/issues",
56 "GET /api/v1/repos/{owner}/{repo}/issues/{number}",
57 "PUT /api/v1/repos/{owner}/{repo}/issues/{number}",
58 "DELETE /api/v1/repos/{owner}/{repo}/issues/{number}",
59 "POST /api/v1/repos/{owner}/{repo}/issues/{number}/notes":
60 return true
61 default:
62 return false
63 }
64}
65
66func (s *Server) mountAPI(mux *http.ServeMux) {
67 mux.HandleFunc("GET /api/v1/openapi.json", func(w http.ResponseWriter, r *http.Request) {
68 s.serveAPI(w, r, apiRoute{Method: http.MethodGet, Path: "/api/v1/openapi.json", Class: access.ScopePublic, Auth: authPublic, Summary: "OpenAPI document", Handler: (*Server).openAPI})
69 })
70 for _, rt := range apiCatalog {
71 rt := rt
72 if apiRouteTaken(rt.Method, rt.Path) {
73 continue
74 }
75 mux.HandleFunc(rt.Method+" "+rt.Path, func(w http.ResponseWriter, r *http.Request) {
76 s.serveAPI(w, r, rt)
77 })
78 }
79}
80
81func (s *Server) serveAPI(w http.ResponseWriter, r *http.Request, rt apiRoute) {
82 w.Header().Set("Cache-Control", "no-store")
83 if rt.Auth == authPublic {
84 rt.Handler(s, w, r)
85 return
86 }
87 if rt.Auth == authRelease {
88 tok := tokenFrom(r)
89 if strings.HasPrefix(tok, "bgj_") {
90 rt.Handler(s, w, r)
91 return
92 }
93 }
94 actor, ok := r.Context().Value(actorKey{}).(apiActor)
95 if !ok {
96 tok := tokenFrom(r)
97 if tok == "" || !strings.HasPrefix(tok, "bg_") {
98 s.writeAPIErr(w, r, fail(http.StatusUnauthorized, i18n.E("err.apiAuth")))
99 return
100 }
101 auth, err := s.Store.AuthenticateToken(r.Context(), tok)
102 if err != nil {
103 s.writeAPIErr(w, r, fail(http.StatusUnauthorized, err))
104 return
105 }
106 actor = apiActor{User: auth.User, Scopes: access.StoredScopes(auth.Token.Scopes), Via: "token"}
107 }
108 if !actor.Scopes.Allows(rt.Class) {
109 s.writeAPIErr(w, r, fail(http.StatusForbidden, i18n.E("err.apiScope")))
110 return
111 }
112 ctx := context.WithValue(r.Context(), ctxKey{}, principal{User: actor.User, OK: true})
113 ctx = context.WithValue(ctx, actorKey{}, actor)
114 rt.Handler(s, w, r.WithContext(ctx))
115}
116
117func tokenFrom(r *http.Request) string {
118 if t := strings.TrimSpace(r.Header.Get("PRIVATE-TOKEN")); t != "" {
119 return t
120 }
121 if t := bearer(r); t != "" {
122 return t
123 }
124 _, pass, ok := r.BasicAuth()
125 if ok {
126 return pass
127 }
128 return ""
129}
130
131func apiUser(r *http.Request) store.User {
132 a, _ := r.Context().Value(actorKey{}).(apiActor)
133 return a.User
134}
135
136func readJSON(r *http.Request, dst any) error {
137 if r.Body == nil {
138 return nil
139 }
140 dec := json.NewDecoder(io.LimitReader(r.Body, 1<<20))
141 err := dec.Decode(dst)
142 if err == io.EOF {
143 return nil
144 }
145 return err
146}
147
148func writeJSON(w http.ResponseWriter, status int, v any) {
149 if status == http.StatusNoContent {
150 w.WriteHeader(status)
151 return
152 }
153 w.Header().Set("Content-Type", "application/json; charset=utf-8")
154 w.Header().Set("Cache-Control", "no-store")
155 w.WriteHeader(status)
156 _ = json.NewEncoder(w).Encode(v)
157}
158
159func (s *Server) writeAPIErr(w http.ResponseWriter, r *http.Request, err error) {
160 writeJSON(w, statusOf(err), map[string]any{"message": s.trErr(r, err)})
161}
162
163func (s *Server) apiOK(w http.ResponseWriter, r *http.Request, err error) bool {
164 if err == nil {
165 return true
166 }
167 s.writeAPIErr(w, r, err)
168 return false
169}
170
171func pageQuery(r *http.Request) (page, per int) {
172 page, _ = strconv.Atoi(r.URL.Query().Get("page"))
173 per, _ = strconv.Atoi(r.URL.Query().Get("per_page"))
174 if page < 1 {
175 page = 1
176 }
177 if per < 1 {
178 per = 20
179 }
180 if per > 100 {
181 per = 100
182 }
183 return page, per
184}
185
186func writePage(w http.ResponseWriter, r *http.Request, items any, total, page, per int) {
187 w.Header().Set("X-Total", strconv.Itoa(total))
188 w.Header().Set("X-Page", strconv.Itoa(page))
189 w.Header().Set("X-Per-Page", strconv.Itoa(per))
190 next := ""
191 if page*per < total {
192 next = strconv.Itoa(page + 1)
193 }
194 w.Header().Set("X-Next-Page", next)
195 writeJSON(w, http.StatusOK, items)
196}
197
198func slicePage[T any](items []T, page, per int) []T {
199 if items == nil {
200 items = []T{}
201 }
202 start := (page - 1) * per
203 if start > len(items) {
204 start = len(items)
205 }
206 end := start + per
207 if end > len(items) {
208 end = len(items)
209 }
210 out := items[start:end]
211 if out == nil {
212 out = []T{}
213 }
214 return out
215}
216
217// CallAPI voert een API-verzoek uit als deze gebruiker, zonder cookie.
218// SSH gebruikt hetzelfde pad als een toegangstoken met scope api.
219func (s *Server) CallAPI(ctx context.Context, user store.User, method, path string, body []byte) (int, []byte) {
220 if !strings.HasPrefix(path, "/") {
221 path = "/" + path
222 }
223 if !strings.HasPrefix(path, "/api/") {
224 path = "/api/v1" + path
225 }
226 var rdr io.Reader = http.NoBody
227 if len(body) > 0 {
228 rdr = bytes.NewReader(body)
229 }
230 req := httptest.NewRequest(method, path, rdr).WithContext(context.WithValue(ctx, actorKey{}, apiActor{
231 User: user, Scopes: access.AllScopes(), Via: "ssh",
232 }))
233 req.Header.Set("Content-Type", "application/json")
234 rec := httptest.NewRecorder()
235 s.Handler().ServeHTTP(rec, req)
236 return rec.Code, rec.Body.Bytes()
237}
238
239func (s *Server) openAPI(w http.ResponseWriter, r *http.Request) {
240 writeJSON(w, http.StatusOK, openAPIDoc())
241}
242
243func openAPIDoc() map[string]any {
244 paths := map[string]map[string]any{}
245 for _, rt := range apiCatalog {
246 rel := strings.TrimPrefix(rt.Path, "/api/v1")
247 rel = openAPIPath(rel)
248 item := paths[rel]
249 if item == nil {
250 item = map[string]any{}
251 paths[rel] = item
252 }
253 op := map[string]any{
254 "summary": rt.Summary,
255 "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"}}}}},
256 }
257 if rt.Auth != authPublic {
258 op["security"] = []any{
259 map[string]any{"bearer": []any{}},
260 map[string]any{"privateToken": []any{}},
261 map[string]any{"basic": []any{}},
262 }
263 }
264 item[strings.ToLower(rt.Method)] = op
265 }
266 schemas := map[string]any{
267 "Error": map[string]any{"type": "object", "properties": map[string]any{"message": map[string]any{"type": "string"}}},
268 }
269 decorateAPI(paths, schemas)
270 paths["/openapi.json"] = map[string]any{
271 "get": map[string]any{"summary": "OpenAPI document", "responses": map[string]any{"200": map[string]any{"description": "OK"}}},
272 }
273 out := map[string]any{}
274 for k, v := range paths {
275 out[k] = v
276 }
277 return map[string]any{
278 "openapi": "3.0.3",
279 "info": map[string]any{"title": "BlueGit", "version": "v1"},
280 "servers": []any{map[string]any{"url": "/api/v1"}},
281 "paths": out,
282 "components": map[string]any{
283 "securitySchemes": map[string]any{
284 "bearer": map[string]any{"type": "http", "scheme": "bearer"},
285 "privateToken": map[string]any{"type": "apiKey", "in": "header", "name": "PRIVATE-TOKEN"},
286 "basic": map[string]any{"type": "http", "scheme": "basic"},
287 },
288 "schemas": schemas,
289 },
290 }
291}
292
293func openAPIPath(p string) string {
294 var b strings.Builder
295 for i := 0; i < len(p); i++ {
296 if p[i] == '{' {
297 j := strings.IndexByte(p[i:], '}')
298 if j < 0 {
299 b.WriteByte(p[i])
300 continue
301 }
302 name := p[i+1 : i+j]
303 name = strings.TrimSuffix(name, "...")
304 b.WriteByte('{')
305 b.WriteString(name)
306 b.WriteByte('}')
307 i += j
308 continue
309 }
310 b.WriteByte(p[i])
311 }
312 return b.String()
313}
314
315func apiIndex() []byte {
316 type row struct {
317 Method string `json:"method"`
318 Path string `json:"path"`
319 Summary string `json:"summary"`
320 Auth string `json:"auth"`
321 }
322 routes := []row{{Method: http.MethodGet, Path: "/api/v1/openapi.json", Summary: "OpenAPI document", Auth: "public"}}
323 for _, rt := range apiCatalog {
324 auth := "token"
325 if rt.Auth == authPublic {
326 auth = "public"
327 }
328 if rt.Auth == authRelease {
329 auth = "token_or_job"
330 }
331 routes = append(routes, row{Method: rt.Method, Path: rt.Path, Summary: rt.Summary, Auth: auth})
332 }
333 raw, _ := json.Marshal(map[string]any{
334 "openapi": "/api/v1/openapi.json",
335 "auth": []string{"Authorization: Bearer", "PRIVATE-TOKEN", "HTTP basic"},
336 "scopes": []string{access.ScopeAPI, access.ScopeReadAPI, access.ScopeReadRepo, access.ScopeWriteRepo},
337 "ssh": "ssh git@host api METHOD /api/v1/... ",
338 "routes": routes,
339 })
340 return raw
341}