Skip to content
quarry Artifact [ec282e1bc3]
Login

Artifact [ec282e1bc3]

Artifact ec282e1bc36d9ffe2da9054e6765d8ea373b4ef336ea49fcae3cd74902c872bf:


package pickupclient

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

// oneObject decodes stdout as exactly one JSON object and nothing else.
func oneObject(t *testing.T, out string) map[string]any {
	t.Helper()
	dec := json.NewDecoder(strings.NewReader(out))
	var m map[string]any
	if err := dec.Decode(&m); err != nil {
		t.Errorf("FAIL: stdout is not a JSON object: %v (%q)", err, out)
		return map[string]any{}
	}
	if dec.More() || strings.TrimSpace(out[dec.InputOffset():]) != "" {
		t.Errorf("FAIL: stdout holds more than one object: %q", out)
	}
	return m
}

func nextOf(m map[string]any) map[string]any {
	n, _ := m["next"].(map[string]any)
	if n == nil {
		return map[string]any{}
	}
	return n
}

// delStore is a store that can refuse to forget.
type delStore struct {
	fakeStore
	delErr  error
	deleted []string
}

func (d *delStore) Delete(host string) error {
	if d.delErr != nil {
		return d.delErr
	}
	d.deleted = append(d.deleted, host)
	delete(d.rec, host)
	return nil
}

func (f *fakeStore) Delete(host string) error {
	delete(f.rec, host)
	return nil
}

// endForge answers me and me.token.end, recording what came in.
type endForge struct {
	srv     *httptest.Server
	mu      sync.Mutex
	ended   []string // Authorization of each end call
	endCode int
	meCode  int
}

func newEndForge(t *testing.T) *endForge {
	f := &endForge{endCode: 200, meCode: 200}
	f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		f.mu.Lock()
		defer f.mu.Unlock()
		switch {
		case r.URL.Path == "/api/v1/me/token/end" && r.Method == "POST":
			f.ended = append(f.ended, r.Header.Get("Authorization"))
			w.WriteHeader(f.endCode)
			w.Write([]byte(`{}`))
		case r.URL.Path == "/api/v1/me":
			if f.meCode != 200 {
				w.WriteHeader(f.meCode)
				w.Write([]byte(`{"error":"authentication required"}`))
				return
			}
			w.Write([]byte(`{"name":"alex","token":{"label":"mac","may":"M","mayNot":["a","b"],"revoke":"/me#machines"},"repos":[{"repo":"alex/website","role":"developer"}]}`))
		default:
			w.WriteHeader(404)
		}
	}))
	t.Cleanup(f.srv.Close)
	return f
}

func (f *endForge) host() string { return strings.TrimPrefix(f.srv.URL, "http://") }

func TestVerbsWithNoLoginExit4WithTheLoginCommandAsNext(t *testing.T) {
	for name, verb := range map[string]func(context.Context, []string, *Env) int{"status": Whoami, "logout": Logout} {
		var out, errw bytes.Buffer
		st := &fakeStore{}
		args := []string{"http://127.0.0.1:1"}
		if code := verb(context.Background(), args, loginEnv(&out, &errw, st)); code != 4 {
			t.Errorf("FAIL: %s with no login exit %d", name, code)
		}
		if out.Len() != 0 || !strings.Contains(errw.String(), "quarry auth login") {
			t.Errorf("FAIL: %s human output: stdout %q stderr %q", name, out.String(), errw.String())
		}
		out.Reset()
		errw.Reset()
		code := verb(context.Background(), append([]string{"--json"}, args...), loginEnv(&out, &errw, st))
		m := oneObject(t, out.String())
		if code != 4 || m["ok"] != false || m["code"] != "no_login" || m["error"] == "" || nextOf(m)["cmd"] != "quarry auth login" {
			t.Errorf("FAIL: %s --json with no login: exit %d %v", name, code, m)
		}
		// -F json is the same thing.
		out.Reset()
		if code := verb(context.Background(), append([]string{"-F", "json"}, args...), loginEnv(&out, &errw, st)); code != 4 || oneObject(t, out.String())["code"] != "no_login" {
			t.Errorf("FAIL: %s -F json: exit %d %q", name, code, out.String())
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestStatusUsesAnEnvironmentTokenWhenNothingIsStored(t *testing.T) {
	f := newEndForge(t)
	var out, errw bytes.Buffer
	e := loginEnv(&out, &errw, &fakeStore{})
	e.Getenv = func(k string) string {
		if k == "QUARRY_TOKEN" {
			return "env-token-value"
		}
		return ""
	}
	if code := Whoami(context.Background(), []string{"--json", f.srv.URL}, e); code != 0 {
		t.Errorf("FAIL: exit %d", code)
	}
	m := oneObject(t, out.String())
	if m["ok"] != true || m["account"] != "alex" {
		t.Errorf("FAIL: %v", m)
	}
	if strings.Contains(out.String()+errw.String(), "env-token-value") {
		t.Errorf("FAIL: the token was printed")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestStatusJSONCarriesOKAndWhatItPrints(t *testing.T) {
	f := newEndForge(t)
	st := &fakeStore{rec: map[string]Record{f.host(): {Account: "alex", Token: loginTestToken}}}
	var out, errw bytes.Buffer
	if code := Whoami(context.Background(), []string{"--json", f.srv.URL}, loginEnv(&out, &errw, st)); code != 0 {
		t.Errorf("FAIL: exit %d", code)
	}
	m := oneObject(t, out.String())
	tok, _ := m["token"].(map[string]any)
	repos, _ := m["repos"].([]any)
	if m["ok"] != true || m["host"] != f.host() || m["account"] != "alex" || tok["label"] != "mac" || tok["may"] != "M" ||
		tok["revoke"] != f.srv.URL+"/me#machines" || len(repos) != 1 || repos[0].(map[string]any)["repo"] != "alex/website" {
		t.Errorf("FAIL: %v", m)
	}
	if strings.Contains(out.String(), loginTestToken) {
		t.Errorf("FAIL: the token was printed")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestStatusWhenTheForgeRefusesTheTokenExits1WithALoginNext(t *testing.T) {
	f := newEndForge(t)
	f.meCode = 401
	st := &fakeStore{rec: map[string]Record{f.host(): {Account: "alex", Token: loginTestToken}}}
	var out, errw bytes.Buffer
	code := Whoami(context.Background(), []string{"--json", f.srv.URL}, loginEnv(&out, &errw, st))
	m := oneObject(t, out.String())
	if code != 1 || m["ok"] != false || m["code"] != "refused" || nextOf(m)["cmd"] != "quarry auth login" {
		t.Errorf("FAIL: exit %d %v", code, m)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLoginJSONIsOneObjectAndTheProgressGoesToStderr(t *testing.T) {
	f := newLoginForge(t)
	var out, errw bytes.Buffer
	st := &fakeStore{}
	if code := Login(context.Background(), []string{"--json", f.srv.URL}, loginEnv(&out, &errw, st)); code != 0 {
		t.Errorf("FAIL: exit %d", code)
	}
	m := oneObject(t, out.String())
	tok, _ := m["token"].(map[string]any)
	if m["ok"] != true || m["account"] != "alex" || tok["label"] != "mac mini, my site" || m["host"] != strings.TrimPrefix(f.srv.URL, "http://") {
		t.Errorf("FAIL: %v", m)
	}
	if !strings.Contains(errw.String(), "ABCD-EFGH") || strings.Contains(out.String()+errw.String(), loginTestToken) {
		t.Errorf("FAIL: the code went missing or the token was printed")
	}
	if got := st.rec[strings.TrimPrefix(f.srv.URL, "http://")].Revoke; got != f.srv.URL+"/me#push" {
		t.Errorf("FAIL: the record keeps revoke address %q", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLoginJSONRefusalsAreOneObjectWithANext(t *testing.T) {
	f := newLoginForge(t)
	f.final = func(w http.ResponseWriter) {
		w.WriteHeader(410)
		w.Write([]byte(`{"state":"expired","error":"x"}`))
	}
	var out, errw bytes.Buffer
	code := Login(context.Background(), []string{"--json", f.srv.URL}, loginEnv(&out, &errw, &fakeStore{}))
	m := oneObject(t, out.String())
	if code != 3 || m["ok"] != false || m["code"] == "" || m["error"] == "" || nextOf(m)["cmd"] != "quarry auth login" {
		t.Errorf("FAIL: exit %d %v", code, m)
	}
	out.Reset()
	code = Login(context.Background(), []string{"--json", "--nope"}, loginEnv(&out, &errw, &fakeStore{}))
	if m := oneObject(t, out.String()); code != 2 || m["ok"] != false {
		t.Errorf("FAIL: usage exit %d %v", code, m)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLogoutEndsTheTokenOnTheForgeThenForgetsIt(t *testing.T) {
	f := newEndForge(t)
	st := &delStore{fakeStore: fakeStore{rec: map[string]Record{f.host(): {Account: "alex", Token: loginTestToken}}}}
	var out, errw bytes.Buffer
	if code := Logout(context.Background(), []string{"--json", f.srv.URL}, loginEnv(&out, &errw, st)); code != 0 {
		t.Errorf("FAIL: exit %d %s", code, errw.String())
	}
	m := oneObject(t, out.String())
	if m["ok"] != true || m["ended"] != true || m["account"] != "alex" {
		t.Errorf("FAIL: %v", m)
	}
	if len(f.ended) != 1 || f.ended[0] != "Bearer "+loginTestToken {
		t.Errorf("FAIL: the forge was asked %v", f.ended)
	}
	if _, err := st.Get(f.host()); !errors.Is(err, ErrNoLogin) || len(st.deleted) != 1 {
		t.Errorf("FAIL: the token is still stored (%v, deleted %v)", err, st.deleted)
	}
	if strings.Contains(out.String()+errw.String(), loginTestToken) {
		t.Errorf("FAIL: the token was printed")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLogoutWhenTheForgeCannotBeReachedKeepsTheTokenAndSaysItIsLive(t *testing.T) {
	f := newEndForge(t)
	host, url := f.host(), f.srv.URL
	f.srv.Close()
	for name, rec := range map[string]Record{
		"with the recorded revoke page": {Account: "alex", Token: loginTestToken, Revoke: url + "/me#machines"},
		"with none recorded":            {Account: "alex", Token: loginTestToken},
	} {
		st := &delStore{fakeStore: fakeStore{rec: map[string]Record{host: rec}}}
		var out, errw bytes.Buffer
		code := Logout(context.Background(), []string{"--json", url}, loginEnv(&out, &errw, st))
		m := oneObject(t, out.String())
		if code != 1 || m["ok"] != false || m["live"] != true || m["code"] != "unreachable" {
			t.Errorf("FAIL: %s: exit %d %v", name, code, m)
		}
		if open, _ := nextOf(m)["open"].(string); !strings.HasPrefix(open, url+"/me") {
			t.Errorf("FAIL: %s: next.open is %q", name, open)
		}
		if got, err := st.Get(host); err != nil || got.Token != loginTestToken || len(st.deleted) != 0 {
			t.Errorf("FAIL: %s: the token was forgotten while live (%v)", name, err)
		}
		if strings.Contains(out.String()+errw.String(), loginTestToken) {
			t.Errorf("FAIL: the token was printed")
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLogoutWhenTheForgeAnswersAnythingButYesKeepsTheToken(t *testing.T) {
	for _, status := range []int{403, 404, 500, 429} {
		f := newEndForge(t)
		f.endCode = status
		st := &delStore{fakeStore: fakeStore{rec: map[string]Record{f.host(): {Account: "alex", Token: loginTestToken}}}}
		var out, errw bytes.Buffer
		code := Logout(context.Background(), []string{"--json", f.srv.URL}, loginEnv(&out, &errw, st))
		m := oneObject(t, out.String())
		if code != 1 || m["ok"] != false || m["live"] != true || nextOf(m)["open"] == nil {
			t.Errorf("FAIL: %d: exit %d %v", status, code, m)
		}
		if _, err := st.Get(f.host()); err != nil {
			t.Errorf("FAIL: %d: the token was forgotten while live", status)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A 401 means the forge already does not take the token: nothing is
// live, so the local copy goes, and the verb does not claim a revoke it
// did not see.
func TestLogoutOfATokenTheForgeAlreadyRefusesForgetsItWithoutClaimingARevoke(t *testing.T) {
	f := newEndForge(t)
	f.endCode = 401
	st := &delStore{fakeStore: fakeStore{rec: map[string]Record{f.host(): {Account: "alex", Token: loginTestToken}}}}
	var out, errw bytes.Buffer
	code := Logout(context.Background(), []string{"--json", f.srv.URL}, loginEnv(&out, &errw, st))
	m := oneObject(t, out.String())
	if code != 0 || m["ok"] != true || m["ended"] != false {
		t.Errorf("FAIL: exit %d %v", code, m)
	}
	if _, err := st.Get(f.host()); !errors.Is(err, ErrNoLogin) {
		t.Errorf("FAIL: the dead token is still stored")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLogoutThatCannotForgetSaysTheTokenWasEndedAndExits1(t *testing.T) {
	f := newEndForge(t)
	st := &delStore{fakeStore: fakeStore{rec: map[string]Record{f.host(): {Account: "alex", Token: loginTestToken}}}, delErr: errors.New("disk said no")}
	var out, errw bytes.Buffer
	code := Logout(context.Background(), []string{"--json", f.srv.URL}, loginEnv(&out, &errw, st))
	m := oneObject(t, out.String())
	if code != 1 || m["ok"] != false || m["code"] != "not_removed" || m["live"] == true || len(f.ended) != 1 {
		t.Errorf("FAIL: exit %d %v", code, m)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLogoutUsageExits2(t *testing.T) {
	var out, errw bytes.Buffer
	for _, args := range [][]string{{"--nope"}, {"a", "b"}} {
		if code := Logout(context.Background(), args, loginEnv(&out, &errw, &fakeStore{})); code != 2 {
			t.Errorf("FAIL: %v exit %d", args, code)
		}
	}
	if code := Logout(context.Background(), []string{"--help"}, loginEnv(&out, &errw, &fakeStore{})); code != 0 {
		t.Errorf("FAIL: help exit %d", code)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The real store forgets from the file and the keychain both.
func TestDirStoreDeleteRemovesTheFileAndTheKeychainItem(t *testing.T) {
	dir := t.TempDir()
	kc := &oneLoginKeychain{}
	s := &dirStore{Dir: dir, Keychain: kc}
	if _, err := s.Put("forge.test", Record{Account: "alex", Token: "tok-alex"}); err != nil {
		t.Fatal(err)
	}
	if err := s.Delete("forge.test"); err != nil {
		t.Errorf("FAIL: delete: %v", err)
	}
	if _, err := s.Get("forge.test"); !errors.Is(err, ErrNoLogin) {
		t.Errorf("FAIL: still stored: %v", err)
	}
	if _, err := kc.Get("forge.test", "alex"); err == nil {
		t.Errorf("FAIL: the keychain still holds the token")
	}
	if _, err := os.Stat(filepath.Join(dir, hostFile("forge.test"))); !errors.Is(err, os.ErrNotExist) {
		t.Errorf("FAIL: the record file is still there: %v", err)
	}
	// A keychain that will not let go is an error, not a silent forget.
	stuck := &dirStore{Dir: dir, Keychain: &stuckKeychain{}}
	stuck.Put("forge.test", Record{Account: "alex", Token: "tok-alex"})
	if err := stuck.Delete("forge.test"); err == nil {
		t.Errorf("FAIL: a keychain that kept the token was reported as forgotten")
	}
	// File store alone.
	plain := &dirStore{Dir: t.TempDir()}
	plain.Put("forge.test", Record{Account: "alex", Token: "tok-alex"})
	if err := plain.Delete("forge.test"); err != nil {
		t.Errorf("FAIL: %v", err)
	}
	if _, err := plain.Get("forge.test"); !errors.Is(err, ErrNoLogin) {
		t.Errorf("FAIL: file store still holds it")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

type stuckKeychain struct{}

func (stuckKeychain) Put(string, string, string) error   { return nil }
func (stuckKeychain) Get(string, string) (string, error) { return "tok-alex", nil }
func (stuckKeychain) Delete(string, string) error        { return errors.New("locked") }

func TestMacKeychainDeleteRemovesTheHostsItems(t *testing.T) {
	var calls [][]string
	n := 0
	m := macKeychain{sec: func(stdin string, args ...string) (string, error) {
		calls = append(calls, args)
		n++
		if n > 1 {
			return "could not be found", errors.New("exit 44")
		}
		return "", nil
	}}
	if err := m.Delete("forge.test", "alex"); err != nil {
		t.Errorf("FAIL: %v", err)
	}
	if len(calls) < 1 || calls[0][0] != "delete-generic-password" || calls[0][2] != "quarry:forge.test" {
		t.Errorf("FAIL: security was run as %v", calls)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}