about summary refs log tree commit diff stats
path: root/classes/RateLimitMiddleware.php
diff options
context:
space:
mode:
Diffstat (limited to 'classes/RateLimitMiddleware.php')
-rw-r--r--classes/RateLimitMiddleware.php119
1 files changed, 119 insertions, 0 deletions
diff --git a/classes/RateLimitMiddleware.php b/classes/RateLimitMiddleware.php
new file mode 100644
index 0000000..564fc50
--- /dev/null
+++ b/classes/RateLimitMiddleware.php
@@ -0,0 +1,119 @@
+<?php
+
+class RateLimitMiddleware implements MiddlewareInterface
+{
+    /** @var list<string> */
+    private array $loginOps;
+
+    private int $maxAttempts;
+    private int $windowSeconds;
+    private int $lockoutBase;
+    private int $lockoutMax;
+    private string $ip;
+    private bool $enabled;
+
+    /**
+     * @param list<string> $loginOps  Operations to protect (default: ['perform-login'])
+     * @param int $maxAttempts        Max attempts within the window
+     * @param int $windowSeconds      Sliding window size in seconds
+     * @param int $lockoutBase        Initial lockout duration in seconds
+     * @param int $lockoutMax         Maximum lockout duration (cap) in seconds
+     */
+    public function __construct(
+        array $loginOps = ['perform-login'],
+        int $maxAttempts = 5,
+        int $windowSeconds = 300,
+        int $lockoutBase = 60,
+        int $lockoutMax = 1800
+    ) {
+        $this->loginOps       = $loginOps;
+        $this->maxAttempts    = $maxAttempts;
+        $this->windowSeconds  = $windowSeconds;
+        $this->lockoutBase    = $lockoutBase;
+        $this->lockoutMax     = $lockoutMax;
+        $this->ip             = $this->getClientIp();
+        $this->enabled        = $this->isApcuAvailable();
+    }
+
+    public function process(Request $request, callable $next): Response
+    {
+        $op = $request->getString('op', '');
+
+        // Only apply to login endpoints
+        if (!in_array($op, $this->loginOps, true)) {
+            return $next($request);
+        }
+
+        // Graceful degradation — never block legitimate users
+        if (!$this->enabled) {
+            return $next($request);
+        }
+
+        // Check for active lockout
+        $lockKey    = "epube_rl_lock_{$this->ip}";
+        $remaining  = apcu_fetch($lockKey, $lockSuccess);
+        if ($lockSuccess && is_int($remaining) && $remaining > 0) {
+            return $this->lockedOutResponse($remaining);
+        }
+        if ($lockSuccess) {
+            apcu_delete($lockKey);
+        }
+
+        // Check sliding window of attempts
+        $windowKey = "epube_rl_win_{$this->ip}";
+        $now       = time();
+        $cutoff    = $now - $this->windowSeconds;
+
+        $attempts = apcu_fetch($windowKey, $winSuccess);
+        if (!$winSuccess || !is_array($attempts)) {
+            $attempts = [];
+        }
+
+        // Prune expired entries
+        $attempts = array_values(array_filter(
+            $attempts,
+            static fn($t): bool => is_int($t) && $t > $cutoff
+        ));
+
+        if (count($attempts) >= $this->maxAttempts) {
+            $excess      = count($attempts) - $this->maxAttempts;
+            $lockoutDur  = min(
+                $this->lockoutBase * pow(2, $excess),
+                $this->lockoutMax
+            );
+            apcu_store($lockKey, $lockoutDur, $lockoutDur);
+            return $this->lockedOutResponse($lockoutDur);
+        }
+
+        // Record this attempt
+        $attempts[] = $now;
+        apcu_store($windowKey, $attempts, $this->windowSeconds);
+
+        return $next($request);
+    }
+
+    private function lockedOutResponse(int $remaining): Response
+    {
+        return (new Response())
+            ->withStatus(429)
+            ->withHeader('Retry-After', (string) $remaining)
+            ->withBody(json_encode([
+                'error' => "Too many login attempts. Try again in {$remaining}s.",
+            ]));
+    }
+
+    private function getClientIp(): string
+    {
+        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
+            $ips = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
+            return $ips[0];
+        }
+
+        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
+    }
+
+    private function isApcuAvailable(): bool
+    {
+        return function_exists('apcu_enabled') && apcu_enabled();
+    }
+}