fix(lidarr): saved defaults, conflicts, no proxy, readable addresses

- Setting the address alone now stores the default options (monitor all, search
  for missing albums), so what is shown is what will be sent.
- A 409 from Lidarr, when two adds of the same artist cross, means the artist is
  already there; only "an artist with this ID was not found" is an unknown artist.
- The client never goes through a proxy named by the environment, since Lidarr is
  on the admin's own network and the key travels in a header.
- An address that cannot be read back (an IPv6 zone) is refused instead of being
  stored and reported as "not configured".
- A deadline asking Lidarr is a bad gateway, not an internal error; a redirect is
  reported with a hint to use the final address; the request schema of the Lidarr
  options is closed.
This commit is contained in:
tgiachi 2026-11-12 11:11:35 +01:00
commit 4dbe1074ba
8 changed files with 106 additions and 5 deletions

View file

@ -213,7 +213,7 @@ curl -s -X PUT $BASE/providers/lidarr -H "$AUTH" -d '{"lidarr":{"quality_profile
curl -s -X PUT $BASE/providers/lidarr -H "$AUTH" -d '{"enabled":true}'
```
The address can have a path if Lidarr runs under a URL base, and it cannot carry a user, a password or a query: the key is sent in a header, never in the address, and Sonda never follows a redirect, so it cannot go anywhere else. `lidarr` replaces all its options at once; what it leaves out is `monitor` `all` and `search_missing` `true`. The folder of an artist that Lidarr downloads shows up in Lidarr's root folder only with the first import: add that folder as a library of Sonda yourself, and a scan finds the new files.
The address can have a path if Lidarr runs under a URL base, and it cannot carry a user, a password or a query: the key is sent in a header, never in the address, and Sonda never follows a redirect, so it cannot go anywhere else (if your `http://` address redirects to `https://`, set the `https://` one) and never goes through a proxy named by the environment, since Lidarr is on your own network. `lidarr` replaces all its options at once; what it leaves out is `monitor` `all` and `search_missing` `true`. The folder of an artist that Lidarr downloads shows up in Lidarr's root folder only with the first import: add that folder as a library of Sonda yourself, and a scan finds the new files.
The key is stored in the database, in clear text, and is never returned by the API or written to the log: the list only says `has_api_key`. Because the database holds it, treat database backups like secrets. Removing the key turns the provider off, and each provider describes in the list exactly what it sends.

View file

@ -159,7 +159,7 @@ func writeLidarrError(c *gin.Context, err error) {
writeError(c, http.StatusBadGateway, "lidarr_key_refused", "Lidarr refused the API key")
case errors.Is(err, context.Canceled):
writeError(c, 499, "canceled", "request canceled")
case errors.Is(err, lidarr.ErrUnreachable), errors.Is(err, lidarr.ErrBadResponse):
case errors.Is(err, lidarr.ErrUnreachable), errors.Is(err, lidarr.ErrBadResponse), errors.Is(err, context.DeadlineExceeded):
_ = c.Error(err)
writeError(c, http.StatusBadGateway, "lidarr_unavailable", "Lidarr could not be asked")
default:

View file

@ -148,6 +148,7 @@ func TestWhatGoesWrongAskingLidarrIsSaidPlainly(t *testing.T) {
{lidarr.ErrKeyRefused, http.StatusBadGateway, "lidarr_key_refused"},
{lidarr.ErrUnreachable, http.StatusBadGateway, "lidarr_unavailable"},
{lidarr.ErrBadResponse, http.StatusBadGateway, "lidarr_unavailable"},
{context.DeadlineExceeded, http.StatusBadGateway, "lidarr_unavailable"},
} {
fake.err = c.err
if r := do(t, h, "GET", "/api/v1/providers/lidarr/options", admin, nil); r.Code != c.status || errCode(r) != c.code {

View file

@ -2355,6 +2355,7 @@ components:
lidarr:
description: "Only for Lidarr. Replaces all its options at once: what is left out is the default (`monitor` all, `search_missing` true, the rest empty or 0)."
type: object
additionalProperties: false
properties:
quality_profile_id: {type: integer, minimum: 0}
metadata_profile_id: {type: integer, minimum: 0}

View file

@ -76,6 +76,13 @@ func New(cfg ConfigFunc, userAgent func() string, rt http.RoundTripper) *Client
if userAgent == nil {
userAgent = func() string { return providers.UserAgent("", "") }
}
if rt == nil {
// Lidarr is on the admin's own network, and the key must not go through a proxy that the
// environment names for the rest of the world.
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.Proxy = nil
rt = tr
}
return &Client{
cfg: cfg,
userAgent: userAgent,
@ -130,7 +137,7 @@ func (c *Client) do(ctx context.Context, method, path string, query url.Values,
}
defer resp.Body.Close()
if resp.StatusCode >= 300 && resp.StatusCode < 400 {
return 0, nil, fmt.Errorf("%w: a redirect, which is never followed", ErrBadResponse)
return 0, nil, fmt.Errorf("%w: the address answers with a redirect, which is never followed: use the address Lidarr finally answers on", ErrBadResponse)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))
if err != nil {
@ -385,12 +392,15 @@ func (c *Client) Add(ctx context.Context, r AddRequest) error {
if status >= 200 && status < 300 {
return nil
}
if status == http.StatusConflict {
return ErrAlreadyAdded // Lidarr answers so when two adds of the same artist cross
}
if status == http.StatusBadRequest {
reason := reasons(data)
switch lower := strings.ToLower(reason); {
case strings.Contains(lower, "already been added"):
return ErrAlreadyAdded
case strings.Contains(lower, "was not found"):
case strings.Contains(lower, "artist with this id was not found"):
return ErrNotFound
case reason == "":
return fmt.Errorf("%w: no reason given", ErrRejected)

View file

@ -373,3 +373,51 @@ func TestProbeSaysWhatTheTestOfAProviderNeeds(t *testing.T) {
t.Errorf("not set up: %v", err)
}
}
func TestAConflictFromLidarrMeansTheArtistIsAlreadyThere(t *testing.T) {
f := newFake(t)
f.json("GET", "/api/v1/artist/lookup", lookup)
f.on("POST", "/api/v1/artist", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusConflict) })
err := f.client().Add(context.Background(), AddRequest{MBID: mbid, QualityProfileID: 1, MetadataProfileID: 1, RootFolderPath: "/m", Monitor: "all"})
if !errors.Is(err, ErrAlreadyAdded) {
t.Errorf("err = %v", err)
}
}
func TestOnlyAnUnknownArtistIsNotFoundWhateverElseLidarrSays(t *testing.T) {
req := AddRequest{MBID: mbid, QualityProfileID: 1, MetadataProfileID: 1, RootFolderPath: "/m", Monitor: "all"}
for message, want := range map[string]error{
"An artist with this ID was not found": ErrNotFound,
"Root folder was not found": ErrRejected,
"Quality profile was not found": ErrRejected,
} {
f := newFake(t)
f.json("GET", "/api/v1/artist/lookup", lookup)
f.on("POST", "/api/v1/artist", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `[{"errorMessage":"`+message+`"}]`)
})
if err := f.client().Add(context.Background(), req); !errors.Is(err, want) {
t.Errorf("%q: err = %v, want %v", message, err, want)
}
}
}
func TestTheServerOfYourOwnIsNeverReachedThroughAProxyFromTheEnvironment(t *testing.T) {
c := New(nil, nil, nil)
tr, ok := c.hc.Transport.(*http.Transport)
if !ok || tr.Proxy != nil {
t.Errorf("transport = %#v: Lidarr is on your own network, and the key must not go through a proxy", c.hc.Transport)
}
}
func TestARedirectIsReportedWithAHintToUseTheFinalAddress(t *testing.T) {
f := newFake(t)
f.on("GET", "/api/v1/system/status", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://example.org/", http.StatusMovedPermanently)
})
_, err := f.client().Status(context.Background())
if !errors.Is(err, ErrBadResponse) || !strings.Contains(err.Error(), "address") {
t.Errorf("err = %v, want it to say that the address answers with a redirect", err)
}
}

View file

@ -208,3 +208,36 @@ func TestStoredGivesTheSettingsWhetherTheProviderIsOnOrNot(t *testing.T) {
t.Errorf("unknown: %v", err)
}
}
func TestSettingTheAddressAloneStoresTheDefaultOptions(t *testing.T) {
s, st := newSvc()
ctx := context.Background()
if _, err := s.Update(ctx, Lidarr, Patch{APIKey: strp(lidarrKey), URL: strp("http://orion:8686")}); err != nil {
t.Fatal(err)
}
// What the list shows is what is stored, so what Sonda sends to Lidarr is what the admin saw.
if got := st.rows[Lidarr].Lidarr; got.Monitor != "all" || !got.SearchMissing {
t.Errorf("stored = %+v, want monitor all and search_missing true", got)
}
got, err := s.Stored(ctx, Lidarr)
if err != nil || got.Lidarr.Monitor != "all" || !got.Lidarr.SearchMissing {
t.Errorf("Stored = %+v err=%v", got.Lidarr, err)
}
// A choice that is made stays, including "do not search".
off := LidarrOptions{QualityProfileID: 1, MetadataProfileID: 1, RootFolderPath: "/m", Monitor: "none", SearchMissing: false}
_, _ = s.Update(ctx, Lidarr, Patch{Lidarr: &off})
_, _ = s.Update(ctx, Lidarr, Patch{Contact: strp("x")})
if got, _ := s.Stored(ctx, Lidarr); got.Lidarr != off {
t.Errorf("after another change = %+v, want %+v", got.Lidarr, off)
}
}
func TestAnAddressWithAZoneThatCannotBeReadBackIsRefused(t *testing.T) {
s, _ := newSvc()
if _, err := s.Update(context.Background(), Lidarr, Patch{URL: strp("http://[fe80::1%25eth0]:8686")}); !errors.Is(err, ErrInvalidSettings) {
t.Errorf("err = %v", err)
}
if in, err := s.Update(context.Background(), Lidarr, Patch{URL: strp("http://[fd00::5]:8686/")}); err != nil || in.URL != "http://[fd00::5]:8686" {
t.Errorf("an IPv6 address: %+v %v", in, err)
}
}

View file

@ -313,6 +313,10 @@ func (s *Service) Update(ctx context.Context, name string, p Patch) (Info, error
cur.Enabled = *p.Enabled
}
if m.needsURL {
// What the list shows is what is stored: a setup that never chose a monitor option has the default.
cur.Lidarr = cur.Lidarr.withDefaults()
}
cur.UpdatedAt = s.now()
if err := s.store.Save(ctx, cur); err != nil {
return Info{}, fmt.Errorf("save provider settings: %w", err)
@ -406,7 +410,11 @@ func validateURL(m meta, raw string) (string, error) {
if u.User != nil {
return bad("cannot carry a user or a password: the key is set apart")
}
return u.Scheme + "://" + u.Host + strings.TrimRight(u.EscapedPath(), "/"), nil
out := u.Scheme + "://" + u.Host + strings.TrimRight(u.EscapedPath(), "/")
if back, err := url.Parse(out); err != nil || back.Host != u.Host {
return bad("cannot be used as it is (an IPv6 zone must be left out)") // what is stored must read back
}
return out, nil
}
func validateLidarrOptions(o LidarrOptions) error {