BlueGit

timfa bluegit

Files

bluegit / internal / server / api_http.go

api_http.go

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