Skip to content
quarry Artifact [535a5b5e24]
Login

Artifact [535a5b5e24]

Artifact 535a5b5e24b8c4e5663fff840206b5f440719d697569e055ba33201342f458dd:


package main

import (
	"bytes"
	"compress/zlib"
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"sort"
	"strings"
	"sync"
	"testing"

	"craftdesign.group/quarry/internal/pickupclient"
)

type memStore map[string]pickupclient.Record

func (m memStore) Put(host string, r pickupclient.Record) (string, error) {
	m[host] = r
	return "memory", nil
}
func (m memStore) Delete(host string) error { delete(m, host); return nil }
func (m memStore) Get(host string) (pickupclient.Record, error) {
	if r, ok := m[host]; ok {
		return r, nil
	}
	return pickupclient.Record{}, pickupclient.ErrNoLogin
}

// RFC 0033 step 5, against the real sync lane (wired as serve wires it)
// and the real zit and fossil: quarry repo clone of a private repository,
// then bare pull and push with no password and nothing in the
// environment, and no copy of the token left in the checkout.
func TestRepoCloneThenBareSyncNeedsNoPassword(t *testing.T) {
	r := newFirstPushRig(t, "vault")
	if _, err := exec.LookPath("fossil"); err != nil {
		if os.Getenv("CI") == "true" {
			t.Fatal("FAIL: fossil not on PATH under CI")
		}
		t.Skip("fossil not on PATH")
	}
	r.commit(t, r.dirs["vault"])
	token := r.token
	mux := http.NewServeMux()
	// The namespaced address the client clones from (RFC 0025).
	var tapMu sync.Mutex
	var tapping bool
	tapped := map[string]bool{}
	mux.HandleFunc("POST /r/jan/vault", func(w http.ResponseWriter, req *http.Request) {
		req.SetPathValue("repo", "vault")
		tapMu.Lock()
		on := tapping
		tapMu.Unlock()
		// Only what came through the proxy, which sends Basic itself;
		// fossil's own later rounds sign a login card instead.
		if on && req.Header.Get("Authorization") != "" {
			// Every card fossil sent while it cloned through the proxy.
			raw, _ := io.ReadAll(req.Body)
			req.Body = io.NopCloser(bytes.NewReader(raw))
			if len(raw) > 4 {
				if zr, err := zlib.NewReader(bytes.NewReader(raw[4:])); err == nil {
					text, _ := io.ReadAll(zr)
					tapMu.Lock()
					for _, line := range strings.Split(string(text), "\n") {
						if card, _, _ := strings.Cut(line, " "); card != "" {
							tapped[card] = true
						}
					}
					tapMu.Unlock()
				}
			}
		}
		r.front.ServeHTTP(w, req)
	})
	mux.HandleFunc("GET /api/v1/me", func(w http.ResponseWriter, req *http.Request) {
		if req.Header.Get("Authorization") != "Bearer "+token {
			w.WriteHeader(401)
			return
		}
		w.Write([]byte(`{"name":"jan"}`))
	})
	mux.HandleFunc("GET /api/v1/r/jan/vault/info", func(w http.ResponseWriter, req *http.Request) {
		if req.Header.Get("Authorization") != "Bearer "+token {
			w.WriteHeader(404)
			return
		}
		w.Write([]byte(`{"name":"vault","checkins":1}`))
	})
	srv := httptest.NewServer(mux)
	t.Cleanup(srv.Close)
	u, _ := url.Parse(srv.URL)
	t.Setenv("ZIT_PASSWORD", "")
	t.Setenv("HOME", r.home)
	t.Setenv("FOSSIL_HOME", r.home)

	clone := func(extra ...string) (string, string) {
		work := t.TempDir()
		var out, errw bytes.Buffer
		st := memStore{u.Host: {Host: u.Host, Account: "jan", Token: token}}
		e := &pickupclient.Env{Client: &http.Client{}, Stdout: &out, Stderr: &errw, Keys: st, ConfigDir: t.TempDir(),
			Getenv: func(string) string { return "" }}
		args := append([]string{"jan/vault", filepath.Join(work, "vault"), "--host", srv.URL, "--json"}, extra...)
		if code := pickupclient.Clone(context.Background(), args, e); code != 0 {
			t.Fatalf("FAIL: clone exit %d out %q err %q", code, out.String(), errw.String())
		}
		if strings.Contains(out.String()+errw.String(), token) {
			t.Errorf("FAIL: the token was printed")
		}
		return work, filepath.Join(work, "vault")
	}
	noTokenOnDisk := func(root string) {
		filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
			if err == nil && info.Mode().IsRegular() {
				if b, _ := os.ReadFile(p); bytes.Contains(b, []byte(token)) {
					t.Errorf("FAIL: the token is on disk in %s", p)
				}
			}
			return nil
		})
	}
	bare := func(dir, tool string, args ...string) {
		t.Helper()
		cmd := exec.Command(tool, args...)
		cmd.Dir = dir
		cmd.Env = append(os.Environ(), "FOSSIL_USER=jan")
		if out, err := cmd.CombinedOutput(); err != nil {
			t.Fatalf("FAIL: bare %s %v: %v\n%s", tool, args, err, out)
		}
	}

	work, dir := clone()
	bare(dir, "zit", "pull")
	if err := os.WriteFile(filepath.Join(dir, "new.txt"), []byte("hello\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	bare(dir, "zit", "add", "new.txt")
	bare(dir, "zit", "commit", "-m", "from a clone")
	bare(dir, "zit", "push")
	noTokenOnDisk(work)

	// While fossil clones, no process on the machine has the token in its
	// arguments (a poll of ps can miss one; it cannot invent one).
	stop, polled := make(chan struct{}), make(chan int, 1)
	go func() {
		n := 0
		for {
			select {
			case <-stop:
				polled <- n
				return
			default:
			}
			if out, err := exec.Command("ps", "-Ao", "args").Output(); err == nil && bytes.Contains(out, []byte(token)) {
				t.Errorf("FAIL: the token is on a command line")
				polled <- n
				return
			}
			n++
		}
	}()
	tapMu.Lock()
	tapping = true
	tapMu.Unlock()
	work, dir = clone("--fossil")
	tapMu.Lock()
	tapping = false
	tapMu.Unlock()
	close(stop)
	<-polled
	// What a real clone sends is exactly what the proxy allows: nothing
	// more (or the clone could not have worked), and nothing it never
	// sends (or the list has grown past what was found).
	var sent []string
	for c := range tapped {
		sent = append(sent, c)
	}
	sort.Strings(sent)
	if got, want := strings.Join(sent, " "), strings.Join(pickupclient.CloneCards(), " "); got != want {
		t.Errorf("FAIL: a real fossil clone sent the cards [%s]; the proxy allows [%s]", got, want)
	}
	bare(dir, "fossil", "sync")
	noTokenOnDisk(work) // fossil keeps the password obscured, not as the token
	bare(dir, "fossil", "pull")
	if err := os.WriteFile(filepath.Join(dir, "more.txt"), []byte("hello\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	bare(dir, "fossil", "add", "more.txt")
	bare(dir, "fossil", "commit", "-m", "from a fossil clone", "--no-warnings")
	bare(dir, "fossil", "push")
	noTokenOnDisk(work)

	// setup-zit in a real fossil checkout whose saved password is gone:
	// a bare pull is refused until it runs, and works after.
	vout, _ := exec.Command("fossil", "version").Output()
	t.Logf("fossil: %s", strings.TrimSpace(string(vout)))
	cmd := exec.Command("fossil", "sql", "DELETE FROM config WHERE name='last-sync-pw'")
	cmd.Dir = dir
	if out, err := cmd.CombinedOutput(); err != nil {
		t.Fatalf("FAIL: clearing the password: %v\n%s", err, out)
	}
	pull := exec.Command("fossil", "pull")
	pull.Dir = dir
	if out, err := pull.CombinedOutput(); err == nil {
		t.Fatalf("FAIL: a pull with no saved password was answered\n%s", out)
	}
	var sout, serr bytes.Buffer
	se := &pickupclient.Env{Client: &http.Client{}, Stdout: &sout, Stderr: &serr, ConfigDir: t.TempDir(),
		Keys:   memStore{u.Host: {Host: u.Host, Account: "jan", Token: token}},
		Getenv: func(string) string { return "" }, Getwd: func() (string, error) { return dir, nil }}
	if code := pickupclient.SetupZit(context.Background(), []string{"--host", srv.URL, "--json"}, se); code != 0 {
		t.Fatalf("FAIL: setup-zit in a fossil checkout: exit %d out %q err %q", code, sout.String(), serr.String())
	}
	bare(dir, "fossil", "pull")
	noTokenOnDisk(work)
	if !t.Failed() {
		t.Log("ok: zit and fossil clones pull and push with no password")
	}
}