package runnerdist
import (
"crypto/sha256"
"encoding/hex"
"encoding/pem"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
)
// fakeForge serves a fake client build for this machine's platform, with
// SHA256SUMS, over TLS; corrupt serves bytes that do not match the sums.
func fakeForge(t *testing.T, corrupt bool) (srv *httptest.Server, caFile string) {
t.Helper()
dir := t.TempDir()
runnerName := "quarry-runner-" + runtime.GOOS + "-" + runtime.GOARCH
build := []byte("#!/bin/sh\necho \"$QUARRY_TEST_LOG\" \"$@\" > \"$QUARRY_TEST_LOG\"\necho fake-quarry \"$@\"\n")
sum := sha256.Sum256(build)
if err := os.WriteFile(filepath.Join(dir, runnerName), build, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, SumsFile), []byte(hex.EncodeToString(sum[:])+" "+runnerName+"\n"), 0o644); err != nil {
t.Fatal(err)
}
if corrupt {
os.WriteFile(filepath.Join(dir, runnerName), append(build, "tampered\n"...), 0o755)
}
var h http.Handler
srv = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.ServeHTTP(w, r) }))
t.Cleanup(srv.Close)
h = CLIHandler(dir, srv.URL)
ca := filepath.Join(t.TempDir(), "ca.pem")
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw})
if err := os.WriteFile(ca, pemBytes, 0o600); err != nil {
t.Fatal(err)
}
return srv, ca
}
// shells are the interpreters the installer is run under.
var shells = []string{"sh", "dash"}
func runInstaller(t *testing.T, srv *httptest.Server, ca string, extraEnv ...string) (out string, err error, home, bin, log string) {
t.Helper()
resp, gerr := srv.Client().Get(srv.URL + "/install.sh")
if gerr != nil {
t.Fatal(gerr)
}
script, _ := io.ReadAll(resp.Body)
resp.Body.Close()
home = t.TempDir()
bin = filepath.Join(home, "bin")
log = filepath.Join(home, "ran.log")
shell := "sh"
for _, e := range extraEnv {
if v, ok := strings.CutPrefix(e, "TEST_SHELL="); ok {
shell = v
}
}
cmd := exec.Command(shell, "-s")
cmd.Stdin = strings.NewReader(string(script))
cmd.Env = append([]string{
"HOME=" + home, "PATH=" + os.Getenv("PATH"), "TMPDIR=" + home,
"QUARRY_INSTALL_DIR=" + bin, "CURL_CA_BUNDLE=" + ca, "SSL_CERT_FILE=" + ca,
"QUARRY_TEST_LOG=" + log,
}, extraEnv...)
b, err := cmd.CombinedOutput()
return string(b), err, home, bin, log
}
func TestInstallScriptInstallsRecordsTheHostAndRunsVersion(t *testing.T) {
for _, shell := range shells {
t.Run(shell, func(t *testing.T) { installsOK(t, shell) })
}
}
func installsOK(t *testing.T, shell string) {
if _, err := exec.LookPath(shell); err != nil {
t.Skip(shell + " is not installed")
}
srv, ca := fakeForge(t, false)
out, err, home, bin, log := runInstaller(t, srv, ca, "TEST_SHELL="+shell)
if err != nil {
t.Fatalf("FAIL: installer: %v\n%s", err, out)
}
if st, err := os.Stat(filepath.Join(bin, "quarry")); err != nil || st.Mode().Perm()&0o100 == 0 {
t.Errorf("FAIL: no executable quarry in %s: %v", bin, err)
}
if entries, _ := os.ReadDir(bin); len(entries) != 1 {
t.Errorf("FAIL: %d entries in the install dir, want only quarry", len(entries))
}
cfg, err := os.ReadFile(filepath.Join(home, ".config", "quarry", "config.json"))
if err != nil || !strings.Contains(string(cfg), `"host":"`+srv.URL+`"`) {
t.Errorf("FAIL: config records %q (%v), want host %s", cfg, err, srv.URL)
}
if st, err := os.Stat(filepath.Join(home, ".config", "quarry")); err != nil || st.Mode().Perm() != 0o700 {
t.Errorf("FAIL: config dir mode %v (%v), want 0700", st.Mode().Perm(), err)
}
if st, err := os.Stat(filepath.Join(home, ".config", "quarry", "config.json")); err != nil || st.Mode().Perm() != 0o600 {
t.Errorf("FAIL: config file mode %v (%v), want 0600", st.Mode().Perm(), err)
}
if b, err := os.ReadFile(log); err != nil || !strings.Contains(string(b), "version") {
t.Errorf("FAIL: the installer did not run quarry version: %q %v", b, err)
}
if !strings.Contains(out, "export PATH") {
t.Errorf("FAIL: an install dir off PATH was not said")
}
left, _ := filepath.Glob(filepath.Join(home, "quarry-install.*"))
if len(left) != 0 {
t.Errorf("FAIL: scratch left behind: %v", left)
}
for _, f := range []string{".profile", ".bashrc", ".zshrc", ".bash_profile"} {
if _, err := os.Stat(filepath.Join(home, f)); err == nil {
t.Errorf("FAIL: the installer wrote %s", f)
}
}
if !t.Failed() {
t.Log("ok")
}
}
func TestInstallScriptRefusesACorruptedDownloadAndInstallsNothing(t *testing.T) {
for _, shell := range shells {
t.Run(shell, func(t *testing.T) {
if _, err := exec.LookPath(shell); err != nil {
t.Skip(shell + " is not installed")
}
srv, ca := fakeForge(t, true)
out, err, home, bin, _ := runInstaller(t, srv, ca, "TEST_SHELL="+shell)
if err == nil {
t.Errorf("FAIL: a corrupted download was accepted:\n%s", out)
}
if _, serr := os.Stat(filepath.Join(bin, "quarry")); serr == nil {
t.Errorf("FAIL: quarry was installed from a corrupted download")
}
if _, serr := os.Stat(filepath.Join(home, ".config", "quarry", "config.json")); serr == nil {
t.Errorf("FAIL: a host was recorded for a failed install")
}
if entries, _ := os.ReadDir(bin); len(entries) != 0 {
t.Errorf("FAIL: %d files in the install dir after a refusal", len(entries))
}
if !t.Failed() {
t.Log("ok")
}
})
}
}
// Where quarry would go is a directory or a device, not a file: the
// installer says so and puts nothing there, writes no host, leaves no
// staging file.
func TestInstallScriptRefusesToReplaceWhatIsNotAFile(t *testing.T) {
for _, shell := range shells {
t.Run(shell, func(t *testing.T) {
if _, err := exec.LookPath(shell); err != nil {
t.Skip(shell + " is not installed")
}
srv, ca := fakeForge(t, false)
home := t.TempDir()
bin := filepath.Join(home, "inst")
if err := os.MkdirAll(filepath.Join(bin, "quarry"), 0o755); err != nil {
t.Fatal(err)
}
script, _ := io.ReadAll(func() io.Reader {
r, _ := srv.Client().Get(srv.URL + "/install.sh")
return r.Body
}())
cmd := exec.Command(shell, "-s")
cmd.Stdin = strings.NewReader(string(script))
cmd.Env = []string{"HOME=" + home, "PATH=" + os.Getenv("PATH"), "TMPDIR=" + home,
"QUARRY_INSTALL_DIR=" + bin, "CURL_CA_BUNDLE=" + ca, "SSL_CERT_FILE=" + ca}
out, err := cmd.CombinedOutput()
if err == nil || !strings.Contains(string(out), filepath.Join(bin, "quarry")) {
t.Errorf("FAIL: a directory in the way was not refused by name: %v\n%s", err, out)
}
entries, _ := os.ReadDir(bin)
if len(entries) != 1 {
t.Errorf("FAIL: %d entries in the install dir after a refusal, want the directory alone", len(entries))
}
if _, serr := os.Stat(filepath.Join(home, ".config", "quarry", "config.json")); serr == nil {
t.Errorf("FAIL: a host was recorded for a refused install")
}
if !t.Failed() {
t.Log("ok")
}
})
}
}
// A plain-http forge is refused by the installer: it speaks TLS only.
func TestInstallScriptWillNotDownloadOverPlainHTTP(t *testing.T) {
dir := t.TempDir()
srv := httptest.NewServer(CLIHandler(dir, "http://example.test"))
defer srv.Close()
resp, err := http.Get(srv.URL + "/install.sh")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("FAIL: an installer was served for a forge with no https origin: %d", resp.StatusCode)
}
if !t.Failed() {
t.Log("ok")
}
}
func TestCLIServesTheRunnerBytesUnderBothNames(t *testing.T) {
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "quarry-runner-linux-amd64"), []byte("ELF"), 0o755)
os.WriteFile(filepath.Join(dir, SumsFile), []byte("abc quarry-runner-linux-amd64\n"), 0o644)
os.WriteFile(filepath.Join(dir, "secret.env"), []byte("x"), 0o600)
srv := httptest.NewServer(CLIHandler(dir, ""))
defer srv.Close()
get := func(p string) (int, string) {
resp, err := http.Get(srv.URL + p)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, string(b)
}
for _, p := range []string{"/cli/quarry-linux-amd64", "/cli/quarry-runner-linux-amd64"} {
if code, body := get(p); code != 200 || body != "ELF" {
t.Errorf("FAIL: GET %s = %d %q", p, code, body)
}
}
code, sums := get("/cli/SHA256SUMS")
if code != 200 || !strings.Contains(sums, "abc quarry-linux-amd64\n") || !strings.Contains(sums, "abc quarry-runner-linux-amd64\n") {
t.Errorf("FAIL: sums %d %q do not list both names", code, sums)
}
for _, p := range []string{"/cli/secret.env", "/cli/quarry-darwin-arm64", "/cli/..%2Fsecret.env", "/cli/quarry-plan9-386"} {
if code, _ := get(p); code != 404 {
t.Errorf("FAIL: GET %s = %d, want 404", p, code)
}
}
if !t.Failed() {
t.Log("ok")
}
}
func TestEveryPlatformNamesAServableClientFile(t *testing.T) {
for _, p := range Platforms {
if !cliName.MatchString(p.CLIFile()) {
t.Errorf("FAIL: %s/%s builds %q, which the handler would refuse", p.OS, p.Arch, p.CLIFile())
}
}
if !t.Failed() {
t.Log("ok")
}
}
// installOver runs the installer with seed already at <dir>/quarry and
// says whether the run failed and whether the seed was replaced.
func installOver(t *testing.T, shell, seed string, extraEnv ...string) (out string, failed, replaced bool) {
t.Helper()
srv, ca := fakeForge(t, false)
resp, err := srv.Client().Get(srv.URL + "/install.sh")
if err != nil {
t.Fatal(err)
}
script, _ := io.ReadAll(resp.Body)
resp.Body.Close()
home := t.TempDir()
bin := filepath.Join(home, "inst")
if err := os.MkdirAll(bin, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(bin, "quarry"), []byte(seed), 0o755); err != nil {
t.Fatal(err)
}
cmd := exec.Command(shell, "-s")
cmd.Stdin = strings.NewReader(string(script))
cmd.Env = append([]string{"HOME=" + home, "PATH=" + os.Getenv("PATH"), "TMPDIR=" + home,
"QUARRY_INSTALL_DIR=" + bin, "CURL_CA_BUNDLE=" + ca, "SSL_CERT_FILE=" + ca}, extraEnv...)
b, rerr := cmd.CombinedOutput()
got, _ := os.ReadFile(filepath.Join(bin, "quarry"))
return string(b), rerr != nil, string(got) != seed
}
// A quarry in the install directory that is not a client build is left
// alone unless QUARRY_INSTALL_FORCE=1; a client build is the update path.
func TestInstallScriptDoesNotOverwriteANonClientQuarry(t *testing.T) {
server := "#!/bin/sh\necho 'quarry 0.0.0-dev'\n"
client := "#!/bin/sh\necho 'quarry 0.0.1 (client)'\n"
broken := "#!/bin/sh\nexit 3\n"
for _, shell := range shells {
t.Run(shell, func(t *testing.T) {
if _, err := exec.LookPath(shell); err != nil {
t.Skip(shell + " is not installed")
}
for name, seed := range map[string]string{"server": server, "broken": broken} {
_, failed, replaced := installOver(t, shell, seed)
if !failed || replaced {
t.Errorf("FAIL: %s build: failed=%v replaced=%v, want a refusal and the file untouched", name, failed, replaced)
}
out, failed, replaced := installOver(t, shell, seed, "QUARRY_INSTALL_FORCE=1")
if failed || !replaced {
t.Errorf("FAIL: %s build with force: failed=%v replaced=%v\n%s", name, failed, replaced, out)
}
}
out, failed, replaced := installOver(t, shell, client)
if failed || !replaced {
t.Errorf("FAIL: client build: failed=%v replaced=%v\n%s", failed, replaced, out)
}
if !t.Failed() {
t.Log("ok")
}
})
}
}