Files
minstrel/internal/api/admin_users.go
T
bvandeusen 9ed576a029 fix(ci): pgconn import path + reset-password token type + SMTP label
Three CI fixes from the U1+U2+U3 push:

- internal/api/admin_users.go imported the standalone
  github.com/jackc/pgconn — that module isn't in go.sum and
  go vet caught it. Switch to github.com/jackc/pgx/v5/pgconn
  (the path used elsewhere in the package, e.g. auth_register.go
  and me_profile.go).

- /reset-password/[token] dereferenced page.params.token without
  the undefined narrowing svelte-kit's typegen requires. Coalesce
  to '' on read and reject empty token at submit time with a
  clear error.

- /admin/integrations SMTP card had a label without an associated
  control as the TLS row's leading column header. Switched to a
  span — the actual checkbox lives in the wrapping label below it.
2026-05-07 17:48:44 -04:00

381 lines
12 KiB
Go

package api
import (
"encoding/json"
"errors"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"golang.org/x/crypto/bcrypt"
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
type adminUserView struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName *string `json:"display_name"`
IsAdmin bool `json:"is_admin"`
AutoApproveRequests bool `json:"auto_approve_requests"`
CreatedAt string `json:"created_at"`
}
type listUsersResp struct {
Users []adminUserView `json:"users"`
}
func (h *handlers) handleAdminListUsers(w http.ResponseWriter, r *http.Request) {
q := dbq.New(h.pool)
rows, err := q.ListUsers(r.Context())
if err != nil {
h.logger.Error("admin: list users failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
out := make([]adminUserView, 0, len(rows))
for _, row := range rows {
v := adminUserView{
ID: uuidToString(row.ID),
Username: row.Username,
DisplayName: row.DisplayName,
IsAdmin: row.IsAdmin,
AutoApproveRequests: row.AutoApproveRequests,
CreatedAt: row.CreatedAt.Time.UTC().Format(time.RFC3339),
}
out = append(out, v)
}
writeJSON(w, http.StatusOK, listUsersResp{Users: out})
}
type updateUserAdminReq struct {
IsAdmin bool `json:"is_admin"`
}
func (h *handlers) handleUpdateUserAdmin(w http.ResponseWriter, r *http.Request) {
caller, ok := auth.UserFromContext(r.Context())
if !ok {
writeErr(w, http.StatusUnauthorized, "auth_required", "")
return
}
targetID, ok := parseUUID(chi.URLParam(r, "id"))
if !ok {
writeErr(w, http.StatusBadRequest, "invalid_id", "")
return
}
var req updateUserAdminReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, "invalid_body", "")
return
}
q := dbq.New(h.pool)
// Last-admin guard: if demoting (is_admin=false) AND target is
// currently the only admin, refuse. The check has a race window
// (between counting and updating, another admin could be demoted)
// but the worst-case outcome is "no admins left," which the
// operator can recover from via the env-driven bootstrap or the
// CLI password-reset path. The check still prevents the common
// path of "admin demotes themselves and loses access."
if !req.IsAdmin {
count, err := q.CountAdmins(r.Context())
if err != nil {
h.logger.Error("admin: count admins failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
// We need to know whether the target is currently an admin.
// If they're already not-admin, the demote is a no-op (we
// allow it). If they ARE admin and they're the last one, refuse.
current, err := q.GetUserByID(r.Context(), targetID)
if err != nil {
h.logger.Error("admin: get user failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
if current.IsAdmin && count <= 1 {
writeErr(w, http.StatusConflict, "last_admin",
"can't remove the last admin — promote someone else first")
return
}
}
updated, err := q.UpdateUserAdmin(r.Context(), dbq.UpdateUserAdminParams{
ID: targetID,
IsAdmin: req.IsAdmin,
})
if err != nil {
h.logger.Error("admin: update user admin failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
action := audit.ActionPromoteAdmin
if !req.IsAdmin {
action = audit.ActionDemoteAdmin
}
if err := audit.Write(r.Context(), h.pool, caller.ID, targetID, action, nil); err != nil {
h.logger.Warn("admin: promote/demote audit failed", "err", err)
}
writeJSON(w, http.StatusOK, adminUserView{
ID: uuidToString(updated.ID),
Username: updated.Username,
DisplayName: updated.DisplayName,
IsAdmin: updated.IsAdmin,
AutoApproveRequests: updated.AutoApproveRequests,
CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339),
})
}
// --- Admin user create -----------------------------------------------------
type adminCreateUserReq struct {
Username string `json:"username"`
Password string `json:"password"`
DisplayName *string `json:"display_name"`
IsAdmin bool `json:"is_admin"`
}
func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request) {
caller, ok := auth.UserFromContext(r.Context())
if !ok {
writeErr(w, http.StatusUnauthorized, "auth_required", "")
return
}
var req adminCreateUserReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, "invalid_body", "")
return
}
if !usernameRe.MatchString(req.Username) {
writeErr(w, http.StatusBadRequest, "username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen")
return
}
if len(req.Password) < minPasswordLength {
writeErr(w, http.StatusBadRequest, "password_too_short", "password must be at least 8 chars")
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
h.logger.Error("admin create user: hash failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
apiToken, err := auth.MintSessionToken()
if err != nil {
h.logger.Error("admin create user: mint token failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
q := dbq.New(h.pool)
user, err := q.CreateUserAdmin(r.Context(), dbq.CreateUserAdminParams{
Username: req.Username,
PasswordHash: string(hash),
ApiToken: apiToken,
IsAdmin: req.IsAdmin,
DisplayName: req.DisplayName,
})
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation {
writeErr(w, http.StatusConflict, "username_taken", "")
return
}
h.logger.Error("admin create user: insert failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
if err := audit.Write(r.Context(), h.pool, caller.ID, user.ID, audit.ActionCreateUserAdmin,
map[string]any{"is_admin": req.IsAdmin}); err != nil {
h.logger.Warn("admin create user: audit failed", "err", err)
}
writeJSON(w, http.StatusOK, adminUserView{
ID: uuidToString(user.ID),
Username: user.Username,
DisplayName: user.DisplayName,
IsAdmin: user.IsAdmin,
AutoApproveRequests: user.AutoApproveRequests,
CreatedAt: user.CreatedAt.Time.UTC().Format(time.RFC3339),
})
}
// --- Admin user delete -----------------------------------------------------
func (h *handlers) handleAdminDeleteUser(w http.ResponseWriter, r *http.Request) {
caller, ok := auth.UserFromContext(r.Context())
if !ok {
writeErr(w, http.StatusUnauthorized, "auth_required", "")
return
}
targetID, ok := parseUUID(chi.URLParam(r, "id"))
if !ok {
writeErr(w, http.StatusBadRequest, "invalid_id", "")
return
}
q := dbq.New(h.pool)
target, err := q.GetUserByID(r.Context(), targetID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
writeErr(w, http.StatusNotFound, "not_found", "")
return
}
h.logger.Error("admin delete user: lookup failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
// Last-admin guard: refuse delete if target is the only admin.
if target.IsAdmin {
count, cerr := q.CountAdmins(r.Context())
if cerr != nil {
h.logger.Error("admin delete user: count admins failed", "err", cerr)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
if count <= 1 {
writeErr(w, http.StatusConflict, "last_admin",
"can't delete the last admin — promote someone else first")
return
}
}
if err := q.DeleteUser(r.Context(), targetID); err != nil {
h.logger.Error("admin delete user: delete failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
if err := audit.Write(r.Context(), h.pool, caller.ID, targetID, audit.ActionDeleteUser,
map[string]any{"username": target.Username, "was_admin": target.IsAdmin}); err != nil {
h.logger.Warn("admin delete user: audit failed", "err", err)
}
w.WriteHeader(http.StatusNoContent)
}
// --- Admin password reset --------------------------------------------------
type adminResetPasswordReq struct {
Password string `json:"password"`
}
func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Request) {
caller, ok := auth.UserFromContext(r.Context())
if !ok {
writeErr(w, http.StatusUnauthorized, "auth_required", "")
return
}
targetID, ok := parseUUID(chi.URLParam(r, "id"))
if !ok {
writeErr(w, http.StatusBadRequest, "invalid_id", "")
return
}
var req adminResetPasswordReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, "invalid_body", "")
return
}
if len(req.Password) < minPasswordLength {
writeErr(w, http.StatusBadRequest, "password_too_short", "password must be at least 8 chars")
return
}
q := dbq.New(h.pool)
// Verify target exists for a useful 404.
if _, err := q.GetUserByID(r.Context(), targetID); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
writeErr(w, http.StatusNotFound, "not_found", "")
return
}
h.logger.Error("admin reset password: lookup failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
h.logger.Error("admin reset password: hash failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
if err := q.ResetUserPassword(r.Context(), dbq.ResetUserPasswordParams{
ID: targetID,
PasswordHash: string(hash),
}); err != nil {
h.logger.Error("admin reset password: update failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
if err := audit.Write(r.Context(), h.pool, caller.ID, targetID, audit.ActionPasswordResetAdmin, nil); err != nil {
h.logger.Warn("admin reset password: audit failed", "err", err)
}
w.WriteHeader(http.StatusNoContent)
}
// --- Admin auto-approve toggle ---------------------------------------------
type adminAutoApproveReq struct {
AutoApprove bool `json:"auto_approve"`
}
func (h *handlers) handleAdminAutoApproveToggle(w http.ResponseWriter, r *http.Request) {
caller, ok := auth.UserFromContext(r.Context())
if !ok {
writeErr(w, http.StatusUnauthorized, "auth_required", "")
return
}
targetID, ok := parseUUID(chi.URLParam(r, "id"))
if !ok {
writeErr(w, http.StatusBadRequest, "invalid_id", "")
return
}
var req adminAutoApproveReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, "invalid_body", "")
return
}
q := dbq.New(h.pool)
updated, err := q.UpdateUserAutoApprove(r.Context(), dbq.UpdateUserAutoApproveParams{
ID: targetID,
AutoApproveRequests: req.AutoApprove,
})
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
writeErr(w, http.StatusNotFound, "not_found", "")
return
}
h.logger.Error("admin auto-approve: update failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
if err := audit.Write(r.Context(), h.pool, caller.ID, targetID, audit.ActionAutoApproveToggle,
map[string]any{"auto_approve": req.AutoApprove}); err != nil {
h.logger.Warn("admin auto-approve: audit failed", "err", err)
}
writeJSON(w, http.StatusOK, adminUserView{
ID: uuidToString(updated.ID),
Username: updated.Username,
DisplayName: updated.DisplayName,
IsAdmin: updated.IsAdmin,
AutoApproveRequests: updated.AutoApproveRequests,
CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339),
})
}