Skip to content
quarry Artifact [6c4d36ffe9]
Login

Artifact [6c4d36ffe9]

Artifact 6c4d36ffe96eb99ae9b9be289b6adc6edeed9ece5732bc58029aad610fef4b59:


//go:build unix

package api

import (
	"bytes"
	"context"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io/fs"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"

	"craftdesign.group/quarry/internal/runner/install"
)

// e2eSys is the real file system under a temporary home, a user who is
// not root, and a launchctl that only records what it was asked.
type e2eSys struct {
	install.HostSystem
	home, exe string
	mu        sync.Mutex
	runs      []string
}

func (s *e2eSys) Geteuid() int                      { return 501 }
func (s *e2eSys) Hostname() (string, error)         { return "build-box", nil }
func (s *e2eSys) UserHome() (string, error)         { return s.home, nil }
func (s *e2eSys) Executable() (string, error)       { return s.exe, nil }
func (s *e2eSys) LookPath(n string) (string, error) { return "/usr/bin/" + n, nil }
func (s *e2eSys) Run(ctx context.Context, name string, args ...string) ([]byte, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.runs = append(s.runs, name+" "+strings.Join(args, " "))
	return nil, nil
}

type e2eForge struct {
	*runnerRig
	srv  *httptest.Server
	sys  *e2eSys
	env  install.Env
	out  *bytes.Buffer
	prog string
}

func newE2EForge(t *testing.T) *e2eForge {
	t.Helper()
	g := newRunnerRig(t)
	home := t.TempDir()
	if err := os.MkdirAll(filepath.Join(home, "Library", "Application Support"), 0o755); err != nil {
		t.Fatal(err)
	}
	exe := filepath.Join(t.TempDir(), "quarry-runner")
	if err := os.WriteFile(exe, []byte("PROGRAM-BYTES"), 0o755); err != nil {
		t.Fatal(err)
	}
	sum := sha256.Sum256([]byte("PROGRAM-BYTES"))
	mux := http.NewServeMux()
	mux.HandleFunc("GET /api/v1", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("{}")) })
	mux.HandleFunc("GET /runner/SHA256SUMS", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "%s  quarry-runner-darwin-arm64\n", hex.EncodeToString(sum[:]))
	})
	mux.Handle("POST /api/v1/setup/start", g.st)
	mux.Handle("POST /api/v1/pickups/collect", g.coll)
	mux.HandleFunc("POST /r/{repo}/ci/bridge/v1/workers/connect", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) })
	mux.Handle("/api/v1/", g.h)
	srv := httptest.NewServer(mux)
	t.Cleanup(srv.Close)
	f := &e2eForge{runnerRig: g, srv: srv, sys: &e2eSys{home: home, exe: exe}, out: &bytes.Buffer{}}
	f.env = install.Env{Sys: f.sys, HTTP: srv.Client(), Out: f.out, Getenv: func(string) string { return "" }, Version: "v-test", GOOS: "darwin",
		Trunk: func(context.Context, string) (bool, error) { return true, nil }, Poll: 15 * time.Millisecond, Wait: 20 * time.Second}
	return f
}

// tree is every path under the home, for "nothing is left" checks.
func (f *e2eForge) tree(t *testing.T) []string {
	t.Helper()
	var out []string
	filepath.WalkDir(f.sys.home, func(p string, d fs.DirEntry, err error) error {
		if err == nil && p != f.sys.home {
			rel, _ := filepath.Rel(f.sys.home, p)
			out = append(out, rel)
		}
		return nil
	})
	return out
}

// runInstall runs install in the background and answers the request it
// files (approve or deny) as the owner once it is waiting.
func (f *e2eForge) runInstall(t *testing.T, repo string, approve bool) error {
	t.Helper()
	done := make(chan error, 1)
	go func() {
		done <- install.Install(context.Background(), f.env, []string{f.srv.URL + "/r/" + repo})
	}()
	deadline := time.Now().Add(15 * time.Second)
	for time.Now().Before(deadline) {
		select {
		case err := <-done:
			return err
		default:
		}
		if w := f.waiting(t); len(w) > 0 {
			f.decide(t, w[0].ID, approve)
			break
		}
		time.Sleep(10 * time.Millisecond)
	}
	select {
	case err := <-done:
		return err
	case <-time.After(20 * time.Second):
		t.Fatalf("FAIL: the install did not finish")
		return nil
	}
}

// THE WHOLE FLOW AGAINST THE REAL OPS: install starts a runner request,
// the owner's inbox holds it, approving mints the token, the installer
// collects it, writes the 0600 token file, loads the agent and passes
// doctor. The token is in no command and no output.
func TestARunnerInstallsByOneApprovalEndToEnd(t *testing.T) {
	f := newE2EForge(t)
	if err := f.runInstall(t, "test", true); err != nil {
		t.Fatalf("FAIL: install: %v\n%s", err, f.out)
	}
	dir := filepath.Join(f.sys.home, "Library", "Application Support", "quarry-runner", "test")
	fi, err := os.Stat(filepath.Join(dir, "token"))
	if err != nil || fi.Mode().Perm() != 0o600 {
		t.Fatalf("FAIL: the token file: %v %v", fi, err)
	}
	tok, _ := os.ReadFile(filepath.Join(dir, "token"))
	if strings.TrimSpace(string(tok)) != "s3cret-bearer-value" {
		t.Errorf("FAIL: the token file does not hold the minted token")
	}
	if f.eng.mints != 1 {
		t.Errorf("FAIL: %d tokens minted, want 1", f.eng.mints)
	}
	var inbox bool
	for _, e := range f.attn.sent["jva"] {
		if e.Kind == "signoff" && e.Repo == "test" && isRunnerAsker(e.From) {
			inbox = true
		}
	}
	if !inbox {
		t.Errorf("FAIL: the owner's inbox never held the request")
	}
	boot := false
	for _, c := range f.sys.runs {
		if strings.Contains(c, "s3cret-bearer-value") {
			t.Errorf("FAIL: the token is in a command: %s", c)
		}
		if strings.HasPrefix(c, "launchctl bootstrap gui/501 ") {
			boot = true
		}
	}
	if !boot {
		t.Errorf("FAIL: the agent was not loaded: %v", f.sys.runs)
	}
	if strings.Contains(f.out.String(), "s3cret-bearer-value") {
		t.Errorf("FAIL: the token was printed")
	}
	if _, err := os.Stat(filepath.Join(dir, "pickup.key")); err == nil {
		t.Errorf("FAIL: the pickup key was left behind")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// DENIED, THE INSTALLER STOPS WITH A NON-ZERO EXIT AND NOTHING LEFT; A
// REPOSITORY THE CALLER CANNOT SEE IS REFUSED THE SAME WAY AS A MISSING
// ONE, AND FILES NOTHING.
func TestADeniedOrUnseeableRunnerRequestLeavesNothingBehind(t *testing.T) {
	f := newE2EForge(t)
	before := f.tree(t)
	if err := f.runInstall(t, "test", false); err == nil {
		t.Fatalf("FAIL: a denied request installed")
	}
	if got := f.tree(t); strings.Join(got, "\n") != strings.Join(before, "\n") {
		t.Errorf("FAIL: a denied install left %v (was %v)", got, before)
	}
	if f.eng.mints != 0 {
		t.Errorf("FAIL: %d tokens minted for a denied request", f.eng.mints)
	}
	for _, c := range f.sys.runs {
		if strings.HasPrefix(c, "launchctl bootstrap") {
			t.Errorf("FAIL: an agent was loaded: %s", c)
		}
	}
	for _, repo := range []string{"hidden", "no-such-repo"} {
		if err := f.runInstall(t, repo, true); err == nil {
			t.Errorf("FAIL: install for %s succeeded", repo)
		}
	}
	if n := len(f.waiting(t)); n != 0 {
		t.Errorf("FAIL: %d requests waiting after refused starts", n)
	}
	if got := f.tree(t); strings.Join(got, "\n") != strings.Join(before, "\n") {
		t.Errorf("FAIL: refused installs left %v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}