1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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();
}
}
|