Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions src/memos/api/middleware/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import hashlib
import os
import re
import time

from typing import Any
Expand All @@ -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."""
Expand Down Expand Up @@ -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:
Expand Down
18 changes: 8 additions & 10 deletions src/memos/api/utils/api_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -49,23 +53,17 @@ 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

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]:
Expand Down
83 changes: 83 additions & 0 deletions tests/api/test_api_key_format.py
Original file line number Diff line number Diff line change
@@ -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("")
Loading