From ec424dd9093d94b69ec3a118f321cd1f85c7dd54 Mon Sep 17 00:00:00 2001 From: Marrrrrrrrry <34876935+Marrrrrrrrry@users.noreply.github.com> Date: Wed, 9 Sep 2026 18:33:27 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20make=20is=5Fconfig=5Finitialized=20chea?= =?UTF-8?q?p=20=E2=80=94=20no=20scrypt=20on=20the=20per-request=20probe=20?= =?UTF-8?q?(D1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/security.py | 9 +++++++++ tests/test_password_hashing.py | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/core/security.py b/core/security.py index 7625287..1e80556 100644 --- a/core/security.py +++ b/core/security.py @@ -29,9 +29,18 @@ def is_valid_jwt_secret(secret: Any) -> bool: def is_config_initialized(config: dict[str, Any]) -> bool: + """Cheap initialization probe — runs on EVERY request via the middleware. + + Must never run a slow hash: a scrypt-stored token cannot be the legacy + default (which only ever existed as plaintext or sha256), so those tokens + are initialized without any verification. Only plaintext/sha256 tokens go + through the legacy-default comparison, which is microseconds. + """ admin_token = str(config.get("admin_token") or "") if not admin_token: return False + if is_password_hashed(admin_token) and admin_token.startswith("scrypt$"): + return True return not verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token) diff --git a/tests/test_password_hashing.py b/tests/test_password_hashing.py index 4ccfc4f..88e8cc7 100644 --- a/tests/test_password_hashing.py +++ b/tests/test_password_hashing.py @@ -5,6 +5,7 @@ hashes are scrypt (memory-hard). A successful login with a legacy-stored password upgrades the stored hash in place. """ import asyncio +import time import hashlib import unittest @@ -87,3 +88,23 @@ class TransparentRehashTests(SettingsOverrideMixin, unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class CheapInitProbeTests(unittest.TestCase): + """D1 回归:is_config_initialized 在每个请求都会被中间件调用, + 对 scrypt 口令绝不允许跑慢哈希。""" + + def test_scrypt_token_is_initialized_without_slow_hash(self): + from core.security import is_config_initialized + from core.utils import hash_password as hp + + token = hp("some-real-password") + t0 = time.perf_counter() + self.assertTrue(is_config_initialized({"admin_token": token})) + self.assertLess(time.perf_counter() - t0, 0.01, "初始化探测不应执行 scrypt") + + def test_empty_and_legacy_default_are_not_initialized(self): + from core.security import is_config_initialized, LEGACY_DEFAULT_ADMIN_TOKEN + + self.assertFalse(is_config_initialized({"admin_token": ""})) + self.assertFalse(is_config_initialized({"admin_token": LEGACY_DEFAULT_ADMIN_TOKEN}))