ratelimit.go (2360B)
1 // GoToSocial 2 // Copyright (C) GoToSocial Authors admin@gotosocial.org 3 // SPDX-License-Identifier: AGPL-3.0-or-later 4 // 5 // This program is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Affero General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Affero General Public License for more details. 14 // 15 // You should have received a copy of the GNU Affero General Public License 16 // along with this program. If not, see <http://www.gnu.org/licenses/>. 17 18 package middleware 19 20 import ( 21 "net" 22 "net/http" 23 "time" 24 25 "github.com/gin-gonic/gin" 26 "github.com/ulule/limiter/v3" 27 limitergin "github.com/ulule/limiter/v3/drivers/middleware/gin" 28 "github.com/ulule/limiter/v3/drivers/store/memory" 29 ) 30 31 const rateLimitPeriod = 5 * time.Minute 32 33 // RateLimit returns a gin middleware that will automatically rate limit caller (by IP address), 34 // and enrich the response header with the following headers: 35 // 36 // - `x-ratelimit-limit` - maximum number of requests allowed per time period (fixed). 37 // - `x-ratelimit-remaining` - number of remaining requests that can still be performed. 38 // - `x-ratelimit-reset` - unix timestamp when the rate limit will reset. 39 // 40 // If `x-ratelimit-limit` is exceeded, the request is aborted and an HTTP 429 TooManyRequests 41 // status is returned. 42 // 43 // If the config AdvancedRateLimitRequests value is <= 0, then a noop handler will be returned, 44 // which performs no rate limiting. 45 func RateLimit(limit int) gin.HandlerFunc { 46 if limit <= 0 { 47 // use noop middleware if ratelimiting is disabled 48 return func(ctx *gin.Context) {} 49 } 50 51 limiter := limiter.New( 52 memory.NewStore(), 53 limiter.Rate{Period: rateLimitPeriod, Limit: int64(limit)}, 54 limiter.WithIPv6Mask(net.CIDRMask(64, 128)), // apply /64 mask to IPv6 addresses 55 ) 56 57 // use custom rate limit reached error 58 handler := func(c *gin.Context) { 59 c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "rate limit reached"}) 60 } 61 62 return limitergin.NewMiddleware( 63 limiter, 64 limitergin.WithLimitReachedHandler(handler), 65 ) 66 }