navidrome/server/nativeapi/plugin_test.go
Deluan Quintão b293b96256
refactor(persistence): stateless repositories with per-call context (#6149)
* refactor(persistence): adopt generic deluan/rest repository API

Pin deluan/rest to the refactor branch. REST-facing repository methods
take a context and return typed values. Drop DataStore.Resource and
ResourceRepository; the native API names typed repositories directly
through a per-request adapter that later commits remove.

* refactor(persistence): base repository helpers take a context

* refactor(persistence): LibraryRepository takes a context per call

* refactor(persistence): PropertyRepository takes a context per call

* refactor(persistence): UserPropsRepository takes a context per call

* refactor(persistence): TranscodingRepository takes a context per call

* refactor(persistence): ShareRepository takes a context per call

* refactor(persistence): PlayerRepository takes a context per call

* refactor(persistence): RadioRepository takes a context per call

* refactor(persistence): PlayQueueRepository takes a context per call

* refactor(persistence): Tag and Genre repositories take a context per call

* refactor(persistence): PluginRepository takes a context per call

* refactor(persistence): Scrobble repositories take a context per call

* refactor(persistence): FolderRepository takes a context per call

* refactor(persistence): Artwork repositories take a context per call

* refactor(persistence): UserRepository takes a context per call

* refactor(persistence): ArtistRepository takes a context per call

ReadAll no longer rewrites the shared sort mappings for the role filter;
it works on a per-call copy.

* test(persistence): assert artist role sort sanitization in ReadAll

* refactor(persistence): AlbumRepository takes a context per call

* test(persistence): pass the test context to album repository helpers

* refactor(persistence): MediaFileRepository takes a context per call

* refactor(persistence): Playlist repositories take a context per call

* refactor(persistence): build all repositories once per store

* refactor(core): REST repository wrappers are built once

* refactor(persistence): repositories are stateless

Remove the context field from the base repository and the per-request
REST adapter. Enable the containedctx linter so no repository can hold a
request context again.

* chore(lint): skip containedctx in test files

* refactor: share simplifications from the stateless repositories sweep

Add deleteOwnedAll on sqlRepository and use it in player/share Delete
to remove the duplicated bulk-delete loop; have Share.Repository()
return model.ShareRepository so subsonic sharing.go drops its repeated
type assertions.

* chore(core): assert REST wrappers implement Persistable

* chore: reformat imports

* perf(persistence): build repositories on first use

Each transaction store used to construct all 21 repositories up front,
paying for filter and sort mapping setup the block never touched. Fields
are now sync.OnceValue thunks, so a store only builds what it uses.

* fix(persistence): clean plugin references per deleted user

A bulk user delete that fails on a later id had already removed the
earlier rows but skipped their plugin cleanup. Cleanup now runs right
after each successful delete.

* fix(core): unload disabled plugins even when a user delete fails

A bulk delete can fail on a later id after earlier users were removed
and their plugins auto-disabled. The wrapper returned before unloading,
leaving those plugins running until the next successful delete or a
restart.

* chore(deps): pin deluan/rest to v1.0.1

Replaces the pseudo-version of the refactor branch with the tagged
release. REST error messages now name the bare type (Artist, not
model.Artist).

* test: use the spec context instead of context.Background()

Replace the context.Background()/context.TODO() calls this branch added
to tests with the spec's ctx, GinkgoT().Context(), or t/b.Context(), so
repository calls are bound to the running spec's lifetime.

* test: declare the spec context once per Describe

Set ctx from GinkgoT().Context() first in each top-level BeforeEach and reuse it, building user contexts on top of it instead of repeating inline calls.
2026-09-25 18:06:10 -04:00

490 lines
16 KiB
Go

package nativeapi
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/server"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Plugin API", func() {
var ctx context.Context
var ds *tests.MockDataStore
var mockManager *tests.MockPluginManager
var router http.Handler
var adminUser, regularUser model.User
var testPlugin1, testPlugin2 model.Plugin
BeforeEach(func() {
ctx = GinkgoT().Context()
DeferCleanup(configtest.SetupConfig())
conf.Server.EnableSharing = false
conf.Server.Plugins.Enabled = true
ds = &tests.MockDataStore{}
mockManager = &tests.MockPluginManager{}
auth.Init(ds)
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, mockManager, nil, nil, nil)
router = server.JWTVerifier(nativeRouter)
// Create test users
adminUser = model.User{
ID: "admin-1",
UserName: "admin",
Name: "Admin User",
IsAdmin: true,
NewPassword: "adminpass",
}
regularUser = model.User{
ID: "user-1",
UserName: "regular",
Name: "Regular User",
IsAdmin: false,
NewPassword: "userpass",
}
// Create test plugins
testPlugin1 = model.Plugin{
ID: "test-plugin-1",
Path: "/plugins/test1.wasm",
Manifest: `{"name":"Test Plugin 1","version":"1.0.0"}`,
SHA256: "abc123",
Enabled: false,
}
testPlugin2 = model.Plugin{
ID: "test-plugin-2",
Path: "/plugins/test2.wasm",
Manifest: `{"name":"Test Plugin 2","version":"2.0.0"}`,
Config: `{"setting":"value"}`,
SHA256: "def456",
Enabled: true,
}
// Store users in mock datastore
Expect(ds.User().Put(ctx, &adminUser)).To(Succeed())
Expect(ds.User().Put(ctx, &regularUser)).To(Succeed())
})
Context("when plugins are disabled", func() {
BeforeEach(func() {
conf.Server.Plugins.Enabled = false
})
It("returns 404 for all plugin endpoints", func() {
adminToken, err := auth.CreateToken(&adminUser)
Expect(err).ToNot(HaveOccurred())
req := httptest.NewRequest("GET", "/plugin", nil)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusNotFound))
})
})
Context("when plugins are enabled", func() {
Describe("as admin user", func() {
var adminToken string
BeforeEach(func() {
var err error
adminToken, err = auth.CreateToken(&adminUser)
Expect(err).ToNot(HaveOccurred())
// Store test plugins as admin
adminCtx := request.WithUser(ctx, adminUser)
Expect(ds.Plugin().Put(adminCtx, &testPlugin1)).To(Succeed())
Expect(ds.Plugin().Put(adminCtx, &testPlugin2)).To(Succeed())
})
Describe("GET /api/plugin", func() {
It("returns all plugins", func() {
req := httptest.NewRequest("GET", "/plugin", nil)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusOK))
var plugins []model.Plugin
err := json.Unmarshal(w.Body.Bytes(), &plugins)
Expect(err).ToNot(HaveOccurred())
Expect(plugins).To(HaveLen(2))
})
})
Describe("GET /api/plugin/{id}", func() {
It("returns a specific plugin", func() {
req := httptest.NewRequest("GET", "/plugin/test-plugin-1", nil)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusOK))
var plugin model.Plugin
err := json.Unmarshal(w.Body.Bytes(), &plugin)
Expect(err).ToNot(HaveOccurred())
Expect(plugin.ID).To(Equal("test-plugin-1"))
Expect(plugin.Path).To(Equal("/plugins/test1.wasm"))
})
It("returns 404 for non-existent plugin", func() {
req := httptest.NewRequest("GET", "/plugin/non-existent", nil)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusNotFound))
})
})
Describe("PUT /api/plugin/{id}", func() {
It("updates plugin enabled state", func() {
// Configure mock to update the repo when EnablePlugin is called
mockManager.EnablePluginFn = func(ctx context.Context, id string) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Enabled = true
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"enabled":true}`)
req := httptest.NewRequest("PUT", "/plugin/test-plugin-1", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusOK))
var plugin model.Plugin
err := json.Unmarshal(w.Body.Bytes(), &plugin)
Expect(err).ToNot(HaveOccurred())
Expect(plugin.Enabled).To(BeTrue())
Expect(mockManager.EnablePluginCalls).To(ContainElement("test-plugin-1"))
})
It("updates plugin config with valid JSON", func() {
// Configure mock to update the repo when UpdatePluginConfig is called
mockManager.UpdatePluginConfigFn = func(ctx context.Context, id, configJSON string) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Config = configJSON
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"config":"{\"key\":\"value\"}"}`)
req := httptest.NewRequest("PUT", "/plugin/test-plugin-1", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusOK))
var plugin model.Plugin
err := json.Unmarshal(w.Body.Bytes(), &plugin)
Expect(err).ToNot(HaveOccurred())
Expect(plugin.Config).To(Equal(`{"key":"value"}`))
Expect(mockManager.UpdatePluginConfigCalls).To(HaveLen(1))
Expect(mockManager.UpdatePluginConfigCalls[0].ConfigJSON).To(Equal(`{"key":"value"}`))
})
It("rejects invalid JSON in config field", func() {
body := bytes.NewBufferString(`{"config":"not valid json"}`)
req := httptest.NewRequest("PUT", "/plugin/test-plugin-1", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusBadRequest))
Expect(w.Body.String()).To(ContainSubstring("Invalid JSON"))
})
It("allows empty config", func() {
// Configure mock to update the repo when UpdatePluginConfig is called
mockManager.UpdatePluginConfigFn = func(ctx context.Context, id, configJSON string) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Config = configJSON
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"config":""}`)
req := httptest.NewRequest("PUT", "/plugin/test-plugin-1", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusOK))
var plugin model.Plugin
err := json.Unmarshal(w.Body.Bytes(), &plugin)
Expect(err).ToNot(HaveOccurred())
Expect(plugin.Config).To(Equal(""))
})
It("updates users field", func() {
// Configure mock to update the repo when UpdatePluginUsers is called
mockManager.UpdatePluginUsersFn = func(ctx context.Context, id, usersJSON string, allUsers bool) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Users = usersJSON
p.AllUsers = allUsers
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"users":"[\"user1\",\"user2\"]"}`)
req := httptest.NewRequest("PUT", "/plugin/test-plugin-1", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusOK))
var plugin model.Plugin
err := json.Unmarshal(w.Body.Bytes(), &plugin)
Expect(err).ToNot(HaveOccurred())
Expect(plugin.Users).To(Equal(`["user1","user2"]`))
Expect(mockManager.UpdatePluginUsersCalls).To(HaveLen(1))
Expect(mockManager.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["user1","user2"]`))
})
It("updates allUsers field", func() {
// Configure mock to update the repo when UpdatePluginUsers is called
mockManager.UpdatePluginUsersFn = func(ctx context.Context, id, usersJSON string, allUsers bool) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Users = usersJSON
p.AllUsers = allUsers
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"allUsers":true}`)
req := httptest.NewRequest("PUT", "/plugin/test-plugin-1", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusOK))
var plugin model.Plugin
err := json.Unmarshal(w.Body.Bytes(), &plugin)
Expect(err).ToNot(HaveOccurred())
Expect(plugin.AllUsers).To(BeTrue())
Expect(mockManager.UpdatePluginUsersCalls).To(HaveLen(1))
Expect(mockManager.UpdatePluginUsersCalls[0].AllUsers).To(BeTrue())
})
It("updates both users and allUsers fields together", func() {
// Configure mock to update the repo when UpdatePluginUsers is called
mockManager.UpdatePluginUsersFn = func(ctx context.Context, id, usersJSON string, allUsers bool) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Users = usersJSON
p.AllUsers = allUsers
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"users":"[\"user1\"]","allUsers":false}`)
req := httptest.NewRequest("PUT", "/plugin/test-plugin-1", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusOK))
var plugin model.Plugin
err := json.Unmarshal(w.Body.Bytes(), &plugin)
Expect(err).ToNot(HaveOccurred())
Expect(plugin.Users).To(Equal(`["user1"]`))
Expect(plugin.AllUsers).To(BeFalse())
Expect(mockManager.UpdatePluginUsersCalls).To(HaveLen(1))
})
It("rejects invalid JSON in users field", func() {
body := bytes.NewBufferString(`{"users":"not valid json"}`)
req := httptest.NewRequest("PUT", "/plugin/test-plugin-1", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusBadRequest))
Expect(w.Body.String()).To(ContainSubstring("Invalid JSON"))
})
It("allows empty users", func() {
// Configure mock to update the repo when UpdatePluginUsers is called
mockManager.UpdatePluginUsersFn = func(ctx context.Context, id, usersJSON string, allUsers bool) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Users = usersJSON
p.AllUsers = allUsers
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"users":""}`)
req := httptest.NewRequest("PUT", "/plugin/test-plugin-1", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusOK))
var plugin model.Plugin
err := json.Unmarshal(w.Body.Bytes(), &plugin)
Expect(err).ToNot(HaveOccurred())
Expect(plugin.Users).To(Equal(""))
})
It("returns 404 for non-existent plugin", func() {
body := bytes.NewBufferString(`{"enabled":true}`)
req := httptest.NewRequest("PUT", "/plugin/non-existent", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusNotFound))
})
It("returns 400 for invalid request body", func() {
body := bytes.NewBufferString(`not json`)
req := httptest.NewRequest("PUT", "/plugin/test-plugin-1", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusBadRequest))
})
})
Describe("POST /api/plugin/rescan", func() {
It("triggers plugin rescan", func() {
req := httptest.NewRequest("POST", "/plugin/rescan", nil)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusOK))
Expect(mockManager.RescanPluginsCalls).To(Equal(1))
})
It("returns error when rescan fails", func() {
mockManager.RescanError = errors.New("folder not configured")
req := httptest.NewRequest("POST", "/plugin/rescan", nil)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+adminToken)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusInternalServerError))
Expect(w.Body.String()).To(ContainSubstring("folder not configured"))
})
})
})
Describe("as regular user", func() {
var userToken string
BeforeEach(func() {
var err error
userToken, err = auth.CreateToken(&regularUser)
Expect(err).ToNot(HaveOccurred())
})
It("denies access to GET /api/plugin", func() {
req := httptest.NewRequest("GET", "/plugin", nil)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+userToken)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusForbidden))
})
It("denies access to GET /api/plugin/{id}", func() {
req := httptest.NewRequest("GET", "/plugin/test-plugin-1", nil)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+userToken)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusForbidden))
})
It("denies access to PUT /api/plugin/{id}", func() {
body := bytes.NewBufferString(`{"enabled":true}`)
req := httptest.NewRequest("PUT", "/plugin/test-plugin-1", body)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+userToken)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusForbidden))
})
It("denies access to POST /api/plugin/rescan", func() {
req := httptest.NewRequest("POST", "/plugin/rescan", nil)
req.Header.Set(consts.UIAuthorizationHeader, "Bearer "+userToken)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusForbidden))
})
})
Describe("without authentication", func() {
It("denies access to plugin endpoints", func() {
req := httptest.NewRequest("GET", "/plugin", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusUnauthorized))
})
})
})
})