git.go

  1package web
  2
  3import (
  4	"bytes"
  5	"compress/gzip"
  6	"context"
  7	"errors"
  8	"fmt"
  9	"io"
 10	"net/http"
 11	"os"
 12	"path/filepath"
 13	"strings"
 14	"time"
 15
 16	"github.com/charmbracelet/log"
 17	gitb "github.com/charmbracelet/soft-serve/git"
 18	"github.com/charmbracelet/soft-serve/server/access"
 19	"github.com/charmbracelet/soft-serve/server/backend"
 20	"github.com/charmbracelet/soft-serve/server/config"
 21	"github.com/charmbracelet/soft-serve/server/git"
 22	"github.com/charmbracelet/soft-serve/server/lfs"
 23	"github.com/charmbracelet/soft-serve/server/proto"
 24	"github.com/charmbracelet/soft-serve/server/utils"
 25	"github.com/gorilla/mux"
 26	"github.com/prometheus/client_golang/prometheus"
 27	"github.com/prometheus/client_golang/prometheus/promauto"
 28)
 29
 30// GitRoute is a route for git services.
 31type GitRoute struct {
 32	method  []string
 33	handler http.HandlerFunc
 34	path    string
 35}
 36
 37var _ http.Handler = GitRoute{}
 38
 39// ServeHTTP implements http.Handler.
 40func (g GitRoute) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 41	var hasMethod bool
 42	for _, m := range g.method {
 43		if m == r.Method {
 44			hasMethod = true
 45			break
 46		}
 47	}
 48
 49	if !hasMethod {
 50		renderMethodNotAllowed(w, r)
 51		return
 52	}
 53
 54	g.handler(w, r)
 55}
 56
 57var (
 58	//nolint:revive
 59	gitHttpReceiveCounter = promauto.NewCounterVec(prometheus.CounterOpts{
 60		Namespace: "soft_serve",
 61		Subsystem: "http",
 62		Name:      "git_receive_pack_total",
 63		Help:      "The total number of git push requests",
 64	}, []string{"repo"})
 65
 66	//nolint:revive
 67	gitHttpUploadCounter = promauto.NewCounterVec(prometheus.CounterOpts{
 68		Namespace: "soft_serve",
 69		Subsystem: "http",
 70		Name:      "git_upload_pack_total",
 71		Help:      "The total number of git fetch/pull requests",
 72	}, []string{"repo", "file"})
 73)
 74
 75func withParams(h http.Handler) http.Handler {
 76	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 77		ctx := r.Context()
 78		logger := log.FromContext(ctx)
 79		cfg := config.FromContext(ctx)
 80		vars := mux.Vars(r)
 81		repo := vars["repo"]
 82
 83		// Construct "file" param from path
 84		vars["file"] = strings.TrimPrefix(r.URL.Path, "/"+repo+"/")
 85
 86		// Set service type
 87		switch {
 88		case strings.HasSuffix(r.URL.Path, git.UploadPackService.String()):
 89			vars["service"] = git.UploadPackService.String()
 90		case strings.HasSuffix(r.URL.Path, git.ReceivePackService.String()):
 91			vars["service"] = git.ReceivePackService.String()
 92		}
 93
 94		repo = utils.SanitizeRepo(repo)
 95		vars["repo"] = repo
 96		vars["dir"] = filepath.Join(cfg.DataPath, "repos", repo+".git")
 97		logger.Info("request vars", "vars", vars)
 98
 99		// Add repo suffix (.git)
100		r.URL.Path = fmt.Sprintf("%s.git/%s", repo, vars["file"])
101		r = mux.SetURLVars(r, vars)
102		h.ServeHTTP(w, r)
103	})
104}
105
106// GitController is a router for git services.
107func GitController(_ context.Context, r *mux.Router) {
108	basePrefix := "/{repo:.*}"
109	for _, route := range gitRoutes {
110		// NOTE: withParam must always be the outermost wrapper, otherwise the
111		// request vars will not be set.
112		r.Handle(basePrefix+route.path, withParams(withAccess(route)))
113	}
114
115	// Handle go-get
116	r.Handle(basePrefix, withParams(withAccess(GoGetHandler{}))).Methods(http.MethodGet)
117}
118
119var gitRoutes = []GitRoute{
120	// Git services
121	// These routes don't handle authentication/authorization.
122	// This is handled through wrapping the handlers for each route.
123	// See below (withAccess).
124	{
125		method:  []string{http.MethodPost},
126		handler: serviceRpc,
127		path:    "/{service:(?:git-upload-pack|git-receive-pack)$}",
128	},
129	{
130		method:  []string{http.MethodGet},
131		handler: getInfoRefs,
132		path:    "/info/refs",
133	},
134	{
135		method:  []string{http.MethodGet},
136		handler: getTextFile,
137		path:    "/{_:(?:HEAD|objects/info/alternates|objects/info/http-alternates|objects/info/[^/]*)$}",
138	},
139	{
140		method:  []string{http.MethodGet},
141		handler: getInfoPacks,
142		path:    "/objects/info/packs",
143	},
144	{
145		method:  []string{http.MethodGet},
146		handler: getLooseObject,
147		path:    "/objects/{_:[0-9a-f]{2}/[0-9a-f]{38}$}",
148	},
149	{
150		method:  []string{http.MethodGet},
151		handler: getPackFile,
152		path:    "/objects/pack/{_:pack-[0-9a-f]{40}\\.pack$}",
153	},
154	{
155		method:  []string{http.MethodGet},
156		handler: getIdxFile,
157		path:    "/objects/pack/{_:pack-[0-9a-f]{40}\\.idx$}",
158	},
159	// Git LFS
160	{
161		method:  []string{http.MethodPost},
162		handler: serviceLfsBatch,
163		path:    "/info/lfs/objects/batch",
164	},
165	{
166		// Git LFS basic object handler
167		method:  []string{http.MethodGet, http.MethodPut},
168		handler: serviceLfsBasic,
169		path:    "/info/lfs/objects/basic/{oid:[0-9a-f]{64}$}",
170	},
171	{
172		method:  []string{http.MethodPost},
173		handler: serviceLfsBasicVerify,
174		path:    "/info/lfs/objects/basic/verify",
175	},
176	// Git LFS locks
177	{
178		method:  []string{http.MethodPost, http.MethodGet},
179		handler: serviceLfsLocks,
180		path:    "/info/lfs/locks",
181	},
182	{
183		method:  []string{http.MethodPost},
184		handler: serviceLfsLocksVerify,
185		path:    "/info/lfs/locks/verify",
186	},
187	{
188		method:  []string{http.MethodPost},
189		handler: serviceLfsLocksDelete,
190		path:    "/info/lfs/locks/{lock_id:[0-9]+}/unlock",
191	},
192}
193
194func askCredentials(w http.ResponseWriter, _ *http.Request) {
195	w.Header().Set("WWW-Authenticate", `Basic realm="Git" charset="UTF-8", Token, Bearer`)
196	w.Header().Set("LFS-Authenticate", `Basic realm="Git LFS" charset="UTF-8", Token, Bearer`)
197}
198
199// withAccess handles auth.
200func withAccess(next http.Handler) http.HandlerFunc {
201	return func(w http.ResponseWriter, r *http.Request) {
202		ctx := r.Context()
203		cfg := config.FromContext(ctx)
204		logger := log.FromContext(ctx)
205		be := backend.FromContext(ctx)
206
207		// Store repository in context
208		// We're not checking for errors here because we want to allow
209		// repo creation on the fly.
210		repoName := mux.Vars(r)["repo"]
211		repo, _ := be.Repository(ctx, repoName)
212		ctx = proto.WithRepositoryContext(ctx, repo)
213		r = r.WithContext(ctx)
214
215		user, err := authenticate(r)
216		if err != nil {
217			switch {
218			case errors.Is(err, ErrInvalidToken):
219			case errors.Is(err, proto.ErrUserNotFound):
220			default:
221				logger.Error("failed to authenticate", "err", err)
222			}
223		}
224
225		if user == nil && !be.AllowKeyless(ctx) {
226			askCredentials(w, r)
227			renderUnauthorized(w, r)
228			return
229		}
230
231		// Store user in context
232		ctx = proto.WithUserContext(ctx, user)
233		r = r.WithContext(ctx)
234
235		if user != nil {
236			logger.Info("found user", "username", user.Username())
237		}
238
239		service := git.Service(mux.Vars(r)["service"])
240		if service == "" {
241			// Get service from request params
242			service = getServiceType(r)
243		}
244
245		accessLevel := be.AccessLevelForUser(ctx, repoName, user)
246		ctx = access.WithContext(ctx, accessLevel)
247		r = r.WithContext(ctx)
248
249		file := mux.Vars(r)["file"]
250
251		// We only allow these services to proceed any other services should return 403
252		// - git-upload-pack
253		// - git-receive-pack
254		// - git-lfs
255		switch {
256		case service == git.ReceivePackService:
257			if accessLevel < access.ReadWriteAccess {
258				askCredentials(w, r)
259				renderUnauthorized(w, r)
260				return
261			}
262
263			// Create the repo if it doesn't exist.
264			if repo == nil {
265				repo, err = be.CreateRepository(ctx, repoName, proto.RepositoryOptions{})
266				if err != nil {
267					logger.Error("failed to create repository", "repo", repoName, "err", err)
268					renderInternalServerError(w, r)
269					return
270				}
271
272				ctx = proto.WithRepositoryContext(ctx, repo)
273				r = r.WithContext(ctx)
274			}
275
276			fallthrough
277		case service == git.UploadPackService:
278			if repo == nil {
279				// If the repo doesn't exist, return 404
280				renderNotFound(w, r)
281				return
282			} else if errors.Is(err, ErrInvalidToken) || errors.Is(err, ErrInvalidPassword) {
283				// return 403 when bad credentials are provided
284				renderForbidden(w, r)
285				return
286			} else if accessLevel < access.ReadOnlyAccess {
287				askCredentials(w, r)
288				renderUnauthorized(w, r)
289				return
290			}
291
292		case strings.HasPrefix(file, "info/lfs"):
293			if !cfg.LFS.Enabled {
294				logger.Debug("LFS is not enabled, skipping")
295				renderNotFound(w, r)
296				return
297			}
298
299			switch {
300			case strings.HasPrefix(file, "info/lfs/locks"):
301				switch {
302				case strings.HasSuffix(file, "lfs/locks"), strings.HasSuffix(file, "/unlock") && r.Method == http.MethodPost:
303					// Create lock, list locks, and delete lock require write access
304					fallthrough
305				case strings.HasSuffix(file, "lfs/locks/verify"):
306					// Locks verify requires write access
307					// https://github.com/git-lfs/git-lfs/blob/main/docs/api/locking.md#unauthorized-response-2
308					if accessLevel < access.ReadWriteAccess {
309						renderJSON(w, http.StatusForbidden, lfs.ErrorResponse{
310							Message: "write access required",
311						})
312						return
313					}
314				}
315			case strings.HasPrefix(file, "info/lfs/objects/basic"):
316				switch r.Method {
317				case http.MethodPut:
318					// Basic upload
319					if accessLevel < access.ReadWriteAccess {
320						renderJSON(w, http.StatusForbidden, lfs.ErrorResponse{
321							Message: "write access required",
322						})
323						return
324					}
325				case http.MethodGet:
326					// Basic download
327				case http.MethodPost:
328					// Basic verify
329				}
330			}
331
332			if accessLevel < access.ReadOnlyAccess {
333				if repo == nil {
334					renderJSON(w, http.StatusNotFound, lfs.ErrorResponse{
335						Message: "repository not found",
336					})
337				} else if errors.Is(err, ErrInvalidToken) || errors.Is(err, ErrInvalidPassword) {
338					renderJSON(w, http.StatusForbidden, lfs.ErrorResponse{
339						Message: "bad credentials",
340					})
341				} else {
342					askCredentials(w, r)
343					renderJSON(w, http.StatusUnauthorized, lfs.ErrorResponse{
344						Message: "credentials needed",
345					})
346				}
347				return
348			}
349		}
350
351		switch {
352		case r.URL.Query().Get("go-get") == "1" && accessLevel >= access.ReadOnlyAccess:
353			// Allow go-get requests to passthrough.
354			break
355		case errors.Is(err, ErrInvalidToken), errors.Is(err, ErrInvalidPassword):
356			// return 403 when bad credentials are provided
357			renderForbidden(w, r)
358			return
359		case repo == nil, accessLevel < access.ReadOnlyAccess:
360			// Don't hint that the repo exists if the user doesn't have access
361			renderNotFound(w, r)
362			return
363		}
364
365		next.ServeHTTP(w, r)
366	}
367}
368
369//nolint:revive
370func serviceRpc(w http.ResponseWriter, r *http.Request) {
371	ctx := r.Context()
372	cfg := config.FromContext(ctx)
373	logger := log.FromContext(ctx)
374	service, dir, repoName := git.Service(mux.Vars(r)["service"]), mux.Vars(r)["dir"], mux.Vars(r)["repo"]
375
376	if !isSmart(r, service) {
377		renderForbidden(w, r)
378		return
379	}
380
381	if service == git.ReceivePackService {
382		gitHttpReceiveCounter.WithLabelValues(repoName)
383	}
384
385	w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-result", service))
386	w.Header().Set("Connection", "Keep-Alive")
387	w.Header().Set("Transfer-Encoding", "chunked")
388	w.Header().Set("X-Content-Type-Options", "nosniff")
389	w.WriteHeader(http.StatusOK)
390
391	version := r.Header.Get("Git-Protocol")
392
393	var stdout bytes.Buffer
394	cmd := git.ServiceCommand{
395		Stdout: &stdout,
396		Dir:    dir,
397		Args:   []string{"--stateless-rpc"},
398	}
399
400	user := proto.UserFromContext(ctx)
401	cmd.Env = cfg.Environ()
402	cmd.Env = append(cmd.Env, []string{
403		"SOFT_SERVE_REPO_NAME=" + repoName,
404		"SOFT_SERVE_REPO_PATH=" + dir,
405		"SOFT_SERVE_LOG_PATH=" + filepath.Join(cfg.DataPath, "log", "hooks.log"),
406	}...)
407	if user != nil {
408		cmd.Env = append(cmd.Env, []string{
409			"SOFT_SERVE_USERNAME=" + user.Username(),
410		}...)
411	}
412	if len(version) != 0 {
413		cmd.Env = append(cmd.Env, []string{
414			fmt.Sprintf("GIT_PROTOCOL=%s", version),
415		}...)
416	}
417
418	// Handle gzip encoding
419	reader := r.Body
420	defer reader.Close() // nolint: errcheck
421	switch r.Header.Get("Content-Encoding") {
422	case "gzip":
423		reader, err := gzip.NewReader(reader)
424		if err != nil {
425			logger.Errorf("failed to create gzip reader: %v", err)
426			renderInternalServerError(w, r)
427			return
428		}
429		defer reader.Close() // nolint: errcheck
430	}
431
432	cmd.Stdin = reader
433
434	if err := service.Handler(ctx, cmd); err != nil {
435		if errors.Is(err, git.ErrInvalidRepo) {
436			renderNotFound(w, r)
437			return
438		}
439		renderInternalServerError(w, r)
440		return
441	}
442
443	// Handle buffered output
444	// Useful when using proxies
445
446	// We know that `w` is an `http.ResponseWriter`.
447	flusher, ok := w.(http.Flusher)
448	if !ok {
449		logger.Errorf("expected http.ResponseWriter to be an http.Flusher, got %T", w)
450		return
451	}
452
453	p := make([]byte, 1024)
454	for {
455		nRead, err := stdout.Read(p)
456		if err == io.EOF {
457			break
458		}
459		nWrite, err := w.Write(p[:nRead])
460		if err != nil {
461			logger.Errorf("failed to write data: %v", err)
462			return
463		}
464		if nRead != nWrite {
465			logger.Errorf("failed to write data: %d read, %d written", nRead, nWrite)
466			return
467		}
468		flusher.Flush()
469	}
470
471	if service == git.ReceivePackService {
472		if err := git.EnsureDefaultBranch(ctx, cmd); err != nil {
473			logger.Errorf("failed to ensure default branch: %s", err)
474		}
475	}
476}
477
478func getInfoRefs(w http.ResponseWriter, r *http.Request) {
479	ctx := r.Context()
480	cfg := config.FromContext(ctx)
481	dir, repoName, file := mux.Vars(r)["dir"], mux.Vars(r)["repo"], mux.Vars(r)["file"]
482	service := getServiceType(r)
483	version := r.Header.Get("Git-Protocol")
484
485	gitHttpUploadCounter.WithLabelValues(repoName, file).Inc()
486
487	if service != "" && (service == git.UploadPackService || service == git.ReceivePackService) {
488		// Smart HTTP
489		var refs bytes.Buffer
490		cmd := git.ServiceCommand{
491			Stdout: &refs,
492			Dir:    dir,
493			Args:   []string{"--stateless-rpc", "--advertise-refs"},
494		}
495
496		user := proto.UserFromContext(ctx)
497		cmd.Env = cfg.Environ()
498		cmd.Env = append(cmd.Env, []string{
499			"SOFT_SERVE_REPO_NAME=" + repoName,
500			"SOFT_SERVE_REPO_PATH=" + dir,
501			"SOFT_SERVE_LOG_PATH=" + filepath.Join(cfg.DataPath, "log", "hooks.log"),
502		}...)
503		if user != nil {
504			cmd.Env = append(cmd.Env, []string{
505				"SOFT_SERVE_USERNAME=" + user.Username(),
506			}...)
507		}
508		if len(version) != 0 {
509			cmd.Env = append(cmd.Env, fmt.Sprintf("GIT_PROTOCOL=%s", version))
510		}
511
512		if err := service.Handler(ctx, cmd); err != nil {
513			renderNotFound(w, r)
514			return
515		}
516
517		hdrNocache(w)
518		w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", service))
519		w.WriteHeader(http.StatusOK)
520		if len(version) == 0 {
521			git.WritePktline(w, "# service="+service.String()) // nolint: errcheck
522		}
523
524		w.Write(refs.Bytes()) // nolint: errcheck
525	} else {
526		// Dumb HTTP
527		updateServerInfo(ctx, dir) // nolint: errcheck
528		hdrNocache(w)
529		sendFile("text/plain; charset=utf-8", w, r)
530	}
531}
532
533func getInfoPacks(w http.ResponseWriter, r *http.Request) {
534	hdrCacheForever(w)
535	sendFile("text/plain; charset=utf-8", w, r)
536}
537
538func getLooseObject(w http.ResponseWriter, r *http.Request) {
539	hdrCacheForever(w)
540	sendFile("application/x-git-loose-object", w, r)
541}
542
543func getPackFile(w http.ResponseWriter, r *http.Request) {
544	hdrCacheForever(w)
545	sendFile("application/x-git-packed-objects", w, r)
546}
547
548func getIdxFile(w http.ResponseWriter, r *http.Request) {
549	hdrCacheForever(w)
550	sendFile("application/x-git-packed-objects-toc", w, r)
551}
552
553func getTextFile(w http.ResponseWriter, r *http.Request) {
554	hdrNocache(w)
555	sendFile("text/plain", w, r)
556}
557
558func sendFile(contentType string, w http.ResponseWriter, r *http.Request) {
559	dir, file := mux.Vars(r)["dir"], mux.Vars(r)["file"]
560	reqFile := filepath.Join(dir, file)
561
562	f, err := os.Stat(reqFile)
563	if os.IsNotExist(err) {
564		renderNotFound(w, r)
565		return
566	}
567
568	w.Header().Set("Content-Type", contentType)
569	w.Header().Set("Content-Length", fmt.Sprintf("%d", f.Size()))
570	w.Header().Set("Last-Modified", f.ModTime().Format(http.TimeFormat))
571	http.ServeFile(w, r, reqFile)
572}
573
574func getServiceType(r *http.Request) git.Service {
575	service := r.FormValue("service")
576	if !strings.HasPrefix(service, "git-") {
577		return ""
578	}
579
580	return git.Service(service)
581}
582
583func isSmart(r *http.Request, service git.Service) bool {
584	contentType := r.Header.Get("Content-Type")
585	return strings.HasPrefix(contentType, fmt.Sprintf("application/x-%s-request", service))
586}
587
588func updateServerInfo(ctx context.Context, dir string) error {
589	return gitb.UpdateServerInfo(ctx, dir)
590}
591
592// HTTP error response handling functions
593
594func renderBadRequest(w http.ResponseWriter, r *http.Request) {
595	renderStatus(http.StatusBadRequest)(w, r)
596}
597
598func renderMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
599	if r.Proto == "HTTP/1.1" {
600		renderStatus(http.StatusMethodNotAllowed)(w, r)
601	} else {
602		renderBadRequest(w, r)
603	}
604}
605
606func renderNotFound(w http.ResponseWriter, r *http.Request) {
607	renderStatus(http.StatusNotFound)(w, r)
608}
609
610func renderUnauthorized(w http.ResponseWriter, r *http.Request) {
611	renderStatus(http.StatusUnauthorized)(w, r)
612}
613
614func renderForbidden(w http.ResponseWriter, r *http.Request) {
615	renderStatus(http.StatusForbidden)(w, r)
616}
617
618func renderInternalServerError(w http.ResponseWriter, r *http.Request) {
619	renderStatus(http.StatusInternalServerError)(w, r)
620}
621
622// Header writing functions
623
624func hdrNocache(w http.ResponseWriter) {
625	w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
626	w.Header().Set("Pragma", "no-cache")
627	w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
628}
629
630func hdrCacheForever(w http.ResponseWriter) {
631	now := time.Now().Unix()
632	expires := now + 31536000
633	w.Header().Set("Date", fmt.Sprintf("%d", now))
634	w.Header().Set("Expires", fmt.Sprintf("%d", expires))
635	w.Header().Set("Cache-Control", "public, max-age=31536000")
636}