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:
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user