navidrome/plugins/host_websocket.go
Deluan Quintão 9ff0058620
fix: assorted scanner, plugin, and server fixes from the Go 1.27 work (#6050)
* fix(plugins): stop the cache janitor when a plugin cache is dropped

newCacheService started a ttlcache janitor goroutine that only stopped via the
explicit Close() path, so a cache service that was discarded without being closed
leaked its janitor for the process lifetime. It now registers the same
runtime.AddCleanup safety net that utils/cache.simpleCache already uses.

* fix(scanner): stop splitting multi-byte characters when truncating tags

sanitize() capped tag values with a byte slice, so a value whose limit falls in
the middle of a multi-byte character was stored as invalid UTF-8. defaultMaxTagLength
is 1024, which is not a multiple of 3, so any sufficiently long CJK title hit this.
Only trailing invalid bytes are trimmed, leaving bad bytes elsewhere in the value
untouched.

* fix(scanner): store MusicBrainz ids in their canonical form

uuid.Parse accepts a UUID wrapped in any two bytes, as well as braced and urn:
forms, but sanitize() returned the raw string. A tag like {<mbid>} or a quoted
value was therefore persisted with its wrapper into the mbz_* columns, where the
exact-match MBID search can never find it. The parsed value is now stored, which
also lowercases uppercase ids and adds the dashes to unhyphenated ones.

* fix(plugins): parse IPv6 hosts correctly in the websocket allowlist

isHostAllowed cut the host at the last colon, which mangles an IPv6 literal:
"[::1]:8080" became "[::1]" and "[::1]" became "[:". A plugin manifest could
therefore never allow an IPv6 host. It now uses net.SplitHostPort, falling back to
unwrapping the brackets when there is no port.

* fix(server): serve pprof profiles when a BaseURL is configured

net/http/pprof's Index resolves the profile name by trimming "/debug/pprof/" from
the raw request path, which never matches once MountRouter prepends the BasePath.
Requests for any profile without an explicit chi route fell through to the index
page, returning HTML with a 200 instead of the profile. The handler now strips the
BasePath first.

* test(scanner): run the goroutine leak check unconditionally

The scanner suite's goleak check only ran when the GOLEAK env var was set, so it
never ran in CI and could not catch a regression. It passes with the existing
ignore list, verified over repeated runs, so the gate is removed.

* fix(server): close the background image body on a non-200 response

serveImage returned early on an unexpected status code without closing the response
body, pinning the connection until the 5s client timeout. The nolint:bodyclose
above the request suppressed the linter that would have caught it, and its
justification only holds on the success path, where the body is handed to the
CachedStream wrapper.

* test(scanner): repair BenchmarkScan so it can actually run

The benchmark failed three ways before reaching its first iteration: it reused a
shared temp DB and tried to repoint the default library, it never loaded the config
defaults so the scanner got a concurrency of 0, and it lacked the notify ignore that
the suite already carries. tests.Init now takes a testing.TB so a benchmark can load
the test config the same way the suites do.

* refactor(artwork): drop the unused sourceFunc Stringer

sourceFunc.String derived a label from the closure's symbol name via reflection, but
nothing called it: the trace output builds its candidate labels from explicit strings.
Whole-program analysis confirms it is unreachable, and dropping it removes a
reflection-based dependency on compiler closure-naming details.

* refactor(plugins): reuse extractHostname in the websocket allowlist

The IPv6 host parsing added for isHostAllowed duplicated extractHostname, which
already lives in the same package and backs the HTTP client's identical allowlist
check. Two copies of a security-relevant parser can drift, so the websocket service
now calls the existing helper. The port-stripping specs move into the URL Validation
block that already covered them.

* perf(scanner): bound the tag truncation trim to a partial rune

The trim loop dropped every trailing byte that failed to decode, so a value ending
in a long run of invalid bytes was walked one byte at a time: a 1 MiB lyrics tag
measured 2.58ms against 45ns for a normal cut. A partial rune is at most 3 trailing
bytes, so the loop is capped there, which also stops it consuming a pre-existing
invalid run.

* test: tighten the tests added with the Go 1.27 bugfixes

Drop the testItem stub in favour of the package's own cacheKey, register the pprof
test profile once at package scope, and replace the hand-rolled goroutine settle
loop with Eventually. Also corrects a comment that credited a TestMain the scanner
suite does not have.

* test(scanner): ignore notify's nonrecursive-tree goroutines on Linux

The goroutine leak check only ignored the recursive tree (macOS/FSEvents).
Linux CI uses inotify, whose nonrecursive tree leaks dispatch and internal
goroutines after Stop(), failing the check.

* fix(scanner): avoid a truncation panic when MaxLength is 1 or 2

A value of only UTF-8 continuation bytes drained the partial-rune loop to
empty, then sliced value[:-1] and panicked. Break when DecodeLastRune returns
size 0 (empty string) by testing size != 1 instead of size > 1.

* fix: address Codex review on the pprof base path and scan benchmark

- profilerHandler: treat a root BasePath ("/") as no prefix, so http.StripPrefix
  keeps the leading slash chi needs; without this the profiler 404s when BaseURL
  is "/". Cover the root case in the test.
- BenchmarkScan: make it run regardless of test/benchmark ordering. Add
  singleton.DeleteInstance so a fresh DB is opened after TestScanner closes the
  shared one, guard driver registration with sync.Once so the rebuild does not
  re-Register, and ignore the Ginkgo interrupt-handler and Linux notify
  goroutines the preceding suite leaves behind.

* fix: address Codex round 2 on BasePath trailing slash and benchmark DB cleanup

- profilerHandler: trim all trailing slashes (TrimRight), not just a bare "/", so
  a BaseURL like "/music/" strips correctly instead of 404ing. Cover it in the test.
- BenchmarkScan: keep and defer db.Init's closer so the DB is closed before
  b.TempDir cleanup, which otherwise cannot delete the open SQLite/WAL files on Windows.
2026-08-30 21:24:50 -04:00

389 lines
11 KiB
Go

package plugins
import (
"context"
"errors"
"fmt"
"maps"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model/id"
"github.com/navidrome/navidrome/plugins/capabilities"
"github.com/navidrome/navidrome/plugins/host"
)
// CapabilityWebSocket indicates the plugin can receive WebSocket callbacks.
// Detected when the plugin exports any of the WebSocket callback functions.
const CapabilityWebSocket Capability = "WebSocket"
// webSocketCallbackTimeout is the maximum duration allowed for a WebSocket callback.
const webSocketCallbackTimeout = 30 * time.Second
// WebSocket callback function names
const (
FuncWebSocketOnTextMessage = "nd_websocket_on_text_message"
FuncWebSocketOnBinaryMessage = "nd_websocket_on_binary_message"
FuncWebSocketOnError = "nd_websocket_on_error"
FuncWebSocketOnClose = "nd_websocket_on_close"
)
func init() {
registerCapability(
CapabilityWebSocket,
FuncWebSocketOnTextMessage,
FuncWebSocketOnBinaryMessage,
FuncWebSocketOnError,
FuncWebSocketOnClose,
)
}
// wsConnection represents an active WebSocket connection.
type wsConnection struct {
conn *websocket.Conn
done chan struct{}
closeMu sync.Mutex
isClosed bool
}
// webSocketServiceImpl implements host.WebSocketService.
// It provides plugins with WebSocket communication capabilities.
type webSocketServiceImpl struct {
baseCtx context.Context // bounds the read loops, which outlive the Connect() call
pluginName string
manager *Manager
requiredHosts []string
mu sync.RWMutex
connections map[string]*wsConnection
}
// newWebSocketService creates a new WebSocketService for a plugin.
func newWebSocketService(ctx context.Context, pluginName string, manager *Manager, permission *WebSocketPermission) *webSocketServiceImpl {
return &webSocketServiceImpl{
baseCtx: ctx,
pluginName: pluginName,
manager: manager,
requiredHosts: permission.RequiredHosts,
connections: make(map[string]*wsConnection),
}
}
func (s *webSocketServiceImpl) Connect(ctx context.Context, urlStr string, headers map[string]string, connectionID string) (string, error) {
// Parse and validate URL
parsedURL, err := url.Parse(urlStr)
if err != nil {
return "", fmt.Errorf("invalid URL: %w", err)
}
// Validate scheme
if parsedURL.Scheme != "ws" && parsedURL.Scheme != "wss" {
return "", fmt.Errorf("invalid URL scheme: must be ws:// or wss://")
}
// Validate host against allowed hosts
if !s.isHostAllowed(parsedURL.Host) {
return "", fmt.Errorf("host %q is not allowed", parsedURL.Host)
}
// Generate connection ID if not provided
if connectionID == "" {
connectionID = id.NewRandom()
}
s.mu.Lock()
if _, exists := s.connections[connectionID]; exists {
s.mu.Unlock()
return "", fmt.Errorf("connection ID %q already exists", connectionID)
}
s.mu.Unlock()
// Create HTTP headers for handshake
httpHeaders := http.Header{}
for k, v := range headers {
httpHeaders.Set(k, v)
}
// Establish WebSocket connection
dialer := websocket.Dialer{
HandshakeTimeout: 30 * time.Second,
}
conn, resp, err := dialer.DialContext(ctx, urlStr, httpHeaders)
if resp != nil && resp.Body != nil {
_ = resp.Body.Close()
}
if err != nil {
return "", fmt.Errorf("failed to connect: %w", err)
}
wsConn := &wsConnection{
conn: conn,
done: make(chan struct{}),
}
s.mu.Lock()
s.connections[connectionID] = wsConn
s.mu.Unlock()
// Start read goroutine with the service's base context instead of the
// caller's ctx, because the readLoop must outlive the Connect() call.
// Connections are closed by Close() when the plugin is unloaded, which ends
// the readLoop; the base context is a backstop that also ends it on server
// shutdown (it is never cancelled in one-shot CLI runs).
go s.readLoop(s.baseCtx, connectionID, wsConn)
log.Debug(ctx, "WebSocket connected", "plugin", s.pluginName, "connectionID", connectionID, "url", urlStr)
return connectionID, nil
}
func (s *webSocketServiceImpl) SendText(ctx context.Context, connectionID, message string) error {
wsConn, err := s.getConnection(connectionID)
if err != nil {
return err
}
if err := wsConn.conn.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
return fmt.Errorf("failed to send text message: %w", err)
}
return nil
}
func (s *webSocketServiceImpl) SendBinary(ctx context.Context, connectionID string, data []byte) error {
wsConn, err := s.getConnection(connectionID)
if err != nil {
return err
}
if err := wsConn.conn.WriteMessage(websocket.BinaryMessage, data); err != nil {
return fmt.Errorf("failed to send binary message: %w", err)
}
return nil
}
func (s *webSocketServiceImpl) CloseConnection(ctx context.Context, connectionID string, code int32, reason string) error {
s.mu.Lock()
wsConn, exists := s.connections[connectionID]
if !exists {
s.mu.Unlock()
return fmt.Errorf("connection ID %q not found", connectionID)
}
delete(s.connections, connectionID)
s.mu.Unlock()
// Mark as closed to prevent callback
wsConn.closeMu.Lock()
wsConn.isClosed = true
wsConn.closeMu.Unlock()
// Send close message
closeMsg := websocket.FormatCloseMessage(int(code), reason)
_ = wsConn.conn.WriteControl(websocket.CloseMessage, closeMsg, time.Now().Add(5*time.Second))
_ = wsConn.conn.Close()
// Signal read goroutine to stop
close(wsConn.done)
// Invoke close callback
s.invokeOnClose(ctx, connectionID, code, reason)
log.Debug(ctx, "WebSocket connection closed", "plugin", s.pluginName, "connectionID", connectionID, "code", code)
return nil
}
// Close closes all connections for this plugin.
// This is called when the plugin is unloaded.
func (s *webSocketServiceImpl) Close() error {
s.mu.Lock()
connections := make(map[string]*wsConnection, len(s.connections))
maps.Copy(connections, s.connections)
s.connections = make(map[string]*wsConnection)
s.mu.Unlock()
ctx := context.Background()
for connID, wsConn := range connections {
wsConn.closeMu.Lock()
wsConn.isClosed = true
wsConn.closeMu.Unlock()
closeMsg := websocket.FormatCloseMessage(websocket.CloseGoingAway, "plugin unloaded")
err := wsConn.conn.WriteControl(websocket.CloseMessage, closeMsg, time.Now().Add(2*time.Second))
if err != nil {
log.Warn("Failed to send WebSocket close message on plugin unload", "plugin", s.pluginName, "connectionID", connID, "error", err)
}
err = wsConn.conn.Close()
if err != nil {
log.Warn("Failed to close WebSocket connection on plugin unload", "plugin", s.pluginName, "connectionID", connID, "error", err)
}
close(wsConn.done)
s.invokeOnClose(ctx, connID, websocket.CloseGoingAway, "plugin unloaded")
log.Debug("WebSocket connection closed on plugin unload", "plugin", s.pluginName, "connectionID", connID)
}
return nil
}
func (s *webSocketServiceImpl) getConnection(connectionID string) (*wsConnection, error) {
s.mu.RLock()
defer s.mu.RUnlock()
wsConn, exists := s.connections[connectionID]
if !exists {
return nil, fmt.Errorf("connection ID %q not found", connectionID)
}
return wsConn, nil
}
func (s *webSocketServiceImpl) isHostAllowed(host string) bool {
hostWithoutPort := extractHostname(host)
for _, pattern := range s.requiredHosts {
if matchHostPattern(pattern, hostWithoutPort) {
return true
}
}
return false
}
// matchHostPattern matches a host against a pattern.
// Supports "*" (allow all) and wildcards like "*.example.com".
func matchHostPattern(pattern, host string) bool {
if pattern == "*" {
return true
}
if pattern == host {
return true
}
// Handle wildcard patterns like *.example.com
if strings.HasPrefix(pattern, "*.") {
suffix := pattern[1:] // Get .example.com
return strings.HasSuffix(host, suffix)
}
return false
}
func (s *webSocketServiceImpl) readLoop(ctx context.Context, connectionID string, wsConn *wsConnection) {
defer func() {
// Remove connection if still present
s.mu.Lock()
delete(s.connections, connectionID)
s.mu.Unlock()
}()
for {
select {
case <-wsConn.done:
return
default:
}
messageType, data, err := wsConn.conn.ReadMessage()
if err != nil {
wsConn.closeMu.Lock()
isClosed := wsConn.isClosed
wsConn.closeMu.Unlock()
if isClosed {
return
}
// Check if it's a close error
if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway, websocket.CloseNoStatusReceived) {
closeCode := websocket.CloseNoStatusReceived
closeReason := ""
if ce, ok := errors.AsType[*websocket.CloseError](err); ok {
closeCode = ce.Code
closeReason = ce.Text
}
s.invokeOnClose(ctx, connectionID, int32(closeCode), closeReason)
return
}
// Other read error
s.invokeOnError(ctx, connectionID, err.Error())
return
}
switch messageType {
case websocket.TextMessage:
s.invokeOnTextMessage(ctx, connectionID, string(data))
case websocket.BinaryMessage:
s.invokeOnBinaryMessage(ctx, connectionID, data)
}
}
}
// invokeWebSocketCallback is a generic helper that handles the common callback invocation pattern.
func invokeWebSocketCallback[I any](ctx context.Context, s *webSocketServiceImpl, funcName string, input I, callbackName string, connectionID string) {
instance := s.getPluginInstance()
if instance == nil {
return
}
callbackCtx, cancel := context.WithTimeout(ctx, webSocketCallbackTimeout)
defer cancel()
start := time.Now()
err := callPluginFunctionNoOutput(callbackCtx, instance, funcName, input)
if err != nil {
if !errors.Is(errFunctionNotFound, err) {
log.Error(ctx, "WebSocket "+callbackName+" callback failed", "plugin", s.pluginName, "connectionID", connectionID, "duration", time.Since(start), err)
}
}
}
func (s *webSocketServiceImpl) invokeOnTextMessage(ctx context.Context, connectionID, message string) {
invokeWebSocketCallback(ctx, s, FuncWebSocketOnTextMessage, capabilities.OnTextMessageRequest{
ConnectionID: connectionID,
Message: message,
}, "text message", connectionID)
}
func (s *webSocketServiceImpl) invokeOnBinaryMessage(ctx context.Context, connectionID string, data []byte) {
invokeWebSocketCallback(ctx, s, FuncWebSocketOnBinaryMessage, capabilities.OnBinaryMessageRequest{
ConnectionID: connectionID,
Data: data,
}, "binary message", connectionID)
}
func (s *webSocketServiceImpl) invokeOnError(ctx context.Context, connectionID, errorMsg string) {
invokeWebSocketCallback(ctx, s, FuncWebSocketOnError, capabilities.OnErrorRequest{
ConnectionID: connectionID,
Error: errorMsg,
}, "error", connectionID)
}
func (s *webSocketServiceImpl) invokeOnClose(ctx context.Context, connectionID string, code int32, reason string) {
invokeWebSocketCallback(ctx, s, FuncWebSocketOnClose, capabilities.OnCloseRequest{
ConnectionID: connectionID,
Code: code,
Reason: reason,
}, "close", connectionID)
}
func (s *webSocketServiceImpl) getPluginInstance() *plugin {
s.manager.mu.RLock()
instance, ok := s.manager.plugins[s.pluginName]
s.manager.mu.RUnlock()
if !ok {
log.Warn("Plugin not loaded for WebSocket callback", "plugin", s.pluginName)
return nil
}
return instance
}
// Verify interface implementation
var _ host.WebSocketService = (*webSocketServiceImpl)(nil)