Dev.to WebDev ๐Ÿ›  Dev ๐Ÿ‘ 2 ๐Ÿ“– 6 min read

My Rate Limiter Trusted X-Forwarded-For. Yours Probably Does Too

Here's a function from my rate limiter. It sat in the library for a year. It had a test. The test passed. func KeyByIP(r *http.Request) string { if xff := r.Header.Get("X-Forwarded-For"); xff != "" { ips :

Here's a function from my rate limiter. It sat in the library for a year. It had a test. The test passed.

func KeyByIP(r *http.Request) string {
    if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
        ips := strings.Split(xff, ",")
        return strings.TrimSpace(ips[0])
    }
    if xri := r.Header.Get("X-Real-IP"); xri != "" {
        return xri
    }
    ip, _, _ := net.SplitHostPort(r.RemoteAddr)
    return ip
}

The test was literally called X-Forwarded-For takes precedence. My article about the library said it "handles X-Forwarded-For and X-Real-IP headers correctly".

It didn't. And it wasn't the only bug.

This week I went back to kazrl and reviewed it like a stranger would. Read every line, ran it under pprof, built it into real Gin, Echo and Fiber apps. I found five bugs. One of them let any client switch the limit off. Two more came from my own fixes.

None of them are specific to my code. If you wrote a rate limiter, or copied one, check yours against this list.

1. The client picks its own key

X-Forwarded-For is a request header. The client writes it. A proxy appends the address it saw to the right end of it. So the leftmost entry is whatever the client put there.

With the code above, this request gets a fresh limiter every time:

curl -H "X-Forwarded-For: 1.2.3.$RANDOM" https://api.example.com/login

The limit never triggers. X-Real-IP is no better: if your proxy doesn't overwrite it, the client sets it too.

The fix has two parts. KeyByIP now reads only the address of the connection, which the client can't fake:

func KeyByIP(r *http.Request) string {
    ip, _, err := net.SplitHostPort(r.RemoteAddr)
    if err != nil {
        return r.RemoteAddr
    }
    return ip
}

Behind a load balancer that address is the balancer's, so there's a second key function. You tell it which networks are your proxies, and it walks the header from the right while the address in hand belongs to one of them:

ip := KeyByIP(r)
hops := strings.Split(strings.Join(r.Header.Values("X-Forwarded-For"), ","), ",")
for i := len(hops) - 1; i >= 0 && trusted(ip); i-- {
    if hop := strings.TrimSpace(hops[i]); hop != "" {
        ip = hop
    }
}
return ip

It stops at the first address your proxies didn't add. Whatever the client wrote further left is ignored.

keyFunc := middleware.KeyByIPBehindProxies(netip.MustParsePrefix("10.0.0.0/8"))

Bonus: KeyByIP went from 48 ns to 7.5 ns, since it no longer parses a header.

2. Every fake key lives forever

The per-client map had a comment: "manages per-key rate limiters with automatic cleanup". There was no cleanup. Every key got a limiter, and the limiter stayed until the process died.

Together with bug #1 that's a memory leak anyone can drive with a curl loop. A benchmark with a stream of unique keys left 3.2 million limiters in the map.

The obvious fix is a TTL per key. I didn't want a background goroutine and a timestamp per entry, so the fix uses a property the limiters already have: a limiter that is back in its initial state decides exactly like a new one. A full token bucket, an empty leaky bucket, a sliding window with nothing in it. Dropping it changes no decision.

type Idler interface {
    Idle() bool
}

When a new key comes in, the map drops every idle limiter, at most once a minute. So it holds only the keys seen within about one window. The same flood with a sweep every 10 ms leaves about 28 thousand keys, and allocations per run drop from 2.3 GB to 1.1 GB.

3. Anonymous clients share one limiter

func KeyByAPIKey(r *http.Request) string {
    auth := r.Header.Get("Authorization")
    if auth == "" {
        return ""
    }
    ...
}

Every request without an API key got the key "". One limiter for all anonymous users. One noisy client and everyone without a key gets 429.

Now a request without a key falls back to its IP. The keys get prefixes, key: and ip:, so an API key can never match somebody's address.

4. Wait didn't wait

This one is subtle. Reserve tells you how long to wait before your request may go. Here's the leaky bucket version:

if len(lb.queue)+n <= lb.capacity {
    lb.queue = append(lb.queue, now)
    return 0
}

itemsToLeak := len(lb.queue) + n - lb.capacity
return lb.leakInterval * time.Duration(itemsToLeak)

When the bucket is full, it computes the wait and returns. It doesn't book anything. So ten goroutines calling Wait at the same moment all get the same delay, all sleep, and all go through together.

The numbers show it. With the limit at 1 million requests per second, Wait should take exactly 1.00 ยตs per request. The leaky bucket took 0.74 ยตs. That's 35% over the limit it was supposed to enforce.

A reservation has to take the slot:

itemsToLeak := lb.queued + n - lb.capacity
lb.queued += n
if itemsToLeak <= 0 {
    return 0
}
return lb.lastLeak.Add(time.Duration(itemsToLeak) * lb.leakInterval).Sub(now)

The sliding window got the same fix: the request is booked at the moment the k-th oldest entry leaves the window. All three algorithms now land at 1.00 to 1.02 ยตs.

5. pprof on my own fix

Here's where it got humbling. After fixing Reserve, I ran the benchmarks again. The sliding window's Reserve went from 37 ns to 870 ns.

The CPU profile showed the time going into copying. Every time an old entry expired, the code copied the whole log into a new slice. Reservations made the log longer than the burst, so every call copied more. The fix is to reslice instead of copy:

sw.requests = sw.requests[validIdx:]

append drops the dead head on its own the next time it reallocates. 80 ns.

The memory profile found the second one. The leaky bucket kept a slice of timestamps, one per queued request. Nothing ever read them, only the length mattered. With reservations the queue grew, and one benchmark run allocated 2 GB. I replaced the slice with a counter. Now every leaky bucket benchmark shows 0 B/op.

Lesson: benchmark the fix, not only the bug.

6. The middleware didn't compile

Not a security bug, but the most embarrassing one. The Gin and Fiber adapters were written against interfaces that the real *gin.Context and *fiber.Ctx don't satisfy. The Echo one returned nil where it should have called the next handler. The tests used mocks, so they all passed.

The adapters are generic now, so they take the framework's real context type without importing the framework:

r.Use(middleware.Gin[*gin.Context](limiter))

The root module still has zero dependencies. The real frameworks live in a separate test module, frameworktest, that runs Gin, Echo, Fiber v2 and Fiber v3 in CI.

And that module paid for itself right away. A Fiber test was flaky: it expected 200 200 429 and sometimes got 200 200 200. Fiber hands out strings that point into a buffer it reuses for the next request. My map stored that string as the key, so the key changed under the map, and the next lookup missed. The map now keeps its own copy with strings.Clone. A mock would never show you that.

Check your limiter

Five questions, a few minutes each:

  1. Where does the key come from? If it reads X-Forwarded-For or X-Real-IP without knowing your proxies, the client picks it.
  2. What removes old keys? If nothing does, a loop of fake keys is a memory leak.
  3. What key does a request without credentials get? An empty string means one limiter for everyone.
  4. Does Wait book the slot? Start ten goroutines on a limiter with burst 1 and time them.
  5. Is the middleware tested against the real framework? Mocks won't reuse buffers.

The library

All of this is fixed in kazrl: token bucket, leaky bucket and sliding window, middleware for net/http, Chi, Gin, Echo and Fiber.

go get github.com/makennsky/kazrl

Zero dependencies, tests run with the race detector, MIT license.

If you find a sixth bug, open an issue. I'd rather hear it from you than from someone's curl loop.

๐Ÿ“ฐ Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.