package runner
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
// loginCheckout is a checkout that can fetch as a task's login, and
// records every credential it was used with.
type loginCheckout struct {
fakeCheckout
mu sync.Mutex
used []string // "user:password" of each checkout made as a login
plain int // checkouts made with the runner's own credentials
// fail makes the first n checkouts as a login fail, naming the
// password in the error as a careless checkout might.
fail int
// order records "checkout" for every checkout, with the bridge's asked list
// at that moment, to show the login was asked for first.
seen func() []string
at [][]string
}
func (l *loginCheckout) Checkout(ctx context.Context, dir, checkin string) error {
l.mu.Lock()
l.plain++
l.mu.Unlock()
return l.fakeCheckout.Checkout(ctx, dir, checkin)
}
func (l *loginCheckout) As(user, password string) Checkout { return loginAs{l, user, password} }
type loginAs struct {
l *loginCheckout
user, password string
}
func (a loginAs) Checkout(ctx context.Context, dir, checkin string) error {
a.l.mu.Lock()
a.l.used = append(a.l.used, a.user+":"+a.password)
failing := len(a.l.used) <= a.l.fail
if a.l.seen != nil {
a.l.at = append(a.l.at, a.l.seen())
}
a.l.mu.Unlock()
if failing {
return errors.New("clone as " + a.user + " with " + a.password + " failed")
}
return a.l.fakeCheckout.Checkout(ctx, dir, checkin)
}
func loginRunner(t *testing.T, srv *httptest.Server, co Checkout) *Runner {
t.Helper()
r, err := New(Config{
Bridge: srv.URL, Token: "WT", Tasks: []string{"t"},
WorkDir: t.TempDir(), Checkout: co, Logf: t.Logf,
CheckoutRetry: []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond},
})
if err != nil {
t.Fatal(err)
}
return r
}
// A TASK'S CHECKOUT USES THE LOGIN THE FORGE MINTED FOR IT, ASKED FOR
// FIRST, AND THE LOGIN GOES TO NO ONE ELSE: not the job's environment,
// not the log, not the error a failed checkout reports.
func TestATaskChecksOutWithTheLoginTheForgeMintedForIt(t *testing.T) {
envFile := filepath.Join(t.TempDir(), "env")
manifest := `{"tasks":{"t":["sh","-c","env > ` + envFile + `"]}}`
b := &fakeBridge{resolved: map[string]map[string]any{}, logs: map[string]string{}}
b.checkout = func(string) (string, string, int) { return "run-abc", "qrt_abc_SECRETVALUE", 200 }
srv := httptest.NewServer(b.handler())
defer srv.Close()
co := &loginCheckout{fakeCheckout: fakeCheckout{map[string]string{"c1": manifest}}, fail: 1}
co.seen = func() []string { b.mu.Lock(); defer b.mu.Unlock(); return append([]string(nil), b.asked...) }
r := loginRunner(t, srv, co)
var log strings.Builder
if err := r.execute(context.Background(), "task1", "t", "c1", "", "", nil, &log, &log); err != nil {
t.Fatalf("FAIL: a checkout that failed once, then worked, failed the task: %v", err)
}
if len(co.used) != 2 || co.used[1] != "run-abc:qrt_abc_SECRETVALUE" || co.plain != 0 {
t.Errorf("FAIL: checkouts made as %v, %d with the runner's own; want two, as the login", co.used, co.plain)
}
for i, at := range co.at {
if len(at) <= i {
t.Errorf("FAIL: checkout %d was made after %v logins were asked for; want one asked first each time", i+1, at)
}
}
if strings.Contains(log.String(), "SECRETVALUE") {
t.Errorf("FAIL: the task's log carries the login's token:\n%s", log.String())
}
if env, _ := os.ReadFile(envFile); strings.Contains(string(env), "SECRETVALUE") || strings.Contains(string(env), "run-abc") {
t.Errorf("FAIL: the job's environment carries the checkout login:\n%s", env)
}
// The failure that never works reports without the token too.
co2 := &loginCheckout{fakeCheckout: fakeCheckout{map[string]string{"c1": manifest}}, fail: 99}
err := loginRunner(t, srv, co2).execute(context.Background(), "task2", "t", "c1", "", "", nil, io.Discard, io.Discard)
if err == nil || strings.Contains(err.Error(), "SECRETVALUE") {
t.Errorf("FAIL: a checkout that never works reported %v; want a failure naming no token", err)
}
if !t.Failed() {
t.Log("ok")
}
}
// AN OLDER FORGE HAS NO ROUTE: THE RUNNER'S OWN CREDENTIALS DO THE
// CHECKOUT, as they always did. A forge that refuses the task, or one
// the runner no longer holds, fails the checkout and never falls back.
func TestWithoutACheckoutLoginTheRunnersOwnCredentialsDoIt(t *testing.T) {
manifest := `{"tasks":{"t":["true"]}}`
run := func(b *fakeBridge, co *loginCheckout) error {
srv := httptest.NewServer(b.handler())
defer srv.Close()
return loginRunner(t, srv, co).execute(context.Background(), "task1", "t", "c1", "", "", nil, io.Discard, io.Discard)
}
newBridge := func() *fakeBridge {
return &fakeBridge{resolved: map[string]map[string]any{}, logs: map[string]string{}}
}
co := &loginCheckout{fakeCheckout: fakeCheckout{map[string]string{"c1": manifest}}}
if err := run(newBridge(), co); err != nil || co.plain != 1 || len(co.used) != 0 {
t.Errorf("FAIL: against a forge with no route: %v, %d own checkouts, %v as a login; want one own checkout", err, co.plain, co.used)
}
{
name := "a task the runner does not hold"
b := newBridge()
b.checkout = func(string) (string, string, int) { return "", "", http.StatusForbidden }
co := &loginCheckout{fakeCheckout: fakeCheckout{map[string]string{"c1": manifest}}}
err := run(b, co)
if err == nil || co.plain != 0 || len(co.used) != 0 {
t.Errorf("FAIL: %s: %v, %d own checkouts, %v as a login; want a failure and no checkout at all", name, err, co.plain, co.used)
}
if len(b.asked) != 1 {
t.Errorf("FAIL: %s: the login was asked for %d times; a refusal is not retried", name, len(b.asked))
}
}
// A forge that errs is retried like any checkout failure.
b := newBridge()
var calls int
b.checkout = func(string) (string, string, int) {
calls++
if calls == 1 {
return "", "", http.StatusBadGateway
}
return "run-abc", "qrt_abc_t", 200
}
co = &loginCheckout{fakeCheckout: fakeCheckout{map[string]string{"c1": manifest}}}
if err := run(b, co); err != nil || len(co.used) != 1 {
t.Errorf("FAIL: a login route that failed once, then answered: %v, checkouts as a login %v; want one", err, co.used)
}
// A checkout that cannot be a login (the fake ones) is used as it is.
b = newBridge()
b.checkout = func(string) (string, string, int) { return "run-abc", "qrt_abc_t", 200 }
srv := httptest.NewServer(b.handler())
defer srv.Close()
plain := &flakyCheckout{inner: fakeCheckout{map[string]string{"c1": manifest}}}
if err := loginRunner(t, srv, plain).execute(context.Background(), "task1", "t", "c1", "", "", nil, io.Discard, io.Discard); err != nil || plain.calls != 1 {
t.Errorf("FAIL: a checkout with no login of its own: %v after %d calls; want one", err, plain.calls)
}
if !t.Failed() {
t.Log("ok")
}
}
// AS A LOGIN, THE ARCHIVE CHECKOUT SENDS THE LOGIN AND NOT THE
// RUNNER'S OWN ACCOUNT.
func TestAnArchiveCheckoutAsALoginSendsTheLogin(t *testing.T) {
var gotUser, gotPass string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotUser, gotPass, _ = r.BasicAuth()
http.Error(w, "stop here", http.StatusNotFound)
}))
defer srv.Close()
own := ArchiveCheckout{URL: srv.URL + "/r/demo", User: "account", Password: "its-sync-token"}
var co Checkout = own
lo, ok := co.(LoginCheckout)
if !ok {
t.Fatal("FAIL: the archive checkout cannot be a login")
}
lo.As("run-abc", "qrt_abc_t").Checkout(context.Background(), filepath.Join(t.TempDir(), "ws"), "trunk")
if gotUser != "run-abc" || gotPass != "qrt_abc_t" {
t.Errorf("FAIL: the archive was fetched as %q:%q; want the login", gotUser, gotPass)
}
if own.User != "account" || own.Password != "its-sync-token" {
t.Errorf("FAIL: becoming a login changed the runner's own checkout: %+v", own)
}
}
// AS A LOGIN, ZIT IS HANDED THE TOKEN IN ITS ENVIRONMENT ALONE, AND
// SAVES NEITHER THE LOGIN NOR THE REMOTE: a workspace is left holding
// no credential, a reused one is cleared of a saved one.
func TestAZitCheckoutAsALoginSavesNoLogin(t *testing.T) {
seen := filepath.Join(t.TempDir(), "seen")
zit := filepath.Join(t.TempDir(), "zit")
script := "#!/bin/sh\nprintf '%s|%s\\n' \"$ZIT_PASSWORD\" \"$*\" >> " + seen + "\ncase \"$1\" in\nclone) : > .zit ;;\nupdate) [ -f .zit ] || exit 1 ;;\nesac\n"
if err := os.WriteFile(zit, []byte(script), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("ZIT_PASSWORD", "")
dir := filepath.Join(t.TempDir(), "ws")
co := ZitCheckout{Zit: zit, URL: "https://forge.example/r/demo", User: "account", Password: "its-sync-token"}.As("run-abc", "qrt_abc_t")
for i := 0; i < 2; i++ { // the clone, then the refresh of the workspace it left
if err := co.Checkout(context.Background(), dir, strings.Repeat("a", 64)); err != nil {
t.Fatalf("FAIL: checkout %d: %v", i+1, err)
}
}
b, _ := os.ReadFile(seen)
lines := strings.Split(strings.TrimSpace(string(b)), "\n")
var cleared bool
for _, l := range lines {
pw, args, _ := strings.Cut(l, "|")
fields := strings.Fields(args)
switch fields[0] {
case "clone", "pull":
if pw != "qrt_abc_t" || !strings.Contains(args, "--user run-abc") || !strings.Contains(args, "--once") || strings.Contains(args, "account") || strings.Contains(args, "qrt_") {
t.Errorf("FAIL: %q; want the login's name, --once, the token in ZIT_PASSWORD alone, and not the account", l)
}
case "remote":
cleared = cleared || strings.Contains(args, "--unset")
}
if strings.Contains(pw, "its-sync-token") {
t.Errorf("FAIL: %q handed the runner's own token to a checkout made as a login", l)
}
}
if !cleared {
t.Errorf("FAIL: a reused workspace's saved login was not cleared; zit saw:\n%s", b)
}
}