From 5faa7ee19435539f782e0a5eddba760d5519aead Mon Sep 17 00:00:00 2001 From: simpleqt <89645338+simpleqt@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:42:55 +0800 Subject: [PATCH] Recognize Bearer-scheme API keys in the rate limiter _get_client_key checked that the Authorization header starts with krlk_, but real requests send 'Bearer krlk_...', so the per-key branch was unreachable and every request fell into the shared IP bucket. Strip the scheme before the prefix check while keeping raw-key headers working. Fixes #2428 --- src/memos/api/middleware/rate_limit.py | 10 ++-- tests/api/test_rate_limit_key.py | 74 ++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 tests/api/test_rate_limit_key.py diff --git a/src/memos/api/middleware/rate_limit.py b/src/memos/api/middleware/rate_limit.py index c547378ca..920fc0083 100644 --- a/src/memos/api/middleware/rate_limit.py +++ b/src/memos/api/middleware/rate_limit.py @@ -57,11 +57,15 @@ def _get_client_key(request: Request) -> str: Uses API key if available, otherwise falls back to IP. """ - # Try to get API key from header + # Try to get API key from header. Requests send "Authorization: Bearer + # krlk_...", so the Bearer scheme must be stripped before checking the + # key prefix; a raw "krlk_..." header keeps working unchanged. auth_header = request.headers.get("Authorization", "") - if auth_header.startswith("krlk_"): + scheme, _, credentials = auth_header.partition(" ") + key_part = credentials.strip() if scheme.lower() == "bearer" else auth_header + if key_part.startswith("krlk_"): # Use first 20 chars of key as identifier - return f"ratelimit:key:{auth_header[:20]}" + return f"ratelimit:key:{key_part[:20]}" # Fall back to IP address client_ip = request.client.host if request.client else "unknown" diff --git a/tests/api/test_rate_limit_key.py b/tests/api/test_rate_limit_key.py new file mode 100644 index 000000000..450484e3d --- /dev/null +++ b/tests/api/test_rate_limit_key.py @@ -0,0 +1,74 @@ +import importlib +import logging +import sys +import types + +from pathlib import Path + +import pytest + + +SRC_DIR = Path(__file__).resolve().parents[2] / "src" / "memos" + + +def _install_memos_package_stub() -> None: + if "memos" not in sys.modules: + memos_pkg = types.ModuleType("memos") + memos_pkg.__path__ = [str(SRC_DIR)] + sys.modules["memos"] = memos_pkg + + if "memos.log" not in sys.modules: + log_stub = types.ModuleType("memos.log") + log_stub.get_logger = logging.getLogger + sys.modules["memos.log"] = log_stub + sys.modules["memos"].log = log_stub + + if "memos.api" not in sys.modules: + api_pkg = types.ModuleType("memos.api") + api_pkg.__path__ = [str(SRC_DIR / "api")] + sys.modules["memos.api"] = api_pkg + sys.modules["memos"].api = api_pkg + + +@pytest.fixture(scope="module") +def rate_limit_module(): + _install_memos_package_stub() + middleware_pkg = types.ModuleType("memos.api.middleware") + middleware_pkg.__path__ = [str(SRC_DIR / "api" / "middleware")] + sys.modules["memos.api.middleware"] = middleware_pkg + sys.modules["memos"].api.middleware = middleware_pkg + return importlib.import_module("memos.api.middleware.rate_limit") + + +class _FakeRequest: + def __init__(self, headers, client_host="10.0.0.1"): + self.headers = headers + self.client = types.SimpleNamespace(host=client_host) + + +KEY = "krlk_" + "a" * 64 + + +def test_bearer_api_key_gets_keyed_bucket(rate_limit_module): + request = _FakeRequest({"Authorization": f"Bearer {KEY}"}) + assert rate_limit_module._get_client_key(request) == f"ratelimit:key:{KEY[:20]}" + + +def test_lowercase_bearer_scheme_is_recognized(rate_limit_module): + request = _FakeRequest({"Authorization": f"bearer {KEY}"}) + assert rate_limit_module._get_client_key(request) == f"ratelimit:key:{KEY[:20]}" + + +def test_raw_key_header_still_gets_keyed_bucket(rate_limit_module): + request = _FakeRequest({"Authorization": KEY}) + assert rate_limit_module._get_client_key(request) == f"ratelimit:key:{KEY[:20]}" + + +def test_non_key_authorization_falls_back_to_ip(rate_limit_module): + request = _FakeRequest({"Authorization": "Bearer some-other-token"}) + assert rate_limit_module._get_client_key(request) == "ratelimit:ip:10.0.0.1" + + +def test_missing_authorization_falls_back_to_ip(rate_limit_module): + request = _FakeRequest({}) + assert rate_limit_module._get_client_key(request) == "ratelimit:ip:10.0.0.1"