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
+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