fix: resource leaks, cancellation, races and path traversal

Six correctness bugs that the existing tests could not see. The suite passed
and `go test -race` was clean throughout, because nothing exercised concurrent
token refresh, shared-folder artwork, or hostile metadata.

main(): extract run() int
  main() was a single 1196-line function that registered 20
  `defer mainApp.Close()` handlers and then called os.Exit 150 times, so none
  of them ever ran. Close() is what closes the SQLite handle, flushes the
  progress bars and removes the artwork temp dirs, so every failed rip leaked
  temp directories. main() is now a wrapper around run() int and the command
  bodies return exit codes.

Ctrl-C now stops a rip
  ctx was threaded everywhere but never checked: zero ctx.Err()/ctx.Done()
  in internal/app and internal/download. Cancellation left Rip() iterating
  the whole remaining queue, and the retry ladder retried on a dead context,
  so one Ctrl-C cost three doomed attempts per remaining track. Adds checks to
  the dispatch loops, the worker-spawn loops and the retry ladder, and routes
  the MarkFailed/MarkDownloaded bookkeeping through a detached context so the
  records survive cancellation. Convert and TagFLAC now take a ctx and use
  exec.CommandContext, so a stalled ffmpeg/ffprobe no longer outlives Ctrl-C.

Config race
  Provider token refresh mutated the shared *config.Config and called
  SaveFile() from inside download workers with no lock, racing the struct
  fields and issuing concurrent os.WriteFile against one path. Adds a mutex to
  config.Config plus UpdateTokens(), and routes all five refresh sites through
  it. Each provider client gets an authMu guarding loggedIn and its
  login/refresh path; beatport needed it most, since ensureToken is reached
  from apiRequest.

Artwork cover race
  artwork.Prepare was check-then-write on a path shared by every worker in a
  playlist rip. Two workers both saw a missing cover.jpg, both created it, and
  the loser's cleanup deleted the winner's finished file. Adds a per-folder
  lock and downloads via a unique temp file + rename. The regression test
  fails against the old code with 15 of 16 workers getting no cover.

Path traversal from remote metadata
  naming.CleanName stripped <>:"/\|?* and control chars but not "." , so a
  title of ".." survived into filepath.Join and escaped the download root.
  SoundCloud and Tidal playlist names are user-generated. Now rejects "." and
  "..", trims trailing dots, handles Windows device names, adds DEL to the
  invalid set and caps components at 255 bytes without splitting a rune.
  app.go gains safeJoin as a second line of defence.

Credentials no longer world-readable
  The config holds plaintext provider passwords, Deezer ARL cookies and OAuth
  tokens and was written 0o644. Now 0o600, with 0o700 directories, and an
  existing 0o644 file is tightened on write.

Also: deletes the 9 duplicated *-rip-smoke dev commands (~300 lines fully
subsumed by `rip id`) and the unreachable second dev-help arm; registers
image/png so PNG covers are downscaled instead of being silently saved as
cover.jpg containing PNG bytes; adds the missing .gitignore, which was keeping
a 21MB build artifact one `git add -A` away from the repo.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
JorenandClaude Opus 5 committed 2026-10-03 16:52:58 +02:00
1 parent eb7854bac3
commit c030d1be09
19 files changed
+915 -562

No files matched your search

+18 -6
View File
@@ -30,6 +30,7 @@ import (
"streamrip-go/internal/netutil"
"streamrip-go/internal/provider"
"streamrip-go/internal/ratelimit"
"streamrip-go/internal/verbose"
"github.com/vbauerster/mpb/v8"
"github.com/vbauerster/mpb/v8/decor"
@@ -63,6 +64,9 @@ type Client struct {
limiter *ratelimit.Limiter
baseURL string
fetchCfg func(ctx context.Context) (string, []string, error)
// authMu guards loggedIn and the login/refresh path, which download
// workers can reach concurrently.
authMu sync.Mutex
loggedIn bool
secret string
uat string
@@ -100,10 +104,14 @@ func (c *Client) Source() string {
}
func (c *Client) LoggedIn() bool {
c.authMu.Lock()
defer c.authMu.Unlock()
return c.loggedIn
}
func (c *Client) Login(ctx context.Context) error {
c.authMu.Lock()
defer c.authMu.Unlock()
q := &c.cfg.Session.Qobuz
q.EmailOrUserID = strings.TrimSpace(q.EmailOrUserID)
q.PasswordOrToken = strings.TrimSpace(q.PasswordOrToken)
@@ -203,14 +211,18 @@ func (c *Client) refreshAppCredentials(ctx context.Context, q *config.QobuzConfi
return errors.New("qobuz app credential refresh returned no secrets")
}
q.Secrets = append([]string(nil), clean...)
c.cfg.File.Qobuz.AppID = q.AppID
c.cfg.File.Qobuz.Secrets = append([]string(nil), clean...)
_ = c.cfg.SaveFile()
refreshedAppID := q.AppID
if err := c.cfg.UpdateTokens(func(file, session *config.ConfigData) {
file.Qobuz.AppID = refreshedAppID
file.Qobuz.Secrets = append([]string(nil), clean...)
}); err != nil {
verbose.Printf(verbose.V, "qobuz: could not persist refreshed credentials: %v\n", err)
}
return nil
}
func (c *Client) GetMetadata(ctx context.Context, item, mediaType string) (map[string]any, error) {
if !c.loggedIn {
if !c.LoggedIn() {
return nil, errNotLoggedIn
}
if mediaType == "playlist" {
@@ -260,7 +272,7 @@ func (c *Client) GetTrackMetadata(ctx context.Context, id string) (*TrackMetadat
}
func (c *Client) Search(ctx context.Context, mediaType, query string, limit int) ([]map[string]any, error) {
if !c.loggedIn {
if !c.LoggedIn() {
return nil, errNotLoggedIn
}
if limit <= 0 {
@@ -283,7 +295,7 @@ func (c *Client) Search(ctx context.Context, mediaType, query string, limit int)
}
func (c *Client) GetDownloadable(ctx context.Context, item string, quality int) (*provider.Downloadable, error) {
if !c.loggedIn {
if !c.LoggedIn() {
return nil, errNotLoggedIn
}
if quality < 1 || quality > 4 {