internal/httpd/api.go

153 lines · 4724 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		Done:     s.until(r),
 77		Stopping: s.stopping,
 78	}
 79	code := control.Dispatch(ctx, req.Argv)
 80
 81	status := statusForExit(code)
 82
 83	// Commands normally emit exactly one JSON envelope; inject exit_code.
 84	// A few (mr diff, repo download) write raw bytes instead — wrap those.
 85	var body map[string]any
 86	if err := json.Unmarshal(stdout.Bytes(), &body); err != nil || body == nil {
 87		body = map[string]any{
 88			"protocol_version": protocol.Version,
 89			"output":           stdout.String(),
 90		}
 91	}
 92	body["exit_code"] = code
 93	if msg := strings.TrimSpace(stderr.String()); msg != "" {
 94		body["stderr"] = msg
 95	}
 96	w.Header().Set("Content-Type", "application/json")
 97	w.WriteHeader(status)
 98	json.NewEncoder(w).Encode(body)
 99}
100
101// statusForExit maps a command's exit code onto an HTTP status, shared by
102// both API surfaces so they cannot answer the same failure differently.
103func statusForExit(code int) int {
104	switch code {
105	case protocol.ExitOK:
106		return http.StatusOK
107	case protocol.ExitUsage:
108		return http.StatusBadRequest
109	case protocol.ExitNotFound:
110		return http.StatusNotFound
111	case protocol.ExitDenied:
112		return http.StatusForbidden
113	}
114	return http.StatusInternalServerError
115}
116
117// limitKey buckets an authenticated caller by account, so rotating tokens
118// buys no extra budget, and everyone else by peer address.
119func (s *Server) limitKey(r *http.Request, user store.User) string {
120	if user.ID != 0 {
121		return "u" + strconv.FormatInt(user.ID, 10)
122	}
123	return "ip" + s.clientIP(r)
124}
125
126// apiAuth resolves the bearer token; failures are uniform 401s.
127func (s *Server) apiAuth(w http.ResponseWriter, r *http.Request) (store.User, string, bool) {
128	token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
129	if !ok || token == "" {
130		w.Header().Set("WWW-Authenticate", `Bearer realm="gitbay api"`)
131		apiError(w, http.StatusUnauthorized, "missing bearer token; mint one over SSH: token create --name <n>")
132		return store.User{}, "", false
133	}
134	user, scope, err := s.st.APITokenUser(store.HashToken(strings.TrimSpace(token)))
135	if err != nil {
136		if errors.Is(err, store.ErrNotFound) {
137			apiError(w, http.StatusUnauthorized, "invalid or expired token")
138			return store.User{}, "", false
139		}
140		apiError(w, http.StatusInternalServerError, "internal error")
141		return store.User{}, "", false
142	}
143	return user, scope, true
144}
145
146func apiError(w http.ResponseWriter, status int, msg string) {
147	w.Header().Set("Content-Type", "application/json")
148	w.WriteHeader(status)
149	json.NewEncoder(w).Encode(map[string]any{
150		"protocol_version": protocol.Version,
151		"error":            msg,
152	})
153}