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

52 lines
1.3 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"
"strings"
"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 defaultMobileApiBandwidthAbuseThreshold = 100
2022-12-31 10:22:38 +01:00
2024-01-02 09:48:34 +01:00
func MobileIpAbuseAuditMiddleware(rateLimiter rate_limit.RateLimiter, rateLimitValue int) gin.HandlerFunc {
2022-12-31 10:22:38 +01:00
return func(c *gin.Context) {
deviceId := c.Param("device_id")
extensionId := c.Param("extension_id")
if deviceId == "" && extensionId == "" {
return
}
key := strings.TrimSuffix(
fmt.Sprintf("security.api.mobile.bandwidth.%s.%s", deviceId, extensionId),
".",
)
2024-01-02 09:48:34 +01:00
limitValue := rateLimitValue
if limitValue == 0 {
limitValue = defaultMobileApiBandwidthAbuseThreshold
}
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 {
logging.WithFields(logging.Fields{
"type": "security",
"uri": c.Request.URL.String(),
"device_id": deviceId,
"browser_extension_id": extensionId,
"ip": c.ClientIP(),
2024-01-02 09:48:34 +01:00
}).Warning("API potentially abused at mobile scope, blocking")
c.AbortWithStatus(http.StatusTooManyRequests)
2022-12-31 10:22:38 +01:00
}
}
}