internal/httpd/api.go

61564b7c32807deb349e28f2b5c6909cb4143870
gitbay/internal/httpd/api.go history · blame · raw

151 lines · 4676 bytes

  1package httpd
  2
  3import (
  4	"bytes"
  5	"encoding/json"
  6	"errors"
  7	"io"
  8	"net/http"
  9	"strconv"
 10	"strings"
 11
 12	"gitbay.org/gitbay/internal/control"
 13	"gitbay.org/gitbay/internal/protocol"
 14	"gitbay.org/gitbay/internal/store"
 15)
 16
 17// apiRequest is the wire form of one command invocation. argv is real
 18// argv — no shell, no tokenizer, no quoting rules.
 19type apiRequest struct {
 20	Argv  []string `json:"argv"`
 21	Stdin string   `json:"stdin,omitempty"`
 22}
 23
 24const maxAPIBody = 1 << 20
 25
 26// apiCmd fronts the same control-command registry the SSH dispatcher uses:
 27// every command, current and future, is reachable here with identical
 28// semantics. Exit codes map onto HTTP statuses; the body is the command's
 29// JSON envelope with exit_code added.
 30func (s *Server) apiCmd(w http.ResponseWriter, r *http.Request) {
 31	user, scope, ok := s.apiAuth(w, r)
 32	if !ok {
 33		return
 34	}
 35
 36	var req apiRequest
 37	if err := json.NewDecoder(io.LimitReader(r.Body, maxAPIBody)).Decode(&req); err != nil {
 38		apiError(w, http.StatusBadRequest, "body must be JSON: {\"argv\": [...], \"stdin\": \"...\"}")
 39		return
 40	}
 41	if len(req.Argv) == 0 {
 42		apiError(w, http.StatusBadRequest, "argv is required")
 43		return
 44	}
 45	switch req.Argv[0] {
 46	case "git-upload-pack", "git-receive-pack", "git-upload-archive":
 47		apiError(w, http.StatusBadRequest, "git transport does not run over the JSON API; use git with an SSH remote")
 48		return
 49	}
 50
 51	// Rate limit after auth so the bucket follows the token rather than the
 52	// network, but before dispatch so a rejected call costs nothing beyond
 53	// the lookup. A write draws on a separate, smaller budget.
 54	write := true
 55	if cmd, _, ok := control.Lookup(req.Argv); ok {
 56		write = !cmd.ReadOnly
 57	}
 58	if allowed, wait := s.apiLimit.allow(s.limitKey(r, user), write); !allowed {
 59		tooManyRequests(w, wait)
 60		return
 61	}
 62
 63	var stdout, stderr bytes.Buffer
 64	ctx := &control.Ctx{
 65		User:     user,
 66		Source:   "api",
 67		Scope:    "full", // key scopes are an SSH concept; token scope is below
 68		Store:    s.st,
 69		Cfg:      s.cfg,
 70		Stdin:    strings.NewReader(req.Stdin),
 71		Stdout:   &stdout,
 72		Stderr:   &stderr,
 73		JSON:     true,
 74		ViaAPI:   true,
 75		ReadOnly: scope == "read",
 76	}
 77	code := control.Dispatch(ctx, req.Argv)
 78
 79	status := statusForExit(code)
 80
 81	// Commands normally emit exactly one JSON envelope; inject exit_code.
 82	// A few (mr diff, repo download) write raw bytes instead — wrap those.
 83	var body map[string]any
 84	if err := json.Unmarshal(stdout.Bytes(), &body); err != nil || body == nil {
 85		body = map[string]any{
 86			"protocol_version": protocol.Version,
 87			"output":           stdout.String(),
 88		}
 89	}
 90	body["exit_code"] = code
 91	if msg := strings.TrimSpace(stderr.String()); msg != "" {
 92		body["stderr"] = msg
 93	}
 94	w.Header().Set("Content-Type", "application/json")
 95	w.WriteHeader(status)
 96	json.NewEncoder(w).Encode(body)
 97}
 98
 99// statusForExit maps a command's exit code onto an HTTP status, shared by
100// both API surfaces so they cannot answer the same failure differently.
101func statusForExit(code int) int {
102	switch code {
103	case protocol.ExitOK:
104		return http.StatusOK
105	case protocol.ExitUsage:
106		return http.StatusBadRequest
107	case protocol.ExitNotFound:
108		return http.StatusNotFound
109	case protocol.ExitDenied:
110		return http.StatusForbidden
111	}
112	return http.StatusInternalServerError
113}
114
115// limitKey buckets an authenticated caller by account, so rotating tokens
116// buys no extra budget, and everyone else by peer address.
117func (s *Server) limitKey(r *http.Request, user store.User) string {
118	if user.ID != 0 {
119		return "u" + strconv.FormatInt(user.ID, 10)
120	}
121	return "ip" + s.clientIP(r)
122}
123
124// apiAuth resolves the bearer token; failures are uniform 401s.
125func (s *Server) apiAuth(w http.ResponseWriter, r *http.Request) (store.User, string, bool) {
126	token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
127	if !ok || token == "" {
128		w.Header().Set("WWW-Authenticate", `Bearer realm="gitbay api"`)
129		apiError(w, http.StatusUnauthorized, "missing bearer token; mint one over SSH: token create --name <n>")
130		return store.User{}, "", false
131	}
132	user, scope, err := s.st.APITokenUser(store.HashToken(strings.TrimSpace(token)))
133	if err != nil {
134		if errors.Is(err, store.ErrNotFound) {
135			apiError(w, http.StatusUnauthorized, "invalid or expired token")
136			return store.User{}, "", false
137		}
138		apiError(w, http.StatusInternalServerError, "internal error")
139		return store.User{}, "", false
140	}
141	return user, scope, true
142}
143
144func apiError(w http.ResponseWriter, status int, msg string) {
145	w.Header().Set("Content-Type", "application/json")
146	w.WriteHeader(status)
147	json.NewEncoder(w).Encode(map[string]any{
148		"protocol_version": protocol.Version,
149		"error":            msg,
150	})
151}