-
Notifications
You must be signed in to change notification settings - Fork 163
/
server.go
679 lines (551 loc) · 16.7 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
package main
import (
"crypto/rand"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/gorilla/context"
"github.com/gorilla/mux"
)
// RequestVars contain variables from the HTTP request. Variables from routing, json body decoding, and
// some headers are stored.
type RequestVars struct {
Oid string
Size int64
User string
Password string
Repo string
Authorization string
}
type BatchVars struct {
Transfers []string `json:"transfers,omitempty"`
Operation string `json:"operation"`
Objects []*RequestVars `json:"objects"`
}
// MetaObject is object metadata as seen by the object and metadata stores.
type MetaObject struct {
Oid string `json:"oid"`
Size int64 `json:"size"`
Existing bool
}
type BatchResponse struct {
Transfer string `json:"transfer,omitempty"`
Objects []*Representation `json:"objects"`
}
// Representation is object medata as seen by clients of the lfs server.
type Representation struct {
Oid string `json:"oid"`
Size int64 `json:"size"`
Actions map[string]*link `json:"actions"`
Error *ObjectError `json:"error,omitempty"`
}
type ObjectError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type User struct {
Name string `json:"name"`
}
type Lock struct {
Id string `json:"id"`
Path string `json:"path"`
Owner User `json:"owner"`
LockedAt time.Time `json:"locked_at"`
}
type LockRequest struct {
Path string `json:"path"`
}
type LockResponse struct {
Lock *Lock `json:"lock"`
Message string `json:"message,omitempty"`
}
type UnlockRequest struct {
Force bool `json:"force"`
}
type UnlockResponse struct {
Lock *Lock `json:"lock"`
Message string `json:"message,omitempty"`
}
type LockList struct {
Locks []Lock `json:"locks"`
NextCursor string `json:"next_cursor,omitempty"`
Message string `json:"message,omitempty"`
}
type VerifiableLockRequest struct {
Cursor string `json:"cursor,omitempty"`
Limit int `json:"limit,omitempty"`
}
type VerifiableLockList struct {
Ours []Lock `json:"ours"`
Theirs []Lock `json:"theirs"`
NextCursor string `json:"next_cursor,omitempty"`
Message string `json:"message,omitempty"`
}
// DownloadLink builds a URL to download the object.
func (v *RequestVars) DownloadLink() string {
return v.internalLink("objects")
}
// UploadLink builds a URL to upload the object.
func (v *RequestVars) UploadLink(useTus bool) string {
if useTus {
return v.tusLink()
}
return v.internalLink("objects")
}
func (v *RequestVars) internalLink(subpath string) string {
path := ""
if len(v.User) > 0 {
path += fmt.Sprintf("/%s", v.User)
}
if len(v.Repo) > 0 {
path += fmt.Sprintf("/%s", v.Repo)
}
path += fmt.Sprintf("/%s/%s", subpath, v.Oid)
return fmt.Sprintf("%s%s", Config.ExtOrigin, path)
}
func (v *RequestVars) tusLink() string {
link, err := tusServer.Create(v.Oid, v.Size)
if err != nil {
logger.Fatal(kv{"fn": fmt.Sprintf("Unable to create tus link for %s: %v", v.Oid, err)})
}
return link
}
func (v *RequestVars) VerifyLink() string {
path := fmt.Sprintf("/verify/%s", v.Oid)
return fmt.Sprintf("%s%s", Config.ExtOrigin, path)
}
// link provides a structure used to build a hypermedia representation of an HTTP link.
type link struct {
Href string `json:"href"`
Header map[string]string `json:"header,omitempty"`
ExpiresAt time.Time `json:"expires_at,omitempty"`
}
// App links a Router, ContentStore, and MetaStore to provide the LFS server.
type App struct {
router *mux.Router
contentStore *ContentStore
metaStore *MetaStore
}
// NewApp creates a new App using the ContentStore and MetaStore provided
func NewApp(content *ContentStore, meta *MetaStore) *App {
app := &App{contentStore: content, metaStore: meta}
r := mux.NewRouter()
r.HandleFunc("/{user}/{repo}/objects/batch", app.requireAuth(app.BatchHandler)).Methods("POST").MatcherFunc(MetaMatcher)
route := "/{user}/{repo}/objects/{oid}"
r.HandleFunc(route, app.requireAuth(app.GetContentHandler)).Methods("GET", "HEAD").MatcherFunc(ContentMatcher)
r.HandleFunc(route, app.requireAuth(app.GetMetaHandler)).Methods("GET", "HEAD").MatcherFunc(MetaMatcher)
r.HandleFunc(route, app.requireAuth(app.PutHandler)).Methods("PUT").MatcherFunc(ContentMatcher)
r.HandleFunc("/{user}/{repo}/objects", app.requireAuth(app.PostHandler)).Methods("POST").MatcherFunc(MetaMatcher)
r.HandleFunc("/{user}/{repo}/locks", app.requireAuth(app.LocksHandler)).Methods("GET").MatcherFunc(MetaMatcher)
r.HandleFunc("/{user}/{repo}/locks/verify", app.requireAuth(app.LocksVerifyHandler)).Methods("POST").MatcherFunc(MetaMatcher)
r.HandleFunc("/{user}/{repo}/locks", app.requireAuth(app.CreateLockHandler)).Methods("POST").MatcherFunc(MetaMatcher)
r.HandleFunc("/{user}/{repo}/locks/{id}/unlock", app.requireAuth(app.DeleteLockHandler)).Methods("POST").MatcherFunc(MetaMatcher)
r.HandleFunc("/objects/batch", app.requireAuth(app.BatchHandler)).Methods("POST").MatcherFunc(MetaMatcher)
route = "/objects/{oid}"
r.HandleFunc(route, app.requireAuth(app.GetContentHandler)).Methods("GET", "HEAD").MatcherFunc(ContentMatcher)
r.HandleFunc(route, app.requireAuth(app.GetMetaHandler)).Methods("GET", "HEAD").MatcherFunc(MetaMatcher)
r.HandleFunc(route, app.requireAuth(app.PutHandler)).Methods("PUT").MatcherFunc(ContentMatcher)
r.HandleFunc("/objects", app.requireAuth(app.PostHandler)).Methods("POST").MatcherFunc(MetaMatcher)
r.HandleFunc("/verify/{oid}", app.VerifyHandler).Methods("POST")
app.addMgmt(r)
app.router = r
return app
}
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b := make([]byte, 16)
_, err := rand.Read(b)
if err == nil {
context.Set(r, "RequestID", fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]))
}
a.router.ServeHTTP(w, r)
}
// Serve calls http.Serve with the provided Listener and the app's router
func (a *App) Serve(l net.Listener) error {
return http.Serve(l, a)
}
// GetContentHandler gets the content from the content store
func (a *App) GetContentHandler(w http.ResponseWriter, r *http.Request) {
rv := unpack(r)
meta, err := a.metaStore.Get(rv)
if err != nil {
writeStatus(w, r, 404)
return
}
// Support resume download using Range header
var fromByte int64
statusCode := 200
if rangeHdr := r.Header.Get("Range"); rangeHdr != "" {
regex := regexp.MustCompile(`bytes=(\d+)\-.*`)
match := regex.FindStringSubmatch(rangeHdr)
if match != nil && len(match) > 1 {
statusCode = 206
fromByte, _ = strconv.ParseInt(match[1], 10, 64)
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", fromByte, meta.Size-1, int64(meta.Size)-fromByte))
}
}
content, err := a.contentStore.Get(meta, fromByte)
if err != nil {
writeStatus(w, r, 404)
return
}
defer content.Close()
w.WriteHeader(statusCode)
io.Copy(w, content)
logRequest(r, statusCode)
}
// GetMetaHandler retrieves metadata about the object
func (a *App) GetMetaHandler(w http.ResponseWriter, r *http.Request) {
rv := unpack(r)
meta, err := a.metaStore.Get(rv)
if err != nil {
writeStatus(w, r, 404)
return
}
w.Header().Set("Content-Type", metaMediaType)
if r.Method == "GET" {
enc := json.NewEncoder(w)
enc.Encode(a.Represent(rv, meta, true, false, false))
}
logRequest(r, 200)
}
// PostHandler instructs the client how to upload data
func (a *App) PostHandler(w http.ResponseWriter, r *http.Request) {
rv := unpack(r)
meta, err := a.metaStore.Put(rv)
if err != nil {
writeStatus(w, r, 404)
return
}
w.Header().Set("Content-Type", metaMediaType)
sentStatus := 202
if meta.Existing && a.contentStore.Exists(meta) {
sentStatus = 200
}
w.WriteHeader(sentStatus)
enc := json.NewEncoder(w)
enc.Encode(a.Represent(rv, meta, meta.Existing, true, false))
logRequest(r, sentStatus)
}
// BatchHandler provides the batch api
func (a *App) BatchHandler(w http.ResponseWriter, r *http.Request) {
bv := unpackBatch(r)
var responseObjects []*Representation
var useTus bool
if bv.Operation == "upload" && Config.IsUsingTus() {
for _, t := range bv.Transfers {
if t == "tus" {
useTus = true
break
}
}
}
// Create a response object
for _, object := range bv.Objects {
meta, err := a.metaStore.Get(object)
if err == nil && a.contentStore.Exists(meta) { // Object is found and exists
responseObjects = append(responseObjects, a.Represent(object, meta, true, false, false))
continue
}
// Object is not found
if bv.Operation == "upload" {
meta, err = a.metaStore.Put(object)
if err == nil {
responseObjects = append(responseObjects, a.Represent(object, meta, false, true, useTus))
}
} else {
rep := &Representation{
Oid: object.Oid,
Size: object.Size,
Error: &ObjectError{
Code: 404,
Message: "Not found",
},
}
responseObjects = append(responseObjects, rep)
}
}
w.Header().Set("Content-Type", metaMediaType)
respobj := &BatchResponse{Objects: responseObjects}
// Respond with TUS support if advertised
if useTus {
respobj.Transfer = "tus"
}
enc := json.NewEncoder(w)
enc.Encode(respobj)
logRequest(r, 200)
}
// PutHandler receives data from the client and puts it into the content store
func (a *App) PutHandler(w http.ResponseWriter, r *http.Request) {
rv := unpack(r)
meta, err := a.metaStore.Get(rv)
if err != nil {
writeStatus(w, r, 404)
return
}
if err := a.contentStore.Put(meta, r.Body); err != nil {
a.metaStore.Delete(rv)
w.WriteHeader(500)
fmt.Fprintf(w, `{"message":"%s"}`, err)
return
}
logRequest(r, 200)
}
func (a *App) VerifyHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
oid := vars["oid"]
err := tusServer.Finish(oid, a.contentStore)
if err != nil {
logger.Fatal(kv{"fn": "VerifyHandler", "err": fmt.Sprintf("Failed to verify %s: %v", oid, err)})
}
logRequest(r, 200)
}
func (a *App) LocksHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
repo := vars["repo"]
enc := json.NewEncoder(w)
ll := &LockList{}
w.Header().Set("Content-Type", metaMediaType)
locks, nextCursor, err := a.metaStore.FilteredLocks(repo,
r.FormValue("path"),
r.FormValue("cursor"),
r.FormValue("limit"))
if err != nil {
ll.Message = err.Error()
} else {
ll.Locks = locks
ll.NextCursor = nextCursor
}
enc.Encode(ll)
logRequest(r, 200)
}
func (a *App) LocksVerifyHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
repo := vars["repo"]
user := context.Get(r, "USER")
dec := json.NewDecoder(r.Body)
enc := json.NewEncoder(w)
w.Header().Set("Content-Type", metaMediaType)
reqBody := &VerifiableLockRequest{}
if err := dec.Decode(reqBody); err != nil {
w.WriteHeader(http.StatusBadRequest)
enc.Encode(&VerifiableLockList{Message: err.Error()})
return
}
// Limit is optional
limit := reqBody.Limit
if limit == 0 {
limit = 100
}
ll := &VerifiableLockList{}
locks, nextCursor, err := a.metaStore.FilteredLocks(repo, "",
reqBody.Cursor,
strconv.Itoa(limit))
if err != nil {
ll.Message = err.Error()
} else {
ll.NextCursor = nextCursor
for _, l := range locks {
if l.Owner.Name == user {
ll.Ours = append(ll.Ours, l)
} else {
ll.Theirs = append(ll.Theirs, l)
}
}
}
enc.Encode(ll)
logRequest(r, 200)
}
func (a *App) CreateLockHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
repo := vars["repo"]
user := context.Get(r, "USER").(string)
dec := json.NewDecoder(r.Body)
enc := json.NewEncoder(w)
w.Header().Set("Content-Type", metaMediaType)
var lockRequest LockRequest
if err := dec.Decode(&lockRequest); err != nil {
w.WriteHeader(http.StatusBadRequest)
enc.Encode(&LockResponse{Message: err.Error()})
return
}
locks, _, err := a.metaStore.FilteredLocks(repo, lockRequest.Path, "", "1")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
enc.Encode(&LockResponse{Message: err.Error()})
return
}
if len(locks) > 0 {
w.WriteHeader(http.StatusConflict)
enc.Encode(&LockResponse{Message: "lock already created"})
return
}
lock := &Lock{
Id: randomLockId(),
Path: lockRequest.Path,
Owner: User{Name: user},
LockedAt: time.Now(),
}
if err := a.metaStore.AddLocks(repo, *lock); err != nil {
w.WriteHeader(http.StatusInternalServerError)
enc.Encode(&LockResponse{Message: err.Error()})
return
}
w.WriteHeader(http.StatusCreated)
enc.Encode(&LockResponse{
Lock: lock,
})
logRequest(r, 200)
}
func (a *App) DeleteLockHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
repo := vars["repo"]
lockId := vars["id"]
user := context.Get(r, "USER").(string)
dec := json.NewDecoder(r.Body)
enc := json.NewEncoder(w)
w.Header().Set("Content-Type", metaMediaType)
var unlockRequest UnlockRequest
if len(lockId) == 0 {
w.WriteHeader(http.StatusBadRequest)
enc.Encode(&UnlockResponse{Message: "invalid lock id"})
return
}
if err := dec.Decode(&unlockRequest); err != nil {
w.WriteHeader(http.StatusBadRequest)
enc.Encode(&UnlockResponse{Message: err.Error()})
return
}
l, err := a.metaStore.DeleteLock(repo, user, lockId, unlockRequest.Force)
if err != nil {
if err == errNotOwner {
w.WriteHeader(http.StatusForbidden)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
enc.Encode(&UnlockResponse{Message: err.Error()})
return
}
if l == nil {
w.WriteHeader(http.StatusNotFound)
enc.Encode(&UnlockResponse{Message: "unable to find lock"})
return
}
enc.Encode(&UnlockResponse{Lock: l})
logRequest(r, 200)
}
// Represent takes a RequestVars and Meta and turns it into a Representation suitable
// for json encoding
func (a *App) Represent(rv *RequestVars, meta *MetaObject, download, upload, useTus bool) *Representation {
rep := &Representation{
Oid: meta.Oid,
Size: meta.Size,
Actions: make(map[string]*link),
}
header := make(map[string]string)
verifyHeader := make(map[string]string)
header["Accept"] = contentMediaType
if len(rv.Authorization) > 0 {
header["Authorization"] = rv.Authorization
verifyHeader["Authorization"] = rv.Authorization
}
if download {
rep.Actions["download"] = &link{Href: rv.DownloadLink(), Header: header}
}
if upload {
rep.Actions["upload"] = &link{Href: rv.UploadLink(useTus), Header: header}
if useTus {
rep.Actions["verify"] = &link{Href: rv.VerifyLink(), Header: verifyHeader}
}
}
return rep
}
func (a *App) requireAuth(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !Config.IsPublic() {
user, password, _ := r.BasicAuth()
if user, ret := a.metaStore.Authenticate(user, password); !ret {
w.Header().Set("WWW-Authenticate", "Basic realm=git-lfs-server")
writeStatus(w, r, 401)
return
} else {
context.Set(r, "USER", user)
}
}
h(w, r)
}
}
// ContentMatcher provides a mux.MatcherFunc that only allows requests that contain
// an Accept header with the contentMediaType
func ContentMatcher(r *http.Request, m *mux.RouteMatch) bool {
mediaParts := strings.Split(r.Header.Get("Accept"), ";")
mt := mediaParts[0]
return mt == contentMediaType
}
// MetaMatcher provides a mux.MatcherFunc that only allows requests that contain
// an Accept header with the metaMediaType
func MetaMatcher(r *http.Request, m *mux.RouteMatch) bool {
mediaParts := strings.Split(r.Header.Get("Accept"), ";")
mt := mediaParts[0]
return mt == metaMediaType
}
func randomLockId() string {
var id [20]byte
rand.Read(id[:])
return fmt.Sprintf("%x", id[:])
}
func unpack(r *http.Request) *RequestVars {
vars := mux.Vars(r)
rv := &RequestVars{
User: vars["user"],
Repo: vars["repo"],
Oid: vars["oid"],
Authorization: r.Header.Get("Authorization"),
}
if r.Method == "POST" { // Maybe also check if +json
var p RequestVars
dec := json.NewDecoder(r.Body)
err := dec.Decode(&p)
if err != nil {
return rv
}
rv.Oid = p.Oid
rv.Size = p.Size
}
return rv
}
// TODO cheap hack, unify with unpack
func unpackBatch(r *http.Request) *BatchVars {
vars := mux.Vars(r)
var bv BatchVars
dec := json.NewDecoder(r.Body)
err := dec.Decode(&bv)
if err != nil {
return &bv
}
for i := 0; i < len(bv.Objects); i++ {
bv.Objects[i].User = vars["user"]
bv.Objects[i].Repo = vars["repo"]
bv.Objects[i].Authorization = r.Header.Get("Authorization")
}
return &bv
}
func writeStatus(w http.ResponseWriter, r *http.Request, status int) {
message := http.StatusText(status)
mediaParts := strings.Split(r.Header.Get("Accept"), ";")
mt := mediaParts[0]
if strings.HasSuffix(mt, "+json") {
message = `{"message":"` + message + `"}`
}
w.WriteHeader(status)
fmt.Fprint(w, message)
logRequest(r, status)
}
func logRequest(r *http.Request, status int) {
logger.Log(kv{"method": r.Method, "url": r.URL, "status": status, "request_id": context.Get(r, "RequestID")})
}