From f97b2d863d26812b84362f4cb27e5c7732dd5302 Mon Sep 17 00:00:00 2001 From: simpleqt <89645338+simpleqt@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:41:36 +0800 Subject: [PATCH] Reject non-canonical hex in API key format validation validate_key_format used int(hex_part, 16), which accepts a leading sign, a 0x prefix, underscore separators, and whitespace. Enforce the exact generated form with a [0-9a-f]{64} fullmatch in both copies (api utils and auth middleware). Fixes #2427 --- src/memos/api/middleware/auth.py | 15 +++--- src/memos/api/utils/api_keys.py | 18 +++---- tests/api/test_api_key_format.py | 83 ++++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+), 18 deletions(-) create mode 100644 tests/api/test_api_key_format.py diff --git a/src/memos/api/middleware/auth.py b/src/memos/api/middleware/auth.py index 15b217651..08ba6d9da 100644 --- a/src/memos/api/middleware/auth.py +++ b/src/memos/api/middleware/auth.py @@ -7,6 +7,7 @@ import hashlib import os +import re import time from typing import Any @@ -30,6 +31,11 @@ # Connection pool for auth queries (lazy init) _auth_pool = None +# int(hex, 16) also accepts a leading sign, a 0x prefix, underscore +# separators, and whitespace, so the format gate must match the exact +# form generate_api_key() produces instead. +_HEX_KEY_RE = re.compile(r"[0-9a-f]{64}") + def _get_auth_pool(): """Get or create auth database connection pool.""" @@ -66,14 +72,7 @@ def validate_key_format(key: str) -> bool: """Validate API key format: krlk_<64-hex>.""" if not key or not key.startswith("krlk_"): return False - hex_part = key[5:] # Remove 'krlk_' prefix - if len(hex_part) != 64: - return False - try: - int(hex_part, 16) - return True - except ValueError: - return False + return _HEX_KEY_RE.fullmatch(key[5:]) is not None def get_key_prefix(key: str) -> str: diff --git a/src/memos/api/utils/api_keys.py b/src/memos/api/utils/api_keys.py index 29b493fd0..cb880890e 100644 --- a/src/memos/api/utils/api_keys.py +++ b/src/memos/api/utils/api_keys.py @@ -5,12 +5,16 @@ """ import hashlib +import re import secrets from dataclasses import dataclass from datetime import datetime, timedelta +_HEX_KEY_RE = re.compile(r"[0-9a-f]{64}") + + @dataclass class APIKey: """Represents a generated API key.""" @@ -49,7 +53,9 @@ def validate_key_format(key: str) -> bool: """ Validate API key format. - Valid format: krlk_<64-hex-chars> + Valid format: krlk_<64-hex-chars>, exactly the form generate_api_key() + produces. int(hex, 16) is not usable here because it also accepts a + leading sign, a 0x prefix, underscore separators, and whitespace. """ if not key or not isinstance(key, str): return False @@ -57,15 +63,7 @@ def validate_key_format(key: str) -> bool: if not key.startswith("krlk_"): return False - hex_part = key[5:] - if len(hex_part) != 64: - return False - - try: - int(hex_part, 16) - return True - except ValueError: - return False + return _HEX_KEY_RE.fullmatch(key[5:]) is not None def generate_master_key() -> tuple[str, str]: diff --git a/tests/api/test_api_key_format.py b/tests/api/test_api_key_format.py new file mode 100644 index 000000000..a58096215 --- /dev/null +++ b/tests/api/test_api_key_format.py @@ -0,0 +1,83 @@ +import importlib +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.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 api_keys_module(): + _install_memos_package_stub() + utils_pkg = types.ModuleType("memos.api.utils") + utils_pkg.__path__ = [str(SRC_DIR / "api" / "utils")] + sys.modules["memos.api.utils"] = utils_pkg + sys.modules["memos"].api.utils = utils_pkg + return importlib.import_module("memos.api.utils.api_keys") + + +@pytest.fixture(scope="module") +def auth_module(api_keys_module): + import logging + + log_stub = types.ModuleType("memos.log") + log_stub.get_logger = logging.getLogger + sys.modules["memos.log"] = log_stub + sys.modules["memos"].log = log_stub + return importlib.import_module("memos.api.middleware.auth") + + +# int(x, 16) accepted these 64-char hex_parts; none of them is a form +# generate_api_key() can ever produce. +NON_CANONICAL_HEX_PARTS = [ + "+" + "a" * 63, + "-" + "a" * 63, + "0x" + "a" * 62, + "a" * 30 + "_" + "b" * 33, + " " + "a" * 63, +] + + +def test_generated_key_passes_format_validation(api_keys_module): + generated = api_keys_module.generate_api_key() + assert api_keys_module.validate_key_format(generated.key) + + +def test_canonical_key_is_accepted(api_keys_module, auth_module): + key = "krlk_" + "a" * 64 + assert api_keys_module.validate_key_format(key) + assert auth_module.validate_key_format(key) + + +@pytest.mark.parametrize("hex_part", NON_CANONICAL_HEX_PARTS) +def test_non_canonical_hex_is_rejected(hex_part, api_keys_module, auth_module): + key = "krlk_" + hex_part + assert not api_keys_module.validate_key_format(key) + assert not auth_module.validate_key_format(key) + + +def test_wrong_length_is_rejected(api_keys_module, auth_module): + assert not api_keys_module.validate_key_format("krlk_" + "a" * 63) + assert not auth_module.validate_key_format("krlk_" + "a" * 65) + + +def test_missing_prefix_is_rejected(api_keys_module, auth_module): + assert not api_keys_module.validate_key_format("a" * 64) + assert not auth_module.validate_key_format("")