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)
}
}
// The routes that turn another server's word into letters: the peer sync,
// a repointed upstream, a team owner, and a repository put under a team.
yes := true
for _, c := range []struct {
what string
op string
in any
}{
{"fossil users sync", "repo.fossil.users.sync", fossilUsersSyncIn{Repo: "suit"}},
{"a new upstream", "mirror.set", mirrorSetIn{Repo: "suit", URL: "https://evil.example/r/suit", Every: 3600}},
{"a team owner", "team.member", teamMemberIn{Name: "grove", Account: "jva", Owner: &yes}},
{"a repository under a team", "team.repo.add", teamRepoIn{Name: "grove", Repo: "suit"}},
{"a repository accepted under a team", "team.repo.offer.accept", teamRepoIn{Name: "grove", Repo: "suit"}},
} {
if _, err := r.Invoke(tctx, c.op, c.in); browserOnly(t, err) == nil {
t.Errorf("FAIL: %s on a login token: %v", c.what, err)
}
}
// The same upstream with another interval is ordinary; so is a member who
// is not an owner. The gate with no mirror store fails closed.
d2 := d
d2.Mirrors = fixedMirror{url: "https://up.example/r/suit"}
r2 := ops.NewRegistry()
if err := RegisterAll(r2, d2); err != nil {
t.Fatal(err)
}
// Asked of the gate itself: the call that passes it would go on to run
// against a store this test does not build.
desc, _ := r2.Lookup("mirror.set")
if err := d2.hardStopGate(tctx, desc, mirrorSetIn{Repo: "suit", URL: "https://up.example/r/suit", Every: 7200}); err != nil {
t.Errorf("FAIL: the same upstream with a new interval was refused: %v", err)
}
if err := d2.hardStopGate(tctx, desc, mirrorSetIn{Repo: "suit", URL: "https://evil.example/r/suit", Every: 7200}); browserOnly(t, err) == nil {
t.Errorf("FAIL: a different upstream was allowed with a mirror store")
}
if _, err := r.Invoke(tctx, "team.member", teamMemberIn{Name: "grove", Account: "jva", Caps: "oi"}); browserOnly(t, err) != nil {
t.Errorf("FAIL: an ordinary team member was refused")
}
// 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")
}
}
// fixedMirror is a mirror store that holds one upstream.
type fixedMirror struct {
MirrorStore
url string
}
func (m fixedMirror) MirrorFor(string) (Mirror, bool, error) {
return Mirror{URL: m.url, Enabled: true}, true, nil
}