package pickupclient
import (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"errors"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"sync"
"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.
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{}
}
// 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").
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 = 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{})}
p.URL = "http://" + ln.Addr().String() + want
p.srv = &http.Server{
ReadHeaderTimeout: 10 * time.Second,
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
}
rp.ServeHTTP(w, r)
}),
}
go p.srv.Serve(ln)
go func() {
select {
case <-ctx.Done():
p.Close()
case <-p.done:
}
}()
return p, nil
}
// 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()
}