mirror of
https://git.sr.ht/~joren/streamrip-go
synced 2026-11-26 19:40:04 +01:00
- redact credentials from transport errors, verbose request logs, and download-start logs; add sid/api_key/sign to sensitive params - stop forwarding Yandex OAuth headers to API-supplied download hosts and give the last.fm mirror an opt-out and a notice - serialize deezer token state, beatport token snapshots, and qobuz mobile KEK access so concurrent workers cannot race login refreshes - suffix colliding track/video output names instead of overwriting - propagate deezer/qobuz pagination errors, keep paginating when counts are missing, and return a non-zero exit for partial album/playlist rips - clear failed_downloads rows on success and downloads rows on failure; open browse databases read-only; honor independent DB feature flags - drop the redundant deezer metadata call, paginate Yandex searches, bound and rate-limit yt-dlp, and deep-clone the SoundCloud cache - validate conversion codecs before ripping and isolate the qobuz convert smoke test from the real library - write the config atomically and fix deezer slug-vs-id URL parsing
168 lines
4.6 KiB
Go
168 lines
4.6 KiB
Go
package netutil
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"net/http"
|
|
"net/url"
|
|
"time"
|
|
|
|
"streamrip-go/internal/verbose"
|
|
)
|
|
|
|
const defaultMaxConnsPerHost = 16
|
|
|
|
// NewHTTPClient builds an *http.Client whose transport is tuned for the
|
|
// concurrent download workloads this app issues against single CDN hosts.
|
|
//
|
|
// maxConnsPerHost caps idle keep-alive sockets per host; pass <= 0 to use a
|
|
// sensible default. The downloader and provider clients should pass the
|
|
// configured concurrency so keep-alive sockets aren't evicted between workers.
|
|
func NewHTTPClient(timeout time.Duration, verifySSL bool, maxConnsPerHost int) *http.Client {
|
|
if maxConnsPerHost <= 0 {
|
|
maxConnsPerHost = defaultMaxConnsPerHost
|
|
}
|
|
|
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
|
if transport.TLSClientConfig == nil {
|
|
transport.TLSClientConfig = &tls.Config{}
|
|
}
|
|
transport.TLSClientConfig.InsecureSkipVerify = !verifySSL
|
|
|
|
transport.MaxIdleConnsPerHost = maxConnsPerHost
|
|
if maxIdle := maxConnsPerHost * 4; maxIdle > transport.MaxIdleConns {
|
|
transport.MaxIdleConns = maxIdle
|
|
}
|
|
if transport.MaxIdleConns < 100 {
|
|
transport.MaxIdleConns = 100
|
|
}
|
|
transport.MaxConnsPerHost = 0
|
|
transport.IdleConnTimeout = 90 * time.Second
|
|
transport.WriteBufferSize = 64 * 1024
|
|
transport.ReadBufferSize = 64 * 1024
|
|
transport.ForceAttemptHTTP2 = true
|
|
|
|
return &http.Client{
|
|
Timeout: timeout,
|
|
Transport: &loggingTransport{base: transport},
|
|
}
|
|
}
|
|
|
|
// Do performs req and sanitizes transport errors before returning them.
|
|
//
|
|
// http.Client.Do wraps transport failures in *url.Error, whose Error() method
|
|
// embeds the full request URL. Several providers put credentials in query
|
|
// parameters (qobuz password/user_auth_token, deezer api_key/sid, yandex
|
|
// sign), so returning that error verbatim would print the secret to the
|
|
// terminal and into failure logs. Callers should use this instead of
|
|
// client.Do directly.
|
|
func Do(client *http.Client, req *http.Request) (*http.Response, error) {
|
|
resp, err := client.Do(req)
|
|
if err == nil {
|
|
return resp, nil
|
|
}
|
|
return resp, RedactError(err)
|
|
}
|
|
|
|
// RedactError returns err with credentials in its URL removed. It only
|
|
// rewrites a top-level *url.Error, which is what http.Client.Do returns;
|
|
// other error types are returned unchanged.
|
|
func RedactError(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
uerr, ok := err.(*url.Error)
|
|
if !ok {
|
|
return err
|
|
}
|
|
u, parseErr := url.Parse(uerr.URL)
|
|
if parseErr != nil {
|
|
return err
|
|
}
|
|
redacted := redactURL(u)
|
|
if redacted == uerr.URL {
|
|
return err
|
|
}
|
|
cp := *uerr
|
|
cp.URL = redacted
|
|
return &cp
|
|
}
|
|
|
|
// RedactURLString is the string form of redactURL, for logging URLs that are
|
|
// already serialized (download URLs, error messages).
|
|
func RedactURLString(raw string) string {
|
|
u, err := url.Parse(raw)
|
|
if err != nil {
|
|
return raw
|
|
}
|
|
return redactURL(u)
|
|
}
|
|
|
|
// loggingTransport emits one verbose line per HTTP request when verbose
|
|
// level >= VV. The check is per-call so toggling the level at runtime
|
|
// affects subsequent requests without rebuilding clients.
|
|
type loggingTransport struct {
|
|
base http.RoundTripper
|
|
}
|
|
|
|
func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
if !verbose.Enabled(verbose.VV) {
|
|
return t.base.RoundTrip(req)
|
|
}
|
|
start := time.Now()
|
|
resp, err := t.base.RoundTrip(req)
|
|
elapsed := time.Since(start).Round(time.Millisecond)
|
|
target := redactURL(req.URL)
|
|
if err != nil {
|
|
verbose.Printf(verbose.VV, "http %s %s -> error %v (%s)\n", req.Method, target, err, elapsed)
|
|
return resp, err
|
|
}
|
|
verbose.Printf(verbose.VV, "http %s %s -> %d (%s)\n", req.Method, target, resp.StatusCode, elapsed)
|
|
return resp, err
|
|
}
|
|
|
|
// redactURL hides values for query parameters that commonly carry
|
|
// credentials so -vv output and transport errors are safe to paste in an
|
|
// issue. Userinfo passwords are redacted as well.
|
|
func redactURL(u *url.URL) string {
|
|
if u == nil {
|
|
return ""
|
|
}
|
|
cp := *u
|
|
changed := false
|
|
if cp.User != nil {
|
|
if _, hasPassword := cp.User.Password(); hasPassword {
|
|
cp.User = url.UserPassword(cp.User.Username(), "REDACTED")
|
|
changed = true
|
|
}
|
|
}
|
|
if cp.RawQuery != "" {
|
|
q := cp.Query()
|
|
redactedQuery := false
|
|
for k := range q {
|
|
if isSensitiveParam(k) {
|
|
q.Set(k, "REDACTED")
|
|
redactedQuery = true
|
|
}
|
|
}
|
|
if redactedQuery {
|
|
cp.RawQuery = q.Encode()
|
|
changed = true
|
|
}
|
|
}
|
|
if !changed {
|
|
return u.String()
|
|
}
|
|
return cp.String()
|
|
}
|
|
|
|
func isSensitiveParam(name string) bool {
|
|
switch name {
|
|
case "user_auth_token", "api_token", "access_token", "refresh_token",
|
|
"request_sig", "signature", "sign", "password", "pass", "pwd",
|
|
"secret", "app_secret", "client_secret", "token", "code", "auth",
|
|
"key", "api_key", "sid", "arl":
|
|
return true
|
|
}
|
|
return false
|
|
}
|