Skip to content
quarry Artifact [d6d579a196]
Login

Artifact [d6d579a196]

Artifact d6d579a196584487c739254a1a54a547cb5a2700ef4e8d0557ef231e8b23df22:


package pickupclient

import (
	"bytes"
	"compress/zlib"
	"context"
	"crypto/rand"
	"crypto/subtle"
	"encoding/binary"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"sort"
	"strings"
	"sync"
	"sync/atomic"
	"time"
)

// authProxy is the way a stock fossil clones a private repository with
// the token on no command line. Fossil takes a first password from the
// address it is given and from nowhere else, so it is given the address
// of this proxy instead: loopback, a random port, and a path that begins
// with a 32-byte nonce. The proxy answers only that path, and forwards
// it as POST to exactly one sync address on the forge's own origin,
// adding the account and token as HTTP Basic (the one form the forge's
// sync lane reads; it is a header, never a URL or an argument). It
// follows no redirect and answers no other path, method or Host.
//
// The port and nonce are in fossil's arguments, which any local user can
// read, so two more things hold. The proxy is read-only by content: it
// forwards a round only when every card in it is one a clone sends
// (cloneCards). And it serves only the process it was told to serve: a
// connection is accepted when its peer socket belongs to that pid (see
// peer*.go), and refused when that cannot be told.
type authProxy struct {
	// URL is the address to hand to fossil: http://127.0.0.1:PORT/NONCE/r/OWNER/NAME.
	URL   string
	nonce string
	srv   *http.Server
	once  sync.Once
	done  chan struct{}

	pid     atomic.Int64
	pidSet  chan struct{}
	pidOnce sync.Once

	mu       sync.Mutex
	refusals []string
}

// What a clone may say: the cards a real `fossil clone` of a repository
// sent through this proxy, 2.29 (found by running one, not from the
// manual). TestRepoCloneThenBareSyncNeedsNoPassword (cmd/quarry) runs one
// against the installed fossil and fails if the set it sends is not this.
var cloneCards = map[string]bool{
	"clone":     true, // the clone itself: protocol version and sequence number
	"pragma":    true, // only client-version (see clonePragmas)
	"#":         true, // the comment card that ends a round
	"reqconfig": true, // asks for configuration (project name, and the like)
}

// clonePragmas are the pragmas a clone sends. Others change what the
// server does (ci-lock takes a lock, uv-push-ok announces a push).
var clonePragmas = map[string]bool{"client-version": true}

// CloneCards is the list, sorted, for the test that runs a real clone.
func CloneCards() []string {
	var out []string
	for c := range cloneCards {
		out = append(out, c)
	}
	sort.Strings(out)
	return out
}

// writeCards are the cards that carry content to the server or change
// its state; they are named only so that a refusal can say which.
var writeCards = map[string]bool{
	"push": true, "file": true, "cfile": true, "uvfile": true, "config": true,
	"private": true, "uvigot": true,
}

const (
	maxProxyBody  = 1 << 20 // compressed bytes of one round
	maxProxyCards = 4 << 20 // the same, uncompressed
)

// peerWaitForPID is how long a connection waits to be told which process
// is served before it is refused.
var peerWaitForPID = 5 * time.Second

// startAuthProxy listens on loopback and serves until Close or until ctx
// ends. origin is the forge's scheme and host; syncPath is the one path
// forwarded to ("/r/OWNER/NAME"). Until SetPID says which process is
// fossil, nothing is served.
func startAuthProxy(ctx context.Context, origin *url.URL, syncPath, account, token string) (*authProxy, error) {
	raw := make([]byte, 32)
	if _, err := rand.Read(raw); err != nil {
		return nil, err
	}
	nonce := hex.EncodeToString(raw)
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return nil, err
	}
	want := "/" + nonce + syncPath
	target := &url.URL{Scheme: origin.Scheme, Host: origin.Host}
	rp := &httputil.ReverseProxy{
		Rewrite: func(pr *httputil.ProxyRequest) {
			pr.SetURL(target)
			pr.Out.URL.Path, pr.Out.URL.RawPath, pr.Out.URL.RawQuery = syncPath, "", ""
			pr.Out.Host = target.Host
			pr.Out.Header.Del("Authorization")
			pr.Out.SetBasicAuth(account, token)
		},
		// A redirect is the forge sending the token's holder somewhere
		// else: it is refused, not followed and not passed on.
		ModifyResponse: func(r *http.Response) error {
			if r.StatusCode >= 300 && r.StatusCode < 400 {
				return errors.New("the forge redirected")
			}
			return nil
		},
		ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) {
			http.Error(w, "bad gateway", http.StatusBadGateway)
		},
	}
	p := &authProxy{nonce: nonce, done: make(chan struct{}), pidSet: make(chan struct{})}
	p.URL = "http://" + ln.Addr().String() + want
	proxyAddr := ln.Addr().(*net.TCPAddr)

	p.srv = &http.Server{
		ReadHeaderTimeout: 10 * time.Second,
		// One verdict per connection about who is on the other end of it.
		ConnContext: func(ctx context.Context, c net.Conn) context.Context {
			return context.WithValue(ctx, peerKey{}, &peerVerdict{conn: c})
		},
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Host must be the loopback address itself, so a page in a
			// browser cannot reach this through a name that rebinds.
			if r.Host != ln.Addr().String() {
				http.NotFound(w, r)
				return
			}
			if r.Method != http.MethodPost || subtle.ConstantTimeCompare([]byte(r.URL.Path), []byte(want)) != 1 {
				http.NotFound(w, r)
				return
			}
			if why := p.checkPeer(r, proxyAddr); why != "" {
				p.refuse(w, http.StatusForbidden, "refused: "+why)
				return
			}
			body, why := readCloneRound(r)
			if why != "" {
				p.refuse(w, http.StatusForbidden, "refused: "+why)
				return
			}
			r.Body = io.NopCloser(bytes.NewReader(body))
			r.ContentLength = int64(len(body))
			r.Header.Del("Content-Encoding")
			rp.ServeHTTP(w, r)
		}),
	}
	go p.srv.Serve(ln)
	go func() {
		select {
		case <-ctx.Done():
			p.Close()
		case <-p.done:
		}
	}()
	return p, nil
}

func (p *authProxy) refuse(w http.ResponseWriter, code int, why string) {
	p.mu.Lock()
	p.refusals = append(p.refusals, why)
	p.mu.Unlock()
	http.Error(w, why, code)
}

// Refusals is what the proxy refused, in order, and why.
func (p *authProxy) Refusals() []string {
	p.mu.Lock()
	defer p.mu.Unlock()
	return append([]string(nil), p.refusals...)
}

// SetPID names the one process the proxy serves: the fossil it started.
func (p *authProxy) SetPID(pid int) {
	p.pidOnce.Do(func() {
		p.pid.Store(int64(pid))
		close(p.pidSet)
	})
}

type peerKey struct{}

// peerVerdict is the answer, made once, to "is the process at the other
// end of this connection the one we serve".
type peerVerdict struct {
	conn net.Conn
	once sync.Once
	why  string // empty: yes
}

func (p *authProxy) checkPeer(r *http.Request, proxyAddr *net.TCPAddr) string {
	v, _ := r.Context().Value(peerKey{}).(*peerVerdict)
	if v == nil {
		return "the connection is not known"
	}
	v.once.Do(func() {
		select {
		case <-p.pidSet:
		case <-time.After(peerWaitForPID):
			v.why = "no process was named to serve"
			return
		case <-p.done:
			v.why = "the proxy is closing"
			return
		}
		src, ok := v.conn.RemoteAddr().(*net.TCPAddr)
		if !ok {
			v.why = "the peer is not a TCP connection"
			return
		}
		if err := peerOwnedBy(int(p.pid.Load()), src, proxyAddr); err != nil {
			v.why = err.Error()
		}
	})
	return v.why
}

// readCloneRound reads one round of the sync protocol and returns it as
// it was sent when it is only what a clone says. Fossil's framing is the
// uncompressed length as 4 big-endian bytes, then a zlib stream; a body
// sent as application/x-fossil-uncompressed is the text itself.
func readCloneRound(r *http.Request) ([]byte, string) {
	raw, err := io.ReadAll(io.LimitReader(r.Body, maxProxyBody+1))
	if err != nil {
		return nil, "the request could not be read"
	}
	if len(raw) > maxProxyBody {
		return nil, "the request is too large"
	}
	text := raw
	if !strings.Contains(r.Header.Get("Content-Type"), "x-fossil-uncompressed") {
		if len(raw) < 4 {
			return nil, "the request is not a sync round"
		}
		want := binary.BigEndian.Uint32(raw[:4])
		if want > maxProxyCards {
			return nil, "the request is too large"
		}
		zr, err := zlib.NewReader(bytes.NewReader(raw[4:]))
		if err != nil {
			return nil, "the request does not decompress"
		}
		text, err = io.ReadAll(io.LimitReader(zr, maxProxyCards+1))
		if err != nil || len(text) > maxProxyCards || uint32(len(text)) != want {
			return nil, "the request does not decompress to the length it states"
		}
	}
	for _, line := range strings.Split(string(text), "\n") {
		if line == "" {
			continue
		}
		card, rest, _ := strings.Cut(line, " ")
		if card == "pragma" {
			if name, _, _ := strings.Cut(rest, " "); !clonePragmas[name] {
				return nil, fmt.Sprintf("a pragma that is not part of a clone (%.20q)", name)
			}
		}
		if !cloneCards[card] {
			if writeCards[card] {
				return nil, "a " + card + " card is not part of a clone"
			}
			return nil, fmt.Sprintf("a card that is not part of a clone (%.12q)", card)
		}
	}
	return raw, ""
}

// Close stops the proxy; it is safe to call more than once.
func (p *authProxy) Close() {
	p.once.Do(func() {
		close(p.done)
		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
		defer cancel()
		if err := p.srv.Shutdown(ctx); err != nil {
			p.srv.Close()
		}
	})
}

// isLoopbackHost says host (with or without a port) is this machine.
func isLoopbackHost(host string) bool {
	h := host
	if hh, _, err := net.SplitHostPort(host); err == nil {
		h = hh
	}
	h = strings.Trim(h, "[]")
	if h == "localhost" {
		return true
	}
	ip := net.ParseIP(h)
	return ip != nil && ip.IsLoopback()
}