Files
minstrel/internal/audit/audit_test.go
T
bvandeusenandClaude Opus 5 11ef044ef6
test-web / test (push) Successful in 57s
test-go / test (push) Successful in 1m16s
test-go / integration (push) Successful in 3m39s
release / Build signed APK (releases and dev) (push) Successful in 4m46s
release / Build + push container image (push) Successful in 26s
release / Verify release artifacts (tag releases only) (push) Skipped
feat(library): merge duplicates without losing history (M400 #3911)
Merge keeps one copy of a duplicate group and removes the rest. Every
table that references tracks does so ON DELETE CASCADE, so deleting a
duplicate's row outright would silently destroy its likes, plays,
playlist entries and tags. The merge moves all of that onto the kept
copy first, then deletes the empty row.

In one transaction, holding a lock on the group:
- repoints play_events, skip_events, contextual_likes, playback_errors,
  lidarr_requests.matched_track_id and playlist_tracks. The last is
  keyed by position, so every entry stays where it was.
- merges general_likes one per user, dated to the earlier like
- takes the union of track_tags, keeping the kept copy's own weight on
  a shared tag
- rewrites track_similarity onto the kept copy, dropping edges that
  would point a track at itself and keeping the kept copy's existing
  edge on a collision
- lets the kept copy take a recording MBID only the removed copy had
- deletes the removed copies' rows, tidies emptied albums and artists,
  marks the group merged
- logs sync changes: track deletes, and like and playlist-track
  delete/upsert pairs

The removed copies' files are deleted first, before any row changes,
through the same helper as DeleteTrackFile (now shared, along with the
album tidy-up). A merge that left the file behind would be undone by
the next scan re-importing it. An unwritable library answers 409
library_not_writable and nothing changes.

tracks.Service.MergeDuplicates wraps it with the opt-in Lidarr unmonitor
from RemoveTrack, skipped when the removed copy is a second file of the
kept copy's own album track: unmonitoring that would stop Lidarr
managing the kept file. It writes a duplicate_merge audit row after
commit, per the audit package's best-effort contract, naming both
paths.

POST /api/admin/library/duplicates/{id}/merge takes an optional
survivor_track_id (the report's proposal otherwise) and unmonitor.

On the report page:
- each copy gets a Keep choice, defaulting to the proposed one
- Merge needs a second click, on a button that says how many files it
  removes, with the consequence stated beside an opt-in Lidarr checkbox

Integration tests cover:
- every piece of history landing on the kept copy exactly: likes
  deduped at the earlier time, plays and skips counted, playlist
  position unchanged, tags unioned, similarity rewritten with no
  duplicate or self-edge, MBID inherited
- the removed file gone, and a second merge refused
- an unwritable file leaving likes, plays, row and group untouched
- a survivor outside the group refused

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SQ31KQpYbStyK5y58UmPLH
2026-09-11 17:25:06 -04:00

186 lines
5.5 KiB
Go

package audit_test
import (
"bytes"
"context"
"log/slog"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
)
func newTestPool(t *testing.T) *pgxpool.Pool {
t.Helper()
url := os.Getenv("MINSTREL_TEST_DATABASE_URL")
if url == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
pool, err := pgxpool.New(context.Background(), url)
if err != nil {
t.Fatalf("connect: %v", err)
}
t.Cleanup(pool.Close)
// Reset audit_log so each test runs against a known state.
if _, err := pool.Exec(context.Background(), `DELETE FROM audit_log`); err != nil {
t.Fatalf("reset audit_log: %v", err)
}
return pool
}
func TestWrite_NoMetadata(t *testing.T) {
pool := newTestPool(t)
// Use NULL FKs (Valid: false) — the column is nullable.
var nilUUID pgtype.UUID
if err := audit.Write(context.Background(), pool, nilUUID, nilUUID, audit.ActionRegister, nil); err != nil {
t.Fatalf("Write: %v", err)
}
var count int
if err := pool.QueryRow(context.Background(),
`SELECT count(*) FROM audit_log WHERE action = 'register' AND metadata IS NULL`,
).Scan(&count); err != nil {
t.Fatalf("count: %v", err)
}
if count != 1 {
t.Errorf("count = %d, want 1", count)
}
}
func TestWrite_WithMetadata(t *testing.T) {
pool := newTestPool(t)
var nilUUID pgtype.UUID
if err := audit.Write(context.Background(), pool, nilUUID, nilUUID, audit.ActionPromoteAdmin, map[string]any{
"reason": "test",
"first_admin": true,
}); err != nil {
t.Fatalf("Write: %v", err)
}
var meta string
if err := pool.QueryRow(context.Background(),
`SELECT metadata::text FROM audit_log WHERE action = 'promote_admin' LIMIT 1`,
).Scan(&meta); err != nil {
t.Fatalf("read metadata: %v", err)
}
// Postgres jsonb::text renders a space after ':' and ',', e.g.
// {"reason": "test", "first_admin": true}.
if !contains(meta, `"first_admin": true`) || !contains(meta, `"reason": "test"`) {
t.Errorf("metadata = %q, expected first_admin + reason fields", meta)
}
}
func contains(s, sub string) bool {
return len(s) >= len(sub) && (func() bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
})()
}
// TestWriteOrLog_Success exercises the happy path — when Write
// succeeds, no log line is emitted. Skipped unless a test DB is
// configured (no fixtures harness exists in this package beyond the
// env-driven pool above).
func TestWriteOrLog_Success(t *testing.T) {
pool := newTestPool(t)
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn}))
var nilUUID pgtype.UUID
audit.WriteOrLog(context.Background(), pool, logger, nilUUID, nilUUID, audit.ActionRegister, nil)
if buf.Len() != 0 {
t.Errorf("expected no log output on success, got %q", buf.String())
}
}
// TestWriteOrLog_DBFailure_Logs forces Write to fail by passing a
// closed pool, and asserts the logger captured a Warn record with
// action + err keys.
func TestWriteOrLog_DBFailure_Logs(t *testing.T) {
url := os.Getenv("MINSTREL_TEST_DATABASE_URL")
if url == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
pool, err := pgxpool.New(context.Background(), url)
if err != nil {
t.Fatalf("connect: %v", err)
}
pool.Close() // force subsequent ops to fail
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn}))
var nilUUID pgtype.UUID
audit.WriteOrLog(context.Background(), pool, logger, nilUUID, nilUUID, audit.ActionRegister, nil)
out := buf.String()
if out == "" {
t.Fatal("expected a Warn log line on failure, got none")
}
if !strings.Contains(out, "level=WARN") {
t.Errorf("expected level=WARN in log line, got %q", out)
}
if !strings.Contains(out, "action=register") {
t.Errorf("expected action=register key in log line, got %q", out)
}
if !strings.Contains(out, "err=") {
t.Errorf("expected err= key in log line, got %q", out)
}
}
// TestWriteOrLog_NilLogger ensures a nil logger + failing pool does
// not panic. Uses a closed pool to force the failure branch.
func TestWriteOrLog_NilLogger(t *testing.T) {
url := os.Getenv("MINSTREL_TEST_DATABASE_URL")
if url == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
pool, err := pgxpool.New(context.Background(), url)
if err != nil {
t.Fatalf("connect: %v", err)
}
pool.Close()
var nilUUID pgtype.UUID
// Must not panic.
audit.WriteOrLog(context.Background(), pool, nil, nilUUID, nilUUID, audit.ActionRegister, nil)
}
func TestWrite_AllActionConstantsArePersisted(t *testing.T) {
pool := newTestPool(t)
var nilUUID pgtype.UUID
actions := []audit.Action{
audit.ActionRegister,
audit.ActionPromoteAdmin,
audit.ActionDemoteAdmin,
audit.ActionInviteCreate,
audit.ActionInviteRedeem,
audit.ActionInviteRevoke,
audit.ActionCreateUserAdmin,
audit.ActionDeleteUser,
audit.ActionPasswordResetAdmin,
audit.ActionAutoApproveToggle,
audit.ActionPasswordChangeSelf,
audit.ActionTokenRegenerate,
audit.ActionForgotPasswordInit,
audit.ActionPasswordResetByEmail,
audit.ActionDuplicateMerge,
}
for _, a := range actions {
if err := audit.Write(context.Background(), pool, nilUUID, nilUUID, a, nil); err != nil {
t.Errorf("action %q: Write: %v", a, err)
}
}
var count int
if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM audit_log`).Scan(&count); err != nil {
t.Fatalf("count: %v", err)
}
if count != len(actions) {
t.Errorf("count = %d, want %d", count, len(actions))
}
}