diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-06-21 14:37:09 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-06-21 14:37:09 +0300 |
| commit | 5a2b451afb7a5c794b5da19dd22b4ba40c256b03 (patch) | |
| tree | 7e2ae0bf2a8cd88ccc70fefdee2d4c3c288e9a92 | |
| parent | 1215afa6ef28a6e0a53aab98263e922b7c66a580 (diff) | |
| download | the-epube-5a2b451afb7a5c794b5da19dd22b4ba40c256b03.tar.gz the-epube-5a2b451afb7a5c794b5da19dd22b4ba40c256b03.tar.xz | |
rework login throttling to use database field check instead of APCu
| -rw-r--r-- | backend.php | 1 | ||||
| -rw-r--r-- | classes/Handler/LoginHandler.php | 67 | ||||
| -rw-r--r-- | classes/RateLimitMiddleware.php | 119 | ||||
| -rw-r--r-- | sql/pgsql/migrations/3.sql | 2 | ||||
| -rw-r--r-- | sql/pgsql/schema.sql | 3 | ||||
| -rw-r--r-- | sql/sqlite/migrations/3.sql | 2 | ||||
| -rw-r--r-- | sql/sqlite/schema.sql | 3 |
7 files changed, 67 insertions, 130 deletions
diff --git a/backend.php b/backend.php index 2c43dad..07405de 100644 --- a/backend.php +++ b/backend.php @@ -13,7 +13,6 @@ $router = new Router(); $router->addMiddleware(new CsrfMiddleware()); - $router->addMiddleware(new RateLimitMiddleware()); $router->addRoute("perform-login", new \Handler\LoginHandler()); $router->addRoute("perform-oidc-login", new \Handler\LoginHandler()); diff --git a/classes/Handler/LoginHandler.php b/classes/Handler/LoginHandler.php index e317054..aff9d80 100644 --- a/classes/Handler/LoginHandler.php +++ b/classes/Handler/LoginHandler.php @@ -11,7 +11,40 @@ use Response; class LoginHandler implements RequestHandlerInterface { - /** @return array{result: string, user: string, csrf_token: string}|null */ + const USER_NOT_FOUND = 1; + const USER_RATE_LIMITED = 2; + const USER_WRONG_PASSWORD = 3; + const USER_AUTH_SUCCESS = 4; + + private function isRateLimited(object $user): bool + { + // Skip rate limiting during integration tests or schema is older than required + if (getenv('IS_INTEGRATION_TESTING') || Config::get_schema_version() < 3) { + return false; + } + + $windowSeconds = 60; + $lastAttempt = $user->last_auth_attempt; + + if ($lastAttempt !== null && is_numeric($lastAttempt) && (int) $lastAttempt > 0) { + if ((time() - (int) $lastAttempt) < $windowSeconds) { + + // Bump login attempt timestamp + $user->last_auth_attempt = time(); + $user->save(); + + return true; + } + } + + // Record this attempt timestamp before expensive password verification. + $user->last_auth_attempt = time(); + $user->save(); + + return false; + } + + /** @return array{array{result: string, user: string, csrf_token: string}|null, int} */ private function doLocalLogin(string $username, string $password): ?array { $user = ORM::for_table('epube_users') @@ -19,7 +52,13 @@ class LoginHandler implements RequestHandlerInterface ->find_one(); if (!$user) { - return null; + return [null, self::USER_NOT_FOUND]; + } + + // Check rate limit against the *previous* attempt before updating. + // This avoids blocking the first attempt in any window. + if ($this->isRateLimited($user)) { + return [null, self::USER_RATE_LIMITED]; } // Verify password against stored hash (legacy or modern) @@ -29,7 +68,7 @@ class LoginHandler implements RequestHandlerInterface : password_verify($password, $user->pass); if (!$valid) { - return null; + return [null, self::USER_WRONG_PASSWORD]; } // Upgrade legacy hash to bcrypt @@ -37,6 +76,12 @@ class LoginHandler implements RequestHandlerInterface $this->upgradePassword($user, $password); } + // Reset last login attempt on successful login + if (Config::get_schema_version() >= 3) { + $user->last_auth_attempt = 0; + $user->save(); + } + // Set up session if (session_status() != PHP_SESSION_ACTIVE) { session_start(); @@ -51,7 +96,7 @@ class LoginHandler implements RequestHandlerInterface setcookie("epube_csrf_token", $_SESSION["csrf_token"], time() + Config::get(Config::SESSION_LIFETIME), "/", "", Config::is_server_https()); - return ["result" => "ok", "user" => $username, "csrf_token" => $_SESSION["csrf_token"]]; + return [["result" => "ok", "user" => $username, "csrf_token" => $_SESSION["csrf_token"]], self::USER_AUTH_SUCCESS]; } /** @@ -183,12 +228,18 @@ class LoginHandler implements RequestHandlerInterface ->withBody(json_encode(["error" => "Username and password are required."])); } - $result = $this->doLocalLogin($username, $password); + [$result, $status] = $this->doLocalLogin($username, $password); if (!$result) { - return (new Response()) - ->withStatus(401) - ->withBody(json_encode(["error" => "Incorrect username or password."])); + if ($status === self::USER_RATE_LIMITED) { + return (new Response()) + ->withStatus(429) + ->withBody(json_encode(["error" => "Too many login attempts."])); + } else { + return (new Response()) + ->withStatus(401) + ->withBody(json_encode(["error" => "Incorrect username or password."])); + } } return (new Response()) 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(); - } -} diff --git a/sql/pgsql/migrations/3.sql b/sql/pgsql/migrations/3.sql new file mode 100644 index 0000000..450a5f1 --- /dev/null +++ b/sql/pgsql/migrations/3.sql @@ -0,0 +1,2 @@ +alter table epube_users add column last_auth_attempt bigint default null; +create index if not exists idx_epube_users_last_auth_attempt on epube_users(last_auth_attempt); diff --git a/sql/pgsql/schema.sql b/sql/pgsql/schema.sql index 2d02190..950bfad 100644 --- a/sql/pgsql/schema.sql +++ b/sql/pgsql/schema.sql @@ -1,7 +1,8 @@ create table if not exists epube_users ( id serial not null primary key, username varchar(100) not null unique, - pass varchar(200) not null); + pass varchar(200) not null, + last_auth_attempt bigint default null); create table if not exists epube_pagination ( id serial not null primary key, diff --git a/sql/sqlite/migrations/3.sql b/sql/sqlite/migrations/3.sql new file mode 100644 index 0000000..450a5f1 --- /dev/null +++ b/sql/sqlite/migrations/3.sql @@ -0,0 +1,2 @@ +alter table epube_users add column last_auth_attempt bigint default null; +create index if not exists idx_epube_users_last_auth_attempt on epube_users(last_auth_attempt); diff --git a/sql/sqlite/schema.sql b/sql/sqlite/schema.sql index eeab2f9..f14bcf9 100644 --- a/sql/sqlite/schema.sql +++ b/sql/sqlite/schema.sql @@ -7,7 +7,8 @@ create table if not exists epube_pagination ( create table if not exists epube_users ( id integer not null primary key autoincrement, username varchar(100) not null, - pass varchar(200) not null); + pass varchar(200) not null, + last_auth_attempt bigint default null); create table if not exists epube_books ( id integer not null primary key autoincrement, |
