Skip to content
quarry Artifact [9329c984c6]
Login

Artifact [9329c984c6]

Artifact 9329c984c61d9884efaae1a91c90d71666ea1b5d1d9b6f8fbe1bed517ec4d4c5:


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 protectionFixture(t *testing.T) (*ops.Registry, *oltp.DB) {
	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", "bo"} {
		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 {
		switch account {
		case "eve":
			return oltp.CapSet("3")
		case "dev":
			return oltp.CapSet("i")
		}
		return oltp.CapSet("a")
	}
	r := ops.NewRegistry()
	if err := RegisterAll(r, Deps{Version: "v", Protect: db, SettingsLog: db.SettingsLog, 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
}

func TestAnAdminSetsListsAndClearsAProtection(t *testing.T) {
	r, db := protectionFixture(t)
	ctx := ops.WithToken(ops.WithUser(context.Background(), "dan"), ops.TokenAuth{ID: "T1", Caps: func(string) ops.Caps { return oltp.CapSet("a") }})
	if _, err := r.Invoke(ctx, "branch.protection.set", branchProtectionSetIn{Repo: "test", Branch: "release-*", Owners: []string{"jva", "bo", "jva"}}); err != nil {
		t.Fatalf("FAIL: set: %v", err)
	}
	out, err := r.Invoke(ctx, "branch.protection.list", branchProtectionsIn{Repo: "test"})
	if err != nil {
		t.Fatalf("FAIL: list: %v", err)
	}
	if got := out.(branchProtectionsOut).Rules; !reflect.DeepEqual(got, []oltp.Protection{{Branch: "release-*", Owners: []string{"bo", "jva"}}}) {
		t.Errorf("FAIL: the list is %+v", got)
	}
	log, _ := db.SettingsLog("test", 10)
	if len(log) != 1 || log[0].Actor != "dan" || log[0].Via != "T1" || log[0].Field != "protect:release-*" {
		t.Errorf("FAIL: the trail: %+v", log)
	}
	if _, err := r.Invoke(ctx, "branch.protection.set", branchProtectionSetIn{Repo: "test", Branch: "release-*"}); err != nil {
		t.Fatalf("FAIL: clear: %v", err)
	}
	out, _ = r.Invoke(ctx, "branch.protection.list", branchProtectionsIn{Repo: "test"})
	body, _ := json.Marshal(out)
	if !strings.Contains(string(body), `"rules":[]`) {
		t.Errorf("FAIL: after clearing the wire shape is %s", body)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestProtectionOpsRefuseWhoLacksAdmin(t *testing.T) {
	r, db := protectionFixture(t)
	in := branchProtectionSetIn{Repo: "test", Branch: "trunk", Owners: []string{"jva"}}
	for _, who := range []string{"eve", "dev"} {
		if _, err := r.Invoke(asUser(who), "branch.protection.set", in); !errors.Is(err, ops.ErrForbidden) {
			t.Errorf("FAIL: %s set: %v", who, err)
		}
		if _, err := r.Invoke(asUser(who), "branch.protection.list", branchProtectionsIn{Repo: "test"}); !errors.Is(err, ops.ErrForbidden) {
			t.Errorf("FAIL: %s listed: %v", who, err)
		}
	}
	h, err := RouterWithCaps(r, "v", func(string, string) CapSet { return oltp.CapSet("a") }, nil)
	if err != nil {
		t.Fatal(err)
	}
	ctx := ops.WithToken(ops.WithUser(context.Background(), "dan"), ops.TokenAuth{ID: "T", Caps: func(string) ops.Caps { return oltp.CapSet("i") }})
	req := httptest.NewRequest("POST", "/api/v1/r/test/branch-protection", strings.NewReader(`{"branch":"trunk","owners":["jva"]}`)).WithContext(ctx)
	req.Header.Set("Content-Type", "application/json")
	w := httptest.NewRecorder()
	h.ServeHTTP(w, req)
	if w.Code != 403 {
		t.Errorf("FAIL: a token below a answered %d: %s", w.Code, w.Body)
	}
	if got, _ := db.Protections("test"); len(got) != 0 {
		t.Errorf("FAIL: refused calls wrote %v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestProtectionSetRefusesUnknownOwnersAndBadPatterns(t *testing.T) {
	r, db := protectionFixture(t)
	dan := asUser("dan")
	_, err := r.Invoke(dan, "branch.protection.set", branchProtectionSetIn{Repo: "test", Branch: "trunk", Owners: []string{"jva", "ghost", "phantom"}})
	if !errors.Is(err, ops.ErrInvalid) || !strings.Contains(err.Error(), "ghost") || !strings.Contains(err.Error(), "phantom") || strings.Contains(err.Error(), "jva") {
		t.Errorf("FAIL: unknown owners: %v", err)
	}
	for _, b := range []string{"  ", "release-[", "bad\x00name"} {
		if _, err := r.Invoke(dan, "branch.protection.set", branchProtectionSetIn{Repo: "test", Branch: b, Owners: []string{"jva"}}); !errors.Is(err, ops.ErrInvalid) {
			t.Errorf("FAIL: branch %q: %v", b, err)
		}
	}
	if _, err := r.Invoke(dan, "branch.protection.set", branchProtectionSetIn{Repo: "gone", Branch: "trunk", Owners: []string{"jva"}}); !errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: unserved repo: %v", err)
	}
	if got, _ := db.Protections("test"); len(got) != 0 {
		t.Errorf("FAIL: refused calls wrote %v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestAnAgentAsksItsPersonToSetAProtection(t *testing.T) {
	r, db := protectionFixture(t)
	in := branchProtectionSetIn{Repo: "test", Branch: "trunk", Owners: []string{"jva"}}
	if _, err := r.Invoke(asUser("jva-bot"), "branch.protection.set", in); !errors.Is(err, ops.ErrForbidden) {
		t.Fatalf("FAIL: an agent set a rule: %v", err)
	}
	h, err := RouterWithCaps(r, "v", func(string, string) CapSet { return oltp.CapSet("a") }, 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/branch-protection", strings.NewReader(`{"branch":"trunk","owners":["jva"]}`)).WithContext(ctx)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Quarry-Ask", "keep trunk to jva")
	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.State != "pending" {
		t.Fatalf("FAIL: the request: %s", w.Body)
	}
	if got, _ := db.Protections("test"); 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.Protections("test"); !reflect.DeepEqual(got, []oltp.Protection{{Branch: "trunk", Owners: []string{"jva"}}}) {
		t.Errorf("FAIL: approval left %v", got)
	}
	log, _ := db.SettingsLog("test", 5)
	if len(log) != 1 || log[0].Actor != "jva" {
		t.Errorf("FAIL: the trail: %+v", log)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// What the API writes is what the form writes: the same rule, enforced
// by the same gate.
func TestAProtectionSetByTheAPIBindsLikeTheForm(t *testing.T) {
	r, db := protectionFixture(t)
	if _, err := r.Invoke(asUser("dan"), "branch.protection.set", branchProtectionSetIn{Repo: "test", Branch: "trunk", Owners: []string{"jva"}}); err != nil {
		t.Fatal(err)
	}
	if err := db.SetProtectionBy("other", "trunk", []string{"jva"}, "dan", ""); err != nil {
		t.Fatal(err)
	}
	api, _ := db.Protections("test")
	form, _ := db.Protections("other")
	if !reflect.DeepEqual(api, form) {
		t.Errorf("FAIL: api wrote %v, the form's call %v", api, form)
	}
	if db.MayJoin("test", "bo", "trunk") || !db.MayJoin("test", "jva", "trunk") {
		t.Errorf("FAIL: the rule does not bind a non-owner and admit an owner")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func askProtection(t *testing.T, r *ops.Registry, body string) SignOffRequest {
	t.Helper()
	h, err := RouterWithCaps(r, "v", func(string, string) CapSet { return oltp.CapSet("a") }, 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/branch-protection", strings.NewReader(body)).WithContext(ctx)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Quarry-Ask", "why")
	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 {
		t.Fatal(err)
	}
	return asked.SignOff
}

// The approver sees the branch and every owner, and a removal reads as
// one; the approved change's trail names the asker and the request.
func TestAProtectionSignOffNamesOwnersAndTheTrailTheAsker(t *testing.T) {
	r, db := protectionFixture(t)
	set := askProtection(t, r, `{"branch":"release-*","owners":["jva","bo"]}`)
	for _, want := range []string{"release-*", "jva", "bo"} {
		if !strings.Contains(set.Summary, want) {
			t.Errorf("FAIL: the set summary lacks %q: %q", want, set.Summary)
		}
	}
	clear := askProtection(t, r, `{"branch":"release-*","owners":[]}`)
	if clear.Summary == set.Summary || !strings.Contains(clear.Summary, "release-*") || strings.Contains(clear.Summary, "jva") {
		t.Errorf("FAIL: the clear summary: %q vs %q", clear.Summary, set.Summary)
	}
	if _, err := r.Invoke(asUser("jva"), "signoff.decide", signOffDecideIn{ID: set.ID, Approve: true}); err != nil {
		t.Fatalf("FAIL: approving: %v", err)
	}
	log, _ := db.SettingsLog("test", 5)
	if len(log) != 1 || !strings.Contains(log[0].Now, "jva-bot") || !strings.Contains(log[0].Now, set.ID) || log[0].Actor != "jva" {
		t.Errorf("FAIL: the trail: %+v", log)
	}
	if got, _ := db.Protections("test"); len(got) != 1 || !reflect.DeepEqual(got[0].Owners, []string{"bo", "jva"}) {
		t.Errorf("FAIL: the stored owners carry more than logins: %v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestAnAgentCannotOwnAProtectedBranch(t *testing.T) {
	r, db := protectionFixture(t)
	_, err := r.Invoke(asUser("dan"), "branch.protection.set", branchProtectionSetIn{Repo: "test", Branch: "trunk", Owners: []string{"jva", "jva-bot"}})
	if !errors.Is(err, ops.ErrInvalid) || !strings.Contains(err.Error(), "jva-bot") {
		t.Errorf("FAIL: an agent owner: %v", err)
	}
	if got, _ := db.Protections("test"); len(got) != 0 {
		t.Errorf("FAIL: wrote %v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}