Skip to content
quarry Artifact [3bdf4324dd]
Login

Artifact [3bdf4324dd]

Artifact 3bdf4324ddc34d43f52936dd64e758f869ccfb04812a835a645e8da33e6bfe99:


package pickupclient

import (
	"bufio"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
)

// 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. Fossil has no way to take the
           first password but on its command line, so for the life of that
           one clone the token is in fossil's arguments
  --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] [--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)
  --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
}

// 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"`
}

// 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()))
	}
	missing, derr := emptyOrMissing(dir)
	if 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)
	fail := func(what, out string) int {
		if missing {
			os.RemoveAll(dir)
		}
		if repoFile != "" {
			os.Remove(repoFile)
		}
		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, 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 (it reads no environment, no standard
// input and, without a terminal, asks for nothing); --save-http-password
// is what keeps it for later commands.
func (e *Env) fossilClone(ctx context.Context, v voice, base *url.URL, owner, name, dir, repoFile, account, token string, fail func(string, string) int) int {
	u := url.URL{Scheme: base.Scheme, Host: base.Host, Path: "/r/" + owner + "/" + name}
	if token != "" {
		if !plainToken.MatchString(token) {
			return v.refuse(1, "refused", "the login is not in a form fossil can be given", false, nil)
		}
		u.User = url.UserPassword(account, token)
	}
	args := []string{"clone", "--save-http-password", "--workdir", dir, u.String(), repoFile}
	if token == "" {
		args = []string{"clone", "--workdir", dir, u.String(), repoFile}
	}
	if out, err := e.Fossil(ctx, "", "", args); 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."})
		}
		return fail("fossil clone", out)
	}
	if token != "" {
		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(scrubber(token)(strings.TrimSpace(tail(out, 400)))), false,
				&nextJSON{Say: "Sign the checkout in again.", Cmd: "quarry auth setup-zit"})
		}
	}
	return 0
}

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

// 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.Run(ctx, "", nil, []string{"settings", "--global", credentialSetting})
	return err == 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"`
}

// 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 := ""
	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 == "--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] [--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)
	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"})
		}
	}
	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.Run(ctx, "", nil, []string{"settings", "--global", 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 remote.Host != base.Host {
			return v.refuse(1, "other_forge", "the checkout's remote is on "+remote.Host+", not "+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 remote.Host != base.Host {
			return v.refuse(1, "other_forge", "the checkout's remote is on "+remote.Host+", not "+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)
		}
		// The password goes to fossil's own table through its SQL
		// prompt's standard input, obscured by fossil's own function, so
		// it is on no command line.
		signed := *remote
		signed.User = url.User(account)
		if o, err := e.Fossil(ctx, root, "", []string{"remote", signed.String()}); err != nil {
			return v.refuse(1, "setup_failed", "fossil remote failed: "+show(scrub(strings.TrimSpace(tail(o, 400)))), false, nil)
		}
		sql := "REPLACE INTO config(name,value,mtime) VALUES('last-sync-pw', obscure('" + token + "'), now());\n"
		if o, err := e.Fossil(ctx, root, sql, []string{"sql"}); err != nil {
			return v.refuse(1, "setup_failed", "fossil sql 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
}

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