Deluan Quintão 2e7e24a023
chore(lint): ban panic (#6478)
* chore(lint): ban panic in production code

Add a forbidigo rule that rejects panic outside tests and test helpers
(_test.go, tests/ and storagetest/). Its message says to return an error,
and to use log.Fatal only for startup failures.

The existing production panics are gone:
- model.MustParseArtworkID was only used by core/artwork tests. It is now a
  Gomega helper in those test suites, and it also panicked with the parsed
  ID instead of the error.
- isDBInitialized in db/migrations panicked on a query error and never
  closed its rows. It now uses QueryRowContext and logs the error.

The two http.ErrAbortHandler panics in the stream and API v1 handlers stay,
because net/http requires them to abort a response. They are marked with
//nolint:forbidigo. cmd/wire_injectors.go is not linted, because of its
wireinject build tag.

* chore(lint): ban panic in tests too

The panic ban excluded test files and test helpers, so agents could read it as permission to panic in tests. The rule now applies everywhere, and its message says what to use instead: return an error, or Expect(...)/Fail(...) in tests.

Test panics are replaced with Gomega assertions, and the helpers that assert call GinkgoHelper() so failures point at the calling spec. The fake HTTP clients in the deezer tests and getDirEntry use Fail(...). storagetest.FakeFS.UpdateTags now asserts with Gomega instead of panicking.

Seven test panics stay, marked //nolint:forbidigo: they exercise panic recovery or stand in for log.Fatal.

* refactor(tests): share panicking test helpers

Move mustParseArtworkID out of the two core/artwork suites into tests.MustParseArtworkID, and add conf.PanicOnLogFatal so the conf specs share one panicking logFatal stub and one //nolint. The MustPath spec now asserts the fatal message instead of capturing it. Also merge the back-to-back user and artist loops in the persistence suite setup.
2026-11-15 19:07:43 -05:00

99 lines
3.1 KiB
Go

package apiv1
import (
"errors"
"net/http"
"runtime/debug"
"slices"
"strings"
"github.com/go-chi/chi/v5"
"github.com/navidrome/navidrome/api"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
)
type Router struct {
http.Handler
ds model.DataStore
}
func New(ds model.DataStore) *Router {
rt := &Router{ds: ds}
rt.Handler = rt.routes()
return rt
}
func (rt *Router) routes() http.Handler {
r := chi.NewRouter()
r.Use(problemRecoverer, headAsGet(r))
r.NotFound(func(w http.ResponseWriter, req *http.Request) {
writeProblemStatus(w, req, http.StatusNotFound, ProblemCodeNotFound, "no such endpoint")
})
r.MethodNotAllowed(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Allow", strings.Join(allowedMethods(r, req), ", "))
writeProblemStatus(w, req, http.StatusMethodNotAllowed, ProblemCodeMethodNotAllowed, "")
})
r.Get("/openapi.json", specHandler(withBasePath(api.SpecJSON(), `"url": `, true), "application/json"))
r.Get("/openapi.yaml", specHandler(withBasePath(api.SpecYAML(), "url: ", false), "application/yaml"))
strict := NewStrictHandlerWithOptions(rt, nil, StrictHTTPServerOptions{
RequestErrorHandlerFunc: func(w http.ResponseWriter, req *http.Request, err error) {
writeProblemStatus(w, req, http.StatusBadRequest, "validation", err.Error())
},
ResponseErrorHandlerFunc: writeProblem,
})
HandlerWithOptions(strict, ChiServerOptions{BaseRouter: r, ErrorHandlerFunc: bindingErrorHandler})
return r
}
func problemRecoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
rec := recover()
if rec == nil {
return
}
if err, ok := rec.(error); ok && errors.Is(err, http.ErrAbortHandler) {
panic(rec) //nolint:forbidigo
}
log.Error(r.Context(), "API v1: panic in handler", "panic", rec, "stack", string(debug.Stack()))
writeProblemStatus(w, r, http.StatusInternalServerError, ProblemCodeInternal, "")
}()
next.ServeHTTP(w, r)
})
}
var routableMethods = []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete}
// Looks routes up on mux itself: chi's RouteContext().Routes points at the parent router when mounted.
func allowedMethods(mux chi.Routes, req *http.Request) []string {
path := routePath(req)
var allowed []string
for _, m := range routableMethods {
if mux.Match(chi.NewRouteContext(), m, path) || (m == http.MethodHead && slices.Contains(allowed, http.MethodGet)) {
allowed = append(allowed, m)
}
}
return allowed
}
func headAsGet(mux chi.Routes) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodHead && !mux.Match(chi.NewRouteContext(), http.MethodHead, routePath(req)) {
chi.RouteContext(req.Context()).RouteMethod = http.MethodGet
}
next.ServeHTTP(w, req)
})
}
}
func routePath(req *http.Request) string {
if rctx := chi.RouteContext(req.Context()); rctx != nil && rctx.RoutePath != "" {
return rctx.RoutePath
}
return req.URL.Path
}