diff options
| author | fox <fox@fakecake.org> | 2026-06-21 14:51:01 +0300 |
|---|---|---|
| committer | fox <fox@fakecake.org> | 2026-06-21 14:51:01 +0300 |
| commit | 8e569855249dda7a17402e5ae20044e8149d992e (patch) | |
| tree | 6a6acc9a378e2402d048a02e47b5ab99dc5247e2 | |
| parent | 23ca9695d1b38c7a27cf132d517a6ed6b19f607a (diff) | |
| parent | 17296a2ef8fa2658dca471285bce40ee67469179 (diff) | |
| download | the-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
| -rw-r--r-- | backend.php | 1 | ||||
| -rw-r--r-- | classes/Handler/LoginHandler.php | 77 | ||||
| -rw-r--r-- | classes/RateLimitMiddleware.php | 119 | ||||
| -rw-r--r-- | sql/pgsql/migrations/3.sql | 2 | ||||
| -rw-r--r-- | sql/pgsql/schema.sql | 6 | ||||
| -rw-r--r-- | sql/sqlite/migrations/3.sql | 2 | ||||
| -rw-r--r-- | sql/sqlite/schema.sql | 5 |
7 files changed, 80 insertions, 132 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..7b6fabb 100644 --- a/classes/Handler/LoginHandler.php +++ b/classes/Handler/LoginHandler.php @@ -11,15 +11,61 @@ use Response; class LoginHandler implements RequestHandlerInterface { - /** @return array{result: string, user: string, csrf_token: string}|null */ - private function doLocalLogin(string $username, string $password): ?array + 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; + } + } + + return false; + } + + /** + * Record a failed authentication attempt for rate limiting purposes. + */ + private function recordFailedAttempt(object $user): void + { + if (Config::get_schema_version() >= 3) { + $user->last_auth_attempt = time(); + $user->save(); + } + } + + /** @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') ->where('username', $username) ->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 +75,8 @@ class LoginHandler implements RequestHandlerInterface : password_verify($password, $user->pass); if (!$valid) { - return null; + $this->recordFailedAttempt($user); + return [null, self::USER_WRONG_PASSWORD]; } // Upgrade legacy hash to bcrypt @@ -37,6 +84,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 +104,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 +236,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..e23d0ca --- /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 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..df76b16 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, @@ -26,4 +27,5 @@ create table if not exists epube_sessions (id varchar(250) not null primary key, data text, expire integer not null); -create index epube_sessions_expire_index on epube_sessions(expire); +create index if not exists epube_sessions_expire_index on epube_sessions(expire); +create index if not exists epube_users_last_auth_attempt on epube_users(last_auth_attempt); diff --git a/sql/sqlite/migrations/3.sql b/sql/sqlite/migrations/3.sql new file mode 100644 index 0000000..e23d0ca --- /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 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..dacb1f2 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, @@ -21,3 +22,5 @@ create table if not exists epube_favorites( id integer not null primary key autoincrement, bookid integer not null, owner varchar(200) not null); + +create index if not exists epube_users_last_auth_attempt on epube_users(last_auth_attempt); |
