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
This commit is contained in:
2026-11-19 00:35:21 +01:00
co-authored by Claude Sonnet 5.5
parent 5ac02360c4
commit 3799faddcf
10 changed files with 296 additions and 17 deletions
+15
View File
@@ -14,6 +14,7 @@ import (
"fmt"
"io"
"net/http"
"net/netip"
"slices"
"strconv"
"strings"
@@ -47,6 +48,14 @@ type Config struct {
MessageDifficulty int
// PostsPerMinute limits envelopes accepted per client address; 0 means 30.
PostsPerMinute int
// RequestsPerMinute limits API requests of any kind per client address;
// 0 means 600, negative no limit. Requests from the node's own machine are
// exempt.
RequestsPerMinute int
// TrustedProxies are the reverse proxies in front of the node. Only a
// connection from one of them may name the client in X-Forwarded-For;
// without any, the limits see the proxy's address for every client.
TrustedProxies []netip.Prefix
// Inbox is the owner's conversations. Without it the owner endpoints are
// absent; relaying messages for buyers still works.
Inbox *inbox.Inbox
@@ -102,6 +111,9 @@ func New(cfg Config) http.Handler {
if cfg.PostsPerMinute <= 0 {
cfg.PostsPerMinute = defaultPostsPerMinute
}
if cfg.RequestsPerMinute == 0 {
cfg.RequestsPerMinute = defaultRequestsPerMinute
}
s := &server{Config: cfg, limiter: newLimiter(cfg.PostsPerMinute, time.Minute, cfg.Clock)}
mux := http.NewServeMux()
mux.HandleFunc("GET /api/v1/status", s.status)
@@ -144,6 +156,9 @@ func New(cfg Config) http.Handler {
mux.HandleFunc("DELETE /api/v1/signals/{author}/{id}", s.admin(s.dismissSignals))
mux.HandleFunc("POST /api/v1/reports", s.admin(s.postReport))
mux.Handle("GET /", s.ui())
if cfg.RequestsPerMinute > 0 {
return secure(s.rateLimited(mux))
}
return secure(mux)
}
+1 -13
View File
@@ -6,7 +6,6 @@ import (
"encoding/json"
"errors"
"io"
"net"
"net/http"
"strconv"
"strings"
@@ -30,7 +29,7 @@ const (
// encrypted envelope and polls its mailbox. The node sees only ciphertext.
func (s *server) postMessage(w http.ResponseWriter, r *http.Request) {
if !s.limiter.allow(clientIP(r)) {
if !s.limiter.allow(s.clientIP(r)) {
w.Header().Set("Retry-After", "60")
fail(w, http.StatusTooManyRequests, "too many messages from this address; try again in a minute")
return
@@ -570,17 +569,6 @@ func decodeBody(w http.ResponseWriter, r *http.Request, v any) bool {
return true
}
// clientIP is the peer address of the connection. Forwarding headers are not
// trusted: they are trivial to forge. Behind a reverse proxy every client then
// shares one allowance, which is the safe failure.
func clientIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}
// limiter allows each key a number of events per fixed window.
type limiter struct {
mu sync.Mutex
+98
View File
@@ -0,0 +1,98 @@
package api
import (
"net"
"net/http"
"net/netip"
"strings"
"time"
)
// defaultRequestsPerMinute is how many API requests one client address may
// make per minute. The browser UI makes a handful per page and polls a mailbox
// every few seconds, so this is far above honest use and far below a flood.
const defaultRequestsPerMinute = 600
// ParseProxies reads trusted proxy addresses or networks ("10.0.0.0/8",
// "203.0.113.5") for Config.TrustedProxies.
func ParseProxies(in []string) ([]netip.Prefix, error) {
var out []netip.Prefix
for _, s := range in {
s = strings.TrimSpace(s)
if p, err := netip.ParsePrefix(s); err == nil {
out = append(out, p.Masked())
continue
}
a, err := netip.ParseAddr(s)
if err != nil {
return nil, &net.ParseError{Type: "proxy address or network", Text: s}
}
out = append(out, netip.PrefixFrom(a, a.BitLen()))
}
return out, nil
}
func inPrefixes(a netip.Addr, ps []netip.Prefix) bool {
for _, p := range ps {
if p.Contains(a) {
return true
}
}
return false
}
// clientIP is the address a request really comes from. Without trusted proxies
// that is the peer address of the connection: forwarding headers are trivial to
// forge, so behind a reverse proxy every client then shares one allowance (the
// safe failure). When the connection comes from a trusted proxy, the client is
// the last address in X-Forwarded-For that is not itself a trusted proxy: each
// proxy appends the address it saw, so only the entries our own proxies added
// can be believed, and anything a client wrote sits to their left.
func (s *server) clientIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
peer, err := netip.ParseAddr(host)
if err != nil || len(s.TrustedProxies) == 0 || !inPrefixes(peer.Unmap(), s.TrustedProxies) {
return host
}
var hops []string
for _, v := range r.Header.Values("X-Forwarded-For") {
hops = append(hops, strings.Split(v, ",")...)
}
for i := len(hops) - 1; i >= 0; i-- {
a, err := netip.ParseAddr(strings.TrimSpace(hops[i]))
if err != nil {
return host // a header we cannot read is not believed
}
if !inPrefixes(a.Unmap(), s.TrustedProxies) {
return a.Unmap().String()
}
}
return host
}
// rateLimited refuses API requests from an address that makes too many. The
// UI's static files are not counted; a node's own machine is not limited, so
// the owner is never locked out of their own node.
func (s *server) rateLimited(next http.Handler) http.Handler {
l := newLimiter(s.RequestsPerMinute, time.Minute, s.Clock)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/") {
ip := s.clientIP(r)
// A request from this machine is exempt, unless a proxy on this
// machine passed it on (it then carries forwarding headers and
// really comes from elsewhere).
forwarded := r.Header.Get("X-Forwarded-For") != "" || r.Header.Get("Forwarded") != ""
if a, err := netip.ParseAddr(ip); err != nil || !a.IsLoopback() || forwarded {
if !l.allow(ip) {
w.Header().Set("Retry-After", "60")
fail(w, http.StatusTooManyRequests, "too many requests from this address; try again in a minute")
return
}
}
}
next.ServeHTTP(w, r)
})
}
+139
View File
@@ -0,0 +1,139 @@
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)
}
}
+1 -1
View File
@@ -58,7 +58,7 @@ type signalRequest struct {
// postSignal records a visitor's tip. Tips stay on this node: they hide
// nothing and are not gossiped; the operator reads them and may sign a report.
func (s *server) postSignal(w http.ResponseWriter, r *http.Request) {
if !s.limiter.allow(clientIP(r)) {
if !s.limiter.allow(s.clientIP(r)) {
w.Header().Set("Retry-After", "60")
fail(w, http.StatusTooManyRequests, "too many requests from this address; try again in a minute")
return