Files
minstrel/internal/scrobble/queue_test.go
T
bvandeusenandClaude Opus 5.5 a8a2d20307
release / govulncheck (push) Successful in 28s
release / web (push) Successful in 1m18s
release / go (push) Successful in 1m35s
release / android (push) Successful in 4m45s
release / Build signed APK (push) Successful in 4m57s
release / integration (push) Successful in 5m3s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 1m14s
release / Verify release artifacts (tag releases only) (push) Skipped
feat: stored credentials are sealed at rest, so a copy of the database alone reveals none of them (#6767)
Minstrel keeps credentials it has to read back: indexer, Prowlarr and
download-client keys and passwords, the AcoustID key, cover-art and tag
provider keys, the SMTP password, and each user's ListenBrainz token and
Subsonic password. They were stored in the clear; they are now sealed with
AES-256-GCM under a per-column HKDF key derived from the stream secret, each
value bound to its row.

- internal/secret: Seal/Open/Reveal, and Columns, the one list of sealed
  columns (a backup will leave them out). Install takes the master key at
  startup; SealStored seals any value still in the clear, so an existing
  database is brought over in place on the first boot.
- Every write seals and every read opens: acquire (one read path, getService
  / usableServices), acoustid settings, SMTP, ListenBrainz, Subsonic auth and
  password generation, cover-art and tag provider settings.
- A value that does not open (the stream secret changed) is logged and reads
  as unset, to be entered again in Settings. docs/security.md says so.
- Tests: secret unit tests (wrong owner/purpose/key, malformed, no key), a
  SealStored integration test over all eight columns plus a schema check that
  each listed column exists, and the existing tests now assert sealed storage.
  dbtest installs a test key for integration tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 13:23:19 -05:00

168 lines
5.3 KiB
Go

package scrobble
import (
"context"
"io"
"log/slog"
"os"
"testing"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/dbtest"
"git.fabledsword.com/bvandeusen/minstrel/internal/secret"
)
func testPool(t *testing.T) (*pgxpool.Pool, *dbq.Queries) {
t.Helper()
if testing.Short() {
t.Skip("skipping in -short mode")
}
dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil {
t.Fatalf("migrate: %v", err)
}
pool, err := pgxpool.New(context.Background(), dsn)
if err != nil {
t.Fatalf("pool: %v", err)
}
t.Cleanup(pool.Close)
dbtest.ResetDB(t, pool)
return pool, dbq.New(pool)
}
type setup struct {
pool *pgxpool.Pool
q *dbq.Queries
user pgtype.UUID
playEvent pgtype.UUID
}
type seedOpts struct {
lbToken string
lbEnabled bool
durationMs int32
ratio float64
}
// seed creates: user (with optional LB token + enabled), one artist/album/track,
// one closed play_event with the given duration_played_ms and completion_ratio.
func seed(t *testing.T, opts seedOpts) setup {
t.Helper()
pool, q := testPool(t)
ctx := context.Background()
u, err := q.CreateUser(ctx, dbq.CreateUserParams{
Username: dbtest.TestUserPrefix + "tester", PasswordHash: "x", ApiTokenHash: "x", IsAdmin: false,
})
if err != nil {
t.Fatalf("user: %v", err)
}
if opts.lbToken != "" {
// Stored sealed, as the settings route stores it.
sealed, err := secret.Seal(secret.ListenBrainzToken.Purpose(), u.ID.String(), opts.lbToken)
if err != nil {
t.Fatalf("seal token: %v", err)
}
if err := q.SetListenBrainzToken(ctx, dbq.SetListenBrainzTokenParams{
ID: u.ID, ListenbrainzToken: &sealed,
}); err != nil {
t.Fatalf("token: %v", err)
}
}
if opts.lbEnabled {
if err := q.SetListenBrainzEnabled(ctx, dbq.SetListenBrainzEnabledParams{
ID: u.ID, ListenbrainzEnabled: true,
}); err != nil {
t.Fatalf("enabled: %v", err)
}
}
a, _ := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "X", SortName: "X"})
al, _ := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: "X", SortTitle: "X", ArtistID: a.ID})
tr, _ := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: "Y", AlbumID: al.ID, ArtistID: a.ID, FilePath: "/tmp/y.flac", DurationMs: 300_000,
})
var sessionID pgtype.UUID
if err := pool.QueryRow(ctx,
`INSERT INTO play_sessions (user_id, started_at, last_event_at, client_id)
VALUES ($1, now() - interval '5 minutes', now(), 'test') RETURNING id`,
u.ID).Scan(&sessionID); err != nil {
t.Fatalf("session: %v", err)
}
var peID pgtype.UUID
if err := pool.QueryRow(ctx,
`INSERT INTO play_events (user_id, track_id, session_id, started_at, ended_at, duration_played_ms, completion_ratio, was_skipped)
VALUES ($1, $2, $3, now() - interval '1 minute', now(), $4, $5, false) RETURNING id`,
u.ID, tr.ID, sessionID, opts.durationMs, opts.ratio).Scan(&peID); err != nil {
t.Fatalf("play_event: %v", err)
}
return setup{pool: pool, q: q, user: u.ID, playEvent: peID}
}
func countQueueRows(t *testing.T, s setup) int {
t.Helper()
var n int
if err := s.pool.QueryRow(context.Background(),
`SELECT count(*) FROM scrobble_queue WHERE play_event_id = $1`, s.playEvent).Scan(&n); err != nil {
t.Fatalf("count: %v", err)
}
return n
}
func TestMaybeEnqueue_QualifyingPlayWithEnabledUser_InsertsRow(t *testing.T) {
s := seed(t, seedOpts{lbToken: "tk", lbEnabled: true, durationMs: 250_000, ratio: 0.83})
if err := MaybeEnqueue(context.Background(), s.q, s.playEvent); err != nil {
t.Fatalf("MaybeEnqueue: %v", err)
}
if got := countQueueRows(t, s); got != 1 {
t.Errorf("rows = %d, want 1", got)
}
}
func TestMaybeEnqueue_SubThreshold_NoRow(t *testing.T) {
s := seed(t, seedOpts{lbToken: "tk", lbEnabled: true, durationMs: 100_000, ratio: 0.33})
if err := MaybeEnqueue(context.Background(), s.q, s.playEvent); err != nil {
t.Fatalf("MaybeEnqueue: %v", err)
}
if got := countQueueRows(t, s); got != 0 {
t.Errorf("rows = %d, want 0 (sub-threshold)", got)
}
}
func TestMaybeEnqueue_DisabledUser_NoRow(t *testing.T) {
s := seed(t, seedOpts{lbToken: "tk", lbEnabled: false, durationMs: 250_000, ratio: 0.83})
if err := MaybeEnqueue(context.Background(), s.q, s.playEvent); err != nil {
t.Fatalf("MaybeEnqueue: %v", err)
}
if got := countQueueRows(t, s); got != 0 {
t.Errorf("rows = %d, want 0 (disabled)", got)
}
}
func TestMaybeEnqueue_NoToken_NoRow(t *testing.T) {
s := seed(t, seedOpts{lbToken: "", lbEnabled: true, durationMs: 250_000, ratio: 0.83})
if err := MaybeEnqueue(context.Background(), s.q, s.playEvent); err != nil {
t.Fatalf("MaybeEnqueue: %v", err)
}
if got := countQueueRows(t, s); got != 0 {
t.Errorf("rows = %d, want 0 (no token)", got)
}
}
func TestMaybeEnqueue_Idempotent_TwoCallsOneRow(t *testing.T) {
s := seed(t, seedOpts{lbToken: "tk", lbEnabled: true, durationMs: 250_000, ratio: 0.83})
for i := 0; i < 2; i++ {
if err := MaybeEnqueue(context.Background(), s.q, s.playEvent); err != nil {
t.Fatalf("MaybeEnqueue #%d: %v", i, err)
}
}
if got := countQueueRows(t, s); got != 1 {
t.Errorf("rows = %d, want 1 (idempotent)", got)
}
}