Skip to content
quarry Artifact [ab727762f0]
Login

Artifact [ab727762f0]

Artifact ab727762f0b23e853b8acff0f8332d68a5e76f60f2cd5c42f4fbfe1f55996f83:


package xfer

import (
	"bytes"
	"crypto/sha1"
	"encoding/hex"
	"io"
	"net/http"
	"net/http/httptest"
	"regexp"
	"strings"
	"testing"
	"time"
)

// The real project code of the "secret" repository in nativeFronter.
const nativeCode = "6f3c2a1b9d8e7f0a5c4b3d2e1f009988aabbccdd"

// nativeFronter is challengeFronter with the project codes the clone
// refusal names: "secret" and "open" hold real ones, anything else is
// made up under a fixed key.
func nativeFronter(t *testing.T) *Fronter {
	t.Helper()
	f := challengeFronter(t)
	f.SetProjectCode(func(name string) (string, bool) {
		switch name {
		case "secret":
			return nativeCode, true
		case "open":
			return "00112233445566778899aabbccddeeff00112233", true
		}
		return "", false
	})
	f.SetDecoyKey(bytes.Repeat([]byte{7}, 32))
	return f
}

// loginOver is a login card signed with secret over covered, then covered.
func loginOver(user, secret, covered string) string {
	sum := sha1.Sum([]byte(covered))
	nonce := hex.EncodeToString(sum[:])
	sig := sha1.Sum([]byte(nonce + secret))
	return "login " + user + " " + nonce + " " + hex.EncodeToString(sig[:]) + "\n" + covered
}

// nativePost is a sync request as stock fossil sends it: compressed card
// stream, fossil's content type and User-Agent.
func nativePost(t *testing.T, repo, cards string) *http.Request {
	t.Helper()
	req := syncPost(t, repo)
	req.Header.Set("User-Agent", fossilUA)
	req.Body = io.NopCloser(bytes.NewReader(encodeContainer([]byte(cards))))
	return req
}

const cloneRound1 = "pragma client-version 22800 20260311 113146\nclone 3 1\n# 0123456789abcdef0123456789abcdef01234567\n"

// replyCards is the decoded card stream of a protocol reply.
func replyCards(t *testing.T, w *httptest.ResponseRecorder) string {
	t.Helper()
	body, compressed, err := openContainer(w.Body.Bytes(), maxBufferedReply)
	if err != nil || !compressed {
		t.Errorf("FAIL: reply is not a compressed fossil container (err %v)", err)
	}
	return string(body)
}

var pushCard = regexp.MustCompile(`^push ([0-9a-f]{40}) ([0-9a-f]{40})\n`)

// A clone's first round carries no credential; Fossil's server answers a
// caller it will not let clone with 200, the push card that teaches the
// project code, and an error the client ignores on that round. Its
// second round then carries the login card. The private repository names
// its real project code, the absent one a made-up code of the same
// shape, and nothing else differs.
func TestAnUnidentifiedCloneIsAnsweredAsFossilAnswers(t *testing.T) {
	f := nativeFronter(t)
	var got [2]*httptest.ResponseRecorder
	for i, repo := range []string{"secret", "absent"} {
		got[i] = httptest.NewRecorder()
		f.ServeHTTP(got[i], nativePost(t, repo, cloneRound1))
	}
	p, a := got[0], got[1]
	for i, w := range got {
		if w.Code != http.StatusOK {
			t.Errorf("FAIL: case %d: status %d, want 200", i, w.Code)
		}
		if ct := w.Header().Get("Content-Type"); ct != "application/x-fossil" {
			t.Errorf("FAIL: case %d: Content-Type %q", i, ct)
		}
		if w.Header().Get("WWW-Authenticate") != "" {
			t.Errorf("FAIL: case %d: a protocol answer carries a Basic challenge", i)
		}
	}
	pc, ac := replyCards(t, p), replyCards(t, a)
	pm, am := pushCard.FindStringSubmatch(pc), pushCard.FindStringSubmatch(ac)
	if pm == nil || am == nil {
		t.Fatalf("FAIL: no well-formed push card first: %q / %q", pc, ac)
	}
	if pm[2] != nativeCode {
		t.Errorf("FAIL: the private repository named %s, not its project code", pm[2])
	}
	if am[2] == nativeCode || am[1] == am[2] {
		t.Errorf("FAIL: the made-up codes are not codes of their own: %q", ac)
	}
	tail := string(errorCard(notAuthorized("clone", loginState{})))
	if !strings.HasPrefix(tail, "error not\\sauthorized\\sto\\sclone:\\s") ||
		pc[len(pm[0]):] != tail || ac[len(am[0]):] != tail {
		t.Errorf("FAIL: cards after push: %q / %q", pc[len(pm[0]):], ac[len(am[0]):])
	}
	// Byte-identical once the codes are taken out.
	if strings.ReplaceAll(strings.ReplaceAll(pc, pm[1], "S"), pm[2], "P") !=
		strings.ReplaceAll(strings.ReplaceAll(ac, am[1], "S"), am[2], "P") {
		t.Errorf("FAIL: the two replies differ beyond their codes")
	}
	sameHeaders(t, "clone", p, a)
	if !t.Failed() {
		t.Log("ok")
	}
}

// sameHeaders fails unless both replies carry the same header set.
func sameHeaders(t *testing.T, name string, p, a *httptest.ResponseRecorder) {
	t.Helper()
	if p.Code != a.Code {
		t.Errorf("FAIL: %s: status %d / %d", name, p.Code, a.Code)
	}
	if len(p.Header()) != len(a.Header()) {
		t.Errorf("FAIL: %s: header sets differ: %v / %v", name, p.Header(), a.Header())
	}
	for k := range p.Header() {
		if strings.Join(p.Header().Values(k), ",") != strings.Join(a.Header().Values(k), ",") {
			t.Errorf("FAIL: %s: header %s differs", name, k)
		}
	}
}

// The made-up codes are fixed per address under one key, differ between
// addresses and between keys, and have a real code's shape.
func TestMadeUpCodesAreStablePerAddress(t *testing.T) {
	f := nativeFronter(t)
	s1, p1 := f.cloneCodes("absent")
	s2, p2 := f.cloneCodes("absent")
	s3, p3 := f.cloneCodes("elsewhere")
	if s1 != s2 || p1 != p2 {
		t.Errorf("FAIL: codes for one address changed between requests")
	}
	if p1 == p3 || s1 == s3 {
		t.Errorf("FAIL: two addresses share a code")
	}
	for _, c := range []string{s1, p1, s3, p3} {
		if !validProjectCode(c) || len(c) != 40 {
			t.Errorf("FAIL: %q is not 40 lowercase hex", c)
		}
	}
	// A restart under the same key gives the same codes; another key, others.
	g := nativeFronter(t)
	if _, p := g.cloneCodes("absent"); p != p1 {
		t.Errorf("FAIL: the same key gave another code after a restart")
	}
	g.SetDecoyKey(bytes.Repeat([]byte{9}, 32))
	if _, p := g.cloneCodes("absent"); p == p1 {
		t.Errorf("FAIL: another key gave the same code")
	}
	// The real repository's server code is made up the same way.
	if s, p := f.cloneCodes("secret"); p != nativeCode || !validProjectCode(s) || s == nativeCode {
		t.Errorf("FAIL: secret: %s %s", s, p)
	}
	// With no key to be had, a per-process one stands in, stable while it lives.
	h := nativeFronter(t)
	h.SetDecoyKey(nil)
	_, q1 := h.cloneCodes("absent")
	_, q2 := h.cloneCodes("absent")
	if q1 != q2 || !validProjectCode(q1) {
		t.Errorf("FAIL: the per-process key is not stable: %s %s", q1, q2)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Round two and the other first rounds, each identical for a private
// repository and one that does not exist.
func TestFossilNativeRefusalsAreIdentical(t *testing.T) {
	const covered = "pragma client-version 22800 20260311 113146\nclone 3 1\n# r\n"
	real := SharedSecret(nativeCode, "insider", "a-push-credential")
	cases := []struct {
		name  string
		cards string
		basic bool
		want  string
	}{
		{"card that does not verify", loginOver("insider", "not-it", covered), false, "error login\\sfailed:\\s"},
		{"card of an unknown account", loginOver("nobody", "x", covered), false, "error login\\sfailed:\\s"},
		{"pull with no card", "pragma client-version 22800 20260311 113146\npull aaaa bbbb\n", false, "error not\\sauthorized\\sto\\sread:\\s"},
		{"sync with no card", "pull aaaa bbbb\npush aaaa bbbb\n", false, "error not\\sauthorized\\sto\\sread:\\s"},
		{"push with no card", "push aaaa bbbb\n", false, "error not\\sauthorized\\sto\\swrite:\\s"},
	}
	for _, c := range cases {
		f := nativeFronter(t)
		f.SetAuth(&mapAuth{users: map[string]string{"insider": real}})
		var got [2]*httptest.ResponseRecorder
		for i, repo := range []string{"secret", "absent"} {
			got[i] = httptest.NewRecorder()
			f.ServeHTTP(got[i], nativePost(t, repo, c.cards))
		}
		p, a := got[0], got[1]
		if p.Code != http.StatusOK {
			t.Errorf("FAIL: %s: status %d, want 200", c.name, p.Code)
		}
		if pc := replyCards(t, p); !strings.HasPrefix(pc, c.want) || strings.Count(pc, "\n") != 1 || !strings.HasSuffix(pc, "\n") {
			t.Errorf("FAIL: %s: cards %q, want %q", c.name, pc, c.want)
		}
		if !bytes.Equal(p.Body.Bytes(), a.Body.Bytes()) {
			t.Errorf("FAIL: %s: bodies differ", c.name)
		}
		sameHeaders(t, c.name, p, a)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A held account is told so in an error card the client prints, the same
// for a private repository and one that does not exist; the limiter is
// not asked anything more for it.
func TestAHeldSyncIsToldInAnErrorCard(t *testing.T) {
	const covered = "clone 3 1\n# r\n"
	f := nativeFronter(t)
	f.SetAuth(&mapAuth{users: map[string]string{"insider": SharedSecret(nativeCode, "insider", "tok")}})
	lim := &countingLimit{max: 1, misses: map[string]int{"insider": 1}}
	f.SetLoginLimit(lim)
	var got [2]*httptest.ResponseRecorder
	for i, repo := range []string{"secret", "absent"} {
		got[i] = httptest.NewRecorder()
		f.ServeHTTP(got[i], nativePost(t, repo, loginOver("insider", "wrong", covered)))
	}
	p, a := got[0], got[1]
	if p.Code != http.StatusOK {
		t.Errorf("FAIL: held: status %d, want 200", p.Code)
	}
	if pc := replyCards(t, p); pc != string(errorCard(holdSentence(90*time.Second))) {
		t.Errorf("FAIL: held: cards %q", pc)
	}
	if !bytes.Equal(p.Body.Bytes(), a.Body.Bytes()) {
		t.Errorf("FAIL: held: bodies differ")
	}
	sameHeaders(t, "held", p, a)
	if lim.misses["insider"] != 1 {
		t.Errorf("FAIL: a held card was counted again: %d", lim.misses["insider"])
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A Basic credential that does not resolve is refused as Fossil refuses
// it, 401, and one that resolves to an account that may not read is
// answered in the protocol, as Fossil answers a user without the clone
// letter; each the same for both. The difference is only a sign-in's:
// every check was counted, once (TestAHeldBasicAnswersAlikeRightOrWrong
// holds the account it would otherwise leave open to guessing).
func TestBasicOnASyncRefusal(t *testing.T) {
	f := nativeFronter(t)
	lim := &countingLimit{max: 99, misses: map[string]int{}}
	calls := 0
	f.SetBasicSignIn(signInWith(lim, map[string]string{"outsider": "right"}, &calls))
	var bad, good [2]*httptest.ResponseRecorder
	for i, repo := range []string{"secret", "absent"} {
		req := nativePost(t, repo, cloneRound1)
		req.SetBasicAuth("outsider", "wrong")
		bad[i] = httptest.NewRecorder()
		f.ServeHTTP(bad[i], req)
		req = nativePost(t, repo, cloneRound1)
		req.SetBasicAuth("outsider", "right")
		good[i] = httptest.NewRecorder()
		f.ServeHTTP(good[i], req)
	}
	if calls != 4 {
		t.Errorf("FAIL: 4 requests checked Basic %d times", calls)
	}
	if bad[0].Code != http.StatusUnauthorized {
		t.Errorf("FAIL: unresolved Basic answered %d, want 401", bad[0].Code)
	}
	if !bytes.Equal(bad[0].Body.Bytes(), bad[1].Body.Bytes()) {
		t.Errorf("FAIL: unresolved Basic: bodies differ")
	}
	sameHeaders(t, "unresolved basic", bad[0], bad[1])
	if good[0].Code != http.StatusOK || !strings.Contains(replyCards(t, good[0]), "\nerror not\\sauthorized\\sto\\sclone") {
		t.Errorf("FAIL: resolved Basic that may not read: %d", good[0].Code)
	}
	sameHeaders(t, "resolved basic", good[0], good[1])
	if !t.Failed() {
		t.Log("ok")
	}
}

// A request that is not the sync protocol (a browser, curl) keeps the
// HTTP answers with their help text.
func TestANonProtocolRequestKeepsTheHTTPRefusal(t *testing.T) {
	f := nativeFronter(t)
	req := httptest.NewRequest(http.MethodPost, "/r/secret", nil)
	req.SetPathValue("repo", "secret")
	w := httptest.NewRecorder()
	f.ServeHTTP(w, req)
	if w.Code != http.StatusUnauthorized || w.Header().Get("WWW-Authenticate") == "" || w.Header().Get("Link") == "" {
		t.Errorf("FAIL: plain request: %d %v", w.Code, w.Header())
	}
	if !t.Failed() {
		t.Log("ok")
	}
}