package api
import (
"context"
"path/filepath"
"testing"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
// By token, the flag answers only for a site token asking about its
// own account (RFC 0021, Forge agents); any other token, or a site
// token asked about somebody else, is no site admin.
func TestATokenIsASiteAdminOnlyAsASiteToken(t *testing.T) {
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{"zeitgeist", "root"} {
if err := db.AddAccount(who, "a-long-enough-password", true); err != nil {
t.Fatal(err)
}
}
d := Deps{Accounts: acctAdapter{db}}
on := func(site bool) context.Context {
return ops.WithToken(ops.WithUser(context.Background(), "zeitgeist"), ops.TokenAuth{ID: "T1",
Caps: func(string) ops.Caps { return oltp.CapSet("") }, Site: func() bool { return site }})
}
if !d.isSiteAdmin(on(true), "zeitgeist") {
t.Errorf("FAIL: a site token is not its account's site admin")
}
if d.isSiteAdmin(on(false), "zeitgeist") {
t.Errorf("FAIL: a token without site is a site admin")
}
if d.isSiteAdmin(on(true), "root") {
t.Errorf("FAIL: a site token answered for another account's flag")
}
plain := ops.WithToken(ops.WithUser(context.Background(), "zeitgeist"), ops.TokenAuth{ID: "T2",
Caps: func(string) ops.Caps { return oltp.CapSet("") }})
if d.isSiteAdmin(plain, "zeitgeist") {
t.Errorf("FAIL: a token with no Site is a site admin")
}
}