diff --git a/internal/gateway/auththrottle.go b/internal/gateway/auththrottle.go new file mode 100644 index 000000000..30c4e339d --- /dev/null +++ b/internal/gateway/auththrottle.go @@ -0,0 +1,66 @@ +package gateway + +import ( + "sync" + "time" +) + +// A publicly reachable gateway turns every request away without a valid +// gateway key, but nothing capped how fast a remote client could try keys: +// no limit let a weak user-set key be guessed, and each try gave a yes/no +// oracle on whether a key was valid. authFailThrottle caps *failed remote* +// authentications. A request that carries a valid key, and any request from +// this computer, never touch it, so flooding wrong keys can only turn later +// wrong keys into 429s — it can never lock a real user out. +// +// It is one token bucket shared across all remote callers. Keying it per +// client address would be pointless behind a reverse proxy, where every +// caller arrives as the proxy's address; a shared bucket is safe here only +// because valid keys bypass it entirely. + +const ( + authFailBurst = 50 // wrong remote keys tolerated before 429s begin + authFailRefill = 1 * time.Second // one more wrong key is allowed per this +) + +var authThrottle = struct { + sync.Mutex + tokens float64 + last time.Time + now func() time.Time +}{tokens: authFailBurst, now: time.Now} + +// tooManyAuthFails records one refused remote authentication and reports +// whether the caller should now be turned away with 429 instead of the usual +// 401, and for how long until a token frees. Only identifyCaller calls it, +// and only for a remote request that presented no valid key. +func tooManyAuthFails() (over bool, retry time.Duration) { + t := &authThrottle + t.Lock() + defer t.Unlock() + now := t.now() + if t.last.IsZero() { + t.last = now + } + t.tokens += now.Sub(t.last).Seconds() / authFailRefill.Seconds() + if t.tokens > authFailBurst { + t.tokens = authFailBurst + } + t.last = now + if t.tokens >= 1 { + t.tokens-- + return false, 0 + } + // No token left: say how long until one refills, so the client can back + // off. The failure is not charged again while the bucket is empty. + return true, time.Duration((1 - t.tokens) * float64(authFailRefill)) +} + +// resetAuthThrottle refills the bucket. fresh(t) calls it so the global +// counter never carries wrong-key tries from one test into the next. +func resetAuthThrottle() { + t := &authThrottle + t.Lock() + t.tokens, t.last, t.now = authFailBurst, time.Time{}, time.Now + t.Unlock() +} diff --git a/internal/gateway/auththrottle_test.go b/internal/gateway/auththrottle_test.go new file mode 100644 index 000000000..ed1bdba0c --- /dev/null +++ b/internal/gateway/auththrottle_test.go @@ -0,0 +1,127 @@ +package gateway + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// The bucket tolerates a burst of wrong remote keys, then turns the next one +// away until a token refills, on an injected clock so the test is not timed. +func TestAuthThrottleBurstThenRefills(t *testing.T) { + resetAuthThrottle() + t.Cleanup(resetAuthThrottle) + cur := time.Unix(1_700_000_000, 0) + authThrottle.Lock() + authThrottle.now = func() time.Time { return cur } + authThrottle.Unlock() + + for i := 0; i < authFailBurst; i++ { + if over, _ := tooManyAuthFails(); over { + t.Fatalf("turned away within the burst, at try %d", i+1) + } + } + over, retry := tooManyAuthFails() + if !over || retry <= 0 { + t.Fatalf("one past the burst: over=%v retry=%v, want over with a wait", over, retry) + } + // Still clamped a moment later. + cur = cur.Add(authFailRefill / 2) + if over, _ := tooManyAuthFails(); !over { + t.Fatal("let a wrong key through before a token refilled") + } + // A full refill period frees exactly one token. + cur = cur.Add(authFailRefill) + if over, _ := tooManyAuthFails(); over { + t.Fatal("still clamped after a token refilled") + } + if over, _ := tooManyAuthFails(); !over { + t.Fatal("let a second wrong key through on one refilled token") + } +} + +// A flood of wrong remote keys ends in 429s with Retry-After, but a valid +// key and a request from this computer are never held — the real caller +// gets in while the attacker is clamped. +func TestAuthThrottleSparesValidAndLocal(t *testing.T) { + fresh(t) // resets the bucket + t.Setenv("MAGPIE_ADDR", "") + h := lanGuard(New().Handler()) + _, secrets := newCaller(t, "LAN client") + key := secrets[0] + + // Hold the clock so no token refills mid-test: the flood must stay + // clamped from the moment it fills the bucket. + cur := time.Unix(1_700_000_000, 0) + authThrottle.Lock() + authThrottle.now = func() time.Time { return cur } + authThrottle.Unlock() + t.Cleanup(resetAuthThrottle) + + call := func(from string, hdr ...string) (int, http.Header) { + r := httptest.NewRequest("GET", "/v1/magpie/quotas", nil) + r.RemoteAddr = from + for i := 0; i+1 < len(hdr); i += 2 { + r.Header.Set(hdr[i], hdr[i+1]) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code, w.Header() + } + + got401, got429 := 0, 0 + for i := 0; i < authFailBurst+10; i++ { + c, hdr := call("192.168.1.9:5000", "Authorization", "Bearer wrong-key-value") + switch c { + case http.StatusUnauthorized: + got401++ + case http.StatusTooManyRequests: + got429++ + if hdr.Get("Retry-After") == "" { + t.Fatal("a 429 with no Retry-After") + } + default: + t.Fatalf("a wrong key got %d", c) + } + } + if got401 < authFailBurst { + t.Fatalf("clamped before the burst was spent: only %d of %d got 401", got401, authFailBurst) + } + if got429 == 0 { + t.Fatal("a flood of wrong keys was never clamped to 429") + } + + // The valid key is answered even though the bucket is empty. + if c, _ := call("192.168.1.9:5000", "Authorization", "Bearer "+key); c != 200 { + t.Fatalf("a valid key was held during the flood: got %d", c) + } + // A request from this computer is never counted or clamped. + for i := 0; i < 5; i++ { + if c, _ := call("127.0.0.1:5000"); c != 200 { + t.Fatalf("a loopback request was clamped: got %d", c) + } + } + // A wrong key is still clamped right after. + if c, _ := call("192.168.1.9:5000", "Authorization", "Bearer wrong-key-value"); c != http.StatusTooManyRequests { + t.Fatalf("the flood cleared when it should not have: got %d", c) + } +} + +// Before the cap is reached, a wrong key still gets the helpful 401, not a +// 429 (the burst does not swallow ordinary mistypes). +func TestAuthThrottleKeepsFirstRefusalHelpful(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + h := lanGuard(New().Handler()) + newCaller(t, "LAN client") + r := httptest.NewRequest("GET", "/v1/magpie/quotas", nil) + r.RemoteAddr = "10.0.0.7:5000" + r.Header.Set("Authorization", "Bearer mgp-typo-key-9z7q") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != http.StatusUnauthorized || !strings.Contains(w.Body.String(), "ending in 9z7q") { + t.Fatalf("first wrong key not a helpful 401: %d %s", w.Code, w.Body.String()) + } +} diff --git a/internal/gateway/group_test.go b/internal/gateway/group_test.go index 582c7ebca..fa5d28a89 100644 --- a/internal/gateway/group_test.go +++ b/internal/gateway/group_test.go @@ -60,6 +60,7 @@ func fresh(t *testing.T) { remoteRefreshes.Lock() remoteRefreshes.at = map[string]time.Time{} remoteRefreshes.Unlock() + resetAuthThrottle() forgetRouting() } diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index 615312f0c..239bba245 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -395,6 +395,14 @@ func identifyCaller(w http.ResponseWriter, r *http.Request) (*http.Request, bool } } if !ok && !local(r) { + if over, retry := tooManyAuthFails(); over { + // A flood of wrong keys: stop answering each one (no 401 oracle, + // no unbounded work) until the bucket refills. A valid key never + // reaches here, so a real caller is not held. + w.Header().Set("Retry-After", strconv.Itoa(int(retry.Seconds())+1)) + writeError(w, provider.Chat, http.StatusTooManyRequests, "too many failed authentications; slow down and send an enabled magpie gateway key") + return r, false + } msg := refusedKey(callerKey(r)) log.Printf("refused %s %s from %s: %s", r.Method, r.URL.Path, r.RemoteAddr, msg) writeError(w, provider.Chat, http.StatusUnauthorized, msg) diff --git a/internal/gateway/lan_test.go b/internal/gateway/lan_test.go index 7560ea67d..ad47dc69a 100644 --- a/internal/gateway/lan_test.go +++ b/internal/gateway/lan_test.go @@ -366,6 +366,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) { for _, rt := range routes { for _, from := range []string{"172.17.0.1:40312", "192.168.1.9:5000"} { for _, hdr := range [][]string{nil, {"Authorization", "Bearer magpie"}, {"x-api-key", "anything"}, {"x-goog-api-key", "magpie"}, {"Authorization", "Bearer " + live}} { + resetAuthThrottle() // test each route's own guard, not the flood limiter that would 429 later tries if c, b := call(rt[0], rt[1], from, hdr...); c != http.StatusUnauthorized || !strings.Contains(b, "gateway key") { t.Errorf("%s %s from %s with %v: %d %.120s", rt[0], rt[1], from, hdr, c, b) }