internal/gitpin/gitpin.go

273e9b95f8b87ee2be442c6bff6cbffbfd09cccf
gitbay/internal/gitpin/gitpin.go

152 lines · 4945 bytes

  1// Package gitpin runs git against a user-supplied http or https remote
  2// only at addresses resolved and checked immediately before: mirror
  3// sync (#279) and repo import (#298).
  4package gitpin
  5
  6import (
  7	"context"
  8	"fmt"
  9	"net"
 10	"net/url"
 11	"os/exec"
 12	"strconv"
 13	"strings"
 14
 15	"gitbay.org/gitbay/internal/toolpath"
 16	"gitbay.org/gitbay/internal/webhook"
 17)
 18
 19// Lookup resolves a host to its addresses.
 20type Lookup func(ctx context.Context, host string) ([]net.IP, error)
 21
 22// LookupIP is the system resolver.
 23func LookupIP(ctx context.Context, host string) ([]net.IP, error) {
 24	return net.DefaultResolver.LookupIP(ctx, "ip", host)
 25}
 26
 27// Remote is a URL whose host resolved to IPs, every one of which passed
 28// the address check.
 29type Remote struct {
 30	URL *url.URL
 31	IPs []net.IP
 32}
 33
 34// Resolve parses raw, requires http or https, resolves the host with
 35// lookup, and refuses it when it resolves to nothing or, unless
 36// allowLocal, to any private or local address.
 37func Resolve(ctx context.Context, lookup Lookup, raw string, allowLocal bool) (Remote, error) {
 38	u, err := url.Parse(raw)
 39	if err != nil {
 40		return Remote{}, err
 41	}
 42	if u.Scheme != "https" && u.Scheme != "http" {
 43		return Remote{}, fmt.Errorf("URL scheme %q is not http or https", u.Scheme)
 44	}
 45	host := u.Hostname()
 46	if host == "" {
 47		return Remote{}, fmt.Errorf("URL has no host")
 48	}
 49	if net.ParseIP(host) == nil && numericHost(host) {
 50		// 127.1, 2130706433 and 0x7f.1 are loopback to curl's parser
 51		// but not to Go's; refuse rather than leave them to a resolver.
 52		return Remote{}, fmt.Errorf("host %q is a numeric address in a form other than dotted decimal; write it as a.b.c.d", host)
 53	}
 54	ips, err := lookup(ctx, host)
 55	if err != nil {
 56		return Remote{}, fmt.Errorf("resolving %s: %w", host, err)
 57	}
 58	if len(ips) == 0 {
 59		// An empty resolve list would leave curl to resolve the host itself.
 60		return Remote{}, fmt.Errorf("%s resolves to no address", host)
 61	}
 62	if err := webhook.CheckAddrs(host, ips, allowLocal); err != nil {
 63		return Remote{}, err
 64	}
 65	return Remote{URL: u, IPs: ips}, nil
 66}
 67
 68// numericHost reports whether every label of host is a decimal, octal
 69// or hex number, the shapes inet_aton reads as an IPv4 address.
 70func numericHost(host string) bool {
 71	for _, label := range strings.Split(strings.TrimSuffix(host, "."), ".") {
 72		digits, base := label, "0123456789"
 73		if rest, ok := strings.CutPrefix(strings.ToLower(label), "0x"); ok {
 74			digits, base = rest, "0123456789abcdef"
 75		}
 76		if strings.Trim(strings.ToLower(digits), base) != "" || label == "" {
 77			return false
 78		}
 79	}
 80	return true
 81}
 82
 83// Args are git's leading -c options for r: curl's resolve list pins
 84// the host, and any other name on the same port, to the checked
 85// addresses, and with redirects off a server
 86// cannot send git on to a host nobody checked. An address literal
 87// needs no pin.
 88func (r Remote) Args() []string {
 89	args := []string{"-c", "http.followRedirects=false"}
 90	host := r.URL.Hostname()
 91	if net.ParseIP(host) != nil {
 92		return args
 93	}
 94	port := r.URL.Port()
 95	if port == "" {
 96		port = "443"
 97		if r.URL.Scheme == "http" {
 98			port = "80"
 99		}
100	}
101	addrs := make([]string, len(r.IPs))
102	for i, ip := range r.IPs {
103		if ip.To4() == nil {
104			addrs[i] = "[" + ip.String() + "]"
105		} else {
106			addrs[i] = ip.String()
107		}
108	}
109	pinned := port + ":" + strings.Join(addrs, ",")
110	// The wildcard entry catches a lookup under any other spelling of
111	// the host, so it too lands on the checked addresses.
112	return append(args, "-c", "http.curloptResolve="+host+":"+pinned,
113		"-c", "http.curloptResolve=*:"+pinned)
114}
115
116// Env is git's whole environment for a pinned remote. No system or
117// global gitconfig: a proxy, URL rewrite or redirect setting there
118// would take git around the pin.
119func Env(home string) []string {
120	return []string{"GIT_TERMINAL_PROMPT=0", "HOME=" + home,
121		"GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null"}
122}
123
124// VersionOK accepts the output of `git version` for git 2.37 or later,
125// the first release with http.curloptResolve. An older git ignores the
126// setting and would resolve the host itself.
127func VersionOK(out string) error {
128	fields := strings.Fields(out)
129	if len(fields) >= 3 && fields[0] == "git" && fields[1] == "version" {
130		parts := strings.Split(fields[2], ".")
131		if len(parts) >= 2 {
132			major, err1 := strconv.Atoi(parts[0])
133			minor, err2 := strconv.Atoi(parts[1])
134			if err1 == nil && err2 == nil {
135				if major > 2 || major == 2 && minor >= 37 {
136					return nil
137				}
138				return fmt.Errorf("git %s is older than 2.37 and cannot pin remote addresses", fields[2])
139			}
140		}
141	}
142	return fmt.Errorf("cannot read git version from %q", strings.TrimSpace(out))
143}
144
145// CheckGit runs the server's git and refuses one that cannot pin.
146func CheckGit(ctx context.Context) error {
147	out, err := exec.CommandContext(ctx, toolpath.Look("git"), "version").Output()
148	if err != nil {
149		return fmt.Errorf("running git version: %v", err)
150	}
151	return VersionOK(string(out))
152}