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