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
+4 -12
View File
@@ -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})
}
+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)
+13 -8
View File
@@ -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