package main
import (
"path/filepath"
"testing"
"craftdesign.group/quarry/internal/oltp"
)
// A site admin's grants are their grant rows and nothing more (#318):
// no "" marker standing for "the fleet is yours", which is what handed
// an admin with no grants every repository's feed.
func TestGrantsForCarriesNoSiteAdminMarker(t *testing.T) {
db, err := oltp.Open(filepath.Join(t.TempDir(), "oltp.db"))
if err != nil {
t.Fatal(err)
}
defer db.Close()
if err := db.AddAccount("root", "pw12345678", true); err != nil {
t.Fatal(err)
}
if err := db.AddAccount("plain", "pw12345678", false); err != nil {
t.Fatal(err)
}
if err := db.Grant("plain", "alpha", oltp.Write); err != nil {
t.Fatal(err)
}
if err := db.Grant("root", "beta", oltp.Read); err != nil {
t.Fatal(err)
}
st := accountStore{db: db}
admin, err := st.GrantsFor("root")
if err != nil {
t.Fatal(err)
}
if len(admin) != 1 || admin["beta"] != "reader" {
t.Fatalf("site admin's grants are not their rows: %v", admin)
}
user, err := st.GrantsFor("plain")
if err != nil {
t.Fatal(err)
}
if _, has := user[""]; has {
t.Fatalf("plain account grew the marker: %v", user)
}
if user["alpha"] != "developer" {
t.Fatalf("explicit grant lost: %v", user)
}
}
// Audit follow-up (ticket ed5bdd89c39a): the API's grant path is
// guarded, and a site admin is held to the guard like anyone (#318):
// demoting a repository's last admin is refused and nothing is written.
func TestGuardedGrantRefusesTheLastAdmin(t *testing.T) {
db, err := oltp.Open(filepath.Join(t.TempDir(), "oltp.db"))
if err != nil {
t.Fatal(err)
}
defer db.Close()
st := accountStore{db: db}
if err := db.AddAccount("root", "pw12345678", true); err != nil {
t.Fatal(err)
}
if err := db.AddAccount("alice", "pw12345678", false); err != nil {
t.Fatal(err)
}
if err := db.Grant("alice", "alpha", oltp.RepoAdmin); err != nil {
t.Fatal(err)
}
if warn, err := st.Grant("root", "alice", "alpha", "developer"); !oltp.IsRefusal(err) {
t.Fatalf("FAIL: grant: warn=%q err=%v", warn, err)
}
if caps, _ := db.CapsOf("alice", "alpha"); caps != oltp.RepoAdmin.Caps() {
t.Fatalf("FAIL: the refused grant was written: alice holds %q", caps)
}
if warn, err := st.Revoke("root", "alice", "alpha"); !oltp.IsRefusal(err) {
t.Fatalf("FAIL: revoke: warn=%q err=%v", warn, err)
}
if _, err := st.Grant("root", "alice", "alpha", "sorcerer"); err == nil {
t.Fatal("FAIL: unknown role must error")
}
t.Log("ok: the site admin is refused the last admin and nothing is written")
}