Skip to content
quarry Artifact [3cec41a428]
Login

Artifact [3cec41a428]

Artifact 3cec41a42801a19ce3d4a8f4c11c39fffec27889cd6659f84141f809701bfdb9:


package pickupclient

import (
	"bufio"
	"context"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"
	"syscall"
)

// quarry repo clone and quarry auth setup-zit (RFC 0033 step 5): code
// without a password. The token reaches zit in the environment of the one
// child that needs it (ZIT_PASSWORD, never argv), zit saves a secret
// derived from it in the checkout, and nothing here writes the token to
// any file or remote. When the installed zit has the credential-command
// setting, setup-zit sets it once instead and zit asks quarry for a login
// whenever it needs one.

const credentialSetting = "credential-command"

// credentialHelper is what the setting is set to; zit runs it with the
// words get, store or erase.
const credentialHelper = "quarry auth credential"

const cloneHelp = `usage: quarry repo clone OWNER/NAME [DIR] [--fossil] [--host URL] [--json] [-- ZIT-ARGS]

Copy a repository here with zit, signed in as this machine's login, and
leave the checkout so that zit pull and zit push need no password. The
repository must exist and the login must be able to read it. A public
repository clones with no login (and says how to log in before pushing).

  DIR      where to put it (default: NAME); refused if it exists and is not empty
  --fossil clone with stock fossil instead; DIR holds the checkout and
           DIR.fossil the repository file. The token is given to fossil
           by a short-lived proxy on loopback, never on its command line
  --host   the forge (default: QUARRY_HOST, else the one the installer recorded)
  --json   one JSON object on stdout
  --       what follows goes to zit clone (--horizon, --cone, ...)

Exit: 0 cloned, 1 refused, 2 usage, 4 not logged in.

Example:
  quarry repo clone alex/website
`

const setupHelp = `usage: quarry auth setup-zit [--host URL] [--undo] [--json]

Set up zit to sign in to a forge with this machine's login. With a zit
that has the credential-command setting, that is one global setting and
every checkout works. With one that has not, run it inside a checkout:
the checkout is signed in once, here, and syncs with no password after.
In a fossil checkout it does the same for fossil.

  --host   the forge (default: QUARRY_HOST, else the checkout's remote,
           else the one the installer recorded)
  --undo   take it back: clear this client's credential-command, and the
           login this checkout was primed with
  --json   one JSON object on stdout

Exit: 0 done, 1 refused, 2 usage, 4 not logged in.

Example:
  quarry auth setup-zit
`

var (
	repoAddress = regexp.MustCompile(`^([A-Za-z0-9][A-Za-z0-9._-]{0,63})/([A-Za-z0-9][A-Za-z0-9._-]{0,63})$`)
	// plainToken is what a forge's tokens are made of; anything else is
	// not put into a SQL line or a URL.
	plainToken = regexp.MustCompile(`^[A-Za-z0-9_.~-]{8,512}$`)
)

// hostArg turns --host into a forge origin; a bare host name is https.
func hostArg(raw string) string {
	if raw != "" && !strings.Contains(raw, "://") {
		return "https://" + raw
	}
	return raw
}

// forgeFor is the forge a verb works against: --host, QUARRY_HOST, else
// the fallback the verb passes (its checkout's remote), else the default.
func (e *Env) forgeFor(flag string, fallback *url.URL) (*url.URL, error) {
	if flag != "" {
		return forgeOf(hostArg(flag))
	}
	if h := strings.TrimSpace(e.Getenv(envHostVar)); h != "" {
		return forgeOf(hostArg(h))
	}
	if fallback != nil {
		return forgeOf(fallback.Scheme + "://" + fallback.Host)
	}
	return e.forgeOf("")
}

// emptyOrMissing says whether dir is absent (true), or present and empty
// (false); anything else is an error saying why it is not a place to clone.
func emptyOrMissing(dir string) (missing bool, err error) {
	st, err := os.Stat(dir)
	switch {
	case errors.Is(err, os.ErrNotExist):
		return true, nil
	case err != nil:
		return false, err
	case !st.IsDir():
		return false, errors.New("it is a file")
	}
	ents, err := os.ReadDir(dir)
	if err != nil {
		return false, err
	}
	if len(ents) > 0 {
		return false, errors.New("it is not empty")
	}
	return false, nil
}

// claimDir makes dir, atomically: created says this call made it. A
// directory that already exists is usable only when it is empty, and is
// then not the caller's to remove.
func claimDir(dir string) (created bool, err error) {
	if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil {
		return false, err
	}
	err = os.Mkdir(dir, 0o755)
	if err == nil {
		return true, nil
	}
	if !errors.Is(err, os.ErrExist) {
		return false, err
	}
	if _, err := emptyOrMissing(dir); err != nil {
		return false, err
	}
	return false, nil
}

// readable is the forge's answer to whether a repository can be read with
// a token (or none): the repository's own info, which answers 404 for a
// repository that is missing or that the caller may not read.
type readable struct {
	Checkins int `json:"checkins"`
}

func (e *Env) readRepo(ctx context.Context, base *url.URL, owner, name, token string) (readable, int, error) {
	var r readable
	u := base.ResolveReference(&url.URL{Path: "/api/v1/r/" + owner + "/" + name + "/info"})
	req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
	if err != nil {
		return r, 0, err
	}
	if token != "" {
		req.Header.Set("Authorization", "Bearer "+token)
	}
	resp, err := e.Client.Do(req)
	if err != nil {
		var ue *url.Error
		if errors.As(err, &ue) {
			err = ue.Err
		}
		return r, 0, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == http.StatusOK {
		_ = json.NewDecoder(io.LimitReader(resp.Body, pickupBodyMax)).Decode(&r)
	}
	return r, resp.StatusCode, nil
}

// scrubber hides a token in anything a child printed.
func scrubber(token string) func(string) string {
	return func(s string) string {
		if token != "" {
			s = strings.ReplaceAll(s, token, "***")
		}
		return s
	}
}

func (e *Env) cloneStep(ctx context.Context, dir, token string, args ...string) (string, error) {
	var env []string
	if token != "" {
		env = []string{"ZIT_PASSWORD=" + token}
	}
	return e.Run(ctx, dir, env, args)
}

type cloneJSON struct {
	OK       bool      `json:"ok"`
	Host     string    `json:"host"`
	Repo     string    `json:"repo"`
	Dir      string    `json:"dir"`
	Account  string    `json:"account,omitempty"`
	Fossil   bool      `json:"fossil"`
	Checkins int       `json:"checkins"`
	Signed   bool      `json:"signedIn"`
	Next     *nextJSON `json:"next"`
}

// clonePlatform is runtime.GOOS; a test sets it.
var clonePlatform = runtime.GOOS

// Clone is quarry repo clone: 0 cloned, 1 refused, 2 usage, 4 not logged
// in.
func Clone(ctx context.Context, args []string, e *Env) int {
	e.fillLogin()
	args, asJSON := stripJSON(args)
	v := voice{e, e.named("repo clone"), asJSON}
	usage := func(msg string) int {
		return v.refuse(2, "usage", msg, false, &nextJSON{Say: "See quarry repo clone --help.", Cmd: "quarry repo clone --help"})
	}
	var pos, zitArgs []string
	useFossil, hostFlag := false, ""
	for i := 0; i < len(args); i++ {
		a := args[i]
		switch {
		case a == "--":
			zitArgs = args[i+1:]
			i = len(args)
		case a == "-h" || a == "--help" || a == "-help":
			fmt.Fprint(e.Stdout, cloneHelp)
			return 0
		case a == "--fossil":
			useFossil = true
		case a == "--host" && i+1 < len(args):
			i++
			hostFlag = args[i]
		case strings.HasPrefix(a, "--host="):
			hostFlag = strings.TrimPrefix(a, "--host=")
		case strings.HasPrefix(a, "-"):
			return usage("usage: quarry repo clone OWNER/NAME [DIR] [--fossil] [--json] [-- ZIT-ARGS]")
		default:
			pos = append(pos, a)
		}
	}
	if len(pos) < 1 || len(pos) > 2 {
		return usage("usage: quarry repo clone OWNER/NAME [DIR] [--fossil] [--json] [-- ZIT-ARGS]")
	}
	m := repoAddress.FindStringSubmatch(pos[0])
	if m == nil {
		return usage("the repository is named OWNER/NAME, for example alex/website")
	}
	owner, name := m[1], m[2]
	if useFossil && len(zitArgs) > 0 {
		return usage("what follows -- goes to zit clone; with --fossil there is nothing for it to go to")
	}
	dirArg := name
	if len(pos) == 2 {
		dirArg = pos[1]
	}
	dir, err := filepath.Abs(dirArg)
	if err != nil {
		return usage(show(err.Error()))
	}
	base, err := e.forgeFor(hostFlag, nil)
	if err != nil {
		return usage(show(err.Error()))
	}
	if _, derr := emptyOrMissing(dir); derr != nil {
		return v.refuse(1, "dir_not_empty", dirArg+" already exists and is not a place to clone into: "+derr.Error(), false,
			&nextJSON{Say: "Name a directory that does not exist yet, or is empty."})
	}
	repoFile := ""
	if useFossil {
		repoFile = dir + ".fossil"
		if _, serr := os.Stat(repoFile); serr == nil {
			return v.refuse(1, "dir_not_empty", filepath.Base(repoFile)+" already exists next to "+dirArg, false,
				&nextJSON{Say: "Name another directory, or move that file."})
		}
	}

	// Who is asking. A login is read through the forge (which also says
	// whether it still takes the token); with none, a public repository
	// still clones.
	token, account := "", ""
	if rec, ok := e.token(base); ok {
		me, merr := e.readMe(ctx, base, rec.Token)
		var se statusError
		switch {
		case merr == nil:
			token, account = rec.Token, me.Name
			if !pickupAgentName.MatchString(account) {
				return v.refuse(1, "refused", "the forge named an account this client will not use", false, nil)
			}
		case errors.As(merr, &se):
			next := &nextJSON{Say: "Log this machine in again.", Cmd: loginCmd, Help: credsHelp}
			if rec.Source == "env" {
				next = &nextJSON{Say: "Unset or replace " + tokenEnvVar + "; it is the token in use here.", Help: credsHelp}
			}
			return v.refuse(1, "refused", "the forge does not take the login: "+show(merr.Error()), false, next)
		default:
			return v.refuse(1, "unreachable", "the forge could not be reached: "+show(merr.Error()), false,
				&nextJSON{Say: "Check the address and the network, then run this again.", Cmd: "quarry repo clone " + pos[0]})
		}
	}
	info, status, rerr := e.readRepo(ctx, base, owner, name, token)
	switch {
	case rerr != nil:
		return v.refuse(1, "unreachable", "the forge could not be reached: "+show(rerr.Error()), false,
			&nextJSON{Say: "Check the address and the network, then run this again.", Cmd: "quarry repo clone " + pos[0]})
	case status == http.StatusNotFound && token == "":
		// Not public, or not there: either way the way forward is a login.
		return v.noLogin(base)
	case status == http.StatusNotFound:
		return v.refuse(1, "no_access", "there is no repository "+pos[0]+" on "+base.Host+" that this login can read", false,
			&nextJSON{Say: "Check the name; for one that exists, ask its owner for a role on it.", Cmd: "quarry auth status", Help: credsHelp})
	case status != http.StatusOK:
		return v.refuse(1, "refused", fmt.Sprintf("the forge answered %d about %s", status, pos[0]), false, nil)
	}

	syncURL := base.Scheme + "://" + base.Host + "/r/" + owner + "/" + name
	scrub := scrubber(token)
	// The directory is made here, by Mkdir, which fails if anything is
	// there; what a failure removes is only what this made.
	created, cerr := claimDir(dir)
	if cerr != nil {
		return v.refuse(1, "dir_not_empty", dirArg+" already exists and is not a place to clone into: "+cerr.Error(), false,
			&nextJSON{Say: "Name a directory that does not exist yet, or is empty."})
	}
	if useFossil && token != "" && clonePlatform == "windows" {
		// The loopback proxy that keeps the token off fossil's command
		// line can tell which process is calling it on Linux and macOS
		// only; with none, any local user could read through it.
		return v.refuse(1, "unsupported", "a --fossil clone with a login is not supported on Windows", false,
			&nextJSON{Say: "Clone with zit, or clone a public repository with --fossil and no login.", Cmd: "quarry repo clone " + pos[0]})
	}
	// made is the files this call made outside the directory, and so the
	// only files a failure may remove.
	var made []string
	fail := func(what, out string) int {
		if created {
			os.RemoveAll(dir)
		}
		for _, f := range made {
			os.Remove(f)
		}
		return v.refuse(1, "clone_failed", what+" failed: "+show(scrub(strings.TrimSpace(tail(out, 400)))), false,
			&nextJSON{Say: "Read what it said, fix that, and run this again.", Cmd: "quarry repo clone " + pos[0]})
	}
	if useFossil {
		if code := e.fossilClone(ctx, v, base, owner, name, dir, repoFile, account, token, &made, fail); code != 0 {
			return code
		}
	} else {
		cargs := []string{"clone", syncURL, dir}
		if token != "" {
			cargs = append(cargs, "--user", account)
		}
		cargs = append(cargs, zitArgs...)
		if out, err := e.cloneStep(ctx, "", token, cargs...); err != nil {
			if errors.Is(err, exec.ErrNotFound) {
				return v.refuse(1, "no_zit", "zit is not on PATH", false, &nextJSON{Say: "Install zit, or clone with --fossil if you have fossil."})
			}
			return fail("zit clone", out)
		}
		if token != "" {
			// The test of "no password": a bare pull, with nothing in its
			// environment, must be answered.
			if out, err := e.cloneStep(ctx, dir, "", "pull"); err != nil {
				return v.refuse(1, "not_primed", "the clone is at "+dirArg+" but a pull there still asks for a password: "+show(scrub(strings.TrimSpace(tail(out, 400)))), false,
					&nextJSON{Say: "Sign the checkout in again.", Cmd: "quarry auth setup-zit"})
			}
		}
	}

	next := &nextJSON{Say: "Make your change on a branch, then commit it.", Cmd: "cd " + shellWord(dirArg)}
	if asJSON {
		v.print(cloneJSON{OK: true, Host: base.Host, Repo: owner + "/" + name, Dir: dir, Account: show(account), Fossil: useFossil,
			Checkins: info.Checkins, Signed: token != "", Next: next})
		return 0
	}
	tool := "zit"
	if useFossil {
		tool = "fossil"
	}
	who := "anonymously"
	if token != "" {
		who = "as " + show(account)
	}
	fmt.Fprintf(e.Stdout, "Cloned %s into %s (%d check-ins) %s.\n", pos[0], dirArg, info.Checkins, who)
	if token != "" {
		fmt.Fprintf(e.Stdout, "  %s pull and %s push work here with no password.\n", tool, tool)
	} else {
		fmt.Fprintf(e.Stdout, "  Public, so no login was used. To push, log in first: %s, then quarry auth setup-zit here.\n", loginCmd)
	}
	if useFossil {
		fmt.Fprintf(e.Stdout, "  The repository file is %s.\n", filepath.Base(repoFile))
	}
	fmt.Fprintf(e.Stdout, "Next: cd %s, then %s commit --branch NAME\n", shellWord(dirArg), tool)
	return 0
}

// fossilClone clones with stock fossil. A private repository's first
// request needs the password, and fossil takes it from nowhere but the
// address on its command line, so it is given the address of a loopback
// proxy that adds the token (authProxy) and the token never reaches a
// command line. When the clone is done the repository is pointed at the
// forge, with the account and no password, and the password is stored
// through fossil's SQL prompt, as setup-zit stores it.
func (e *Env) fossilClone(ctx context.Context, v voice, base *url.URL, owner, name, dir, repoFile, account, token string, made *[]string, fail func(string, string) int) int {
	syncPath := "/r/" + owner + "/" + name
	real := url.URL{Scheme: base.Scheme, Host: base.Host, Path: syncPath}
	from, nonce := real.String(), ""
	var proxy *authProxy
	if token != "" {
		if !plainToken.MatchString(token) {
			return v.refuse(1, "refused", "the login is not in a form fossil can be given", false, nil)
		}
		var cancel, stop context.CancelFunc
		ctx, cancel = context.WithCancel(ctx)
		defer cancel()
		ctx, stop = signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
		defer stop()
		p, err := startAuthProxy(ctx, base, syncPath, account, token)
		if err != nil {
			return fail("starting the local proxy", err.Error())
		}
		defer p.Close()
		proxy, from, nonce = p, p.URL, p.nonce
	}
	scrub := scrubber(token)
	// Fossil clones to a file with a name nobody can have chosen, which
	// is then linked to its real name (link fails where a file is), so
	// that a failure removes only files this call made.
	var rnd [6]byte
	if _, err := rand.Read(rnd[:]); err != nil {
		return fail("making a file name", err.Error())
	}
	tmp := filepath.Join(filepath.Dir(repoFile), "."+filepath.Base(repoFile)+"."+hex.EncodeToString(rnd[:]))
	*made = append(*made, tmp)
	var started func(int)
	if proxy != nil {
		started = proxy.SetPID
	}
	if out, err := e.FossilStart(ctx, "", []string{"clone", "--no-open", from, tmp}, started); err != nil {
		if errors.Is(err, exec.ErrNotFound) {
			return v.refuse(1, "no_fossil", "fossil is not on PATH", false, &nextJSON{Say: "Install fossil, or clone with zit."})
		}
		if proxy != nil {
			for _, r := range proxy.Refusals() {
				out += "\nthe local proxy " + r
			}
		}
		return fail("fossil clone", scrub(out))
	}
	if err := os.Link(tmp, repoFile); err != nil {
		return fail("naming the repository file", err.Error())
	}
	*made = append(*made, repoFile)
	os.Remove(tmp)
	if out, err := e.Fossil(ctx, dir, "", []string{"open", "--nosync", repoFile}); err != nil {
		return fail("fossil open", scrub(out))
	}
	if token == "" {
		return 0
	}
	if out, err := e.fossilSignIn(ctx, dir, real, account, token, nonce); err != nil {
		return fail("signing the clone in", scrub(out))
	}
	if out, err := e.Fossil(ctx, dir, "", []string{"pull"}); err != nil {
		return v.refuse(1, "not_primed", "the clone is at "+dir+" but a pull there still asks for a password: "+show(scrub(strings.TrimSpace(tail(out, 400)))), false,
			&nextJSON{Say: "Sign the checkout in again.", Cmd: "quarry auth setup-zit"})
	}
	return 0
}

// fossilSignIn points the checkout's repository at remote with the
// account and stores the password, obscured by fossil's own function,
// by SQL on the prompt's standard input: fossil's `remote` command
// tries the server and its own prompt takes nothing from a pipe. It also
// drops what the clone recorded about the proxy's address, when there was
// one.
func (e *Env) fossilSignIn(ctx context.Context, dir string, remote url.URL, account, token, nonce string) (string, error) {
	remote.User = url.User(account)
	sql := "REPLACE INTO config(name,value,mtime) VALUES('last-sync-url','" + strings.ReplaceAll(remote.String(), "'", "''") + "', now());\n" +
		"REPLACE INTO config(name,value,mtime) VALUES('last-sync-pw', obscure('" + token + "'), now());\n"
	if nonce != "" {
		sql += "DELETE FROM config WHERE name LIKE '%" + nonce + "%' OR value LIKE '%" + nonce + "%';\n"
	}
	if out, err := e.Fossil(ctx, dir, sql, []string{"sql"}); err != nil {
		return "fossil sql: " + out, err
	}
	return "", nil
}

// checkoutKind says which tool the checkout at or above dir belongs to.
func checkoutKind(dir string) (kind, root string) {
	for d := dir; ; {
		if _, err := os.Stat(filepath.Join(d, ".zit-checkout")); err == nil {
			return "zit", d
		}
		for _, f := range []string{".fslckout", "_FOSSIL_"} {
			if _, err := os.Stat(filepath.Join(d, f)); err == nil {
				return "fossil", d
			}
		}
		p := filepath.Dir(d)
		if p == d {
			return "", ""
		}
		d = p
	}
}

// zitGlobal runs `zit settings --global ARGS` and returns what it
// printed. zit wants a checkout even for a global setting, so it runs in
// a throwaway store made for the call: the answer does not depend on the
// directory quarry was started in, or on there being a checkout at all.
func (e *Env) zitGlobal(ctx context.Context, args ...string) (string, error) {
	d, err := os.MkdirTemp("", "quarry-zit-")
	if err != nil {
		return "", err
	}
	defer os.RemoveAll(d)
	if out, err := e.Run(ctx, d, nil, []string{"init"}); err != nil {
		return out, err
	}
	return e.Run(ctx, d, nil, append([]string{"settings", "--global"}, args...))
}

// zitHasCredentialCommand asks the installed zit whether it knows the
// setting: reading a setting it does not know is an error naming the
// ones it does, and reading one it knows succeeds, set or not. That
// asks the binary, not its version number or its help text, so it
// turns on by itself in whichever release first has the setting.
func (e *Env) zitHasCredentialCommand(ctx context.Context) bool {
	_, err := e.zitGlobal(ctx, credentialSetting)
	return err == nil
}

// removeHook clears the global credential-command when it is this
// client's, and says whether it did. A zit that lacks the setting, or a
// setting that is someone else's, is left alone.
func (e *Env) removeHook(ctx context.Context) (bool, error) {
	out, err := e.zitGlobal(ctx, "--value", credentialSetting)
	if err != nil {
		return false, nil
	}
	if strings.TrimSpace(out) != credentialHelper {
		return false, nil
	}
	if o, err := e.zitGlobal(ctx, credentialSetting, ""); err != nil {
		return false, fmt.Errorf("%s", strings.TrimSpace(tail(o, 200)))
	}
	return true, nil
}

type setupJSON struct {
	OK      bool      `json:"ok"`
	Host    string    `json:"host"`
	Account string    `json:"account"`
	Tool    string    `json:"tool"`
	Mode    string    `json:"mode"`
	Dir     string    `json:"dir,omitempty"`
	Set     string    `json:"set,omitempty"`
	Next    *nextJSON `json:"next"`
}

type undoJSON struct {
	OK   bool     `json:"ok"`
	Undo []string `json:"undone"`
	Dir  string   `json:"dir,omitempty"`
}

// SetupZit is quarry auth setup-zit: 0 done, 1 refused, 2 usage, 4 not
// logged in.
func SetupZit(ctx context.Context, args []string, e *Env) int {
	e.fillLogin()
	args, asJSON := stripJSON(args)
	v := voice{e, e.named("auth setup-zit"), asJSON}
	usage := func(msg string) int {
		return v.refuse(2, "usage", msg, false, &nextJSON{Say: "See quarry auth setup-zit --help.", Cmd: "quarry auth setup-zit --help"})
	}
	hostFlag, undo := "", false
	for i := 0; i < len(args); i++ {
		a := args[i]
		switch {
		case a == "-h" || a == "--help" || a == "-help":
			fmt.Fprint(e.Stdout, setupHelp)
			return 0
		case a == "--undo":
			undo = true
		case a == "--host" && i+1 < len(args):
			i++
			hostFlag = args[i]
		case strings.HasPrefix(a, "--host="):
			hostFlag = strings.TrimPrefix(a, "--host=")
		default:
			return usage("usage: quarry auth setup-zit [--host URL] [--undo] [--json]")
		}
	}
	cwd, err := e.Getwd()
	if err != nil {
		return v.refuse(1, "refused", "this directory cannot be read: "+show(err.Error()), false, nil)
	}
	kind, root := checkoutKind(cwd)
	if undo {
		return e.undoSetup(ctx, v, asJSON, kind, root)
	}
	hasHook := kind != "fossil" && e.zitHasCredentialCommand(ctx)
	if !hasHook && kind == "" {
		return v.refuse(1, "not_a_checkout", "this is not inside a checkout", false,
			&nextJSON{Say: "Run this inside a checkout, or clone with quarry repo clone, which signs the clone in."})
	}

	// The forge: given, else the checkout's remote, else the default.
	var remote *url.URL
	if kind != "" && !hasHook {
		remote = e.checkoutRemote(ctx, kind, root)
		if remote == nil {
			return v.refuse(1, "no_remote", "the checkout at "+root+" has no remote to sign in to", false,
				&nextJSON{Say: "Set its remote first.", Cmd: kind + " remote URL"})
		}
		if remote.Scheme == "http" && !isLoopbackHost(remote.Host) {
			return v.refuse(1, "insecure_remote", "the checkout's remote is plain http to "+remote.Host+"; a login is not sent that way", false,
				&nextJSON{Say: "Point the remote at the forge's https address.", Cmd: kind + " remote https://" + remote.Host + remote.Path})
		}
	}
	base, err := e.forgeFor(hostFlag, remote)
	if err != nil {
		return usage(show(err.Error()))
	}
	rec, ok := e.token(base)
	if !ok {
		return v.noLogin(base)
	}
	me, merr := e.readMe(ctx, base, rec.Token)
	if merr != nil {
		var se statusError
		if errors.As(merr, &se) {
			return v.refuse(1, "refused", "the forge does not take the login: "+show(merr.Error()), false,
				&nextJSON{Say: "Log this machine in again.", Cmd: loginCmd, Help: credsHelp})
		}
		return v.refuse(1, "unreachable", "the forge could not be reached: "+show(merr.Error()), false,
			&nextJSON{Say: "Check the network, then run this again.", Cmd: "quarry auth setup-zit"})
	}
	account, token := me.Name, rec.Token
	if !pickupAgentName.MatchString(account) {
		return v.refuse(1, "refused", "the forge named an account this client will not use", false, nil)
	}
	scrub := scrubber(token)

	out := setupJSON{OK: true, Host: base.Host, Account: show(account)}
	switch {
	case hasHook:
		if o, err := e.zitGlobal(ctx, credentialSetting, credentialHelper); err != nil {
			return v.refuse(1, "setup_failed", "zit would not take the setting: "+show(scrub(strings.TrimSpace(tail(o, 400)))), false, nil)
		}
		out.Tool, out.Mode, out.Set = "zit", "credential-command", credentialSetting
	case kind == "zit":
		if !sameOrigin(remote, base) {
			return v.refuse(1, "other_forge", "the checkout's remote is on "+remote.Scheme+"://"+remote.Host+", not "+base.Scheme+"://"+base.Host, false, nil)
		}
		if o, err := e.cloneStep(ctx, root, token, "pull", "--user", account); err != nil {
			return v.refuse(1, "setup_failed", "zit pull failed: "+show(scrub(strings.TrimSpace(tail(o, 400)))), false,
				&nextJSON{Say: "Check that this login can read the repository.", Cmd: "quarry auth status"})
		}
		if o, err := e.cloneStep(ctx, root, "", "pull"); err != nil {
			return v.refuse(1, "not_primed", "a pull here still asks for a password: "+show(scrub(strings.TrimSpace(tail(o, 400)))), false, nil)
		}
		out.Tool, out.Mode, out.Dir = "zit", "primed", root
	default:
		if !sameOrigin(remote, base) {
			return v.refuse(1, "other_forge", "the checkout's remote is on "+remote.Scheme+"://"+remote.Host+", not "+base.Scheme+"://"+base.Host, false, nil)
		}
		if !plainToken.MatchString(token) {
			return v.refuse(1, "refused", "the login is not in a form fossil can be given", false, nil)
		}
		if o, err := e.fossilSignIn(ctx, root, *remote, account, token, ""); err != nil {
			return v.refuse(1, "setup_failed", show(scrub(strings.TrimSpace(tail(o, 400)))), false, nil)
		}
		if o, err := e.Fossil(ctx, root, "", []string{"pull"}); err != nil {
			return v.refuse(1, "not_primed", "a pull here still asks for a password: "+show(scrub(strings.TrimSpace(tail(o, 400)))), false, nil)
		}
		out.Tool, out.Mode, out.Dir = "fossil", "primed", root
	}
	out.Next = &nextJSON{Say: "Sync as usual.", Cmd: out.Tool + " pull"}
	if asJSON {
		v.print(out)
		return 0
	}
	if out.Mode == "credential-command" {
		fmt.Fprintf(e.Stdout, "zit will now ask quarry for a login whenever a forge needs one.\n")
		fmt.Fprintf(e.Stdout, "  set   %s = %s   (zit settings --global)\n", credentialSetting, credentialHelper)
		fmt.Fprintf(e.Stdout, "Try it: zit pull\n")
		return 0
	}
	fmt.Fprintf(e.Stdout, "%s now syncs with %s as %s.\n", root, base.Host, show(account))
	fmt.Fprintf(e.Stdout, "  %s pull, %s push and autosync work here with no password.\n", out.Tool, out.Tool)
	fmt.Fprintf(e.Stdout, "  Other checkouts: run this in each, or clone with quarry repo clone.\n")
	return 0
}

// undoSetup takes back what setup-zit did: the global credential-command
// when it is this client's, and the primed login of the checkout the
// command runs in. Nothing is asked of the forge.
func (e *Env) undoSetup(ctx context.Context, v voice, asJSON bool, kind, root string) int {
	var undone []string
	if kind != "fossil" {
		if ok, err := e.removeHook(ctx); err != nil {
			return v.refuse(1, "setup_failed", "zit would not clear the setting: "+show(err.Error()), false, nil)
		} else if ok {
			undone = append(undone, credentialSetting)
		}
	}
	switch kind {
	case "zit":
		// A saved login belongs to the saved remote, and unsetting the
		// remote drops it; the remote is then put back as it was.
		if u := e.checkoutRemote(ctx, "zit", root); u != nil {
			if o, err := e.Run(ctx, root, nil, []string{"remote", "--unset"}); err != nil {
				return v.refuse(1, "setup_failed", "zit remote --unset failed: "+show(tail(o, 200)), false, nil)
			}
			if o, err := e.Run(ctx, root, nil, []string{"remote", u.String()}); err != nil {
				return v.refuse(1, "setup_failed", "the remote could not be put back ("+u.String()+"): "+show(tail(o, 200)), false, nil)
			}
			undone = append(undone, "primed login")
		}
	case "fossil":
		sql := "DELETE FROM config WHERE name='last-sync-pw';\n"
		if o, err := e.Fossil(ctx, root, sql, []string{"sql"}); err != nil {
			return v.refuse(1, "setup_failed", "fossil sql failed: "+show(tail(o, 200)), false, nil)
		}
		undone = append(undone, "primed login")
	}
	if undone == nil {
		undone = []string{}
	}
	if asJSON {
		v.print(undoJSON{OK: true, Undo: undone, Dir: root})
		return 0
	}
	if len(undone) == 0 {
		fmt.Fprintln(e.Stdout, "Nothing to undo: no credential-command of this client's is set, and this is not a signed-in checkout.")
		return 0
	}
	fmt.Fprintf(e.Stdout, "Undone: %s.\n", strings.Join(undone, ", "))
	return 0
}

// checkoutRemote is the address a checkout syncs with, without any login
// in it; nil when it has none.
func (e *Env) checkoutRemote(ctx context.Context, kind, root string) *url.URL {
	var out string
	var err error
	if kind == "zit" {
		out, err = e.Run(ctx, root, nil, []string{"remote"})
	} else {
		out, err = e.Fossil(ctx, root, "", []string{"remote"})
	}
	if err != nil {
		return nil
	}
	u := pickupRemote(out)
	if u == nil {
		return nil
	}
	c := *u
	c.User = nil
	return &c
}

// Credential is quarry auth credential, the helper zit's credential-command
// runs: git's credential-helper protocol on standard input and output. It
// answers "get" for a forge this machine is logged in to, and nothing for
// every other word or host.
func Credential(ctx context.Context, args []string, e *Env) int {
	e.fillLogin()
	if f, ok := e.Stdout.(*os.File); ok {
		if st, err := f.Stat(); err == nil && st.Mode()&os.ModeCharDevice != 0 {
			fmt.Fprintln(e.Stderr, "quarry auth credential: this is for zit to call, and it will not print a token to a terminal")
			return 2
		}
	}
	stdin := e.Stdin
	if stdin == nil {
		stdin = os.Stdin
	}
	if len(args) != 1 || args[0] != "get" {
		return 0
	}
	attrs := map[string]string{}
	sc := bufio.NewScanner(io.LimitReader(stdin, 1<<16))
	for sc.Scan() {
		line := sc.Text()
		if line == "" {
			break
		}
		if k, v, ok := strings.Cut(line, "="); ok {
			attrs[k] = v
		}
	}
	if attrs["protocol"] != "http" && attrs["protocol"] != "https" || attrs["host"] == "" {
		return 0
	}
	base, err := forgeOf(attrs["protocol"] + "://" + attrs["host"])
	if err != nil {
		return 0
	}
	rec, ok := e.token(base)
	if !ok {
		return 0
	}
	account := rec.Account
	if account == "" {
		me, err := e.readMe(ctx, base, rec.Token)
		if err != nil {
			return 0
		}
		account = me.Name
	}
	if !pickupAgentName.MatchString(account) {
		return 0
	}
	fmt.Fprintf(e.Stdout, "username=%s\npassword=%s\n", account, rec.Token)
	return 0
}