Skip to content
quarry Artifact [ab12626605]
Login

Artifact [ab12626605]

Artifact ab12626605b7314d7e6758848ef35cc61bbc0da02661e1849bf80da1b4d3fe39:


package pickupclient

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

type doctorForge struct {
	srv     *httptest.Server
	version string
	meCode  int
	calls   map[string]int
	auths   []string
}

func newDoctorForge(t *testing.T) *doctorForge {
	f := &doctorForge{version: "0.42.0", meCode: 200, calls: map[string]int{}}
	f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		f.calls[r.Method+" "+r.URL.Path]++
		switch r.URL.Path {
		case "/api/v1/version":
			w.Write([]byte(`{"version":"` + f.version + `"}`))
		case "/api/v1/me":
			f.auths = append(f.auths, r.Header.Get("Authorization"))
			if f.meCode != 200 {
				w.WriteHeader(f.meCode)
				w.Write([]byte(`{"code":"no_login"}`))
				return
			}
			w.Write([]byte(`{"name":"alex","token":{"label":"mac-mini","may":"m","mayNot":[]},"repos":[]}`))
		default:
			w.WriteHeader(404)
		}
	}))
	t.Cleanup(f.srv.Close)
	return f
}

type doctorRun struct {
	code int
	out  string
	obj  doctorJSON
}

// runDoctor runs doctor against f with a login stored (or not) in a
// fresh config directory; tweak edits the Env first.
func runDoctor(t *testing.T, f *doctorForge, stored bool, asJSON bool, tweak func(*Env, string)) doctorRun {
	t.Helper()
	dir := filepath.Join(t.TempDir(), "quarry")
	st := &dirStore{Dir: dir, Keychain: nil}
	host := strings.TrimPrefix(f.srv.URL, "http://")
	if stored {
		if _, err := st.Put(host, Record{Account: "alex", Token: loginTestToken}); err != nil {
			t.Fatal(err)
		}
	}
	var out, errw bytes.Buffer
	e := &Env{Client: &http.Client{}, Stdout: &out, Stderr: &errw, Keys: st, ConfigDir: dir, Version: "0.42.0",
		Hostname: func() (string, error) { return "mac-mini", nil },
		Getenv:   func(string) string { return "" },
		Run: func(context.Context, string, []string, []string) (string, error) {
			return "this is zit version 0.14.14\n", nil
		}}
	if tweak != nil {
		tweak(e, dir)
	}
	args := []string{f.srv.URL}
	if asJSON {
		args = append(args, "--json")
	}
	r := doctorRun{code: Doctor(context.Background(), args, e), out: out.String()}
	if asJSON {
		if err := json.Unmarshal(out.Bytes(), &r.obj); err != nil {
			t.Errorf("FAIL: stdout is not one JSON object: %v", err)
		}
	}
	return r
}

func (r doctorRun) check(t *testing.T, id string) doctorCheck {
	t.Helper()
	for _, c := range r.obj.Checks {
		if c.ID == id {
			return c
		}
	}
	t.Errorf("FAIL: no check %q", id)
	return doctorCheck{}
}

func wantState(t *testing.T, r doctorRun, id, state string) doctorCheck {
	t.Helper()
	c := r.check(t, id)
	if c.State != state {
		t.Errorf("FAIL: check %s is %q, want %q (%s)", id, c.State, state, c.Found)
	}
	if state != stateOK && (c.Next == nil || c.Next.Say == "") {
		t.Errorf("FAIL: check %s is %s with no next", id, state)
	}
	if state == stateOK && c.Next != nil {
		t.Errorf("FAIL: check %s is ok and has a next", id)
	}
	return c
}

func TestDoctorHealthyIsAllOkAndExitsZero(t *testing.T) {
	f := newDoctorForge(t)
	r := runDoctor(t, f, true, true, nil)
	if r.code != 0 || !r.obj.OK || r.obj.Next != nil {
		t.Errorf("FAIL: exit %d ok %v next %v", r.code, r.obj.OK, r.obj.Next)
	}
	for _, id := range []string{checkForge, checkVersion, checkLogin, checkStorage, checkPending, checkZit} {
		wantState(t, r, id, stateOK)
	}
	for _, c := range r.obj.Checks {
		if c.ID == checkEnvToken {
			t.Errorf("FAIL: env_token listed with no QUARRY_TOKEN set")
		}
	}
	if strings.Contains(r.out, loginTestToken) {
		t.Errorf("FAIL: the token was printed")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorJSONShape(t *testing.T) {
	f := newDoctorForge(t)
	r := runDoctor(t, f, false, true, nil)
	var raw map[string]json.RawMessage
	if err := json.Unmarshal([]byte(r.out), &raw); err != nil {
		t.Fatalf("FAIL: %v", err)
	}
	for _, k := range []string{"ok", "host", "checks", "next"} {
		if _, ok := raw[k]; !ok {
			t.Errorf("FAIL: no key %q", k)
		}
	}
	var checks []map[string]json.RawMessage
	json.Unmarshal(raw["checks"], &checks)
	for _, c := range checks {
		for _, k := range []string{"id", "state", "found", "next"} {
			if _, ok := c[k]; !ok {
				t.Errorf("FAIL: a check has no key %q", k)
			}
		}
	}
	if string(raw["ok"]) != "false" || bytes.Count([]byte(r.out), []byte("\n")) != 1 {
		t.Errorf("FAIL: ok %s, lines %d", raw["ok"], bytes.Count([]byte(r.out), []byte("\n")))
	}
	var next map[string]any
	json.Unmarshal(raw["next"], &next)
	if next["cmd"] != "quarry auth login" {
		t.Errorf("FAIL: top next %v", next)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorNoLoginExitsFour(t *testing.T) {
	f := newDoctorForge(t)
	r := runDoctor(t, f, false, true, nil)
	wantState(t, r, checkLogin, stateFail)
	if r.code != exitNoLogin || r.obj.OK {
		t.Errorf("FAIL: exit %d ok %v", r.code, r.obj.OK)
	}
	if f.calls["GET /api/v1/me"] != 0 {
		t.Errorf("FAIL: me was called with no token")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorForgeDownFailsAndExitsOne(t *testing.T) {
	f := newDoctorForge(t)
	f.srv.Close()
	r := runDoctor(t, f, true, true, nil)
	wantState(t, r, checkForge, stateFail)
	wantState(t, r, checkVersion, stateWarn)
	wantState(t, r, checkLogin, stateWarn)
	if r.code != 1 {
		t.Errorf("FAIL: exit %d", r.code)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorVersionStates(t *testing.T) {
	for ver, want := range map[string]string{"0.42.7": stateOK, "0.43.0": stateWarn, "1.0.0": stateFail, "dev": stateOK} {
		f := newDoctorForge(t)
		f.version = ver
		r := runDoctor(t, f, true, true, nil)
		c := wantState(t, r, checkVersion, want)
		if want == stateFail && r.code != 1 {
			t.Errorf("FAIL: incompatible forge exit %d", r.code)
		}
		_ = c
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorRefusedTokenFails(t *testing.T) {
	f := newDoctorForge(t)
	f.meCode = 401
	r := runDoctor(t, f, true, true, nil)
	c := wantState(t, r, checkLogin, stateFail)
	if c.Next.Cmd != loginCmd || r.code != 1 {
		t.Errorf("FAIL: next %+v exit %d", c.Next, r.code)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorEnvTokenStates(t *testing.T) {
	hostOf := ""
	setEnv := func(e *Env, _ string) {
		e.Getenv = func(k string) string {
			switch k {
			case tokenEnvVar:
				return "env-token-value"
			case envHostVar:
				return hostOf
			}
			return ""
		}
	}
	// In use, and hiding a stored login: warn.
	f := newDoctorForge(t)
	hostOf = f.srv.URL
	r := runDoctor(t, f, true, true, setEnv)
	wantState(t, r, checkEnvToken, stateWarn)
	wantState(t, r, checkLogin, stateOK)
	if len(f.auths) != 1 || f.auths[0] != "Bearer env-token-value" {
		t.Errorf("FAIL: me carried %v", f.auths)
	}
	if r.code != 0 || strings.Contains(r.out, "env-token-value") {
		t.Errorf("FAIL: exit %d or the token printed", r.code)
	}
	// In use, nothing stored: ok.
	f = newDoctorForge(t)
	hostOf = f.srv.URL
	r = runDoctor(t, f, false, true, setEnv)
	wantState(t, r, checkEnvToken, stateOK)
	if r.code != 0 {
		t.Errorf("FAIL: env login exit %d", r.code)
	}
	// Refused: the login check fails and says to unset it.
	f = newDoctorForge(t)
	hostOf = f.srv.URL
	f.meCode = 401
	r = runDoctor(t, f, true, true, setEnv)
	c := wantState(t, r, checkLogin, stateFail)
	if c.Next.Cmd != "" || r.code != 1 {
		t.Errorf("FAIL: refused env token next %+v exit %d", c.Next, r.code)
	}
	// Set for another host: ok, and never sent here.
	f = newDoctorForge(t)
	r = runDoctor(t, f, true, true, func(e *Env, d string) {
		setEnv(e, d)
		base := e.Getenv
		e.Getenv = func(k string) string {
			if k == envHostVar {
				return "https://other.example"
			}
			return base(k)
		}
	})
	wantState(t, r, checkEnvToken, stateOK)
	if len(f.auths) != 1 || f.auths[0] != "Bearer "+loginTestToken {
		t.Errorf("FAIL: me carried %v", f.auths)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorStoragePermissions(t *testing.T) {
	f := newDoctorForge(t)
	host := strings.TrimPrefix(f.srv.URL, "http://")
	for name, tc := range map[string]struct {
		mutate func(dir string)
		want   string
	}{
		"file open": {func(d string) { os.Chmod(filepath.Join(d, hostFile(host)), 0o644) }, stateFail},
		"dir open":  {func(d string) { os.Chmod(d, 0o755) }, stateFail},
		"private":   {func(string) {}, stateOK},
	} {
		r := runDoctor(t, f, true, true, func(e *Env, d string) { tc.mutate(d) })
		c := wantState(t, r, checkStorage, tc.want)
		if tc.want == stateFail && !strings.HasPrefix(c.Next.Cmd, "chmod ") {
			t.Errorf("FAIL: %s next %+v", name, c.Next)
		}
		if tc.want == stateFail && r.code != 1 {
			t.Errorf("FAIL: %s exit %d", name, r.code)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorPendingStates(t *testing.T) {
	f := newDoctorForge(t)
	host := strings.TrimPrefix(f.srv.URL, "http://")
	mk := func(started time.Time, life int) func(*Env, string) {
		return func(e *Env, d string) {
			p := pendingLogin{Host: host, Label: "mac-mini", Key: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", Code: "ABCD-EFGH",
				Started: started.UTC().Format(time.RFC3339), Life: life}
			if err := savePending(d, p); err != nil {
				t.Fatal(err)
			}
		}
	}
	r := runDoctor(t, f, true, true, mk(time.Now().Add(-2*time.Minute), 600))
	wantState(t, r, checkPending, stateWarn)
	r2 := runDoctor(t, f, true, true, mk(time.Now().Add(-14*time.Minute), 600))
	c := wantState(t, r2, checkPending, stateWarn)
	if c.Next.Cmd != loginCmd || r2.code != 0 {
		t.Errorf("FAIL: next %+v exit %d", c.Next, r2.code)
	}
	if r.check(t, checkPending).Found == r2.check(t, checkPending).Found {
		t.Errorf("FAIL: waiting and expired read the same")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorZitStates(t *testing.T) {
	f := newDoctorForge(t)
	r := runDoctor(t, f, true, true, func(e *Env, _ string) {
		e.Run = func(context.Context, string, []string, []string) (string, error) { return "", exec.ErrNotFound }
	})
	wantState(t, r, checkZit, stateWarn)
	r = runDoctor(t, f, true, true, func(e *Env, _ string) {
		e.Run = func(context.Context, string, []string, []string) (string, error) { return "boom", errors.New("exit 1") }
	})
	wantState(t, r, checkZit, stateWarn)
	r = runDoctor(t, f, true, true, nil)
	if c := wantState(t, r, checkZit, stateOK); !strings.Contains(c.Found, "0.14.14") {
		t.Errorf("FAIL: version not reported: %s", c.Found)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorChangesNothingAndUsesTheTokenOnlyForMe(t *testing.T) {
	f := newDoctorForge(t)
	var dir string
	before := map[string]os.FileInfo{}
	snap := func(d string) map[string]os.FileInfo {
		m := map[string]os.FileInfo{}
		filepath.Walk(d, func(p string, fi os.FileInfo, err error) error {
			if err == nil {
				m[p] = fi
			}
			return nil
		})
		return m
	}
	runDoctor(t, f, true, false, func(e *Env, d string) {
		dir = d
		before = snap(d)
	})
	after := snap(dir)
	if len(before) != len(after) {
		t.Errorf("FAIL: files %d before, %d after", len(before), len(after))
	}
	for p, fi := range before {
		if a, ok := after[p]; !ok || !a.ModTime().Equal(fi.ModTime()) || a.Size() != fi.Size() {
			t.Errorf("FAIL: %s changed", p)
		}
	}
	for call := range f.calls {
		if !strings.HasPrefix(call, "GET ") {
			t.Errorf("FAIL: doctor made a %s", call)
		}
	}
	if f.calls["GET /api/v1/me"] != 1 || len(f.calls) != 2 {
		t.Errorf("FAIL: calls %v", f.calls)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorHumanOutputIsOneLinePerCheckThenNext(t *testing.T) {
	f := newDoctorForge(t)
	r := runDoctor(t, f, false, false, nil)
	lines := strings.Split(strings.TrimRight(r.out, "\n"), "\n")
	// header, one per check (6), then the next step and its command.
	if len(lines) != 1+6+2 {
		t.Errorf("FAIL: %d lines:\n%s", len(lines), r.out)
	}
	if !strings.Contains(r.out, loginCmd) {
		t.Errorf("FAIL: the next command is not printed")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestDoctorUsage(t *testing.T) {
	f := newDoctorForge(t)
	var out, errw bytes.Buffer
	e := &Env{Client: &http.Client{}, Stdout: &out, Stderr: &errw, Keys: &fakeStore{}, ConfigDir: t.TempDir()}
	if code := Doctor(context.Background(), []string{"--fix", f.srv.URL}, e); code != 2 {
		t.Errorf("FAIL: --fix exit %d", code)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}