Skip to content
quarry Artifact [8f1a99b7db]
Login

Artifact [8f1a99b7db]

Artifact 8f1a99b7dbce6ec0977cc3f86199abf142dfffdb81c9190d3bdfbfdeb6c679ed:


package pickupclient

import (
	"context"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"net/url"
	"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:" + string(b)))
	}))
	t.Cleanup(u.srv.Close)
	return u
}

func (u *upstream) count() int { u.mu.Lock(); defer u.mu.Unlock(); return len(u.seen) }

func post(t *testing.T, target, host string) (*http.Response, string) {
	t.Helper()
	req, _ := http.NewRequest("POST", target, strings.NewReader("round"))
	req.Header.Set("Authorization", "Bearer "+"client-supplied")
	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)
	origin, _ := url.Parse(up.srv.URL)
	p, err := startAuthProxy(context.Background(), origin, "/r/alex/site", "alex", cloneTestToken)
	if err != nil {
		t.Fatal(err)
	}
	defer p.Close()
	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)
	}

	resp, body := post(t, p.URL, "")
	if resp.StatusCode != 200 || body != "reply:round" {
		t.Fatalf("FAIL: the right address answered %d %q", resp.StatusCode, body)
	}
	up.mu.Lock()
	got := up.seen[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)
	}

	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, ""); resp.StatusCode != 404 {
			t.Errorf("FAIL: %s answered %d", name, resp.StatusCode)
		}
	}
	if resp, _ := post(t, p.URL, "evil.example"); 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 TestAuthProxyRefusesAnUpstreamRedirect(t *testing.T) {
	up := newUpstream(t)
	up.redirect = true
	origin, _ := url.Parse(up.srv.URL)
	p, err := startAuthProxy(context.Background(), origin, "/r/alex/site", "alex", cloneTestToken)
	if err != nil {
		t.Fatal(err)
	}
	defer p.Close()
	resp, _ := post(t, p.URL, "")
	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"))
	}
}

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")
	}
}