package pickupclient
import (
"bytes"
"context"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
type upstream struct {
srv *httptest.Server
mu sync.Mutex
seen []*http.Request
body []string
// redirect makes the forge answer 302.
redirect bool
}
func newUpstream(t *testing.T) *upstream {
u := &upstream{}
u.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
u.mu.Lock()
u.seen = append(u.seen, r)
u.body = append(u.body, string(b))
redirect := u.redirect
u.mu.Unlock()
if redirect {
http.Redirect(w, r, "http://elsewhere.example/steal", http.StatusFound)
return
}
w.Write([]byte("reply"))
}))
t.Cleanup(u.srv.Close)
return u
}
func (u *upstream) count() int { u.mu.Lock(); defer u.mu.Unlock(); return len(u.seen) }
// newProxy starts a proxy to up that serves this very process, which is
// what the in-process client below is.
func newProxy(t *testing.T, up *upstream) *authProxy {
t.Helper()
origin, _ := url.Parse(up.srv.URL)
p, err := startAuthProxy(context.Background(), origin, "/r/alex/site", "alex", cloneTestToken)
if err != nil {
t.Fatal(err)
}
t.Cleanup(p.Close)
return p
}
func post(t *testing.T, target, host string, body []byte) (*http.Response, string) {
t.Helper()
req, _ := http.NewRequest("POST", target, bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer client-supplied")
req.Header.Set("Content-Type", "application/x-fossil")
if host != "" {
req.Host = host
}
c := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
resp, err := c.Do(req)
if err != nil {
t.Fatalf("FAIL: %v", err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp, string(b)
}
func TestAuthProxyForwardsOneAddressWithTheTokenAndRefusesTheRest(t *testing.T) {
up := newUpstream(t)
p := newProxy(t, up)
p.SetPID(os.Getpid())
pu, _ := url.Parse(p.URL)
if !strings.HasPrefix(pu.Host, "127.0.0.1:") || len(p.nonce) != 64 || pu.Path != "/"+p.nonce+"/r/alex/site" || pu.User != nil {
t.Fatalf("FAIL: the proxy address is %q", p.URL)
}
round := fossilRound(cloneRound)
resp, body := post(t, p.URL+"?x=1&y=2", "", round)
if resp.StatusCode != 200 || body != "reply" {
t.Fatalf("FAIL: the right address answered %d %q (%v)", resp.StatusCode, body, p.Refusals())
}
up.mu.Lock()
got, sent := up.seen[0], up.body[0]
up.mu.Unlock()
if user, pw, ok := got.BasicAuth(); !ok || user != "alex" || pw != cloneTestToken || got.URL.Path != "/r/alex/site" {
t.Errorf("FAIL: the forge saw user %q on %q", user, got.URL.Path)
}
if got.URL.RawQuery != "" {
t.Errorf("FAIL: a query string was forwarded: %q", got.URL.RawQuery)
}
if sent != string(round) {
t.Errorf("FAIL: the round was changed on the way")
}
before := up.count()
base := "http://" + pu.Host
for name, target := range map[string]string{
"a wrong nonce": base + "/" + strings.Repeat("0", 64) + "/r/alex/site",
"no nonce": base + "/r/alex/site",
"another path": p.URL + "/../other",
"another repo": base + "/" + p.nonce + "/r/alex/other",
"the API": base + "/" + p.nonce + "/api/v1/me",
"the nonce only": base + "/" + p.nonce,
} {
if resp, _ := post(t, target, "", round); resp.StatusCode != 404 {
t.Errorf("FAIL: %s answered %d", name, resp.StatusCode)
}
}
if resp, _ := post(t, p.URL, "evil.example", round); resp.StatusCode != 404 {
t.Errorf("FAIL: another Host answered %d", resp.StatusCode)
}
if resp, err := http.Get(p.URL); err != nil || resp.StatusCode != 404 {
t.Errorf("FAIL: a GET to the right address was answered")
}
if up.count() != before {
t.Errorf("FAIL: a refused request reached the forge")
}
}
func TestAuthProxyIsReadOnlyByContent(t *testing.T) {
up := newUpstream(t)
p := newProxy(t, up)
p.SetPID(os.Getpid())
ok := cloneRound
oversize := bytes.Repeat([]byte("x"), maxProxyBody+10)
for name, body := range map[string][]byte{
"a push card": fossilRound(ok + "push SRVCODE PROJCODE\n"),
"a file card": fossilRound(ok + "file 1234567890abcdef 5\nabcde"),
"a cfile card": fossilRound(ok + "cfile 1234567890abcdef 5 5\nabcde"),
"an uvfile card": fossilRound(ok + "uvfile a.txt 0 0 5 1\nabcde"),
"a config card": fossilRound(ok + "config skin 5\nabcde"),
"an unknown card": fossilRound(ok + "frobnicate 1 2\n"),
"a pragma that locks": fossilRound(ok + "pragma ci-lock abc 123\n"),
"a login card": fossilRound(ok + "login jan x y\n"),
"a pull card": fossilRound(ok + "pull A B\n"),
"an igot after a push": fossilRound("push A B\nigot 1234567890abcdef\n"),
"a body that is not zlib": append([]byte{0, 0, 0, 10}, []byte("not zlib at all")...),
"a body too short": []byte{1, 2},
"a wrong stated length": append([]byte{0, 0, 0, 1}, fossilRound(ok)[4:]...),
"a body over the cap": oversize,
} {
resp, _ := post(t, p.URL, "", body)
if resp.StatusCode != http.StatusForbidden {
t.Errorf("FAIL: %s answered %d", name, resp.StatusCode)
}
}
if up.count() != 0 {
t.Errorf("FAIL: a refused round reached the forge (%d)", up.count())
}
if len(p.Refusals()) != 14 {
t.Errorf("FAIL: refusals %v", p.Refusals())
}
// Fossil may also send the text as it is.
req, _ := http.NewRequest("POST", p.URL, strings.NewReader(ok))
req.Header.Set("Content-Type", "application/x-fossil-uncompressed")
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode != 200 {
t.Errorf("FAIL: an uncompressed clone round was not forwarded")
}
// and a push in that form is refused the same.
req, _ = http.NewRequest("POST", p.URL, strings.NewReader(ok+"push A B\n"))
req.Header.Set("Content-Type", "application/x-fossil-uncompressed")
if resp, err := http.DefaultClient.Do(req); err != nil || resp.StatusCode != 403 {
t.Errorf("FAIL: an uncompressed push was not refused")
}
}
func TestAuthProxyRefusesAnUpstreamRedirect(t *testing.T) {
up := newUpstream(t)
up.redirect = true
p := newProxy(t, up)
p.SetPID(os.Getpid())
resp, _ := post(t, p.URL, "", fossilRound(cloneRound))
if resp.StatusCode != http.StatusBadGateway || resp.Header.Get("Location") != "" {
t.Errorf("FAIL: a redirect was answered %d with Location %q", resp.StatusCode, resp.Header.Get("Location"))
}
}
// A process other than the one the proxy serves is refused, though it
// has the address and the nonce: here the in-process client, and a second
// process, are not the sleeper the proxy was told about.
func TestAuthProxyServesOnlyTheProcessItWasToldAbout(t *testing.T) {
curl, err := exec.LookPath("curl")
if err != nil {
t.Skip("curl not on PATH")
}
up := newUpstream(t)
p := newProxy(t, up)
sleeper := exec.Command("sleep", "30")
if err := sleeper.Start(); err != nil {
t.Skip("no sleep")
}
defer func() { sleeper.Process.Kill(); sleeper.Wait() }()
p.SetPID(sleeper.Process.Pid)
round := fossilRound(cloneRound)
if resp, _ := post(t, p.URL, "", round); resp.StatusCode != http.StatusForbidden {
t.Errorf("FAIL: this process, which is not the one served, answered %d", resp.StatusCode)
}
file := filepath.Join(t.TempDir(), "round.bin")
os.WriteFile(file, round, 0o644)
other := exec.Command(curl, "-s", "-o", "/dev/null", "-w", "%{http_code}", "-X", "POST", "-H", "Content-Type: application/x-fossil", "--data-binary", "@"+file, p.URL)
out, _ := other.Output()
if strings.TrimSpace(string(out)) != "403" {
t.Errorf("FAIL: a second process with the right nonce answered %q", out)
}
if up.count() != 0 {
t.Errorf("FAIL: a refused connection reached the forge")
}
if r := p.Refusals(); len(r) < 2 || !strings.Contains(r[0], "not from the fossil") {
t.Errorf("FAIL: refusals %v", r)
}
}
// The process that is named is served: a second process, here curl, is
// named, and its connection is the one let through.
func TestAuthProxyServesTheProcessItWasToldAbout(t *testing.T) {
curl, err := exec.LookPath("curl")
if err != nil {
t.Skip("curl not on PATH")
}
up := newUpstream(t)
p := newProxy(t, up)
file := filepath.Join(t.TempDir(), "round.bin")
os.WriteFile(file, fossilRound(cloneRound), 0o644)
child := exec.Command(curl, "-s", "-o", "/dev/null", "-w", "%{http_code}", "-X", "POST", "-H", "Content-Type: application/x-fossil", "--data-binary", "@"+file, p.URL)
var out bytes.Buffer
child.Stdout = &out
if err := child.Start(); err != nil {
t.Fatal(err)
}
p.SetPID(child.Process.Pid)
child.Wait()
if strings.TrimSpace(out.String()) != "200" || up.count() != 1 {
t.Errorf("FAIL: the named process answered %q (%d forwarded, refusals %v)", out.String(), up.count(), p.Refusals())
}
}
func TestAuthProxyFailsClosedWhenNoProcessIsNamed(t *testing.T) {
old := peerWaitForPID
peerWaitForPID = 150 * time.Millisecond
defer func() { peerWaitForPID = old }()
up := newUpstream(t)
p := newProxy(t, up) // SetPID is never called
resp, body := post(t, p.URL, "", fossilRound(cloneRound))
if resp.StatusCode != http.StatusForbidden || !strings.Contains(body, "no process was named") || up.count() != 0 {
t.Errorf("FAIL: answered %d %q", resp.StatusCode, body)
}
}
func TestInodeOfConnReadsProcNetTCP(t *testing.T) {
const text = ` sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
0: 0100007F:C350 0100007F:1F90 01 00000000:00000000 00:00000000 00000000 1000 0 424242 1 0000000000000000 100 0 0 10 0
1: 0100007F:C351 0100007F:1F90 01 00000000:00000000 00:00000000 00000000 1000 0 515151 1 0000000000000000 100 0 0 10 0
`
src := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0xC351}
dst := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0x1F90}
if got, ok := inodeOfConn(text, src, dst); !ok || got != "515151" {
t.Errorf("FAIL: inode %q %v", got, ok)
}
src.Port = 1
if _, ok := inodeOfConn(text, src, dst); ok {
t.Errorf("FAIL: an absent connection was found")
}
}
func TestAuthProxyStopsOnCloseAndOnContext(t *testing.T) {
origin, _ := url.Parse("http://127.0.0.1:1")
down := func(addr string) bool {
for i := 0; i < 50; i++ {
c, err := net.DialTimeout("tcp", addr, 100*time.Millisecond)
if err != nil {
return true
}
c.Close()
time.Sleep(20 * time.Millisecond)
}
return false
}
p, _ := startAuthProxy(context.Background(), origin, "/r/a/b", "alex", cloneTestToken)
pu, _ := url.Parse(p.URL)
p.Close()
p.Close() // twice is fine
if !down(pu.Host) {
t.Errorf("FAIL: the proxy still listens after Close")
}
ctx, cancel := context.WithCancel(context.Background())
p2, _ := startAuthProxy(ctx, origin, "/r/a/b", "alex", cloneTestToken)
pu2, _ := url.Parse(p2.URL)
cancel()
if !down(pu2.Host) {
t.Errorf("FAIL: the proxy still listens after its context ended")
}
}