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:
@@ -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("")
|
||||
|
||||
Reference in New Issue
Block a user