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
+17 -8
View File
@@ -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)