diff --git a/README.md b/README.md index ce8883d..04eb12e 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,13 @@ than once, is refused with 400. - ``: one of `orig`, `png`, `jpeg`, `webp` - ``: `orig` or `x` (e.g. `800x600`) +The login form (`POST /`) is limited to 5 attempts per minute per client +address, counting an IPv6 client by its /64; an attempt over the limit is +refused with 429 and a `Retry-After` header. Behind a reverse proxy the client +address comes from `X-Forwarded-For` only when the proxy's address is in +`trusted_proxies`; otherwise all users behind the proxy are counted as one +client. + ### Source Hosts Source hosts may be allowlisted in the configuration. Non-allowlisted diff --git a/TODO.md b/TODO.md index 672d6d1..d4ed1ed 100644 --- a/TODO.md +++ b/TODO.md @@ -30,6 +30,14 @@ exhaustion # Completed Steps +- 2026-09-28 rate limit the login form (closes #66): `POST /` is limited to 5 + attempts per minute per client address, and an attempt over the limit is + refused with 429 and a `Retry-After` header; the address is the one + `internal/clientip` resolves through `trusted_proxies`, and an IPv6 client is + counted by its /64; the limit is a `RateLimit` middleware in + `internal/middleware` on `github.com/go-chi/httprate`, which the image routes + can reuse; the library keeps counts for the current and the previous minute + only; documented in `README.md`. - 2026-09-28 refuse an unparseable `exp` on `/v1/image/` and log swallowed cache errors (closes #72): an `exp` in the URL that is not a whole number, an empty `exp=` included, is a 400 naming `exp` and the value, @@ -245,7 +253,7 @@ exhaustion - P1: strip EXIF and other metadata from processed images (privacy) - P2: security - referer blacklist - - per-IP rate limiting + - per-IP rate limiting on the image routes - per-origin rate limiting - P2: HTTP response handling - Last-Modified headers diff --git a/go.mod b/go.mod index f3648e0..f5c4c98 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/getsentry/sentry-go v0.40.0 github.com/go-chi/chi/v5 v5.2.3 github.com/go-chi/cors v1.2.2 + github.com/go-chi/httprate v0.16.0 github.com/gorilla/csrf v1.7.3 github.com/gorilla/securecookie v1.1.2 github.com/prometheus/client_golang v1.23.2 @@ -91,6 +92,7 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.10 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect @@ -113,6 +115,7 @@ require ( github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.0 // indirect github.com/x448/float16 v0.8.4 // indirect + github.com/zeebo/xxh3 v1.0.2 // indirect go.etcd.io/etcd/api/v3 v3.6.2 // indirect go.etcd.io/etcd/client/pkg/v3 v3.6.2 // indirect go.etcd.io/etcd/client/v3 v3.6.2 // indirect diff --git a/go.sum b/go.sum index af3e229..f9a4f3d 100644 --- a/go.sum +++ b/go.sum @@ -114,6 +114,8 @@ github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE= github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops= github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE= github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58= +github.com/go-chi/httprate v0.16.0 h1:8V5DH9j6pSK6UQoBsTpvMyFxycqaKEIToyPKzHJjUa8= +github.com/go-chi/httprate v0.16.0/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-jose/go-jose/v4 v4.0.5 h1:M6T8+mKZl/+fNNuFHvGIzDz7BTLQPIounk/b9dw3AaE= @@ -251,6 +253,8 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= +github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= @@ -396,6 +400,10 @@ github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcY github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= +github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= +github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= go.etcd.io/etcd/api/v3 v3.6.2 h1:25aCkIMjUmiiOtnBIp6PhNj4KdcURuBak0hU2P1fgRc= go.etcd.io/etcd/api/v3 v3.6.2/go.mod h1:eFhhvfR8Px1P6SEuLT600v+vrhdDTdcfMzmnxVXXSbk= go.etcd.io/etcd/client/pkg/v3 v3.6.2 h1:zw+HRghi/G8fKpgKdOcEKpnBTE4OO39T6MegA0RopVU= diff --git a/internal/middleware/middleware.go b/internal/middleware/middleware.go index 916e3c8..95a83e8 100644 --- a/internal/middleware/middleware.go +++ b/internal/middleware/middleware.go @@ -9,6 +9,7 @@ import ( basicauth "github.com/99designs/basicauth-go" "github.com/go-chi/chi/v5/middleware" "github.com/go-chi/cors" + "github.com/go-chi/httprate" metrics "github.com/slok/go-http-metrics/metrics/prometheus" ghmm "github.com/slok/go-http-metrics/middleware" "github.com/slok/go-http-metrics/middleware/std" @@ -88,6 +89,22 @@ func (s *Middleware) ClientIP() func(http.Handler) http.Handler { } } +// RateLimit returns a middleware that limits each client to requestLimit +// requests per window and refuses a request over the limit with 429 Too Many +// Requests and a Retry-After header. Clients are told apart by the address +// the ClientIP middleware stored in the request context, so ClientIP must +// run first. An IPv6 client is counted by its /64, which one client usually +// holds whole. Counts are kept only for the current and the previous +// window, so memory stays bounded. +func (s *Middleware) RateLimit( + requestLimit int, window time.Duration, +) func(http.Handler) http.Handler { + return httprate.LimitBy(requestLimit, window, + func(r *http.Request) (string, error) { + return httprate.CanonicalizeIP(clientip.FromContext(r.Context())), nil + }) +} + type loggingResponseWriter struct { http.ResponseWriter diff --git a/internal/server/routes.go b/internal/server/routes.go index 8e41fd7..0bb2748 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -2,6 +2,7 @@ package server import ( "net/http" + "time" sentryhttp "github.com/getsentry/sentry-go/http" "github.com/go-chi/chi/v5" @@ -12,6 +13,10 @@ import ( "sneak.berlin/go/pixa/internal/static" ) +// LoginAttemptsPerMinute is how many login attempts (POST /) one client may +// make per minute; the next is refused with 429 Too Many Requests. +const LoginAttemptsPerMinute = 5 + // SetupRoutes configures all HTTP routes. func (s *Server) SetupRoutes() { s.router = chi.NewRouter() @@ -50,11 +55,14 @@ func (s *Server) SetupRoutes() { // token cookie is independent of the session cookie, so it also // covers the login POST, where no session exists yet. LimitBody caps // the POST body ahead of CSRF, which reads its token from that body. + // The login POST is rate limited per client after both, so every + // attempt that reaches the signing key comparison is counted. s.router.Group(func(r chi.Router) { r.Use(s.h.LimitBody(handlers.MaxFormBytes)) r.Use(s.h.CSRF()) r.Get("/", s.h.HandleRoot()) - r.Post("/", s.h.HandleRoot()) + r.With(s.mw.RateLimit(LoginAttemptsPerMinute, time.Minute)). + Post("/", s.h.HandleRoot()) r.Post("/generate", s.h.HandleGenerateURL()) })