Skip to content
quarry Artifact [fc8f5778cc]
Login

Artifact [fc8f5778cc]

Artifact fc8f5778cc744d9a14890f6990ad11e4b2695ccdc6b28ee6a5be0375ab2f18b0:


package pickupclient

import (
	"bytes"
	"compress/zlib"
	"context"
	"encoding/binary"
	"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 $*"
  echo "CWD=$(pwd -P)"
  env | grep -E '^ZIT_PASSWORD=|qat_' | sort
} >> "$FAKE_DIR/log"
case "$1" in
init)
  : > .zit-checkout ;;
settings)
  shift
  [ "$1" = --global ] && shift
  [ "$1" = --value ] && shift
  if [ "$1" = credential-command ]; then
    [ -e "$FAKE_DIR/has-credential-command" ] || { echo "zit settings: unknown setting 'credential-command' (known: autosync)" >&2; exit 1; }
    if [ $# -ge 2 ]; then printf '%s' "$2" > "$FAKE_DIR/cc-value"; else cat "$FAKE_DIR/cc-value" 2>/dev/null; fi
  fi ;;
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)
  if [ "$2" = --unset ]; then rm -f "$FAKE_DIR/remote"
  elif [ -n "$2" ]; then printf '%s\n' "$2" > "$FAKE_DIR/remote"
  else cat "$FAKE_DIR/remote" 2>/dev/null; fi ;;
esac
exit 0
`

const fakeFossil = `#!/bin/bash
{
  echo "== fossil $*"
  [ "$1" = sql ] && { echo "STDIN:"; cat; echo "ENDSTDIN"; }
  echo "CWD=$(pwd -P)"
  env | grep -E '^ZIT_PASSWORD=|qat_' | sort
} >> "$FAKE_DIR/log"
case "$1" in
clone)
  # fossil clone --no-open URL FILE: speak to the address as fossil does
  # (one POST of a clone round, from this process), then make the file.
  for a in "$@"; do last="$a"; done
  url=""; for a in "$@"; do [ "$a" = "$last" ] && break; url="$a"; done
  hostport=${url#http://}; hostport=${hostport%%/*}; path=/${url#http://*/}
  exec 3<>/dev/tcp/${hostport%%:*}/${hostport##*:}
  printf 'POST %s HTTP/1.0\r\nHost: %s\r\nContent-Type: application/x-fossil\r\nContent-Length: %s\r\n\r\n' "$path" "$hostport" "$(wc -c < "$FAKE_DIR/round.bin" | tr -d ' ')" >&3
  cat "$FAKE_DIR/round.bin" >&3
  cat <&3 > /dev/null
  : > "$last" ;;
open)
  : > .fslckout ;;
remote)
  if [ -n "$2" ]; then printf '%s\n' "$2" > "$FAKE_DIR/remote"; else 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
`

// fossilRound is one round as fossil sends it: the uncompressed length as
// four big-endian bytes, then a zlib stream.
func fossilRound(cards string) []byte {
	var buf bytes.Buffer
	var n [4]byte
	binary.BigEndian.PutUint32(n[:], uint32(len(cards)))
	buf.Write(n[:])
	zw := zlib.NewWriter(&buf)
	zw.Write([]byte(cards))
	zw.Close()
	return buf.Bytes()
}

const cloneRound = "pragma client-version 22900 20260311 113146\nclone 3 1\n"

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)
		}
	}
	if err := os.WriteFile(filepath.Join(dir, "round.bin"), fossilRound(cloneRound), 0o644); 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
	// syncAuth is the Authorization of each POST to the sync address.
	syncAuth atomic.Value
}

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 "/r/alex/site":
			if u, pw, ok := r.BasicAuth(); ok {
				f.syncAuth.Store(u + ":" + pw)
			}
		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 TestCloneWithFossilKeepsTheTokenOffEveryCommandLine(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)
	}
	tools.noTokenOnArgv(t)
	clone := tools.find(t, "fossil clone")
	if len(clone) != 1 || strings.Contains(clone[0].Args, "@") || strings.Contains(clone[0].Args, "--save-http-password") || !strings.Contains(clone[0].Args, "http://127.0.0.1:") {
		t.Fatalf("FAIL: fossil clone calls %v", clone)
	}
	// What fossil sent to the address it was given reached the forge with
	// the token as a bearer: the proxy is what carries it.
	if got, _ := f.syncAuth.Load().(string); got != "alex:"+cloneTestToken {
		t.Errorf("FAIL: the forge saw %q", strings.ReplaceAll(got, cloneTestToken, "***"))
	}
	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)
		}
	}
	sql := tools.find(t, "fossil sql")
	if len(sql) != 1 || !strings.Contains(sql[0].Stdin, "'last-sync-url','http://alex@"+f.host()+"/r/alex/site'") {
		t.Errorf("FAIL: the repository was not pointed at the forge: %v", 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)
	}
	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 len(sql) != 1 || !strings.Contains(sql[0].Stdin, "'last-sync-url','http://alex@") {
		t.Errorf("FAIL: the remote was not given the account: %v", sql)
	}
}

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

func TestSetupZitRefusesARemoteThatIsNotTheForgesOriginAndSendsNoToken(t *testing.T) {
	for _, tool := range []string{"zit", "fossil"} {
		for name, remote := range map[string]string{
			"plain http to another host": "http://forge.example/r/alex/site",
			"another scheme":             "https://%HOST%/r/alex/site",
			"another port":               "http://127.0.0.1:1/r/alex/site",
		} {
			tools := newFakeTools(t)
			f := newCloneForge(t)
			tools.flag(t, "remote", strings.ReplaceAll(remote, "%HOST%", f.host())+"\n")
			root := t.TempDir()
			marker := ".zit-checkout"
			if tool == "fossil" {
				marker = ".fslckout"
			}
			os.WriteFile(filepath.Join(root, marker), nil, 0o644)
			var out, errw bytes.Buffer
			e := cloneEnv(t, &out, &errw, f, true, root)
			code := SetupZit(context.Background(), []string{"--host", f.srv.URL, "--json"}, e)
			m := oneObject(t, out.String())
			if code != 1 || m["ok"] != false || (m["code"] != "other_forge" && m["code"] != "insecure_remote") {
				t.Errorf("FAIL: %s, %s: exit %d answer %v", tool, name, code, m)
			}
			for _, c := range tools.calls(t) {
				if strings.Contains(c.Env, cloneTestToken) || strings.Contains(c.Stdin, cloneTestToken) || strings.HasPrefix(c.Args, tool+" pull") || strings.HasPrefix(c.Args, tool+" sql") {
					t.Errorf("FAIL: %s, %s: the checkout was signed in: %q", tool, name, c.Args)
				}
			}
		}
	}
}

func TestClaimDirMakesWhatItRemovesAndNothingElse(t *testing.T) {
	root := t.TempDir()
	made := filepath.Join(root, "new")
	if created, err := claimDir(made); err != nil || !created {
		t.Fatalf("FAIL: a missing directory: created %v err %v", created, err)
	}
	if created, err := claimDir(made); err != nil || created {
		t.Errorf("FAIL: an empty directory that exists was claimed as made: created %v err %v", created, err)
	}
	os.WriteFile(filepath.Join(made, "mine"), []byte("x"), 0o644)
	if _, err := claimDir(made); err == nil {
		t.Errorf("FAIL: a directory with files was claimed")
	}
	if _, err := os.Stat(filepath.Join(made, "mine")); err != nil {
		t.Errorf("FAIL: claiming touched the files")
	}
}

func TestAFailedCloneRemovesOnlyWhatItMade(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)

	// Made by the clone: gone after it fails.
	fresh := filepath.Join(work, "fresh")
	if code := Clone(context.Background(), cloneArgs(f, "alex/site", fresh, "--json"), e); code != 1 {
		t.Fatalf("FAIL: exit %d", code)
	}
	if _, err := os.Stat(fresh); err == nil {
		t.Errorf("FAIL: the directory the clone made was left")
	}
	// Already there (empty): still there.
	mine := filepath.Join(work, "mine")
	os.Mkdir(mine, 0o755)
	out.Reset()
	if code := Clone(context.Background(), cloneArgs(f, "alex/site", mine, "--json"), e); code != 1 {
		t.Fatalf("FAIL: exit %d", code)
	}
	if _, err := os.Stat(mine); err != nil {
		t.Errorf("FAIL: a directory the clone did not make was removed")
	}
}

func TestCredentialHelperWillNotPrintToATerminal(t *testing.T) {
	f := newCloneForge(t)
	tty, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0) // a character device, as a terminal is
	if err != nil {
		t.Skip("no character device to stand in for a terminal")
	}
	defer tty.Close()
	var errw bytes.Buffer
	e := cloneEnv(t, &bytes.Buffer{}, &errw, f, true, t.TempDir())
	e.Stdout = tty
	e.Stdin = strings.NewReader("protocol=http\nhost=" + f.host() + "\n\n")
	if code := Credential(context.Background(), []string{"get"}, e); code != 2 {
		t.Errorf("FAIL: exit %d", code)
	}
	if strings.Count(strings.TrimSpace(errw.String()), "\n") != 0 || errw.Len() == 0 || strings.Contains(errw.String(), cloneTestToken) {
		t.Errorf("FAIL: stderr is %q", errw.String())
	}
}

func TestTheCredentialCommandProbeDoesNotDependOnTheWorkingDirectory(t *testing.T) {
	tools := newFakeTools(t)
	tools.flag(t, "has-credential-command", "")
	f := newCloneForge(t)
	work := t.TempDir() // no checkout here or above
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, true, work)
	if code := SetupZit(context.Background(), []string{"--host", f.srv.URL, "--json"}, e); code != 0 {
		t.Fatalf("FAIL: exit %d %q", code, out.String())
	}
	here, _ := filepath.EvalSymlinks(work)
	calls := tools.calls(t)
	inits, settings := 0, 0
	for _, c := range calls {
		cwd := strings.TrimPrefix(strings.SplitN(c.Env, "\n", 2)[0], "CWD=")
		if cwd == here {
			t.Errorf("FAIL: %q ran in the working directory", c.Args)
		}
		if strings.HasPrefix(c.Args, "zit init") {
			inits++
		}
		if strings.HasPrefix(c.Args, "zit settings") {
			settings++
		}
	}
	if inits < 2 || settings < 2 {
		t.Errorf("FAIL: expected a scratch store for the probe and for the set, got %d inits and %d settings calls", inits, settings)
	}
}

func TestSetupZitUndoClearsOnlyWhatThisClientSet(t *testing.T) {
	tools := newFakeTools(t)
	tools.flag(t, "has-credential-command", "")
	f := newCloneForge(t)
	run := func(cwd string) (int, map[string]any) {
		var out, errw bytes.Buffer
		e := cloneEnv(t, &out, &errw, f, false, cwd)
		code := SetupZit(context.Background(), []string{"--undo", "--json"}, e)
		return code, oneObject(t, out.String())
	}
	cleared := func() bool {
		for _, c := range tools.calls(t) {
			if c.Args == "zit settings --global credential-command " {
				return true
			}
		}
		return false
	}

	tools.flag(t, "cc-value", "some-other-helper")
	if code, m := run(t.TempDir()); code != 0 || m["ok"] != true || cleared() {
		t.Errorf("FAIL: a helper that is not this client's was touched: exit %d %v", code, m)
	}
	tools.flag(t, "cc-value", credentialHelper)
	code, m := run(t.TempDir())
	undone, _ := m["undone"].([]any)
	if code != 0 || len(undone) != 1 || undone[0] != "credential-command" || !cleared() {
		t.Errorf("FAIL: undo of the global setting: exit %d %v", code, m)
	}
	if b, _ := os.ReadFile(filepath.Join(tools.dir, "cc-value")); len(b) != 0 {
		t.Errorf("FAIL: the setting still holds %q", b)
	}

	// A primed zit checkout: the saved login goes with the remote, which
	// is put back.
	os.Remove(filepath.Join(tools.dir, "has-credential-command"))
	tools.flag(t, "remote", f.srv.URL+"/r/alex/site\n")
	root := t.TempDir()
	os.WriteFile(filepath.Join(root, ".zit-checkout"), nil, 0o644)
	code, m = run(root)
	undone, _ = m["undone"].([]any)
	if code != 0 || len(undone) != 1 || undone[0] != "primed login" {
		t.Errorf("FAIL: undo of a primed checkout: exit %d %v", code, m)
	}
	var seq []string
	for _, c := range tools.find(t, "zit remote") {
		seq = append(seq, c.Args)
	}
	if len(seq) != 3 || seq[1] != "zit remote --unset" || seq[2] != "zit remote "+f.srv.URL+"/r/alex/site" {
		t.Errorf("FAIL: remote calls %v", seq)
	}

	// A primed fossil checkout: its saved password is deleted.
	froot := t.TempDir()
	os.WriteFile(filepath.Join(froot, ".fslckout"), nil, 0o644)
	code, m = run(froot)
	sql := tools.find(t, "fossil sql")
	if code != 0 || len(sql) != 1 || !strings.Contains(sql[0].Stdin, "DELETE FROM config WHERE name='last-sync-pw'") {
		t.Errorf("FAIL: undo of a fossil checkout: exit %d %v %v", code, m, sql)
	}
}

func TestLogoutClearsAGlobalCredentialCommandThatIsThisClients(t *testing.T) {
	tools := newFakeTools(t)
	tools.flag(t, "has-credential-command", "")
	for _, tc := range []struct {
		value string
		want  bool
	}{{credentialHelper, true}, {"some-other-helper", false}} {
		tools.flag(t, "cc-value", tc.value)
		f := newEndForge(t)
		var out, errw bytes.Buffer
		st := &fakeStore{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 "" }
		if code := Logout(context.Background(), []string{f.srv.URL, "--json"}, e); code != 0 {
			t.Fatalf("FAIL: exit %d %q", code, out.String())
		}
		m := oneObject(t, out.String())
		got, _ := m["unhooked"].(bool)
		b, _ := os.ReadFile(filepath.Join(tools.dir, "cc-value"))
		if got != tc.want || (tc.want && len(b) != 0) || (!tc.want && string(b) != tc.value) {
			t.Errorf("FAIL: value %q: unhooked %v, setting now %q", tc.value, got, b)
		}
	}
}

// A file that appears at the repository file's name while the clone runs
// is somebody else's: the failure that follows does not remove it.
func TestAFailedFossilCloneNeverRemovesAFileItDidNotMake(t *testing.T) {
	newFakeTools(t)
	f := newCloneForge(t)
	work := t.TempDir()
	var out, errw bytes.Buffer
	e := cloneEnv(t, &out, &errw, f, true, work)
	repo := filepath.Join(work, "site.fossil")
	e.FossilStart = func(ctx context.Context, dir string, args []string, started func(int)) (string, error) {
		os.WriteFile(args[len(args)-1], nil, 0o644) // fossil's file
		os.WriteFile(repo, []byte("theirs"), 0o644) // a racer's
		return "", nil
	}
	code := Clone(context.Background(), cloneArgs(f, "alex/site", filepath.Join(work, "site"), "--fossil", "--json"), e)
	if code != 1 {
		t.Fatalf("FAIL: exit %d %q", code, out.String())
	}
	if b, _ := os.ReadFile(repo); string(b) != "theirs" {
		t.Errorf("FAIL: the file at the repository's name was removed or replaced: %q", b)
	}
	ents, _ := os.ReadDir(work)
	for _, en := range ents {
		if strings.HasPrefix(en.Name(), ".site.fossil.") {
			t.Errorf("FAIL: the clone's own temporary file was left: %s", en.Name())
		}
	}
}

func TestFossilCloneWithALoginIsRefusedWhereThereIsNoPeerCheck(t *testing.T) {
	tools := newFakeTools(t)
	f := newCloneForge(t)
	old := clonePeerCheck
	clonePeerCheck = false // a platform with no peer check
	defer func() { clonePeerCheck = old }()
	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"), "--fossil", "--json"), e)
	m := oneObject(t, out.String())
	if code != 1 || m["code"] != "unsupported" || 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", n)
	}
	if _, err := os.Stat(filepath.Join(work, "site")); err == nil {
		t.Errorf("FAIL: a directory was left behind")
	}
	// Anonymous --fossil, and zit, are not affected.
	out.Reset()
	e = cloneEnv(t, &out, &errw, f, false, work)
	if code := Clone(context.Background(), cloneArgs(f, "alex/open", filepath.Join(work, "open"), "--fossil", "--json"), e); code != 0 {
		t.Errorf("FAIL: an anonymous fossil clone: exit %d %q", code, out.String())
	}
}