Skip to content
quarry Artifact [5f573f03bf]
Login

Artifact [5f573f03bf]

Artifact 5f573f03bfdae40ef75b65a2f4860e958b1b64ea6679dc716e3d716a9d350813:


package pickupclient

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

// quarry doctor, first cut (RFC 0033 step 4): a fixed list of local
// checks and the forge's answer to /api/v1/version and /api/v1/me. It
// is read-only: nothing is written, and the one call that carries the
// token is me.account. The server's judgment (me.check) is a later step.

const doctorHelp = `usage: quarry doctor [URL] [--json]

Check this machine: the forge answers and agrees with this client's
version, the login exists and the forge takes it, the login is kept
privately, no login start is waiting or stale, and zit is found. It
changes nothing. Each check that is not ok says what to run.

  URL      the forge (default: the one the installer recorded, else ` + defaultForge + `)
  --json   one JSON object on stdout: ok, checks (id, state, found, next), next

Exit: 0 everything ok or warn, 1 a check failed, 2 usage, 4 the only
failure is that this machine is not logged in.
`

// Check states.
const (
	stateOK   = "ok"
	stateWarn = "warn"
	stateFail = "fail"
)

// doctorCheck is one finding. Next is set when State is not ok.
type doctorCheck struct {
	ID    string    `json:"id"`
	State string    `json:"state"`
	Found string    `json:"found"`
	Next  *nextJSON `json:"next"`
}

type doctorJSON struct {
	OK     bool          `json:"ok"`
	Host   string        `json:"host"`
	Checks []doctorCheck `json:"checks"`
	Next   *nextJSON     `json:"next"`
}

// The check ids.
const (
	checkForge    = "forge"
	checkVersion  = "version"
	checkLogin    = "login"
	checkEnvToken = "env_token"
	checkStorage  = "storage"
	checkPending  = "pending"
	checkZit      = "zit"
)

var versionWord = regexp.MustCompile(`\d+\.\d+(?:\.\d+)?[0-9A-Za-z.+-]*`)

// Doctor runs the checks. It exits 0 when none failed, 1 when one did,
// 2 on usage, 4 when the only failure is that there is no login.
func Doctor(ctx context.Context, args []string, e *Env) int {
	e.fillLogin()
	args, asJSON := stripJSON(args)
	v := voice{e, e.named("doctor"), asJSON}
	raw := ""
	for _, a := range args {
		switch {
		case a == "-h" || a == "--help" || a == "-help":
			fmt.Fprint(e.Stdout, doctorHelp)
			return 0
		case strings.HasPrefix(a, "-") || raw != "":
			return v.refuse(2, "usage", "usage: quarry doctor [URL] [--json] (quarry doctor --help)", false,
				&nextJSON{Say: "See quarry doctor --help.", Cmd: "quarry doctor --help"})
		default:
			raw = a
		}
	}
	base, err := e.forgeOf(raw)
	if err != nil {
		return v.refuse(2, "usage", show(err.Error()), false, &nextJSON{Say: "See quarry doctor --help.", Cmd: "quarry doctor --help"})
	}

	var checks []doctorCheck
	add := func(id, state, found string, next *nextJSON) {
		checks = append(checks, doctorCheck{ID: id, State: state, Found: found, Next: next})
	}

	forgeVersion, ferr := e.forgeVersion(ctx, base)
	if ferr != nil {
		add(checkForge, stateFail, base.Host+" did not answer: "+show(ferr.Error()),
			&nextJSON{Say: "Check the address and the network, then run this again.", Cmd: "quarry doctor"})
		add(checkVersion, stateWarn, "not compared: the forge did not answer",
			&nextJSON{Say: "Run this again when the forge answers.", Cmd: "quarry doctor"})
	} else {
		add(checkForge, stateOK, base.Host+" answers", nil)
		state, found, next := compareVersions(e.Version, forgeVersion)
		add(checkVersion, state, found, next)
	}

	noLogin := false
	rec, have := e.token(base)
	switch {
	case !have:
		noLogin = true
		add(checkLogin, stateFail, "no login for "+base.Host,
			&nextJSON{Say: "Log this machine in; one approval, in a browser.", Cmd: loginCmd, Help: credsHelp})
	case ferr != nil:
		add(checkLogin, stateWarn, "a login is kept ("+sourceWord(rec.Source)+"); not tried: the forge did not answer",
			&nextJSON{Say: "Run this again when the forge answers.", Cmd: "quarry doctor"})
	default:
		me, merr := e.readMe(ctx, base, rec.Token)
		var se statusError
		switch {
		case merr == nil:
			found := "logged in as " + show(me.Name)
			if me.Token != nil && me.Token.Label != "" {
				found += ", token " + strconv.Quote(show(me.Token.Label))
			}
			add(checkLogin, stateOK, found+" ("+sourceWord(rec.Source)+")", 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}
			}
			add(checkLogin, stateFail, "the forge does not take the token ("+sourceWord(rec.Source)+"): "+show(merr.Error()), next)
		default:
			add(checkLogin, stateWarn, "the token was not tried: "+show(merr.Error()),
				&nextJSON{Say: "Run this again.", Cmd: "quarry doctor"})
		}
	}

	if strings.TrimSpace(e.Getenv(tokenEnvVar)) != "" {
		checks = append(checks, e.envTokenCheck(base))
	}
	checks = append(checks, e.storageCheck(base), e.pendingCheck(base), e.zitCheck(ctx))

	fails, first := 0, (*nextJSON)(nil)
	for _, pass := range []string{stateFail, stateWarn} {
		for _, c := range checks {
			if c.State == pass && first == nil {
				first = c.Next
			}
		}
	}
	for _, c := range checks {
		if c.State == stateFail {
			fails++
		}
	}
	exit := 0
	switch {
	case fails == 0:
	case fails == 1 && noLogin:
		exit = exitNoLogin
	default:
		exit = 1
	}

	if asJSON {
		v.print(doctorJSON{OK: fails == 0, Host: base.Host, Checks: checks, Next: first})
		return exit
	}
	client := "quarry " + show(e.Version) + " (client)"
	if h, err := e.Hostname(); err == nil && h != "" {
		client += " on " + show(h)
	}
	if ferr == nil && forgeVersion != "" {
		fmt.Fprintf(e.Stdout, "%s; forge %s %s\n", client, base.Host, show(forgeVersion))
	} else {
		fmt.Fprintf(e.Stdout, "%s; forge %s\n", client, base.Host)
	}
	for _, c := range checks {
		label := map[string]string{stateOK: "ok  ", stateWarn: "warn", stateFail: "FAIL"}[c.State]
		fmt.Fprintf(e.Stdout, "  %s  %s\n", label, c.Found)
	}
	if first == nil {
		fmt.Fprintln(e.Stdout, "Nothing to fix.")
		return exit
	}
	fmt.Fprintf(e.Stdout, "Next: %s\n", first.Say)
	if first.Open != "" {
		fmt.Fprintf(e.Stdout, "  open   %s\n", first.Open)
	}
	if first.Cmd != "" {
		fmt.Fprintf(e.Stdout, "  run    %s\n", first.Cmd)
	}
	return exit
}

func sourceWord(s string) string {
	switch s {
	case "keychain":
		return "in the keychain"
	case "file":
		return "in a private file"
	case "env":
		return "from " + tokenEnvVar
	}
	return "stored"
}

// forgeVersion asks the forge for its version; any answer that is not a
// 200 with a version is an error.
func (e *Env) forgeVersion(ctx context.Context, base *url.URL) (string, error) {
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()
	req, err := http.NewRequestWithContext(ctx, "GET", base.ResolveReference(&url.URL{Path: "/api/v1/version"}).String(), nil)
	if err != nil {
		return "", err
	}
	resp, err := e.Client.Do(req)
	if err != nil {
		var ue *url.Error
		if errors.As(err, &ue) {
			err = ue.Err
		}
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", statusError(resp.StatusCode)
	}
	var b struct {
		Version string `json:"version"`
	}
	if err := json.NewDecoder(io.LimitReader(resp.Body, pickupBodyMax)).Decode(&b); err != nil || b.Version == "" {
		return "", errors.New("it did not say its version")
	}
	return b.Version, nil
}

// majorMinor reads the leading numbers of a version such as "v0.42.0".
func majorMinor(s string) (major, minor int, ok bool) {
	s = strings.TrimPrefix(strings.TrimSpace(s), "v")
	parts := strings.SplitN(s, ".", 3)
	if len(parts) < 2 {
		return 0, 0, false
	}
	var err1, err2 error
	major, err1 = strconv.Atoi(parts[0])
	minor, err2 = strconv.Atoi(parts[1])
	return major, minor, err1 == nil && err2 == nil
}

// compareVersions: the same major.minor is ok, another minor warns, and
// another major fails. A version that is not a number (a dev build) is
// not compared.
func compareVersions(client, forge string) (string, string, *nextJSON) {
	cm, cn, cok := majorMinor(client)
	fm, fn, fok := majorMinor(forge)
	found := "client " + show(client) + ", forge " + show(forge)
	switch {
	case !cok || !fok:
		return stateOK, found + " (not compared)", nil
	case cm != fm:
		return stateFail, found + ": not compatible", &nextJSON{Say: "Install the client that matches this forge.", Help: "/llms.txt"}
	case cn != fn:
		return stateWarn, found + ": differ", &nextJSON{Say: "Update the client to the forge's version.", Help: "/llms.txt"}
	}
	return stateOK, found, nil
}

func (e *Env) envTokenCheck(base *url.URL) doctorCheck {
	c := doctorCheck{ID: checkEnvToken, State: stateOK}
	if !e.envHostIs(base) {
		c.Found = tokenEnvVar + " is set, for another forge; it is not sent to " + base.Host
		return c
	}
	if _, err := e.Keys.Get(hostKey(base)); err == nil {
		c.State = stateWarn
		c.Found = tokenEnvVar + " is set and used in place of the stored login"
		c.Next = &nextJSON{Say: "Unset " + tokenEnvVar + " to use the stored login.", Cmd: "unset " + tokenEnvVar}
		return c
	}
	c.Found = tokenEnvVar + " is set and in use"
	return c
}

func (e *Env) storageCheck(base *url.URL) doctorCheck {
	c := doctorCheck{ID: checkStorage, State: stateOK}
	host := hostKey(base)
	rec, err := e.Keys.Get(host)
	if err != nil {
		c.Found = "no stored login to protect"
		return c
	}
	where := "token in the keychain"
	if rec.Source == "file" {
		where = "token in a file"
	}
	if runtime.GOOS == "windows" {
		c.Found = where + " (file permissions not checked here)"
		return c
	}
	var bad []string
	if fi, err := os.Stat(e.ConfigDir); err == nil && fi.Mode().Perm()&0o077 != 0 {
		bad = append(bad, fmt.Sprintf("the directory is %04o, must be 0700", fi.Mode().Perm()))
	}
	file := filepath.Join(e.ConfigDir, hostFile(host))
	if fi, err := os.Stat(file); err == nil && fi.Mode().Perm()&0o077 != 0 {
		bad = append(bad, fmt.Sprintf("the file is %04o, must be 0600", fi.Mode().Perm()))
	}
	if len(bad) > 0 {
		c.State = stateFail
		c.Found = where + "; others can read it: " + strings.Join(bad, "; ")
		c.Next = &nextJSON{Say: "Make the directory and file private to you.",
			Cmd: "chmod 700 " + shellWord(e.ConfigDir) + " && chmod 600 " + shellWord(file)}
		return c
	}
	c.Found = where + ", kept private (0700 directory, 0600 file)"
	return c
}

// shellWord quotes s for a shell only when it needs it.
func shellWord(s string) string {
	if keychainSafe.MatchString(s) {
		return s
	}
	return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}

func (e *Env) pendingCheck(base *url.URL) doctorCheck {
	c := doctorCheck{ID: checkPending, State: stateOK}
	p, ok := loadPending(e.ConfigDir, hostKey(base))
	if !ok {
		c.Found = "no login start is waiting"
		return c
	}
	ago := e.Now().Sub(p.startedAt()).Round(time.Minute)
	next := &nextJSON{Say: "Collect it, or start a new one.", Cmd: loginCmd}
	c.State = stateWarn
	if e.Now().After(p.deadline().Add(expiryGrace)) {
		c.Found = fmt.Sprintf("a login started %s ago was never collected, and its code has expired", ago)
		c.Next = next
		return c
	}
	c.Found = fmt.Sprintf("a login started %s ago is waiting for approval", ago)
	c.Next = next
	return c
}

func (e *Env) zitCheck(ctx context.Context) doctorCheck {
	c := doctorCheck{ID: checkZit}
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()
	out, err := e.Run(ctx, "", nil, []string{"version"})
	if errors.Is(err, exec.ErrNotFound) {
		c.State = stateWarn
		c.Found = "zit is not on PATH"
		c.Next = &nextJSON{Say: "Install zit; the API verbs work without it, code sync does not."}
		return c
	}
	ver := versionWord.FindString(out)
	if err != nil && ver == "" {
		c.State = stateWarn
		c.Found = "zit is on PATH but did not report a version"
		c.Next = &nextJSON{Say: "Run zit version and read what it says.", Cmd: "zit version"}
		return c
	}
	c.State = stateOK
	if ver == "" {
		c.Found = "zit found"
		return c
	}
	c.Found = "zit " + show(ver) + " found"
	return c
}