Skip to content
quarry Artifact [cf73e7d512]
Login

Artifact [cf73e7d512]

Artifact cf73e7d512bcca6232478e60d31468b0fc913ccc83d1c8e7959b3f58bede62f3:


package pickupclient

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

const loginTestToken = "tok_Zq81-fake_login_value"

type fakeStore struct {
	rec   map[string]Record
	where string
	err   error
}

func (f *fakeStore) Put(host string, r Record) (string, error) {
	if f.err != nil {
		return "", f.err
	}
	if f.rec == nil {
		f.rec = map[string]Record{}
	}
	f.rec[host] = r
	return "the fake keychain", nil
}

func (f *fakeStore) Get(host string) (Record, error) {
	r, ok := f.rec[host]
	if !ok {
		return Record{}, ErrNoLogin
	}
	return r, nil
}

type loginForge struct {
	srv       *httptest.Server
	collects  atomic.Int32
	final     func(w http.ResponseWriter)
	startBody map[string]any
	meAuth    string
	expires   time.Time
}

func newLoginForge(t *testing.T) *loginForge {
	f := &loginForge{expires: time.Now().Add(10 * time.Minute)}
	f.final = func(w http.ResponseWriter) {
		w.Write([]byte(`{"request":"r1","op":"login.token.new","result":{"account":"alex","label":"mac","token":{"id":"t1"}},"secret":{"value":"` + loginTestToken + `"}}`))
	}
	f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/api/v1/setup/start":
			if err := json.NewDecoder(r.Body).Decode(&f.startBody); err != nil {
				t.Errorf("FAIL: start body: %v", err)
			}
			json.NewEncoder(w).Encode(map[string]string{"code": "ABCD-EFGH", "link": f.srv.URL + "/setup", "expires": f.expires.UTC().Format(time.RFC3339)})
		case "/api/v1/pickups/collect":
			if r.Header.Get("Quarry-Pickup-Kind") != "login" || !strings.HasPrefix(r.Header.Get("Authorization"), "Pickup ") {
				t.Errorf("FAIL: collect carried kind %q", r.Header.Get("Quarry-Pickup-Kind"))
			}
			switch f.collects.Add(1) {
			case 1:
				w.WriteHeader(404)
				w.Write([]byte(`{"error":"no such pickup"}`))
			case 2:
				w.Header().Set("Retry-After", "1")
				w.WriteHeader(429)
			case 3:
				w.WriteHeader(202)
				w.Write([]byte(`{"state":"pending"}`))
			default:
				f.final(w)
			}
		case "/api/v1/me":
			f.meAuth = r.Header.Get("Authorization")
			w.Write([]byte(`{"name":"alex","token":{"label":"mac mini, my site","may":"MAY-FROM-SERVER","mayNot":["stop one","stop two","stop three"],"revoke":"/me#push"},"repos":[{"repo":"alex/website","role":"developer"},{"repo":"alex/blog","role":"reader"}]}`))
		default:
			w.WriteHeader(404)
		}
	}))
	t.Cleanup(f.srv.Close)
	return f
}

func loginEnv(out, errw *bytes.Buffer, st Store) *Env {
	return &Env{
		Client: &http.Client{}, Stdout: out, Stderr: errw, Keys: st,
		Poll:     time.Millisecond,
		Sleep:    func(context.Context, time.Duration) error { return nil },
		Hostname: func() (string, error) { return "mac mini", nil },
		Getwd:    func() (string, error) { return "/work/my site", nil },
	}
}

func TestLoginStoresTheTokenAndPrintsNoSecret(t *testing.T) {
	f := newLoginForge(t)
	var out, errw bytes.Buffer
	st := &fakeStore{}
	code := Login(context.Background(), []string{f.srv.URL}, loginEnv(&out, &errw, st))
	if code != 0 {
		t.Errorf("FAIL: exit %d", code)
	}
	host := strings.TrimPrefix(f.srv.URL, "http://")
	if got := st.rec[host]; got.Token != loginTestToken || got.Account != "alex" {
		t.Errorf("FAIL: stored %+v", got)
	}
	if f.startBody["kind"] != "login" || f.startBody["label"] != "mac mini" || len(f.startBody["pickup"].(string)) != 64 || len(f.startBody) != 3 {
		t.Errorf("FAIL: start body %v", f.startBody)
	}
	if f.meAuth != "Bearer "+loginTestToken {
		t.Errorf("FAIL: me was read with the wrong credential")
	}
	if strings.Contains(out.String()+errw.String(), loginTestToken) {
		t.Errorf("FAIL: the token was printed")
	}
	for _, want := range []string{"MAY-FROM-SERVER", "stop one; stop two; stop three", `"mac mini, my site"`, f.srv.URL + "/me#push"} {
		if !strings.Contains(out.String(), want) {
			t.Errorf("FAIL: output lacks the server's %q", want)
		}
	}
	if !strings.Contains(out.String(), "ABCD-EFGH") || !strings.Contains(out.String(), f.srv.URL+"/setup") {
		t.Errorf("FAIL: link or code not shown")
	}
	if f.collects.Load() != 4 {
		t.Errorf("FAIL: collected %d times", f.collects.Load())
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLoginExpiredCodeExits3(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
	st := &fakeStore{}
	if code := Login(context.Background(), []string{f.srv.URL}, loginEnv(&out, &errw, st)); code != 3 {
		t.Errorf("FAIL: exit %d", code)
	}
	if len(st.rec) != 0 {
		t.Errorf("FAIL: something was stored")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLoginTimeOutExits3(t *testing.T) {
	f := newLoginForge(t)
	f.final = func(w http.ResponseWriter) { w.WriteHeader(202) }
	f.expires = time.Now().Add(-time.Second)
	var out, errw bytes.Buffer
	if code := Login(context.Background(), []string{f.srv.URL}, loginEnv(&out, &errw, &fakeStore{})); code != 3 {
		t.Errorf("FAIL: exit %d", code)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLoginDeniedExits1(t *testing.T) {
	f := newLoginForge(t)
	f.final = func(w http.ResponseWriter) {
		w.WriteHeader(410)
		w.Write([]byte(`{"state":"denied","error":"x"}`))
	}
	var out, errw bytes.Buffer
	if code := Login(context.Background(), []string{f.srv.URL}, loginEnv(&out, &errw, &fakeStore{})); code != 1 {
		t.Errorf("FAIL: exit %d", code)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

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

func TestWhoamiWithNoTokenExits1(t *testing.T) {
	var out, errw bytes.Buffer
	if code := Whoami(context.Background(), []string{"http://127.0.0.1:1"}, loginEnv(&out, &errw, &fakeStore{})); code != 1 {
		t.Errorf("FAIL: exit %d", code)
	}
	if out.Len() != 0 {
		t.Errorf("FAIL: printed on stdout")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestWhoamiReadsTheStoredToken(t *testing.T) {
	f := newLoginForge(t)
	host := strings.TrimPrefix(f.srv.URL, "http://")
	st := &fakeStore{rec: map[string]Record{host: {Account: "alex", Token: loginTestToken}}}
	var out, errw bytes.Buffer
	if code := Whoami(context.Background(), []string{f.srv.URL}, loginEnv(&out, &errw, st)); code != 0 {
		t.Errorf("FAIL: exit %d", code)
	}
	for _, want := range []string{"alex", "mac mini, my site", "alex/website", "alex/blog"} {
		if !strings.Contains(out.String(), want) {
			t.Errorf("FAIL: output lacks %q", want)
		}
	}
	if strings.Contains(out.String(), loginTestToken) {
		t.Errorf("FAIL: the token was printed")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestCleanLabel(t *testing.T) {
	for in, want := range map[string]string{
		"mac mini, site":        "mac mini, site",
		"a/b\\c:é!d":            "abcd",
		"  spaced  ":            "spaced",
		"":                      "machine",
		strings.Repeat("x", 90): strings.Repeat("x", 64),
	} {
		if got := cleanLabel(in); got != want {
			t.Errorf("FAIL: cleanLabel(%q) = %q", in, got)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestFileStoreIsPrivateAndKeychainKeepsTokenOut(t *testing.T) {
	dir := t.TempDir()
	// No keychain: the token lives in a 0600 file named for the host.
	s := &dirStore{Dir: dir}
	where, err := s.Put("forge.example:8080", Record{Account: "alex", Token: loginTestToken})
	if err != nil {
		t.Fatal(err)
	}
	fi, err := os.Stat(filepath.Join(dir, hostFile("forge.example:8080")))
	if err != nil || fi.Mode().Perm() != 0o600 || where == "" {
		t.Errorf("FAIL: stat %v %v", fi, err)
	}
	got, err := s.Get("forge.example:8080")
	if err != nil || got.Token != loginTestToken || got.Account != "alex" {
		t.Errorf("FAIL: get %+v %v", got, err)
	}
	// A keychain that works holds the token; the file then has none.
	var kept string
	k := &dirStore{Dir: dir, Keychain: &memKeychain{put: func(h, a, v string) error { kept = v; return nil }, get: func(string, string) (string, error) { return kept, nil }}}
	if _, err := k.Put("h2", Record{Account: "alex", Token: loginTestToken}); err != nil {
		t.Fatal(err)
	}
	b, _ := os.ReadFile(filepath.Join(dir, hostFile("h2")))
	if kept != loginTestToken || bytes.Contains(b, []byte(loginTestToken)) {
		t.Errorf("FAIL: token placement")
	}
	if r, err := k.Get("h2"); err != nil || r.Token != loginTestToken {
		t.Errorf("FAIL: get through keychain %v", err)
	}
	// A keychain that fails falls back to the file.
	bad := &dirStore{Dir: dir, Keychain: &memKeychain{put: func(string, string, string) error { return errors.New("no") }}}
	if _, err := bad.Put("h3", Record{Account: "a", Token: loginTestToken}); err != nil {
		t.Fatal(err)
	}
	if r, err := bad.Get("h3"); err != nil || r.Token != loginTestToken {
		t.Errorf("FAIL: fallback %v", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

type memKeychain struct {
	put func(host, account, value string) error
	get func(host, account string) (string, error)
}

func (m *memKeychain) Put(h, a, v string) error { return m.put(h, a, v) }
func (m *memKeychain) Get(h, a string) (string, error) {
	if m.get == nil {
		return "", errors.New("none")
	}
	return m.get(h, a)
}

// oneLoginKeychain holds one item per host, as macKeychain's Put leaves it.
type oneLoginKeychain struct{ items map[string][2]string }

func (k *oneLoginKeychain) Put(h, a, v string) error {
	if k.items == nil {
		k.items = map[string][2]string{}
	}
	k.items[h] = [2]string{a, v}
	return nil
}

func (k *oneLoginKeychain) Get(h, a string) (string, error) {
	if it, ok := k.items[h]; ok && it[0] == a {
		return it[1], nil
	}
	return "", errors.New("none")
}

func TestSecondLoginOnAHostReplacesTheFirst(t *testing.T) {
	s := &dirStore{Dir: t.TempDir(), Keychain: &oneLoginKeychain{}}
	s.Put("forge.test", Record{Account: "alice", Token: "tok-alice"})
	s.Put("forge.test", Record{Account: "bob", Token: "tok-bob"})
	if r, err := s.Get("forge.test"); err != nil || r.Account != "bob" || r.Token != "tok-bob" {
		t.Errorf("FAIL: whoami would use %+v %v", r, err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestMacKeychainCommands(t *testing.T) {
	var calls [][]string
	var stdins []string
	m := macKeychain{sec: func(stdin string, args ...string) (string, error) {
		calls = append(calls, args)
		stdins = append(stdins, stdin)
		if args[0] == "delete-generic-password" {
			return "", errors.New("none left")
		}
		return "the-token\n", nil
	}}
	if err := m.Put("h.test", "alice", "tok123"); err != nil {
		t.Fatal(err)
	}
	if calls[0][0] != "delete-generic-password" || calls[0][2] != "quarry:h.test" {
		t.Errorf("FAIL: the old item is not removed first: %v", calls)
	}
	last := calls[len(calls)-1]
	if last[0] != "-i" || strings.Contains(strings.Join(last, " "), "tok123") || !strings.Contains(stdins[len(stdins)-1], "tok123") {
		t.Errorf("FAIL: the value must travel on stdin alone: %v", calls)
	}
	calls = nil
	got, _ := m.Get("h.test", "alice")
	if got != "the-token" || strings.Join(calls[0], " ") != "find-generic-password -s quarry:h.test -a alice -w" {
		t.Errorf("FAIL: get %q via %v", got, calls)
	}
	for _, bad := range []string{`a"b`, "a b", "a;b", "a\nb", ""} {
		before := len(calls)
		if err := m.Put("h.test", "alice", bad); err == nil || len(calls) != before {
			t.Errorf("FAIL: value %q was not refused before any command", bad)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestHostsNeverShareARecord(t *testing.T) {
	u := func(s string) *url.URL { x, _ := url.Parse(s); return x }
	if hostKey(u("https://ZeitForge.app:443")) != hostKey(u("https://zeitforge.app")) {
		t.Errorf("FAIL: the default port and case split one host")
	}
	if hostKey(u("http://a.test:80")) != "a.test" || hostKey(u("https://a.test:80")) != "a.test:80" {
		t.Errorf("FAIL: default port is per scheme")
	}
	if hostFile("a:8080") == hostFile("a_8080") {
		t.Errorf("FAIL: file names collide")
	}
	s := &dirStore{Dir: t.TempDir()}
	s.Put("a:8080", Record{Account: "x", Token: "t1"})
	if _, err := s.Get("a_8080"); err == nil {
		t.Errorf("FAIL: another host read the record")
	}
	// A record moved to another host's file is refused.
	b, _ := os.ReadFile(filepath.Join(s.Dir, hostFile("a:8080")))
	os.WriteFile(filepath.Join(s.Dir, hostFile("b")), b, 0o600)
	if _, err := s.Get("b"); err == nil {
		t.Errorf("FAIL: a record for another host was accepted")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestStoreTightensItsDirectoryAndLeavesNoLooseTemp(t *testing.T) {
	dir := filepath.Join(t.TempDir(), "q")
	os.Mkdir(dir, 0o755)
	s := &dirStore{Dir: dir}
	if _, err := s.Put("h", Record{Account: "a", Token: "t"}); err != nil {
		t.Fatal(err)
	}
	if fi, _ := os.Stat(dir); fi.Mode().Perm() != 0o700 {
		t.Errorf("FAIL: directory mode %v", fi.Mode().Perm())
	}
	ents, _ := os.ReadDir(dir)
	for _, e := range ents {
		if fi, _ := e.Info(); fi.Mode().Perm() != 0o600 {
			t.Errorf("FAIL: %s mode %v", e.Name(), fi.Mode().Perm())
		}
	}
	if len(ents) != 1 {
		t.Errorf("FAIL: %d files", len(ents))
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestShowStripsControlAndEscapes(t *testing.T) {
	for in, want := range map[string]string{
		"a\x1b[31mred\x1b[0m": "ared",
		"x\x1b]0;title\x07y":  "xy",
		"t\x00\x07\r\n\x7fz":  "tz",
		"c1\u009bz":           "c1z",
	} {
		if got := show(in); got != want {
			t.Errorf("FAIL: show(%q) = %q", in, got)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLoginPrintsOnlyItsOwnOriginsLinkAndStripsServerText(t *testing.T) {
	var out, errw bytes.Buffer
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/api/v1/setup/start":
			w.Write([]byte(`{"code":"AB\u001b[31mCD","link":"https://evil.test/phish","expires":"` + time.Now().Add(24*time.Hour).UTC().Format(time.RFC3339) + `"}`))
		default:
			http.Redirect(w, r, "/elsewhere", 302)
		}
	}))
	defer srv.Close()
	// A 3xx on collect is refused, not followed.
	code := Login(context.Background(), []string{srv.URL}, loginEnv(&out, &errw, &fakeStore{}))
	if code != 1 {
		t.Errorf("FAIL: exit %d on a redirect", code)
	}
	if strings.Contains(out.String(), "evil.test") || !strings.Contains(out.String(), srv.URL+"/setup") || strings.Contains(out.String(), "\x1b") {
		t.Errorf("FAIL: link or code not made safe")
	}
	if !strings.Contains(out.String(), "(15 minutes)") {
		t.Errorf("FAIL: the wait is not capped")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestA401IsRefusedByLoginAndWhoami(t *testing.T) {
	f := newLoginForge(t)
	f.final = func(w http.ResponseWriter) { w.WriteHeader(401) }
	var out, errw bytes.Buffer
	if code := Login(context.Background(), []string{f.srv.URL}, loginEnv(&out, &errw, &fakeStore{})); code != 1 {
		t.Errorf("FAIL: login exit %d on 401", code)
	}
	deny := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(401) }))
	defer deny.Close()
	host := strings.TrimPrefix(deny.URL, "http://")
	st := &fakeStore{rec: map[string]Record{host: {Account: "alex", Token: "t"}}}
	if code := Whoami(context.Background(), []string{deny.URL}, loginEnv(&out, &errw, st)); code != 1 {
		t.Errorf("FAIL: whoami exit %d on 401", code)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The revoke address is the server's: a forge that gives none gets no
// revoke line, and the client never makes one up.
func TestRevokeLineComesFromTheServerAlone(t *testing.T) {
	f := newLoginForge(t)
	f.srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/api/v1/me" {
			w.Write([]byte(`{"name":"alex","token":{"label":"mac","may":"m","mayNot":[]},"repos":[]}`))
			return
		}
		w.WriteHeader(404)
	})
	var out, errw bytes.Buffer
	st := &fakeStore{rec: map[string]Record{strings.TrimPrefix(f.srv.URL, "http://"): {Account: "alex", Token: loginTestToken}}}
	if code := Whoami(context.Background(), []string{f.srv.URL}, loginEnv(&out, &errw, st)); code != 0 {
		t.Errorf("FAIL: exit %d: %s", code, errw.String())
	}
	if strings.Contains(out.String(), "revoke") {
		t.Errorf("FAIL: the client composed a revoke address the server did not give")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// With no address on the command line the host is the installer's
// recorded one; with none recorded, the default forge.
func TestDefaultHostIsTheInstallersRecordedOne(t *testing.T) {
	dir := t.TempDir()
	if got := DefaultHost(dir); got != defaultForge {
		t.Errorf("FAIL: nothing recorded gave %q, want %q", got, defaultForge)
	}
	if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"host":"https://forge.example.test"}`), 0o600); err != nil {
		t.Fatal(err)
	}
	if got := DefaultHost(dir); got != "https://forge.example.test" {
		t.Errorf("FAIL: recorded host gave %q", got)
	}
	if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"host":"not a url"}`), 0o600); err != nil {
		t.Fatal(err)
	}
	if got := DefaultHost(dir); got != defaultForge {
		t.Errorf("FAIL: a bad record gave %q, want the default", got)
	}
	// Whoami with no argument reads the recorded host.
	f := newLoginForge(t)
	os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"host":"`+f.srv.URL+`"}`), 0o600)
	var out, errw bytes.Buffer
	st := &fakeStore{rec: map[string]Record{strings.TrimPrefix(f.srv.URL, "http://"): {Account: "alex", Token: loginTestToken}}}
	e := loginEnv(&out, &errw, st)
	e.ConfigDir = dir
	if code := Whoami(context.Background(), nil, e); code != 0 {
		t.Errorf("FAIL: whoami with the recorded host exit %d: %s", code, errw.String())
	}
	if !t.Failed() {
		t.Log("ok")
	}
}