Deluan Quintão c66ef04dd3
refactor(jellyfin): emit real 128-bit GUIDs as item ids (#5942)
* test(jellyfin): use canonical ids in dto fixtures

Fixtures used short placeholder strings, which are not valid Navidrome ids. Deriving them from
id.NewHash keeps the labels readable while exercising the real id shape.

* test(jellyfin): use canonical ids in handler fixtures

Fixtures used short placeholder strings, which are not valid Navidrome ids. Deriving them from
id.NewHash keeps the labels readable while exercising the real id shape. Playlist entry positions
stay decimal, matching the integer playlist_tracks.id column.

* test(jellyfin): use canonical ids in e2e fixtures

Fixtures used short placeholder strings, which are not valid Navidrome ids. Deriving them from
id.NewHash keeps the labels readable while exercising the real id shape.

* test(jellyfin): use canonical ids in audiomuse fixtures

audiomuse_test.go passes ids as bare function args (mf(id, ...), call(query, user)) rather than
via ID: struct-literal fields, so the original grep-built file list missed it. Same conversion as
the rest of the fixtures: fake labels through id.NewHash via testID.

* test(jellyfin): convert remaining nonexistent-id sentinels in e2e tests

Reviewer swept for enc("literal") sites the brief's dto.EncodeID grep missed. These "does not
exist" fixtures must stay well-formed GUIDs under the strict codec, or the test degrades from
"resolves to nothing" to "empty path segment".

* refactor(jellyfin): emit real 128-bit GUIDs as item ids

Navidrome ids are now a canonical 22-char base62 encoding of exactly 128 bits, so they map
losslessly onto Jellyfin GUIDs. Previously the API hex-encoded the id string itself, producing
44 hex chars where Jellyfin uses 32.

Integer library ids, the synthetic playlists folder, and playlist entry positions (a
playlist_tracks.id, an integer column) aren't 128-bit values, so they get a reserved GUID space
tagged by kind. DecodeID is now strict: malformed input returns an empty string instead of
passing through unchanged.

BREAKING: Jellyfin clients see entirely new item ids.

* fix(jellyfin): 404 malformed playlist ids instead of silently creating

updatePlaylist decoded a malformed playlistId to "", the same sentinel core/playlists.Create
uses to mean "make a new playlist" — the overload createPlaylist deliberately relies on. A
malformed id now 404s before reaching Create.

Also tightens id-codec test fixtures: several tests set chi params to a raw canonical id, which
now decodes to "" and only passed because the fakes ignore the id argument; and a batch of
not-found sentinels now use well-formed-but-nonexistent GUIDs so they exercise the intended path
instead of the malformed-id path. READMEs "lossless" claim softened to note the reserved space.

* refactor(jellyfin): drop the id truncation workaround

Finamp's saved-queue packing keeps the first 16 bytes of each item id. That was lossy only
because our ids were 44 hex chars; now they are 32, so the packing round-trips exactly and the
server-side prefix recovery is dead code.

Removes an indexed range scan per restored queue and the ambiguous-prefix path that could
resolve to the wrong item.

* fix(jellyfin): emit ServerId and PlaySessionId in Jellyfin's id format

Jellyfin serializes GUIDs without dashes; ServerId was emitting the dashed UUID form. A
ServerId persisted before this change is normalized on read rather than rewritten.

PlaySessionId was emitting a raw internal id instead of the encoded form.

BREAKING: the ServerId change makes clients treat the server as new, so users re-login once.

* fix(jellyfin): 404 on undecodable id filters instead of widening the query

DecodeID collapsed an absent param and an undecodable one into the empty string, and downstream
an empty id means no filter. A client sending a stale pre-upgrade id therefore had its filter
silently dropped: ParentId, ArtistIds and AlbumArtistIds each returned the whole library instead
of a scoped result. Every existing client hits this on first launch after the id format changes.

Scalar id params now distinguish the two cases and report not-found. List-valued params already
failed closed. EncodeID logs a diagnostic when a non-empty id is not canonical, which should not
happen post-migration and would otherwise ship an unaddressable item silently.

* test(jellyfin): drop comments that restate the spec names

* refactor(jellyfin): decode reserved GUIDs from bytes, not hex strings

DecodeID already had the 16 decoded bytes, then re-derived the kind tag and payload by slicing the
hex string and parsing it a second time. Reading them off the byte slice matches how the format is
specified and removes the duplicate parse.

Bounding the payload inside encodeReserved gives both encoders the 32-char guarantee, which only
EncodePlaylistEntryID enforced before.

Playlist entries now decode through DecodePlaylistEntryID, which rejects other kinds. The tag was
being encoded and then discarded, so a song id passed as an EntryId reached RemoveTracks as a
playlist_tracks position.

Drops the per-field log.Warn from EncodeID: it sat in a leaf codec without a ctx and would emit
once per item per request on exactly the bad-data population it was meant to surface.

* refactor(jellyfin): make DecodeID report whether the id was decodable

DecodeID returned the empty string for both an absent param and an undecodable one, and
downstream an empty id means no filter. That conflation is what let a stale id widen /Items to
the whole library; it had been patched at two call sites, leaving three different policies for an
undecodable id in one package and ~16 handlers correct only because a repo Get("") happens to fail.

Returning (string, bool) makes the ambiguity unrepresentable, and the compiler forces each of the
~22 sites to decide. URL params share one itemIDParam helper that 404s; id lists go through
DecodeIDs, which is all-or-nothing because dropping bad entries would empty a list and make its
len() > 0 filter gate vanish — the original bug by another route.

A well-formed but unknown id is still 200 with zero results; only malformed ids 404. Malformed
ids now also 404 on the image and similar/instant-mix routes, which previously answered with a
placeholder or an empty list.
2026-08-12 19:02:34 -04:00

162 lines
5.0 KiB
Go

package dto
import (
"encoding/hex"
"strconv"
"strings"
"github.com/navidrome/navidrome/model/id"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("id codec", func() {
Describe("canonical ids", func() {
It("round-trips a random id", func() {
ndID := id.NewRandom()
decoded, ok := DecodeID(EncodeID(ndID))
Expect(ok).To(BeTrue())
Expect(decoded).To(Equal(ndID))
})
It("round-trips a hash id", func() {
ndID := id.NewHash("artist", "Weird Al")
decoded, ok := DecodeID(EncodeID(ndID))
Expect(ok).To(BeTrue())
Expect(decoded).To(Equal(ndID))
})
It("emits exactly 32 lowercase hex chars", func() {
for range 20 {
Expect(EncodeID(id.NewRandom())).To(MatchRegexp("^[0-9a-f]{32}$"))
}
})
It("accepts a dashed GUID, matching Jellyfin's Guid.Parse", func() {
ndID := id.NewRandom()
guid := EncodeID(ndID)
dashed := guid[0:8] + "-" + guid[8:12] + "-" + guid[12:16] + "-" + guid[16:20] + "-" + guid[20:32]
decoded, ok := DecodeID(dashed)
Expect(ok).To(BeTrue())
Expect(decoded).To(Equal(ndID))
})
It("accepts an uppercase GUID", func() {
ndID := id.NewRandom()
decoded, ok := DecodeID(strings.ToUpper(EncodeID(ndID)))
Expect(ok).To(BeTrue())
Expect(decoded).To(Equal(ndID))
})
})
Describe("reserved space", func() {
DescribeTable("round-trips library ids",
func(libID int, guid string) {
Expect(EncodeLibraryID(libID)).To(Equal(guid))
decoded, ok := DecodeID(guid)
Expect(ok).To(BeTrue())
Expect(decoded).To(Equal(strconv.Itoa(libID)))
},
Entry("first library", 1, "00000000000000000000000001000001"),
Entry("double digit", 42, "0000000000000000000000000100002a"),
Entry("max payload", 0xffffff, "00000000000000000000000001ffffff"),
)
It("round-trips the playlists folder", func() {
Expect(PlaylistsFolderGUID).To(Equal("00000000000000000000000002000000"))
decoded, ok := DecodeID(PlaylistsFolderGUID)
Expect(ok).To(BeTrue())
Expect(decoded).To(Equal(PlaylistsFolderID))
})
DescribeTable("round-trips playlist entry positions",
func(entryID, guid string) {
Expect(EncodePlaylistEntryID(entryID)).To(Equal(guid))
decoded, ok := DecodePlaylistEntryID(guid)
Expect(ok).To(BeTrue())
Expect(decoded).To(Equal(entryID))
},
Entry("first entry", "1", "00000000000000000000000003000001"),
Entry("later entry", "300", "0000000000000000000000000300012c"),
)
It("rejects a non-integer playlist entry id", func() {
Expect(EncodePlaylistEntryID("s1")).To(Equal(""))
Expect(EncodePlaylistEntryID("")).To(Equal(""))
Expect(EncodePlaylistEntryID("-1")).To(Equal(""))
})
It("rejects a payload wider than the reserved 24 bits", func() {
Expect(EncodeLibraryID(1 << 24)).To(Equal(""))
Expect(EncodeLibraryID(-1)).To(Equal(""))
Expect(EncodePlaylistEntryID("16777216")).To(Equal(""))
})
It("keeps library and playlist-entry GUIDs distinct for the same number", func() {
Expect(EncodeLibraryID(3)).ToNot(Equal(EncodePlaylistEntryID("3")))
})
It("does not let one reserved kind decode as another", func() {
_, ok := DecodeID(EncodePlaylistEntryID("3"))
Expect(ok).To(BeFalse())
_, ok = DecodePlaylistEntryID(EncodeLibraryID(3))
Expect(ok).To(BeFalse())
_, ok = DecodePlaylistEntryID(PlaylistsFolderGUID)
Expect(ok).To(BeFalse())
})
It("rejects an unknown kind tag", func() {
_, ok := DecodeID("000000000000000000000000ff000000")
Expect(ok).To(BeFalse())
})
It("never emits the all-zero GUID, which Jellyfin serializes as null", func() {
Expect(EncodeLibraryID(0)).ToNot(Equal("00000000000000000000000000000000"))
Expect(PlaylistsFolderGUID).ToNot(Equal("00000000000000000000000000000000"))
})
})
Describe("malformed input", func() {
DescribeTable("DecodeID reports ok=false",
func(input string) {
decoded, ok := DecodeID(input)
Expect(ok).To(BeFalse())
Expect(decoded).To(BeEmpty())
},
Entry("empty", ""),
Entry("too short", "abc123"),
Entry("too long", "000000000000000000000000010000011"),
Entry("non-hex chars", "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"),
Entry("a raw base62 id", id.NewRandom()),
Entry("the old 44-char hex format", hex.EncodeToString([]byte("5QFKvMsJrd57QE2Le2dKKo"))),
)
It("encodes a non-canonical id to the empty string", func() {
Expect(EncodeID("")).To(Equal(""))
Expect(EncodeID("playlists")).To(Equal(""))
Expect(EncodeID("42")).To(Equal(""))
})
})
Describe("DecodeIDs", func() {
It("decodes every entry when all are well-formed", func() {
a, b := id.NewRandom(), id.NewRandom()
decoded, ok := DecodeIDs([]string{EncodeID(a), EncodeID(b)})
Expect(ok).To(BeTrue())
Expect(decoded).To(Equal([]string{a, b}))
})
It("is all-or-nothing: one malformed entry fails the whole list", func() {
decoded, ok := DecodeIDs([]string{EncodeID(id.NewRandom()), "not-a-guid"})
Expect(ok).To(BeFalse())
Expect(decoded).To(BeNil())
})
It("succeeds on an empty list", func() {
decoded, ok := DecodeIDs(nil)
Expect(ok).To(BeTrue())
Expect(decoded).To(BeEmpty())
})
})
})