Files
minstrel/internal/api/admin_users_test.go
T
bvandeusenandClaude Opus 5.5 e1f270362d
release / go (push) Successful in 2m7s
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m30s
release / android (push) Successful in 4m39s
release / Build signed APK (push) Successful in 5m10s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 29s
release / Verify release artifacts (tag releases only) (push) Skipped
chore(release): everything that ships points at GitHub and GHCR (#7897)
- Module path: github.com/Fabled-Sword/minstrel, in go.mod, every
  import and the Dockerfile's version ldflags.
- buildinfo.ProjectURL, the contact outside services see in Minstrel's
  User-Agent: https://github.com/Fabled-Sword/minstrel.
- README's compose example pulls ghcr.io/fabled-sword/minstrel:latest.
- docs/security.md sends problem reports to the GitHub issues.
- The demo-library stack builds Minstrel from the checkout, since :dev
  is not published to GHCR.
- hygiene.go's same-site example uses example.com names.

The workbench CI (.gitea/, ci/, export-ignored) still builds and
publishes :dev to the private registry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:28:16 -05:00

293 lines
9.5 KiB
Go

package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/go-chi/chi/v5"
"golang.org/x/crypto/bcrypt"
"github.com/Fabled-Sword/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)
// U2 additions:
admin.Post("/users", h.handleAdminCreateUser)
admin.Delete("/users/{id}", h.handleAdminDeleteUser)
admin.Post("/users/{id}/reset-password", h.handleAdminResetPassword)
})
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())
}
}
func TestAdminCreateUser_Happy(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, "creator", "pw", true)
body := `{"username":"newuser1","password":"abcd1234","is_admin":false}`
req := httptest.NewRequest(http.MethodPost, "/api/admin/users", 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 resp adminUserView
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
if resp.Username != "newuser1" || resp.IsAdmin {
t.Errorf("response unexpected: %+v", resp)
}
}
func TestAdminCreateUser_DuplicateUsername_409(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, "duper", "pw", true)
seedUser(t, pool, "existing", "pw", false)
// seedUser prefixes usernames with dbtest.TestUserPrefix, so the
// row above is "test-existing"; POST that exact name to actually
// collide (stays test-prefixed for ResetDB).
body := `{"username":"test-existing","password":"abcd1234"}`
req := httptest.NewRequest(http.MethodPost, "/api/admin/users", bytes.NewReader([]byte(body)))
req = withUser(req, admin)
rec := httptest.NewRecorder()
newAdminUsersRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusConflict {
t.Errorf("status = %d, want 409", rec.Code)
}
}
func TestAdminDeleteUser_Happy(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, "delcaller", "pw", true)
target := seedUser(t, pool, "deltarget", "pw", false)
req := httptest.NewRequest(http.MethodDelete, "/api/admin/users/"+uuidToString(target.ID), nil)
req = withUser(req, admin)
rec := httptest.NewRecorder()
newAdminUsersRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusNoContent {
t.Errorf("status = %d, want 204", rec.Code)
}
var count int
if err := pool.QueryRow(context.Background(),
"SELECT count(*) FROM users WHERE id = $1", target.ID).Scan(&count); err != nil {
t.Fatalf("verify: %v", err)
}
if count != 0 {
t.Errorf("user still exists after delete (count=%d)", count)
}
}
func TestAdminDeleteUser_LastAdmin_Refused(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)
}
soleAdmin := seedUser(t, pool, "soleadmin", "pw", true)
req := httptest.NewRequest(http.MethodDelete, "/api/admin/users/"+uuidToString(soleAdmin.ID), nil)
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)", rec.Code)
}
}
func TestAdminResetPassword_Happy(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, "rcaller", "pw", true)
target := seedUser(t, pool, "rtarget", "oldpw1234", false)
body := `{"password":"newpassword1"}`
req := httptest.NewRequest(http.MethodPost, "/api/admin/users/"+uuidToString(target.ID)+"/reset-password",
bytes.NewReader([]byte(body)))
req = withUser(req, admin)
rec := httptest.NewRecorder()
newAdminUsersRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusNoContent {
t.Errorf("status = %d, want 204; body=%s", rec.Code, rec.Body.String())
}
// Old password should no longer match.
var hash string
if err := pool.QueryRow(context.Background(),
"SELECT password_hash FROM users WHERE id = $1", target.ID).Scan(&hash); err != nil {
t.Fatalf("read hash: %v", err)
}
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte("oldpw1234")); err == nil {
t.Errorf("old password still matches; reset did nothing")
}
}
func TestAdminResetPassword_TooShort_400(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, "rsadm", "pw", true)
target := seedUser(t, pool, "rstgt", "pw", false)
body := `{"password":"abc"}`
req := httptest.NewRequest(http.MethodPost, "/api/admin/users/"+uuidToString(target.ID)+"/reset-password",
bytes.NewReader([]byte(body)))
req = withUser(req, admin)
rec := httptest.NewRecorder()
newAdminUsersRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400", rec.Code)
}
}
func TestAdminResetPassword_SignsOutSubsonicApps(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, "rsubadm", "pw", true)
target := seedUser(t, pool, "rsubtgt", "oldpw1234", false)
giveSubsonicPassword(t, h, target)
before, _ := subsonicCredentials(t, h, target)
req := httptest.NewRequest(http.MethodPost, "/api/admin/users/"+uuidToString(target.ID)+"/reset-password",
bytes.NewReader([]byte(`{"password":"newpassword1"}`)))
rec := httptest.NewRecorder()
newAdminUsersRouter(h).ServeHTTP(rec, withUser(req, admin))
if rec.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204; body=%s", rec.Code, rec.Body.String())
}
assertSubsonicSignedOut(t, h, target, before)
}