Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.91% covered (success)
90.91%
70 / 77
77.78% covered (warning)
77.78%
7 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
RateLimitingMiddleware
90.91% covered (success)
90.91%
70 / 77
77.78% covered (warning)
77.78%
7 / 9
21.33
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%
7 / 7
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\Utils\ClientIpHelper;
8use BO\Zmscitizenapi\Utils\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    #[\Override]
41    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
42    {
43        try {
44            $ip = ClientIpHelper::getClientIp();
45            $key = 'rate_limit_' . md5($ip);
46            $lockKey = $key . '_lock';
47// Try to acquire rate limit with retries and exponential backoff
48            $attempt = 0;
49            $limited = false;
50            while ($attempt < $this->maxRetries) {
51                try {
52                    if ($this->acquireLock($lockKey)) {
53                        try {
54                            $limited = $this->checkAndIncrementLimit($key);
55                            break;
56                        } finally {
57                            $this->releaseLock($lockKey);
58                        }
59                    }
60                } catch (\Throwable $e) {
61                    $this->logger->logError($e, $request);
62                }
63
64                $attempt++;
65                if ($attempt < $this->maxRetries) {
66                // Exponential backoff with jitter
67                            $backoffMs = min($this->backoffMax, (int)($this->backoffMin * min(pow(2, $attempt), PHP_INT_MAX / $this->backoffMin)));
68                    $jitterMs = random_int(0, (int)($backoffMs * 0.1));
69                    $sleepMs = $backoffMs + $jitterMs;
70                    usleep($sleepMs * 1000);
71                // Convert to microseconds
72                }
73            }
74
75            if ($limited) {
76                $this->logger->logInfo(sprintf('Rate limit exceeded for IP %s. URI: %s', $ip, $request->getUri()));
77                return $this->createRateLimitResponse();
78            }
79
80            $response = $handler->handle($request);
81// Subtract one extra to account for the current request
82            $remaining = max(0, $this->maxRequests - $this->getCurrentRequestCount($key) - 1);
83            return $response
84                ->withHeader('X-RateLimit-Limit', (string)$this->maxRequests)
85                ->withHeader('X-RateLimit-Remaining', (string)max(0, $remaining))
86                ->withHeader('X-RateLimit-Reset', (string)$this->getResetTime($key));
87        } catch (\Throwable $e) {
88            $this->logger->logError($e, $request);
89            throw $e;
90        }
91    }
92
93    private function checkAndIncrementLimit(string $key): bool
94    {
95        $requestData = $this->cache->get($key);
96        if ($requestData === null) {
97        // First request
98            $this->cache->set($key, [
99                'count' => 1,
100                'timestamp' => time()
101            ], $this->cacheExpiry);
102            return false;
103        }
104
105        if (!is_array($requestData)) {
106// Handle corrupted data
107            $this->cache->delete($key);
108            return false;
109        }
110
111        $count = (int)($requestData['count'] ?? 0);
112        if ($count >= $this->maxRequests) {
113            return true;
114        }
115
116        // Update the counter atomically
117        $requestData['count'] = $count + 1;
118        $requestData['timestamp'] = time();
119        $this->cache->set($key, $requestData, $this->cacheExpiry);
120        return false;
121    }
122
123    private function getCurrentRequestCount(string $key): int
124    {
125        $requestData = $this->cache->get($key);
126        if (!is_array($requestData)) {
127            return 0;
128        }
129        return (int)($requestData['count'] ?? 0);
130    }
131
132    private function getResetTime(string $key): int
133    {
134        $requestData = $this->cache->get($key);
135        if (!is_array($requestData)) {
136            return time() + $this->cacheExpiry;
137        }
138        return (int)($requestData['timestamp'] ?? time()) + $this->cacheExpiry;
139    }
140
141    private function createRateLimitResponse(): ResponseInterface
142    {
143        $response = \App::$slim->getResponseFactory()->createResponse();
144        $response = $response->withStatus(ErrorMessages::get(self::ERROR_RATE_LIMIT)['statusCode'])
145            ->withHeader('Content-Type', 'application/json');
146        $response->getBody()->write(json_encode([
147            'errors' => [ErrorMessages::get(self::ERROR_RATE_LIMIT)]
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}