package pickupclient
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"craftdesign.group/quarry/internal/nextstep"
)
// 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 *nextstep.Next `json:"next"`
}
type doctorJSON struct {
OK bool `json:"ok"`
Host string `json:"host"`
Checks []doctorCheck `json:"checks"`
Next *nextstep.Next `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, nil}
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,
&nextstep.Next{Say: "See quarry doctor --help.", Cmd: "quarry doctor --help"})
default:
raw = a
}
}
base, err := e.forgeOf(raw)
v.base = base
if err != nil {
return v.refuse(2, "usage", show(err.Error()), false, &nextstep.Next{Say: "See quarry doctor --help.", Cmd: "quarry doctor --help"})
}
var checks []doctorCheck
add := func(id, state, found string, next *nextstep.Next) {
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()),
&nextstep.Next{Say: "Check the address and the network, then run this again.", Cmd: "quarry doctor"})
add(checkVersion, stateWarn, "not compared: the forge did not answer",
&nextstep.Next{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, kerr := e.doctorToken(base)
switch {
case kerr != nil:
add(checkLogin, stateFail, "the login could not be read: "+show(kerr.Error()),
&nextstep.Next{Say: "Unlock the login keychain, or fix it, then run this again.", Cmd: "quarry doctor"})
case !have:
noLogin = true
add(checkLogin, stateFail, "no login for "+base.Host,
&nextstep.Next{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",
&nextstep.Next{Say: "Run this again when the forge answers.", Cmd: "quarry doctor"})
default:
mctx, mcancel := context.WithTimeout(ctx, 10*time.Second)
me, merr := e.readMe(mctx, base, rec.Token)
mcancel()
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 := &nextstep.Next{Say: "Log this machine in again.", Cmd: loginCmd, Help: credsHelp}
if rec.Source == "env" {
next = &nextstep.Next{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()),
&nextstep.Next{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, (*nextstep.Next)(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
}
first.Render(e.Stdout, "Next: ", base)
return exit
}
// doctorToken is e.token, except that a keychain that could not be read
// is an error and not "no login".
func (e *Env) doctorToken(base *url.URL) (Record, bool, error) {
if rec, ok := e.token(base); ok && rec.Source == "env" {
return rec, true, nil
}
rec, err := e.Keys.Get(hostKey(base))
switch {
case err == nil:
return rec, true, nil
case errors.Is(err, ErrNoLogin):
return Record{}, false, nil
}
return Record{}, false, err
}
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, *nextstep.Next) {
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", &nextstep.Next{Say: "Install the client that matches this forge.", Help: "/llms.txt"}
case cn != fn:
return stateWarn, found + ": differ", &nextstep.Next{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 = &nextstep.Next{Say: "Unset " + tokenEnvVar + " to use the stored login.", Cmd: "unset " + tokenEnvVar}
return c
}
c.Found = tokenEnvVar + " is set and in use"
return c
}
// doctorGOOS is the system whose permission model the storage check
// follows; tests change it.
var doctorGOOS = runtime.GOOS
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 {
if errors.Is(err, ErrNoLogin) {
c.Found = "no stored login to protect"
return c
}
c.State = stateWarn
c.Found = "not checked: the login could not be read"
c.Next = &nextstep.Next{Say: "Unlock the login keychain, or fix it, then run this again.", Cmd: "quarry doctor"}
return c
}
where := "token in the keychain"
if rec.Source == "file" {
where = "token in a file"
}
if doctorGOOS == "windows" {
c.Found = where + " (file permissions are not checked on Windows)"
return c
}
var bad, fix []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()))
fix = append(fix, "chmod 700 -- "+shellWord(e.ConfigDir))
}
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()))
fix = append(fix, "chmod 600 -- "+shellWord(file))
}
if len(bad) > 0 {
c.State = stateFail
c.Found = where + "; others can read it: " + strings.Join(bad, "; ")
c.Next = &nextstep.Next{Say: "Make it private to you.", Cmd: strings.Join(fix, " && ")}
return c
}
c.Found = where + ", kept private"
return c
}
// shellWord quotes s for a shell only when it needs it. A leading ~ is
// quoted so that it names this path and is not expanded to a home.
func shellWord(s string) string {
if keychainSafe.MatchString(s) && !strings.HasPrefix(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)
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 = &nextstep.Next{Say: "Start a new login, or collect one that was approved.", Cmd: loginCmd}
return c
}
// Live: another run may be waiting on it, so no command is offered
// that could replace it; the approval page is.
c.Found = fmt.Sprintf("a login started %s ago is waiting for approval", ago)
c.Next = &nextstep.Next{Say: "A login is waiting for approval; approve it in a browser."}
if u, err := base.Parse(p.Link); err == nil && p.Link != "" && nextstep.SameOrigin(u, base) {
c.Next.Open = u.String()
}
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 = &nextstep.Next{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 = &nextstep.Next{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
}