From 45bf16970867cc6f23738224dacf201905adcab6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?berislav=20grgi=C4=8Dak?= Date: Tue, 26 Mar 2024 10:26:11 +0100 Subject: [PATCH] Add rate limiting (#1142) Fixes #1123 ## What is this PR doing? It adds rate limiting to the logger API. ## What problem is it solving? Increases protection from spam requests. ## How is the problem addressed? By tracking the number of requests in `$_SESSION` and returning early if the limit was reached. ## Testing Instructions - Checkout this branch - Copy the `logger.php` file to a PHP local server or start a Docker server ``` cd packages/playground/website/public/ docker run -d -p 8787:80 --name playground-website -v "$PWD":/var/www/html php:8.0-apache ``` - Open the [API endpoint link](http://127.0.0.1:8787/logger.php) - Reload 5 times and confirm that the error message changed to _Too many requests_ **Known limitations** Because this is implemented using `$_SESSION` it can easily be worked around using `curl` or by removing session data. To improve rate limiting we would need support for storing request counts by IP on the server and there is currently no storage support except for files. --- packages/playground/website/public/logger.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/playground/website/public/logger.php b/packages/playground/website/public/logger.php index a2f259bfcf..ad80a97daa 100644 --- a/packages/playground/website/public/logger.php +++ b/packages/playground/website/public/logger.php @@ -4,6 +4,22 @@ header('Content-Type: application/json'); +/** + * Rate limit logger requests + */ +$max_requests_per_hour = 5; + +session_start(); +$rate_limit_key = md5('logger_requests_' . date('Y-m-d H')); +if (!isset($_SESSION[$rate_limit_key])) { + $_SESSION[$rate_limit_key] = 0; +} +$_SESSION[$rate_limit_key]++; + +if ($_SESSION[$rate_limit_key] > $max_requests_per_hour) { + response(false, 'Too many requests'); +} + $channel = getenv('SLACK_CHANNEL'); $token = getenv('SLACK_TOKEN');