package api
import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
"craftdesign.group/quarry/internal/zitcli"
)
// A RUNNER'S TASK GETS A READ-ONLY CHECKOUT TOKEN FOR ITS OWN RUN'S
// REPOSITORY, whatever the task is and whatever branch it is on, and
// nothing else: not for a run the forge has no record of, not for
// another repository's, not once the run is over.
func TestATaskIsDeliveredAReadOnlyCheckoutToken(t *testing.T) {
wait := runStartWait
runStartWait = 20 * time.Millisecond
t.Cleanup(func() { runStartWait = wait })
db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
db.SyncProjectCode = func(repo string) (string, bool) { return "CODE-" + repo, true }
for _, name := range []string{"test", "other"} {
if err := db.AddRepo(name, filepath.Join(t.TempDir(), name), "", "private"); err != nil {
t.Fatal(err)
}
}
for _, id := range []string{"manifest", "jobrun", "pair", "slow", "done"} {
checkin := "c"
if id == "pair" {
checkin = "pair:a:b"
}
if err := db.AddCIRun(oltp.CIRun{RunID: id, Repo: "test", Checkin: checkin, Workflow: "w", Pipeline: "p", Status: "running"}); err != nil {
t.Fatal(err)
}
}
if err := db.RecordCIRunStart("jobrun", "push", "", map[string]oltp.RunJobGrant{"build": {Letters: "iy", Timeout: 10}}); err != nil {
t.Fatal(err)
}
if err := db.RecordCIRunStart("slow", "push", "", map[string]oltp.RunJobGrant{"build": {Timeout: 24 * 60}}); err != nil {
t.Fatal(err)
}
if err := db.CompleteCIRun("done", "succeeded", ""); err != nil {
t.Fatal(err)
}
d := Deps{Secrets: db}
for _, task := range []string{"manifest.test", "jobrun.build", "pair.merge", "slow.build"} {
got, err := d.DeliverCheckoutToken("test", task)
if err != nil || !strings.HasPrefix(got.User, "run-") || !strings.HasPrefix(got.Token, "qrt_") {
t.Fatalf("FAIL: %s got %+v, %v; want a run login and token", task, got, err)
}
tok, ok := db.ResolveToken(got.User, got.Token, oltp.ScopeSync)
if !ok || strings.Join(tok.Scopes, ",") != oltp.ScopeSync || !tok.Reaches("test") || tok.Reaches("other") {
t.Errorf("FAIL: %s: the token is %+v (live %v); want sync alone, on test alone", task, tok, ok)
}
if _, ok := db.ResolveToken(got.User, got.Token, oltp.ScopeAPI); ok {
t.Errorf("FAIL: %s: the checkout token opened the API door", task)
}
if strings.ContainsAny(tok.Ceiling, "iy") {
t.Errorf("FAIL: %s: the checkout token carries %q, a write letter", task, tok.Ceiling)
}
exp, err := time.Parse(time.RFC3339, got.Expires)
if err != nil || time.Until(exp) > oltp.RunTokenMaxLife {
t.Errorf("FAIL: %s: expires %q, %v; want within %s", task, got.Expires, err, oltp.RunTokenMaxLife)
}
if task == "jobrun.build" && time.Until(exp) > 10*time.Minute {
t.Errorf("FAIL: a job with a 10 minute timeout was given a token that lives %s", time.Until(exp))
}
}
// A retried checkout replaces the first token.
first, _ := d.DeliverCheckoutToken("test", "manifest.test")
second, err := d.DeliverCheckoutToken("test", "manifest.test")
if err != nil {
t.Fatal(err)
}
if _, ok := db.ResolveToken(first.User, first.Token, oltp.ScopeSync); ok {
t.Errorf("FAIL: a retried checkout left the first token live")
}
if _, ok := db.ResolveToken(second.User, second.Token, oltp.ScopeSync); !ok {
t.Errorf("FAIL: the retried checkout's token is not live")
}
// The task's end revokes it, by the task id alone.
if err := d.TaskEnded("test", "manifest.test"); err != nil {
t.Fatal(err)
}
if _, ok := db.ResolveToken(second.User, second.Token, oltp.ScopeSync); ok {
t.Errorf("FAIL: the checkout token outlived its task")
}
for name, c := range map[string][2]string{
"another repository's run": {"other", "manifest.test"},
"a run nobody recorded": {"test", "forged.test"},
"a run that is over": {"test", "done.test"},
"a task that is no task": {"test", "nodot"},
"a task with no job": {"test", "manifest."},
} {
if got, err := d.DeliverCheckoutToken(c[0], c[1]); !errors.Is(err, ErrSecretRefused) || got.Token != "" {
t.Errorf("FAIL: %s got %+v, %v; want a refusal and no token", name, got, err)
}
}
if _, err := (Deps{}).DeliverCheckoutToken("test", "manifest.test"); err == nil {
t.Errorf("FAIL: a forge with no run records delivered a token")
}
if !t.Failed() {
t.Log("ok")
}
}
// ci.run.tokens LISTS A CHECKOUT TOKEN AS A CHECKOUT FOR ITS JOB, never
// as a job of its own, beside the job's own run token.
func TestARunsTokenListShowsCheckoutsAsCheckouts(t *testing.T) {
db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
db.SyncProjectCode = func(repo string) (string, bool) { return "CODE-" + repo, true }
if err := db.AddRepo("test", filepath.Join(t.TempDir(), "test"), "", "private"); err != nil {
t.Fatal(err)
}
if err := db.AddCIRun(oltp.CIRun{RunID: "run1", Repo: "test", Checkin: "c", Workflow: "w", Pipeline: "p", Status: "running"}); err != nil {
t.Fatal(err)
}
d := Deps{Secrets: db, Repos: NewRepos(map[string]*Repo{"test": {Chat: "test"}})}
if _, err := d.DeliverCheckoutToken("test", "run1.build"); err != nil {
t.Fatal(err)
}
if _, _, _, err := db.MintRunToken(oltp.RunTokenSpec{Run: "run1", Repo: "test", Job: "build", Letters: "go", Expires: time.Now().Add(time.Hour)}); err != nil {
t.Fatal(err)
}
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
out, err := r.Invoke(context.Background(), "ci.run.tokens", ciRunTokensIn{Repo: "test", RunID: "run1"})
if err != nil {
t.Fatal(err)
}
got := map[string]string{} // kind -> job
for _, l := range out.(ciRunTokensOut).Tokens {
got[l.Kind] = l.Job
}
if len(out.(ciRunTokensOut).Tokens) != 2 || got["checkout"] != "build" || got["job"] != "build" {
t.Errorf("FAIL: the tokens are %+v; want a checkout for build and the job build's own", out.(ciRunTokensOut).Tokens)
}
}
// THE TASK TYPES A RUNNER STARTS WITH ARE THE ONES TRUNK'S
// ci/runner.json NAMES, read by the forge from its own store.
func TestTrunkTasksAreReadFromTheForgesOwnStore(t *testing.T) {
if _, err := exec.LookPath("zit"); err != nil {
t.Skip("zit not on PATH")
}
store := func(manifest string) *Repo {
dir := t.TempDir()
run := func(args ...string) {
t.Helper()
cmd := exec.Command("zit", args...)
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("zit %v: %v\n%s", args, err, out)
}
}
run("init", ".")
if err := os.WriteFile(filepath.Join(dir, "README"), []byte("x\n"), 0o644); err != nil {
t.Fatal(err)
}
run("add", "README")
if manifest != "" {
if err := os.MkdirAll(filepath.Join(dir, "ci"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "ci/runner.json"), []byte(manifest), 0o644); err != nil {
t.Fatal(err)
}
run("add", "ci/runner.json")
}
run("commit", "-m", "c", "--user", "u")
return &Repo{Chat: "r", Zit: zitcli.New(dir)}
}
d := Deps{Repos: NewRepos(map[string]*Repo{
"named": store(`{"tasks":{"test":["true"],"lint":{"argv":["true"]}}}`),
"none": store(""),
"broken": store(`{"tasks":`),
"nothing": store(`{"tasks":{}}`),
})}
got, err := d.DeliverTrunkTasks("named")
if err != nil || len(got) != 2 || got[0] != "lint" || got[1] != "test" {
t.Errorf("FAIL: a manifest naming two tasks gave %v, %v; want them sorted", got, err)
}
if got, err := d.DeliverTrunkTasks("none"); err != nil || len(got) != 0 {
t.Errorf("FAIL: a trunk with no manifest gave %v, %v; want none and no error", got, err)
}
for _, repo := range []string{"broken", "nothing"} {
if _, err := d.DeliverTrunkTasks(repo); !errors.Is(err, ErrSecretRefused) {
t.Errorf("FAIL: %s: an unusable manifest gave %v; want a refusal", repo, err)
}
}
if _, err := d.DeliverTrunkTasks("absent"); err == nil {
t.Errorf("FAIL: a repository the forge does not serve gave names")
}
}