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