navidrome/plugins/host_artwork_test.go
Deluan Quintão c9385fbb6b
test(plugins): build test plugins in Go instead of shelling out to make (#6060)
* test(plugins): build test plugins in Go instead of shelling out to make

The plugins suite built its .ndp test packages by running `make -C
plugins/testdata`, which needs make and zip on the PATH. That is the reason
the 26 WASM-dependent spec files are tagged //go:build !windows.

buildTestPlugins now does the same work in Go: the same mtime check make
performed, `GOOS=wasip1 GOARCH=wasm go build` per plugin, and archive/zip
for the package. TinyGo was already optional and unused in CI, so nothing is
lost there. The first plugin builds on its own so the shared wasip1 stdlib
and PDK objects land in the build cache before the rest fan out: on a cold
cache that is 2.2s against 3.4s for the sequential make and 7.3s for an
unrestrained fan-out.

Packaging moved into a writeNdp helper shared with createTestPackage, which
was already writing the same two-entry archive. Entries are written in a
fixed order, so the .ndp bytes are now reproducible; the loader hashes those
bytes, and `zip` also stored file mtimes, so the previous packages differed
on every rebuild.

The Makefile is unchanged and still works for building the plugins by hand.
Removing the !windows tags is a separate step, once CI is green here.

* test(plugins): run the WASM plugin specs on Windows

With the test plugins now built in Go, nothing in the suite needs a Unix
toolchain, so the //go:build !windows tags come off all 25 spec files. The
Windows CI job runs `go test ./...`, so it picks the suite up with no
workflow change.

plugins_suite_windows_test.go existed only to bootstrap the handful of specs
that compiled on Windows; plugins_suite_test.go now serves both.

* test(plugins): skip the planted-symlink spec where symlinks need privileges

os.Symlink needs an elevated token or Developer Mode on Windows, so the
unconditional Expect(...).To(Succeed()) would fail for contributors running
the suite on an ordinary Windows box. The elevated GitHub runner hides this.

The equivalent spec in sandbox_fs_internal_test.go already attempts the
symlink and skips on error; this does the same, keeping the pin live
everywhere it can run, including Windows CI.

* fix(ci): stop the Windows ndpgen test failing silently

The ndpgen suite builds its helper binary to %TEMP%\ndpgen-test, and Windows
will not exec a file without an executable extension, so the "supports
verbose mode" spec has been failing there. Nobody noticed because the
Test ndpgen step ran under pwsh, which carries on after a non-zero exit and
takes the step's status from the last command, so the job stayed green with
a FAIL line in its log.

Add the .exe suffix, and run the step under bash like the Linux job does, so
a failure in any of its three commands fails the job.
2026-08-31 21:42:10 -04:00

247 lines
7.1 KiB
Go

package plugins
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("ArtworkService", Ordered, func() {
var (
manager *Manager
tmpDir string
)
BeforeAll(func() {
var err error
tmpDir, err = os.MkdirTemp("", "artwork-test-*")
Expect(err).ToNot(HaveOccurred())
// Copy the test-artwork plugin
srcPath := filepath.Join(testdataDir, "test-artwork"+PackageExtension)
destPath := filepath.Join(tmpDir, "test-artwork"+PackageExtension)
data, err := os.ReadFile(srcPath)
Expect(err).ToNot(HaveOccurred())
err = os.WriteFile(destPath, data, 0600)
Expect(err).ToNot(HaveOccurred())
// Compute SHA256 for the plugin
hash := sha256.Sum256(data)
hashHex := hex.EncodeToString(hash[:])
// Setup config
DeferCleanup(configtest.SetupConfig())
conf.Server.Plugins.Enabled = true
conf.Server.Plugins.Folder = conf.NewDir(tmpDir)
conf.Server.Plugins.AutoReload = false
// Initialize auth (required for token generation)
ds := &tests.MockDataStore{MockedProperty: &tests.MockedPropertyRepo{}}
auth.Init(ds)
// Setup mock DataStore with pre-enabled plugin
mockPluginRepo := tests.CreateMockPluginRepo()
mockPluginRepo.Permitted = true
mockPluginRepo.SetData(model.Plugins{{
ID: "test-artwork",
Path: destPath,
SHA256: hashHex,
Enabled: true,
}})
dataStore := &tests.MockDataStore{
MockedProperty: &tests.MockedPropertyRepo{},
MockedPlugin: mockPluginRepo,
}
// Create and start manager
manager = &Manager{
plugins: make(map[string]*plugin),
ds: dataStore,
subsonicRouter: http.NotFoundHandler(),
}
err = manager.Start(GinkgoT().Context())
Expect(err).ToNot(HaveOccurred())
DeferCleanup(func() {
_ = manager.Stop()
_ = os.RemoveAll(tmpDir)
})
})
Describe("Plugin Loading", func() {
It("should load plugin with artwork permission", func() {
manager.mu.RLock()
p, ok := manager.plugins["test-artwork"]
manager.mu.RUnlock()
Expect(ok).To(BeTrue())
Expect(p.manifest.Permissions).ToNot(BeNil())
Expect(p.manifest.Permissions.Artwork).ToNot(BeNil())
})
})
Describe("Artwork URL Generation", func() {
type testArtworkInput struct {
ArtworkType string `json:"artwork_type"`
ID string `json:"id"`
Size int32 `json:"size"`
}
type testArtworkOutput struct {
URL string `json:"url,omitempty"`
Error *string `json:"error,omitempty"`
}
callTestArtwork := func(ctx context.Context, artworkType, id string, size int32) (string, error) {
manager.mu.RLock()
p := manager.plugins["test-artwork"]
manager.mu.RUnlock()
instance, err := p.instance(ctx)
if err != nil {
return "", err
}
defer instance.Close(ctx)
input := testArtworkInput{
ArtworkType: artworkType,
ID: id,
Size: size,
}
inputBytes, _ := json.Marshal(input)
_, outputBytes, err := instance.CallWithContext(ctx, "nd_test_artwork", inputBytes)
if err != nil {
return "", err
}
var output testArtworkOutput
if err := json.Unmarshal(outputBytes, &output); err != nil {
return "", err
}
if output.Error != nil {
return "", Errorf(*output.Error)
}
return output.URL, nil
}
It("should generate artist artwork URL", func() {
url, err := callTestArtwork(GinkgoT().Context(), "artist", "ar-123", 0)
Expect(err).ToNot(HaveOccurred())
Expect(url).To(ContainSubstring("/img/"))
Expect(url).ToNot(ContainSubstring("size="))
// Decode JWT and verify artwork ID
artID := decodeArtworkURL(url)
Expect(artID.Kind).To(Equal(model.KindArtistArtwork))
Expect(artID.ID).To(Equal("ar-123"))
})
It("should generate album artwork URL", func() {
url, err := callTestArtwork(GinkgoT().Context(), "album", "al-456", 0)
Expect(err).ToNot(HaveOccurred())
Expect(url).To(ContainSubstring("/img/"))
artID := decodeArtworkURL(url)
Expect(artID.Kind).To(Equal(model.KindAlbumArtwork))
Expect(artID.ID).To(Equal("al-456"))
})
It("should generate track artwork URL", func() {
url, err := callTestArtwork(GinkgoT().Context(), "track", "mf-789", 0)
Expect(err).ToNot(HaveOccurred())
Expect(url).To(ContainSubstring("/img/"))
artID := decodeArtworkURL(url)
Expect(artID.Kind).To(Equal(model.KindMediaFileArtwork))
Expect(artID.ID).To(Equal("mf-789"))
})
It("should generate playlist artwork URL", func() {
url, err := callTestArtwork(GinkgoT().Context(), "playlist", "pl-abc", 0)
Expect(err).ToNot(HaveOccurred())
Expect(url).To(ContainSubstring("/img/"))
artID := decodeArtworkURL(url)
Expect(artID.Kind).To(Equal(model.KindPlaylistArtwork))
Expect(artID.ID).To(Equal("pl-abc"))
})
It("should include size parameter when specified", func() {
url, err := callTestArtwork(GinkgoT().Context(), "album", "al-456", 300)
Expect(err).ToNot(HaveOccurred())
Expect(url).To(ContainSubstring("size=300"))
artID := decodeArtworkURL(url)
Expect(artID.Kind).To(Equal(model.KindAlbumArtwork))
Expect(artID.ID).To(Equal("al-456"))
})
It("uses the address of the request that triggered the plugin", func() {
ctx := request.WithServerAddress(GinkgoT().Context(), "https", "music.example.com")
url, err := callTestArtwork(ctx, "track", "mf-789", 300)
Expect(err).ToNot(HaveOccurred())
Expect(url).To(HavePrefix("https://music.example.com/share/img/"))
})
It("should handle unknown artwork type", func() {
_, err := callTestArtwork(GinkgoT().Context(), "unknown", "id-123", 0)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("unknown artwork type"))
})
})
})
// Errorf creates an error from a format string (helper for tests)
func Errorf(format string, args ...any) error {
return &errorString{s: format}
}
type errorString struct {
s string
}
func (e *errorString) Error() string {
return e.s
}
// decodeArtworkURL extracts and decodes the JWT token from an artwork URL,
// returning the parsed ArtworkID. Panics on error (test helper).
func decodeArtworkURL(artworkURL string) model.ArtworkID {
// URL format: http://localhost/img/<token>?size=...
// Extract token from path after /img/
idx := strings.Index(artworkURL, "/img/")
Expect(idx).To(BeNumerically(">=", 0), "URL should contain /img/")
tokenPart := artworkURL[idx+5:] // skip "/img/"
// Remove query string if present
if qIdx := strings.Index(tokenPart, "?"); qIdx >= 0 {
tokenPart = tokenPart[:qIdx]
}
// Decode JWT token
token, err := auth.PublicTokenAuth.Decode(tokenPart)
Expect(err).ToNot(HaveOccurred(), "Failed to decode JWT token")
c := auth.ClaimsFromToken(token)
id := c.ID
Expect(id).ToNot(BeEmpty(), "Token should contain 'id' claim")
artID, err := model.ParseArtworkID(id)
Expect(err).ToNot(HaveOccurred(), "Failed to parse artwork ID from token")
return artID
}