mirror of
https://github.com/navidrome/navidrome.git
synced 2025-08-13 14:01:14 +03:00
* fix: enable library access for headless processes Fixed multi-library filtering to allow headless processes (shares, external providers) to access data by skipping library restrictions when no user context is present. Previously, the library filtering system returned empty results (WHERE 1=0) for processes without user authentication, breaking functionality like public shares and external service integrations. Key changes: - Modified applyLibraryFilter methods to skip filtering when user.ID == invalidUserId - Refactored tag repository to use helper method for library filtering logic - Fixed SQL aggregation bug in tag statistics calculation across multiple libraries - Added comprehensive test coverage for headless process scenarios - Updated genre repository to support proper column mappings for aggregated data This preserves the secure "safe by default" approach for authenticated users while restoring backward compatibility for background processes that need unrestricted data access. Signed-off-by: Deluan <deluan@navidrome.org> * fix: resolve SQL ambiguity errors in share queries Fixed SQL ambiguity errors that were breaking share links after the Multi-library PR. The Multi-library changes introduced JOINs between album and library tables, both of which have 'id' columns, causing 'ambiguous column name: id' errors when unqualified column references were used in WHERE clauses. Changes made: - Updated core/share.go to use 'album.id' instead of 'id' in contentsLabelFromAlbums - Updated persistence/share_repository.go to use 'album.id' in album share loading - Updated persistence/sql_participations.go to use 'artist.id' for consistency - Added regression tests to prevent future SQL ambiguity issues This resolves HTTP 500 errors that users experienced when accessing existing share URLs after the Multi-library feature was merged. Signed-off-by: Deluan <deluan@navidrome.org> * fix: improve headless library access handling Added proper user context validation and reordered joins in applyLibraryFilterToArtistQuery to ensure library filtering works correctly for both authenticated and headless operations. The user_library join is now only applied when a valid user context exists, while the library_artist join is always applied to maintain proper data relationships. (+1 squashed commit) Squashed commits: [a28c6965b] fix: remove headless library access guard Removed the invalidUserId guard condition in applyLibraryFilterToArtistQuery that was preventing proper library filtering for headless operations. This fix ensures that library filtering joins are always applied consistently, allowing headless library access to work correctly with the library_artist junction table filtering. The previous guard was skipping all library filtering when no user context was present, which could cause issues with headless operations that still need to respect library boundaries through the library_artist relationship. * fix: simplify genre selection query in genre repository Signed-off-by: Deluan <deluan@navidrome.org> * fix: enhance tag library filtering tests for headless access Signed-off-by: Deluan <deluan@navidrome.org> * test: add comprehensive test coverage for headless library access Added extensive test coverage for headless library access improvements including: - Added 17 new tests across 4 test files covering headless access scenarios - artist_repository_test.go: Added headless process tests for GetAll, Count, Get operations and explicit library_id filtering functionality - genre_repository_test.go: Added library filtering tests for headless processes including GetAll, Count, ReadAll, and Read operations - sql_base_repository_test.go: Added applyLibraryFilter method tests covering admin users, regular users, and headless processes with/without custom table names - share_repository_test.go: Added headless access tests and SQL ambiguity verification for the album.id vs id fix in loadMedia function - Cleaned up test setup by replacing log.NewContext usage with GinkgoT().Context() and removing unnecessary configtest.SetupConfig() calls for better test isolation These tests ensure that headless processes (background operations without user context) can access all libraries while respecting explicit filters, and verify that the SQL ambiguity fixes work correctly without breaking existing functionality. * revert: remove user context handling from scrobble buffer getParticipants Reverts commit 5b8ef74f05109ecf30ddfc936361b84314522869. The artist repository no longer requires user context for proper library filtering, so the workaround of temporarily injecting user context into the scrobbleBufferRepository.Next method is no longer needed. This simplifies the code and removes the dependency on fetching user information during background scrobbling operations. * fix: improve library access filtering for artists Enhanced artist repository filtering to properly handle library access restrictions and prevent artists with no accessible content from appearing in results. Backend changes: - Modified roleFilter to use direct JSON_EXTRACT instead of EXISTS subquery for better performance - Enhanced applyLibraryFilterToArtistQuery to filter out artists with empty stats (no content) - Changed from LEFT JOIN to INNER JOIN with library_artist table for stricter filtering - Added condition to exclude artists where library_artist.stats = '{}' (empty content) Frontend changes: - Added null-checking in getCounter function to prevent TypeError when accessing undefined records - Improved optional chaining for safer property access in role-based statistics display These changes ensure that users only see artists that have actual accessible content in their permitted libraries, fixing issues where artists appeared in the list despite having no albums or songs available to the user. * fix: update library access logic for non-admin users and enhance test coverage Signed-off-by: Deluan <deluan@navidrome.org> * fix: refine library artist query and implement cleanup for empty entries Signed-off-by: Deluan <deluan@navidrome.org> * refactor: consolidate artist repository tests to eliminate duplication Significantly refactored artist_repository_test.go to reduce code duplication and improve maintainability by ~27% (930 to 680 lines). Key improvements include: - Added test helper functions createTestArtistWithMBID() and createUserWithLibraries() to eliminate repetitive test data creation - Consolidated duplicate MBID search tests using DescribeTable for parameterized testing - Removed entire 'Permission-Based Behavior Comparison' section (~150 lines) that duplicated functionality already covered in other test contexts - Reorganized search tests into cohesive 'MBID and Text Search' section with proper setup/teardown and shared test infrastructure - Streamlined missing artist tests and moved them to dedicated section - Maintained 100% test coverage while eliminating redundant test patterns All tests continue to pass with identical functionality and coverage. --------- Signed-off-by: Deluan <deluan@navidrome.org>
203 lines
5.4 KiB
Go
203 lines
5.4 KiB
Go
package persistence
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
. "github.com/Masterminds/squirrel"
|
|
"github.com/deluan/rest"
|
|
"github.com/navidrome/navidrome/log"
|
|
"github.com/navidrome/navidrome/model"
|
|
"github.com/navidrome/navidrome/model/request"
|
|
"github.com/pocketbase/dbx"
|
|
)
|
|
|
|
type shareRepository struct {
|
|
sqlRepository
|
|
}
|
|
|
|
func NewShareRepository(ctx context.Context, db dbx.Builder) model.ShareRepository {
|
|
r := &shareRepository{}
|
|
r.ctx = ctx
|
|
r.db = db
|
|
r.registerModel(&model.Share{}, nil)
|
|
r.setSortMappings(map[string]string{
|
|
"username": "username",
|
|
})
|
|
return r
|
|
}
|
|
|
|
func (r *shareRepository) Delete(id string) error {
|
|
err := r.delete(Eq{"id": id})
|
|
if errors.Is(err, model.ErrNotFound) {
|
|
return rest.ErrNotFound
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (r *shareRepository) selectShare(options ...model.QueryOptions) SelectBuilder {
|
|
return r.newSelect(options...).Join("user u on u.id = share.user_id").
|
|
Columns("share.*", "user_name as username")
|
|
}
|
|
|
|
func (r *shareRepository) Exists(id string) (bool, error) {
|
|
return r.exists(Eq{"id": id})
|
|
}
|
|
|
|
func (r *shareRepository) Get(id string) (*model.Share, error) {
|
|
sel := r.selectShare().Where(Eq{"share.id": id})
|
|
var res model.Share
|
|
err := r.queryOne(sel, &res)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
err = r.loadMedia(&res)
|
|
return &res, err
|
|
}
|
|
|
|
func (r *shareRepository) GetAll(options ...model.QueryOptions) (model.Shares, error) {
|
|
sq := r.selectShare(options...)
|
|
res := model.Shares{}
|
|
err := r.queryAll(sq, &res)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for i := range res {
|
|
err = r.loadMedia(&res[i])
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error loading media for share %s: %w", res[i].ID, err)
|
|
}
|
|
}
|
|
return res, err
|
|
}
|
|
|
|
func (r *shareRepository) loadMedia(share *model.Share) error {
|
|
var err error
|
|
ids := strings.Split(share.ResourceIDs, ",")
|
|
if len(ids) == 0 {
|
|
return nil
|
|
}
|
|
noMissing := func(cond Sqlizer) Sqlizer {
|
|
return And{cond, Eq{"missing": false}}
|
|
}
|
|
switch share.ResourceType {
|
|
case "artist":
|
|
albumRepo := NewAlbumRepository(r.ctx, r.db)
|
|
share.Albums, err = albumRepo.GetAll(model.QueryOptions{Filters: noMissing(Eq{"album_artist_id": ids}), Sort: "artist"})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
mfRepo := NewMediaFileRepository(r.ctx, r.db)
|
|
share.Tracks, err = mfRepo.GetAll(model.QueryOptions{Filters: noMissing(Eq{"album_artist_id": ids}), Sort: "artist"})
|
|
return err
|
|
case "album":
|
|
albumRepo := NewAlbumRepository(r.ctx, r.db)
|
|
share.Albums, err = albumRepo.GetAll(model.QueryOptions{Filters: noMissing(Eq{"album.id": ids})})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
mfRepo := NewMediaFileRepository(r.ctx, r.db)
|
|
share.Tracks, err = mfRepo.GetAll(model.QueryOptions{Filters: noMissing(Eq{"album_id": ids}), Sort: "album"})
|
|
return err
|
|
case "playlist":
|
|
// Create a context with a fake admin user, to be able to access all playlists
|
|
ctx := request.WithUser(r.ctx, model.User{IsAdmin: true})
|
|
plsRepo := NewPlaylistRepository(ctx, r.db)
|
|
tracks, err := plsRepo.Tracks(ids[0], true).GetAll(model.QueryOptions{Sort: "id", Filters: noMissing(Eq{})})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(tracks) >= 0 {
|
|
share.Tracks = tracks.MediaFiles()
|
|
}
|
|
return nil
|
|
case "media_file":
|
|
mfRepo := NewMediaFileRepository(r.ctx, r.db)
|
|
tracks, err := mfRepo.GetAll(model.QueryOptions{Filters: noMissing(Eq{"media_file.id": ids})})
|
|
share.Tracks = sortByIdPosition(tracks, ids)
|
|
return err
|
|
}
|
|
log.Warn(r.ctx, "Unsupported Share ResourceType", "share", share.ID, "resourceType", share.ResourceType)
|
|
return nil
|
|
}
|
|
|
|
func sortByIdPosition(mfs model.MediaFiles, ids []string) model.MediaFiles {
|
|
m := map[string]int{}
|
|
for i, mf := range mfs {
|
|
m[mf.ID] = i
|
|
}
|
|
var sorted model.MediaFiles
|
|
for _, id := range ids {
|
|
if idx, ok := m[id]; ok {
|
|
sorted = append(sorted, mfs[idx])
|
|
}
|
|
}
|
|
return sorted
|
|
}
|
|
|
|
func (r *shareRepository) Update(id string, entity interface{}, cols ...string) error {
|
|
s := entity.(*model.Share)
|
|
// TODO Validate record
|
|
s.ID = id
|
|
s.UpdatedAt = time.Now()
|
|
cols = append(cols, "updated_at")
|
|
_, err := r.put(id, s, cols...)
|
|
if errors.Is(err, model.ErrNotFound) {
|
|
return rest.ErrNotFound
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (r *shareRepository) Save(entity interface{}) (string, error) {
|
|
s := entity.(*model.Share)
|
|
// TODO Validate record
|
|
u := loggedUser(r.ctx)
|
|
if s.UserID == "" {
|
|
s.UserID = u.ID
|
|
}
|
|
s.CreatedAt = time.Now()
|
|
s.UpdatedAt = time.Now()
|
|
id, err := r.put(s.ID, s)
|
|
if errors.Is(err, model.ErrNotFound) {
|
|
return "", rest.ErrNotFound
|
|
}
|
|
return id, err
|
|
}
|
|
|
|
func (r *shareRepository) CountAll(options ...model.QueryOptions) (int64, error) {
|
|
return r.count(r.selectShare(), options...)
|
|
}
|
|
|
|
func (r *shareRepository) Count(options ...rest.QueryOptions) (int64, error) {
|
|
return r.CountAll(r.parseRestOptions(r.ctx, options...))
|
|
}
|
|
|
|
func (r *shareRepository) EntityName() string {
|
|
return "share"
|
|
}
|
|
|
|
func (r *shareRepository) NewInstance() interface{} {
|
|
return &model.Share{}
|
|
}
|
|
|
|
func (r *shareRepository) Read(id string) (interface{}, error) {
|
|
sel := r.selectShare().Where(Eq{"share.id": id})
|
|
var res model.Share
|
|
err := r.queryOne(sel, &res)
|
|
return &res, err
|
|
}
|
|
|
|
func (r *shareRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
|
|
sq := r.selectShare(r.parseRestOptions(r.ctx, options...))
|
|
res := model.Shares{}
|
|
err := r.queryAll(sq, &res)
|
|
return res, err
|
|
}
|
|
|
|
var _ model.ShareRepository = (*shareRepository)(nil)
|
|
var _ rest.Repository = (*shareRepository)(nil)
|
|
var _ rest.Persistable = (*shareRepository)(nil)
|