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
+11
View File
@@ -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: &regionKeeper{node: node, dir: *data},
CertKeeper: &certKeeper{dev: dev, dir: *data, store: st, node: node, difficulty: *difficulty, clock: time.Now},