about summary refs log tree commit diff stats
path: root/classes/RateLimitMiddleware.php
diff options
context:
space:
mode:
authorfox <fox@fakecake.org>2026-06-21 14:51:01 +0300
committerfox <fox@fakecake.org>2026-06-21 14:51:01 +0300
commit8e569855249dda7a17402e5ae20044e8149d992e (patch)
tree6a6acc9a378e2402d048a02e47b5ab99dc5247e2 /classes/RateLimitMiddleware.php
parent23ca9695d1b38c7a27cf132d517a6ed6b19f607a (diff)
parent17296a2ef8fa2658dca471285bce40ee67469179 (diff)
downloadthe-epube-8e569855249dda7a17402e5ae20044e8149d992e.tar.gz
the-epube-8e569855249dda7a17402e5ae20044e8149d992e.tar.xz
Merge branch 'dev' into 'master'
rework login throttling to use database field check instead of APCu

See merge request git/the-epube!64
Diffstat (limited to 'classes/RateLimitMiddleware.php')
-rw-r--r--classes/RateLimitMiddleware.php119
1 files changed, 0 insertions, 119 deletions
diff --git a/classes/RateLimitMiddleware.php b/classes/RateLimitMiddleware.php
deleted file mode 100644
index 564fc50..0000000
--- a/classes/RateLimitMiddleware.php
+++ /dev/null
@@ -1,119 +0,0 @@
-<?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();
-    }
-}