Skip to content
quarry Artifact [5a54aa6976]
Login

Artifact [5a54aa6976]

Artifact 5a54aa6976903e528ddb16745e171bbffef5c41c6e70433f2e4057e871b3d4bb:


package api

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"path/filepath"
	"testing"

	"craftdesign.group/quarry/internal/artifact"
	"craftdesign.group/quarry/internal/index"
	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
)

// verdictIndex is redTrunkIndex with a failed verdict tagged on the
// trunk tip, the way a finished run leaves one.
func verdictIndex(t *testing.T) *index.Index {
	t.Helper()
	ix := redTrunkIndex(t)
	if err := ix.FoldNow([]index.Parsed{{Hash: "ctl-ci", Art: &artifact.Artifact{
		Type: artifact.Control, Date: "2026-01-01T08:30:00", User: "quarry",
		Tags: []artifact.Tag{{Name: "ci-fail", Target: redTrunkTip}},
	}}}); err != nil {
		t.Fatal(err)
	}
	return ix
}

func verdictRuns() runsStub {
	return runsStub{runs: []CIRun{
		{RunID: "run-one", Checkin: redTrunkTip, Workflow: "quarry.quarry.1", Pipeline: "ci/quarry.json", Status: "completed"},
		{RunID: "run-two", Checkin: redTrunkTip, Workflow: "quarry.race.1", Pipeline: "ci/race.json", Status: "failed",
			URL: "https://ci.example/run-two", Summary: "boom", RerunOf: "run-zero", RerunAs: "run-three", InheritedFrom: "run-pair"},
	}}
}

func verdictJSON(t *testing.T, v any) map[string]any {
	t.Helper()
	b, _ := json.Marshal(v)
	var m map[string]any
	if err := json.Unmarshal(b, &m); err != nil {
		t.Fatal(err)
	}
	return m
}

// A visitor without 8 reads each check's name and state and the
// verdict, and no run id or link to one; a holder of 8 reads both.
func TestACheckinsVerdictIsOpenAndItsRunsStayShut(t *testing.T) {
	d := Deps{Version: "v", CI: verdictRuns(), Checks: checksStub{required: []string{"quarry", "race"}},
		Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: verdictIndex(t)}})}
	r := ops.NewRegistry()
	if err := RegisterAll(r, d); err != nil {
		t.Fatal(err)
	}
	get := func(letters string) map[string]any {
		t.Helper()
		got, err := r.Invoke(ops.WithCaps(context.Background(), oltp.CapSet(letters)), "checkin.get",
			checkinGetIn{Repo: "test", Hash: redTrunkTip, Files: "0"})
		if err != nil {
			t.Fatal(err)
		}
		return verdictJSON(t, got)
	}

	m := get("o")
	if m["ci"] != "ci-fail" {
		t.Errorf("FAIL: the verdict reads %v without 8", m["ci"])
	}
	checks, _ := m["checks"].([]any)
	if len(checks) != 2 {
		t.Fatalf("FAIL: %d checks without 8, want 2: %v", len(checks), m["checks"])
	}
	for i, c := range checks {
		row := c.(map[string]any)
		if row["pipeline"] == "" || row["status"] == "" {
			t.Errorf("FAIL: check %d lost its name or state: %v", i, row)
		}
		for _, k := range []string{"runId", "url", "summary", "rerunOf", "rerunAs", "inheritedFrom"} {
			if v, ok := row[k]; ok && v != "" {
				t.Errorf("FAIL: check %d carries %s without 8: %v", i, k, v)
			}
		}
	}
	if _, ok := m["ciRun"]; ok {
		t.Errorf("FAIL: the run behind the badge is named without 8: %v", m["ciRun"])
	}

	m = get("o8")
	checks, _ = m["checks"].([]any)
	if len(checks) != 2 || checks[0].(map[string]any)["runId"] != "run-one" || m["ciRun"] == nil {
		t.Errorf("FAIL: a holder of 8 lost the run ids: %v", m)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A landing's checks arrive the same way: names and states, no runs.
func TestALandingsChecksCarryNoRunIDsWithoutEight(t *testing.T) {
	tip := "f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1"
	d := Deps{Version: "v", CI: verdictRuns(), Checks: checksStub{required: []string{"quarry", "race"}},
		Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: openLandingIndex(t, "feature", tip)}})}
	r := ops.NewRegistry()
	if err := RegisterAll(r, d); err != nil {
		t.Fatal(err)
	}
	got, err := r.Invoke(ops.WithCaps(context.Background(), oltp.CapSet("o2")), "landing.get",
		landingGetIn{Repo: "test", ID: landingHash})
	if err != nil {
		t.Fatal(err)
	}
	m := verdictJSON(t, got)
	checks, _ := m["checks"].([]any)
	if len(checks) != 2 {
		t.Fatalf("FAIL: %d checks without 8, want 2: %v", len(checks), m["checks"])
	}
	for i, c := range checks {
		row := c.(map[string]any)
		if row["pipeline"] == "" || row["status"] == "" {
			t.Errorf("FAIL: check %d lost its name or state: %v", i, row)
		}
		for _, k := range []string{"runId", "url"} {
			if v, ok := row[k]; ok && v != "" {
				t.Errorf("FAIL: check %d carries %s without 8: %v", i, k, v)
			}
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// ciRig serves ci.run.log behind the real capability plane, with a
// public repository whose box the test ticks.
type ciRig struct {
	db *oltp.DB
	h  http.Handler
}

func newCIRig(t *testing.T) ciRig {
	t.Helper()
	db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { db.Close() })
	if err := db.AddAccount("jan", "a-long-enough-password", false); err != nil {
		t.Fatal(err)
	}
	if err := db.AddRepo("test", t.TempDir(), "", oltp.Public); err != nil {
		t.Fatal(err)
	}
	if err := db.SetVisibility("test", "Public project"); err != nil {
		t.Fatal(err)
	}
	d := Deps{Version: "v", Repos: testRepos(wikiIndex(t)),
		CIRunByPrefix: func(repo, prefix string) (CIRun, bool, bool, error) {
			return CIRun{RunID: "run-one", Checkin: "c1", Status: "completed"}, true, false, nil
		}}
	r := ops.NewRegistry()
	if err := RegisterAll(r, d); err != nil {
		t.Fatal(err)
	}
	h, err := RouterWithCaps(r, "v", func(acct, repo string) CapSet { return db.EffectiveCaps(acct, repo) }, nil)
	if err != nil {
		t.Fatal(err)
	}
	return ciRig{db: db, h: h}
}

// get answers GET .../ci/runs/run-one/log for a caller: nobody, a
// person, or a token whose ceiling is letters.
func (g ciRig) get(user, ceiling string) *httptest.ResponseRecorder {
	req := httptest.NewRequest("GET", "/api/v1/r/test/ci/runs/run-one/log", nil)
	ctx := req.Context()
	if user != "" {
		ctx = ops.WithUser(ctx, user)
	}
	if ceiling != "" {
		ctx = ops.WithToken(ctx, ops.TokenAuth{ID: "T1", Caps: func(string) ops.Caps { return oltp.CapSet(ceiling) }})
	}
	w := httptest.NewRecorder()
	g.h.ServeHTTP(w, req.WithContext(ctx))
	return w
}

// With no credential a run's log is a 401 that says what to send; a
// token whose ceiling lacks 8 gets a 403; the box opens the log to the
// visitor, and clearing it shuts it again.
func TestACIRefusalSaysWhatToDoAndTheBoxOpensTheLog(t *testing.T) {
	g := newCIRig(t)
	w := g.get("", "")
	if w.Code != http.StatusUnauthorized {
		t.Errorf("FAIL: a visitor's log read answered %d, want 401: %s", w.Code, w.Body)
	}
	code := func(w *httptest.ResponseRecorder) string {
		var body map[string]string
		_ = json.Unmarshal(w.Body.Bytes(), &body)
		return body["code"]
	}
	if code(w) != "ci_sign_in" {
		t.Errorf("FAIL: the 401 carries code %q, want ci_sign_in", code(w))
	}
	if w := g.get("jan", ""); w.Code != http.StatusOK {
		t.Errorf("FAIL: a signed-in account's log read answered %d: %s", w.Code, w.Body)
	}
	w = g.get("jan", "o")
	if w.Code != http.StatusForbidden || code(w) != "ci_token_ceiling" {
		t.Errorf("FAIL: a token without 8 in its ceiling answered %d code %q, want 403 ci_token_ceiling", w.Code, code(w))
	}
	// Signing in would not help where the signed-in category lacks 8:
	// no promise of it, and no 401 to ask for it.
	if err := g.db.SetCategoryCaps("test", "anonymous", "mnc3C"); err != nil {
		t.Fatal(err)
	}
	if w := g.get("", ""); w.Code != http.StatusForbidden || code(w) != "ci_not_open" {
		t.Errorf("FAIL: a visitor where signed-in accounts lack 8 answered %d code %q, want 403 ci_not_open", w.Code, code(w))
	}
	if err := g.db.SetCategoryCaps("test", "anonymous", "mnc3C8"); err != nil {
		t.Fatal(err)
	}

	on := true
	if _, err := g.db.PatchRepo("test", oltp.RepoPatch{CIPublic: &on}, "jan", ""); err != nil {
		t.Fatal(err)
	}
	if w := g.get("", ""); w.Code != http.StatusOK {
		t.Errorf("FAIL: with the box ticked a visitor's log read answered %d: %s", w.Code, w.Body)
	}
	if w := g.get("jan", "o"); w.Code != http.StatusForbidden {
		t.Errorf("FAIL: the box lifted a token's ceiling: %d", w.Code)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// repo.update carries the box as ciPublic, and a body that does not name
// it leaves it alone.
func TestRepoUpdateCarriesTheCIBox(t *testing.T) {
	reg := &fakeRegistry{}
	r := ops.NewRegistry()
	if err := RegisterAll(r, Deps{Version: "v", Registry: reg, Repos: testRepos(wikiIndex(t))}); err != nil {
		t.Fatal(err)
	}
	var in repoUpdateIn
	if err := json.Unmarshal([]byte(`{"name":"test","ciPublic":true}`), &in); err != nil {
		t.Fatal(err)
	}
	if _, err := r.Invoke(asUser("dan"), "repo.update", in); err != nil {
		t.Fatal(err)
	}
	if _, err := r.Invoke(asUser("dan"), "repo.update", repoUpdateIn{Name: "test", Description: new(string)}); err != nil {
		t.Fatal(err)
	}
	if len(reg.updates) != 2 || reg.updates[0].CIPublic == nil || !*reg.updates[0].CIPublic {
		t.Fatalf("FAIL: the box did not reach the registry: %+v", reg.updates)
	}
	if reg.updates[1].CIPublic != nil {
		t.Errorf("FAIL: a body that left the box out wrote it")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}