Skip to content
quarry Artifact [c75e066ee3]
Login

Artifact [c75e066ee3]

Artifact c75e066ee35f558fdeec3c49fdb113916e251fbe7466f745c54cc047e95a2175:


package api

import (
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"testing"

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

// makingRegistry makes repositories in the rig's store, as the forge's
// registrar does: a name taken is refused, the spec's visibility is kept.
type makingRegistry struct {
	fakeRegistry
	t     *testing.T
	db    *oltp.DB
	repos *Repos
	made  []RepoSpec
}

func (m *makingRegistry) Add(spec RepoSpec) (string, string, error) {
	vis := oltp.Public
	if spec.Visibility == "private" {
		vis = oltp.Private
	}
	if err := m.db.AddRepo(spec.Name, m.t.TempDir(), "", vis); err != nil {
		return "", "", err
	}
	m.repos.Put(spec.Name, &Repo{Index: wikiIndex(m.t), Code: "code-" + spec.Name})
	m.made = append(m.made, spec)
	return spec.Name, "/repos/" + spec.Name, nil
}

func (m *makingRegistry) NameFree(namespace, name, author string) error {
	if _, ok := m.repos.Get(name); ok {
		return fmt.Errorf("%s is already a repository: %w", name, ops.ErrInvalid)
	}
	if strings.ContainsAny(name, " !/") {
		return fmt.Errorf("%q is not a repository name: %w", name, ops.ErrInvalid)
	}
	return nil
}

func (g *startRig) registry() *makingRegistry { return g.deps.Registry.(*makingRegistry) }

func (g *startRig) claimWith(who string, in setupClaimIn) (string, error) {
	out, err := g.r.Invoke(asUser(who), "setup.start.claim", in)
	if err != nil {
		return "", err
	}
	return out.(setupClaimOut).Request, nil
}

func (g *startRig) addRepo(name string, private bool) {
	g.t.Helper()
	vis := oltp.Public
	if private {
		vis = oltp.Private
	}
	if err := g.db.AddRepo(name, g.t.TempDir(), "", vis); err != nil {
		g.t.Fatal(err)
	}
	g.registry().repos.Put(name, &Repo{Index: wikiIndex(g.t), Code: "code-" + name})
	if err := g.db.Grant("dmestas", name, oltp.RepoAdmin); err != nil {
		g.t.Fatal(err)
	}
}

func (g *startRig) inputOf(id string) agentSetupIn {
	g.t.Helper()
	var in agentSetupIn
	for _, s := range g.requestsOf("dmestas") {
		if s.ID == id {
			if err := json.Unmarshal([]byte(s.Input), &in); err != nil {
				g.t.Fatal(err)
			}
			return in
		}
	}
	g.t.Fatalf("FAIL: no request %s", id)
	return in
}

// A started name that is an account is not a dead end: the page offers a
// free name made from it, and the claim files the request under the one the
// person chose, judged as agent.setup judges any name.
func TestATakenStartNameIsRenamedAtTheClaim(t *testing.T) {
	g := newStartRig(t)
	key, pickup := newPickupKey(t)
	code := g.begin("dmestas", "read", pickup)
	look, err := g.look("dmestas", code)
	if err != nil || look.NameTaken == "" || look.Suggest != "dmestas-agent" || len(look.Repos) == 0 {
		t.Fatalf("FAIL: the look at a taken name: %+v %v", look, err)
	}
	if err := g.db.AddAccount("dmestas-agent", "a-long-enough-password", false); err != nil {
		t.Fatal(err)
	}
	if again, _ := g.look("dmestas", code); again.Suggest != "dmestas-agent-2" {
		t.Errorf("FAIL: the next free suggestion is %q", again.Suggest)
	}
	for what, name := range map[string]string{"no new name": "", "the taken name again": "Dmestas", "another account": "jva", "a malformed one": "bad name!"} {
		if _, err := g.claimWith("dmestas", setupClaimIn{Code: code, Repos: "suit", Name: name}); !errors.Is(err, ops.ErrInvalid) {
			t.Errorf("FAIL: %s: %v", what, err)
		}
	}
	if _, ok, _ := g.db.SetupStartByCode(code, g.clock); !ok || len(g.requestsOf("dmestas")) != 0 {
		t.Fatalf("FAIL: refusals consumed the start or filed a request")
	}
	id, err := g.claimWith("dmestas", setupClaimIn{Code: code, Repos: "suit", Name: "dmestas-agent-2"})
	if err != nil {
		t.Fatal(err)
	}
	if in := g.inputOf(id); in.Name != "dmestas-agent-2" || in.Repos != "suit" {
		t.Errorf("FAIL: the request is for %+v", in)
	}
	if err := g.decide("dmestas", id, true); err != nil {
		t.Fatal(err)
	}
	if _, ok := g.db.AccountByName("dmestas-agent-2"); !ok {
		t.Errorf("FAIL: the agent was not made under the chosen name")
	}
	status, body := g.collectKey(key, "192.0.2.60")
	var got struct {
		Result struct {
			Agent string `json:"agent"`
		} `json:"result"`
	}
	_ = json.Unmarshal([]byte(body), &got)
	if status != 200 || got.Result.Agent != "dmestas-agent-2" {
		t.Errorf("FAIL: the collect answered %d with agent %q", status, got.Result.Agent)
	}
	// A free name is the client's own: it is not renamed.
	_, p2 := newPickupKey(t)
	free := g.begin("e-desktop", "read", p2)
	if l, _ := g.look("dmestas", free); l.NameTaken != "" || l.Suggest != "" {
		t.Errorf("FAIL: a free name offers a rename: %+v", l)
	}
	if _, err := g.claimWith("dmestas", setupClaimIn{Code: free, Repos: "suit", Name: "other-name"}); !errors.Is(err, ops.ErrInvalid) {
		t.Errorf("FAIL: renaming a free name: %v", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A push claim may ask for a repository that does not exist: nothing is
// made until the request is approved, then it is made private and the agent
// is set up on it.
func TestAPushClaimMayHaveTheRepositoryMadeAtApproval(t *testing.T) {
	g := newStartRig(t)
	key, pickup := newPickupKey(t)
	code := g.begin("mirror-push", "push", pickup)
	look, err := g.look("dmestas", code)
	if err != nil || !look.CanCreate {
		t.Fatalf("FAIL: a push start is not offered a new repository: %+v %v", look, err)
	}
	_, rp := newPickupKey(t)
	if l, _ := g.look("dmestas", g.begin("e-reader", "read", rp)); l.CanCreate {
		t.Errorf("FAIL: a read start is offered a new repository")
	}
	for what, in := range map[string]setupClaimIn{
		"a name that is taken":  {NewRepo: "suit"},
		"a malformed name":      {NewRepo: "bad name"},
		"a pick and a new one":  {NewRepo: "fresh", Repos: "suit"},
		"a namespace with none": {Repos: "suit", Namespace: "acme"},
		"admin":                 {NewRepo: "fresh", Role: "admin"},
	} {
		in.Code = code
		if _, err := g.claimWith("dmestas", in); !errors.Is(err, ops.ErrInvalid) {
			t.Errorf("FAIL: %s: %v", what, err)
		}
	}
	if _, err := g.claimWith("dmestas", setupClaimIn{Code: g.begin("e-reader2", "read", rp), NewRepo: "fresh"}); !errors.Is(err, ops.ErrInvalid) {
		t.Errorf("FAIL: a read start with a new repository: %v", err)
	}
	if _, ok, _ := g.db.SetupStartByCode(code, g.clock); !ok {
		t.Fatalf("FAIL: refusals consumed the start")
	}
	id, err := g.claimWith("dmestas", setupClaimIn{Code: code, NewRepo: "fresh-mirror", Role: "maintainer"})
	if err != nil {
		t.Fatal(err)
	}
	if in := g.inputOf(id); !in.NewRepo || in.Repos != "fresh-mirror" || in.Name != "mirror-push" || in.Role != "maintainer" || in.BelongsTo != "repository" {
		t.Errorf("FAIL: the request is %+v", in)
	}
	got := g.get("dmestas", id)
	if got.Setup == nil || !got.Setup.NewRepo || strings.Join(got.Setup.Repos, ",") != "fresh-mirror" || got.Setup.Problem != "" {
		t.Errorf("FAIL: the page's view: %+v", got.Setup)
	}
	if len(g.registry().made) != 0 {
		t.Fatalf("FAIL: a repository was made before approval")
	}
	if err := g.decide("dmestas", id, true); err != nil {
		t.Fatal(err)
	}
	made := g.registry().made
	if len(made) != 1 || made[0].Name != "fresh-mirror" || made[0].Visibility != "private" || !made[0].Create {
		t.Fatalf("FAIL: repositories made: %+v", made)
	}
	if set, _ := g.db.PrivateRepos(); !set["fresh-mirror"] {
		t.Errorf("FAIL: the repository is not private")
	}
	if a, ok := g.db.AccountByName("mirror-push"); !ok || a.Operator != "repo:fresh-mirror" {
		t.Errorf("FAIL: the agent: %+v", a)
	}
	status, body := g.collectKey(key, "192.0.2.61")
	var c struct {
		Result struct {
			Agent   string        `json:"agent"`
			Remotes []setupRemote `json:"remotes"`
		} `json:"result"`
	}
	_ = json.Unmarshal([]byte(body), &c)
	if status != 200 || c.Result.Agent != "mirror-push" || len(c.Result.Remotes) != 1 || !strings.HasSuffix(c.Result.Remotes[0].URL, "/r/fresh-mirror") {
		t.Errorf("FAIL: the collect: %d %s", status, body)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Only a person's claim may ask for a repository to be made: an agent's own
// ask is refused, and so is one that reaches the op as any other asker.
func TestAnAgentCannotAskForARepositoryToBeMade(t *testing.T) {
	g := newStartRig(t)
	body := `{"name":"sneaky","kind":"push","repos":"fresh","new_repo":true}`
	if status, _ := g.post(tokenCtx("dmestas-bot"), body, true, ""); status != 400 {
		t.Errorf("FAIL: an agent's ask for a repository to be made answered %d", status)
	}
	if status, _ := g.post(asUser("dmestas"), body, false, ""); status == 200 {
		t.Errorf("FAIL: the op ran directly")
	}
	if len(g.registry().made) != 0 {
		t.Errorf("FAIL: a repository was made")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// If the agent's own step fails after the repository was made, the
// repository stays: nothing takes it back.
func TestARepositoryMadeForASetupStaysWhenTheAgentStepFails(t *testing.T) {
	g := newStartRig(t)
	_, pickup := newPickupKey(t)
	id, err := g.claimWith("dmestas", setupClaimIn{Code: g.begin("mirror-push", "push", pickup), NewRepo: "left-behind"})
	if err != nil {
		t.Fatal(err)
	}
	g.failFinish = true
	if err := g.decide("dmestas", id, true); err == nil {
		t.Fatalf("FAIL: the approval did not fail")
	}
	if _, ok := g.db.AccountByName("mirror-push"); ok {
		t.Errorf("FAIL: the agent was left")
	}
	if _, ok := g.registry().repos.Get("left-behind"); !ok {
		t.Errorf("FAIL: the repository was taken back")
	}
	// The request says so: left, naming the repository, never undone.
	got := g.get("dmestas", id)
	if got.Setup == nil || got.Setup.Outcome != setupLeft || got.Setup.LeftRepo != "left-behind" || len(got.Setup.Left) == 0 {
		t.Errorf("FAIL: the recorded outcome: %+v", got.Setup)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The picker lists private repositories first, each group by name with
// case ignored.
func TestThePickerListsPrivateFirstAndIgnoresCase(t *testing.T) {
	g := newStartRig(t)
	g.addRepo("Zebra", false)
	g.addRepo("apple", false)
	g.addRepo("Bravo-private", true)
	g.addRepo("alpha-private", true)
	_, pickup := newPickupKey(t)
	look, err := g.look("dmestas", g.begin("e-desktop", "read", pickup))
	if err != nil {
		t.Fatal(err)
	}
	want := "alpha-private,Bravo-private,secret,apple,ctx,suit,Zebra"
	if got := strings.Join(repoNames(look.Repos), ","); got != want {
		t.Errorf("FAIL: the picker is %s, want %s", got, want)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A request that reaches agent.setup with a repository to make, but not
// from a claimed start, is refused when it runs and makes nothing.
func TestARepositoryIsNotMadeForAnAskerThatIsNotAClaimedClient(t *testing.T) {
	g := newStartRig(t)
	raw, err := json.Marshal(agentSetupIn{Name: "sneaky", Kind: "push", Repos: "fresh", NewRepo: true, BelongsTo: "repository", Ceiling: "uv3bBC78"})
	if err != nil {
		t.Fatal(err)
	}
	s, err := g.deps.SignOffs.RequestSignOff(SignOffRequest{Agent: "dmestas-bot", Owner: "dmestas", Op: setupOp, Input: string(raw), Summary: "x"})
	if err != nil {
		t.Fatal(err)
	}
	if err := g.decide("dmestas", s.ID, true); !errors.Is(err, ops.ErrForbidden) {
		t.Errorf("FAIL: approving it: %v", err)
	}
	if len(g.registry().made) != 0 {
		t.Errorf("FAIL: a repository was made")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The request list and notifications name the repository at its full
// address, as step 1 of the page does.
func TestTheSummaryNamesTheNewRepositoryWithItsNamespace(t *testing.T) {
	a := setupSummary(agentSetupIn{Name: "n", Kind: "push", Repos: "fresh", NewRepo: true, Namespace: "acme"})
	b := setupSummary(agentSetupIn{Name: "n", Kind: "push", Repos: "fresh", NewRepo: true})
	if !strings.Contains(a, "acme/fresh") || strings.Contains(b, "/") {
		t.Errorf("FAIL: summaries %q and %q", a, b)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}