Skip to content
quarry Artifact [8a12409823]
Login

Artifact [8a12409823]

Artifact 8a124098231ad358428b9474f9995d1570f3b72bc8d8d11719765af7b1534496:


package api

import (
	"errors"
	"reflect"
	"strings"
	"testing"

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

func browserOnly(t *testing.T, err error) *ops.Refusal {
	t.Helper()
	var ref *ops.Refusal
	if !errors.As(err, &ref) || ref.Code != browserOnlyCode || !errors.Is(err, ops.ErrForbidden) || ref.Fields["next"] == "" {
		return nil
	}
	return ref
}

// What stays with the person at a browser is refused to their login token,
// each with a next pointing at the web page.
func TestALoginTokenIsRefusedTheBrowserOnlyActs(t *testing.T) {
	g := newStartRig(t)
	_, value := g.loggedIn("dmestas", "mac")
	tok, ok := g.db.ResolveToken("dmestas", value, "api")
	if !ok {
		t.Fatal("FAIL: no token")
	}
	tctx := ops.WithToken(ops.WithUser(t.Context(), "dmestas"), ops.TokenAuth{ID: tok.ID, Name: tok.Name, Login: tok.Has("login"),
		Caps: func(repo string) ops.Caps { return g.db.TokenCaps(tok, repo) }, Reaches: tok.Reaches})
	for name, c := range map[string]struct {
		op   string
		in   any
		next string
	}{
		"branch protection":  {"branch.protection.set", branchProtectionSetIn{Repo: "suit", Branch: "trunk", Owners: []string{"dmestas"}}, "/r/suit/settings"},
		"required checks":    {"ci.checks.set", checkRuleSetIn{Repo: "suit", Branch: "trunk"}, "/r/suit/settings"},
		"an accept override": {"landing.accept", landingSayIn{Repo: "suit", ID: "abcd", Override: "ship it"}, "/r/suit/landings"},
		"a delete":           {"repo.delete", repoDeleteIn{Name: "suit", Confirm: "suit"}, ""},
		"a remove":           {"repo.remove", repoRemoveIn{Name: "suit"}, ""},
		"a hand-on":          {"repo.claim", repoClaimIn{Repo: "suit", Account: "jva"}, "/r/suit/settings"},
	} {
		_, err := g.r.Invoke(tctx, c.op, c.in)
		ref := browserOnly(t, err)
		if ref == nil {
			t.Errorf("FAIL: %s on a login token: %v", name, err)
			continue
		}
		if c.next != "" && !strings.HasSuffix(ref.Fields["next"], c.next) {
			t.Errorf("FAIL: %s: next is %q, want it to end %q", name, ref.Fields["next"], c.next)
		}
		// The signed-in person is not stopped by the gate.
		if _, perr := g.r.Invoke(asUser("dmestas"), c.op, c.in); browserOnly(t, perr) != nil {
			t.Errorf("FAIL: %s refused to the person signed in", name)
		}
	}
	// Every site-admin command is refused to it too.
	n := 0
	for _, desc := range g.r.All() {
		if desc.Auth != ops.Admin || desc.Kind != ops.Command {
			continue
		}
		n++
		arg := reflect.ValueOf(desc.NewIn()).Elem().Interface()
		if _, err := g.r.Invoke(tctx, desc.Name, arg); browserOnly(t, err) == nil {
			t.Errorf("FAIL: site-admin %s on a login token: %v", desc.Name, err)
		}
	}
	if n == 0 {
		t.Errorf("FAIL: no site-admin command was tried")
	}
	// Every op that hands out a secret is refused too, found by what it
	// returns and not by its name; the three the review named are among them.
	minting := map[string]bool{}
	for _, desc := range g.r.All() {
		if desc.Kind != ops.Command || !(desc.HasOnceSecret() || desc.Name == "me.signin-link") {
			continue
		}
		minting[desc.Name] = true
		arg := reflect.ValueOf(desc.NewIn()).Elem().Interface()
		if _, err := g.r.Invoke(tctx, desc.Name, arg); browserOnly(t, err) == nil {
			t.Errorf("FAIL: %s, which hands out a credential, on a login token: %v", desc.Name, err)
		}
	}
	for _, name := range []string{"ci.token.new", "ci.worker.token.new", "ci.runner.code.new", "agent.token.new", "agent.token.reissue", "me.sync.token", "me.signin-link", "account.invite"} {
		if !minting[name] {
			t.Errorf("FAIL: %s is not among the credential-minting ops the gate found", name)
		}
	}
	// An ordinary call is not a hard stop: an accept without an override.
	if _, err := g.r.Invoke(tctx, "landing.accept", landingSayIn{Repo: "suit", ID: "abcd"}); browserOnly(t, err) != nil {
		t.Errorf("FAIL: a plain accept was refused as browser-only")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Only a login token is held to the table: a token that holds its letters
// on a repository keeps using them, and a forge agent's site reach is by
// design.
func TestTheBrowserOnlyGateLeavesOtherTokensAlone(t *testing.T) {
	g := newStartRig(t)
	_, err := g.r.Invoke(tokenCtx("dmestas-bot"), "landing.accept", landingSayIn{Repo: "suit", ID: "abcd", Override: "x"})
	if browserOnly(t, err) != nil {
		t.Errorf("FAIL: an agent's token got the person's browser-only refusal")
	}
	plain := ops.WithToken(ops.WithUser(t.Context(), "dmestas"), ops.TokenAuth{ID: "T", Caps: func(string) ops.Caps { return oltp.CapSet("a") }})
	if _, err := g.r.Invoke(plain, "branch.protection.set", branchProtectionSetIn{Repo: "suit", Branch: "trunk"}); browserOnly(t, err) != nil {
		t.Errorf("FAIL: a token that is not a login got the refusal")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The page's sentence is made from the table the gate refuses by.
func TestTheLoginSentenceNamesEveryStopInTheTable(t *testing.T) {
	sentence := loginSentence("mac", "dmestas")
	for _, h := range hardStops {
		if !strings.Contains(sentence, h.Words) {
			t.Errorf("FAIL: the sentence leaves out %q", h.Words)
		}
	}
	if !strings.Contains(sentence, "mac") || !strings.Contains(sentence, "dmestas") {
		t.Errorf("FAIL: the sentence names no machine or person")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A login token cannot hand another account admin-class letters, by any
// door that gives letters; ordinary grants stay open to it.
func TestALoginTokenCannotGrantAdminRightsToAnotherAccount(t *testing.T) {
	g := newStartRig(t)
	_, value := g.loggedIn("dmestas", "mac")
	tok, _ := g.db.ResolveToken("dmestas", value, "api")
	tctx := ops.WithToken(ops.WithUser(t.Context(), "dmestas"), ops.TokenAuth{ID: tok.ID, Name: tok.Name, Login: true,
		Caps: func(repo string) ops.Caps { return g.db.TokenCaps(tok, repo) }, Reaches: tok.Reaches})
	d := g.deps
	d.FossilUsers = g.db
	r := ops.NewRegistry()
	if err := RegisterAll(r, d); err != nil {
		t.Fatal(err)
	}
	if _, _, err := g.db.ReplaceFossilUsers("suit", []oltp.FossilUser{{Login: "boss", Caps: "as"}, {Login: "dev", Caps: "oi"}}); err != nil {
		t.Fatal(err)
	}
	for _, c := range []struct {
		op       string
		ordinary any
		admin    any
	}{
		{"account.grant", accountGrantIn{Name: "jva", Repo: "suit", Role: "developer"}, accountGrantIn{Name: "jva", Repo: "suit", Role: "admin"}},
		{"account.caps", accountCapsIn{Account: "jva", Repo: "suit", Caps: "oi"}, accountCapsIn{Account: "jva", Repo: "suit", Caps: "oia"}},
		{"account.caps (site letter)", accountCapsIn{Account: "jva", Repo: "suit", Caps: "o"}, accountCapsIn{Account: "jva", Repo: "suit", Caps: "s"}},
		{"agent.grant", agentGrantIn{Agent: "dmestas-bot", Repo: "suit", Role: "developer"}, agentGrantIn{Agent: "dmestas-bot", Repo: "suit", Role: "admin"}},
		{"agent.grant (caps)", agentGrantIn{Agent: "dmestas-bot", Repo: "suit", Caps: "oi"}, agentGrantIn{Agent: "dmestas-bot", Repo: "suit", Caps: "a"}},
		{"repo.category.set", categorySetIn{Repo: "suit", Category: "developer", Caps: "oi"}, categorySetIn{Repo: "suit", Category: "developer", Caps: "oia"}},
		{"team.member", teamMemberIn{Name: "grove", Account: "jva", Caps: "oi"}, teamMemberIn{Name: "grove", Account: "jva", Caps: "a"}},
		{"repo.fossil.users.link", fossilUserLinkIn{Repo: "suit", Login: "dev", Account: "jva"}, fossilUserLinkIn{Repo: "suit", Login: "boss", Account: "jva"}},
	} {
		if _, err := r.Invoke(tctx, c.op[:strings.IndexAny(c.op+" ", " ")], c.admin); browserOnly(t, err) == nil {
			t.Errorf("FAIL: %s: an admin grant on a login token: %v", c.op, err)
		}
		if _, err := r.Invoke(tctx, c.op[:strings.IndexAny(c.op+" ", " ")], c.ordinary); browserOnly(t, err) != nil {
			t.Errorf("FAIL: %s: an ordinary grant was refused as browser-only", c.op)
		}
	}
	// An unlink grants nothing; a purge grant is an admin power, its revoke is not.
	if _, err := r.Invoke(tctx, "repo.fossil.users.link", fossilUserLinkIn{Repo: "suit", Login: "boss"}); browserOnly(t, err) != nil {
		t.Errorf("FAIL: an unlink was refused")
	}
	if _, err := r.Invoke(tctx, "purge.grant", purgeGrantIn{Repo: "suit", Account: "jva"}); browserOnly(t, err) == nil {
		t.Errorf("FAIL: a purge grant on a login token: %v", err)
	}
	if _, err := r.Invoke(tctx, "purge.grant", purgeGrantIn{Repo: "suit", Account: "jva", Revoke: true}); browserOnly(t, err) != nil {
		t.Errorf("FAIL: a purge revoke was refused")
	}
	// Signed in, the same admin grant is not the gate's to refuse.
	if _, err := r.Invoke(asUser("dmestas"), "account.grant", accountGrantIn{Name: "jva", Repo: "suit", Role: "admin"}); browserOnly(t, err) != nil {
		t.Errorf("FAIL: the person signed in was stopped by the gate")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}