Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(auth): serialize API key registry writes (#3377)

Qin Haojie370fe45f6f6f
diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.py
index a13aa939d..d19b1095e 100644
--- a/openviking/server/api_keys/legacy.py
+++ b/openviking/server/api_keys/legacy.py
@@ -16,6 +16,8 @@ from argon2.exceptions import VerifyMismatchError
from openviking.pyagfs import AGFSAlreadyExistsError, AGFSNotFoundError, AsyncAGFSClient
from openviking.server.api_keys.models import AccountInfo, UserKeyEntry
from openviking.server.identity import ResolvedIdentity, Role
+from openviking.storage.errors import LockAcquisitionError, ResourceBusyError
+from openviking.storage.transaction import LockContext, get_lock_manager
from openviking.storage.viking_fs import VikingFS
from openviking_cli.exceptions import (
AlreadyExistsError,
@@ -651,18 +653,38 @@ class LegacyAPIKeyManager:
async def _save_accounts_json(self) -> None:
"""Persist the global accounts list."""
- data = {
- "accounts": {
- aid: {"created_at": info.created_at} for aid, info in self._accounts.items()
- }
- }
- await self._write_json(ACCOUNTS_PATH, data)
+ try:
+ async with LockContext(
+ get_lock_manager(), [ACCOUNTS_PATH], lock_mode="exact", timeout=10.0
+ ):
+ data = {
+ "accounts": {
+ aid: {"created_at": info.created_at}
+ for aid, info in self._accounts.items()
+ }
+ }
+ await self._write_json(ACCOUNTS_PATH, data)
+ except LockAcquisitionError as exc:
+ raise ResourceBusyError(
+ "Another account operation is in progress. Please retry.",
+ uri=ACCOUNTS_PATH,
+ conflict_type="account_registry_busy",
+ ) from exc
async def _save_users_json(self, account_id: str) -> None:
"""Persist a single account's user registry."""
- account = self._accounts.get(account_id)
- if account is None:
- return
- data = {"users": account.users}
path = USERS_PATH_TEMPLATE.format(account_id=account_id)
- await self._write_json(path, data)
+ try:
+ async with LockContext(
+ get_lock_manager(), [path], lock_mode="exact", timeout=10.0
+ ):
+ account = self._accounts.get(account_id)
+ if account is None:
+ return
+ await self._write_json(path, {"users": account.users})
+ except LockAcquisitionError as exc:
+ raise ResourceBusyError(
+ "Another user operation is in progress for this account. Please retry.",
+ uri=path,
+ conflict_type="user_registry_busy",
+ ) from exc
diff --git a/openviking/storage/transaction/lock_context.py b/openviking/storage/transaction/lock_context.py
index 05212ddf0..424cca343 100644
--- a/openviking/storage/transaction/lock_context.py
+++ b/openviking/storage/transaction/lock_context.py
@@ -2,12 +2,12 @@
# SPDX-License-Identifier: AGPL-3.0
"""LockContext — async context manager for acquiring/releasing path locks."""
-from typing import Optional
+from typing import Any, Optional
from openviking.storage.errors import LockAcquisitionError
from openviking.storage.transaction.lock_handle import LockHandle
from openviking.storage.transaction.lock_lease import OwnedLockLease
-from openviking.storage.transaction.lock_manager import LockManager
+from openviking.storage.transaction.lock_manager import LOCK_TIMEOUT_DEFAULT, LockManager
class LockContext:
@@ -25,6 +25,7 @@ class LockContext:
mv_dst_path: Optional[str] = None,
src_is_dir: bool = True,
handle: Optional[LockHandle] = None,
+ timeout: Any = LOCK_TIMEOUT_DEFAULT,
):
self._manager = lock_manager
self._paths = paths
@@ -32,6 +33,7 @@ class LockContext:
self._mv_dst_path = mv_dst_path
self._src_is_dir = src_is_dir
self._handle: Optional[LockHandle] = handle
+ self._timeout = timeout
self._owns_handle = handle is None
self._locks_before: list[str] = []
self._acquired_lock_paths: list[str] = []
@@ -45,11 +47,15 @@ class LockContext:
if self._lock_mode == "tree":
for path in self._paths:
- success = await self._manager.acquire_tree(self._handle, path)
+ success = await self._manager.acquire_tree(
+ self._handle, path, timeout=self._timeout
+ )
if not success:
break
elif self._lock_mode == "exact":
- success = await self._manager.acquire_exact_path_batch(self._handle, self._paths)
+ success = await self._manager.acquire_exact_path_batch(
+ self._handle, self._paths, timeout=self._timeout
+ )
elif self._lock_mode == "mv":
if self._mv_dst_path is None:
raise LockAcquisitionError("mv lock mode requires mv_dst_path")
@@ -58,6 +64,7 @@ class LockContext:
self._paths[0],
self._mv_dst_path,
src_is_dir=self._src_is_dir,
+ timeout=self._timeout,
)
else:
raise LockAcquisitionError(f"Unsupported lock mode: {self._lock_mode}")
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index cff1d4a5f..53f99c57e 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -43,6 +43,19 @@ def _seed_secret(user_id: str, seed: str) -> str:
ROOT_KEY = "admin-api-test-root-key-abcdef1234567890ab"
+class _NoopLockContext:
+ """The lightweight fake storage does not exercise transaction locking."""
+
+ def __init__(self, *_args, **_kwargs):
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return False
+
+
class _FakeAGFS:
def __init__(self):
self._files = {}
@@ -134,7 +147,13 @@ def _build_lightweight_admin_test_app() -> FastAPI:
@pytest_asyncio.fixture(scope="function")
-async def lightweight_admin_app():
+async def lightweight_admin_app(monkeypatch):
+ monkeypatch.setattr(
+ "openviking.server.api_keys.legacy.get_lock_manager", lambda: None
+ )
+ monkeypatch.setattr(
+ "openviking.server.api_keys.legacy.LockContext", _NoopLockContext
+ )
app = _build_lightweight_admin_test_app()
await app.state.api_key_manager.load()
return app
diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.py
index 8d614bfea..309c02efe 100644
--- a/tests/server/test_api_key_manager.py
+++ b/tests/server/test_api_key_manager.py
@@ -3,6 +3,7 @@
"""Tests for APIKeyManager (openviking/server/api_keys.py)."""
+import asyncio
import hashlib
import uuid
@@ -11,8 +12,10 @@ import pytest_asyncio
from openviking.pyagfs.exceptions import AGFSNotFoundError
from openviking.server.api_keys import APIKeyManager
+from openviking.server.api_keys.legacy import ACCOUNTS_PATH
from openviking.server.identity import Role
from openviking.service.core import OpenVikingService
+from openviking.storage.transaction import LockContext, get_lock_manager
from openviking_cli.exceptions import (
AlreadyExistsError,
InvalidArgumentError,
@@ -165,6 +168,36 @@ async def test_register_user(manager: APIKeyManager):
assert identity.user_id == "bob"
+async def test_concurrent_registry_writes_wait_for_locks(manager: APIKeyManager):
+ first_account = _uid()
+ second_account = _uid()
+
+ async with LockContext(get_lock_manager(), [ACCOUNTS_PATH], lock_mode="exact"):
+ account_tasks = [
+ asyncio.create_task(manager.create_account(first_account, "alice")),
+ asyncio.create_task(manager.create_account(second_account, "bob")),
+ ]
+ await asyncio.sleep(0.05)
+ assert all(not task.done() for task in account_tasks)
+
+ await asyncio.gather(*account_tasks)
+ accounts = await manager._read_json(ACCOUNTS_PATH)
+ assert {first_account, second_account} <= set(accounts["accounts"])
+
+ users_path = f"/local/{first_account}/_system/users.json"
+ async with LockContext(get_lock_manager(), [users_path], lock_mode="exact"):
+ user_tasks = [
+ asyncio.create_task(manager.register_user(first_account, "bob")),
+ asyncio.create_task(manager.register_user(first_account, "carol")),
+ ]
+ await asyncio.sleep(0.05)
+ assert all(not task.done() for task in user_tasks)
+
+ await asyncio.gather(*user_tasks)
+ users = await manager._read_json(users_path)
+ assert set(users["users"]) == {"alice", "bob", "carol"}
+
+
async def test_register_duplicate_user_raises(manager: APIKeyManager):
"""Registering duplicate user should raise AlreadyExistsError."""
acct = _uid()