From 3799faddcf805ca7b3e80b07b5e58dbe67103525 Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Thu, 19 Nov 2026 00:35:21 +0100 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw --- SPECS.md | 5 +- cmd/allmende/run.go | 11 +++ docs/PROTOCOL.md | 15 +++- internal/api/api.go | 15 ++++ internal/api/messages.go | 14 +--- internal/api/ratelimit.go | 98 +++++++++++++++++++++++ internal/api/ratelimit_test.go | 139 +++++++++++++++++++++++++++++++++ internal/api/reports.go | 2 +- k8s/base/config.env | 9 +++ k8s/base/statefulset.yaml | 5 ++ 10 files changed, 296 insertions(+), 17 deletions(-) create mode 100644 internal/api/ratelimit.go create mode 100644 internal/api/ratelimit_test.go diff --git a/SPECS.md b/SPECS.md index 74344b5..ec5be96 100644 --- a/SPECS.md +++ b/SPECS.md @@ -151,8 +151,9 @@ starting a design-heavy item; see "Working with the owner". relaying over 1200 messages a minute and bans one that sends 20 invalid ones for an hour, limits sync streams (4 at once, 1500 a minute), keeps at most 100 listings per author (`--max-per-author`) and 16 inbound connections per - public IP (`--max-conns-per-ip`). Not covered: a rate limit on the HTTP API, - attackers with many addresses, sharing bans between nodes (deliberately). + public IP (`--max-conns-per-ip`), and 600 API requests a minute per client + address (`--requests-per-minute`, `--trusted-proxy`). Not covered: attackers + with many addresses, sharing bans between nodes (deliberately). - **Joining without the seeds.** A newcomer whose remembered peers are all in another region cannot find its region when no DHT server is up (sim: 0 of 114 listings). Remember region peers separately, or ask connected peers. diff --git a/cmd/allmende/run.go b/cmd/allmende/run.go index 219abd2..c5c4b9f 100644 --- a/cmd/allmende/run.go +++ b/cmd/allmende/run.go @@ -71,7 +71,16 @@ func cmdRun(args []string) error { "most unexpired listings this node keeps for one author; more are neither stored nor passed on (-1: no limit)") maxConnsPerIP := fs.Int("max-conns-per-ip", p2p.DefaultConnsPerIP, "inbound connections accepted from one public IP address (IPv6: one /64); local and private addresses are exempt (-1: no limit)") + requestsPerMinute := fs.Int("requests-per-minute", 0, + "API requests one client address may make per minute (0: 600; -1: no limit); the node's own machine is exempt") + var trustedProxies listFlag + fs.Var(&trustedProxies, "trusted-proxy", + "address or network (10.0.0.0/8) of a reverse proxy in front of the HTTP API, whose X-Forwarded-For names the real client; repeatable. Without one, every client behind a proxy shares one allowance") fs.Parse(args) + proxies, err := api.ParseProxies(trustedProxies) + if err != nil { + return fmt.Errorf("--trusted-proxy: %w", err) + } for _, k := range trustReporters { if !validKey(k) { return fmt.Errorf("--trust-reporter %q: want an identity key of 64 hex characters (the \"author\" in a node's /api/v1/status)", k) @@ -187,6 +196,8 @@ func cmdRun(args []string) error { handler := api.New(api.Config{ Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty, MessageDifficulty: *msgDifficulty, + RequestsPerMinute: *requestsPerMinute, + TrustedProxies: proxies, Inbox: in, RegionKeeper: ®ionKeeper{node: node, dir: *data}, CertKeeper: &certKeeper{dev: dev, dir: *data, store: st, node: node, difficulty: *difficulty, clock: time.Now}, diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 0bff770..6415221 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -719,8 +719,21 @@ Findings (see "What is left" in SPECS.md for the open ones): Behind a Kubernetes service the real source address is only visible with `externalTrafficPolicy: Local` (the base manifest has it; the nodeport overlay uses `Cluster`, which hides it, so the limit does nothing there). + - **HTTP API:** at most 600 `/api/` requests a minute per client address + (`--requests-per-minute`, -1 for no limit), answered with 429 and + `Retry-After`; the UI's static files are not counted, and requests from the + node's own machine are exempt so the owner is never locked out. On top of + that, posting messages and tips keep their own, much lower limit (30 a + minute). Behind a reverse proxy the client is read from `X-Forwarded-For` + only when the connection comes from a `--trusted-proxy` (address or + network, repeatable), and then it is the last entry that is not itself a + trusted proxy, so what a client writes itself is never believed. Without a + trusted proxy every client behind the proxy shares one allowance; the + manifest sets `TRUSTED_PROXY` to the private ranges for that reason. A + request carrying forwarding headers is never treated as local, so a proxy + on the node's machine does not exempt its clients. Bans are per node and not shared (a shared ban would let one node get - honest ones banned); the HTTP API still has no limits. + honest ones banned). 3. **The DHT is only as good as its servers.** Only publicly reachable nodes serve it. With every seed gone, a newcomer whose remembered peers are all in another region found nobody (0 of 114 listings), and one that remembers no diff --git a/internal/api/api.go b/internal/api/api.go index 5079d4a..9a10529 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -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) } diff --git a/internal/api/messages.go b/internal/api/messages.go index c64b3f2..ce663a8 100644 --- a/internal/api/messages.go +++ b/internal/api/messages.go @@ -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 diff --git a/internal/api/ratelimit.go b/internal/api/ratelimit.go new file mode 100644 index 0000000..fab5190 --- /dev/null +++ b/internal/api/ratelimit.go @@ -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) + }) +} diff --git a/internal/api/ratelimit_test.go b/internal/api/ratelimit_test.go new file mode 100644 index 0000000..6caed19 --- /dev/null +++ b/internal/api/ratelimit_test.go @@ -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) + } +} diff --git a/internal/api/reports.go b/internal/api/reports.go index 68b2d12..7d2cb60 100644 --- a/internal/api/reports.go +++ b/internal/api/reports.go @@ -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 diff --git a/k8s/base/config.env b/k8s/base/config.env index 0f3868a..1061ca2 100644 --- a/k8s/base/config.env +++ b/k8s/base/config.env @@ -22,3 +22,12 @@ REGION= # The default of the binary is 24; it is written here so it is visible, and so # a later change of the network's value is one edit in one place. DIFFICULTY=24 + +# The reverse proxies in front of the web UI and API (your ingress controller), +# comma separated addresses or networks. Only a connection from one of them may +# say who the real client is (X-Forwarded-For); the node then limits requests +# per real client (600 a minute) instead of counting the whole site as one +# client. These are the private ranges, which covers the pod networks of k3s +# (10.42.0.0/16), most CNIs and a Traefik on the same cluster. Empty: every +# visitor shares one allowance, which throttles the site as a whole. +TRUSTED_PROXY=10.0.0.0/8,172.16.0.0/12,192.168.0.0/16 diff --git a/k8s/base/statefulset.yaml b/k8s/base/statefulset.yaml index 94edf00..ba6ab44 100644 --- a/k8s/base/statefulset.yaml +++ b/k8s/base/statefulset.yaml @@ -61,6 +61,11 @@ spec: for r in ${REGION}; do set -- "$@" --region "$r"; done unset IFS; set +f fi + if [ -n "${TRUSTED_PROXY}" ]; then + set -f; IFS=, + for p in ${TRUSTED_PROXY}; do set -- "$@" --trusted-proxy "$p"; done + unset IFS; set +f + fi exec allmende run "$@" envFrom: - configMapRef: