navidrome/server/subsonic/auth_limiter_test.go
Deluan Quintão c3b9b4ecb3
fix(subsonic): rate limit failed authentication attempts (#6185)
* fix(subsonic): limit failed authentication attempts per client IP and username

The Subsonic API checked credentials on every request with no limit on failures, so any
account could be brute-forced over /rest/*. Failed u+p, t+s and jwt attempts are now capped
per (client IP, lower-cased username) using AuthRequestLimit and AuthWindowLength, the same
settings that guard the UI login. Every request carries credentials, so only failures count:
a slot is taken before the check and given back on success or on a server error, which also
stops concurrent guesses from overshooting the limit.

Blocked attempts get the same response as a wrong password (HTTP 200, error code 40, no
Retry-After), so an attacker cannot tell a block from a wrong guess. Reverse proxy and
internal authentication are not limited. The client IP helper behind ClientIPRateLimiter is
now exported as server.ClientIP, so spoofed forwarding headers cannot open a fresh bucket.

* refactor(subsonic): simplify failed authentication limiter

Release the limiter slot from a single place in authenticate(), after the user lookup and
credential check, instead of separately in the canceled branch. Store attempt counters by
value instead of by pointer, and drop limiter unit tests that only repeated the middleware
specs.

* fix(subsonic): wait for an in-flight auth check instead of rejecting

Slots were reserved before the credential check and only released afterwards, so once
AuthRequestLimit checks for the same client IP and username overlapped, the next request was
answered with error code 40 even when its credentials were valid. Clients that fan out parallel
requests hit this constantly: a burst of six valid logins lost one, a burst of fifty lost forty
five, and the web UI authenticates its own /rest calls the same way.

A key now carries a slot channel of AuthRequestLimit capacity, and a request waits on it rather
than failing when other checks for that key are in flight. Failures are recorded after the check,
and a request is only rejected when the key already reached the limit within the window. A waiting
request gives up if its context is canceled. Concurrent guesses still cannot run unchecked: at most
AuthRequestLimit checks run at once and the rest are turned away as soon as the failures land.

* docs(subsonic): state the real guess ceiling of the auth limiter

The comment claimed a burst cannot overshoot, which reads as a hard cap of AuthRequestLimit. Allowing concurrent checks means a window admits up to 2*limit-1 guesses, so say that instead.
2026-09-20 22:02:23 -04:00

143 lines
3.2 KiB
Go

package subsonic
import (
"context"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("authLimiter", func() {
var ctx context.Context
BeforeEach(func() {
ctx = context.Background()
})
acquire := func(l *authLimiter, key string) (*authSlot, bool) {
GinkgoHelper()
return l.acquire(ctx, key)
}
It("blocks a key after the configured number of failures", func() {
l := newAuthLimiter(2, time.Minute)
for range 2 {
slot, ok := acquire(l, "k")
Expect(ok).To(BeTrue())
slot.release(true)
}
_, ok := acquire(l, "k")
Expect(ok).To(BeFalse())
})
It("never counts successful checks", func() {
l := newAuthLimiter(2, time.Minute)
for range 50 {
slot, ok := acquire(l, "k")
Expect(ok).To(BeTrue())
slot.release(false)
}
})
It("keeps keys independent", func() {
l := newAuthLimiter(1, time.Minute)
slot, _ := acquire(l, "a")
slot.release(true)
_, ok := acquire(l, "a")
Expect(ok).To(BeFalse())
_, ok = acquire(l, "b")
Expect(ok).To(BeTrue())
})
It("waits for an in-flight check instead of failing the request", func() {
l := newAuthLimiter(1, time.Minute)
held, ok := acquire(l, "k")
Expect(ok).To(BeTrue())
waiting := make(chan bool, 1)
go func() {
slot, ok := l.acquire(ctx, "k")
slot.release(false)
waiting <- ok
}()
Consistently(waiting, 50*time.Millisecond).ShouldNot(Receive())
held.release(false)
Eventually(waiting).Should(Receive(BeTrue()))
})
It("stops waiting when the request is canceled", func() {
l := newAuthLimiter(1, time.Minute)
held, _ := acquire(l, "k")
DeferCleanup(func() { held.release(false) })
canceled, cancel := context.WithCancel(context.Background())
cancel()
_, ok := l.acquire(canceled, "k")
Expect(ok).To(BeFalse())
})
It("does not let concurrent guesses overshoot the limit", func() {
l := newAuthLimiter(5, time.Minute)
hold := make(chan struct{})
var checks atomic.Int32
var wg sync.WaitGroup
for range 50 {
wg.Go(func() {
slot, ok := l.acquire(ctx, "k")
if !ok {
return
}
checks.Add(1)
<-hold
slot.release(true)
})
}
Eventually(checks.Load).Should(Equal(int32(5)))
Consistently(checks.Load, 100*time.Millisecond).Should(Equal(int32(5)))
close(hold)
wg.Wait()
_, ok := acquire(l, "k")
Expect(ok).To(BeFalse())
})
It("allows everything when the limit is disabled", func() {
l := newAuthLimiter(0, time.Minute)
for range 10 {
slot, ok := acquire(l, "k")
Expect(ok).To(BeTrue())
slot.release(true)
}
})
})
// testing/synctest's fake clock needs a *testing.T, which Ginkgo doesn't give.
func TestAuthLimiterWindow(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
g := NewWithT(t)
ctx := context.Background()
l := newAuthLimiter(1, 20*time.Second)
for _, key := range []string{"a", "b"} {
slot, ok := l.acquire(ctx, key)
g.Expect(ok).To(BeTrue())
slot.release(true)
}
_, ok := l.acquire(ctx, "a")
g.Expect(ok).To(BeFalse())
time.Sleep(20 * time.Second)
slot, ok := l.acquire(ctx, "a")
g.Expect(ok).To(BeTrue())
slot.release(false)
g.Expect(l.keys).To(HaveLen(1), "expired keys must be dropped")
})
}