Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.03% covered (success)
91.03%
71 / 78
77.78% covered (warning)
77.78%
7 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
RateLimitingMiddleware
91.03% covered (success)
91.03%
71 / 78
77.78% covered (warning)
77.78%
7 / 9
21.32
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 process
83.33% covered (warning)
83.33%
25 / 30
0.00% covered (danger)
0.00%
0 / 1
7.23
 checkAndIncrementLimit
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
4
 getCurrentRequestCount
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getResetTime
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 createRateLimitResponse
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 acquireLock
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 releaseLock
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isLocked
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3declare(strict_types=1);
4
5namespace BO\Zmscitizenapi\Middleware;
6
7use BO\Zmscitizenapi\Helper\ClientIpHelper;
8use BO\Zmscitizenapi\Localization\ErrorMessages;
9use BO\Zmscitizenapi\Services\Core\LoggerService;
10use Psr\Http\Message\ResponseInterface;
11use Psr\Http\Message\ServerRequestInterface;
12use Psr\Http\Server\MiddlewareInterface;
13use Psr\Http\Server\RequestHandlerInterface;
14use Psr\SimpleCache\CacheInterface;
15
16class RateLimitingMiddleware implements MiddlewareInterface
17{
18    private const ERROR_RATE_LIMIT = 'rateLimitExceeded';
19    private int $maxRequests;
20    private int $cacheExpiry;
21    private int $maxRetries;
22    private int $backoffMin;
23    private int $backoffMax;
24    private int $lockTimeout;
25    private CacheInterface $cache;
26    private LoggerService $logger;
27    public function __construct(CacheInterface $cache, LoggerService $logger)
28    {
29        $this->cache = $cache;
30        $this->logger = $logger;
31        $config = \App::getRateLimit();
32        $this->maxRequests = $config['maxRequests'];
33        $this->cacheExpiry = $config['cacheExpiry'];
34        $this->maxRetries = $config['maxRetries'];
35        $this->backoffMin = $config['backoffMin'];
36        $this->backoffMax = $config['backoffMax'];
37        $this->lockTimeout = $config['lockTimeout'];
38    }
39
40    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
41    {
42        try {
43            $ip = ClientIpHelper::getClientIp();
44            $key = 'rate_limit_' . md5($ip);
45            $lockKey = $key . '_lock';
46// Try to acquire rate limit with retries and exponential backoff
47            $attempt = 0;
48            $limited = false;
49            while ($attempt < $this->maxRetries) {
50                try {
51                    if ($this->acquireLock($lockKey)) {
52                        try {
53                            $limited = $this->checkAndIncrementLimit($key);
54                            break;
55                        } finally {
56                            $this->releaseLock($lockKey);
57                        }
58                    }
59                } catch (\Throwable $e) {
60                    $this->logger->logError($e, $request);
61                }
62
63                $attempt++;
64                if ($attempt < $this->maxRetries) {
65                // Exponential backoff with jitter
66                            $backoffMs = min($this->backoffMax, (int)($this->backoffMin * min(pow(2, $attempt), PHP_INT_MAX / $this->backoffMin)));
67                    $jitterMs = random_int(0, (int)($backoffMs * 0.1));
68                    $sleepMs = $backoffMs + $jitterMs;
69                    usleep($sleepMs * 1000);
70                // Convert to microseconds
71                }
72            }
73
74            if ($limited) {
75                $this->logger->logInfo(sprintf('Rate limit exceeded for IP %s. URI: %s', $ip, $request->getUri()));
76                return $this->createRateLimitResponse($request);
77            }
78
79            $response = $handler->handle($request);
80// Subtract one extra to account for the current request
81            $remaining = max(0, $this->maxRequests - $this->getCurrentRequestCount($key) - 1);
82            return $response
83                ->withHeader('X-RateLimit-Limit', (string)$this->maxRequests)
84                ->withHeader('X-RateLimit-Remaining', (string)max(0, $remaining))
85                ->withHeader('X-RateLimit-Reset', (string)$this->getResetTime($key));
86        } catch (\Throwable $e) {
87            $this->logger->logError($e, $request);
88            throw $e;
89        }
90    }
91
92    private function checkAndIncrementLimit(string $key): bool
93    {
94        $requestData = $this->cache->get($key);
95        if ($requestData === null) {
96        // First request
97            $this->cache->set($key, [
98                'count' => 1,
99                'timestamp' => time()
100            ], $this->cacheExpiry);
101            return false;
102        }
103
104        if (!is_array($requestData)) {
105// Handle corrupted data
106            $this->cache->delete($key);
107            return false;
108        }
109
110        $count = (int)($requestData['count'] ?? 0);
111        if ($count >= $this->maxRequests) {
112            return true;
113        }
114
115        // Update the counter atomically
116        $requestData['count'] = $count + 1;
117        $requestData['timestamp'] = time();
118        $this->cache->set($key, $requestData, $this->cacheExpiry);
119        return false;
120    }
121
122    private function getCurrentRequestCount(string $key): int
123    {
124        $requestData = $this->cache->get($key);
125        if (!is_array($requestData)) {
126            return 0;
127        }
128        return (int)($requestData['count'] ?? 0);
129    }
130
131    private function getResetTime(string $key): int
132    {
133        $requestData = $this->cache->get($key);
134        if (!is_array($requestData)) {
135            return time() + $this->cacheExpiry;
136        }
137        return (int)($requestData['timestamp'] ?? time()) + $this->cacheExpiry;
138    }
139
140    private function createRateLimitResponse($request): ResponseInterface
141    {
142        $response = \App::$slim->getResponseFactory()->createResponse();
143        $language = $request->getAttribute('language');
144        $response = $response->withStatus(ErrorMessages::get(self::ERROR_RATE_LIMIT, $language)['statusCode'])
145            ->withHeader('Content-Type', 'application/json');
146        $response->getBody()->write(json_encode([
147            'errors' => [ErrorMessages::get(self::ERROR_RATE_LIMIT, $language)]
148        ]));
149        return $response;
150    }
151
152    private function acquireLock(string $lockKey): bool
153    {
154        // Try to acquire lock by setting it only if it doesn't exist
155        if (!$this->cache->has($lockKey)) {
156            return $this->cache->set($lockKey, true, $this->lockTimeout);
157        }
158        return false;
159    }
160
161    private function releaseLock(string $lockKey): void
162    {
163        $this->cache->delete($lockKey);
164    }
165
166    /**
167     * For testing purposes - allows checking if a lock exists
168     */
169    public function isLocked(string $ip): bool
170    {
171        $lockKey = 'rate_limit_' . md5($ip) . '_lock';
172        return $this->cache->has($lockKey);
173    }
174}