about summary refs log tree commit diff stats
path: root/classes/Handler
diff options
context:
space:
mode:
authorAndrew Dolgov <fox@fakecake.org>2026-06-21 14:37:09 +0300
committerAndrew Dolgov <fox@fakecake.org>2026-06-21 14:37:09 +0300
commit5a2b451afb7a5c794b5da19dd22b4ba40c256b03 (patch)
tree7e2ae0bf2a8cd88ccc70fefdee2d4c3c288e9a92 /classes/Handler
parent1215afa6ef28a6e0a53aab98263e922b7c66a580 (diff)
downloadthe-epube-5a2b451afb7a5c794b5da19dd22b4ba40c256b03.tar.gz
the-epube-5a2b451afb7a5c794b5da19dd22b4ba40c256b03.tar.xz
rework login throttling to use database field check instead of APCu
Diffstat (limited to 'classes/Handler')
-rw-r--r--classes/Handler/LoginHandler.php67
1 files changed, 59 insertions, 8 deletions
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())