Skip to content
quarry Artifact [1d0bef9a2c]
Login

Artifact [1d0bef9a2c]

Artifact 1d0bef9a2cfe24953d0b219714101e72f07f4a618f9c9ad2671417d4c612bf02:


package pickupclient

import (
	"bytes"
	"context"
	"encoding/hex"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"
	"time"
)

// quarry login and quarry whoami: log a machine in as the person (RFC
// 0032). The client makes the pickup key, starts a login, shows the link
// and code, waits for the one approval, and keeps the token it collects
// where only this user reads it.

const (
	defaultForge = "https://zeitforge.app"
	loginKind    = "login"
	labelMax     = 64
	// pollFallback is the wait between collect calls when the forge
	// names none (RFC 8628's default).
	pollFallback = 10 * time.Second
	// maxRenewals is how many times one run starts a new code when the
	// last lapsed unclaimed.
	maxRenewals = 3
	// expiryGrace is how long past its stated expiry a start is still
	// believed to be waiting before the client stops trusting the forge.
	expiryGrace = 30 * time.Second
)

var (
	// ErrNoLogin is a host with no stored token.
	ErrNoLogin = errors.New("no token is stored for this host")

	// errNoItem is a keychain with nothing for the host, as against one
	// that could not be asked.
	errNoItem = errors.New("no such item")

	labelOK  = regexp.MustCompile(`^[A-Za-z0-9 .,_-]{1,64}$`)
	labelBad = regexp.MustCompile(`[^A-Za-z0-9 .,_-]+`)
	// keychainSafe is what may be written on a `security -i` command line
	// inside double quotes; anything else goes to the file store.
	keychainSafe = regexp.MustCompile(`^[A-Za-z0-9._~:+/=@,-]+$`)
)

// Record is what is kept for a host. Token is empty in the file when the
// keychain holds it. Host is the normalised host the record belongs to.
type Record struct {
	Host    string `json:"host"`
	Account string `json:"account"`
	Token   string `json:"token,omitempty"`
	// Revoke is the page the forge named, at login, that ends this token;
	// kept so that a logout the forge cannot hear can still point at it.
	Revoke string `json:"revoke,omitempty"`
	// Source says where Get found the token: "keychain" or "file". It is
	// never written.
	Source string `json:"-"`
}

// Store keeps a login by host key (see hostKey); Put says where it went.
// A host holds one login: a second replaces the first.
type Store interface {
	Put(host string, r Record) (where string, err error)
	Get(host string) (Record, error)
	// Delete forgets the host's login from every place Put kept it; an
	// error means some copy may remain.
	Delete(host string) error
}

// Keychain is the OS secret store, holding the token alone. Put leaves
// the host with one item, for account; Get reads the item for account.
type Keychain interface {
	Put(host, account, value string) error
	Get(host, account string) (string, error)
	// Delete removes the host's item; Get afterwards says whether it went.
	Delete(host, account string) error
}

// hostKey names a forge's host the one way: lower case, with the
// scheme's default port dropped.
func hostKey(u *url.URL) string {
	h := strings.ToLower(u.Hostname())
	if strings.Contains(h, ":") {
		h = "[" + h + "]"
	}
	port := u.Port()
	if port == "" || (u.Scheme == "https" && port == "443") || (u.Scheme == "http" && port == "80") {
		return h
	}
	return h + ":" + port
}

// dirStore keeps a small JSON record per host under Dir (0600), and the
// token in Keychain when there is one that works, else in the record.
type dirStore struct {
	Dir      string
	Keychain Keychain
	// Timeout bounds every keychain call (zero: ten seconds); a keychain
	// that does not answer, a locked one waiting on a prompt nobody can
	// see, is as good as none.
	Timeout time.Duration
}

var errKeychainSilent = errors.New("the keychain did not answer")

// kget reads the keychain item within the store's timeout.
func (s *dirStore) kget(host, account string) (string, error) {
	type res struct {
		v   string
		err error
	}
	done := make(chan res, 1)
	go func() { v, err := s.Keychain.Get(host, account); done <- res{v, err} }()
	d := s.Timeout
	if d == 0 {
		d = 10 * time.Second
	}
	select {
	case r := <-done:
		return r.v, r.err
	case <-time.After(d):
		return "", errKeychainSilent
	}
}

// timed runs f, giving up on it after the store's timeout. The call is
// left to finish on its own.
func (s *dirStore) timed(f func() error) error {
	d := s.Timeout
	if d == 0 {
		d = 10 * time.Second
	}
	done := make(chan error, 1)
	go func() { done <- f() }()
	select {
	case err := <-done:
		return err
	case <-time.After(d):
		return errKeychainSilent
	}
}

// hostFile is injective: two hosts never share a file.
func hostFile(host string) string {
	return hex.EncodeToString([]byte(host)) + ".json"
}

func (s *dirStore) Put(host string, r Record) (string, error) {
	where := ""
	token := r.Token
	r.Host = host
	if s.Keychain != nil {
		// One host, one login: the item of an earlier account goes first.
		if b, err := os.ReadFile(filepath.Join(s.Dir, hostFile(host))); err == nil {
			var old Record
			if json.Unmarshal(b, &old) == nil && old.Account != "" && old.Account != r.Account {
				s.timed(func() error { return s.Keychain.Delete(host, old.Account) })
			}
		}
	}
	var kerr error
	var oldAccount string
	if s.Keychain != nil {
		if b, err := os.ReadFile(filepath.Join(s.Dir, hostFile(host))); err == nil {
			var old Record
			if json.Unmarshal(b, &old) == nil {
				oldAccount = old.Account
			}
		}
		kerr = s.timed(func() error { return s.Keychain.Put(host, r.Account, token) })
		if kerr == nil {
			r.Token = ""
			where = "in the login keychain"
		}
	}
	path := filepath.Join(s.Dir, hostFile(host))
	if err := writePrivate(s.Dir, path, r); err != nil {
		return where, err
	}
	if where == "" {
		where = "in " + path + " (private to you)"
		if errors.Is(kerr, errKeychainSilent) {
			where = "in " + path + " (private to you; the keychain did not answer)"
		}
		// The token is now in the file alone: an earlier one the keychain
		// still holds for this host would outlive a logout.
		stale := false
		for _, acct := range []string{r.Account, oldAccount, ""} {
			if s.Keychain == nil {
				break
			}
			if err := s.timed(func() error { return s.Keychain.Delete(host, acct) }); err != nil {
				stale = true
			}
		}
		if stale && s.Keychain != nil {
			where += "; an older copy may remain in the keychain: delete the item named quarry:" + host + " there"
		}
	}
	return where, nil
}

// writePrivate writes r as JSON to path through a fresh 0600 temp file in dir,
// which is made 0700 and tightened if it was looser.
func writePrivate(dir, path string, r any) error {
	if err := os.MkdirAll(dir, 0o700); err != nil {
		return err
	}
	if err := os.Chmod(dir, 0o700); err != nil {
		return err
	}
	f, err := os.CreateTemp(dir, ".login-*")
	if err != nil {
		return err
	}
	b, _ := json.Marshal(r)
	_, werr := f.Write(b)
	if serr := f.Sync(); werr == nil {
		werr = serr
	}
	if cerr := f.Close(); werr == nil {
		werr = cerr
	}
	if werr == nil {
		werr = os.Rename(f.Name(), path)
	}
	if werr != nil {
		os.Remove(f.Name())
	}
	return werr
}

func (s *dirStore) Get(host string) (Record, error) {
	b, err := os.ReadFile(filepath.Join(s.Dir, hostFile(host)))
	if err != nil {
		return Record{}, ErrNoLogin
	}
	var r Record
	if json.Unmarshal(b, &r) != nil || r.Host != host {
		return Record{}, ErrNoLogin
	}
	r.Source = "file"
	if r.Token == "" && s.Keychain != nil {
		var kerr error
		r.Token, kerr = s.kget(host, r.Account)
		r.Source = "keychain"
		if r.Token == "" && kerr != nil && !errors.Is(kerr, errNoItem) {
			return Record{}, fmt.Errorf("the keychain would not give up the token: %w", kerr)
		}
	}
	if r.Token == "" {
		return Record{}, ErrNoLogin
	}
	return r, nil
}

// Delete forgets the host's login: the keychain item, which must be
// gone when this returns nil, and then the record file. A keychain that
// cannot be changed is an error and the record stays, so the login is
// not half forgotten.
func (s *dirStore) Delete(host string) error {
	path := filepath.Join(s.Dir, hostFile(host))
	if s.Keychain != nil {
		var r Record
		if b, err := os.ReadFile(path); err == nil {
			json.Unmarshal(b, &r)
		}
		// With no account on record the keychain is still tried, under
		// the host's service name.
		// A record that holds the token itself was stored with no keychain
		// in play, so a keychain that cannot be asked changes nothing.
		derr := s.timed(func() error { return s.Keychain.Delete(host, r.Account) })
		if derr != nil && r.Token == "" {
			return fmt.Errorf("the login keychain would not let go of the token: %w", derr)
		}
		if derr == nil {
			if v, gerr := s.kget(host, r.Account); gerr == nil && v != "" {
				return errors.New("the login keychain still holds the token")
			}
		}
	}
	if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
		return err
	}
	return nil
}

// macKeychain uses security(1). The value goes in on the interactive
// mode's stdin, never on a command line or in the environment. sec runs
// it (nil: the real one) and returns its output.
type macKeychain struct {
	sec func(stdin string, args ...string) (string, error)
}

func (m macKeychain) run(stdin string, args ...string) (string, error) {
	if m.sec != nil {
		return m.sec(stdin, args...)
	}
	cmd := exec.Command("security", args...)
	cmd.Stdin = strings.NewReader(stdin)
	var out bytes.Buffer
	cmd.Stdout, cmd.Stderr = &out, &out
	err := cmd.Run()
	return out.String(), err
}

func (m macKeychain) Put(host, account, value string) error {
	for _, s := range []string{host, account, value} {
		if !keychainSafe.MatchString(s) {
			return errors.New("not storable in the keychain")
		}
	}
	// One host, one login: whatever else is held for it goes first.
	for i := 0; i < 8; i++ {
		if _, err := m.run("", "delete-generic-password", "-s", "quarry:"+host); err != nil {
			break
		}
	}
	line := fmt.Sprintf("add-generic-password -U -s \"quarry:%s\" -a \"%s\" -w \"%s\"\n", host, account, value)
	out, err := m.run(line, "-i")
	if err != nil {
		return err
	}
	if strings.Contains(out, "security: ") {
		return errors.New("the keychain refused it")
	}
	return nil
}

func (m macKeychain) Delete(host, account string) error {
	for i := 0; i < 8; i++ {
		out, err := m.run("", "delete-generic-password", "-s", "quarry:"+host)
		if err != nil {
			if i == 0 && !strings.Contains(out, "could not be found") {
				return fmt.Errorf("security: %w", err)
			}
			break
		}
	}
	return nil
}

func (m macKeychain) Get(host, account string) (string, error) {
	if !keychainSafe.MatchString(account) {
		return "", errNoItem
	}
	out, err := m.run("", "find-generic-password", "-s", "quarry:"+host, "-a", account, "-w")
	if err != nil && strings.Contains(out, "could not be found") {
		return "", errNoItem
	}
	return strings.TrimSpace(out), err
}

// ConfigDir is where the client keeps its settings and logins.
func ConfigDir() string {
	dir := os.Getenv("XDG_CONFIG_HOME")
	if dir == "" {
		if h, err := os.UserHomeDir(); err == nil {
			dir = filepath.Join(h, ".config")
		}
	}
	return filepath.Join(dir, "quarry")
}

// DefaultHost is the forge a verb works against when none is named: the
// one the installer recorded in dir's config.json, else the default
// forge. A record that is not a plain forge address is ignored.
func DefaultHost(dir string) string {
	b, err := os.ReadFile(filepath.Join(dir, "config.json"))
	if err != nil {
		return defaultForge
	}
	var c struct {
		Host string `json:"host"`
	}
	if json.Unmarshal(b, &c) != nil {
		return defaultForge
	}
	if _, err := forgeOf(c.Host); err != nil || c.Host == "" {
		return defaultForge
	}
	return c.Host
}

func defaultStore(dir string) Store {
	s := &dirStore{Dir: dir}
	if runtime.GOOS == "darwin" {
		s.Keychain = macKeychain{}
	} else {
		s.Keychain = ringKeychain{}
	}
	return s
}

// cleanLabel keeps the characters the forge accepts, at most 64.
func cleanLabel(s string) string {
	s = strings.TrimSpace(labelBad.ReplaceAllString(s, ""))
	if len(s) > labelMax {
		s = strings.TrimSpace(s[:labelMax])
	}
	if s == "" {
		return "machine"
	}
	return s
}

func (e *Env) fillLogin() {
	e.fill()
	if e.ConfigDir == "" {
		e.ConfigDir = ConfigDir()
	}
	if e.Keys == nil {
		e.Keys = defaultStore(e.ConfigDir)
	}
	if e.Poll == 0 {
		e.Poll = pollFallback
	}
	if e.Hostname == nil {
		e.Hostname = os.Hostname
	}
	if e.Getwd == nil {
		e.Getwd = os.Getwd
	}
	if e.Getenv == nil {
		e.Getenv = os.Getenv
	}
}

func LoginMain(args []string) int {
	return Login(context.Background(), args, &Env{Stdout: os.Stdout, Stderr: os.Stderr})
}

func WhoamiMain(args []string) int {
	return Whoami(context.Background(), args, &Env{Stdout: os.Stdout, Stderr: os.Stderr})
}

const loginHelp = `usage: quarry auth login [URL] [--label NAME] [--no-wait] [--json]

Log this machine in as you. Prints a link and a code, waits while you
approve on that page, then keeps the token it is given in the OS keychain
(a private file where there is none). The token is never printed.

Run it again at any time: a login still waiting is resumed with the same
code, one approved meanwhile is collected, and one that lapsed gets a new
code. While waiting, a code that lapses is replaced (up to 3 times).

  URL        the forge (default: the one the installer recorded, else ` + defaultForge + `)
  --label    what to call this machine (default: this machine's name)
  --no-wait  print the link and code and exit 3; run it again to collect
  --json     one JSON object on stdout (the link and code go to stderr)

Exit: 0 signed in, 1 refused, 2 usage, 3 still waiting (--no-wait, or the
code expired or the wait ended).

Example:
  quarry auth login
`

const whoamiHelp = `usage: quarry auth status [URL] [--json]

Show who this machine is signed in as on a forge, the token's label, the
repositories it reaches and where to revoke it. Prints no token.

  URL      the forge (default: the one the installer recorded, else ` + defaultForge + `)
  --json   one JSON object on stdout

Uses QUARRY_TOKEN when it is set, else the stored login.

Exit: 0 signed in, 1 the forge refuses the token, 2 usage, 4 not logged in.

Example:
  quarry auth status
`

// forgeOf is the origin a verb works against; with none named, the
// installer's recorded one.
func (e *Env) forgeOf(raw string) (*url.URL, error) {
	if raw == "" {
		raw = DefaultHost(e.ConfigDir)
	}
	return forgeOf(raw)
}

func forgeOf(raw string) (*url.URL, error) {
	u, _, err := pickupURL(raw)
	if err != nil {
		return nil, err
	}
	if p := strings.Trim(u.Path, "/"); p != "" {
		return nil, errors.New("give the forge's address alone, with no path")
	}
	return u, nil
}

// Exit statuses: 0 done, 1 refused or denied, 2 usage, 3 the code
// expired or the wait ended.
func Login(ctx context.Context, args []string, e *Env) int {
	e.fillLogin()
	args, asJSON := stripJSON(args)
	v := voice{e, e.named("login"), asJSON}
	fail := func(code int, format string, a ...any) int {
		next := &nextJSON{Say: "Start again.", Cmd: loginCmd, Help: credsHelp}
		ecode := "refused"
		switch code {
		case 2:
			ecode = "usage"
			next = &nextJSON{Say: "See quarry auth login --help.", Cmd: "quarry auth login --help"}
		case 3:
			ecode = "expired"
		}
		return v.refuse(code, ecode, fmt.Sprintf(format, a...), false, next)
	}
	progress := e.Stdout
	if asJSON {
		progress = e.Stderr
	}
	fs := flag.NewFlagSet("login", flag.ContinueOnError)
	fs.SetOutput(io.Discard)
	label := fs.String("label", "", "")
	noWait := fs.Bool("no-wait", false, "")
	var rawURL string
	rest := args
	for {
		if err := fs.Parse(rest); err != nil {
			if errors.Is(err, flag.ErrHelp) {
				fmt.Fprint(e.Stdout, loginHelp)
				return 0
			}
			return fail(2, "%v (quarry login --help)", err)
		}
		if fs.NArg() == 0 {
			break
		}
		if rawURL != "" {
			return fail(2, "one URL only")
		}
		rawURL, rest = fs.Arg(0), fs.Args()[1:]
	}
	base, err := e.forgeOf(rawURL)
	if err != nil {
		return fail(2, "%v", err)
	}
	lab := *label
	if lab == "" {
		host, _ := e.Hostname()
		lab = cleanLabel(host)
	} else if !labelOK.MatchString(lab) || strings.TrimSpace(lab) != lab {
		return fail(2, "a label is letters, digits, space, '.', ',', '-' or '_', at most %d characters", labelMax)
	}

	host := hostKey(base)
	if err := os.MkdirAll(e.ConfigDir, 0o700); err != nil {
		return fail(1, "%v", err)
	}
	// One run at a time per host: two would each make a key and the later
	// would overwrite the earlier's. A lock the system cannot give is no
	// reason to refuse.
	if release, ok, lerr := lockFile(lockPath(e.ConfigDir, host)); lerr == nil {
		if !ok {
			return fail(1, "a login to %s is already in progress in another quarry; let it finish, or end it and run this again", base.Host)
		}
		defer release()
	}
	runEnd := e.Now().Add(pickupDefaultWait)
	p, resumed := loadPending(e.ConfigDir, host)
	needStart := !resumed
	renewals := 0
	note := ""
	if resumed {
		if lu, err := url.Parse(p.Link); err != nil || !sameOrigin(lu, base) {
			p.Link = base.ResolveReference(&url.URL{Path: "/setup"}).String()
		}
		// An approval stays collectable for a day; a start older than that
		// is nothing to ask the forge about.
		if e.Now().Sub(p.startedAt()) > pendingKeep {
			dropPending(e.ConfigDir, host)
			resumed, needStart = false, true
			note = "the last code expired; here is a new one"
		}
	}
	shown := false
	show1 := func() {
		end := p.deadline()
		if end.After(runEnd) {
			end = runEnd
		}
		mins := int((end.Sub(e.Now()) + 30*time.Second) / time.Minute)
		if mins < 0 {
			mins = 0
		}
		out := progress
		if *noWait && !asJSON {
			out = e.Stdout
		}
		fmt.Fprintf(out, "Open %s and type %s (%d minutes)\n", show(p.Link), show(p.Code), mins)
		shown = true
	}
	stillWaiting := func() int {
		next := &nextJSON{Say: "Tell the person to open the link and type the code, then run this again to collect the token.", Open: show(p.Link), Cmd: "quarry auth login --no-wait", Ask: true, Help: credsHelp}
		if asJSON {
			v.print(waitingJSON{State: "waiting", Host: base.Host, Link: show(p.Link), Code: show(p.Code), Expires: p.Expires, Next: next})
		} else {
			fmt.Fprintln(e.Stdout, "Still waiting for the approval; run quarry auth login again to collect it.")
		}
		return 3
	}
	var ans pickupAnswer
	for first := true; ; first = false {
		if needStart {
			np, err := e.startLogin(ctx, base, lab)
			if err != nil {
				return fail(1, "%v", err)
			}
			p, needStart = np, false
			if note != "" {
				fmt.Fprintln(progress, note)
				note = ""
			}
			show1()
			if *noWait {
				return stillWaiting()
			}
			fmt.Fprintln(progress, "Waiting for your approval ...")
		}
		res, err := e.pollLogin(ctx, base, p)
		if err != nil {
			// The network may be back next time: the start is kept.
			return fail(1, "%v", err)
		}
		pause := p.wait(e.Poll)
		lapsed := false
		switch res.kind {
		case pollDone:
			ans = res.ans
		case pollDenied, pollOther:
			// A permanent answer: the key is of no further use.
			dropPending(e.ConfigDir, host)
			return fail(1, "%s", res.msg)
		case pollExpired, pollMissing:
			lapsed = true
		case pollWaiting:
			// The forge says unclaimed; past the life it gave, counted from
			// our own start, it is not believed for long.
			lapsed = e.Now().After(p.deadline().Add(expiryGrace))
		case pollBusy:
			if res.retry > pause {
				pause = res.retry
			}
		}
		if res.kind == pollDone {
			break
		}
		if lapsed {
			if resumed && first {
				note = "the last code expired; here is a new one"
				needStart = true
				continue
			}
			if renewals >= maxRenewals || !e.Now().Add(pause).Before(runEnd) {
				dropPending(e.ConfigDir, host)
				if renewals >= maxRenewals {
					return fail(3, "the code expired %d times without an approval", renewals+1)
				}
				return fail(3, "no approval before the wait ended")
			}
			// Never faster than the forge's rate, whatever the clocks say.
			if err := e.Sleep(ctx, pause); err != nil {
				return fail(1, "interrupted")
			}
			renewals++
			note = "the code expired; here is a new one"
			needStart = true
			continue
		}
		if *noWait {
			if !shown {
				show1()
			}
			return stillWaiting()
		}
		if resumed && first && !shown {
			show1()
			fmt.Fprintln(progress, "Waiting for your approval ...")
		}
		if !e.Now().Add(pause).Before(runEnd) {
			return fail(3, "no approval before the wait ended")
		}
		if err := e.Sleep(ctx, pause); err != nil {
			return fail(1, "interrupted")
		}
	}

	token := ans.Secret.Value
	var res struct {
		Account string `json:"account"`
	}
	b, _ := json.Marshal(ans.Result)
	json.Unmarshal(b, &res)
	lost := func(format string, a ...any) int {
		dropPending(e.ConfigDir, host)
		return v.refuse(1, "refused", fmt.Sprintf(format, a...)+fmt.Sprintf("; a live token was released and saved nowhere; revoke it on your tokens list (request %s, token %s)", orUnknown(ans.Request), orUnknown(ans.Result.Token.ID)), true, nil)
	}
	if ans.Op != "login.token.new" || token == "" {
		return lost("the answer is not a login token")
	}
	me, merr := e.readMe(ctx, base, token)
	account := me.Name
	if account == "" {
		account = res.Account
	}
	if account == "" {
		return lost("the forge did not say whose token this is")
	}
	rec := Record{Account: account, Token: token}
	if merr == nil {
		rec.Revoke = revokeURL(base, me)
	}
	where, err := e.Keys.Put(hostKey(base), rec)
	// The token is stored, or lost for good: the key has no more use.
	dropPending(e.ConfigDir, host)
	if err != nil && where != "" {
		return v.refuse(1, "refused", fmt.Sprintf("the token is in the login keychain but its record could not be written (%v); run quarry login again", err), false, nil)
	}
	if err != nil {
		return lost("the token could not be stored: %v", err)
	}
	if asJSON {
		out := meResultJSON{OK: true, Host: base.Host, Account: show(account), Kept: where}
		if merr == nil {
			out.Token = tokenOut(base, me)
		}
		v.print(out)
		return 0
	}
	if merr != nil || me.Token == nil {
		fmt.Fprintf(e.Stdout, "Signed in to %s as %s, token kept %s\n", base.Host, show(account), where)
		return 0
	}
	e.printHolding(base, me, where)
	return 0
}

// printHolding prints what the forge says this token holds, as given.
func (e *Env) printHolding(base *url.URL, me meAnswer, where string) {
	fmt.Fprintf(e.Stdout, "Signed in to %s as %s\n", base.Host, show(me.Name))
	if t := me.Token; t != nil {
		fmt.Fprintf(e.Stdout, "  may      %s\n", show(t.May))
		fmt.Fprintf(e.Stdout, "  may not  %s\n", show(strings.Join(t.MayNot, "; ")))
		fmt.Fprintf(e.Stdout, "  token    %q", show(t.Label))
		if where != "" {
			fmt.Fprintf(e.Stdout, ", kept %s", where)
		}
		fmt.Fprintln(e.Stdout)
	}
	e.printRevoke(base, me)
}

// printRevoke prints the page the forge says ends this token, when it
// says one on its own origin. The client makes up no address.
func (e *Env) printRevoke(base *url.URL, me meAnswer) {
	if u := revokeURL(base, me); u != "" {
		fmt.Fprintf(e.Stdout, "  revoke   %s\n", show(u))
	}
}

type meAnswer struct {
	Name  string `json:"name"`
	Token *struct {
		Label  string   `json:"label"`
		May    string   `json:"may"`
		MayNot []string `json:"mayNot"`
		Revoke string   `json:"revoke"`
	} `json:"token"`
	Repos []struct {
		Repo string `json:"repo"`
		Role string `json:"role"`
	} `json:"repos"`
}

func (e *Env) readMe(ctx context.Context, base *url.URL, token string) (meAnswer, error) {
	var me meAnswer
	req, err := http.NewRequestWithContext(ctx, "GET", base.ResolveReference(&url.URL{Path: "/api/v1/me"}).String(), nil)
	if err != nil {
		return me, err
	}
	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 me, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return me, statusError(resp.StatusCode)
	}
	err = json.NewDecoder(io.LimitReader(resp.Body, pickupBodyMax)).Decode(&me)
	return me, err
}

// Whoami exits 0 when the token works, 1 when the forge no longer takes
// it, 2 on usage, 4 when there is no token.
func Whoami(ctx context.Context, args []string, e *Env) int {
	e.fillLogin()
	args, asJSON := stripJSON(args)
	v := voice{e, e.named("whoami"), asJSON}
	for _, a := range args {
		if a == "-h" || a == "--help" || a == "-help" {
			fmt.Fprint(e.Stdout, whoamiHelp)
			return 0
		}
	}
	usage := func(msg string) int {
		return v.refuse(2, "usage", msg, false, &nextJSON{Say: "See quarry auth status --help.", Cmd: "quarry auth status --help"})
	}
	if len(args) > 1 || len(args) == 1 && strings.HasPrefix(args[0], "-") {
		return usage("usage: quarry whoami [URL] [--json] (quarry whoami --help)")
	}
	raw := ""
	if len(args) == 1 {
		raw = args[0]
	}
	base, err := e.forgeOf(raw)
	if err != nil {
		return usage(show(err.Error()))
	}
	rec, ok := e.token(base)
	if !ok {
		return v.noLogin(base)
	}
	me, err := e.readMe(ctx, base, rec.Token)
	if err != nil {
		code, why := "unreachable", "the forge could not be reached: "
		var se statusError
		next := &nextJSON{Say: "Log this machine in again.", Cmd: loginCmd, Help: credsHelp}
		if errors.As(err, &se) {
			code, why = "refused", "the forge does not take the token: "
			if rec.Source == "env" {
				next = &nextJSON{Say: "Unset or replace " + tokenEnvVar + "; it is the token in use here.", Help: credsHelp}
			}
		}
		return v.refuse(1, code, why+show(err.Error()), false, next)
	}
	if asJSON {
		out := meResultJSON{OK: true, Host: base.Host, Account: show(me.Name), Source: rec.Source, Token: tokenOut(base, me)}
		repos := []repoJSON{}
		for _, r := range me.Repos {
			repos = append(repos, repoJSON{show(r.Repo), show(r.Role)})
		}
		out.Repos = &repos
		v.print(out)
		return 0
	}
	fmt.Fprintf(e.Stdout, "Signed in to %s as %s\n", base.Host, show(me.Name))
	if rec.Source == "env" {
		fmt.Fprintf(e.Stdout, "  using the token in %s\n", tokenEnvVar)
	}
	if me.Token != nil {
		fmt.Fprintf(e.Stdout, "  token    %q\n", show(me.Token.Label))
	}
	if len(me.Repos) == 0 {
		fmt.Fprintln(e.Stdout, "  reaches  no repositories")
	}
	for i, r := range me.Repos {
		lead := "           "
		if i == 0 {
			lead = "  reaches  "
		}
		fmt.Fprintf(e.Stdout, "%s%s (%s)\n", lead, show(r.Repo), show(r.Role))
	}
	e.printRevoke(base, me)
	return 0
}

var terminalEscape = regexp.MustCompile(`\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b.?`)

// show makes a server string safe to print: escape sequences and control
// characters (C0, DEL, C1) are dropped, so a forge cannot write to the
// terminal.
func show(s string) string {
	s = terminalEscape.ReplaceAllString(s, "")
	return strings.Map(func(r rune) rune {
		if r < 0x20 || r == 0x7f || (r >= 0x80 && r <= 0x9f) {
			return -1
		}
		return r
	}, s)
}