Skip to content
quarry Artifact [addb69ed08]
Login

Artifact [addb69ed08]

Artifact addb69ed084abdb8bd82acf3e7bb2573fc9d73f9f8dae61e8ed68873f4511e41:


package runner

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

// THE RUNNER READS ITS TOKEN FROM A FILE THAT ONLY ITS OWNER MAY READ
// (RFC 0030, Without root): a looser file is refused before it is read,
// and the value is in no error.
func TestTokenFileIsReadOnlyWhenPrivate(t *testing.T) {
	dir := t.TempDir()
	const secret = "wt-very-secret-value-1234"
	good := filepath.Join(dir, "token")
	if err := os.WriteFile(good, []byte(secret+"\n"), 0o600); err != nil {
		t.Fatal(err)
	}
	got, err := readTokenFile(good)
	if err != nil || got != secret {
		t.Errorf("FAIL: a 0600 file read as %q, %v", got, err)
	}
	for _, mode := range []os.FileMode{0o644, 0o640, 0o604, 0o660} {
		loose := filepath.Join(dir, "loose"+mode.String())
		if err := os.WriteFile(loose, []byte(secret), mode); err != nil {
			t.Fatal(err)
		}
		if err := os.Chmod(loose, mode); err != nil {
			t.Fatal(err)
		}
		v, err := readTokenFile(loose)
		if err == nil || v != "" {
			t.Errorf("FAIL: a %v file was read", mode)
		} else if strings.Contains(err.Error(), secret) {
			t.Errorf("FAIL: the refusal of a %v file carries the value", mode)
		}
	}
	link := filepath.Join(dir, "link")
	if err := os.Symlink(good, link); err != nil {
		t.Fatal(err)
	}
	if _, err := readTokenFile(link); err == nil {
		t.Errorf("FAIL: a link was followed")
	}
	empty := filepath.Join(dir, "empty")
	if err := os.WriteFile(empty, []byte("\n"), 0o600); err != nil {
		t.Fatal(err)
	}
	if _, err := readTokenFile(empty); err == nil {
		t.Errorf("FAIL: an empty file gave a token")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// With --token-file the environment is not consulted for the token, and
// a refused file stops the runner before it connects anywhere.
func TestMainRefusesALooseTokenFile(t *testing.T) {
	loose := filepath.Join(t.TempDir(), "token")
	const secret = "wt-another-secret-5678"
	if err := os.WriteFile(loose, []byte(secret), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.Chmod(loose, 0o644); err != nil {
		t.Fatal(err)
	}
	err := Main([]string{"--token-file", loose, "https://forge.example/r/dmestas/suit"}, "quarry-runner", "dev")
	if err == nil {
		t.Fatalf("FAIL: a 0644 token file started the runner")
	}
	if strings.Contains(err.Error(), secret) {
		t.Errorf("FAIL: the refusal carries the value")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}