Files
minstrel/internal/api/admin_users_test.go
T
bvandeusen bd362ab384 feat(server/m7-user-mgmt): admin endpoints (invites, users, promote/demote)
Five admin endpoints under existing RequireAdmin middleware:

- GET /api/admin/invites — list active + recently-redeemed
- POST /api/admin/invites — generate 24h invite, returns
  {token, expires_at, ...}. Audits ActionInviteCreate.
- DELETE /api/admin/invites/{token} — revoke unredeemed invite.
  Audits ActionInviteRevoke.
- GET /api/admin/users — list all users (id, username,
  display_name, is_admin, created_at).
- PUT /api/admin/users/{id}/admin — toggle is_admin with
  last-admin guard. Audits ActionPromoteAdmin / ActionDemoteAdmin.

Last-admin guard counts admins, refuses demotion of the sole
admin with 409 'last_admin'. Race window between count and update
is acceptable for v1 — worst case is 'no admins left,' which the
env-driven bootstrap or CLI reset can recover from. Common path
('admin demotes themselves') is now blocked.

Adds ListUsers, CountAdmins, UpdateUserAdmin sqlc queries to
users.sql.

Tests cover: invite create/list/delete round-trip, non-admin gets
403, user list, promote happy path, last-admin demotion refused,
two-admins demotion allowed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 12:01:16 -04:00

126 lines
3.7 KiB
Go

package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/go-chi/chi/v5"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
)
func newAdminUsersRouter(h *handlers) chi.Router {
r := chi.NewRouter()
r.Route("/api/admin", func(admin chi.Router) {
admin.Use(auth.RequireAdmin())
admin.Get("/users", h.handleAdminListUsers)
admin.Put("/users/{id}/admin", h.handleUpdateUserAdmin)
})
return r
}
func TestAdminUsers_List(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
admin := seedUser(t, pool, "listadmin", "pw", true)
req := httptest.NewRequest(http.MethodGet, "/api/admin/users", nil)
req = withUser(req, admin)
rec := httptest.NewRecorder()
newAdminUsersRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
}
var resp struct {
Users []struct{ Username string } `json:"users"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
if len(resp.Users) == 0 {
t.Errorf("users list is empty; expected at least the seeded admin")
}
}
func TestAdminUsers_Promote(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
admin := seedUser(t, pool, "promadmin", "pw", true)
target := seedUser(t, pool, "promtarget", "pw", false)
body := `{"is_admin": true}`
req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(target.ID)+"/admin",
bytes.NewReader([]byte(body)))
req = withUser(req, admin)
rec := httptest.NewRecorder()
newAdminUsersRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
}
var isAdmin bool
if err := pool.QueryRow(context.Background(),
"SELECT is_admin FROM users WHERE id = $1", target.ID).Scan(&isAdmin); err != nil {
t.Fatalf("verify: %v", err)
}
if !isAdmin {
t.Errorf("target not promoted")
}
}
func TestAdminUsers_Demote_LastAdmin_Refused(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
// Reset to ensure exactly one admin exists.
if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil {
t.Fatalf("reset: %v", err)
}
soleAdmin := seedUser(t, pool, "soleadmin", "pw", true)
body := `{"is_admin": false}`
req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(soleAdmin.ID)+"/admin",
bytes.NewReader([]byte(body)))
req = withUser(req, soleAdmin)
rec := httptest.NewRecorder()
newAdminUsersRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusConflict {
t.Errorf("status = %d, want 409 (last_admin guard)", rec.Code)
}
}
func TestAdminUsers_Demote_OtherAdmin_Allowed(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil {
t.Fatalf("reset: %v", err)
}
caller := seedUser(t, pool, "caller", "pw", true)
target := seedUser(t, pool, "targetadmin", "pw", true)
body := `{"is_admin": false}`
req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(target.ID)+"/admin",
bytes.NewReader([]byte(body)))
req = withUser(req, caller)
rec := httptest.NewRecorder()
newAdminUsersRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d, want 200 (two admins exist; demoting one is fine); body=%s", rec.Code, rec.Body.String())
}
}