Files
allmende/internal/api/ratelimit_test.go
T
nilsandClaude Sonnet 5.5 3799faddcf api: a per-client rate limit on the HTTP API, with trusted proxies for X-Forwarded-For
600 /api/ requests a minute per client address (--requests-per-minute), 429 with Retry-After; static UI files and the node's own machine are exempt. The real client behind a reverse proxy is read from X-Forwarded-For only when the connection comes from a --trusted-proxy, taking the last entry that is not itself a trusted proxy. k8s: TRUSTED_PROXY in config.env (the private ranges) is passed as --trusted-proxy.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
2026-11-19 00:35:21 +01:00

140 lines
5.2 KiB
Go

package api
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
// hit makes one request as if it came over a connection from remote, with an
// optional X-Forwarded-For, and returns the status.
func hit(h http.Handler, path, remote, xff string) int {
r := httptest.NewRequest("GET", path, nil)
r.RemoteAddr = remote
if xff != "" {
r.Header.Set("X-Forwarded-For", xff)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code
}
func limitedHandler(t *testing.T, limit int, proxies ...string) (http.Handler, *time.Time) {
t.Helper()
now := time.Unix(1_800_000_000, 0)
p, err := ParseProxies(proxies)
if err != nil {
t.Fatal(err)
}
return New(Config{RequestsPerMinute: limit, TrustedProxies: p, Clock: func() time.Time { return now }}), &now
}
func TestOneAddressCannotMakeMoreRequestsThanTheLimit(t *testing.T) {
h, now := limitedHandler(t, 5)
for i := 0; i < 5; i++ {
if c := hit(h, "/api/v1/nothing", "203.0.113.7:5000", ""); c == http.StatusTooManyRequests {
t.Fatalf("request %d within the limit refused", i)
}
}
if c := hit(h, "/api/v1/nothing", "203.0.113.7:5001", ""); c != http.StatusTooManyRequests {
t.Fatalf("over the limit: %d, want 429", c)
}
if c := hit(h, "/api/v1/nothing", "203.0.113.8:5000", ""); c == http.StatusTooManyRequests {
t.Fatal("another address must not share the allowance")
}
*now = now.Add(time.Minute)
if c := hit(h, "/api/v1/nothing", "203.0.113.7:5002", ""); c == http.StatusTooManyRequests {
t.Fatal("the next minute must start fresh")
}
}
func TestTheUIFilesAndTheNodesOwnMachineAreNotLimited(t *testing.T) {
h, _ := limitedHandler(t, 2)
for i := 0; i < 20; i++ {
if c := hit(h, "/index.html", "203.0.113.7:5000", ""); c == http.StatusTooManyRequests {
t.Fatal("static files must not count")
}
if c := hit(h, "/api/v1/nothing", "127.0.0.1:5000", ""); c == http.StatusTooManyRequests {
t.Fatal("the owner on the node's own machine must not be limited")
}
if c := hit(h, "/api/v1/nothing", "[::1]:5000", ""); c == http.StatusTooManyRequests {
t.Fatal("IPv6 loopback must not be limited")
}
}
}
func TestANegativeLimitSwitchesItOff(t *testing.T) {
h, _ := limitedHandler(t, -1)
for i := 0; i < 50; i++ {
if hit(h, "/api/v1/nothing", "203.0.113.7:5000", "") == http.StatusTooManyRequests {
t.Fatal("limited although switched off")
}
}
}
func TestForwardedForIsBelievedOnlyFromATrustedProxy(t *testing.T) {
h, _ := limitedHandler(t, 2, "10.42.0.0/16")
// A stranger cannot pick its own address: the header is ignored.
for i := 0; i < 2; i++ {
hit(h, "/api/v1/nothing", "203.0.113.7:5000", "198.51.100."+string(rune('1'+i)))
}
if c := hit(h, "/api/v1/nothing", "203.0.113.7:5000", "198.51.100.9"); c != http.StatusTooManyRequests {
t.Fatalf("a stranger varying X-Forwarded-For escaped the limit: %d", c)
}
// Through the proxy, each real client has its own allowance.
for i := 0; i < 2; i++ {
hit(h, "/api/v1/nothing", "10.42.1.1:5000", "198.51.100.20")
}
if c := hit(h, "/api/v1/nothing", "10.42.1.1:5000", "198.51.100.20"); c != http.StatusTooManyRequests {
t.Fatalf("the third request of one forwarded client: %d, want 429", c)
}
if c := hit(h, "/api/v1/nothing", "10.42.1.1:5000", "198.51.100.21"); c == http.StatusTooManyRequests {
t.Fatal("another forwarded client must not share the allowance")
}
}
func TestAClientCannotForgeItsAddressBehindTheProxy(t *testing.T) {
s := &server{}
s.TrustedProxies, _ = ParseProxies([]string{"10.42.0.0/16", "192.0.2.1"})
for name, c := range map[string]struct{ remote, xff, want string }{
"no proxy, header ignored": {"203.0.113.7:1", "1.2.3.4", "203.0.113.7"},
"proxy adds the client": {"10.42.0.5:1", "198.51.100.20", "198.51.100.20"},
"the client wrote its own first": {"10.42.0.5:1", "6.6.6.6, 198.51.100.20", "198.51.100.20"},
"two proxies in a row": {"10.42.0.5:1", "198.51.100.20, 192.0.2.1", "198.51.100.20"},
"header from the proxy is empty": {"10.42.0.5:1", "", "10.42.0.5"},
"unreadable entry is not trusted": {"10.42.0.5:1", "198.51.100.20, nonsense", "10.42.0.5"},
"IPv4 written as IPv6": {"10.42.0.5:1", "::ffff:198.51.100.20", "198.51.100.20"},
} {
r := httptest.NewRequest("GET", "/", nil)
r.RemoteAddr = c.remote
if c.xff != "" {
r.Header.Set("X-Forwarded-For", c.xff)
}
if got := s.clientIP(r); got != c.want {
t.Errorf("%s: clientIP = %q, want %q", name, got, c.want)
}
}
if _, err := ParseProxies([]string{"not an address"}); err == nil {
t.Error("a bad proxy address was accepted")
}
}
func TestAProxyOnTheSameMachineDoesNotExemptItsClients(t *testing.T) {
h, _ := limitedHandler(t, 2, "127.0.0.1")
for i := 0; i < 2; i++ {
hit(h, "/api/v1/nothing", "127.0.0.1:5000", "198.51.100.30")
}
if c := hit(h, "/api/v1/nothing", "127.0.0.1:5000", "198.51.100.30"); c != http.StatusTooManyRequests {
t.Fatalf("a forwarded client through a local proxy escaped the limit: %d", c)
}
// Without a trusted proxy the same request still must not be exempt.
h2, _ := limitedHandler(t, 2)
for i := 0; i < 2; i++ {
hit(h2, "/api/v1/nothing", "127.0.0.1:5000", "198.51.100.31")
}
if c := hit(h2, "/api/v1/nothing", "127.0.0.1:5000", "198.51.100.31"); c != http.StatusTooManyRequests {
t.Fatalf("forwarded requests from loopback were exempt: %d", c)
}
}