internal/httpd/lfs.go
271 lines · 8671 bytes
1package httpd
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "strings"
9 "time"
10
11 "gitbay.org/gitbay/internal/lfs"
12 "gitbay.org/gitbay/internal/policy"
13 "gitbay.org/gitbay/internal/store"
14)
15
16// Git LFS server: the batch API plus basic-transfer endpoints. SSH clients
17// arrive with a token minted by git-lfs-authenticate; anonymous HTTPS
18// clients may download from public repositories, mirroring the smart-http
19// read-only rule. Uploads always require an upload token.
20
21const lfsMediaType = "application/vnd.git-lfs+json"
22
23func (s *Server) lfsStore() lfs.BlobStore {
24 return lfs.LocalStore{Root: lfs.RootFor(s.cfg.LFS.Root, s.cfg.Server.Root)}
25}
26
27func (s *Server) lfsMaxObject() int64 {
28 if s.cfg.LFS.MaxObjectBytes > 0 {
29 return s.cfg.LFS.MaxObjectBytes
30 }
31 return 512 << 20
32}
33
34func (s *Server) lfsSecret() ([]byte, error) {
35 v, err := s.st.LFSSecret(lfs.NewSecret)
36 return []byte(v), err
37}
38
39// lfsAuth resolves what the request may do to the repo: "upload",
40// "download", or "" for no access, and the key the grant rests on (0
41// for none). A token is bound to the SSH key that obtained it and
42// works only while that key is registered, unexpired and on an enabled
43// account, and while the key still has the access its operation needs
44// on the repo (#285). Without one, public repos allow anonymous
45// download only.
46func (s *Server) lfsAuth(r *http.Request, repo store.Repo) (string, int64) {
47 auth := r.Header.Get("Authorization")
48 if tok, ok := strings.CutPrefix(auth, "Bearer "); ok {
49 secret, err := s.lfsSecret()
50 if err != nil {
51 return "", 0
52 }
53 g, ok := lfs.Verify(secret, tok, time.Now())
54 if !ok || g.RepoID != repo.ID {
55 return "", 0
56 }
57 if g.KeyID == 0 {
58 // Minted by an anonymous batch: worth what anonymous is.
59 if g.Op == "download" && repo.Visibility == "public" {
60 return "download", 0
61 }
62 return "", 0
63 }
64 live, err := s.st.LiveSSHKeys([]int64{g.KeyID})
65 if err != nil || !live[g.KeyID] || !s.lfsKeyAllows(g.KeyID, repo, g.Op == "upload") {
66 return "", 0
67 }
68 return g.Op, g.KeyID
69 }
70 if repo.Visibility == "public" {
71 return "download", 0
72 }
73 return "", 0
74}
75
76// lfsKeyAllows repeats git-lfs-authenticate's access check for the key
77// now: a deploy key by its binding, any other key by its account's
78// access narrowed by the key's scope. An archived repo takes no uploads.
79func (s *Server) lfsKeyAllows(keyID int64, repo store.Repo, write bool) bool {
80 if write && repo.Settings.Archived {
81 return false
82 }
83 key, err := s.st.SSHKeyByID(keyID)
84 if err != nil {
85 return false
86 }
87 if policy.IsDeployScope(key.Scope) {
88 return policy.DeployScopeAllows(key.Scope, repo.ID, write)
89 }
90 user, err := s.st.UserByID(key.UserID)
91 if err != nil {
92 return false
93 }
94 grant, err := s.st.AccessRole(repo.ID, user.ID)
95 if err != nil {
96 return false
97 }
98 if !policy.CanRead(user, repo, grant) || !policy.ScopeAllowsGit(key.Scope, repo.Path(), write) {
99 return false
100 }
101 return !write || policy.CanWrite(user, repo, grant)
102}
103
104func lfsError(w http.ResponseWriter, code int, msg string) {
105 w.Header().Set("Content-Type", lfsMediaType)
106 w.WriteHeader(code)
107 json.NewEncoder(w).Encode(map[string]string{"message": msg})
108}
109
110type lfsBatchReq struct {
111 Operation string `json:"operation"`
112 Transfers []string `json:"transfers"`
113 Objects []struct {
114 OID string `json:"oid"`
115 Size int64 `json:"size"`
116 } `json:"objects"`
117}
118
119type lfsAction struct {
120 Href string `json:"href"`
121 Header map[string]string `json:"header,omitempty"`
122 ExpiresIn int `json:"expires_in,omitempty"`
123}
124
125type lfsObject struct {
126 OID string `json:"oid"`
127 Size int64 `json:"size"`
128 Authenticated bool `json:"authenticated,omitempty"`
129 Actions map[string]lfsAction `json:"actions,omitempty"`
130 Error *struct {
131 Code int `json:"code"`
132 Message string `json:"message"`
133 } `json:"error,omitempty"`
134}
135
136// lfsBatch answers POST /{owner}/{repo}/info/lfs/objects/batch.
137func (s *Server) lfsBatch(w http.ResponseWriter, r *http.Request) {
138 repo, err := s.st.RepoByPath(r.PathValue("owner") + "/" + r.PathValue("repo"))
139 if err != nil {
140 lfsError(w, http.StatusNotFound, "repository not found")
141 return
142 }
143 granted, keyID := s.lfsAuth(r, repo)
144 if granted == "" {
145 // Not naming whether the repo exists, per the enumeration rule.
146 lfsError(w, http.StatusNotFound, "repository not found")
147 return
148 }
149 var req lfsBatchReq
150 if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req); err != nil {
151 lfsError(w, http.StatusBadRequest, "bad batch request")
152 return
153 }
154 if req.Operation != "download" && req.Operation != "upload" {
155 lfsError(w, http.StatusBadRequest, "operation must be download or upload")
156 return
157 }
158 if req.Operation == "upload" && granted != "upload" {
159 lfsError(w, http.StatusForbidden, "upload requires write access (authenticate over SSH)")
160 return
161 }
162 if len(req.Objects) > 1000 {
163 lfsError(w, http.StatusUnprocessableEntity, "too many objects in one batch")
164 return
165 }
166
167 // The token in transfer hrefs is operation-scoped and freshly minted,
168 // so anonymous downloads work without the client sending one back.
169 secret, err := s.lfsSecret()
170 if err != nil {
171 lfsError(w, http.StatusInternalServerError, "lfs secret unavailable")
172 return
173 }
174 transferToken := lfs.Sign(secret, repo.ID, keyID, req.Operation, time.Now())
175 base := fmt.Sprintf("%s/%s/%s.git/info/lfs/objects",
176 strings.TrimSuffix(s.cfg.Server.SiteURL, "/"), repo.OwnerName, repo.Name)
177 authHeader := map[string]string{"Authorization": "Bearer " + transferToken}
178
179 blobs := s.lfsStore()
180 out := struct {
181 Transfer string `json:"transfer"`
182 Objects []lfsObject `json:"objects"`
183 }{Transfer: "basic"}
184 for _, o := range req.Objects {
185 obj := lfsObject{OID: o.OID, Size: o.Size, Authenticated: true}
186 switch {
187 case !lfs.OIDPat.MatchString(o.OID) || o.Size < 0:
188 obj.Error = &struct {
189 Code int `json:"code"`
190 Message string `json:"message"`
191 }{422, "malformed object"}
192 case req.Operation == "download":
193 if size, ok := blobs.Exists(o.OID); ok {
194 obj.Size = size
195 obj.Actions = map[string]lfsAction{"download": {
196 Href: base + "/" + o.OID, Header: authHeader, ExpiresIn: int(lfs.TokenTTL.Seconds()),
197 }}
198 } else {
199 obj.Error = &struct {
200 Code int `json:"code"`
201 Message string `json:"message"`
202 }{404, "object not found"}
203 }
204 default: // upload
205 if o.Size > s.lfsMaxObject() {
206 obj.Error = &struct {
207 Code int `json:"code"`
208 Message string `json:"message"`
209 }{422, fmt.Sprintf("object exceeds the %d byte limit", s.lfsMaxObject())}
210 } else if _, ok := blobs.Exists(o.OID); !ok {
211 // Present objects get no actions: the client skips them.
212 obj.Actions = map[string]lfsAction{"upload": {
213 Href: base + "/" + o.OID, Header: authHeader, ExpiresIn: int(lfs.TokenTTL.Seconds()),
214 }}
215 }
216 }
217 out.Objects = append(out.Objects, obj)
218 }
219 w.Header().Set("Content-Type", lfsMediaType)
220 json.NewEncoder(w).Encode(out)
221}
222
223// lfsDownload answers GET /{owner}/{repo}/info/lfs/objects/{oid}.
224func (s *Server) lfsDownload(w http.ResponseWriter, r *http.Request) {
225 repo, err := s.st.RepoByPath(r.PathValue("owner") + "/" + r.PathValue("repo"))
226 if err != nil {
227 lfsError(w, http.StatusNotFound, "not found")
228 return
229 }
230 if op, _ := s.lfsAuth(r, repo); op == "" {
231 lfsError(w, http.StatusNotFound, "not found")
232 return
233 }
234 rc, size, err := s.lfsStore().Get(r.PathValue("oid"))
235 if err != nil {
236 lfsError(w, http.StatusNotFound, "object not found")
237 return
238 }
239 defer rc.Close()
240 w.Header().Set("Content-Type", "application/octet-stream")
241 w.Header().Set("Content-Length", fmt.Sprint(size))
242 w.Header().Set("X-Content-Type-Options", "nosniff")
243 io.Copy(w, rc)
244}
245
246// lfsUpload answers PUT /{owner}/{repo}/info/lfs/objects/{oid}.
247func (s *Server) lfsUpload(w http.ResponseWriter, r *http.Request) {
248 repo, err := s.st.RepoByPath(r.PathValue("owner") + "/" + r.PathValue("repo"))
249 if err != nil {
250 lfsError(w, http.StatusNotFound, "not found")
251 return
252 }
253 if op, _ := s.lfsAuth(r, repo); op != "upload" {
254 lfsError(w, http.StatusNotFound, "not found")
255 return
256 }
257 oid := r.PathValue("oid")
258 if r.ContentLength < 0 || r.ContentLength > s.lfsMaxObject() {
259 lfsError(w, http.StatusRequestEntityTooLarge, "object too large or length unknown")
260 return
261 }
262 if _, ok := s.lfsStore().Exists(oid); ok {
263 w.WriteHeader(http.StatusOK) // already have it; idempotent
264 return
265 }
266 if err := s.lfsStore().Put(oid, r.Body, r.ContentLength); err != nil {
267 lfsError(w, http.StatusUnprocessableEntity, err.Error())
268 return
269 }
270 w.WriteHeader(http.StatusOK)
271}