BlueGit

timfa bluegit

Files

bluegit / internal / server / api_http.go

api_http.go

fix: houd één writeJSON voor de API
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
a3dee03d History
api_http.go 8.7 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 paths["/openapi.json"] = map[string]any{
261 "get": map[string]any{"summary": "OpenAPI document", "responses": map[string]any{"200": map[string]any{"description": "OK"}}},
262 }
263 out := map[string]any{}
264 for k, v := range paths {
265 out[k] = v
266 }
267 return map[string]any{
268 "openapi": "3.0.3",
269 "info": map[string]any{"title": "BlueGit", "version": "v1"},
270 "servers": []any{map[string]any{"url": "/api/v1"}},
271 "paths": out,
272 "components": map[string]any{
273 "securitySchemes": map[string]any{
274 "bearer": map[string]any{"type": "http", "scheme": "bearer"},
275 "privateToken": map[string]any{"type": "apiKey", "in": "header", "name": "PRIVATE-TOKEN"},
276 "basic": map[string]any{"type": "http", "scheme": "basic"},
277 },
278 "schemas": map[string]any{
279 "Error": map[string]any{"type": "object", "properties": map[string]any{"message": map[string]any{"type": "string"}}},
280 },
281 },
282 }
283}
284
285func openAPIPath(p string) string {
286 var b strings.Builder
287 for i := 0; i < len(p); i++ {
288 if p[i] == '{' {
289 j := strings.IndexByte(p[i:], '}')
290 if j < 0 {
291 b.WriteByte(p[i])
292 continue
293 }
294 name := p[i+1 : i+j]
295 name = strings.TrimSuffix(name, "...")
296 b.WriteByte('{')
297 b.WriteString(name)
298 b.WriteByte('}')
299 i += j
300 continue
301 }
302 b.WriteByte(p[i])
303 }
304 return b.String()
305}
306
307func apiIndex() []byte {
308 type row struct {
309 Method string `json:"method"`
310 Path string `json:"path"`
311 Summary string `json:"summary"`
312 Auth string `json:"auth"`
313 }
314 routes := []row{{Method: http.MethodGet, Path: "/api/v1/openapi.json", Summary: "OpenAPI document", Auth: "public"}}
315 for _, rt := range apiCatalog {
316 auth := "token"
317 if rt.Auth == authPublic {
318 auth = "public"
319 }
320 if rt.Auth == authRelease {
321 auth = "token_or_job"
322 }
323 routes = append(routes, row{Method: rt.Method, Path: rt.Path, Summary: rt.Summary, Auth: auth})
324 }
325 raw, _ := json.Marshal(map[string]any{
326 "openapi": "/api/v1/openapi.json",
327 "auth": []string{"Authorization: Bearer", "PRIVATE-TOKEN", "HTTP basic"},
328 "scopes": []string{access.ScopeAPI, access.ScopeReadAPI, access.ScopeReadRepo, access.ScopeWriteRepo},
329 "ssh": "ssh git@host api METHOD /api/v1/... ",
330 "routes": routes,
331 })
332 return raw
333}