Skip to content
quarry Artifact [502dd556d2]
Login

Artifact [502dd556d2]

Artifact 502dd556d229c58f8f25fef2d68750c6b0d57a0a0971efb195939ae42ce4de35:


package api

import (
	"context"
	"errors"
	"net/http/httptest"
	"strings"
	"testing"

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

// A URL names a repository OWNER/NAME; the forge keys it by NAME. A token
// minted with the URL's spelling is stored under the key and reaches it.
func TestATokenMintedByAddressIsStoredUnderTheKeyAndReachesIt(t *testing.T) {
	c := newCredRig(t)
	out, err := c.r.Invoke(asUser("dmestas"), "agent.token.new", agentTokenNewIn{Agent: "fbot", Name: "n", Scopes: "api", Repos: "dmestas/test"})
	if err != nil {
		t.Fatalf("FAIL: minting by address: %v", err)
	}
	toks, _ := c.db.Tokens("fbot")
	if len(toks) != 1 || strings.Join(toks[0].Repos, ",") != "test" {
		t.Fatalf("FAIL: stored repos: %+v", toks)
	}
	_ = out
	if !toks[0].Reaches("test") {
		t.Errorf("FAIL: the token does not reach the repository")
	}
	// The bare key is accepted too, and the list collapses repeats.
	if _, err := c.r.Invoke(asUser("dmestas"), "agent.token.new", agentTokenNewIn{Agent: "fbot", Name: "m", Scopes: "api", Repos: "test, dmestas/test"}); err != nil {
		t.Fatalf("FAIL: minting by key: %v", err)
	}
	toks, _ = c.db.Tokens("fbot")
	for _, tk := range toks {
		if strings.Join(tk.Repos, ",") != "test" {
			t.Errorf("FAIL: stored repos: %+v", tk.Repos)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// agent.token.repos resolves the same way.
func TestTokenReposByAddressStoresTheKey(t *testing.T) {
	c := newCredRig(t)
	if _, err := c.r.Invoke(asUser("dmestas"), "agent.token.new", agentTokenNewIn{Agent: "fbot", Name: "n", Scopes: "api"}); err != nil {
		t.Fatal(err)
	}
	toks, _ := c.db.Tokens("fbot")
	if _, err := c.r.Invoke(asUser("dmestas"), "agent.token.repos", agentTokenReposIn{Agent: "fbot", ID: toks[0].ID, Repos: "dmestas/test"}); err != nil {
		t.Fatalf("FAIL: %v", err)
	}
	toks, _ = c.db.Tokens("fbot")
	if strings.Join(toks[0].Repos, ",") != "test" {
		t.Errorf("FAIL: stored repos: %+v", toks[0].Repos)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A name that is no repository is refused at mint, with a 400 that names
// it, and nothing is stored.
func TestAnUnknownRepositoryIsRefusedAtMint(t *testing.T) {
	c := newCredRig(t)
	for _, name := range []string{"dmestas/nope", "nope", "other/test"} {
		_, err := c.r.Invoke(asUser("dmestas"), "agent.token.new", agentTokenNewIn{Agent: "fbot", Name: "n", Scopes: "api", Repos: name})
		if !errors.Is(err, ops.ErrInvalid) || !strings.Contains(err.Error(), name) {
			t.Errorf("FAIL: %q: %v", name, err)
		}
	}
	if toks, _ := c.db.Tokens("fbot"); len(toks) != 0 {
		t.Errorf("FAIL: a token was stored: %+v", toks)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// An asked mint, and a plan step, name the repository by key once
// approved: the credentials summary shows the key.
func TestAnAskedMintShowsTheResolvedName(t *testing.T) {
	c := newCredRig(t)
	id := c.ask("fbot", "dmestas", "/api/v1/agents/tokens", `{"agent":"fbot","name":"one","scopes":"api","repos":"dmestas/test"}`)
	out, err := c.r.Invoke(asUser("fbot"), "signoff.get", signOffGetIn{ID: id})
	if err != nil {
		t.Fatal(err)
	}
	g := out.(signOffGetOut)
	if len(g.Credentials) != 1 || strings.Join(g.Credentials[0].Repos, ",") != "test" {
		t.Errorf("FAIL: credentials: %+v", g.Credentials)
	}
	row, _, err := c.db.SignOffByID(id)
	if err != nil || !strings.Contains(row.Input, `"repos":"test"`) {
		t.Errorf("FAIL: stored input %q: %v", row.Input, err)
	}

	po, err := c.r.Invoke(asUser("fbot"), planOp, planIn{Title: "t", Steps: []planStepIn{
		{Op: "agent.token.new", Input: []byte(`{"agent":"fbot","name":"b","scopes":"api","repos":"dmestas/test"}`)},
	}})
	if err != nil {
		t.Fatalf("FAIL: plan: %v", err)
	}
	pid := po.(planOut).SignOff.ID
	c.approve("dmestas", pid)
	pg, err := c.r.Invoke(asUser("fbot"), "signoff.get", signOffGetIn{ID: pid})
	if err != nil {
		t.Fatal(err)
	}
	if p := pg.(signOffGetOut); len(p.Credentials) != 1 || strings.Join(p.Credentials[0].Repos, ",") != "test" {
		t.Errorf("FAIL: plan credentials: %+v", p.Credentials)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A plan step naming OWNER/NAME is judged, and recorded, as NAME: the
// stored plan carries the key, so judging and running see one value.
func TestAPlanStepByAddressIsJudgedAsTheKey(t *testing.T) {
	c := newCredRig(t)
	po, err := c.r.Invoke(asUser("fbot"), planOp, planIn{Title: "t", Steps: []planStepIn{
		{Op: "agent.token.new", Input: []byte(`{"agent":"fbot","name":"b","scopes":"api","repos":"dmestas/test"}`)},
	}})
	if err != nil {
		t.Fatalf("FAIL: plan: %v", err)
	}
	row, _, err := c.db.SignOffByID(po.(planOut).SignOff.ID)
	if err != nil || strings.Contains(row.Input, "dmestas/test") || !strings.Contains(row.Input, `"repos":"test"`) {
		t.Errorf("FAIL: stored plan %q: %v", row.Input, err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// askRaw files an ask as jva-bot and answers what came back, unapproved.
func (c *credRig) askRaw(path, body string) (int, string, []oltp.SignOff) {
	c.t.Helper()
	ctx := ops.WithToken(ops.WithUser(context.Background(), "jva-bot"), ops.TokenAuth{ID: "T",
		Caps: func(string) ops.Caps { return oltp.CapSet("") }})
	req := httptest.NewRequest("POST", path, strings.NewReader(body)).WithContext(ctx)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Quarry-Ask", "for a test")
	w := httptest.NewRecorder()
	c.h.ServeHTTP(w, req)
	rows, _ := c.db.SignOffsFor("jva", 50)
	return w.Code, w.Body.String(), rows
}

// Asking never says more than refusing: an unreadable private repository
// and one that does not exist are answered alike, and filed as nothing.
func TestAskingByAddressRevealsNoPrivateRepository(t *testing.T) {
	c := newCredRig(t)
	c.unreadable = "secret-k"
	body := func(repos string) string {
		return `{"agent":"jva-bot","name":"n","scopes":"api","repos":"` + repos + `"}`
	}
	sc, sb, srows := c.askRaw("/api/v1/agents/tokens", body("alice/secret"))
	uc, ub, urows := c.askRaw("/api/v1/agents/tokens", body("alice/nope"))
	if sc != uc || strings.ReplaceAll(sb, "secret", "X") != strings.ReplaceAll(ub, "nope", "X") || len(srows) != len(urows) {
		t.Errorf("FAIL: unreadable and unknown differ: %d %q / %d %q", sc, sb, uc, ub)
	}
	if len(srows) != 0 || strings.Contains(sb, "secret-k") {
		t.Errorf("FAIL: a request was filed or a key leaked: %q %v", sb, srows)
	}
	// A token's repos change is judged the same.
	toks, _ := c.db.Tokens("jva-bot")
	if len(toks) == 0 {
		if _, err := c.r.Invoke(asUser("jva"), "agent.token.new", agentTokenNewIn{Agent: "jva-bot", Name: "t", Scopes: "api"}); err != nil {
			t.Fatal(err)
		}
		toks, _ = c.db.Tokens("jva-bot")
	}
	rc, rb, rrows := c.askRaw("/api/v1/agents/tokens/repos", `{"agent":"jva-bot","id":"`+toks[0].ID+`","repos":"alice/secret"}`)
	if rc != sc || len(rrows) != 0 || strings.Contains(rb, "secret-k") {
		t.Errorf("FAIL: repos change: %d %q %v", rc, rb, rrows)
	}
	// A readable private repository is asked, by key.
	oc, _, orows := c.askRaw("/api/v1/agents/tokens", body("alice/open"))
	if oc != 202 || len(orows) != 1 || !strings.Contains(orows[len(orows)-1].Input, `"repos":"open-k"`) {
		t.Errorf("FAIL: a readable repository: %d %v", oc, orows)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A grant by OWNER/NAME on a held repository is refused as the key is.
func TestAGrantByAddressOnAHeldRepositoryIsRefused(t *testing.T) {
	c := newCredRig(t)
	c.onHold = "test"
	_, err := c.r.Invoke(asUser("dmestas"), "agent.grant", agentGrantIn{Agent: "fbot", Repo: "dmestas/test", Role: "reader"})
	if !errors.Is(err, ops.ErrForbidden) {
		t.Errorf("FAIL: grant on a held repository by address: %v", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// While the forge starts, a name is refused as an unknown one is.
func TestAStartingRepositoryIsRefusedAsUnknown(t *testing.T) {
	c := newCredRig(t)
	c.deps.Pending = func() []string { return []string{"warming"} }
	for _, name := range []string{"warming", "nope"} {
		_, err := c.deps.repoKeys(asUser("dmestas"), []string{name})
		if !errors.Is(err, ops.ErrInvalid) || !strings.Contains(err.Error(), "no repository") {
			t.Errorf("FAIL: %q: %v", name, err)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}