-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
620 lines (565 loc) · 16.5 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
package githttp
import (
"context"
stderrors "errors"
"fmt"
"net/http"
"net/url"
"os"
"path"
"strings"
base "github.com/omegaup/go-base/v3"
"github.com/omegaup/go-base/v3/logging"
"github.com/omegaup/go-base/v3/tracing"
git "github.com/libgit2/git2go/v33"
)
type doNotCompare [0]func()
// A GitOperation describes the current operation
type GitOperation int
const (
// OperationPull denotes a pull operation.
OperationPull GitOperation = iota
// OperationPush denotes a push operation.
OperationPush
// OperationBrowse denotes a browse request.
OperationBrowse
)
var (
// ErrBadRequest is returned when the client sends a bad request. HTTP 400
// will be returned to http clients.
ErrBadRequest = stderrors.New("bad-request")
// ErrForbidden is returned if an operation is not allowed. HTTP 403 will be
// returned to http clients.
ErrForbidden = stderrors.New("forbidden")
// ErrNotFound is returned if a reference is not found. HTTP 404 will be
// returned to http clients.
ErrNotFound = stderrors.New("not-found")
// ErrNotAcceptable is returned if an operation failed to produce an
// acceptable representation. HTTP 406 will be returned to http clients.
ErrNotAcceptable = stderrors.New("not-acceptable")
// ErrPreconditionFailed is returned if an operation failed a precondition.
// HTTP 412 will be returned to http clients.
ErrPreconditionFailed = stderrors.New("precondition-failed")
// ErrDeleteDisallowed is returned when a delete operation is attempted.
ErrDeleteDisallowed = stderrors.New("delete-disallowed")
// ErrInvalidRef is returned if a reference that the system does not support
// is attempted to be modified.
ErrInvalidRef = stderrors.New("invalid-ref")
// ErrReadOnlyRef is returned if a read-only reference is attempted to be
// modified.
ErrReadOnlyRef = stderrors.New("read-only")
// ErrRestrictedRef is returned if a restricted reference is attempted to be
// modified.
ErrRestrictedRef = stderrors.New("restricted-ref")
// ErrDeleteUnallowed is returned if a reference is attempted to be deleted.
ErrDeleteUnallowed = stderrors.New("delete-unallowed")
// ErrUnknownCommit is returned if the user is attempting to update a ref
// with an unknown commit.
ErrUnknownCommit = stderrors.New("unknown-commit")
// ErrNonFastForward is returned if the user is attempting to update a ref
// with a commit that is not a direct descendant of the current tip.
ErrNonFastForward = stderrors.New("non-fast-forward")
// ErrStaleInfo is returned if the provided old oid does not match the current tip.
ErrStaleInfo = stderrors.New("stale-info")
// ErrInvalidOldOid is returned if the provided old oid is not a valid object id.
ErrInvalidOldOid = stderrors.New("invalid-old-oid")
// ErrInvalidNewOid is returned if the provided new oid is not a valid object id.
ErrInvalidNewOid = stderrors.New("invalid-new-oid")
)
func (o GitOperation) String() string {
switch o {
case OperationPull:
return "pull"
case OperationPush:
return "push"
case OperationBrowse:
return "browse"
default:
return ""
}
}
// AuthorizationLevel describes the result of an authorization attempt.
type AuthorizationLevel int
const (
//AuthorizationDenied denotes that the operation was not allowed.
AuthorizationDenied AuthorizationLevel = iota
// AuthorizationAllowed denotes that the operation was allowed.
AuthorizationAllowed
// AuthorizationAllowedRestricted denotes that the operation was allowed
// (with restrictions).
AuthorizationAllowedRestricted
// AuthorizationAllowedReadOnly denotes that the operation was allowed in a
// read-only fashion.
AuthorizationAllowedReadOnly
)
// AuthorizationCallback is invoked by GitServer when a user requests to
// perform an action. It returns the authorization level and the username that
// is requesting the action.
type AuthorizationCallback func(
ctx context.Context,
w http.ResponseWriter,
r *http.Request,
repositoryName string,
operation GitOperation,
) (AuthorizationLevel, string)
func noopAuthorizationCallback(
ctx context.Context,
w http.ResponseWriter,
r *http.Request,
repositoryName string,
operation GitOperation,
) (AuthorizationLevel, string) {
return AuthorizationDenied, ""
}
// ReferenceDiscoveryCallback is invoked by GitServer when performing reference
// discovery or prior to updating a reference. It returhn whether the provided
// reference should be visible to the user.
type ReferenceDiscoveryCallback func(
ctx context.Context,
repository *git.Repository,
referenceName string,
) bool
func noopReferenceDiscoveryCallback(
ctx context.Context,
repository *git.Repository,
referenceName string,
) bool {
return true
}
// UpdateCallback is invoked by GitServer when a user attempts to update a
// repository. It returns an error if the update request is invalid.
type UpdateCallback func(
ctx context.Context,
repository *git.Repository,
level AuthorizationLevel,
command *GitCommand,
oldCommit, newCommit *git.Commit,
) error
func noopUpdateCallback(
ctx context.Context,
repository *git.Repository,
level AuthorizationLevel,
command *GitCommand,
oldCommit, newCommit *git.Commit,
) error {
return nil
}
// PreprocessCallback is invoked by GitServer when a user attempts to update a
// repository. It can perform an arbitrary transformation of the packfile and
// the update commands to be performed. A temporary directory is provided so
// that the new packfile can be stored there, if needed, and will be deleted
// afterwards. It returns the path of the new packfile, a new list of commands,
// and an error in case the operation failed.
type PreprocessCallback func(
ctx context.Context,
repository *git.Repository,
tmpDir string,
packPath string,
commands []*GitCommand,
) (string, []*GitCommand, error)
func noopPreprocessCallback(
ctx context.Context,
repository *git.Repository,
tmpDir string,
packPath string,
commands []*GitCommand,
) (string, []*GitCommand, error) {
return packPath, commands, nil
}
// ContextCallback is invoked by GitServer at the beginning of each request. It
// allows for callers to create a context wrapper.
type ContextCallback func(ctx context.Context) context.Context
func noopContextCallback(ctx context.Context) context.Context {
return ctx
}
// PostUpdateCallback is invoked by GitServer after an update occurs. It allows
// for callers to know which files in the git directory have changed.
type PostUpdateCallback func(
ctx context.Context,
repo *git.Repository,
modifiedFiles []string,
) error
func noopPostUpdateCallback(
ctx context.Context,
repo *git.Repository,
modifiedFiles []string,
) error {
return nil
}
// WriteHeader sets the HTTP status code and optionally clears any pending
// headers from the reply. It also returns the cause of the HTTP error.
func WriteHeader(w http.ResponseWriter, err error, clearHeaders bool) error {
if clearHeaders {
for k := range w.Header() {
w.Header().Del(k)
}
}
if base.HasErrorCategory(err, ErrBadRequest) {
w.WriteHeader(http.StatusBadRequest)
if cause := base.UnwrapCauseFromErrorCategory(err, ErrBadRequest); cause != nil {
return cause
}
return err
} else if base.HasErrorCategory(err, ErrNotFound) {
w.WriteHeader(http.StatusNotFound)
if cause := base.UnwrapCauseFromErrorCategory(err, ErrNotFound); cause != nil {
return cause
}
return err
} else if base.HasErrorCategory(err, ErrForbidden) {
w.WriteHeader(http.StatusForbidden)
if cause := base.UnwrapCauseFromErrorCategory(err, ErrForbidden); cause != nil {
return cause
}
return err
} else if base.HasErrorCategory(err, ErrNotAcceptable) {
w.WriteHeader(http.StatusNotAcceptable)
if cause := base.UnwrapCauseFromErrorCategory(err, ErrNotAcceptable); cause != nil {
return cause
}
return err
} else if base.HasErrorCategory(err, ErrPreconditionFailed) {
w.WriteHeader(http.StatusPreconditionFailed)
if cause := base.UnwrapCauseFromErrorCategory(err, ErrPreconditionFailed); cause != nil {
return cause
}
return err
} else {
w.WriteHeader(http.StatusInternalServerError)
return err
}
}
// A gitHTTPHandler implements git's smart protocol.
type gitHTTPHandler struct {
rootPath string
repositorySuffix string
enableBrowse bool
contextCallback ContextCallback
lockfileManager *LockfileManager
protocol *GitProtocol
tracing tracing.Provider
log logging.Logger
}
func (h *gitHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log := h.log.NewContext(ctx)
txn := tracing.FromContext(ctx)
txn.SetName(r.Method + " /:repo")
splitPath := strings.SplitN(r.URL.Path[1:], "/", 2)
if len(splitPath) < 2 {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"path": r.URL.Path[1:],
"error": "not found",
},
)
w.WriteHeader(http.StatusNotFound)
return
}
repositoryName := splitPath[0]
txn.AddAttributes(tracing.Arg{Name: "repository", Value: repositoryName})
if strings.HasPrefix(repositoryName, ".") {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"path": r.URL.Path[1:],
"error": "repository path starts with .",
},
)
w.WriteHeader(http.StatusNotFound)
return
}
relativeURL, err := url.Parse(
fmt.Sprintf("git:///%s?%s", splitPath[1], r.URL.RawQuery),
)
if err != nil {
panic(err)
}
ctx = h.contextCallback(ctx)
repositoryPath := path.Join(h.rootPath, fmt.Sprintf("%s%s", repositoryName, h.repositorySuffix))
if _, err := os.Stat(repositoryPath); os.IsNotExist(err) {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": err,
},
)
w.WriteHeader(http.StatusNotFound)
return
}
serviceName := relativeURL.Query().Get("service")
if r.Method == "GET" && relativeURL.Path == "/info/refs" &&
serviceName == "git-upload-pack" {
txn.SetName(r.Method + " /:repo/info/refs?service=git-upload-pack")
level, _ := h.protocol.AuthCallback(ctx, w, r, repositoryName, OperationPull)
if level == AuthorizationDenied {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": "authorization denied",
},
)
return
}
w.Header().Set("Content-Type", "application/x-git-upload-pack-advertisement")
w.Header().Set("Cache-Control", "no-cache")
if err := handlePrePull(ctx, h.lockfileManager, repositoryPath, level, h.protocol, log, w); err != nil {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": err,
},
)
WriteHeader(w, err, true)
return
}
} else if r.Method == "POST" && relativeURL.Path == "/git-upload-pack" {
txn.SetName(r.Method + " /:repo/git-upload-pack")
level, _ := h.protocol.AuthCallback(ctx, w, r, repositoryName, OperationPull)
if level == AuthorizationDenied {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": "authorization denied",
},
)
return
}
w.Header().Set("Content-Type", "application/x-git-upload-pack-result")
w.Header().Set("Cache-Control", "no-cache")
if err := handlePull(ctx, h.lockfileManager, repositoryPath, level, log, r.Body, w); err != nil {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": err,
},
)
WriteHeader(w, err, true)
return
}
} else if r.Method == "GET" && relativeURL.Path == "/info/refs" &&
serviceName == "git-receive-pack" {
txn.SetName(r.Method + " /:repo/info/refs?service=git-receive-pack")
level, _ := h.protocol.AuthCallback(ctx, w, r, repositoryName, OperationPush)
if level == AuthorizationDenied {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": "authorization denied",
},
)
return
}
if level == AuthorizationAllowedReadOnly {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": "insufficient permissions to modify repository",
},
)
WriteHeader(w, ErrForbidden, true)
return
}
w.Header().Set("Content-Type", "application/x-git-receive-pack-advertisement")
w.Header().Set("Cache-Control", "no-cache")
if err := handlePrePush(ctx, h.lockfileManager, repositoryPath, level, h.protocol, log, w); err != nil {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": err,
},
)
WriteHeader(w, err, true)
return
}
} else if r.Method == "POST" && relativeURL.Path == "/git-receive-pack" {
txn.SetName(r.Method + " /:repo/git-receive-pack")
level, _ := h.protocol.AuthCallback(ctx, w, r, repositoryName, OperationPush)
if level == AuthorizationDenied {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": "authorization denied",
},
)
return
}
if level == AuthorizationAllowedReadOnly {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": "insufficient permissions to modify repository",
},
)
WriteHeader(w, ErrForbidden, true)
return
}
w.Header().Set("Content-Type", "application/x-git-receive-pack-result")
w.Header().Set("Cache-Control", "no-cache")
if err := handlePush(
ctx,
h.lockfileManager,
repositoryPath,
level,
h.protocol,
log,
r.Body,
w,
); err != nil {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": err,
},
)
WriteHeader(w, err, true)
return
}
} else if (r.Method == "GET" || r.Method == "HEAD") && h.enableBrowse {
level, _ := h.protocol.AuthCallback(ctx, w, r, repositoryName, OperationBrowse)
if level == AuthorizationDenied {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": "authorization denied",
},
)
return
}
trailingSlash := strings.HasSuffix(relativeURL.Path, "/")
cleanedPath := path.Clean(relativeURL.Path)
if strings.HasPrefix(cleanedPath, ".") {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": "path starts with .",
},
)
w.WriteHeader(http.StatusNotFound)
return
}
if trailingSlash && !strings.HasSuffix(cleanedPath, "/") {
cleanedPath += "/"
}
w.Header().Set("Content-Type", "application/json")
if err := handleBrowse(
ctx,
h.lockfileManager,
repositoryPath,
level,
h.protocol,
cleanedPath,
r,
w,
); err != nil {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": err,
},
)
WriteHeader(w, err, true)
return
}
} else {
log.Error(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
"error": "not found",
},
)
w.WriteHeader(http.StatusNotFound)
return
}
log.Info(
"Request",
map[string]any{
"Method": r.Method,
"URL": relativeURL,
"path": repositoryPath,
},
)
}
// GitServerOpts contains all the possible options to initialize the git Server.
type GitServerOpts struct {
doNotCompare
RootPath string
RepositorySuffix string
EnableBrowse bool
Protocol *GitProtocol
LockfileManager *LockfileManager
ContextCallback ContextCallback
Log logging.Logger
Tracing tracing.Provider
}
// NewGitServer returns an http.Handler that implements git's smart protocol,
// as documented on
// https://git-scm.com/book/en/v2/Git-Internals-Transfer-Protocols#_the_smart_protocol .
// The callbacks will be invoked as a way to allow callers to perform
// additional authorization and pre-upload checks.
func NewGitServer(opts GitServerOpts) http.Handler {
if opts.Tracing == nil {
opts.Tracing = tracing.NewNoOpProvider()
}
if opts.ContextCallback == nil {
opts.ContextCallback = noopContextCallback
}
return &gitHTTPHandler{
rootPath: opts.RootPath,
repositorySuffix: opts.RepositorySuffix,
enableBrowse: opts.EnableBrowse,
contextCallback: opts.ContextCallback,
lockfileManager: opts.LockfileManager,
protocol: opts.Protocol,
log: opts.Log,
tracing: opts.Tracing,
}
}