Files
pages/internal/store/groups_backend_test.go
T
2026-11-15 05:47:14 +09:00

368 lines
14 KiB
Go

package store
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"sync"
"testing"
)
type adminBackendFixture struct {
t *testing.T
s *Store
domains, groups map[string]string
}
func newAdminBackendFixture(t *testing.T, backend storeSQLBackend) *adminBackendFixture {
t.Helper()
s := testNamespaceStore(t, backend)
if backend == storePostgreSQL {
if err := s.ensurePostgreSQLAuthFoundation(context.Background()); err != nil {
t.Fatal(err)
}
}
c, err := s.GetDefaultCampus()
if err != nil {
t.Fatal(err)
}
err = s.CreateCampus("outside-admin-test", "Outside", "en", "standalone", "outside-admin.test", true)
if err != nil {
t.Fatal(err)
}
var outside string
if err := s.DB.QueryRow(`SELECT uuid FROM campuses WHERE name='outside-admin-test'`).Scan(&outside); err != nil {
t.Fatal(err)
}
f := &adminBackendFixture{t: t, s: s, domains: map[string]string{}, groups: map[string]string{}}
for _, name := range []string{"a", "b", "c", "outside"} {
campus := c.UUID
if name == "outside" {
campus = outside
}
f.domains[name] = seedNamespaceDomain(t, s, campus, "admin-"+name, "admin-"+name).UUID
}
if err := s.EnsureBuiltinAdminGroups(); err != nil {
t.Fatal(err)
}
for name, domain := range f.domains {
group, err := s.GroupByName(domain, "campus_admin")
if err != nil {
t.Fatal(err)
}
byID, err := s.GroupByUUID(domain, group.UUID)
if err != nil || byID.UUID != group.UUID || !byID.InheritMembers {
t.Fatal("group lookup mismatch", err)
}
f.groups[name] = group.UUID
}
return f
}
// Test fixture SQL is owned and uses explicit format slots; production queries
// do not run through a SQL string rewriting layer.
func (f *adminBackendFixture) query(query string, n int) string {
p := make([]any, n)
for i := range p {
p[i] = f.s.sqlParam(i + 1)
}
return fmt.Sprintf(query, p...)
}
func (f *adminBackendFixture) exec(query string, args ...any) {
f.t.Helper()
if _, err := f.s.DB.Exec(f.query(query, len(args)), args...); err != nil {
f.t.Fatal(err)
}
}
func (f *adminBackendFixture) row(query string, args ...any) *sql.Row {
return f.s.DB.QueryRow(f.query(query, len(args)), args...)
}
func (f *adminBackendFixture) local(domain, user string) string {
f.t.Helper()
f.exec(`INSERT INTO principals(uuid,display_name,created_at_ms,updated_at_ms) VALUES(%s,%s,1,1) ON CONFLICT DO NOTHING`, user, user)
f.exec(`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,subject,created_at_ms) VALUES(%s,%s,'password',%s,1) ON CONFLICT DO NOTHING`, user, user, user)
f.exec(`INSERT INTO domain_memberships(uuid,domain_uuid,principal_uuid,created_at_ms) VALUES(%s,%s,%s,1) ON CONFLICT DO NOTHING`, domain+":"+user, f.domains[domain], user)
var id string
if err := f.row(`SELECT uuid FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid=%s`, f.domains[domain], user).Scan(&id); err != nil {
f.t.Fatal(err)
}
return id
}
func (f *adminBackendFixture) add(domain, user, role string) {
f.t.Helper()
if err := f.s.AddGroupMemberByUsername(f.domains[domain], f.groups[domain], user, role); err != nil {
f.t.Fatal(err)
}
}
func (f *adminBackendFixture) allowed(domain, user string, want bool) {
f.t.Helper()
got, err := f.s.IsBuiltinGroupAdminContext(context.Background(), f.domains[domain], user, "campus_admin")
if err != nil || got != want {
f.t.Fatalf("%s/%s allowed=%v want=%v error=%v", domain, user, got, want, err)
}
}
func (f *adminBackendFixture) membership(domain, user string, want bool) {
f.t.Helper()
var got bool
if err := f.row(`SELECT EXISTS(SELECT 1 FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid=%s)`, f.domains[domain], user).Scan(&got); err != nil || got != want {
f.t.Fatalf("membership %s/%s=%v want=%v error=%v", domain, user, got, want, err)
}
}
func forAdminBackends(t *testing.T, fn func(*testing.T, *adminBackendFixture)) {
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} {
t.Run(fmt.Sprint(b), func(t *testing.T) { fn(t, newAdminBackendFixture(t, b)) })
}
}
func TestAdminInheritanceBackendRevocation(t *testing.T) {
forAdminBackends(t, func(t *testing.T, f *adminBackendFixture) {
f.local("a", "alice")
f.add("a", "alice", "owner")
f.allowed("b", "alice", true)
f.membership("outside", "alice", false)
var before string
if err := f.row(`SELECT uuid FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid='alice'`, f.domains["b"]).Scan(&before); err != nil {
t.Fatal(err)
}
// Session API port is separate. Synthetic storage verifies revocation here.
f.exec(`INSERT INTO auth_sessions(uuid,token_hash,principal_uuid,domain_uuid,auth_time_ms,expires_at_ms,last_seen_at_ms) VALUES('session','synthetic-hash','alice',%s,1,9999999999999,1)`, f.domains["b"])
for range 3 {
if err := f.s.ProjectCampusAdminMemberships(); err != nil {
t.Fatal(err)
}
}
var after string
if err := f.row(`SELECT uuid FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid='alice'`, f.domains["b"]).Scan(&after); err != nil || before != after {
t.Fatal("projection changed membership identity", err)
}
if err := f.s.SetCampusAdminInheritance(f.groups["a"], false); err != nil {
t.Fatal(err)
}
f.allowed("a", "alice", true)
f.allowed("b", "alice", false)
f.membership("b", "alice", false)
f.membership("c", "alice", false)
var revoked int64
if err := f.row(`SELECT revoked_at_ms FROM auth_sessions WHERE uuid='session'`).Scan(&revoked); err != nil || revoked <= 0 {
t.Fatal("session not revoked", err)
}
if err := f.s.SetCampusAdminInheritance(f.groups["a"], true); err != nil {
t.Fatal(err)
}
f.allowed("b", "alice", true)
var stillRevoked int64
if err := f.row(`SELECT revoked_at_ms FROM auth_sessions WHERE uuid='session'`).Scan(&stillRevoked); err != nil || stillRevoked != revoked {
t.Fatal("revoked session resurrected", err)
}
})
}
func TestAdminInheritanceBackendIndependentRoots(t *testing.T) {
forAdminBackends(t, func(t *testing.T, f *adminBackendFixture) {
f.local("a", "alice")
f.local("b", "alice")
f.add("b", "alice", "member")
f.add("a", "alice", "owner")
f.allowed("b", "alice", true)
if err := f.s.SetCampusAdminInheritance(f.groups["a"], false); err != nil {
t.Fatal(err)
}
if role := f.s.GroupMemberRole(f.groups["b"], "alice"); role != "member" {
t.Fatalf("weaker local role lost: %s", role)
}
f.membership("b", "alice", true)
f.allowed("b", "alice", false)
f.add("b", "alice", "owner")
if err := f.s.SetCampusAdminInheritance(f.groups["a"], true); err != nil {
t.Fatal(err)
}
if err := f.s.SetCampusAdminInheritance(f.groups["a"], false); err != nil {
t.Fatal(err)
}
f.allowed("c", "alice", true)
if err := f.s.SetCampusAdminInheritance(f.groups["b"], false); err != nil {
t.Fatal(err)
}
f.allowed("c", "alice", false)
f.membership("c", "alice", false)
})
}
func TestAdminInheritanceBackendPreservesBinding(t *testing.T) {
forAdminBackends(t, func(t *testing.T, f *adminBackendFixture) {
f.local("a", "alice")
f.add("a", "alice", "owner")
f.exec(`INSERT INTO auth_roles(uuid,domain_uuid,name,created_at_ms) VALUES('reader',%s,'reader',1)`, f.domains["b"])
f.exec(`INSERT INTO auth_role_bindings(membership_uuid,role_uuid,created_at_ms) SELECT uuid,'reader',1 FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid='alice'`, f.domains["b"])
f.exec(`INSERT INTO auth_sessions(uuid,token_hash,principal_uuid,domain_uuid,auth_time_ms,expires_at_ms,last_seen_at_ms) VALUES('session','synthetic-hash','alice',%s,1,9999999999999,1)`, f.domains["b"])
if err := f.s.SetCampusAdminInheritance(f.groups["a"], false); err != nil {
t.Fatal(err)
}
f.membership("b", "alice", true)
f.allowed("b", "alice", false)
var revoked int64
if err := f.row(`SELECT revoked_at_ms FROM auth_sessions WHERE uuid='session'`).Scan(&revoked); err != nil || revoked != 0 {
t.Fatal("independent session revoked", err)
}
})
}
func TestAdminInheritanceBackendGuardsAndConcurrency(t *testing.T) {
forAdminBackends(t, func(t *testing.T, f *adminBackendFixture) {
alice := f.local("a", "alice")
bob := f.local("a", "bob")
f.add("a", "alice", "owner")
f.add("a", "bob", "owner")
if err := f.s.AddGroupMemberByUsername(f.domains["a"], f.groups["a"], "alice", "member"); err == nil {
t.Fatal("owner downgrade accepted")
}
var derived string
if err := f.row(`SELECT uuid FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid='alice'`, f.domains["b"]).Scan(&derived); err != nil {
t.Fatal(err)
}
if err := f.s.RemoveGroupMember(f.groups["b"], derived); err == nil {
t.Fatal("inherited-only grant removable at destination")
}
if err := f.s.RemoveGroupMemberWithAuthority(f.groups["a"], alice, false); err == nil {
t.Fatal("manager removed owner")
}
results := make(chan error, 2)
var wg sync.WaitGroup
for _, id := range []string{alice, bob} {
wg.Add(1)
go func(id string) {
defer wg.Done()
peer := &Store{DB: f.s.DB, sqlBackend: f.s.sqlBackend}
results <- peer.RemoveGroupMember(f.groups["a"], id)
}(id)
}
wg.Wait()
close(results)
succeeded := 0
for err := range results {
if err == nil {
succeeded++
} else if !strings.Contains(err.Error(), "remaining local owner") {
t.Fatal(err)
}
}
if succeeded != 1 {
t.Fatalf("successful removals=%d want 1", succeeded)
}
var count int
if err := f.row(`SELECT count(*) FROM campus_admin_grants WHERE group_uuid=%s AND member_role='owner' AND source='local'`, f.groups["a"]).Scan(&count); err != nil || count != 1 {
t.Fatal("last owner lost", err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := f.s.SetCampusAdminInheritanceContext(ctx, f.groups["a"], false); !errors.Is(err, context.Canceled) {
t.Fatalf("cancellation lost: %v", err)
}
})
}
func TestAdminInheritanceBackendRollback(t *testing.T) {
forAdminBackends(t, func(t *testing.T, f *adminBackendFixture) {
f.local("a", "alice")
f.add("a", "alice", "owner")
alice := f.local("a", "alice")
f.local("a", "bob")
f.add("a", "bob", "owner")
f.local("a", "carol")
// All projection statements precede this final missing-column failure.
f.exec(`ALTER TABLE auth_sessions RENAME COLUMN revoked_at_ms TO unavailable_revocation`)
if err := f.s.SetCampusAdminInheritance(f.groups["a"], false); err == nil {
t.Fatal("injected revocation failure accepted")
}
if err := f.s.RemoveGroupMember(f.groups["a"], alice); err == nil {
t.Fatal("failed removal accepted")
}
if err := f.s.AddGroupMemberByUsername(f.domains["a"], f.groups["a"], "carol", "owner"); err == nil {
t.Fatal("failed addition accepted")
}
var inherits int
if err := f.row(`SELECT inherit_members FROM groups WHERE uuid=%s`, f.groups["a"]).Scan(&inherits); err != nil || inherits != 1 {
t.Fatal("source mutation not rolled back", err)
}
f.allowed("b", "alice", true)
f.membership("b", "alice", true)
f.allowed("a", "alice", true)
f.allowed("a", "carol", false)
f.membership("b", "carol", false)
})
}
func TestAdminInheritanceBackendBootstrapDoesNotReseed(t *testing.T) {
forAdminBackends(t, func(t *testing.T, f *adminBackendFixture) {
alice := f.local("a", "alice")
f.local("a", "bob")
f.add("a", "bob", "owner")
f.exec(`INSERT INTO auth_roles(uuid,domain_uuid,name,created_at_ms) VALUES('administrator',%s,'administrator',1)`, f.domains["a"])
f.exec(`INSERT INTO auth_role_bindings(membership_uuid,role_uuid,created_at_ms) VALUES(%s,'administrator',1)`, alice)
f.exec(`INSERT INTO auth_capability_grants(uuid,role_uuid,capability,target_type,target_id,created_at_ms) VALUES('manage','administrator','manage','domain',%s,1)`, f.domains["a"])
if err := f.s.EnsureBuiltinAdminGroups(); err != nil {
t.Fatal(err)
}
f.allowed("b", "alice", true)
if err := f.s.RemoveGroupMember(f.groups["a"], alice); err != nil {
t.Fatal(err)
}
for range 2 {
if err := f.s.EnsureBuiltinAdminGroups(); err != nil {
t.Fatal(err)
}
}
f.allowed("a", "alice", false)
f.allowed("b", "alice", false)
if !f.s.IsBuiltinGroupAdmin(f.domains["a"], "alice", "domain_admin") {
t.Fatal("independent Domain administrator lost")
}
// Malformed cross-domain role bindings or grants targeting another
// Domain must not be upgraded into local administrative group ownership.
mallory := f.local("b", "mallory")
f.exec(`INSERT INTO auth_role_bindings(membership_uuid,role_uuid,created_at_ms) VALUES(%s,'administrator',1)`, mallory)
f.exec(`INSERT INTO auth_roles(uuid,domain_uuid,name,created_at_ms) VALUES('foreign-target',%s,'foreign-target',1)`, f.domains["b"])
f.exec(`INSERT INTO auth_role_bindings(membership_uuid,role_uuid,created_at_ms) VALUES(%s,'foreign-target',1)`, mallory)
f.exec(`INSERT INTO auth_capability_grants(uuid,role_uuid,capability,target_type,target_id,created_at_ms) VALUES('foreign-manage','foreign-target','manage','domain',%s,1)`, f.domains["a"])
if err := f.s.EnsureBuiltinAdminGroups(); err != nil {
t.Fatal(err)
}
f.allowed("b", "mallory", false)
if f.s.IsBuiltinGroupAdmin(f.domains["b"], "mallory", "domain_admin") {
t.Fatal("foreign role/target became local administrator")
}
})
}
func TestAdminInheritanceBackendSuspension(t *testing.T) {
forAdminBackends(t, func(t *testing.T, f *adminBackendFixture) {
f.local("a", "alice")
f.local("b", "alice")
f.exec(`UPDATE domain_memberships SET state='suspended' WHERE domain_uuid=%s AND principal_uuid='alice'`, f.domains["b"])
f.add("a", "alice", "owner")
f.allowed("b", "alice", false)
f.membership("b", "alice", true)
f.allowed("c", "alice", true)
for _, state := range []string{"readonly", "suspended", "quarantined"} {
f.exec(`UPDATE principals SET state=%s WHERE uuid='alice'`, state)
if err := f.s.ProjectCampusAdminMemberships(); err != nil {
t.Fatal(err)
}
f.membership("c", "alice", false)
f.exec(`UPDATE principals SET state='active' WHERE uuid='alice'`)
if err := f.s.ProjectCampusAdminMemberships(); err != nil {
t.Fatal(err)
}
f.allowed("c", "alice", true)
}
f.exec(`UPDATE domains SET enabled=0 WHERE uuid=%s`, f.domains["a"])
if err := f.s.ProjectCampusAdminMemberships(); err != nil {
t.Fatal(err)
}
f.membership("c", "alice", false)
f.membership("b", "alice", true)
})
}