Skip to content
quarry Artifact [efa7e70efb]
Login

Artifact [efa7e70efb]

Artifact efa7e70efb8b1489904375cec34a372ae717edad546fc16bdfd31d37308cd204:


package pickupclient

import (
	"bytes"
	"context"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"sync/atomic"
	"testing"
)

const cloneTestToken = "qat_TESTTOKEN0123456789ABCDEFGHJKMNPQRSTVWXYZ"

// fakeTools puts a zit and a fossil that record every call first on PATH.
// The log holds one block per call: its argument line, its standard
// input where it takes one, then its whole environment. Files named in
// the directory switch behaviours: has-credential-command (zit settings
// knows the setting), clone-fails, pull-fails; remote holds what
// `remote` prints.
type fakeTools struct {
	dir string
	log string
}

const fakeZit = `#!/bin/sh
{
  echo "== zit $*"
  env | grep -v '^_=' | sort
} >> "$FAKE_DIR/log"
case "$1" in
settings)
  [ -e "$FAKE_DIR/has-credential-command" ] && exit 0
  echo "zit settings: unknown setting 'credential-command' (known: autosync)" >&2
  exit 1 ;;
clone)
  [ -e "$FAKE_DIR/clone-fails" ] && { echo "clone refused for ${ZIT_PASSWORD}" >&2; exit 1; }
  mkdir -p "$3" && : > "$3/.zit-checkout"
  echo "cloned" ;;
pull)
  [ -e "$FAKE_DIR/pull-fails" ] && [ -z "$ZIT_PASSWORD" ] && { echo "password needed" >&2; exit 1; }
  echo "already in sync" ;;
remote)
  cat "$FAKE_DIR/remote" 2>/dev/null ;;
esac
exit 0
`

const fakeFossil = `#!/bin/sh
{
  echo "== fossil $*"
  [ "$1" = sql ] && { echo "STDIN:"; cat; echo "ENDSTDIN"; }
  env | grep -v '^_=' | sort
} >> "$FAKE_DIR/log"
case "$1" in
clone)
  # fossil clone ... --workdir DIR URL FILE: make both.
  for a in "$@"; do last="$a"; done
  : > "$last"
  while [ $# -gt 0 ]; do [ "$1" = --workdir ] && { mkdir -p "$2"; : > "$2/.fslckout"; }; shift; done ;;
remote)
  if [ "$2" = "" ]; then cat "$FAKE_DIR/remote" 2>/dev/null; fi ;;
pull)
  [ -e "$FAKE_DIR/pull-fails" ] && { echo "missing or incorrect password" >&2; exit 1; } ;;
esac
exit 0
`

func newFakeTools(t *testing.T) *fakeTools {
	t.Helper()
	dir := t.TempDir()
	bin := filepath.Join(dir, "bin")
	if err := os.MkdirAll(bin, 0o755); err != nil {
		t.Fatal(err)
	}
	for name, body := range map[string]string{"zit": fakeZit, "fossil": fakeFossil} {
		if err := os.WriteFile(filepath.Join(bin, name), []byte(body), 0o755); err != nil {
			t.Fatal(err)
		}
	}
	t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
	t.Setenv("FAKE_DIR", dir)
	t.Setenv("ZIT_PASSWORD", "")
	return &fakeTools{dir: dir, log: filepath.Join(dir, "log")}
}

func (f *fakeTools) flag(t *testing.T, name, body string) {
	t.Helper()
	if err := os.WriteFile(filepath.Join(f.dir, name), []byte(body), 0o644); err != nil {
		t.Fatal(err)
	}
}

type toolCall struct {
	Args  string
	Env   string
	Stdin string
}

func (f *fakeTools) calls(t *testing.T) []toolCall {
	t.Helper()
	raw, err := os.ReadFile(f.log)
	if err != nil {
		return nil
	}
	var out []toolCall
	for _, blk := range strings.Split(string(raw), "== ")[1:] {
		head, rest, _ := strings.Cut(blk, "\n")
		c := toolCall{Args: head}
		if i := strings.Index(rest, "STDIN:\n"); i >= 0 {
			j := strings.Index(rest, "ENDSTDIN\n")
			c.Stdin = rest[i+len("STDIN:\n") : j]
			rest = rest[j+len("ENDSTDIN\n"):]
		}
		c.Env = rest
		out = append(out, c)
	}
	return out
}

// find is the calls whose argument line starts with prefix.
func (f *fakeTools) find(t *testing.T, prefix string) []toolCall {
	var out []toolCall
	for _, c := range f.calls(t) {
		if strings.HasPrefix(c.Args, prefix) {
			out = append(out, c)
		}
	}
	return out
}

// noTokenOnArgv fails when the token is in any call's arguments.
func (f *fakeTools) noTokenOnArgv(t *testing.T) {
	t.Helper()
	for _, c := range f.calls(t) {
		if strings.Contains(c.Args, cloneTestToken) {
			t.Errorf("FAIL: the token is on a command line: %s", strings.ReplaceAll(c.Args, cloneTestToken, "***"))
		}
	}
}

// cloneForge answers me, and the info of two repositories: alex/site is
// private (404 without the token) and alex/open is public.
type cloneForge struct {
	srv   *httptest.Server
	calls atomic.Int32
}

func newCloneForge(t *testing.T) *cloneForge {
	f := &cloneForge{}
	f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		f.calls.Add(1)
		authed := r.Header.Get("Authorization") == "Bearer "+cloneTestToken
		switch r.URL.Path {
		case "/api/v1/me":
			if !authed {
				w.WriteHeader(401)
				w.Write([]byte(`{"code":"no_login"}`))
				return
			}
			w.Write([]byte(`{"name":"alex"}`))
		case "/api/v1/r/alex/site/info":
			if !authed {
				w.WriteHeader(404)
				return
			}
			w.Write([]byte(`{"name":"site","checkins":412}`))
		case "/api/v1/r/alex/open/info":
			w.Write([]byte(`{"name":"open","checkins":7}`))
		default:
			w.WriteHeader(404)
		}
	}))
	t.Cleanup(f.srv.Close)
	return f
}

func (f *cloneForge) host() string { return strings.TrimPrefix(f.srv.URL, "http://") }

func cloneEnv(t *testing.T, out, errw *bytes.Buffer, f *cloneForge, loggedIn bool, cwd string) *Env {
	st := &fakeStore{}
	if loggedIn {
		st.rec = map[string]Record{f.host(): {Host: f.host(), Account: "alex", Token: cloneTestToken}}
	}
	e := loginEnv(t, out, errw, st)
	e.Getenv = func(string) string { return "" }
	e.Getwd = func() (string, error) { return cwd, nil }
	return e
}

func cloneArgs(f *cloneForge, a ...string) []string {
	return append(a, "--host", f.srv.URL)
}

func TestCloneSignsInWithTheTokenInTheEnvironmentOnly(t *testing.T) {
	tools := newFakeTools(t)
	f := newCloneForge(t)
	work := t.TempDir()
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, true, work)
	code := Clone(context.Background(), cloneArgs(f, "alex/site", filepath.Join(work, "site"), "--json"), e)
	if code != 0 {
		t.Fatalf("FAIL: exit %d stderr %q", code, errw.String())
	}
	m := oneObject(t, out.String())
	for _, k := range []string{"ok", "host", "repo", "dir", "account", "fossil", "checkins", "signedIn", "next"} {
		if _, ok := m[k]; !ok {
			t.Errorf("FAIL: the answer has no %q: %v", k, m)
		}
	}
	if m["ok"] != true || m["repo"] != "alex/site" || m["account"] != "alex" || m["fossil"] != false || m["signedIn"] != true || m["checkins"] != float64(412) {
		t.Errorf("FAIL: the answer is %v", m)
	}
	if got := m["dir"]; got != filepath.Join(work, "site") {
		t.Errorf("FAIL: dir is %v", got)
	}
	tools.noTokenOnArgv(t)
	clone := tools.find(t, "zit clone")
	if len(clone) != 1 {
		t.Fatalf("FAIL: %d zit clone calls", len(clone))
	}
	if !strings.Contains(clone[0].Args, "--user alex") || !strings.Contains(clone[0].Args, f.host()+"/r/alex/site") || strings.Contains(clone[0].Args, "@") {
		t.Errorf("FAIL: clone arguments %q", clone[0].Args)
	}
	if !strings.Contains(clone[0].Env, "ZIT_PASSWORD="+cloneTestToken+"\n") {
		t.Errorf("FAIL: the clone did not get the token in its environment")
	}
	// Every other call, the bare pull included, has no token anywhere.
	for _, c := range tools.calls(t) {
		if !strings.HasPrefix(c.Args, "zit clone") && strings.Contains(c.Env, cloneTestToken) {
			t.Errorf("FAIL: the token is in the environment of %q", c.Args)
		}
	}
	pull := tools.find(t, "zit pull")
	if len(pull) != 1 || strings.Contains(pull[0].Args, "--user") {
		t.Errorf("FAIL: want one bare pull after the clone, got %v", pull)
	}
	if strings.Contains(out.String()+errw.String(), cloneTestToken) {
		t.Errorf("FAIL: the token was printed")
	}
}

func TestClonePublicRepositoryNeedsNoLogin(t *testing.T) {
	tools := newFakeTools(t)
	f := newCloneForge(t)
	work := t.TempDir()
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, false, work)
	code := Clone(context.Background(), cloneArgs(f, "alex/open", filepath.Join(work, "open"), "--json"), e)
	if code != 0 {
		t.Fatalf("FAIL: exit %d out %q", code, out.String())
	}
	m := oneObject(t, out.String())
	if m["signedIn"] != false {
		t.Errorf("FAIL: signedIn %v", m["signedIn"])
	}
	for _, c := range tools.calls(t) {
		if strings.Contains(c.Args, "--user") || strings.Contains(c.Env, "ZIT_PASSWORD=qat") {
			t.Errorf("FAIL: an anonymous clone was signed in: %q", c.Args)
		}
	}
}

func TestCloneWithNoLoginExits4ForAPrivateRepository(t *testing.T) {
	tools := newFakeTools(t)
	f := newCloneForge(t)
	work := t.TempDir()
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, false, work)
	code := Clone(context.Background(), cloneArgs(f, "alex/site", filepath.Join(work, "site"), "--json"), e)
	m := oneObject(t, out.String())
	if code != 4 || m["ok"] != false || m["code"] != "no_login" || nextOf(m)["cmd"] != "quarry auth login" {
		t.Errorf("FAIL: exit %d answer %v", code, m)
	}
	if n := len(tools.calls(t)); n != 0 {
		t.Errorf("FAIL: %d tool calls with no login", n)
	}
	if _, err := os.Stat(filepath.Join(work, "site")); err == nil {
		t.Errorf("FAIL: a directory was made")
	}
}

func TestCloneOfARepositoryTheLoginCannotReadIsRefused(t *testing.T) {
	tools := newFakeTools(t)
	f := newCloneForge(t)
	work := t.TempDir()
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, true, work)
	code := Clone(context.Background(), cloneArgs(f, "alex/nope", filepath.Join(work, "nope"), "--json"), e)
	m := oneObject(t, out.String())
	if code != 1 || m["ok"] != false || m["code"] != "no_access" || nextOf(m)["say"] == nil {
		t.Errorf("FAIL: exit %d answer %v", code, m)
	}
	if n := len(tools.calls(t)); n != 0 {
		t.Errorf("FAIL: %d tool calls for a repository that cannot be read", n)
	}
}

func TestCloneRefusesADirectoryThatIsNotEmpty(t *testing.T) {
	tools := newFakeTools(t)
	f := newCloneForge(t)
	work := t.TempDir()
	if err := os.WriteFile(filepath.Join(work, "keep.txt"), []byte("mine"), 0o644); err != nil {
		t.Fatal(err)
	}
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, true, work)
	code := Clone(context.Background(), cloneArgs(f, "alex/site", work, "--json"), e)
	m := oneObject(t, out.String())
	if code != 1 || m["code"] != "dir_not_empty" {
		t.Errorf("FAIL: exit %d answer %v", code, m)
	}
	if f.calls.Load() != 0 || len(tools.calls(t)) != 0 {
		t.Errorf("FAIL: the forge or a tool was called before the refusal")
	}
	if b, _ := os.ReadFile(filepath.Join(work, "keep.txt")); string(b) != "mine" {
		t.Errorf("FAIL: the directory was touched")
	}
	// An empty directory is a place to clone into.
	empty := filepath.Join(work, "empty")
	os.Mkdir(empty, 0o755)
	out.Reset()
	if code := Clone(context.Background(), cloneArgs(f, "alex/site", empty, "--json"), e); code != 0 {
		t.Errorf("FAIL: an empty directory was refused: exit %d %q", code, out.String())
	}
}

func TestCloneFailureLeavesNothingAndPrintsNoToken(t *testing.T) {
	tools := newFakeTools(t)
	tools.flag(t, "clone-fails", "")
	f := newCloneForge(t)
	work := t.TempDir()
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, true, work)
	// The fake makes no directory when it fails; make one to be cleaned.
	code := Clone(context.Background(), cloneArgs(f, "alex/site", filepath.Join(work, "site"), "--json"), e)
	m := oneObject(t, out.String())
	if code != 1 || m["code"] != "clone_failed" {
		t.Errorf("FAIL: exit %d answer %v", code, m)
	}
	if strings.Contains(out.String()+errw.String(), cloneTestToken) {
		t.Errorf("FAIL: the failure printed the token: %q", out.String())
	}
}

func TestCloneUsageExits2(t *testing.T) {
	newFakeTools(t)
	f := newCloneForge(t)
	for _, args := range [][]string{{}, {"nobody"}, {"a/b/c"}, {"alex/site", "d", "e"}, {"alex/site", "--nope"}, {"alex/site", "--fossil", "--", "--horizon"}} {
		var out, errw bytes.Buffer
		e := cloneEnv(t, &out, &errw, f, true, t.TempDir())
		if code := Clone(context.Background(), append(args, "--json"), e); code != 2 {
			t.Errorf("FAIL: %v exit %d", args, code)
		}
		if m := oneObject(t, out.String()); m["code"] != "usage" {
			t.Errorf("FAIL: %v answered %v", args, m)
		}
	}
}

func TestCloneWithFossilGivesTheTokenOnlyToTheCloneAndSavesIt(t *testing.T) {
	tools := newFakeTools(t)
	f := newCloneForge(t)
	work := t.TempDir()
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, true, work)
	dir := filepath.Join(work, "site")
	code := Clone(context.Background(), cloneArgs(f, "alex/site", dir, "--fossil", "--json"), e)
	if code != 0 {
		t.Fatalf("FAIL: exit %d out %q err %q", code, out.String(), errw.String())
	}
	m := oneObject(t, out.String())
	if m["fossil"] != true || m["signedIn"] != true {
		t.Errorf("FAIL: the answer is %v", m)
	}
	clone := tools.find(t, "fossil clone")
	if len(clone) != 1 || !strings.Contains(clone[0].Args, "--save-http-password") {
		t.Fatalf("FAIL: fossil clone calls %v", clone)
	}
	// Fossil takes a first password from its address and nowhere else:
	// the clone is the one call allowed to carry the token, and no later
	// call may.
	for _, c := range tools.calls(t) {
		if !strings.HasPrefix(c.Args, "fossil clone") && (strings.Contains(c.Args, cloneTestToken) || strings.Contains(c.Env, cloneTestToken)) {
			t.Errorf("FAIL: the token is in %q", c.Args)
		}
	}
	if len(tools.find(t, "fossil pull")) != 1 {
		t.Errorf("FAIL: no bare pull after the clone")
	}
	if strings.Contains(out.String()+errw.String(), cloneTestToken) {
		t.Errorf("FAIL: the token was printed")
	}
	if _, err := os.Stat(dir + ".fossil"); err != nil {
		t.Errorf("FAIL: no repository file: %v", err)
	}
}

func TestSetupZitSetsTheCredentialCommandWhenZitHasIt(t *testing.T) {
	tools := newFakeTools(t)
	tools.flag(t, "has-credential-command", "")
	f := newCloneForge(t)
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, true, t.TempDir()) // not in a checkout
	code := SetupZit(context.Background(), []string{"--host", f.srv.URL, "--json"}, e)
	if code != 0 {
		t.Fatalf("FAIL: exit %d out %q err %q", code, out.String(), errw.String())
	}
	m := oneObject(t, out.String())
	if m["ok"] != true || m["mode"] != "credential-command" || m["set"] != "credential-command" || m["tool"] != "zit" {
		t.Errorf("FAIL: the answer is %v", m)
	}
	set := tools.find(t, "zit settings --global credential-command quarry auth credential")
	if len(set) != 1 {
		t.Errorf("FAIL: the setting was not set once: %v", tools.calls(t))
	}
	if len(tools.find(t, "zit pull")) != 0 {
		t.Errorf("FAIL: a checkout was primed as well")
	}
	tools.noTokenOnArgv(t)
	for _, c := range tools.calls(t) {
		if strings.Contains(c.Env, cloneTestToken) {
			t.Errorf("FAIL: the token reached %q", c.Args)
		}
	}
}

func TestSetupZitPrimesTheCheckoutWhenZitHasNoCredentialCommand(t *testing.T) {
	tools := newFakeTools(t)
	f := newCloneForge(t)
	tools.flag(t, "remote", f.srv.URL+"/r/alex/site\n")
	root := t.TempDir()
	os.WriteFile(filepath.Join(root, ".zit-checkout"), nil, 0o644)
	sub := filepath.Join(root, "sub")
	os.Mkdir(sub, 0o755)
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, true, sub)
	code := SetupZit(context.Background(), []string{"--json"}, e)
	if code != 0 {
		t.Fatalf("FAIL: exit %d out %q err %q", code, out.String(), errw.String())
	}
	m := oneObject(t, out.String())
	if m["mode"] != "primed" || m["tool"] != "zit" || m["account"] != "alex" {
		t.Errorf("FAIL: the answer is %v", m)
	}
	if len(tools.find(t, "zit settings --global credential-command quarry")) != 0 {
		t.Errorf("FAIL: the setting was set on a zit that does not have it")
	}
	pulls := tools.find(t, "zit pull")
	if len(pulls) != 2 || !strings.Contains(pulls[0].Args, "--user alex") || !strings.Contains(pulls[0].Env, "ZIT_PASSWORD="+cloneTestToken+"\n") || strings.Contains(pulls[1].Env, cloneTestToken) {
		t.Errorf("FAIL: pulls %v", pulls)
	}
	tools.noTokenOnArgv(t)
}

func TestSetupZitInAFossilCheckoutKeepsTheTokenOffTheCommandLine(t *testing.T) {
	tools := newFakeTools(t)
	f := newCloneForge(t)
	tools.flag(t, "remote", f.srv.URL+"/r/alex/site\n")
	root := t.TempDir()
	os.WriteFile(filepath.Join(root, ".fslckout"), nil, 0o644)
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, true, root)
	code := SetupZit(context.Background(), []string{"--json"}, e)
	if code != 0 {
		t.Fatalf("FAIL: exit %d out %q err %q", code, out.String(), errw.String())
	}
	if m := oneObject(t, out.String()); m["tool"] != "fossil" || m["mode"] != "primed" {
		t.Errorf("FAIL: the answer is %v", m)
	}
	tools.noTokenOnArgv(t)
	sql := tools.find(t, "fossil sql")
	if len(sql) != 1 || !strings.Contains(sql[0].Stdin, "obscure('"+cloneTestToken+"')") {
		t.Errorf("FAIL: the password did not go in through standard input: %v", sql)
	}
	for _, c := range tools.calls(t) {
		if strings.Contains(c.Env, cloneTestToken) {
			t.Errorf("FAIL: the token is in the environment of %q", c.Args)
		}
	}
	if r := tools.find(t, "fossil remote http"); len(r) != 1 || !strings.Contains(r[0].Args, "alex@") {
		t.Errorf("FAIL: the remote was not given the account: %v", r)
	}
}

func TestSetupZitWithNoLoginExits4AndOutsideACheckoutIsRefused(t *testing.T) {
	tools := newFakeTools(t)
	f := newCloneForge(t)
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, false, t.TempDir())
	code := SetupZit(context.Background(), []string{"--host", f.srv.URL, "--json"}, e)
	// Not in a checkout and no hook: that is the first refusal.
	if m := oneObject(t, out.String()); code != 1 || m["code"] != "not_a_checkout" {
		t.Errorf("FAIL: exit %d answer %v", code, m)
	}
	tools.flag(t, "has-credential-command", "")
	out.Reset()
	code = SetupZit(context.Background(), []string{"--host", f.srv.URL, "--json"}, e)
	if m := oneObject(t, out.String()); code != 4 || m["code"] != "no_login" || nextOf(m)["cmd"] != "quarry auth login" {
		t.Errorf("FAIL: exit %d answer %v", code, m)
	}
}

func TestCredentialHelperAnswersGetForALoggedInHostOnly(t *testing.T) {
	f := newCloneForge(t)
	ask := func(verb, in string) string {
		var out, errw bytes.Buffer
		e := cloneEnv(t, &out, &errw, f, true, t.TempDir())
		e.Stdin = strings.NewReader(in)
		if code := Credential(context.Background(), []string{verb}, e); code != 0 {
			t.Errorf("FAIL: %s exit %d", verb, code)
		}
		return out.String()
	}
	got := ask("get", "protocol=http\nhost="+f.host()+"\npath=/r/alex/site\n\n")
	if got != "username=alex\npassword="+cloneTestToken+"\n" {
		t.Errorf("FAIL: get answered %q", strings.ReplaceAll(got, cloneTestToken, "***"))
	}
	if got := ask("get", "protocol=https\nhost=elsewhere.example\n\n"); got != "" {
		t.Errorf("FAIL: a host with no login was answered: %q", got)
	}
	if got := ask("store", "protocol=http\nhost="+f.host()+"\nusername=x\npassword=y\n\n"); got != "" {
		t.Errorf("FAIL: store answered %q", got)
	}
	if got := ask("erase", "protocol=http\nhost="+f.host()+"\n\n"); got != "" {
		t.Errorf("FAIL: erase answered %q", got)
	}
}