Skip to content
quarry Artifact [b8c0f7f6e2]
Login

Artifact [b8c0f7f6e2]

Artifact b8c0f7f6e25ab88fcc6858a3c428809247d8d9fc8e3b857bf7995ad097663cae:


package api

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

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

func requiredChecksFixture(t *testing.T) (*ops.Registry, *oltp.DB, *settingRecorder) {
	t.Helper()
	db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { db.Close() })
	for _, who := range []string{"dmestas", "jva"} {
		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" {
			return oltp.CapSet("3")
		}
		return oltp.CapSet("a")
	}
	rec := &settingRecorder{}
	r := ops.NewRegistry()
	if err := RegisterAll(r, Deps{Version: "v", CheckRules: db, Checks: db, SettingLog: rec, CapsFor: caps,
		Repos:    NewRepos(map[string]*Repo{"test": {Index: wikiIndex(t), Code: "code-test", Chat: "code-test"}}),
		Accounts: adminAdapter{acctAdapter{db}}, SignOffs: testSignOffs{db}, SecretBox: testBox(t)}); err != nil {
		t.Fatal(err)
	}
	return r, db, rec
}

// An admin sets a rule, lists it, a second set replaces it, and an empty
// list removes it.
func TestAnAdminSetsListsAndClearsARequiredChecksRule(t *testing.T) {
	r, db, rec := requiredChecksFixture(t)
	dan := asUser("dan")
	if _, err := r.Invoke(dan, "ci.checks.set", checkRuleSetIn{Repo: "test", Branch: "release-*", Checks: []string{"vet", "go", "go"}}); err != nil {
		t.Fatalf("FAIL: set: %v", err)
	}
	out, err := r.Invoke(dan, "ci.checks.list", checkRulesIn{Repo: "test"})
	if err != nil {
		t.Fatalf("FAIL: list: %v", err)
	}
	got := out.(checkRulesOut).Rules
	if !reflect.DeepEqual(got, []checkRuleRow{{Branch: "release-*", Checks: []string{"go", "vet"}}}) {
		t.Errorf("FAIL: the list is %+v", got)
	}
	if want := []string{"go", "vet"}; !reflect.DeepEqual(db.RequiredChecks("test", "release-1"), want) {
		t.Errorf("FAIL: the store requires %v", db.RequiredChecks("test", "release-1"))
	}
	if len(rec.rows) != 1 || rec.rows[0].actor != "dan" || rec.rows[0].repo != "test" || !strings.HasPrefix(rec.rows[0].field, "checks:") {
		t.Errorf("FAIL: the settings row: %+v", rec.rows)
	}
	if _, err := r.Invoke(dan, "ci.checks.set", checkRuleSetIn{Repo: "test", Branch: "release-*"}); err != nil {
		t.Fatalf("FAIL: clear: %v", err)
	}
	out, _ = r.Invoke(dan, "ci.checks.list", checkRulesIn{Repo: "test"})
	if rules := out.(checkRulesOut).Rules; rules == nil || len(rules) != 0 {
		t.Errorf("FAIL: after clearing the list is %#v", rules)
	}
	body, _ := json.Marshal(out)
	if !strings.Contains(string(body), `"rules":[]`) {
		t.Errorf("FAIL: the wire shape is %s", body)
	}
	if len(rec.rows) != 2 {
		t.Errorf("FAIL: want a row per change, got %+v", rec.rows)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Without the admin letter neither the list nor the set is allowed, and
// a blank branch or a name with a space is invalid.
func TestRequiredChecksOpsRefuseANonAdminAndBadInput(t *testing.T) {
	r, db, _ := requiredChecksFixture(t)
	eve := asUser("eve")
	if _, err := r.Invoke(eve, "ci.checks.set", checkRuleSetIn{Repo: "test", Branch: "trunk", Checks: []string{"go"}}); !errors.Is(err, ops.ErrForbidden) {
		t.Errorf("FAIL: a non-admin set: %v", err)
	}
	if _, err := r.Invoke(eve, "ci.checks.list", checkRulesIn{Repo: "test"}); !errors.Is(err, ops.ErrForbidden) {
		t.Errorf("FAIL: a non-admin listed: %v", err)
	}
	if got := db.RequiredChecks("test", "trunk"); len(got) != 0 {
		t.Errorf("FAIL: a refused call wrote %v", got)
	}
	if _, err := r.Invoke(asUser("dan"), "ci.checks.set", checkRuleSetIn{Repo: "gone", Branch: "trunk", Checks: []string{"go"}}); !errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: an unserved repository: %v", err)
	}
	if _, err := r.Invoke(asUser("dan"), "ci.checks.set", checkRuleSetIn{Repo: "test", Branch: "  ", Checks: []string{"go"}}); !errors.Is(err, ops.ErrInvalid) {
		t.Errorf("FAIL: a blank branch: %v", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// An agent is refused; with Quarry-Ask it files a sign-off, and the
// person's approval sets the rule as the person.
func TestAnAgentAsksItsPersonToSetRequiredChecks(t *testing.T) {
	r, db, rec := requiredChecksFixture(t)
	if _, err := r.Invoke(asUser("jva-bot"), "ci.checks.set", checkRuleSetIn{Repo: "test", Branch: "trunk", Checks: []string{"go"}}); !errors.Is(err, ops.ErrForbidden) {
		t.Fatalf("FAIL: an agent set a rule: %v", err)
	}
	if got := db.RequiredChecks("test", "trunk"); len(got) != 0 {
		t.Fatalf("FAIL: a refused agent wrote %v", got)
	}
	if _, err := r.Invoke(asUser("jva-bot"), "ci.checks.list", checkRulesIn{Repo: "test"}); err != nil {
		t.Errorf("FAIL: an agent could not list: %v", err)
	}
	holds := func(string, string) CapSet { return oltp.CapSet("a") }
	h, err := RouterWithCaps(r, "v", holds, nil)
	if err != nil {
		t.Fatal(err)
	}
	ctx := ops.WithToken(ops.WithUser(context.Background(), "jva-bot"), ops.TokenAuth{ID: "T", Caps: func(string) ops.Caps { return oltp.CapSet("a") }})
	req := httptest.NewRequest("POST", "/api/v1/r/test/ci/required-checks", strings.NewReader(`{"branch":"trunk","checks":["go","vet"]}`)).WithContext(ctx)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Quarry-Ask", "gate trunk on the suite")
	w := httptest.NewRecorder()
	h.ServeHTTP(w, req)
	if w.Code != 202 {
		t.Fatalf("FAIL: asking answered %d: %s", w.Code, w.Body)
	}
	var asked struct {
		SignOff SignOffRequest `json:"signoff"`
	}
	if err := json.Unmarshal(w.Body.Bytes(), &asked); err != nil || asked.SignOff.ID == "" || asked.SignOff.Owner != "jva" || asked.SignOff.State != "pending" {
		t.Fatalf("FAIL: the request: %s", w.Body)
	}
	if got := db.RequiredChecks("test", "trunk"); len(got) != 0 {
		t.Fatalf("FAIL: the ask wrote before approval: %v", got)
	}
	if _, err := r.Invoke(asUser("jva"), "signoff.decide", signOffDecideIn{ID: asked.SignOff.ID, Approve: true}); err != nil {
		t.Fatalf("FAIL: approving: %v", err)
	}
	if got := db.RequiredChecks("test", "trunk"); !reflect.DeepEqual(got, []string{"go", "vet"}) {
		t.Errorf("FAIL: approval left %v", got)
	}
	if len(rec.rows) != 1 || rec.rows[0].actor != "jva" || !strings.Contains(rec.rows[0].now, asked.SignOff.ID) {
		t.Errorf("FAIL: the row: %+v", rec.rows)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}