internal/httpd/smart.go

129 lines · 4397 bytes

  1// Package httpd serves the HTTP listener: anonymous smart-HTTP git reads for
  2// public repositories, and (from M5) the web UI. There is no authentication
  3// on this listener by design — private repositories answer 404 everywhere,
  4// and pushes are refused with a pkt-line ERR so no git version ever falls
  5// back to asking for credentials.
  6package httpd
  7
  8import (
  9	"compress/gzip"
 10	"fmt"
 11	"io"
 12	"net"
 13	"net/http"
 14	"os"
 15	"os/exec"
 16	"strings"
 17
 18	"gitbay.org/gitbay/internal/config"
 19	"gitbay.org/gitbay/internal/control"
 20	"gitbay.org/gitbay/internal/store"
 21)
 22
 23type Server struct {
 24	cfg      config.Config
 25	st       *store.Store
 26	apiLimit *apiLimiter
 27	proxies  []*net.IPNet // http.trusted_proxies, parsed once
 28}
 29
 30func New(cfg config.Config, st *store.Store) *Server {
 31	proxies, _ := cfg.HTTP.TrustedProxyNets() // validated at config load
 32	return &Server{cfg: cfg, st: st, apiLimit: newAPILimiter(cfg.Limits.APIRate), proxies: proxies}
 33}
 34
 35// receivePackRefusal exists only to fail legibly if a client POSTs without
 36// reading the advertisement first.
 37func (s *Server) receivePackRefusal(w http.ResponseWriter, r *http.Request) {
 38	http.Error(w, s.pushRefusalMessage(r.PathValue("owner"), r.PathValue("repo")), http.StatusForbidden)
 39}
 40
 41// publicRepo resolves owner/name and returns it only if it exists and is
 42// public. Every failure mode is the same 404.
 43func (s *Server) publicRepo(owner, name string) (store.Repo, bool) {
 44	repo, err := s.st.RepoByPath(owner + "/" + name)
 45	if err != nil || repo.Visibility != "public" {
 46		return store.Repo{}, false
 47	}
 48	return repo, true
 49}
 50
 51func pktLine(w io.Writer, s string) {
 52	fmt.Fprintf(w, "%04x%s", len(s)+4, s)
 53}
 54
 55func pktFlush(w io.Writer) { io.WriteString(w, "0000") }
 56
 57func (s *Server) pushRefusalMessage(owner, repo string) string {
 58	host := strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(s.cfg.Server.SiteURL, "https://"), "http://"), "/")
 59	name := strings.TrimSuffix(repo, ".git")
 60	return fmt.Sprintf("pushes to this forge go over SSH: git remote set-url --push origin git@%s:%s/%s.git", host, owner, name)
 61}
 62
 63func (s *Server) infoRefs(w http.ResponseWriter, r *http.Request) {
 64	owner, name := r.PathValue("owner"), r.PathValue("repo")
 65	repo, ok := s.publicRepo(owner, name)
 66	if !ok {
 67		http.NotFound(w, r)
 68		return
 69	}
 70	switch service := r.URL.Query().Get("service"); service {
 71	case "git-upload-pack":
 72		w.Header().Set("Content-Type", "application/x-git-upload-pack-advertisement")
 73		w.Header().Set("Cache-Control", "no-cache")
 74		pktLine(w, "# service=git-upload-pack\n")
 75		pktFlush(w)
 76		dir := control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name)
 77		cmd := exec.CommandContext(r.Context(), "git", "upload-pack", "--stateless-rpc", "--advertise-refs", dir)
 78		cmd.Env = append(os.Environ(), gitProtocolEnv(r)...)
 79		cmd.Stdout = w
 80		cmd.Run()
 81	case "git-receive-pack":
 82		// HTTP 200 with a pkt-line ERR: every git version renders this as
 83		// "fatal: remote error: ..." and never falls back to credential
 84		// prompting the way a 401/403 would.
 85		w.Header().Set("Content-Type", "application/x-git-receive-pack-advertisement")
 86		w.Header().Set("Cache-Control", "no-cache")
 87		pktLine(w, "# service=git-receive-pack\n")
 88		pktFlush(w)
 89		pktLine(w, "ERR "+s.pushRefusalMessage(owner, name)+"\n")
 90	default:
 91		// Dumb-protocol clients are not supported.
 92		http.NotFound(w, r)
 93	}
 94}
 95
 96func (s *Server) uploadPack(w http.ResponseWriter, r *http.Request) {
 97	repo, ok := s.publicRepo(r.PathValue("owner"), r.PathValue("repo"))
 98	if !ok {
 99		http.NotFound(w, r)
100		return
101	}
102	body := io.Reader(r.Body)
103	if r.Header.Get("Content-Encoding") == "gzip" {
104		gz, err := gzip.NewReader(body)
105		if err != nil {
106			http.Error(w, "bad gzip body", http.StatusBadRequest)
107			return
108		}
109		defer gz.Close()
110		body = gz
111	}
112	w.Header().Set("Content-Type", "application/x-git-upload-pack-result")
113	w.Header().Set("Cache-Control", "no-cache")
114	dir := control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name)
115	cmd := exec.CommandContext(r.Context(), "git", "upload-pack", "--stateless-rpc", dir)
116	cmd.Env = append(os.Environ(), gitProtocolEnv(r)...)
117	cmd.Stdin = body
118	cmd.Stdout = w
119	cmd.Run()
120}
121
122// gitProtocolEnv forwards the client's protocol negotiation header so
123// protocol v2 works over stateless HTTP.
124func gitProtocolEnv(r *http.Request) []string {
125	if p := r.Header.Get("Git-Protocol"); p != "" {
126		return []string{"GIT_PROTOCOL=" + p}
127	}
128	return nil
129}