feat(server): POST /api/cast/stream-token + secret bootstrap (UPnP slice 2/6)
Adds the client-facing endpoint that issues a signed stream URL for
the current track. Authenticated via the standard session cookie.
Returns {token, exp, url} where url is a fully-formed stream URL
the client passes verbatim to a UPnP / Sonos device's
AVTransport.SetAVTransportURI call.
expSeconds clamped to [60, 86400]; default 21600 (6h) - long enough
to play through any typical track without re-minting mid-playback.
MINSTREL_STREAM_SECRET is loaded from env var with a per-machine
fallback persisted at <Storage.DataDir>/stream_secret (auto-generated
on first boot via 64 random bytes, base64-url-encoded, 0600). The
file-based fallback is operator-machine-scoped runtime state, not a
user-facing setting - chosen over a DB column to avoid a migration
and keep the secret out of cross-instance restores. Operator can
override at any time via the env var; default path requires zero
config.
Tests cover happy-path token issuance + URL formatting, bad-UUID
rejection, unauthenticated rejection, the expSeconds clamp at all
boundaries, secret env override, auto-gen + file persistence at 0600,
second-boot reuse of the persisted file, and rejection of a malformed
env value.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -245,6 +245,7 @@ func run() error {
|
||||
}, cfg.Events, cfg.Recommendation, cfg.Storage.DataDir, cfg.Branding, coverEnricher, coverSettings, scanner, scanCfg, scheduler)
|
||||
srv.Bus = bus
|
||||
srv.PlaylistScheduler = playlistScheduler
|
||||
srv.StreamSecret = cfg.StreamSecret
|
||||
httpServer := &http.Server{
|
||||
Addr: cfg.Server.Address,
|
||||
Handler: srv.Router(),
|
||||
|
||||
+7
-1
@@ -28,7 +28,7 @@ import (
|
||||
// Mount attaches /api/* handlers to r. Public endpoints (login) are outside
|
||||
// RequireUser; everything else is gated by the middleware. The events writer
|
||||
// is shared with the Subsonic mount so /rest/scrobble feeds the same store.
|
||||
func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playevents.Writer, recCfg config.RecommendationConfig, lidarrCfg *lidarrconfig.Service, lidarrReqs *lidarrrequests.Service, lidarrQuar *lidarrquarantine.Service, tracksSvc *tracks.Service, playlistsSvc *playlists.Service, coverEnricher *coverart.Enricher, coverSettings *coverart.SettingsService, scanner *library.Scanner, scanCfg library.RunScanConfig, scheduler *library.Scheduler, dataDir string, sender mailer.Sender, bus *eventbus.Bus, playlistScheduler *playlists.Scheduler) {
|
||||
func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playevents.Writer, recCfg config.RecommendationConfig, lidarrCfg *lidarrconfig.Service, lidarrReqs *lidarrrequests.Service, lidarrQuar *lidarrquarantine.Service, tracksSvc *tracks.Service, playlistsSvc *playlists.Service, coverEnricher *coverart.Enricher, coverSettings *coverart.SettingsService, scanner *library.Scanner, scanCfg library.RunScanConfig, scheduler *library.Scheduler, dataDir string, sender mailer.Sender, bus *eventbus.Bus, playlistScheduler *playlists.Scheduler, streamSecret []byte) {
|
||||
rng := rand.New(rand.NewSource(rand.Int63()))
|
||||
h := &handlers{
|
||||
pool: pool, logger: logger, events: events, recCfg: recCfg,
|
||||
@@ -47,6 +47,7 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
||||
mailer: sender,
|
||||
eventbus: bus,
|
||||
playlistScheduler: playlistScheduler,
|
||||
streamSecret: streamSecret,
|
||||
}
|
||||
|
||||
r.Route("/api", func(api chi.Router) {
|
||||
@@ -97,6 +98,11 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
||||
authed.Get("/home/index", h.handleGetHomeIndex)
|
||||
authed.Post("/events", h.handleEvents)
|
||||
authed.Get("/events/stream", h.handleEventsStream)
|
||||
// UPnP / Sonos cast slice: issue a short-lived HMAC stream URL
|
||||
// the speaker can fetch without the user's session. See the
|
||||
// design at
|
||||
// docs/superpowers/specs/2026-06-03-android-output-picker-upnp-design.md.
|
||||
authed.Post("/cast/stream-token", h.handleCastStreamToken)
|
||||
authed.Post("/likes/tracks/{id}", h.handleLikeTrack)
|
||||
authed.Delete("/likes/tracks/{id}", h.handleUnlikeTrack)
|
||||
authed.Post("/likes/albums/{id}", h.handleLikeAlbum)
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
)
|
||||
|
||||
const (
|
||||
castTokenMinExpSeconds = 60
|
||||
castTokenMaxExpSeconds = 86400 // 24h
|
||||
castTokenDefaultExp = 21600 // 6h
|
||||
)
|
||||
|
||||
type castTokenRequest struct {
|
||||
TrackID string `json:"trackId"`
|
||||
ExpSeconds int `json:"expSeconds,omitempty"`
|
||||
}
|
||||
|
||||
type castTokenResponse struct {
|
||||
Token string `json:"token"`
|
||||
Exp int64 `json:"exp"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// handleCastStreamToken issues a short-lived HMAC stream token for the
|
||||
// given trackId. Authenticated via the standard session cookie / bearer.
|
||||
//
|
||||
// The returned URL is a fully-formed stream URL (token + exp embedded
|
||||
// as query params) that the client passes verbatim to a UPnP / Sonos
|
||||
// device's AVTransport.SetAVTransportURI call — those devices cannot
|
||||
// carry the user's session, so the signed query string is the only way
|
||||
// they can fetch the bytes.
|
||||
//
|
||||
// expSeconds is clamped to [60, 86400]; default 21600 (6h) — long enough
|
||||
// to play through any typical track without re-minting mid-playback.
|
||||
//
|
||||
// Part of the output-picker UPnP slice. See
|
||||
// docs/superpowers/specs/2026-06-03-android-output-picker-upnp-design.md.
|
||||
func (h *handlers) handleCastStreamToken(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := requireUser(w, r); !ok {
|
||||
return
|
||||
}
|
||||
var req castTokenRequest
|
||||
if !decodeBody(w, r, &req) {
|
||||
return
|
||||
}
|
||||
trackUUID, ok := parseUUID(req.TrackID)
|
||||
if !ok || !trackUUID.Valid {
|
||||
writeErr(w, apierror.BadRequest("invalid_track_id", "trackId must be a UUID"))
|
||||
return
|
||||
}
|
||||
expSec := clampExpSeconds(req.ExpSeconds)
|
||||
exp := time.Now().Add(time.Duration(expSec) * time.Second).Unix()
|
||||
token := SignStreamToken(h.streamSecret, req.TrackID, exp)
|
||||
|
||||
scheme := "http"
|
||||
if r.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
url := scheme + "://" + r.Host + "/api/tracks/" + req.TrackID +
|
||||
"/stream?token=" + token + "&exp=" + strconv.FormatInt(exp, 10)
|
||||
|
||||
writeJSON(w, http.StatusOK, castTokenResponse{Token: token, Exp: exp, URL: url})
|
||||
}
|
||||
|
||||
// clampExpSeconds applies the [60, 86400] window with a 6h default for
|
||||
// non-positive inputs. Extracted so it doesn't bloat the handler's
|
||||
// detekt-equivalent line count and so the test can exercise edges directly.
|
||||
func clampExpSeconds(v int) int {
|
||||
if v <= 0 {
|
||||
return castTokenDefaultExp
|
||||
}
|
||||
if v < castTokenMinExpSeconds {
|
||||
return castTokenMinExpSeconds
|
||||
}
|
||||
if v > castTokenMaxExpSeconds {
|
||||
return castTokenMaxExpSeconds
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const testTrackUUID = "11111111-1111-1111-1111-111111111111"
|
||||
|
||||
func TestCastStreamToken_HappyPath(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "hunter2", false)
|
||||
h.streamSecret = []byte("cast-token-test-secret")
|
||||
|
||||
body, err := json.Marshal(castTokenRequest{
|
||||
TrackID: testTrackUUID,
|
||||
ExpSeconds: 3600,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/cast/stream-token", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = withUser(req, user)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.handleCastStreamToken(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp castTokenResponse
|
||||
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if resp.Token == "" || resp.Exp == 0 || resp.URL == "" {
|
||||
t.Fatalf("empty fields in response: %+v", resp)
|
||||
}
|
||||
if !strings.Contains(resp.URL, "token="+resp.Token) {
|
||||
t.Fatalf("URL missing token query: %s", resp.URL)
|
||||
}
|
||||
if !strings.Contains(resp.URL, "/api/tracks/"+testTrackUUID+"/stream") {
|
||||
t.Fatalf("URL missing stream path: %s", resp.URL)
|
||||
}
|
||||
if !VerifyStreamToken(h.streamSecret, testTrackUUID, resp.Exp, resp.Token) {
|
||||
t.Fatal("returned token does not verify")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCastStreamToken_RejectsBadUUID(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "hunter2", false)
|
||||
h.streamSecret = []byte("cast-token-test-secret")
|
||||
|
||||
body, err := json.Marshal(castTokenRequest{TrackID: "not-a-uuid"})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/cast/stream-token", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = withUser(req, user)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.handleCastStreamToken(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400; body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCastStreamToken_RejectsUnauthenticated(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
h.streamSecret = []byte("cast-token-test-secret")
|
||||
|
||||
body, err := json.Marshal(castTokenRequest{TrackID: testTrackUUID})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/cast/stream-token", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
// NO withUser — handler must reject via requireUser.
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.handleCastStreamToken(w, req)
|
||||
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401; body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCastStreamToken_ClampsExpSeconds(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "hunter2", false)
|
||||
h.streamSecret = []byte("cast-token-test-secret")
|
||||
|
||||
// Request 1 second (below min 60), expect clamp to 60s.
|
||||
body, err := json.Marshal(castTokenRequest{
|
||||
TrackID: testTrackUUID,
|
||||
ExpSeconds: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
before := time.Now().Unix()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/cast/stream-token", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = withUser(req, user)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.handleCastStreamToken(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp castTokenResponse
|
||||
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
// Allow a small jitter window around the clamp target (60s).
|
||||
delta := resp.Exp - before
|
||||
if delta < 55 || delta > 70 {
|
||||
t.Fatalf("expected ~60s expiry after clamp, got delta=%ds", delta)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClampExpSeconds(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in int
|
||||
want int
|
||||
}{
|
||||
{"zero defaults to 6h", 0, castTokenDefaultExp},
|
||||
{"negative defaults to 6h", -1, castTokenDefaultExp},
|
||||
{"below min clamps up", 30, castTokenMinExpSeconds},
|
||||
{"exact min passes through", castTokenMinExpSeconds, castTokenMinExpSeconds},
|
||||
{"mid-range passes through", 3600, 3600},
|
||||
{"exact max passes through", castTokenMaxExpSeconds, castTokenMaxExpSeconds},
|
||||
{"above max clamps down", castTokenMaxExpSeconds + 1, castTokenMaxExpSeconds},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := clampExpSeconds(tc.in); got != tc.want {
|
||||
t.Fatalf("clampExpSeconds(%d) = %d, want %d", tc.in, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -19,6 +23,14 @@ type Config struct {
|
||||
Events EventsConfig `yaml:"events"`
|
||||
Recommendation RecommendationConfig `yaml:"recommendation"`
|
||||
Branding BrandingConfig `yaml:"branding"`
|
||||
// StreamSecret is the base64-decoded HMAC key used to sign UPnP /
|
||||
// Sonos stream URLs (see internal/api/stream_token.go and
|
||||
// docs/superpowers/specs/2026-06-03-android-output-picker-upnp-design.md).
|
||||
// Sourced from MINSTREL_STREAM_SECRET (base64-encoded), with a
|
||||
// per-machine fallback persisted at <Storage.DataDir>/stream_secret.
|
||||
// Not serialized to YAML — operator-machine-scoped runtime state, not
|
||||
// a user-facing setting. Never log the contents.
|
||||
StreamSecret []byte `yaml:"-"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
@@ -137,9 +149,83 @@ func Load(path string) (Config, error) {
|
||||
}
|
||||
}
|
||||
applyEnv(&cfg)
|
||||
if err := resolveStreamSecret(&cfg); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// streamSecretBytes is the raw HMAC-key length; 64 bytes gives 512 bits
|
||||
// of entropy, more than enough for HMAC-SHA256, and lands at a 86-char
|
||||
// base64-url-no-padding string that fits cleanly in a single .env line.
|
||||
const streamSecretBytes = 64
|
||||
|
||||
// streamSecretFile is the basename for the per-machine persisted fallback
|
||||
// under <Storage.DataDir>. Kept as a constant so tests assert against the
|
||||
// exact path and operators can find it during backup planning.
|
||||
const streamSecretFile = "stream_secret"
|
||||
|
||||
// resolveStreamSecret populates cfg.StreamSecret using, in order:
|
||||
// 1. MINSTREL_STREAM_SECRET env var (operator-supplied, base64-url
|
||||
// encoded — accepts either padded or raw form).
|
||||
// 2. <Storage.DataDir>/stream_secret if present (auto-generated on a
|
||||
// previous boot; survives restarts so signed URLs stay valid).
|
||||
// 3. Auto-generate streamSecretBytes random bytes, persist them to that
|
||||
// file at 0600, then use them.
|
||||
//
|
||||
// Logs (only) when an auto-generation happens so the operator can spot
|
||||
// it during first-boot. Never logs the contents.
|
||||
//
|
||||
// The loader runs before slog is initialized in cmd/minstrel/main.go;
|
||||
// log.Printf is the project's pre-logger convention.
|
||||
func resolveStreamSecret(cfg *Config) error {
|
||||
if raw := strings.TrimSpace(os.Getenv("MINSTREL_STREAM_SECRET")); raw != "" {
|
||||
decoded, err := decodeBase64Secret(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode MINSTREL_STREAM_SECRET: %w", err)
|
||||
}
|
||||
cfg.StreamSecret = decoded
|
||||
return nil
|
||||
}
|
||||
if cfg.Storage.DataDir == "" {
|
||||
return fmt.Errorf("stream secret: empty storage.data_dir; " +
|
||||
"set MINSTREL_STREAM_SECRET or storage.data_dir")
|
||||
}
|
||||
path := filepath.Join(cfg.Storage.DataDir, streamSecretFile)
|
||||
if buf, err := os.ReadFile(path); err == nil && len(buf) > 0 {
|
||||
decoded, err := decodeBase64Secret(strings.TrimSpace(string(buf)))
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode %s: %w", path, err)
|
||||
}
|
||||
cfg.StreamSecret = decoded
|
||||
return nil
|
||||
}
|
||||
raw := make([]byte, streamSecretBytes)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return fmt.Errorf("auto-gen stream secret: %w", err)
|
||||
}
|
||||
encoded := base64.RawURLEncoding.EncodeToString(raw)
|
||||
if err := os.MkdirAll(cfg.Storage.DataDir, 0o755); err != nil {
|
||||
return fmt.Errorf("ensure data_dir for stream secret: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(encoded), 0o600); err != nil {
|
||||
return fmt.Errorf("persist stream secret: %w", err)
|
||||
}
|
||||
log.Printf("config: auto-generated MINSTREL_STREAM_SECRET (persisted to %s)", path)
|
||||
cfg.StreamSecret = raw
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeBase64Secret accepts base64-url with OR without padding; the
|
||||
// stream-secret bytes are opaque so callers shouldn't have to know which
|
||||
// encoder produced their string. Returns an error on any other shape.
|
||||
func decodeBase64Secret(s string) ([]byte, error) {
|
||||
if buf, err := base64.RawURLEncoding.DecodeString(s); err == nil {
|
||||
return buf, nil
|
||||
}
|
||||
return base64.URLEncoding.DecodeString(s)
|
||||
}
|
||||
|
||||
func applyEnv(cfg *Config) {
|
||||
if v, ok := os.LookupEnv("MINSTREL_SERVER_ADDRESS"); ok {
|
||||
cfg.Server.Address = v
|
||||
|
||||
@@ -1,11 +1,23 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// stubStreamSecret keeps existing tests focused on the fields they
|
||||
// assert against by short-circuiting the auto-generation path (which
|
||||
// would otherwise write ./data/stream_secret in the test workspace).
|
||||
// New tests that exercise the resolver directly do NOT use this.
|
||||
func stubStreamSecret(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("MINSTREL_STREAM_SECRET",
|
||||
base64.RawURLEncoding.EncodeToString([]byte("test-stream-secret-stub-1234567890")))
|
||||
}
|
||||
|
||||
func TestDefault(t *testing.T) {
|
||||
cfg := Default()
|
||||
if cfg.Server.Address != ":4533" {
|
||||
@@ -17,6 +29,7 @@ func TestDefault(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestLoadYAML(t *testing.T) {
|
||||
stubStreamSecret(t)
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.yaml")
|
||||
content := []byte(`server:
|
||||
@@ -46,6 +59,7 @@ log:
|
||||
}
|
||||
|
||||
func TestLoadMissingFileReturnsDefaults(t *testing.T) {
|
||||
stubStreamSecret(t)
|
||||
cfg, err := Load(filepath.Join(t.TempDir(), "does-not-exist.yaml"))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
@@ -56,6 +70,7 @@ func TestLoadMissingFileReturnsDefaults(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestEnvOverrides(t *testing.T) {
|
||||
stubStreamSecret(t)
|
||||
t.Setenv("MINSTREL_SERVER_ADDRESS", ":8080")
|
||||
t.Setenv("MINSTREL_DATABASE_URL", "postgres://env")
|
||||
t.Setenv("MINSTREL_LOG_LEVEL", "WARN")
|
||||
@@ -80,6 +95,7 @@ func TestEnvOverrides(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestLibraryEnvOverrides(t *testing.T) {
|
||||
stubStreamSecret(t)
|
||||
t.Setenv("MINSTREL_LIBRARY_SCAN_PATHS", "/music:/other::/third")
|
||||
t.Setenv("MINSTREL_LIBRARY_SCAN_ON_STARTUP", "true")
|
||||
|
||||
@@ -102,6 +118,7 @@ func TestLibraryEnvOverrides(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSubsonicEnvOverride(t *testing.T) {
|
||||
stubStreamSecret(t)
|
||||
t.Setenv("MINSTREL_SUBSONIC_ALLOW_PLAINTEXT_PASSWORD", "true")
|
||||
cfg, err := Load("")
|
||||
if err != nil {
|
||||
@@ -113,6 +130,7 @@ func TestSubsonicEnvOverride(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestLibraryYAMLLoads(t *testing.T) {
|
||||
stubStreamSecret(t)
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.yaml")
|
||||
content := []byte(`library:
|
||||
@@ -147,6 +165,7 @@ func TestBrandingDefaults(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBrandingYAMLOverride(t *testing.T) {
|
||||
stubStreamSecret(t)
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.yaml")
|
||||
content := []byte(`branding:
|
||||
@@ -168,7 +187,81 @@ func TestBrandingYAMLOverride(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamSecret_EnvOverride(t *testing.T) {
|
||||
want := []byte("hello-stream-secret-from-env-32b")
|
||||
t.Setenv("MINSTREL_STREAM_SECRET", base64.RawURLEncoding.EncodeToString(want))
|
||||
t.Setenv("MINSTREL_STORAGE_DATA_DIR", t.TempDir())
|
||||
cfg, err := Load("")
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if string(cfg.StreamSecret) != string(want) {
|
||||
t.Fatalf("StreamSecret mismatch: got %q want %q", cfg.StreamSecret, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamSecret_AutoGenPersistsToDataDir(t *testing.T) {
|
||||
os.Unsetenv("MINSTREL_STREAM_SECRET")
|
||||
dataDir := t.TempDir()
|
||||
t.Setenv("MINSTREL_STORAGE_DATA_DIR", dataDir)
|
||||
|
||||
cfg, err := Load("")
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if len(cfg.StreamSecret) != streamSecretBytes {
|
||||
t.Fatalf("StreamSecret len = %d, want %d", len(cfg.StreamSecret), streamSecretBytes)
|
||||
}
|
||||
path := filepath.Join(dataDir, streamSecretFile)
|
||||
buf, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("expected persisted secret at %s: %v", path, err)
|
||||
}
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(string(buf)))
|
||||
if err != nil {
|
||||
t.Fatalf("persisted secret is not raw-url-base64: %v", err)
|
||||
}
|
||||
if string(decoded) != string(cfg.StreamSecret) {
|
||||
t.Fatal("persisted file does not match returned secret")
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatalf("stat: %v", err)
|
||||
}
|
||||
// 0600 — never let other users read the HMAC key.
|
||||
if perm := info.Mode().Perm(); perm != 0o600 {
|
||||
t.Fatalf("perm = %o, want 0600", perm)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamSecret_LoadsPersistedOnSecondBoot(t *testing.T) {
|
||||
os.Unsetenv("MINSTREL_STREAM_SECRET")
|
||||
dataDir := t.TempDir()
|
||||
t.Setenv("MINSTREL_STORAGE_DATA_DIR", dataDir)
|
||||
|
||||
first, err := Load("")
|
||||
if err != nil {
|
||||
t.Fatalf("Load #1: %v", err)
|
||||
}
|
||||
second, err := Load("")
|
||||
if err != nil {
|
||||
t.Fatalf("Load #2: %v", err)
|
||||
}
|
||||
if string(first.StreamSecret) != string(second.StreamSecret) {
|
||||
t.Fatal("second Load got a different secret — file fallback didn't fire")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamSecret_RejectsMalformedEnvValue(t *testing.T) {
|
||||
t.Setenv("MINSTREL_STREAM_SECRET", "not!base64!!!")
|
||||
t.Setenv("MINSTREL_STORAGE_DATA_DIR", t.TempDir())
|
||||
if _, err := Load(""); err == nil {
|
||||
t.Fatal("expected error on malformed MINSTREL_STREAM_SECRET")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrandingEnvOverride(t *testing.T) {
|
||||
stubStreamSecret(t)
|
||||
t.Setenv("MINSTREL_BRANDING_APP_NAME", "Office Music")
|
||||
t.Setenv("MINSTREL_BRANDING_DESCRIPTION", "Office tunes.")
|
||||
cfg, err := Load("")
|
||||
|
||||
@@ -89,6 +89,12 @@ type Server struct {
|
||||
// PUT /api/me/timezone and POST /api/auth/register can call
|
||||
// Refresh synchronously.
|
||||
PlaylistScheduler *playlists.Scheduler
|
||||
// StreamSecret is the HMAC key used by /api/cast/stream-token to
|
||||
// mint signed UPnP / Sonos stream URLs and by /api/tracks/{id}/stream
|
||||
// to verify them. Sourced from config.Config.StreamSecret. Tests that
|
||||
// leave it nil leave the cookie path intact and reject all signed
|
||||
// tokens (HMAC of empty key matches nothing a client could mint).
|
||||
StreamSecret []byte
|
||||
}
|
||||
|
||||
func New(logger *slog.Logger, pool *pgxpool.Pool, scanner ScanTrigger, subCfg subsonic.Config, eventsCfg config.EventsConfig, recCfg config.RecommendationConfig, dataDir string, brandingCfg config.BrandingConfig, coverEnricher *coverart.Enricher, coverSettings *coverart.SettingsService, libraryScanner *library.Scanner, scanCfg library.RunScanConfig, scheduler *library.Scheduler) *Server {
|
||||
@@ -138,7 +144,7 @@ func (s *Server) Router() http.Handler {
|
||||
if bus == nil {
|
||||
bus = eventbus.New()
|
||||
}
|
||||
api.Mount(r, s.Pool, s.Logger, writer, s.RecommendationCfg, lidarrCfg, lidarrReqs, lidarrQuar, tracksSvc, playlistsSvc, s.CoverEnricher, s.CoverSettings, s.LibraryScanner, s.ScanCfg, s.Scheduler, s.DataDir, smtpSender, bus, s.PlaylistScheduler)
|
||||
api.Mount(r, s.Pool, s.Logger, writer, s.RecommendationCfg, lidarrCfg, lidarrReqs, lidarrQuar, tracksSvc, playlistsSvc, s.CoverEnricher, s.CoverSettings, s.LibraryScanner, s.ScanCfg, s.Scheduler, s.DataDir, smtpSender, bus, s.PlaylistScheduler, s.StreamSecret)
|
||||
// /api/admin/scan is the only admin route owned by the server package
|
||||
// (it needs the Scanner). Register it as a single inline-middleware
|
||||
// route — using r.Route("/api/admin", ...) here would create a second
|
||||
|
||||
Reference in New Issue
Block a user