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:
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"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/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
||||
@@ -107,7 +108,7 @@ type adminDuplicatesResponse struct {
|
||||
func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request) {
|
||||
limit, offset, err := parsePaging(r.URL.Query())
|
||||
if err != nil {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging")
|
||||
writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset"))
|
||||
return
|
||||
}
|
||||
view := r.URL.Query().Get("view")
|
||||
@@ -115,7 +116,7 @@ func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request)
|
||||
view = duplicateViewReview
|
||||
}
|
||||
if view != duplicateViewReview && view != duplicateViewCrossRelease {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_view")
|
||||
writeErr(w, apierror.BadRequest("invalid_view", "unknown view"))
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
@@ -128,20 +129,20 @@ func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request)
|
||||
sweep = duplicateSweepViewOf(last)
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
h.logger.Error("admin: latest duplicate sweep", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
cov, err := h.fingerprintCoverage(ctx)
|
||||
if err != nil {
|
||||
h.logger.Error("admin: fingerprint coverage", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
counts, err := duplicateCounts(ctx, q)
|
||||
if err != nil {
|
||||
h.logger.Error("admin: count duplicate groups", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
total := counts.Review
|
||||
@@ -153,7 +154,7 @@ func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request)
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("admin: list duplicate groups", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -209,14 +210,14 @@ type resolvedActivityResponse struct {
|
||||
func (h *handlers) handleListResolvedDuplicates(w http.ResponseWriter, r *http.Request) {
|
||||
limit, offset, err := parsePaging(r.URL.Query())
|
||||
if err != nil {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging")
|
||||
writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset"))
|
||||
return
|
||||
}
|
||||
q := dbq.New(h.pool)
|
||||
total, err := q.CountAuditLogByActions(r.Context(), dbq.CountAuditLogByActionsParams{Actions: resolvedActions, SystemOnly: true})
|
||||
if err != nil {
|
||||
h.logger.Error("admin: count resolved duplicates", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
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 {
|
||||
h.logger.Error("admin: list resolved duplicates", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
items := make([]resolvedActivityView, 0, len(rows))
|
||||
@@ -320,11 +321,11 @@ func (h *handlers) handleRunDuplicateSweep(w http.ResponseWriter, _ *http.Reques
|
||||
)
|
||||
if err != nil {
|
||||
h.logger.Error("admin: start duplicate sweep", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
if !started {
|
||||
writeAdminJSONErr(w, http.StatusConflict, "sweep_in_progress")
|
||||
writeErr(w, apierror.Conflict("sweep_in_progress", "a duplicate sweep is already running"))
|
||||
return
|
||||
}
|
||||
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) {
|
||||
id, ok := parseUUID(chi.URLParam(r, "id"))
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
n, err := h.dismissDuplicateGroup(r.Context(), id)
|
||||
if err != nil {
|
||||
h.logger.Error("admin: dismiss duplicate group", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
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"))
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
var body mergeDuplicateRequest
|
||||
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
|
||||
}
|
||||
var survivorID pgtype.UUID // invalid: keep the proposal
|
||||
if body.SurvivorTrackID != "" {
|
||||
if survivorID, ok = parseUUID(body.SurvivorTrackID); !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -432,12 +433,12 @@ func (h *handlers) handleMergeDuplicateGroup(w http.ResponseWriter, r *http.Requ
|
||||
}
|
||||
switch {
|
||||
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):
|
||||
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:
|
||||
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
|
||||
}
|
||||
@@ -486,18 +487,18 @@ func (h *handlers) handleRemoveWrongSlotFiles(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
groupID, ok := parseUUID(chi.URLParam(r, "id"))
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
var body wrongSlotRequest
|
||||
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
|
||||
}
|
||||
var keepID pgtype.UUID // invalid: every copy goes
|
||||
if body.KeepTrackID != "" {
|
||||
if keepID, ok = parseUUID(body.KeepTrackID); !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -511,14 +512,14 @@ func (h *handlers) handleRemoveWrongSlotFiles(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
switch {
|
||||
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):
|
||||
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):
|
||||
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:
|
||||
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
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"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/library"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/tracks"
|
||||
@@ -77,7 +78,7 @@ type adminMissingResponse struct {
|
||||
func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Request) {
|
||||
limit, offset, err := parsePaging(r.URL.Query())
|
||||
if err != nil {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging")
|
||||
writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset"))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -85,7 +86,7 @@ func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Reques
|
||||
total, err := q.CountMissingTracks(r.Context())
|
||||
if err != nil {
|
||||
h.logger.Error("admin: count missing tracks", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
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 {
|
||||
h.logger.Error("admin: list missing tracks", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -185,14 +186,14 @@ func (h *handlers) handleForgetMissingTracks(w http.ResponseWriter, r *http.Requ
|
||||
}
|
||||
var body forgetMissingRequest
|
||||
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
|
||||
}
|
||||
ids := make([]pgtype.UUID, 0, len(body.TrackIDs))
|
||||
for _, raw := range body.TrackIDs {
|
||||
id, ok := parseUUID(raw)
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
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)
|
||||
switch {
|
||||
case errors.Is(err, tracks.ErrNotFound):
|
||||
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found")
|
||||
writeErr(w, apierror.NotFound("track"))
|
||||
return
|
||||
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
|
||||
case err != nil:
|
||||
h.logger.Error("admin: forget missing tracks", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
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())
|
||||
if err != nil {
|
||||
h.logger.Error("admin: count missing tracks", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
rows, err := q.ListMissingTracks(r.Context(), dbq.ListMissingTracksParams{PageLimit: int32(total), PageOffset: 0})
|
||||
if err != nil {
|
||||
h.logger.Error("admin: list missing tracks", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"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/db/dbq"
|
||||
"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())
|
||||
if err != nil {
|
||||
h.logger.Error("admin: list quarantine", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := make([]adminQueueRowView, 0, len(rows))
|
||||
@@ -90,22 +91,22 @@ type actionResultView struct {
|
||||
func (h *handlers) handleResolveQuarantine(w http.ResponseWriter, r *http.Request) {
|
||||
admin, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized")
|
||||
writeErr(w, apierror.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
id, ok := parseUUID(chi.URLParam(r, "track_id"))
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
action, err := h.quarantine.Resolve(r.Context(), id, admin.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, quarantine.ErrTrackNotFound) {
|
||||
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found")
|
||||
writeErr(w, apierror.NotFound("track"))
|
||||
return
|
||||
}
|
||||
h.logger.Error("admin: resolve quarantine", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
// 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) {
|
||||
admin, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized")
|
||||
writeErr(w, apierror.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
id, ok := parseUUID(chi.URLParam(r, "track_id"))
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
action, err := h.quarantine.DeleteFile(r.Context(), id, admin.ID)
|
||||
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 {
|
||||
logFileRemoveFailure(h.logger, apiErr, "track_id", uuidToString(id))
|
||||
writeErr(w, apiErr)
|
||||
@@ -140,10 +140,10 @@ func (h *handlers) handleDeleteQuarantineFile(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, quarantine.ErrTrackNotFound):
|
||||
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found")
|
||||
writeErr(w, apierror.NotFound("track"))
|
||||
default:
|
||||
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
|
||||
}
|
||||
@@ -166,12 +166,12 @@ func (h *handlers) handleDeleteQuarantineFile(w http.ResponseWriter, r *http.Req
|
||||
func (h *handlers) handleRemoveQuarantineFile(w http.ResponseWriter, r *http.Request) {
|
||||
admin, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized")
|
||||
writeErr(w, apierror.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
id, ok := parseUUID(chi.URLParam(r, "track_id"))
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
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 {
|
||||
case errors.Is(err, quarantine.ErrTrackNotFound):
|
||||
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found")
|
||||
writeErr(w, apierror.NotFound("track"))
|
||||
default:
|
||||
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
|
||||
}
|
||||
@@ -229,7 +229,7 @@ func (h *handlers) handleListQuarantineActions(w http.ResponseWriter, r *http.Re
|
||||
rows, err := dbq.New(h.pool).ListQuarantineActions(r.Context(), limit)
|
||||
if err != nil {
|
||||
h.logger.Error("admin: list actions", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := make([]actionLogView, 0, len(rows))
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"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)
|
||||
if err != nil {
|
||||
h.logger.Error("admin status: listening", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
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)
|
||||
if err != nil {
|
||||
h.logger.Error("admin status: plays", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
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)
|
||||
if err != nil {
|
||||
h.logger.Error("admin status: library", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out.Library = libraryStatusView{Tracks: lib.Tracks, Albums: lib.Albums, Artists: lib.Artists,
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"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())
|
||||
if err != nil {
|
||||
h.logger.Error("admin: summary", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, adminSummaryFrom(row))
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"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/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
||||
@@ -62,7 +63,7 @@ type adminSuspectSourcesResponse struct {
|
||||
func (h *handlers) handleListSuspectSources(w http.ResponseWriter, r *http.Request) {
|
||||
limit, offset, err := parsePaging(r.URL.Query())
|
||||
if err != nil {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging")
|
||||
writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset"))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -70,7 +71,7 @@ func (h *handlers) handleListSuspectSources(w http.ResponseWriter, r *http.Reque
|
||||
total, err := q.CountSuspectSourceTracks(r.Context(), library.SuspectSourcePattern)
|
||||
if err != nil {
|
||||
h.logger.Error("admin: count suspect-source tracks", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
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 {
|
||||
h.logger.Error("admin: list suspect-source tracks", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -139,26 +140,26 @@ type suspectVerdictRequest struct {
|
||||
func (h *handlers) handleSetSuspectSourceVerdict(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := parseUUID(chi.URLParam(r, "id"))
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
var req suspectVerdictRequest
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
n, err := dbq.New(h.pool).SetTrackSourceVerdict(r.Context(), dbq.SetTrackSourceVerdictParams{Verdict: req.Verdict, ID: id})
|
||||
if err != nil {
|
||||
h.logger.Error("admin: set suspect-source verdict", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
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"))
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
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)) {
|
||||
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
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Error("admin: read suspect track", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
audit.WriteOrLog(r.Context(), h.pool, h.logger, admin.ID, pgtype.UUID{}, audit.ActionSuspectFileRemove, map[string]any{
|
||||
|
||||
@@ -25,11 +25,11 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
||||
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
|
||||
)
|
||||
@@ -160,6 +160,10 @@ type clientVersionResponse struct {
|
||||
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
|
||||
// URL to fetch the APK. 404 when no APK is bundled.
|
||||
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)
|
||||
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
|
||||
}
|
||||
if err != nil {
|
||||
@@ -179,7 +183,7 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) {
|
||||
|
||||
versionBytes, err := os.ReadFile(versionPath)
|
||||
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
|
||||
}
|
||||
if err != nil {
|
||||
@@ -198,7 +202,7 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) {
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -224,20 +228,19 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) {
|
||||
func (h *handlers) handleClientAPK(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
http.Error(w, `{"error":{"code":"unauthenticated","message":"login required"}}`, http.StatusUnauthorized)
|
||||
writeErr(w, apierror.Unauthorized("unauthenticated", "sign in to continue"))
|
||||
return
|
||||
}
|
||||
userID := syncpkg.FormatUUID(user.ID)
|
||||
if wait := clientAPKAllowDownload(userID, time.Now()); wait > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
|
||||
http.Error(w, `{"error":{"code":"rate_limited","message":"too many downloads; try again shortly"}}`, http.StatusTooManyRequests)
|
||||
writeRateLimited(w, wait)
|
||||
return
|
||||
}
|
||||
|
||||
apkPath := filepath.Join(clientAPKDir(), clientAPKFilename)
|
||||
f, err := os.Open(apkPath)
|
||||
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
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
+4
-34
@@ -11,32 +11,11 @@ import (
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
)
|
||||
|
||||
// errorBody / errorPayload preserve the existing wire envelope:
|
||||
//
|
||||
// {"error": {"code": "...", "message": "..."}}
|
||||
//
|
||||
// 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.
|
||||
// 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;
|
||||
// otherwise it's a 500 server_error.
|
||||
func writeErr(w http.ResponseWriter, err error) {
|
||||
apiErr := apierror.From(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,
|
||||
}})
|
||||
apierror.Write(w, err)
|
||||
}
|
||||
|
||||
// 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)
|
||||
_ = 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})
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
"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()
|
||||
var env errorBody
|
||||
var env apierror.Body
|
||||
if err := json.Unmarshal(body, &env); err != nil {
|
||||
t.Fatalf("decode envelope: %v (body=%s)", err, string(body))
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
|
||||
"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/eventbus"
|
||||
)
|
||||
@@ -57,13 +58,13 @@ const (
|
||||
func (h *handlers) handleEventsStream(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
writeErr(w, apierror.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||
writeErr(w, apierror.InternalMsg("streaming unsupported", nil))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"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/db/dbq"
|
||||
)
|
||||
@@ -255,7 +256,7 @@ func TestHandleGetCover_NoArt(t *testing.T) {
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d", w.Code)
|
||||
}
|
||||
var body errorBody
|
||||
var body apierror.Body
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||
if body.Error.Code != "not_found" || body.Error.Message != "cover not found" {
|
||||
t.Errorf("error body = %+v", body)
|
||||
@@ -282,7 +283,7 @@ func TestHandleGetCover_UnknownAlbum(t *testing.T) {
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d", w.Code)
|
||||
}
|
||||
var body errorBody
|
||||
var body apierror.Body
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||
if body.Error.Message != "album not found" {
|
||||
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 {
|
||||
t.Fatalf("status = %d", w.Code)
|
||||
}
|
||||
var body errorBody
|
||||
var body apierror.Body
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||
if body.Error.Message != "track not found" {
|
||||
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 {
|
||||
t.Fatalf("status = %d", w.Code)
|
||||
}
|
||||
var body errorBody
|
||||
var body apierror.Body
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||
if body.Error.Message != "track file not found" {
|
||||
t.Errorf("message = %q, want \"track file not found\"", body.Error.Message)
|
||||
|
||||
@@ -146,7 +146,7 @@ func (h *handlers) handleListAdminPlaybackErrors(w http.ResponseWriter, r *http.
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("admin: list playback_errors", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
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) {
|
||||
admin, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized")
|
||||
writeErr(w, apierror.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
id, ok := parseUUID(chi.URLParam(r, "id"))
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
|
||||
return
|
||||
}
|
||||
var req resolvePlaybackErrorRequest
|
||||
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
|
||||
}
|
||||
if _, ok := validPlaybackErrorResolutions[req.Resolution]; !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_resolution")
|
||||
writeErr(w, apierror.BadRequest("invalid_resolution", "unknown resolution"))
|
||||
return
|
||||
}
|
||||
resolution := req.Resolution
|
||||
@@ -206,11 +206,11 @@ func (h *handlers) handleResolvePlaybackError(w http.ResponseWriter, r *http.Req
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeAdminJSONErr(w, http.StatusNotFound, "not_found")
|
||||
writeErr(w, apierror.ErrNotFound)
|
||||
return
|
||||
}
|
||||
h.logger.Error("admin: resolve playback_error", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"id": uuidToString(row.ID)})
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
@@ -77,7 +78,7 @@ func TestPlaylists_NoSession401(t *testing.T) {
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
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 {
|
||||
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 {
|
||||
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 {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
@@ -180,7 +181,7 @@ func TestPlaylists_PatchOwnerOnly(t *testing.T) {
|
||||
if pw.Code != http.StatusForbidden {
|
||||
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 {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
@@ -607,7 +608,7 @@ func TestEditEndpoints_403OnSystemPlaylist(t *testing.T) {
|
||||
if w.Code != http.StatusForbidden {
|
||||
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 {
|
||||
t.Fatalf("decode envelope: %v", err)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package apierror
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Error struct {
|
||||
@@ -75,3 +77,36 @@ var (
|
||||
ErrForbidden = &Error{Status: 403, Code: "forbidden", Message: "forbidden"}
|
||||
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
@@ -1,8 +1,9 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
)
|
||||
|
||||
// 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())
|
||||
if !ok {
|
||||
// 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
|
||||
}
|
||||
if !user.IsAdmin {
|
||||
writeAdminErr(w, http.StatusForbidden, "not_authorized")
|
||||
apierror.Write(w, apierror.Forbidden("not_authorized", "admin access required"))
|
||||
return
|
||||
}
|
||||
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})
|
||||
}
|
||||
|
||||
@@ -2,11 +2,13 @@ package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"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)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
called := false
|
||||
stub := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
@@ -58,10 +73,7 @@ func TestRequireAdmin_NonAdminReturns403(t *testing.T) {
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("status = %d, want 403", w.Code)
|
||||
}
|
||||
body := w.Body.String()
|
||||
if !strings.Contains(body, "not_authorized") {
|
||||
t.Errorf("body %q does not contain %q", body, "not_authorized")
|
||||
}
|
||||
assertErrorCode(t, w, "not_authorized")
|
||||
ct := w.Header().Get("Content-Type")
|
||||
if !strings.HasPrefix(ct, "application/json") {
|
||||
t.Errorf("Content-Type = %q, want application/json", ct)
|
||||
@@ -83,10 +95,7 @@ func TestRequireAdmin_NoUserContextReturns500(t *testing.T) {
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("status = %d, want 500", w.Code)
|
||||
}
|
||||
body := w.Body.String()
|
||||
if !strings.Contains(body, "internal_error") {
|
||||
t.Errorf("body %q does not contain %q", body, "internal_error")
|
||||
}
|
||||
assertErrorCode(t, w, "server_error")
|
||||
ct := w.Header().Get("Content-Type")
|
||||
if !strings.HasPrefix(ct, "application/json") {
|
||||
t.Errorf("Content-Type = %q, want application/json", ct)
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"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.
|
||||
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
|
||||
// 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
|
||||
// leak whether the username existed (matches the /rest/* auth posture).
|
||||
// Every request without a valid session gets the same 401 unauthenticated,
|
||||
// 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
|
||||
// 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) {
|
||||
token := sessionTokenFromRequest(r)
|
||||
if token == "" {
|
||||
http.Error(w, "unauthenticated", http.StatusUnauthorized)
|
||||
apierror.Write(w, errUnauthenticated)
|
||||
return
|
||||
}
|
||||
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
|
||||
// short-circuits without a DB call. Any real token here is
|
||||
// programmer error.
|
||||
http.Error(w, "unauthenticated", http.StatusUnauthorized)
|
||||
apierror.Write(w, errUnauthenticated)
|
||||
return
|
||||
}
|
||||
q := dbq.New(pool)
|
||||
sess, err := q.GetSessionByTokenHash(r.Context(), HashSessionToken(token))
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
http.Error(w, "unauthenticated", http.StatusUnauthorized)
|
||||
apierror.Write(w, errUnauthenticated)
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
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,
|
||||
// best-effort cleanup.
|
||||
_ = q.DeleteSession(r.Context(), sess.ID)
|
||||
http.Error(w, "unauthenticated", http.StatusUnauthorized)
|
||||
apierror.Write(w, errUnauthenticated)
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
// Best-effort last-seen update. A failure here shouldn't fail the
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"time"
|
||||
|
||||
"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/backup"
|
||||
"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) {
|
||||
p := req.URL.Path
|
||||
if strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/rest/") {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"error":{"code":"not_found","message":"not found"}}`))
|
||||
apierror.Write(w, apierror.ErrNotFound)
|
||||
return
|
||||
}
|
||||
spa.ServeHTTP(w, req)
|
||||
@@ -266,13 +265,12 @@ func (s *Server) handleHealthz(w http.ResponseWriter, _ *http.Request) {
|
||||
// also published as scan-run events.
|
||||
func (s *Server) handleAdminScan(w http.ResponseWriter, r *http.Request) {
|
||||
stats, err := s.Scanner.Scan(r.Context(), nil)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err != nil {
|
||||
s.Logger.Error("admin scan failed", "err", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": err.Error(), "stats": stats})
|
||||
s.Logger.Error("admin scan failed", "err", err, "stats", stats)
|
||||
apierror.Write(w, apierror.InternalMsg("scan failed", err))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(stats)
|
||||
}
|
||||
|
||||
@@ -48,21 +48,14 @@ export async function apiFetch(path: string, init?: RequestInit): Promise<unknow
|
||||
const { logout } = await import('#lib/auth/store.svelte.js');
|
||||
await logout({ silent: true });
|
||||
}
|
||||
// Two error envelope shapes ship in this codebase today:
|
||||
// 1) {"error": {"code": "...", "message": "..."}} — non-admin endpoints
|
||||
// 2) {"error": "code_string"} — admin endpoints
|
||||
// Without handling (2), every admin error toast renders 'unknown'.
|
||||
const errorField = body && (body as { error?: unknown }).error;
|
||||
let code = 'unknown';
|
||||
let message = res.statusText;
|
||||
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 };
|
||||
// Every /api error is {"error": {"code": "...", "message": "..."}}. A
|
||||
// body without it (a proxy's error page, say) reads as 'unknown'.
|
||||
const env = (body as { error?: { code?: string; message?: string } } | null)?.error;
|
||||
const err: ApiError = {
|
||||
code: env?.code ?? 'unknown',
|
||||
message: env?.message ?? res.statusText,
|
||||
status: res.status
|
||||
};
|
||||
if (res.status === 429) {
|
||||
const retryAfter = Number(res.headers.get('Retry-After'));
|
||||
if (Number.isFinite(retryAfter) && retryAfter > 0) err.retryAfter = retryAfter;
|
||||
|
||||
@@ -69,7 +69,7 @@ describe('playlists API helper', () => {
|
||||
});
|
||||
|
||||
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' });
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user