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
// held is the repositories under a takedown.
held map[string]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{}, held: 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, repo string) bool {
return !(f.private && repo == "alpha") || ops.User(ctx) != ""
},
Held: func(ctx context.Context, repo string) string {
if f.held[repo] && ops.User(ctx) == "" {
return "this repository is down"
}
return ""
},
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")
}
}
type wire struct {
status int
header string
body string
}
func (f *codeFixture) wire(t *testing.T, h http.Handler, path string, body map[string]string) wire {
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)
hd := rec.Header().Clone()
hd.Del("Date")
var b bytes.Buffer
hd.Write(&b)
return wire{rec.Code, b.String(), rec.Body.String()}
}
func (f *codeFixture) router(t *testing.T) http.Handler {
t.Helper()
// As production does: the router asks the registry which names are
// repositories.
SetRepoKnown(func(name string) bool { return name == "alpha" || name == "beta" })
t.Cleanup(func() { SetRepoKnown(func(string) bool { return true }) })
h, err := RouterWithCaps(f.r, "v", func(string, string) CapSet { return oltp.CapSet("") },
func(ctx context.Context, repo string) bool {
return !(f.private && repo == "alpha") || ops.User(ctx) != ""
})
if err != nil {
t.Fatal(err)
}
return h
}
// A NAME THAT IS NO REPOSITORY, A PRIVATE REPOSITORY AND A PUBLIC ONE
// ANSWER A WRONG CODE OR TOKEN IN THE SAME BYTES.
func TestCredentialOpsAnswerUnknownPrivateAndPublicAlike(t *testing.T) {
f := newCodeFixture(t)
f.private = true
h := f.router(t)
for _, c := range []struct {
route string
body map[string]string
}{
{"ci/runner-codes/redeem", map[string]string{"code": "qri_nope", "host": "box"}},
{"ci/worker-tokens/retire", map[string]string{"token": "not-a-token", "host": "box"}},
} {
unknown := f.wire(t, h, "/api/v1/r/nowhere/"+c.route, c.body)
private := f.wire(t, h, "/api/v1/r/alpha/"+c.route, c.body)
public := f.wire(t, h, "/api/v1/r/beta/"+c.route, c.body)
if unknown.status != 404 {
t.Errorf("FAIL: %s: unknown name answered %d", c.route, unknown.status)
}
if unknown != private || unknown != public {
t.Errorf("FAIL: %s: answers differ:\n%+v\n%+v\n%+v", c.route, unknown, private, public)
}
if strings.Contains(unknown.body, "alpha") || strings.Contains(unknown.body, "nowhere") {
t.Errorf("FAIL: %s: the answer names a repository: %s", c.route, unknown.body)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A CODE MADE BEFORE A TAKEDOWN DOES NOT MINT AFTER IT, AND IS NOT
// SPENT; A TOKEN MAY STILL RETIRE ITSELF.
func TestATakedownStopsRedeemButNotRetire(t *testing.T) {
f := newCodeFixture(t)
f.private = true
h := f.router(t)
redeem, retire := "/api/v1/r/alpha/ci/runner-codes/redeem", "/api/v1/r/alpha/ci/worker-tokens/retire"
live := f.code(t, "dmestas", "alpha")
issued := f.code(t, "dmestas", "alpha")
if st, body := f.post(t, h, redeem, map[string]string{"code": issued, "host": "box"}); st != 200 {
t.Fatalf("FAIL: setup redeem %d %s", st, body)
}
f.eng.groups = nil
f.held["alpha"] = true
wrong := f.wire(t, h, redeem, map[string]string{"code": "qri_nope", "host": "box"})
held := f.wire(t, h, redeem, map[string]string{"code": live, "host": "box"})
if held != wrong {
t.Errorf("FAIL: a held repository answers differently:\n%+v\n%+v", held, wrong)
}
if len(f.eng.groups) != 0 {
t.Errorf("FAIL: a token was minted under a takedown")
}
if st, _ := f.post(t, h, retire, map[string]string{"token": "s3cret-bearer-value", "host": "box"}); st != 200 {
t.Errorf("FAIL: retire under a takedown answered %d", st)
}
delete(f.held, "alpha")
if st, body := f.post(t, h, redeem, map[string]string{"code": live, "host": "box"}); st != 200 {
t.Errorf("FAIL: the code was spent by the takedown: %d %s", st, body)
}
if !t.Failed() {
t.Log("ok")
}
}
// An engine that cannot mint is the forge's failure, not the code's:
// the code is not spent and redeems once the engine answers.
func TestAFailedMintLeavesTheCodeUnspent(t *testing.T) {
f := newCodeFixture(t)
code := f.code(t, "dmestas", "alpha")
f.eng.failMint = true
if _, err := f.redeem("alpha", code); err == nil || errors.Is(err, ops.ErrNotFound) {
t.Errorf("FAIL: a failed mint answered %v, want the engine's error", err)
}
out, err := f.redeem("alpha", code)
if err != nil || out.Value == "" {
t.Errorf("FAIL: the code did not redeem after the failed mint: %v", err)
}
if f.eng.mints != 1 {
t.Errorf("FAIL: %d tokens minted, want 1", f.eng.mints)
}
if _, err := f.redeem("alpha", code); !errors.Is(err, ops.ErrNotFound) {
t.Errorf("FAIL: the code redeemed twice: %v", err)
}
if !t.Failed() {
t.Log("ok")
}
}