package main
import (
"path/filepath"
"strings"
"testing"
"craftdesign.group/quarry/internal/oltp"
)
// A site admin with no explicit repo_role rows must still read as
// "the fleet is yours": GrantsFor carries the "" marker me.feed keys
// on. This is the dashboard-was-empty regression (2026-08-21).
func TestGrantsForCarriesSiteAdminMarker(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)
}
st := accountStore{db: db}
admin, err := st.GrantsFor("root")
if err != nil {
t.Fatal(err)
}
if admin[""] != "admin" {
t.Fatalf("site admin marker missing: %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. A site admin demoting a repository's last admin is warned,
// never refused — GuardCaps's s-holder contract, through the seam — and
// the write happens.
func TestGuardedGrantWarnsOnLastAdmin(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)
}
warn, err := st.Grant("root", "alice", "alpha", "developer")
if err != nil || !strings.Contains(warn, "no admin") {
t.Fatalf("FAIL: grant: warn=%q err=%v", warn, err)
}
if caps, _ := db.CapsOf("alice", "alpha"); caps != oltp.Write.Caps() {
t.Fatalf("FAIL: the warned grant was not written: alice holds %q", caps)
}
if err := db.Grant("alice", "alpha", oltp.RepoAdmin); err != nil {
t.Fatal(err)
}
if warn, err := st.Revoke("root", "alice", "alpha"); err != nil || warn == "" {
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 warned and the grant and revoke are written")
}