fix(api): every /api error answers in one envelope, so Android shows the real reason (#8002)

Three error shapes were on the wire: {"error":{"code","message"}} from
writeErr, a flat {"error":"code"} from the admin queues, playback errors
and RequireAdmin, and plain text from RequireUser's 401s. Android reads
only the first, so an admin's quarantine, duplicate or suspect-file
error, and "you're not an admin", all showed "Something went wrong."

apierror.Write is now the one writer, and api.writeErr, RequireAdmin,
RequireUser, the client-APK endpoints, the events stream, the unknown-
route 404 and the admin scan all go through it. The flat writers are
gone, and the web client drops its second branch. The admin codes keep
their names; each now carries a message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 12:43:27 -05:00
co-authored by Claude Opus 5.5
parent 125099ede2
commit 0811775af6
20 changed files with 195 additions and 182 deletions
+28 -27
View File
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/audit" "git.fabledsword.com/bvandeusen/minstrel/internal/audit"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/library" "git.fabledsword.com/bvandeusen/minstrel/internal/library"
@@ -107,7 +108,7 @@ type adminDuplicatesResponse struct {
func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request) {
limit, offset, err := parsePaging(r.URL.Query()) limit, offset, err := parsePaging(r.URL.Query())
if err != nil { if err != nil {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging") writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset"))
return return
} }
view := r.URL.Query().Get("view") view := r.URL.Query().Get("view")
@@ -115,7 +116,7 @@ func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request)
view = duplicateViewReview view = duplicateViewReview
} }
if view != duplicateViewReview && view != duplicateViewCrossRelease { if view != duplicateViewReview && view != duplicateViewCrossRelease {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_view") writeErr(w, apierror.BadRequest("invalid_view", "unknown view"))
return return
} }
ctx := r.Context() ctx := r.Context()
@@ -128,20 +129,20 @@ func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request)
sweep = duplicateSweepViewOf(last) sweep = duplicateSweepViewOf(last)
case !errors.Is(err, pgx.ErrNoRows): case !errors.Is(err, pgx.ErrNoRows):
h.logger.Error("admin: latest duplicate sweep", "err", err) h.logger.Error("admin: latest duplicate sweep", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
cov, err := h.fingerprintCoverage(ctx) cov, err := h.fingerprintCoverage(ctx)
if err != nil { if err != nil {
h.logger.Error("admin: fingerprint coverage", "err", err) h.logger.Error("admin: fingerprint coverage", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
counts, err := duplicateCounts(ctx, q) counts, err := duplicateCounts(ctx, q)
if err != nil { if err != nil {
h.logger.Error("admin: count duplicate groups", "err", err) h.logger.Error("admin: count duplicate groups", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
total := counts.Review total := counts.Review
@@ -153,7 +154,7 @@ func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request)
}) })
if err != nil { if err != nil {
h.logger.Error("admin: list duplicate groups", "err", err) h.logger.Error("admin: list duplicate groups", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
@@ -209,14 +210,14 @@ type resolvedActivityResponse struct {
func (h *handlers) handleListResolvedDuplicates(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleListResolvedDuplicates(w http.ResponseWriter, r *http.Request) {
limit, offset, err := parsePaging(r.URL.Query()) limit, offset, err := parsePaging(r.URL.Query())
if err != nil { if err != nil {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging") writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset"))
return return
} }
q := dbq.New(h.pool) q := dbq.New(h.pool)
total, err := q.CountAuditLogByActions(r.Context(), dbq.CountAuditLogByActionsParams{Actions: resolvedActions, SystemOnly: true}) total, err := q.CountAuditLogByActions(r.Context(), dbq.CountAuditLogByActionsParams{Actions: resolvedActions, SystemOnly: true})
if err != nil { if err != nil {
h.logger.Error("admin: count resolved duplicates", "err", err) h.logger.Error("admin: count resolved duplicates", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
rows, err := q.ListAuditLogByActions(r.Context(), dbq.ListAuditLogByActionsParams{ rows, err := q.ListAuditLogByActions(r.Context(), dbq.ListAuditLogByActionsParams{
@@ -224,7 +225,7 @@ func (h *handlers) handleListResolvedDuplicates(w http.ResponseWriter, r *http.R
}) })
if err != nil { if err != nil {
h.logger.Error("admin: list resolved duplicates", "err", err) h.logger.Error("admin: list resolved duplicates", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
items := make([]resolvedActivityView, 0, len(rows)) items := make([]resolvedActivityView, 0, len(rows))
@@ -320,11 +321,11 @@ func (h *handlers) handleRunDuplicateSweep(w http.ResponseWriter, _ *http.Reques
) )
if err != nil { if err != nil {
h.logger.Error("admin: start duplicate sweep", "err", err) h.logger.Error("admin: start duplicate sweep", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
if !started { if !started {
writeAdminJSONErr(w, http.StatusConflict, "sweep_in_progress") writeErr(w, apierror.Conflict("sweep_in_progress", "a duplicate sweep is already running"))
return return
} }
writeJSON(w, http.StatusAccepted, map[string]bool{"started": true}) writeJSON(w, http.StatusAccepted, map[string]bool{"started": true})
@@ -339,17 +340,17 @@ func (h *handlers) handleRunDuplicateSweep(w http.ResponseWriter, _ *http.Reques
func (h *handlers) handleDismissDuplicateGroup(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleDismissDuplicateGroup(w http.ResponseWriter, r *http.Request) {
id, ok := parseUUID(chi.URLParam(r, "id")) id, ok := parseUUID(chi.URLParam(r, "id"))
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
n, err := h.dismissDuplicateGroup(r.Context(), id) n, err := h.dismissDuplicateGroup(r.Context(), id)
if err != nil { if err != nil {
h.logger.Error("admin: dismiss duplicate group", "err", err) h.logger.Error("admin: dismiss duplicate group", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
if n == 0 { if n == 0 {
writeAdminJSONErr(w, http.StatusNotFound, "duplicate_group_not_pending") writeErr(w, apierror.New(http.StatusNotFound, "duplicate_group_not_pending", "that duplicate group is no longer waiting for a decision"))
return return
} }
writeJSON(w, http.StatusOK, map[string]string{"status": "dismissed"}) writeJSON(w, http.StatusOK, map[string]string{"status": "dismissed"})
@@ -407,18 +408,18 @@ func (h *handlers) handleMergeDuplicateGroup(w http.ResponseWriter, r *http.Requ
} }
groupID, ok := parseUUID(chi.URLParam(r, "id")) groupID, ok := parseUUID(chi.URLParam(r, "id"))
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
var body mergeDuplicateRequest var body mergeDuplicateRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, mergeRequestBodyLimit)).Decode(&body); err != nil && !errors.Is(err, io.EOF) { if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, mergeRequestBodyLimit)).Decode(&body); err != nil && !errors.Is(err, io.EOF) {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_body") writeErr(w, apierror.BadRequest("invalid_body", "invalid request body"))
return return
} }
var survivorID pgtype.UUID // invalid: keep the proposal var survivorID pgtype.UUID // invalid: keep the proposal
if body.SurvivorTrackID != "" { if body.SurvivorTrackID != "" {
if survivorID, ok = parseUUID(body.SurvivorTrackID); !ok { if survivorID, ok = parseUUID(body.SurvivorTrackID); !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
} }
@@ -432,12 +433,12 @@ func (h *handlers) handleMergeDuplicateGroup(w http.ResponseWriter, r *http.Requ
} }
switch { switch {
case errors.Is(err, library.ErrDuplicateGroupNotPending): case errors.Is(err, library.ErrDuplicateGroupNotPending):
writeAdminJSONErr(w, http.StatusNotFound, "duplicate_group_not_pending") writeErr(w, apierror.New(http.StatusNotFound, "duplicate_group_not_pending", "that duplicate group is no longer waiting for a decision"))
case errors.Is(err, library.ErrSurvivorNotInGroup): case errors.Is(err, library.ErrSurvivorNotInGroup):
writeAdminJSONErr(w, http.StatusBadRequest, "survivor_not_in_group") writeErr(w, apierror.BadRequest("survivor_not_in_group", "the copy to keep is not in this group"))
default: default:
h.logger.Error("admin: merge duplicate group", "group_id", uuidToString(groupID), "err", err) h.logger.Error("admin: merge duplicate group", "group_id", uuidToString(groupID), "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
} }
return return
} }
@@ -486,18 +487,18 @@ func (h *handlers) handleRemoveWrongSlotFiles(w http.ResponseWriter, r *http.Req
} }
groupID, ok := parseUUID(chi.URLParam(r, "id")) groupID, ok := parseUUID(chi.URLParam(r, "id"))
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
var body wrongSlotRequest var body wrongSlotRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, mergeRequestBodyLimit)).Decode(&body); err != nil && !errors.Is(err, io.EOF) { if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, mergeRequestBodyLimit)).Decode(&body); err != nil && !errors.Is(err, io.EOF) {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_body") writeErr(w, apierror.BadRequest("invalid_body", "invalid request body"))
return return
} }
var keepID pgtype.UUID // invalid: every copy goes var keepID pgtype.UUID // invalid: every copy goes
if body.KeepTrackID != "" { if body.KeepTrackID != "" {
if keepID, ok = parseUUID(body.KeepTrackID); !ok { if keepID, ok = parseUUID(body.KeepTrackID); !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
} }
@@ -511,14 +512,14 @@ func (h *handlers) handleRemoveWrongSlotFiles(w http.ResponseWriter, r *http.Req
} }
switch { switch {
case errors.Is(err, library.ErrDuplicateGroupNotPending): case errors.Is(err, library.ErrDuplicateGroupNotPending):
writeAdminJSONErr(w, http.StatusNotFound, "duplicate_group_not_pending") writeErr(w, apierror.New(http.StatusNotFound, "duplicate_group_not_pending", "that duplicate group is no longer waiting for a decision"))
case errors.Is(err, library.ErrNotWrongSlot): case errors.Is(err, library.ErrNotWrongSlot):
writeAdminJSONErr(w, http.StatusBadRequest, "not_wrong_slot") writeErr(w, apierror.BadRequest("not_wrong_slot", "this group is not a wrong-slot match"))
case errors.Is(err, library.ErrSurvivorNotInGroup): case errors.Is(err, library.ErrSurvivorNotInGroup):
writeAdminJSONErr(w, http.StatusBadRequest, "survivor_not_in_group") writeErr(w, apierror.BadRequest("survivor_not_in_group", "the copy to keep is not in this group"))
default: default:
h.logger.Error("admin: remove wrong-slot files", "group_id", uuidToString(groupID), "err", err) h.logger.Error("admin: remove wrong-slot files", "group_id", uuidToString(groupID), "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
} }
return return
} }
+11 -10
View File
@@ -9,6 +9,7 @@ import (
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/library" "git.fabledsword.com/bvandeusen/minstrel/internal/library"
"git.fabledsword.com/bvandeusen/minstrel/internal/tracks" "git.fabledsword.com/bvandeusen/minstrel/internal/tracks"
@@ -77,7 +78,7 @@ type adminMissingResponse struct {
func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Request) {
limit, offset, err := parsePaging(r.URL.Query()) limit, offset, err := parsePaging(r.URL.Query())
if err != nil { if err != nil {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging") writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset"))
return return
} }
@@ -85,7 +86,7 @@ func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Reques
total, err := q.CountMissingTracks(r.Context()) total, err := q.CountMissingTracks(r.Context())
if err != nil { if err != nil {
h.logger.Error("admin: count missing tracks", "err", err) h.logger.Error("admin: count missing tracks", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
rows, err := q.ListMissingTracks(r.Context(), dbq.ListMissingTracksParams{ rows, err := q.ListMissingTracks(r.Context(), dbq.ListMissingTracksParams{
@@ -94,7 +95,7 @@ func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Reques
}) })
if err != nil { if err != nil {
h.logger.Error("admin: list missing tracks", "err", err) h.logger.Error("admin: list missing tracks", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
@@ -185,14 +186,14 @@ func (h *handlers) handleForgetMissingTracks(w http.ResponseWriter, r *http.Requ
} }
var body forgetMissingRequest var body forgetMissingRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, forgetMissingRequestLimit)).Decode(&body); err != nil || len(body.TrackIDs) == 0 { if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, forgetMissingRequestLimit)).Decode(&body); err != nil || len(body.TrackIDs) == 0 {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_body") writeErr(w, apierror.BadRequest("invalid_body", "invalid request body"))
return return
} }
ids := make([]pgtype.UUID, 0, len(body.TrackIDs)) ids := make([]pgtype.UUID, 0, len(body.TrackIDs))
for _, raw := range body.TrackIDs { for _, raw := range body.TrackIDs {
id, ok := parseUUID(raw) id, ok := parseUUID(raw)
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
ids = append(ids, id) ids = append(ids, id)
@@ -200,14 +201,14 @@ func (h *handlers) handleForgetMissingTracks(w http.ResponseWriter, r *http.Requ
gone, err := h.tracks.ForgetTracks(r.Context(), ids, admin.ID) gone, err := h.tracks.ForgetTracks(r.Context(), ids, admin.ID)
switch { switch {
case errors.Is(err, tracks.ErrNotFound): case errors.Is(err, tracks.ErrNotFound):
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found") writeErr(w, apierror.NotFound("track"))
return return
case errors.Is(err, library.ErrTrackPresent): case errors.Is(err, library.ErrTrackPresent):
writeAdminJSONErr(w, http.StatusConflict, "track_has_file") writeErr(w, apierror.Conflict("track_has_file", "the track's file is still on disk"))
return return
case err != nil: case err != nil:
h.logger.Error("admin: forget missing tracks", "err", err) h.logger.Error("admin: forget missing tracks", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
writeJSON(w, http.StatusOK, map[string]int{"forgotten": len(gone)}) writeJSON(w, http.StatusOK, map[string]int{"forgotten": len(gone)})
@@ -230,13 +231,13 @@ func (h *handlers) handleExportMissingTracks(w http.ResponseWriter, r *http.Requ
total, err := q.CountMissingTracks(r.Context()) total, err := q.CountMissingTracks(r.Context())
if err != nil { if err != nil {
h.logger.Error("admin: count missing tracks", "err", err) h.logger.Error("admin: count missing tracks", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
rows, err := q.ListMissingTracks(r.Context(), dbq.ListMissingTracksParams{PageLimit: int32(total), PageOffset: 0}) rows, err := q.ListMissingTracks(r.Context(), dbq.ListMissingTracksParams{PageLimit: int32(total), PageOffset: 0})
if err != nil { if err != nil {
h.logger.Error("admin: list missing tracks", "err", err) h.logger.Error("admin: list missing tracks", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
w.Header().Set("Content-Type", "text/csv; charset=utf-8") w.Header().Set("Content-Type", "text/csv; charset=utf-8")
+16 -16
View File
@@ -8,6 +8,7 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth" "git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/quarantine" "git.fabledsword.com/bvandeusen/minstrel/internal/quarantine"
@@ -48,7 +49,7 @@ func (h *handlers) handleListAdminQuarantine(w http.ResponseWriter, r *http.Requ
rows, err := h.quarantine.ListAdminQueue(r.Context()) rows, err := h.quarantine.ListAdminQueue(r.Context())
if err != nil { if err != nil {
h.logger.Error("admin: list quarantine", "err", err) h.logger.Error("admin: list quarantine", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
out := make([]adminQueueRowView, 0, len(rows)) out := make([]adminQueueRowView, 0, len(rows))
@@ -90,22 +91,22 @@ type actionResultView struct {
func (h *handlers) handleResolveQuarantine(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleResolveQuarantine(w http.ResponseWriter, r *http.Request) {
admin, ok := auth.UserFromContext(r.Context()) admin, ok := auth.UserFromContext(r.Context())
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized") writeErr(w, apierror.ErrUnauthorized)
return return
} }
id, ok := parseUUID(chi.URLParam(r, "track_id")) id, ok := parseUUID(chi.URLParam(r, "track_id"))
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
action, err := h.quarantine.Resolve(r.Context(), id, admin.ID) action, err := h.quarantine.Resolve(r.Context(), id, admin.ID)
if err != nil { if err != nil {
if errors.Is(err, quarantine.ErrTrackNotFound) { if errors.Is(err, quarantine.ErrTrackNotFound) {
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found") writeErr(w, apierror.NotFound("track"))
return return
} }
h.logger.Error("admin: resolve quarantine", "err", err) h.logger.Error("admin: resolve quarantine", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
// Broadcast: affects every user who'd flagged this track. // Broadcast: affects every user who'd flagged this track.
@@ -121,18 +122,17 @@ func (h *handlers) handleResolveQuarantine(w http.ResponseWriter, r *http.Reques
func (h *handlers) handleDeleteQuarantineFile(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleDeleteQuarantineFile(w http.ResponseWriter, r *http.Request) {
admin, ok := auth.UserFromContext(r.Context()) admin, ok := auth.UserFromContext(r.Context())
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized") writeErr(w, apierror.ErrUnauthorized)
return return
} }
id, ok := parseUUID(chi.URLParam(r, "track_id")) id, ok := parseUUID(chi.URLParam(r, "track_id"))
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
action, err := h.quarantine.DeleteFile(r.Context(), id, admin.ID) action, err := h.quarantine.DeleteFile(r.Context(), id, admin.ID)
if err != nil { if err != nil {
// Written in the enveloped shape, not writeAdminJSONErr's bare code: // The message is the part that tells an admin which directory and uid.
// the message is the part that tells an admin which directory and uid.
if apiErr, ok := fileRemoveAPIError(err); ok { if apiErr, ok := fileRemoveAPIError(err); ok {
logFileRemoveFailure(h.logger, apiErr, "track_id", uuidToString(id)) logFileRemoveFailure(h.logger, apiErr, "track_id", uuidToString(id))
writeErr(w, apiErr) writeErr(w, apiErr)
@@ -140,10 +140,10 @@ func (h *handlers) handleDeleteQuarantineFile(w http.ResponseWriter, r *http.Req
} }
switch { switch {
case errors.Is(err, quarantine.ErrTrackNotFound): case errors.Is(err, quarantine.ErrTrackNotFound):
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found") writeErr(w, apierror.NotFound("track"))
default: default:
h.logger.Error("admin: delete file", "err", err) h.logger.Error("admin: delete file", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "file_delete_failed") writeErr(w, apierror.New(http.StatusInternalServerError, "file_delete_failed", "the file could not be deleted"))
} }
return return
} }
@@ -166,12 +166,12 @@ func (h *handlers) handleDeleteQuarantineFile(w http.ResponseWriter, r *http.Req
func (h *handlers) handleRemoveQuarantineFile(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleRemoveQuarantineFile(w http.ResponseWriter, r *http.Request) {
admin, ok := auth.UserFromContext(r.Context()) admin, ok := auth.UserFromContext(r.Context())
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized") writeErr(w, apierror.ErrUnauthorized)
return return
} }
id, ok := parseUUID(chi.URLParam(r, "track_id")) id, ok := parseUUID(chi.URLParam(r, "track_id"))
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
action, err := h.quarantine.RemoveFile(r.Context(), id, admin.ID) action, err := h.quarantine.RemoveFile(r.Context(), id, admin.ID)
@@ -183,10 +183,10 @@ func (h *handlers) handleRemoveQuarantineFile(w http.ResponseWriter, r *http.Req
} }
switch { switch {
case errors.Is(err, quarantine.ErrTrackNotFound): case errors.Is(err, quarantine.ErrTrackNotFound):
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found") writeErr(w, apierror.NotFound("track"))
default: default:
h.logger.Error("admin: remove reported file", "err", err) h.logger.Error("admin: remove reported file", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "file_delete_failed") writeErr(w, apierror.New(http.StatusInternalServerError, "file_delete_failed", "the file could not be deleted"))
} }
return return
} }
@@ -229,7 +229,7 @@ func (h *handlers) handleListQuarantineActions(w http.ResponseWriter, r *http.Re
rows, err := dbq.New(h.pool).ListQuarantineActions(r.Context(), limit) rows, err := dbq.New(h.pool).ListQuarantineActions(r.Context(), limit)
if err != nil { if err != nil {
h.logger.Error("admin: list actions", "err", err) h.logger.Error("admin: list actions", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
out := make([]actionLogView, 0, len(rows)) out := make([]actionLogView, 0, len(rows))
+4 -3
View File
@@ -5,6 +5,7 @@ import (
"syscall" "syscall"
"time" "time"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo" "git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/logging" "git.fabledsword.com/bvandeusen/minstrel/internal/logging"
@@ -96,7 +97,7 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request)
now, err := q.ListListeningNow(ctx) now, err := q.ListListeningNow(ctx)
if err != nil { if err != nil {
h.logger.Error("admin status: listening", "err", err) h.logger.Error("admin status: listening", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
out.Listening.Now = make([]listeningView, 0, len(now)) out.Listening.Now = make([]listeningView, 0, len(now))
@@ -111,7 +112,7 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request)
day, err := q.PlaysLastDay(ctx) day, err := q.PlaysLastDay(ctx)
if err != nil { if err != nil {
h.logger.Error("admin status: plays", "err", err) h.logger.Error("admin status: plays", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
out.Listening.PlaysDay, out.Listening.ListenersDay = day.Plays, day.Listeners out.Listening.PlaysDay, out.Listening.ListenersDay = day.Plays, day.Listeners
@@ -123,7 +124,7 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request)
lib, err := q.LibraryStatus(ctx) lib, err := q.LibraryStatus(ctx)
if err != nil { if err != nil {
h.logger.Error("admin status: library", "err", err) h.logger.Error("admin status: library", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
out.Library = libraryStatusView{Tracks: lib.Tracks, Albums: lib.Albums, Artists: lib.Artists, out.Library = libraryStatusView{Tracks: lib.Tracks, Albums: lib.Albums, Artists: lib.Artists,
+2 -1
View File
@@ -5,6 +5,7 @@ import (
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
) )
@@ -48,7 +49,7 @@ func (h *handlers) handleGetAdminSummary(w http.ResponseWriter, r *http.Request)
row, err := dbq.New(h.pool).AdminSummary(r.Context()) row, err := dbq.New(h.pool).AdminSummary(r.Context())
if err != nil { if err != nil {
h.logger.Error("admin: summary", "err", err) h.logger.Error("admin: summary", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
writeJSON(w, http.StatusOK, adminSummaryFrom(row)) writeJSON(w, http.StatusOK, adminSummaryFrom(row))
+14 -13
View File
@@ -10,6 +10,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/audit" "git.fabledsword.com/bvandeusen/minstrel/internal/audit"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/library" "git.fabledsword.com/bvandeusen/minstrel/internal/library"
@@ -62,7 +63,7 @@ type adminSuspectSourcesResponse struct {
func (h *handlers) handleListSuspectSources(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleListSuspectSources(w http.ResponseWriter, r *http.Request) {
limit, offset, err := parsePaging(r.URL.Query()) limit, offset, err := parsePaging(r.URL.Query())
if err != nil { if err != nil {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging") writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset"))
return return
} }
@@ -70,7 +71,7 @@ func (h *handlers) handleListSuspectSources(w http.ResponseWriter, r *http.Reque
total, err := q.CountSuspectSourceTracks(r.Context(), library.SuspectSourcePattern) total, err := q.CountSuspectSourceTracks(r.Context(), library.SuspectSourcePattern)
if err != nil { if err != nil {
h.logger.Error("admin: count suspect-source tracks", "err", err) h.logger.Error("admin: count suspect-source tracks", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
rows, err := q.ListSuspectSourceTracks(r.Context(), dbq.ListSuspectSourceTracksParams{ rows, err := q.ListSuspectSourceTracks(r.Context(), dbq.ListSuspectSourceTracksParams{
@@ -80,7 +81,7 @@ func (h *handlers) handleListSuspectSources(w http.ResponseWriter, r *http.Reque
}) })
if err != nil { if err != nil {
h.logger.Error("admin: list suspect-source tracks", "err", err) h.logger.Error("admin: list suspect-source tracks", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
@@ -139,26 +140,26 @@ type suspectVerdictRequest struct {
func (h *handlers) handleSetSuspectSourceVerdict(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleSetSuspectSourceVerdict(w http.ResponseWriter, r *http.Request) {
id, ok := parseUUID(chi.URLParam(r, "id")) id, ok := parseUUID(chi.URLParam(r, "id"))
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
var req suspectVerdictRequest var req suspectVerdictRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_body") writeErr(w, apierror.BadRequest("invalid_body", "invalid request body"))
return return
} }
if req.Verdict != "fine" && req.Verdict != "suspect" { if req.Verdict != "fine" && req.Verdict != "suspect" {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_verdict") writeErr(w, apierror.BadRequest("invalid_verdict", "verdict must be fine or suspect"))
return return
} }
n, err := dbq.New(h.pool).SetTrackSourceVerdict(r.Context(), dbq.SetTrackSourceVerdictParams{Verdict: req.Verdict, ID: id}) n, err := dbq.New(h.pool).SetTrackSourceVerdict(r.Context(), dbq.SetTrackSourceVerdictParams{Verdict: req.Verdict, ID: id})
if err != nil { if err != nil {
h.logger.Error("admin: set suspect-source verdict", "err", err) h.logger.Error("admin: set suspect-source verdict", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
if n == 0 { if n == 0 {
writeAdminJSONErr(w, http.StatusNotFound, "suspect_track_not_found") writeErr(w, apierror.New(http.StatusNotFound, "suspect_track_not_found", "that track is not on the suspect list"))
return return
} }
writeJSON(w, http.StatusOK, map[string]string{"verdict": req.Verdict}) writeJSON(w, http.StatusOK, map[string]string{"verdict": req.Verdict})
@@ -180,17 +181,17 @@ func (h *handlers) handleRemoveSuspectSourceFile(w http.ResponseWriter, r *http.
} }
id, ok := parseUUID(chi.URLParam(r, "id")) id, ok := parseUUID(chi.URLParam(r, "id"))
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
track, err := dbq.New(h.pool).GetTrackByID(r.Context(), id) track, err := dbq.New(h.pool).GetTrackByID(r.Context(), id)
if errors.Is(err, pgx.ErrNoRows) || (err == nil && (track.MissingSince.Valid || len(library.SourceMarkersFor(track.FilePath)) == 0)) { if errors.Is(err, pgx.ErrNoRows) || (err == nil && (track.MissingSince.Valid || len(library.SourceMarkersFor(track.FilePath)) == 0)) {
writeAdminJSONErr(w, http.StatusNotFound, "suspect_track_not_found") writeErr(w, apierror.New(http.StatusNotFound, "suspect_track_not_found", "that track is not on the suspect list"))
return return
} }
if err != nil { if err != nil {
h.logger.Error("admin: read suspect track", "err", err) h.logger.Error("admin: read suspect track", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
if _, err := library.RemoveFile(r.Context(), h.pool, h.logger, library.RemoveFileParams{ if _, err := library.RemoveFile(r.Context(), h.pool, h.logger, library.RemoveFileParams{
@@ -202,11 +203,11 @@ func (h *handlers) handleRemoveSuspectSourceFile(w http.ResponseWriter, r *http.
return return
} }
if errors.Is(err, library.ErrTrackNotFound) { if errors.Is(err, library.ErrTrackNotFound) {
writeAdminJSONErr(w, http.StatusNotFound, "suspect_track_not_found") writeErr(w, apierror.New(http.StatusNotFound, "suspect_track_not_found", "that track is not on the suspect list"))
return return
} }
h.logger.Error("admin: remove suspect file", "err", err) h.logger.Error("admin: remove suspect file", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "file_delete_failed") writeErr(w, apierror.New(http.StatusInternalServerError, "file_delete_failed", "the file could not be deleted"))
return return
} }
audit.WriteOrLog(r.Context(), h.pool, h.logger, admin.ID, pgtype.UUID{}, audit.ActionSuspectFileRemove, map[string]any{ audit.WriteOrLog(r.Context(), h.pool, h.logger, admin.ID, pgtype.UUID{}, audit.ActionSuspectFileRemove, map[string]any{
+11 -8
View File
@@ -25,11 +25,11 @@ import (
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth" "git.fabledsword.com/bvandeusen/minstrel/internal/auth"
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
) )
@@ -160,6 +160,10 @@ type clientVersionResponse struct {
SHA256 string `json:"sha256"` SHA256 string `json:"sha256"`
} }
// errNoClientAPK answers both client endpoints when this image carries no
// Android app.
var errNoClientAPK = apierror.New(http.StatusNotFound, "no_client_apk", "no bundled client apk")
// handleClientVersion returns the bundled Android client version + a // handleClientVersion returns the bundled Android client version + a
// URL to fetch the APK. 404 when no APK is bundled. // URL to fetch the APK. 404 when no APK is bundled.
func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) { func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) {
@@ -169,7 +173,7 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) {
stat, err := os.Stat(apkPath) stat, err := os.Stat(apkPath)
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
http.Error(w, `{"error":{"code":"no_client_apk","message":"no bundled client apk"}}`, http.StatusNotFound) writeErr(w, errNoClientAPK)
return return
} }
if err != nil { if err != nil {
@@ -179,7 +183,7 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) {
versionBytes, err := os.ReadFile(versionPath) versionBytes, err := os.ReadFile(versionPath)
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
http.Error(w, `{"error":{"code":"no_client_version","message":"apk present but version file missing"}}`, http.StatusNotFound) writeErr(w, apierror.New(http.StatusNotFound, "no_client_version", "apk present but version file missing"))
return return
} }
if err != nil { if err != nil {
@@ -198,7 +202,7 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) {
return return
} }
if sidecar.Name == "" { if sidecar.Name == "" {
http.Error(w, `{"error":{"code":"bad_client_version","message":"version sidecar has no name"}}`, http.StatusInternalServerError) writeErr(w, apierror.New(http.StatusInternalServerError, "bad_client_version", "version sidecar has no name"))
return return
} }
@@ -224,20 +228,19 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) {
func (h *handlers) handleClientAPK(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleClientAPK(w http.ResponseWriter, r *http.Request) {
user, ok := auth.UserFromContext(r.Context()) user, ok := auth.UserFromContext(r.Context())
if !ok { if !ok {
http.Error(w, `{"error":{"code":"unauthenticated","message":"login required"}}`, http.StatusUnauthorized) writeErr(w, apierror.Unauthorized("unauthenticated", "sign in to continue"))
return return
} }
userID := syncpkg.FormatUUID(user.ID) userID := syncpkg.FormatUUID(user.ID)
if wait := clientAPKAllowDownload(userID, time.Now()); wait > 0 { if wait := clientAPKAllowDownload(userID, time.Now()); wait > 0 {
w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1)) writeRateLimited(w, wait)
http.Error(w, `{"error":{"code":"rate_limited","message":"too many downloads; try again shortly"}}`, http.StatusTooManyRequests)
return return
} }
apkPath := filepath.Join(clientAPKDir(), clientAPKFilename) apkPath := filepath.Join(clientAPKDir(), clientAPKFilename)
f, err := os.Open(apkPath) f, err := os.Open(apkPath)
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
http.Error(w, `{"error":{"code":"no_client_apk","message":"no bundled client apk"}}`, http.StatusNotFound) writeErr(w, errNoClientAPK)
return return
} }
if err != nil { if err != nil {
+4 -34
View File
@@ -11,32 +11,11 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
) )
// errorBody / errorPayload preserve the existing wire envelope: // writeErr answers err in the one /api error envelope (apierror.Body). If err
// // is or wraps *apierror.Error, its Status/Code/Message drive the response;
// {"error": {"code": "...", "message": "..."}} // otherwise it's a 500 server_error.
//
// Kept separate from the Subsonic envelope so native clients don't have
// to parse two shapes.
type errorBody struct {
Error errorPayload `json:"error"`
}
type errorPayload struct {
Code string `json:"code"`
Message string `json:"message"`
}
// writeErr emits the failure envelope for err. If err is or wraps
// *apierror.Error, its Status/Code/Message drive the response;
// otherwise it's mapped to a 500 server_error.
func writeErr(w http.ResponseWriter, err error) { func writeErr(w http.ResponseWriter, err error) {
apiErr := apierror.From(err) apierror.Write(w, err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(apiErr.Status)
_ = json.NewEncoder(w).Encode(errorBody{Error: errorPayload{
Code: apiErr.Code,
Message: apiErr.Message,
}})
} }
// writeRateLimited answers 429 with Retry-After in whole seconds, rounded // writeRateLimited answers 429 with Retry-After in whole seconds, rounded
@@ -67,12 +46,3 @@ func writeJSON(w http.ResponseWriter, status int, body any) {
w.WriteHeader(status) w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body) _ = json.NewEncoder(w).Encode(body)
} }
// writeAdminJSONErr writes a flat {"error":"<code>"} JSON response. This
// mirrors the shape the RequireAdmin middleware uses and that the spec
// defines for /api/admin/* errors.
func writeAdminJSONErr(w http.ResponseWriter, status int, code string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": code})
}
+2 -2
View File
@@ -10,9 +10,9 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
) )
func decodeEnvelope(t *testing.T, body []byte) errorBody { func decodeEnvelope(t *testing.T, body []byte) apierror.Body {
t.Helper() t.Helper()
var env errorBody var env apierror.Body
if err := json.Unmarshal(body, &env); err != nil { if err := json.Unmarshal(body, &env); err != nil {
t.Fatalf("decode envelope: %v (body=%s)", err, string(body)) t.Fatalf("decode envelope: %v (body=%s)", err, string(body))
} }
+3 -2
View File
@@ -28,6 +28,7 @@ import (
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth" "git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
) )
@@ -57,13 +58,13 @@ const (
func (h *handlers) handleEventsStream(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleEventsStream(w http.ResponseWriter, r *http.Request) {
user, ok := auth.UserFromContext(r.Context()) user, ok := auth.UserFromContext(r.Context())
if !ok { if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized) writeErr(w, apierror.ErrUnauthorized)
return return
} }
flusher, ok := w.(http.Flusher) flusher, ok := w.(http.Flusher)
if !ok { if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError) writeErr(w, apierror.InternalMsg("streaming unsupported", nil))
return return
} }
+5 -4
View File
@@ -13,6 +13,7 @@ import (
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/coverart" "git.fabledsword.com/bvandeusen/minstrel/internal/coverart"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
) )
@@ -255,7 +256,7 @@ func TestHandleGetCover_NoArt(t *testing.T) {
if w.Code != http.StatusNotFound { if w.Code != http.StatusNotFound {
t.Fatalf("status = %d", w.Code) t.Fatalf("status = %d", w.Code)
} }
var body errorBody var body apierror.Body
_ = json.Unmarshal(w.Body.Bytes(), &body) _ = json.Unmarshal(w.Body.Bytes(), &body)
if body.Error.Code != "not_found" || body.Error.Message != "cover not found" { if body.Error.Code != "not_found" || body.Error.Message != "cover not found" {
t.Errorf("error body = %+v", body) t.Errorf("error body = %+v", body)
@@ -282,7 +283,7 @@ func TestHandleGetCover_UnknownAlbum(t *testing.T) {
if w.Code != http.StatusNotFound { if w.Code != http.StatusNotFound {
t.Fatalf("status = %d", w.Code) t.Fatalf("status = %d", w.Code)
} }
var body errorBody var body apierror.Body
_ = json.Unmarshal(w.Body.Bytes(), &body) _ = json.Unmarshal(w.Body.Bytes(), &body)
if body.Error.Message != "album not found" { if body.Error.Message != "album not found" {
t.Errorf("message = %q, want \"album not found\"", body.Error.Message) t.Errorf("message = %q, want \"album not found\"", body.Error.Message)
@@ -422,7 +423,7 @@ func TestHandleGetStream_UnknownTrack(t *testing.T) {
if w.Code != http.StatusNotFound { if w.Code != http.StatusNotFound {
t.Fatalf("status = %d", w.Code) t.Fatalf("status = %d", w.Code)
} }
var body errorBody var body apierror.Body
_ = json.Unmarshal(w.Body.Bytes(), &body) _ = json.Unmarshal(w.Body.Bytes(), &body)
if body.Error.Message != "track not found" { if body.Error.Message != "track not found" {
t.Errorf("message = %q, want \"track not found\"", body.Error.Message) t.Errorf("message = %q, want \"track not found\"", body.Error.Message)
@@ -456,7 +457,7 @@ func TestHandleGetStream_VanishedFile(t *testing.T) {
if w.Code != http.StatusNotFound { if w.Code != http.StatusNotFound {
t.Fatalf("status = %d", w.Code) t.Fatalf("status = %d", w.Code)
} }
var body errorBody var body apierror.Body
_ = json.Unmarshal(w.Body.Bytes(), &body) _ = json.Unmarshal(w.Body.Bytes(), &body)
if body.Error.Message != "track file not found" { if body.Error.Message != "track file not found" {
t.Errorf("message = %q, want \"track file not found\"", body.Error.Message) t.Errorf("message = %q, want \"track file not found\"", body.Error.Message)
+7 -7
View File
@@ -146,7 +146,7 @@ func (h *handlers) handleListAdminPlaybackErrors(w http.ResponseWriter, r *http.
}) })
if err != nil { if err != nil {
h.logger.Error("admin: list playback_errors", "err", err) h.logger.Error("admin: list playback_errors", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
out := make([]adminPlaybackErrorView, 0, len(rows)) out := make([]adminPlaybackErrorView, 0, len(rows))
@@ -181,21 +181,21 @@ func (h *handlers) handleListAdminPlaybackErrors(w http.ResponseWriter, r *http.
func (h *handlers) handleResolvePlaybackError(w http.ResponseWriter, r *http.Request) { func (h *handlers) handleResolvePlaybackError(w http.ResponseWriter, r *http.Request) {
admin, ok := auth.UserFromContext(r.Context()) admin, ok := auth.UserFromContext(r.Context())
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized") writeErr(w, apierror.ErrUnauthorized)
return return
} }
id, ok := parseUUID(chi.URLParam(r, "id")) id, ok := parseUUID(chi.URLParam(r, "id"))
if !ok { if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return return
} }
var req resolvePlaybackErrorRequest var req resolvePlaybackErrorRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeAdminJSONErr(w, http.StatusBadRequest, "bad_request") writeErr(w, apierror.BadRequest("bad_request", "invalid JSON body"))
return return
} }
if _, ok := validPlaybackErrorResolutions[req.Resolution]; !ok { if _, ok := validPlaybackErrorResolutions[req.Resolution]; !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_resolution") writeErr(w, apierror.BadRequest("invalid_resolution", "unknown resolution"))
return return
} }
resolution := req.Resolution resolution := req.Resolution
@@ -206,11 +206,11 @@ func (h *handlers) handleResolvePlaybackError(w http.ResponseWriter, r *http.Req
}) })
if err != nil { if err != nil {
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
writeAdminJSONErr(w, http.StatusNotFound, "not_found") writeErr(w, apierror.ErrNotFound)
return return
} }
h.logger.Error("admin: resolve playback_error", "err", err) h.logger.Error("admin: resolve playback_error", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") writeErr(w, apierror.Internal(err))
return return
} }
writeJSON(w, http.StatusOK, map[string]string{"id": uuidToString(row.ID)}) writeJSON(w, http.StatusOK, map[string]string{"id": uuidToString(row.ID)})
+5 -4
View File
@@ -12,6 +12,7 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
) )
@@ -77,7 +78,7 @@ func TestPlaylists_NoSession401(t *testing.T) {
if w.Code != http.StatusUnauthorized { if w.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401; body = %s", w.Code, w.Body.String()) t.Fatalf("status = %d, want 401; body = %s", w.Code, w.Body.String())
} }
var env errorBody var env apierror.Body
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil { if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String()) t.Fatalf("decode: %v; body = %s", err, w.Body.String())
} }
@@ -147,7 +148,7 @@ func TestPlaylists_CreateEmptyName400(t *testing.T) {
if w.Code != http.StatusBadRequest { if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String()) t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String())
} }
var env errorBody var env apierror.Body
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil { if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
t.Fatalf("decode: %v", err) t.Fatalf("decode: %v", err)
} }
@@ -180,7 +181,7 @@ func TestPlaylists_PatchOwnerOnly(t *testing.T) {
if pw.Code != http.StatusForbidden { if pw.Code != http.StatusForbidden {
t.Fatalf("non-owner patch status = %d, want 403; body = %s", pw.Code, pw.Body.String()) t.Fatalf("non-owner patch status = %d, want 403; body = %s", pw.Code, pw.Body.String())
} }
var env errorBody var env apierror.Body
if err := json.Unmarshal(pw.Body.Bytes(), &env); err != nil { if err := json.Unmarshal(pw.Body.Bytes(), &env); err != nil {
t.Fatalf("decode: %v", err) t.Fatalf("decode: %v", err)
} }
@@ -607,7 +608,7 @@ func TestEditEndpoints_403OnSystemPlaylist(t *testing.T) {
if w.Code != http.StatusForbidden { if w.Code != http.StatusForbidden {
t.Fatalf("status: got %d want 403; body=%s", w.Code, w.Body.String()) t.Fatalf("status: got %d want 403; body=%s", w.Code, w.Body.String())
} }
var env errorBody var env apierror.Body
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil { if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
t.Fatalf("decode envelope: %v", err) t.Fatalf("decode envelope: %v", err)
} }
+35
View File
@@ -1,8 +1,10 @@
package apierror package apierror
import ( import (
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"net/http"
) )
type Error struct { type Error struct {
@@ -75,3 +77,36 @@ var (
ErrForbidden = &Error{Status: 403, Code: "forbidden", Message: "forbidden"} ErrForbidden = &Error{Status: 403, Code: "forbidden", Message: "forbidden"}
ErrUnauthorized = &Error{Status: 401, Code: "unauthorized", Message: "authentication required"} ErrUnauthorized = &Error{Status: 401, Code: "unauthorized", Message: "authentication required"}
) )
// New returns an Error with any status, code and message, for the cases the
// named constructors don't cover (a 404 with its own code, say).
func New(status int, code, message string) *Error {
return &Error{Status: status, Code: code, Message: message}
}
// Body is the one error envelope every native /api response uses:
//
// {"error": {"code": "...", "message": "..."}}
//
// The code is stable and is what clients map to their own copy; the message
// is English for logs and for codes a client doesn't know. Subsonic's /rest
// keeps its own envelope, which its apps expect.
type Body struct {
Error Payload `json:"error"`
}
// Payload is the inside of Body.
type Payload struct {
Code string `json:"code"`
Message string `json:"message"`
}
// Write answers err in the Body envelope. If err is or wraps an *Error, its
// Status, Code and Message are used; anything else is a 500 server_error, so
// an internal error's text never reaches the client.
func Write(w http.ResponseWriter, err error) {
apiErr := From(err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(apiErr.Status)
_ = json.NewEncoder(w).Encode(Body{Error: Payload{Code: apiErr.Code, Message: apiErr.Message}})
}
+4 -12
View File
@@ -1,8 +1,9 @@
package auth package auth
import ( import (
"encoding/json"
"net/http" "net/http"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
) )
// RequireAdmin is a middleware that MUST run after RequireUser. It reads the // RequireAdmin is a middleware that MUST run after RequireUser. It reads the
@@ -23,23 +24,14 @@ func RequireAdmin() func(http.Handler) http.Handler {
user, ok := UserFromContext(r.Context()) user, ok := UserFromContext(r.Context())
if !ok { if !ok {
// Programmer error: RequireUser was not mounted before RequireAdmin. // Programmer error: RequireUser was not mounted before RequireAdmin.
writeAdminErr(w, http.StatusInternalServerError, "internal_error") apierror.Write(w, apierror.InternalMsg("admin check mounted without a user", nil))
return return
} }
if !user.IsAdmin { if !user.IsAdmin {
writeAdminErr(w, http.StatusForbidden, "not_authorized") apierror.Write(w, apierror.Forbidden("not_authorized", "admin access required"))
return return
} }
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
}) })
} }
} }
// writeAdminErr writes a flat JSON error envelope {"error":"<code>"} and sets
// Content-Type. Uses a flat envelope (not the nested api.errorBody shape)
// because the spec for /api/admin/* errors defines {"error":"<code>"} directly.
func writeAdminErr(w http.ResponseWriter, status int, code string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": code})
}
+17 -8
View File
@@ -2,11 +2,13 @@ package auth
import ( import (
"context" "context"
"encoding/json"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings" "strings"
"testing" "testing"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
) )
@@ -17,6 +19,19 @@ func injectUser(r *http.Request, u dbq.User) *http.Request {
return r.WithContext(ctx) return r.WithContext(ctx)
} }
// assertErrorCode checks the response is the /api error envelope with code.
// Clients read only that shape, so a flat {"error":"code"} must fail here.
func assertErrorCode(t *testing.T, w *httptest.ResponseRecorder, code string) {
t.Helper()
var env apierror.Body
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
t.Fatalf("body %q is not the error envelope: %v", w.Body.String(), err)
}
if env.Error.Code != code {
t.Errorf("error.code = %q, want %q; body %q", env.Error.Code, code, w.Body.String())
}
}
func TestRequireAdmin_AdminPasses(t *testing.T) { func TestRequireAdmin_AdminPasses(t *testing.T) {
called := false called := false
stub := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { stub := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
@@ -58,10 +73,7 @@ func TestRequireAdmin_NonAdminReturns403(t *testing.T) {
if w.Code != http.StatusForbidden { if w.Code != http.StatusForbidden {
t.Errorf("status = %d, want 403", w.Code) t.Errorf("status = %d, want 403", w.Code)
} }
body := w.Body.String() assertErrorCode(t, w, "not_authorized")
if !strings.Contains(body, "not_authorized") {
t.Errorf("body %q does not contain %q", body, "not_authorized")
}
ct := w.Header().Get("Content-Type") ct := w.Header().Get("Content-Type")
if !strings.HasPrefix(ct, "application/json") { if !strings.HasPrefix(ct, "application/json") {
t.Errorf("Content-Type = %q, want application/json", ct) t.Errorf("Content-Type = %q, want application/json", ct)
@@ -83,10 +95,7 @@ func TestRequireAdmin_NoUserContextReturns500(t *testing.T) {
if w.Code != http.StatusInternalServerError { if w.Code != http.StatusInternalServerError {
t.Errorf("status = %d, want 500", w.Code) t.Errorf("status = %d, want 500", w.Code)
} }
body := w.Body.String() assertErrorCode(t, w, "server_error")
if !strings.Contains(body, "internal_error") {
t.Errorf("body %q does not contain %q", body, "internal_error")
}
ct := w.Header().Get("Content-Type") ct := w.Header().Get("Content-Type")
if !strings.HasPrefix(ct, "application/json") { if !strings.HasPrefix(ct, "application/json") {
t.Errorf("Content-Type = %q, want application/json", ct) t.Errorf("Content-Type = %q, want application/json", ct)
+13 -8
View File
@@ -15,6 +15,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
) )
@@ -62,10 +63,14 @@ func VerifyPassword(hash, plaintext string) bool {
// that issue/clear the cookie (handleLogin / handleLogout) need to match it. // that issue/clear the cookie (handleLogin / handleLogout) need to match it.
const SessionCookieName = "minstrel_session" const SessionCookieName = "minstrel_session"
// errUnauthenticated is the answer to a request with no session, or one
// that has ended. Clients sign out on any 401.
var errUnauthenticated = apierror.Unauthorized("unauthenticated", "sign in to continue")
// RequireUser resolves the caller from a session cookie OR Authorization // RequireUser resolves the caller from a session cookie OR Authorization
// bearer header and puts the dbq.User in request context via userCtxKey. // bearer header and puts the dbq.User in request context via userCtxKey.
// Requests without a valid session return 401 with no body so callers don't // Every request without a valid session gets the same 401 unauthenticated,
// leak whether the username existed (matches the /rest/* auth posture). // so a caller can't tell a missing session from a deleted user.
// //
// trustedHops supplies the reverse-proxy depth used to record the session's // trustedHops supplies the reverse-proxy depth used to record the session's
// current address. It's a func rather than an int because the value // current address. It's a func rather than an int because the value
@@ -77,7 +82,7 @@ func RequireUser(pool *pgxpool.Pool, trustedHops func() int) func(http.Handler)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := sessionTokenFromRequest(r) token := sessionTokenFromRequest(r)
if token == "" { if token == "" {
http.Error(w, "unauthenticated", http.StatusUnauthorized) apierror.Write(w, errUnauthenticated)
return return
} }
if pool == nil { if pool == nil {
@@ -85,18 +90,18 @@ func RequireUser(pool *pgxpool.Pool, trustedHops func() int) func(http.Handler)
// the middleware with nil pool to prove the no-token case // the middleware with nil pool to prove the no-token case
// short-circuits without a DB call. Any real token here is // short-circuits without a DB call. Any real token here is
// programmer error. // programmer error.
http.Error(w, "unauthenticated", http.StatusUnauthorized) apierror.Write(w, errUnauthenticated)
return return
} }
q := dbq.New(pool) q := dbq.New(pool)
sess, err := q.GetSessionByTokenHash(r.Context(), HashSessionToken(token)) sess, err := q.GetSessionByTokenHash(r.Context(), HashSessionToken(token))
if err != nil { if err != nil {
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
http.Error(w, "unauthenticated", http.StatusUnauthorized) apierror.Write(w, errUnauthenticated)
return return
} }
slog.Error("api: session lookup failed", "err", err) slog.Error("api: session lookup failed", "err", err)
http.Error(w, "auth lookup failed", http.StatusInternalServerError) apierror.Write(w, apierror.InternalMsg("auth lookup failed", err))
return return
} }
user, err := q.GetUserByID(r.Context(), sess.UserID) user, err := q.GetUserByID(r.Context(), sess.UserID)
@@ -105,11 +110,11 @@ func RequireUser(pool *pgxpool.Pool, trustedHops func() int) func(http.Handler)
// Session points at a deleted user — treat as unauth, // Session points at a deleted user — treat as unauth,
// best-effort cleanup. // best-effort cleanup.
_ = q.DeleteSession(r.Context(), sess.ID) _ = q.DeleteSession(r.Context(), sess.ID)
http.Error(w, "unauthenticated", http.StatusUnauthorized) apierror.Write(w, errUnauthenticated)
return return
} }
slog.Error("api: user lookup failed", "err", err) slog.Error("api: user lookup failed", "err", err)
http.Error(w, "auth lookup failed", http.StatusInternalServerError) apierror.Write(w, apierror.InternalMsg("auth lookup failed", err))
return return
} }
// Best-effort last-seen update. A failure here shouldn't fail the // Best-effort last-seen update. A failure here shouldn't fail the
+5 -7
View File
@@ -15,6 +15,7 @@ import (
"time" "time"
"git.fabledsword.com/bvandeusen/minstrel/internal/api" "git.fabledsword.com/bvandeusen/minstrel/internal/api"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth" "git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/backup" "git.fabledsword.com/bvandeusen/minstrel/internal/backup"
"git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo" "git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo"
@@ -240,9 +241,7 @@ func (s *Server) Router() http.Handler {
r.NotFound(func(w http.ResponseWriter, req *http.Request) { r.NotFound(func(w http.ResponseWriter, req *http.Request) {
p := req.URL.Path p := req.URL.Path
if strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/rest/") { if strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/rest/") {
w.Header().Set("Content-Type", "application/json") apierror.Write(w, apierror.ErrNotFound)
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":{"code":"not_found","message":"not found"}}`))
return return
} }
spa.ServeHTTP(w, req) spa.ServeHTTP(w, req)
@@ -266,13 +265,12 @@ func (s *Server) handleHealthz(w http.ResponseWriter, _ *http.Request) {
// also published as scan-run events. // also published as scan-run events.
func (s *Server) handleAdminScan(w http.ResponseWriter, r *http.Request) { func (s *Server) handleAdminScan(w http.ResponseWriter, r *http.Request) {
stats, err := s.Scanner.Scan(r.Context(), nil) stats, err := s.Scanner.Scan(r.Context(), nil)
w.Header().Set("Content-Type", "application/json")
if err != nil { if err != nil {
s.Logger.Error("admin scan failed", "err", err) s.Logger.Error("admin scan failed", "err", err, "stats", stats)
w.WriteHeader(http.StatusInternalServerError) apierror.Write(w, apierror.InternalMsg("scan failed", err))
_ = json.NewEncoder(w).Encode(map[string]any{"error": err.Error(), "stats": stats})
return return
} }
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(stats) _ = json.NewEncoder(w).Encode(stats)
} }
+8 -15
View File
@@ -48,21 +48,14 @@ export async function apiFetch(path: string, init?: RequestInit): Promise<unknow
const { logout } = await import('#lib/auth/store.svelte.js'); const { logout } = await import('#lib/auth/store.svelte.js');
await logout({ silent: true }); await logout({ silent: true });
} }
// Two error envelope shapes ship in this codebase today: // Every /api error is {"error": {"code": "...", "message": "..."}}. A
// 1) {"error": {"code": "...", "message": "..."}} — non-admin endpoints // body without it (a proxy's error page, say) reads as 'unknown'.
// 2) {"error": "code_string"} — admin endpoints const env = (body as { error?: { code?: string; message?: string } } | null)?.error;
// Without handling (2), every admin error toast renders 'unknown'. const err: ApiError = {
const errorField = body && (body as { error?: unknown }).error; code: env?.code ?? 'unknown',
let code = 'unknown'; message: env?.message ?? res.statusText,
let message = res.statusText; status: res.status
if (typeof errorField === 'string') { };
code = errorField;
} else if (errorField && typeof errorField === 'object') {
const env = errorField as { code?: string; message?: string };
code = env.code ?? 'unknown';
message = env.message ?? res.statusText;
}
const err: ApiError = { code, message, status: res.status };
if (res.status === 429) { if (res.status === 429) {
const retryAfter = Number(res.headers.get('Retry-After')); const retryAfter = Number(res.headers.get('Retry-After'));
if (Number.isFinite(retryAfter) && retryAfter > 0) err.retryAfter = retryAfter; if (Number.isFinite(retryAfter) && retryAfter > 0) err.retryAfter = retryAfter;
+1 -1
View File
@@ -69,7 +69,7 @@ describe('playlists API helper', () => {
}); });
test('not_found surfaces as ApiError', async () => { test('not_found surfaces as ApiError', async () => {
stubFetch(404, { error: 'not_found' }); stubFetch(404, { error: { code: 'not_found', message: 'not found' } });
await expect(getPlaylist('missing')).rejects.toMatchObject({ code: 'not_found' }); await expect(getPlaylist('missing')).rejects.toMatchObject({ code: 'not_found' });
}); });
}); });