Skip to content
quarry Artifact [bfcb55e688]
Login

Artifact [bfcb55e688]

Artifact bfcb55e688c5c1cccdb84da7b86c10c71ea7be8e96d345d79b5a68f2338b2b2a:


package api

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"path/filepath"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"craftdesign.group/quarry/internal/ci"
	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
)

type codeFixture struct {
	r    *ops.Registry
	eng  *workerEngine
	rec  *settingRecorder
	db   *oltp.DB
	now  time.Time
	lost map[string]bool
	// private hides every repository from a caller with no account.
	private bool
}

func newCodeFixture(t *testing.T) *codeFixture {
	t.Helper()
	f := &codeFixture{eng: &workerEngine{}, rec: &settingRecorder{}, now: time.Date(2026, 11, 18, 10, 0, 0, 0, time.UTC), lost: map[string]bool{}}
	db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { db.Close() })
	f.db = db
	for _, who := range []string{"dmestas", "jva", "eve"} {
		if err := db.AddAccount(who, "a-long-enough-password", who == "dmestas"); err != nil {
			t.Fatal(err)
		}
	}
	if err := db.AddAccount("jva-bot", "a-long-enough-password", false); err != nil {
		t.Fatal(err)
	}
	if err := db.SetOperator("jva-bot", "jva"); err != nil {
		t.Fatal(err)
	}
	caps := func(account, repo string) CapSet {
		if account == "eve" || f.lost[account] {
			return oltp.CapSet("3")
		}
		return oltp.CapSet("a")
	}
	f.r = ops.NewRegistry()
	if err := RegisterAll(f.r, Deps{Version: "v", WorkerTokens: f.eng, SettingLog: f.rec, RunnerCodes: db,
		CanRead:  func(ctx context.Context, _ string) bool { return !f.private || ops.User(ctx) != "" },
		Now:      func() time.Time { return f.now },
		Repos:    NewRepos(map[string]*Repo{"alpha": {Chat: "alpha", Index: wikiIndex(t)}, "beta": {Chat: "beta", Index: wikiIndex(t)}}),
		Accounts: adminAdapter{acctAdapter{db}}, SignOffs: testSignOffs{db}, CapsFor: caps, SecretBox: testBox(t)}); err != nil {
		t.Fatal(err)
	}
	return f
}

func (f *codeFixture) code(t *testing.T, who, repo string) string {
	t.Helper()
	out, err := f.r.Invoke(asUser(who), "ci.runner.code.new", runnerCodeNewIn{Repo: repo})
	if err != nil {
		t.Fatalf("FAIL: %s made no code: %v", who, err)
	}
	return out.(runnerCodeNewOut).Code
}

func (f *codeFixture) redeem(repo, code string) (runnerCodeRedeemOut, error) {
	ctx := ops.WithAddr(context.Background(), "203.0.113.9")
	out, err := f.r.Invoke(ctx, "ci.runner.code.redeem", runnerCodeRedeemIn{Repo: repo, Code: code, Host: "build-box", Label: "ci"})
	if err != nil {
		return runnerCodeRedeemOut{}, err
	}
	return out.(runnerCodeRedeemOut), nil
}

// A code redeems once, for one worker token scoped to its repository's
// group; a second redemption, a stale code and a wrong one all get the
// same 404.
func TestInstallCodeRedeemsOnceForAGroupScopedToken(t *testing.T) {
	f := newCodeFixture(t)
	code := f.code(t, "dmestas", "alpha")
	if !strings.HasPrefix(code, "qri_") {
		t.Errorf("FAIL: code %q lacks the qri_ prefix", code)
	}
	out, err := f.redeem("alpha", code)
	if err != nil {
		t.Fatalf("FAIL: redeeming: %v", err)
	}
	if out.Value != "s3cret-bearer-value" || out.Group != ci.GroupFor("alpha") {
		t.Errorf("FAIL: redeem answered %+v", out)
	}
	if len(f.eng.groups) != 1 || f.eng.groups[0] != ci.GroupFor("alpha") {
		t.Errorf("FAIL: token scoped to %v, want alpha's group only", f.eng.groups)
	}
	_, spent := f.redeem("alpha", code)
	f.now = f.now.Add(16 * time.Minute)
	stale := f.code(t, "dmestas", "alpha")
	f.now = f.now.Add(16 * time.Minute)
	_, lapsed := f.redeem("alpha", stale)
	_, wrong := f.redeem("alpha", "qri_nope")
	for name, err := range map[string]error{"spent": spent, "stale": lapsed, "wrong": wrong} {
		if !errors.Is(err, ops.ErrNotFound) {
			t.Errorf("FAIL: a %s code answered %v, want not found", name, err)
		}
	}
	if spent == nil || lapsed == nil || wrong == nil || spent.Error() != lapsed.Error() || spent.Error() != wrong.Error() {
		t.Errorf("FAIL: the refusals differ: %v | %v | %v", spent, lapsed, wrong)
	}
	if f.eng.mints != 1 {
		t.Errorf("FAIL: %d tokens minted, want 1", f.eng.mints)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A code for one repository does nothing on another.
func TestInstallCodeIsForItsOwnRepositoryOnly(t *testing.T) {
	f := newCodeFixture(t)
	code := f.code(t, "dmestas", "alpha")
	if _, err := f.redeem("beta", code); !errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: alpha's code on beta answered %v", err)
	}
	if f.eng.mints != 0 {
		t.Errorf("FAIL: a code minted on another repository")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Six bad codes close the window: the sixth and every later try fails,
// even with a good code.
func TestSixBadInstallCodesCloseRedemption(t *testing.T) {
	f := newCodeFixture(t)
	good := f.code(t, "dmestas", "alpha")
	for i := 0; i < 5; i++ {
		if _, err := f.redeem("alpha", "qri_bad"); !errors.Is(err, ops.ErrNotFound) {
			t.Fatalf("FAIL: bad code %d answered %v", i, err)
		}
	}
	_, err := f.redeem("alpha", good)
	if !errors.Is(err, ops.ErrNotFound) || f.eng.mints != 0 {
		t.Errorf("FAIL: a good code redeemed after five failures: %v (mints %d)", err, f.eng.mints)
	}
	f.now = f.now.Add(16 * time.Minute)
	fresh := f.code(t, "dmestas", "alpha")
	if _, err := f.redeem("alpha", fresh); err != nil {
		t.Errorf("FAIL: the window did not reopen after 15 minutes: %v", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// At most five live codes a repository; the sixth is refused plainly.
func TestInstallCodesAreCappedAtFive(t *testing.T) {
	f := newCodeFixture(t)
	for i := 0; i < 5; i++ {
		f.code(t, "dmestas", "alpha")
	}
	_, err := f.r.Invoke(asUser("dmestas"), "ci.runner.code.new", runnerCodeNewIn{Repo: "alpha"})
	if err == nil || errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: the sixth code answered %v", err)
	}
	if _, err := f.r.Invoke(asUser("dmestas"), "ci.runner.code.new", runnerCodeNewIn{Repo: "beta"}); err != nil {
		t.Errorf("FAIL: another repository was capped too: %v", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// An agent cannot make a code; a non-admin cannot either.
func TestInstallCodeIsRefusedToAnAgentAndANonAdmin(t *testing.T) {
	f := newCodeFixture(t)
	for _, who := range []string{"jva-bot", "eve"} {
		if _, err := f.r.Invoke(asUser(who), "ci.runner.code.new", runnerCodeNewIn{Repo: "alpha"}); !errors.Is(err, ops.ErrForbidden) {
			t.Errorf("FAIL: %s made a code: %v", who, err)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A maker who has lost the letter redeems nothing.
func TestInstallCodeDiesWithItsMakersLetter(t *testing.T) {
	f := newCodeFixture(t)
	code := f.code(t, "jva", "alpha")
	f.lost["jva"] = true
	if _, err := f.redeem("alpha", code); !errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: a code by a maker who lost the letter redeemed: %v", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The settings log names the making, the minting with its address, and
// the retire.
func TestInstallCodeLogsAndRetireRevokesOnlyItsHolder(t *testing.T) {
	f := newCodeFixture(t)
	// A token minted by hand beforehand must survive the retire.
	if _, err := f.r.Invoke(asUser("dmestas"), "ci.worker.token.new", workerTokenNewIn{Repo: "alpha", Label: "hand"}); err != nil {
		t.Fatal(err)
	}
	f.rec.rows = nil
	code := f.code(t, "dmestas", "alpha")
	out, err := f.redeem("alpha", code)
	if err != nil {
		t.Fatal(err)
	}
	if len(f.rec.rows) != 2 {
		t.Fatalf("FAIL: %d log rows, want 2: %+v", len(f.rec.rows), f.rec.rows)
	}
	made, minted := f.rec.rows[0], f.rec.rows[1]
	if made.actor != "dmestas" || made.field != "runner-code" {
		t.Errorf("FAIL: the making row is %+v", made)
	}
	if minted.actor != "dmestas" || !strings.Contains(minted.now, out.Token.ID) || !strings.Contains(minted.now, "203.0.113.9") ||
		!strings.Contains(minted.now, "build-box") {
		t.Errorf("FAIL: the minting row is %+v", minted)
	}
	if _, err := f.r.Invoke(context.Background(), "ci.worker.token.retire", workerTokenRetireIn{Repo: "alpha", Token: "not-a-token"}); !errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: a wrong token retired something: %v", err)
	}
	if len(f.eng.revoked) != 0 {
		t.Fatalf("FAIL: a wrong token revoked %v", f.eng.revoked)
	}
	if _, err := f.r.Invoke(context.Background(), "ci.worker.token.retire", workerTokenRetireIn{Repo: "beta", Token: out.Value}); !errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: a token retired on another repository: %v", err)
	}
	if _, err := f.r.Invoke(context.Background(), "ci.worker.token.retire", workerTokenRetireIn{Repo: "alpha", Token: out.Value}); err != nil {
		t.Fatalf("FAIL: retiring: %v", err)
	}
	if len(f.eng.revoked) != 1 || f.eng.revoked[0] != out.Token.ID {
		t.Errorf("FAIL: revoked %v, want only %s", f.eng.revoked, out.Token.ID)
	}
	last := f.rec.rows[len(f.rec.rows)-1]
	if last.field != "worker-token" || !strings.Contains(last.was, out.Token.ID) || last.now == "" {
		t.Errorf("FAIL: the retire row is %+v", last)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func (f *codeFixture) post(t *testing.T, h http.Handler, path string, body map[string]string) (int, string) {
	t.Helper()
	raw, _ := json.Marshal(body)
	req := httptest.NewRequest("POST", path, bytes.NewReader(raw))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec.Code, rec.Body.String()
}

// A PRIVATE REPOSITORY'S RUNNER INSTALLS AND UNINSTALLS WITH NO ACCOUNT:
// redeem and retire meet no read gate, and every failure is still the
// one 404.
func TestRedeemAndRetireWorkOnAPrivateRepository(t *testing.T) {
	f := newCodeFixture(t)
	f.private = true
	h, err := RouterWithCaps(f.r, "v", func(string, string) CapSet { return oltp.CapSet("") },
		func(ctx context.Context, _ string) bool { return ops.User(ctx) != "" })
	if err != nil {
		t.Fatal(err)
	}
	code := f.code(t, "dmestas", "alpha")
	redeem := "/api/v1/r/alpha/ci/runner-codes/redeem"
	st, body := f.post(t, h, redeem, map[string]string{"code": code, "host": "box"})
	if st != 200 || !strings.Contains(body, `"value":"s3cret-bearer-value"`) {
		t.Fatalf("FAIL: redeem on a private repository answered %d %s", st, body)
	}
	st2, b2 := f.post(t, h, redeem, map[string]string{"code": code, "host": "box"})
	st3, b3 := f.post(t, h, "/api/v1/r/nowhere/ci/runner-codes/redeem", map[string]string{"code": code, "host": "box"})
	if st2 != 404 || st3 != 404 {
		t.Errorf("FAIL: a spent code answered %d, an unknown repository %d", st2, st3)
	}
	var e1, e3 struct{ Error string }
	json.Unmarshal([]byte(b2), &e1)
	json.Unmarshal([]byte(b3), &e3)
	if e1.Error == "" || e1.Error != e3.Error {
		t.Errorf("FAIL: the two refusals differ: %q | %q", b2, b3)
	}
	retire := "/api/v1/r/alpha/ci/worker-tokens/retire"
	if st, body := f.post(t, h, retire, map[string]string{"token": "wrong", "host": "box"}); st != 404 {
		t.Errorf("FAIL: retiring with a wrong token answered %d %s", st, body)
	}
	if st, body := f.post(t, h, retire, map[string]string{"token": "s3cret-bearer-value", "host": "box"}); st != 200 {
		t.Errorf("FAIL: retire on a private repository answered %d %s", st, body)
	}
	if st, _ := f.post(t, h, retire, map[string]string{"token": "s3cret-bearer-value", "host": "box"}); st != 200 {
		t.Errorf("FAIL: retiring twice answered %d, want the same success", st)
	}
	// Other ops on the same private repository stay shut.
	if st, _ := f.post(t, h, "/api/v1/r/alpha/ci/runner-codes", map[string]string{}); st == 200 {
		t.Errorf("FAIL: an anonymous caller made a code")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// TWO REDEEMS OF ONE CODE AT ONCE: EXACTLY ONE GETS A TOKEN.
func TestRacingRedeemsOfOneCodeSucceedOnce(t *testing.T) {
	for round := 0; round < 3; round++ {
		f := newCodeFixture(t)
		code := f.code(t, "dmestas", "alpha")
		var wg sync.WaitGroup
		var won, refused atomic.Int32
		for i := 0; i < 8; i++ {
			wg.Add(1)
			go func() {
				defer wg.Done()
				if _, err := f.redeem("alpha", code); err == nil {
					won.Add(1)
				} else if errors.Is(err, ops.ErrNotFound) {
					refused.Add(1)
				}
			}()
		}
		wg.Wait()
		if won.Load() != 1 || refused.Load() != 7 {
			t.Fatalf("FAIL: round %d: %d redeemed, %d refused, want 1 and 7", round, won.Load(), refused.Load())
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}