From 986000db448f6446dbf88edf2eda2f6ce9ff2e60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deluan=20Quint=C3=A3o?= Date: Mon, 16 Nov 2026 23:18:26 -0500 Subject: [PATCH] chore(lint): enable errchkjson (#6486) errchkjson flags json.Marshal/MarshalIndent/Encoder.Encode calls whose error is discarded. Fixed all 27 sites by hand: errors are returned where the caller already returns one, logged in HTTP handlers and string-returning helpers, and asserted in tests. check-error-free-encoding stays off so every encode error is handled, even for safe types. report-no-exported is on, to catch structs that would silently encode as {}. --- .golangci.yml | 3 +++ adapters/listenbrainz/client.go | 5 ++++- cmd/missing.go | 5 ++++- cmd/pls.go | 5 ++++- cmd/plugin.go | 8 ++++---- cmd/user.go | 5 ++++- core/artwork/trace.go | 6 +++++- core/storage/storagetest/fake_storage.go | 6 ++++-- core/stream/decider_test.go | 3 ++- persistence/album_repository.go | 9 +++++++-- persistence/artist_repository.go | 5 ++++- persistence/criteria_sql_benchmark_test.go | 5 ++++- persistence/mediafile_repository.go | 9 +++++++-- persistence/sql_participations.go | 9 ++++++--- persistence/sql_tags.go | 9 ++++++--- plugins/host_config_test.go | 5 ++++- plugins/host_subsonicapi_test.go | 2 +- plugins/host_users_test.go | 5 ++++- plugins/manager_sync.go | 22 ++++++++++++++++------ server/apiv1/spec.go | 6 +++++- server/events/events.go | 12 ++++++++++-- server/jellyfin/discovery.go | 6 +++++- server/nativeapi/plugin.go | 8 ++++++-- server/nativeapi/quickconnect.go | 4 +++- server/subsonic/api.go | 2 +- utils/cache/cached_http_client.go | 15 +++++++++++---- 26 files changed, 134 insertions(+), 45 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 9ef792d3c..70b900fe5 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -14,6 +14,7 @@ linters: - depguard - dogsled - durationcheck + - errchkjson - errorlint - forbidigo - gocritic @@ -124,6 +125,8 @@ linters: errcheck: exclude-functions: - (*github.com/zeebo/xxh3.Hasher).Write + errchkjson: + report-no-exported: true gocritic: disable-all: true enabled-checks: diff --git a/adapters/listenbrainz/client.go b/adapters/listenbrainz/client.go index 36f700bd4..25252634c 100644 --- a/adapters/listenbrainz/client.go +++ b/adapters/listenbrainz/client.go @@ -162,7 +162,10 @@ func (c *client) path(endpoint string) (string, error) { } func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, endpoint string, r *listenBrainzRequest) (*listenBrainzResponse, error) { - b, _ := json.Marshal(r.Body) + b, err := json.Marshal(r.Body) + if err != nil { + return nil, fmt.Errorf("encoding request body: %w", err) + } uri, err := c.path(endpoint) if err != nil { return nil, err diff --git a/cmd/missing.go b/cmd/missing.go index ce95e39f0..e1fecd9cd 100644 --- a/cmd/missing.go +++ b/cmd/missing.go @@ -94,7 +94,10 @@ func writeMissingList(w io.Writer, format string, mfs model.MediaFileCursor) err if err != nil { return err } - j, _ := json.Marshal(displayMissingFile{ID: mf.ID, LibraryID: mf.LibraryID, Title: mf.Title, Album: mf.Album, Artist: mf.Artist, Path: mf.Path}) + j, err := json.Marshal(displayMissingFile{ID: mf.ID, LibraryID: mf.LibraryID, Title: mf.Title, Album: mf.Album, Artist: mf.Artist, Path: mf.Path}) + if err != nil { + return err + } _, _ = fmt.Fprintf(bw, "%s%s", sep, j) sep = "," } diff --git a/cmd/pls.go b/cmd/pls.go index bf16ea420..6f31d1ca6 100644 --- a/cmd/pls.go +++ b/cmd/pls.go @@ -247,7 +247,10 @@ func runList(ctx context.Context) { display[idx].Public = playlist.Public } - j, _ := json.Marshal(display) + j, err := json.Marshal(display) + if err != nil { + log.Fatal(ctx, "Failed to encode playlists", err) + } fmt.Printf("%s\n", j) } } diff --git a/cmd/plugin.go b/cmd/plugin.go index 523792aa2..d25803bf2 100644 --- a/cmd/plugin.go +++ b/cmd/plugin.go @@ -509,8 +509,8 @@ func usersToJSON(value string) (string, error) { names = append(names, u) } } - b, _ := json.Marshal(names) - return string(b), nil + b, err := json.Marshal(names) + return string(b), err } // librariesToJSON accepts either a JSON array (starts with '[') or a @@ -535,8 +535,8 @@ func librariesToJSON(value string) (string, error) { ids = append(ids, id) } } - b, _ := json.Marshal(ids) - return string(b), nil + b, err := json.Marshal(ids) + return string(b), err } var pluginRescanCmd = &cobra.Command{ diff --git a/cmd/user.go b/cmd/user.go index eb64e69fe..247b59951 100644 --- a/cmd/user.go +++ b/cmd/user.go @@ -469,7 +469,10 @@ func runUserList(ctx context.Context) { users[idx].Libraries = paths } - j, _ := json.Marshal(users) + j, err := json.Marshal(users) + if err != nil { + log.Fatal(ctx, "Failed to encode users", err) + } fmt.Printf("%s\n", j) } } diff --git a/core/artwork/trace.go b/core/artwork/trace.go index bca2f2c7d..68c0bd57a 100644 --- a/core/artwork/trace.go +++ b/core/artwork/trace.go @@ -7,6 +7,7 @@ import ( "slices" "sync" + "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/utils/str" ) @@ -94,7 +95,10 @@ func encodeSteps(steps []TraceStep, sourcePath string) string { } out = append(out, storedStep{C: s.Candidate, O: s.Outcome, D: str.TruncateRunes(d, maxTraceDetail, "...")}) } - b, _ := json.Marshal(out) // []storedStep is all strings, so this cannot fail + b, err := json.Marshal(out) + if err != nil { + log.Error("Artwork: Could not encode resolution trace", err) + } return string(b) } diff --git a/core/storage/storagetest/fake_storage.go b/core/storage/storagetest/fake_storage.go index ea95d6326..fab69da92 100644 --- a/core/storage/storagetest/fake_storage.go +++ b/core/storage/storagetest/fake_storage.go @@ -134,7 +134,8 @@ func (ffs *FakeFS) UpdateTags(filePath string, newTags map[string]any, when ...t var tags map[string]any gomega.Expect(json.Unmarshal(f.Data, &tags)).To(gomega.Succeed()) maps.Copy(tags, newTags) - data, _ := json.Marshal(tags) + data, err := json.Marshal(tags) + gomega.Expect(err).ToNot(gomega.HaveOccurred()) f.Data = data ffs.Touch(filePath, when...) } @@ -208,7 +209,8 @@ func File(tags ...map[string]any) *fstest.MapFile { if _, ok := ts[fakeFileInfoMode]; !ok { ts[fakeFileInfoMode] = fs.ModePerm } - data, _ := json.Marshal(ts) + data, err := json.Marshal(ts) + gomega.Expect(err).ToNot(gomega.HaveOccurred()) if _, ok := ts[fakeFileInfoSize]; !ok { ts[fakeFileInfoSize] = int64(len(data)) } diff --git a/core/stream/decider_test.go b/core/stream/decider_test.go index e5de9154d..979a29825 100644 --- a/core/stream/decider_test.go +++ b/core/stream/decider_test.go @@ -26,7 +26,8 @@ func withProbe(mf *model.MediaFile) *model.MediaFile { BitDepth: gg.V(mf.BitDepth), Channels: mf.Channels, } - data, _ := json.Marshal(probe) + data, err := json.Marshal(probe) + Expect(err).ToNot(HaveOccurred()) mf.ProbeData = string(data) return mf } diff --git a/persistence/album_repository.go b/persistence/album_repository.go index 5c96a845f..e0bc6ae08 100644 --- a/persistence/album_repository.go +++ b/persistence/album_repository.go @@ -79,8 +79,13 @@ func (a *dbAlbum) PostMapArgs(args map[string]any) error { args["search_participants"] = strings.Join(participantNames, " ") args["search_normalized"] = str.NormalizeForFTS(a.Name, a.AlbumArtist) - args["tags"] = marshalTags(a.Album.Tags) - args["participants"] = marshalParticipants(a.Album.Participants) + var err error + if args["tags"], err = marshalTags(a.Album.Tags); err != nil { + return err + } + if args["participants"], err = marshalParticipants(a.Album.Participants); err != nil { + return err + } folderIDs, err := json.Marshal(a.Album.FolderIDs) if err != nil { diff --git a/persistence/artist_repository.go b/persistence/artist_repository.go index 7a7ee3a19..6fb6fa583 100644 --- a/persistence/artist_repository.go +++ b/persistence/artist_repository.go @@ -102,7 +102,10 @@ func (a *dbArtist) PostMapArgs(m map[string]any) error { for _, s := range a.Artist.SimilarArtists { sa = append(sa, dbSimilarArtist{ID: s.ID, Name: s.Name}) } - similarArtists, _ := json.Marshal(sa) + similarArtists, err := json.Marshal(sa) + if err != nil { + return fmt.Errorf("marshalling similar artists: %w", err) + } m["similar_artists"] = string(similarArtists) // When adding a derived column here, also add it to the scanner's artist Put column list // in phase_1_folders.go, or rescans will never update it (how search_normalized went stale). diff --git a/persistence/criteria_sql_benchmark_test.go b/persistence/criteria_sql_benchmark_test.go index 499e09f10..829bf8245 100644 --- a/persistence/criteria_sql_benchmark_test.go +++ b/persistence/criteria_sql_benchmark_test.go @@ -250,7 +250,10 @@ func setupBenchData(b *testing.B, ctx context.Context, conn *dbx.DB, user model. primaryArtistName := fmt.Sprintf("Artist %04d", primaryArtistIdx) participants := map[string][]map[string]string{"artist": artistEntries} - participantsJSON, _ := json.Marshal(participants) + participantsJSON, err := json.Marshal(participants) + if err != nil { + b.Fatal(err) + } if _, err := mfStmt.Exec( trackID, diff --git a/persistence/mediafile_repository.go b/persistence/mediafile_repository.go index 324c88758..3dda5a132 100644 --- a/persistence/mediafile_repository.go +++ b/persistence/mediafile_repository.go @@ -74,8 +74,13 @@ func (m *dbMediaFile) PostMapArgs(args map[string]any) error { args["full_text"] = formatFullText(fullText...) args["search_participants"] = strings.Join(participantNames, " ") args["search_normalized"] = str.NormalizeForFTS(m.FullTitle(), m.Album, m.Artist, m.AlbumArtist) - args["tags"] = marshalTags(m.MediaFile.Tags) - args["participants"] = marshalParticipants(m.MediaFile.Participants) + var err error + if args["tags"], err = marshalTags(m.MediaFile.Tags); err != nil { + return err + } + if args["participants"], err = marshalParticipants(m.MediaFile.Participants); err != nil { + return err + } return nil } diff --git a/persistence/sql_participations.go b/persistence/sql_participations.go index 7d2280042..674006965 100644 --- a/persistence/sql_participations.go +++ b/persistence/sql_participations.go @@ -47,15 +47,18 @@ func participantIDFilter(table string, artistID any, negate bool, roles []model. return Expr(table+".id"+op+sql+")", args...) } -func marshalParticipants(participants model.Participants) string { +func marshalParticipants(participants model.Participants) (string, error) { dbParticipants := make(map[model.Role][]participant) for role, artists := range participants { for _, artist := range artists { dbParticipants[role] = append(dbParticipants[role], participant{ID: artist.ID, SubRole: artist.SubRole, Name: artist.Name}) } } - res, _ := json.Marshal(dbParticipants) - return string(res) + res, err := json.Marshal(dbParticipants) + if err != nil { + return "", fmt.Errorf("marshalling participants: %w", err) + } + return string(res), nil } func unmarshalParticipants(data string) (model.Participants, error) { diff --git a/persistence/sql_tags.go b/persistence/sql_tags.go index 7e1978453..45c4d44af 100644 --- a/persistence/sql_tags.go +++ b/persistence/sql_tags.go @@ -36,7 +36,7 @@ func unmarshalTags(data string) (model.Tags, error) { return res, nil } -func marshalTags(tags model.Tags) string { +func marshalTags(tags model.Tags) (string, error) { dbTags := dbTags{} for name, values := range tags { for _, value := range values { @@ -44,8 +44,11 @@ func marshalTags(tags model.Tags) string { dbTags[name] = append(dbTags[name], dbTag{ID: t.ID, Value: value}) } } - res, _ := json.Marshal(dbTags) - return string(res) + res, err := json.Marshal(dbTags) + if err != nil { + return "", fmt.Errorf("marshalling tags: %w", err) + } + return string(res), nil } // indexedTagNames are the tag types materialized into the _tags join tables, so filtering by diff --git a/plugins/host_config_test.go b/plugins/host_config_test.go index d61cec9a1..bd81b5cd4 100644 --- a/plugins/host_config_test.go +++ b/plugins/host_config_test.go @@ -98,7 +98,10 @@ func setupTestConfigPlugin(configJSON string) (*Manager, func(context.Context, t } defer instance.Close(ctx) - inputBytes, _ := json.Marshal(input) + inputBytes, err := json.Marshal(input) + if err != nil { + return nil, err + } _, outputBytes, err := instance.Call("nd_test_config", inputBytes) if err != nil { return nil, err diff --git a/plugins/host_subsonicapi_test.go b/plugins/host_subsonicapi_test.go index 52791145c..942e1cfd4 100644 --- a/plugins/host_subsonicapi_test.go +++ b/plugins/host_subsonicapi_test.go @@ -459,6 +459,6 @@ func (r *fakeSubsonicRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) }, } w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(response) + Expect(json.NewEncoder(w).Encode(response)).To(Succeed()) } } diff --git a/plugins/host_users_test.go b/plugins/host_users_test.go index 855362bfb..bcec92204 100644 --- a/plugins/host_users_test.go +++ b/plugins/host_users_test.go @@ -517,7 +517,10 @@ func callTestUsersPlugin(ctx context.Context, manager *Manager, input testUsersI } defer instance.Close(ctx) - inputBytes, _ := json.Marshal(input) + inputBytes, err := json.Marshal(input) + if err != nil { + return nil, err + } _, outputBytes, err := instance.Call("nd_test_users", inputBytes) if err != nil { return nil, err diff --git a/plugins/manager_sync.go b/plugins/manager_sync.go index 33b4f81d4..dfa14e952 100644 --- a/plugins/manager_sync.go +++ b/plugins/manager_sync.go @@ -31,10 +31,12 @@ func adminContext(ctx context.Context) context.Context { return request.WithUser(ctx, model.User{IsAdmin: true}) } -// marshalManifest marshals a manifest to JSON string, returning empty string on error. -func marshalManifest(m *Manifest) string { - b, _ := json.Marshal(m) - return string(b) +func marshalManifest(m *Manifest) (string, error) { + b, err := json.Marshal(m) + if err != nil { + return "", fmt.Errorf("marshalling manifest: %w", err) + } + return string(b), nil } // ComputeFileSHA256 computes the SHA-256 hash of a file without loading it into memory. @@ -55,11 +57,15 @@ func ComputeFileSHA256(path string) (string, error) { // addPluginToDB adds a new plugin to the database as disabled. func (m *Manager) addPluginToDB(ctx context.Context, repo model.PluginRepository, name, path string, metadata *PluginMetadata) error { + manifest, err := marshalManifest(metadata.Manifest) + if err != nil { + return err + } now := time.Now() newPlugin := &model.Plugin{ ID: name, Path: path, - Manifest: marshalManifest(metadata.Manifest), + Manifest: manifest, SHA256: metadata.SHA256, Enabled: false, CreatedAt: now, @@ -76,6 +82,10 @@ func (m *Manager) addPluginToDB(ctx context.Context, repo model.PluginRepository // updatePluginInDB updates an existing plugin in the database after a file change. // If the plugin was enabled, it will be unloaded and disabled. func (m *Manager) updatePluginInDB(ctx context.Context, repo model.PluginRepository, dbPlugin *model.Plugin, path string, metadata *PluginMetadata) error { + manifest, err := marshalManifest(metadata.Manifest) + if err != nil { + return err + } wasEnabled := dbPlugin.Enabled if wasEnabled { if err := m.unloadPlugin(dbPlugin.ID); err != nil { @@ -83,7 +93,7 @@ func (m *Manager) updatePluginInDB(ctx context.Context, repo model.PluginReposit } } dbPlugin.Path = path - dbPlugin.Manifest = marshalManifest(metadata.Manifest) + dbPlugin.Manifest = manifest dbPlugin.SHA256 = metadata.SHA256 dbPlugin.Enabled = false dbPlugin.LastError = "" diff --git a/server/apiv1/spec.go b/server/apiv1/spec.go index 244160d66..9a40cc029 100644 --- a/server/apiv1/spec.go +++ b/server/apiv1/spec.go @@ -46,6 +46,10 @@ func withBasePath(body []byte, key string, quotedInBundle bool) []byte { return body } // A JSON string is also a valid YAML double-quoted scalar, so one encoding escapes both formats. - newURL, _ := json.Marshal(serverURL) + newURL, err := json.Marshal(serverURL) + if err != nil { + log.Error("API v1: could not encode the server URL, serving the spec without the base path", err) + return body + } return bytes.Replace(body, old, append([]byte(key), newURL...), 1) } diff --git a/server/events/events.go b/server/events/events.go index ff0a8a40a..0f54a501b 100644 --- a/server/events/events.go +++ b/server/events/events.go @@ -7,6 +7,8 @@ import ( "strings" "time" "unicode" + + "github.com/navidrome/navidrome/log" ) type eventCtxKey string @@ -31,7 +33,10 @@ func (e *baseEvent) Name(evt Event) string { } func (e *baseEvent) Data(evt Event) string { - data, _ := json.Marshal(evt) + data, err := json.Marshal(evt) + if err != nil { + log.Error("Error encoding event", "event", e.Name(evt), err) + } return string(data) } @@ -84,6 +89,9 @@ func (rr *RefreshResource) Data(evt Event) string { return `{"*":"*"}` } r := evt.(*RefreshResource) - data, _ := json.Marshal(r.resources) + data, err := json.Marshal(r.resources) + if err != nil { + log.Error("Error encoding refresh event", err) + } return string(data) } diff --git a/server/jellyfin/discovery.go b/server/jellyfin/discovery.go index a3d8e436b..9bcf6bda4 100644 --- a/server/jellyfin/discovery.go +++ b/server/jellyfin/discovery.go @@ -77,7 +77,11 @@ func (d *Discovery) ServeOn(ctx context.Context, conn net.PacketConn) { continue } info := discoveryInfo{Address: discoveryAddress(ctx, remote), Id: d.serverID(ctx), Name: serverName()} - res, _ := json.Marshal(info) + res, err := json.Marshal(info) + if err != nil { + log.Error(ctx, "Jellyfin API: could not encode auto-discovery response", err) + continue + } log.Debug(ctx, "Jellyfin API: answering auto-discovery request", "from", remote.String(), "address", info.Address) if _, err := conn.WriteTo(res, remote); err != nil { log.Debug(ctx, "Jellyfin API: could not answer auto-discovery request", "to", remote.String(), err) diff --git a/server/nativeapi/plugin.go b/server/nativeapi/plugin.go index 1c067f6e2..736fcdb01 100644 --- a/server/nativeapi/plugin.go +++ b/server/nativeapi/plugin.go @@ -138,7 +138,9 @@ func (api *Router) updatePlugin(w http.ResponseWriter, r *http.Request) { } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusUnprocessableEntity) - _ = json.NewEncoder(w).Encode(errorResponse) + if err := json.NewEncoder(w).Encode(errorResponse); err != nil { + log.Error(ctx, "Error encoding enable plugin error response", "id", id, err) + } return } } else { @@ -186,7 +188,9 @@ func validateAndUpdateConfig(ctx context.Context, pm PluginManager, id, configJS w.WriteHeader(http.StatusBadRequest) // Try to return structured validation errors if available response := map[string]any{"message": err.Error()} - _ = json.NewEncoder(w).Encode(response) + if encErr := json.NewEncoder(w).Encode(response); encErr != nil { + log.Error(ctx, "Error encoding config validation response", "id", id, encErr) + } return err } diff --git a/server/nativeapi/quickconnect.go b/server/nativeapi/quickconnect.go index e2ce39161..7f511aaed 100644 --- a/server/nativeapi/quickconnect.go +++ b/server/nativeapi/quickconnect.go @@ -71,6 +71,8 @@ func writeQuickConnectResult(w http.ResponseWriter, r *http.Request, req quickco http.Error(w, "Internal Server Error", http.StatusInternalServerError) default: w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(quickConnectDevice{AppName: req.Device.App, AppVersion: req.Device.AppVersion, DeviceName: req.Device.Name}) + if err := json.NewEncoder(w).Encode(quickConnectDevice{AppName: req.Device.App, AppVersion: req.Device.AppVersion, DeviceName: req.Device.Name}); err != nil { + log.Error(r.Context(), "Error encoding Quick Connect response", err) + } } } diff --git a/server/subsonic/api.go b/server/subsonic/api.go index 4cb1f2c4c..b2c2d31c8 100644 --- a/server/subsonic/api.go +++ b/server/subsonic/api.go @@ -359,7 +359,7 @@ func sendResponseWithStatus(w http.ResponseWriter, r *http.Request, payload *res errResp := newResponse() errResp.Status = responses.StatusFailed errResp.Error = &responses.Error{Code: responses.ErrorGeneric, Message: "invalid callback parameter"} - response, _ = json.Marshal(responses.JsonWrapper{Subsonic: *errResp}) + response, err = json.Marshal(responses.JsonWrapper{Subsonic: *errResp}) break } w.Header().Set("Content-Type", "application/javascript") diff --git a/utils/cache/cached_http_client.go b/utils/cache/cached_http_client.go index 4eed243dd..36d3b8270 100644 --- a/utils/cache/cached_http_client.go +++ b/utils/cache/cached_http_client.go @@ -5,6 +5,7 @@ import ( "bytes" "encoding/base64" "encoding/json" + "fmt" "io" "net/http" "strings" @@ -42,7 +43,10 @@ func NewHTTPClient(wrapped httpDoer, ttl time.Duration) *HTTPClient { } func (c *HTTPClient) Do(req *http.Request) (*http.Response, error) { - key := c.serializeReq(req) + key, err := c.serializeReq(req) + if err != nil { + return nil, err + } cached := true start := time.Now() respStr, err := c.cache.GetWithLoader(key, func(key string) (string, time.Duration, error) { @@ -67,7 +71,7 @@ func (c *HTTPClient) Do(req *http.Request) (*http.Response, error) { return c.deserializeResponse(req, respStr) } -func (c *HTTPClient) serializeReq(req *http.Request) string { +func (c *HTTPClient) serializeReq(req *http.Request) (string, error) { data := requestData{ Method: req.Method, Header: req.Header, @@ -77,8 +81,11 @@ func (c *HTTPClient) serializeReq(req *http.Request) string { bodyData, _ := io.ReadAll(req.Body) data.Body = new(base64.StdEncoding.EncodeToString(bodyData)) } - j, _ := json.Marshal(&data) - return string(j) + j, err := json.Marshal(&data) + if err != nil { + return "", fmt.Errorf("encoding request cache key: %w", err) + } + return string(j), nil } func (c *HTTPClient) deserializeReq(reqStr string) (*http.Request, error) {