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
- 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>
300 lines
8.9 KiB
Go
300 lines
8.9 KiB
Go
package api
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"github.com/Fabled-Sword/minstrel/internal/apierror"
|
|
"github.com/Fabled-Sword/minstrel/internal/audit"
|
|
"github.com/Fabled-Sword/minstrel/internal/auth"
|
|
"github.com/Fabled-Sword/minstrel/internal/db"
|
|
"github.com/Fabled-Sword/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"`
|
|
DebugModeEnabled bool `json:"debug_mode_enabled"`
|
|
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 {
|
|
writeErrWithLog(w, h.logger, "admin: list users failed", apierror.Internal(err))
|
|
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,
|
|
DebugModeEnabled: row.DebugModeEnabled,
|
|
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 := requireUser(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
targetID, ok := requireURLUUID(w, r, "id")
|
|
if !ok {
|
|
return
|
|
}
|
|
var req updateUserAdminReq
|
|
if !decodeBody(w, r, &req) {
|
|
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 {
|
|
writeErrWithLog(w, h.logger, "admin: count admins failed", apierror.Internal(err))
|
|
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 {
|
|
writeErrWithLog(w, h.logger, "admin: get user failed", apierror.Internal(err))
|
|
return
|
|
}
|
|
if current.IsAdmin && count <= 1 {
|
|
writeErr(w, apierror.Conflict("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 {
|
|
writeErrWithLog(w, h.logger, "admin: update user admin failed", apierror.Internal(err))
|
|
return
|
|
}
|
|
|
|
action := audit.ActionPromoteAdmin
|
|
if !req.IsAdmin {
|
|
action = audit.ActionDemoteAdmin
|
|
}
|
|
audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, action, nil)
|
|
|
|
writeJSON(w, http.StatusOK, adminUserView{
|
|
ID: uuidToString(updated.ID),
|
|
Username: updated.Username,
|
|
DisplayName: updated.DisplayName,
|
|
IsAdmin: updated.IsAdmin,
|
|
DebugModeEnabled: updated.DebugModeEnabled,
|
|
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 := requireUser(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
var req adminCreateUserReq
|
|
if !decodeBody(w, r, &req) {
|
|
return
|
|
}
|
|
if !usernameRe.MatchString(req.Username) {
|
|
writeErr(w, apierror.BadRequest("username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen"))
|
|
return
|
|
}
|
|
if !checkNewPassword(w, req.Password) {
|
|
return
|
|
}
|
|
|
|
hash, err := hashPassword(req.Password)
|
|
if err != nil {
|
|
writeErrWithLog(w, h.logger, "admin create user: hash failed", apierror.Internal(err))
|
|
return
|
|
}
|
|
apiToken, err := auth.MintSessionToken()
|
|
if err != nil {
|
|
writeErrWithLog(w, h.logger, "admin create user: mint token failed", apierror.Internal(err))
|
|
return
|
|
}
|
|
|
|
q := dbq.New(h.pool)
|
|
user, err := q.CreateUserAdmin(r.Context(), dbq.CreateUserAdminParams{
|
|
Username: req.Username,
|
|
PasswordHash: string(hash),
|
|
ApiTokenHash: auth.HashAPIToken(apiToken),
|
|
IsAdmin: req.IsAdmin,
|
|
DisplayName: req.DisplayName,
|
|
})
|
|
if err != nil {
|
|
if db.IsUniqueViolation(err) {
|
|
writeErr(w, apierror.Conflict("username_taken", "username is already taken"))
|
|
return
|
|
}
|
|
writeErrWithLog(w, h.logger, "admin create user: insert failed", apierror.Internal(err))
|
|
return
|
|
}
|
|
|
|
audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, user.ID, audit.ActionCreateUserAdmin,
|
|
map[string]any{"is_admin": req.IsAdmin})
|
|
|
|
writeJSON(w, http.StatusOK, adminUserView{
|
|
ID: uuidToString(user.ID),
|
|
Username: user.Username,
|
|
DisplayName: user.DisplayName,
|
|
IsAdmin: user.IsAdmin,
|
|
DebugModeEnabled: user.DebugModeEnabled,
|
|
CreatedAt: user.CreatedAt.Time.UTC().Format(time.RFC3339),
|
|
})
|
|
}
|
|
|
|
// --- Admin user delete -----------------------------------------------------
|
|
|
|
func (h *handlers) handleAdminDeleteUser(w http.ResponseWriter, r *http.Request) {
|
|
caller, ok := requireUser(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
q := dbq.New(h.pool)
|
|
target, apiErr := resolveByID(r, "id", q.GetUserByID, "user")
|
|
if apiErr != nil {
|
|
writeErr(w, apiErr)
|
|
return
|
|
}
|
|
|
|
// Last-admin guard: refuse delete if target is the only admin.
|
|
if target.IsAdmin {
|
|
count, cerr := q.CountAdmins(r.Context())
|
|
if cerr != nil {
|
|
writeErrWithLog(w, h.logger, "admin delete user: count admins failed", apierror.Internal(cerr))
|
|
return
|
|
}
|
|
if count <= 1 {
|
|
writeErr(w, apierror.Conflict("last_admin",
|
|
"can't delete the last admin — promote someone else first"))
|
|
return
|
|
}
|
|
}
|
|
|
|
if err := q.DeleteUser(r.Context(), target.ID); err != nil {
|
|
writeErrWithLog(w, h.logger, "admin delete user: delete failed", apierror.Internal(err))
|
|
return
|
|
}
|
|
|
|
audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, target.ID, audit.ActionDeleteUser,
|
|
map[string]any{"username": target.Username, "was_admin": target.IsAdmin})
|
|
|
|
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 := requireUser(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
targetID, ok := requireURLUUID(w, r, "id")
|
|
if !ok {
|
|
return
|
|
}
|
|
var req adminResetPasswordReq
|
|
if !decodeBody(w, r, &req) {
|
|
return
|
|
}
|
|
if !checkNewPassword(w, req.Password) {
|
|
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, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: ""})
|
|
return
|
|
}
|
|
writeErrWithLog(w, h.logger, "admin reset password: lookup failed", apierror.Internal(err))
|
|
return
|
|
}
|
|
|
|
hash, err := hashPassword(req.Password)
|
|
if err != nil {
|
|
writeErrWithLog(w, h.logger, "admin reset password: hash failed", apierror.Internal(err))
|
|
return
|
|
}
|
|
if err := q.ResetUserPassword(r.Context(), dbq.ResetUserPasswordParams{
|
|
ID: targetID,
|
|
PasswordHash: string(hash),
|
|
}); err != nil {
|
|
writeErrWithLog(w, h.logger, "admin reset password: update failed", apierror.Internal(err))
|
|
return
|
|
}
|
|
|
|
// The target's existing sessions end with the old password, and so does
|
|
// their Subsonic apps' access (signOutSubsonicApps). An admin resetting
|
|
// their own password keeps the session they're using, the same as a
|
|
// self-service change.
|
|
sessID, ownSession := auth.SessionIDFromContext(r.Context())
|
|
if targetID == caller.ID && ownSession {
|
|
_, err = q.DeleteOtherSessionsForUser(r.Context(), dbq.DeleteOtherSessionsForUserParams{UserID: targetID, ID: sessID})
|
|
} else {
|
|
_, err = q.DeleteSessionsForUser(r.Context(), targetID)
|
|
}
|
|
if err != nil {
|
|
h.logger.Error("admin reset password: revoke sessions failed", "err", err)
|
|
}
|
|
if err := h.signOutSubsonicApps(r.Context(), targetID); err != nil {
|
|
h.logger.Error("admin reset password: sign out subsonic apps failed", "err", err)
|
|
}
|
|
|
|
audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, audit.ActionPasswordResetAdmin, nil)
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|