π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Rate limit event ingestion
Neeraj Gupta8c473e041ea2
diff --git a/server/pkg/middleware/event_test.go b/server/pkg/middleware/event_test.goindex 1eb580e486..92b3b0f9b5 100644--- a/server/pkg/middleware/event_test.go+++ b/server/pkg/middleware/event_test.go@@ -2,9 +2,12 @@ package middlewareimport ("net/http"+ "net/http/httptest""testing"+ "github.com/ente/museum/pkg/controller/discord"util "github.com/ente/museum/pkg/utils"+ "github.com/gin-gonic/gin""github.com/stretchr/testify/require")@@ -14,10 +17,43 @@ func TestShouldSkipBodyLogForEvents(t *testing.T) {require.False(t, shouldSkipBodyLog(http.MethodGet, "/events"))}-func TestEventsUseRouteRateLimit(t *testing.T) {- limit := util.NewRateLimiter("10-M")- rateLimiter := &RateLimitMiddleware{limit10ReqPerMin: limit}+func TestEventsUse120PerHourGlobalRateLimit(t *testing.T) {+ limit := util.NewRateLimiter("120-H")+ rateLimiter := &RateLimitMiddleware{limit120ReqPerHour: limit}- require.Same(t, limit, rateLimiter.getLimiter("/events", http.MethodPost))- require.Same(t, limit, rateLimiter.getLimiter("/events/user", http.MethodPost))+ require.Same(t, limit, rateLimiter.getGlobalLimiter("/events", http.MethodPost))+ require.Same(t, limit, rateLimiter.getGlobalLimiter("/events/user", http.MethodPost))+ require.Nil(t, rateLimiter.getLimiter("/events", http.MethodPost))+ require.Nil(t, rateLimiter.getLimiter("/events/user", http.MethodPost))+}++func TestEventsShareGlobalRateLimitAcrossPublicAndAuthenticatedRoutes(t *testing.T) {+ gin.SetMode(gin.TestMode)+ rateLimiter := &RateLimitMiddleware{+ limit120ReqPerHour: util.NewRateLimiter("1-H"),+ discordCtrl: discord.NewDiscordController(nil, "test", "test"),+ }+ router := gin.New()+ router.POST("/events", rateLimiter.APIRateLimitMiddleware(eventTestURLSanitizer), func(c *gin.Context) {+ c.Status(http.StatusNoContent)+ })+ router.POST("/events/user", rateLimiter.APIRateLimitForUserMiddleware(eventTestURLSanitizer), func(c *gin.Context) {+ c.Status(http.StatusNoContent)+ })++ require.Equal(t, http.StatusNoContent, performEventRequest(router, "/events", "198.51.100.1:1000", "1").Code)+ require.Equal(t, http.StatusTooManyRequests, performEventRequest(router, "/events/user", "198.51.100.2:1000", "2").Code)+}++func eventTestURLSanitizer(c *gin.Context) string {+ return c.Request.URL.Path+}++func performEventRequest(router *gin.Engine, path string, remoteAddr string, userID string) *httptest.ResponseRecorder {+ recorder := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodPost, path, nil)+ req.RemoteAddr = remoteAddr+ req.Header.Set("X-Auth-User-ID", userID)+ router.ServeHTTP(recorder, req)+ return recorder}diff --git a/server/pkg/middleware/rate_limit.go b/server/pkg/middleware/rate_limit.goindex 4ff088b717..bd9d3ad9b2 100644--- a/server/pkg/middleware/rate_limit.go+++ b/server/pkg/middleware/rate_limit.go@@ -19,31 +19,33 @@ import ()type RateLimitMiddleware struct {- count int64 // Use int64 for atomic operations- limit int64- reset time.Duration- ticker *time.Ticker- limit10ReqPerMin *limiter.Limiter- limit200ReqPerMin *limiter.Limiter- limit250ReqPerMin *limiter.Limiter- limit300ReqPerMin *limiter.Limiter- limit500ReqPerMin *limiter.Limiter- limit700ReqPerSec *limiter.Limiter- discordCtrl *discord.DiscordController+ count int64 // Use int64 for atomic operations+ limit int64+ reset time.Duration+ ticker *time.Ticker+ limit10ReqPerMin *limiter.Limiter+ limit120ReqPerHour *limiter.Limiter+ limit200ReqPerMin *limiter.Limiter+ limit250ReqPerMin *limiter.Limiter+ limit300ReqPerMin *limiter.Limiter+ limit500ReqPerMin *limiter.Limiter+ limit700ReqPerSec *limiter.Limiter+ discordCtrl *discord.DiscordController}func NewRateLimitMiddleware(discordCtrl *discord.DiscordController, limit int64, reset time.Duration) *RateLimitMiddleware {rl := &RateLimitMiddleware{- limit10ReqPerMin: util.NewRateLimiter("10-M"),- limit200ReqPerMin: util.NewRateLimiter("200-M"),- limit250ReqPerMin: util.NewRateLimiter("250-M"),- limit300ReqPerMin: util.NewRateLimiter("300-M"),- limit500ReqPerMin: util.NewRateLimiter("500-M"),- limit700ReqPerSec: util.NewRateLimiter("700-S"),- discordCtrl: discordCtrl,- limit: limit,- reset: reset,- ticker: time.NewTicker(reset),+ limit10ReqPerMin: util.NewRateLimiter("10-M"),+ limit120ReqPerHour: util.NewRateLimiter("120-H"),+ limit200ReqPerMin: util.NewRateLimiter("200-M"),+ limit250ReqPerMin: util.NewRateLimiter("250-M"),+ limit300ReqPerMin: util.NewRateLimiter("300-M"),+ limit500ReqPerMin: util.NewRateLimiter("500-M"),+ limit700ReqPerSec: util.NewRateLimiter("700-S"),+ discordCtrl: discordCtrl,+ limit: limit,+ reset: reset,+ ticker: time.NewTicker(reset),}go func() {for range rl.ticker.C {@@ -86,19 +88,8 @@ func (r *RateLimitMiddleware) APIRateLimitMiddleware(urlSanitizer func(_ *gin.Coreturn func(c *gin.Context) {requestPath := urlSanitizer(c)- globalRateLimiter := r.getGlobalLimiter(requestPath, c.Request.Method)- if globalRateLimiter != nil {- limitContext, err := globalRateLimiter.Get(c, requestPath)- if err != nil {- log.Error("Failed to check global rate limit", err)- c.Next() // assume that limit hasn't reached- return- }- if limitContext.Reached {- msg := fmt.Sprintf("π Global rate limit: %s", requestPath)- go r.discordCtrl.NotifyPotentialAbuse(msg)- log.Error(msg)- c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "Rate limit breached, try later"})+ if globalRateLimiter := r.getGlobalLimiter(requestPath, c.Request.Method); globalRateLimiter != nil {+ if r.isRateLimited(c, globalRateLimiter, globalRateLimitKey(requestPath), fmt.Sprintf("π Global rate limit: %s", requestPath)) {return}}@@ -106,16 +97,7 @@ func (r *RateLimitMiddleware) APIRateLimitMiddleware(urlSanitizer func(_ *gin.CorateLimiter := r.getLimiter(requestPath, c.Request.Method)if rateLimiter != nil {key := r.getRateLimitKey(c, requestPath)- limitContext, err := rateLimiter.Get(c, key)- if err != nil {- log.Error("Failed to check rate limit", err)- c.Next() // assume that limit hasn't reached- return- }- if limitContext.Reached {- go r.discordCtrl.NotifyPotentialAbuse(fmt.Sprintf("π IP rate limit: %s", requestPath))- log.Error(fmt.Sprintf("Rate limit breached %s", key))- c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "Rate limit breached, try later"})+ if r.isRateLimited(c, rateLimiter, key, fmt.Sprintf("π IP rate limit: %s", requestPath)) {return}}@@ -128,6 +110,12 @@ func (r *RateLimitMiddleware) APIRateLimitMiddleware(urlSanitizer func(_ *gin.Cofunc (r *RateLimitMiddleware) APIRateLimitForUserMiddleware(urlSanitizer func(_ *gin.Context) string) gin.HandlerFunc {return func(c *gin.Context) {requestPath := urlSanitizer(c)+ if globalRateLimiter := r.getGlobalLimiter(requestPath, c.Request.Method); globalRateLimiter != nil {+ if r.isRateLimited(c, globalRateLimiter, globalRateLimitKey(requestPath), fmt.Sprintf("π Global rate limit: %s", requestPath)) {+ return+ }+ }+rateLimiter := r.getLimiter(requestPath, c.Request.Method)if rateLimiter != nil {userID := auth.GetUserID(c.Request.Header)@@ -136,17 +124,7 @@ func (r *RateLimitMiddleware) APIRateLimitForUserMiddleware(urlSanitizer func(_log.Error("userID must be present in request header for applying rate-limit")return}- limitContext, err := rateLimiter.Get(c, fmt.Sprintf("%d-%s", userID, requestPath))- if err != nil {- log.Error("Failed to check rate limit", err)- c.Next() // assume that limit hasn't reached- return- }- if limitContext.Reached {- msg := fmt.Sprintf("π€ User rate limit: %s user=%d", requestPath, userID)- go r.discordCtrl.NotifyPotentialAbuse(msg)- log.Error(msg)- c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "Rate limit breached, try later"})+ if r.isRateLimited(c, rateLimiter, fmt.Sprintf("%d-%s", userID, requestPath), fmt.Sprintf("π€ User rate limit: %s user=%d", requestPath, userID)) {return}}@@ -154,16 +132,41 @@ func (r *RateLimitMiddleware) APIRateLimitForUserMiddleware(urlSanitizer func(_}}+func (r *RateLimitMiddleware) isRateLimited(c *gin.Context, rateLimiter *limiter.Limiter, key string, message string) bool {+ limitContext, err := rateLimiter.Get(c, key)+ if err != nil {+ log.Error("Failed to check rate limit", err)+ return false+ }+ if !limitContext.Reached {+ return false+ }+ go r.discordCtrl.NotifyPotentialAbuse(message)+ log.Error(fmt.Sprintf("Rate limit breached %s", key))+ c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "Rate limit breached, try later"})+ return true+}+// getGlobalLimiter, based on reqPath & reqMethod, returns a limiter that should// be applied globally for requests matching the route. It returns nil if no// global route-specific limit should be applied.func (r *RateLimitMiddleware) getGlobalLimiter(reqPath string, reqMethod string) *limiter.Limiter {+ if isEventURLPath(reqPath) {+ return r.limit120ReqPerHour+ }if reqPath == "/paste/create" || reqPath == "/paste/guard" || reqPath == "/paste/consume" {return r.limit300ReqPerMin}return nil}+func globalRateLimitKey(reqPath string) string {+ if isEventURLPath(reqPath) {+ return "/events"+ }+ return reqPath+}+func (r *RateLimitMiddleware) getRateLimitKey(c *gin.Context, reqPath string) string {if !isPublicCollectionUploadURLPath(reqPath) {return fmt.Sprintf("%s-%s", network.GetClientIP(c), reqPath)@@ -195,6 +198,11 @@ func isAuthenticatedUploadURLPath(reqPath string) bool {reqPath == "/files/multipart-upload-url"}+func isEventURLPath(reqPath string) bool {+ return reqPath == "/events" ||+ reqPath == "/events/user"+}+// getLimiter, based on reqPath & reqMethod, return instance of limiter.Limiter which needs to// be applied for a request. It returns nil if the request is not rate limitedfunc (r *RateLimitMiddleware) getLimiter(reqPath string, reqMethod string) *limiter.Limiter {@@ -217,8 +225,6 @@ func (r *RateLimitMiddleware) getLimiter(reqPath string, reqMethod string) *limireturn r.limit500ReqPerMin}if reqPath == "/users/ott" ||- reqPath == "/events" ||- reqPath == "/events/user" ||reqPath == "/users/verify-email" ||reqPath == "/users/change-email" ||reqPath == "/paste/create" ||