2fas-server/internal/api/browser_extension/app/security/middleware.go

46 lines
1.2 KiB
Go
Raw Normal View History

2022-12-31 10:22:38 +01:00
package security
import (
"fmt"
2024-01-02 09:48:34 +01:00
"net/http"
"time"
2022-12-31 10:22:38 +01:00
"github.com/gin-gonic/gin"
2023-01-30 19:59:42 +01:00
"github.com/twofas/2fas-server/internal/common/logging"
"github.com/twofas/2fas-server/internal/common/rate_limit"
2022-12-31 10:22:38 +01:00
)
2024-01-02 09:48:34 +01:00
const defaultBrowserExtensionApiBandwidthAbuseThreshold = 100
2022-12-31 10:22:38 +01:00
2024-01-02 09:48:34 +01:00
func BrowserExtensionBandwidthAuditMiddleware(rateLimiter rate_limit.RateLimiter, rateLimitValue int) gin.HandlerFunc {
2022-12-31 10:22:38 +01:00
return func(c *gin.Context) {
extensionId := c.Param("extension_id")
if extensionId == "" {
return
}
key := fmt.Sprintf("security.api.browser_extension.bandwidth.%s", extensionId)
2024-01-02 09:48:34 +01:00
limitValue := rateLimitValue
if limitValue == 0 {
limitValue = defaultBrowserExtensionApiBandwidthAbuseThreshold
}
2022-12-31 10:22:38 +01:00
rate := rate_limit.Rate{
TimeUnit: time.Minute,
2024-01-02 09:48:34 +01:00
Limit: limitValue,
2022-12-31 10:22:38 +01:00
}
2024-01-02 09:48:34 +01:00
limitReached := rateLimiter.Test(c, key, rate)
2022-12-31 10:22:38 +01:00
if limitReached {
2024-03-16 19:05:21 +01:00
logging.FromContext(c.Request.Context()).WithFields(logging.Fields{
2022-12-31 10:22:38 +01:00
"type": "security",
"uri": c.Request.URL.String(),
"browser_extension_id": extensionId,
"ip": c.ClientIP(),
2024-01-02 09:48:34 +01:00
}).Warning("API potentially abused at Browser Extension scope, blocking")
c.AbortWithStatus(http.StatusTooManyRequests)
2022-12-31 10:22:38 +01:00
}
}
}