feat(server): POST /api/cast/stream-token + secret bootstrap (UPnP slice 2/6)
test-go / test (push) Failing after 15s
test-go / integration (push) Failing after 5m54s

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:
2026-06-03 11:46:57 -04:00
parent 236637fcd3
commit e774097fd8
7 changed files with 429 additions and 2 deletions
+86
View File
@@ -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