gateway: a flood of wrong remote keys is capped to 429, so a weak caller key can't be guessed unthrottled and each try stops being a valid/invalid oracle (akic404 on Discord)

A pentest of a publicly-exposed magpie gateway found the auth entry had no
rate limit: a remote client could try keys as fast as it liked. The system
key (sk-magpie-key-<48 hex>) is infeasible to guess, but a weak user-set key
(8+ ASCII) is not, and every try returned a distinct 401 that told the
caller whether the key was valid/well-formed.

tooManyAuthFails is one token bucket (50 wrong keys, then ~1/s) shared across
all remote callers. identifyCaller spends a token only on the !ok && !local
branch; once empty, later wrong keys get 429 + Retry-After instead of the
401 message, closing the oracle and bounding the work. A request carrying a
valid key, and any loopback request, never touch the bucket, so flooding
wrong keys can only clamp later wrong keys -- it can never lock out a real
caller (no self-DoS, which is why the bucket is global, not per-IP: behind a
reverse proxy every caller shares the proxy's address anyway).

Left unchanged, by design: the last-4 echo for a long key (#545, it names
only the caller's own submitted key, for debugging), and MAGPIE_WEB_KEY
(already forced >=16 chars + a charset in internal/gui/web.go).

Run (macOS): go test ./internal/gateway/ ./internal/access/ (both ok);
gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/gateway/ clean.
Broke tooManyAuthFails to always return false and watched
TestAuthThrottleSparesValidAndLocal go red ("never clamped to 429").
This commit is contained in:
yetone
2026-10-11 23:14:44 +08:00
parent b0e25696eb
commit 396a6a3d4f
5 changed files with 203 additions and 0 deletions
+66
View File
@@ -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()
}
+127
View File
@@ -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())
}
}
+1
View File
@@ -60,6 +60,7 @@ func fresh(t *testing.T) {
remoteRefreshes.Lock()
remoteRefreshes.at = map[string]time.Time{}
remoteRefreshes.Unlock()
resetAuthThrottle()
forgetRouting()
}
+8
View File
@@ -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)
+1
View File
@@ -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)
}