Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
[security] fix(admin): restrict privileged roles in register_user (#1624)
Hinotobid0b9fb415a49
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex 66c1aebbf..ff123d9e1 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -362,12 +362,12 @@ Register a new user in a workspace.|-----------|------|----------|---------|-------------|| account_id | str | Yes | - | Workspace ID || user_id | str | Yes | - | User ID |-| role | str | No | "user" | Role: "admin" or "user" |+| role | str | No | "user" | Role to assign. `ROOT` and same-account `ADMIN` may register `"user"` or `"admin"`. `"root"` must be assigned through the dedicated role-change endpoint. |**Notes:**- In `trusted` mode, `user_key` is omitted from the response- ADMIN can only register users in their own account-- Only ROOT can set role to "admin" for new users+- The `"root"` role cannot be minted through user registration#### 3. Usage Examplesdiff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex 4dc6c3b05..c36507d47 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -360,12 +360,12 @@ ov --sudo admin delete-account acme|------|------|------|--------|------|| account_id | str | 是 | - | 工作区 ID || user_id | str | 是 | - | 用户 ID |-| role | str | 否 | "user" | 角色:"admin" 或 "user" |+| role | str | 否 | "user" | 要分配的角色。`ROOT` 和同 account 的 `ADMIN` 可直接注册 `"user"` 或 `"admin"`。`"root"` 必须通过专门的改角色接口分配。 |**说明:**- 在 `trusted` 模式下,响应中不会包含 `user_key` 字段- ADMIN 只能在自己所属的 account 中注册用户-- 只有 ROOT 可以将新用户角色设置为 "admin"+- 无法通过用户注册接口直接创建 `"root"` 角色#### 3. 使用示例diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex eda91bdbf..684930f43 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -16,7 +16,7 @@ from openviking.server.dependencies import get_servicefrom openviking.server.identity import AccountNamespacePolicy, RequestContext, Rolefrom openviking.server.models import Responsefrom openviking.storage.viking_fs import get_viking_fs-from openviking_cli.exceptions import NotFoundError, PermissionDeniedError+from openviking_cli.exceptions import InvalidArgumentError, NotFoundError, PermissionDeniedErrorfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.logger import get_logger@@ -59,6 +59,26 @@ def _check_account_access(ctx: RequestContext, account_id: str) -> None:raise PermissionDeniedError(f"ADMIN can only manage account: {ctx.account_id}")+def _validate_register_user_role(ctx: RequestContext, role: str) -> Role:+ """Validate which roles may be minted through register_user.++ register_user is the user-creation path, not the privileged role-escalation path.+ - ROOT may create USER or ADMIN accounts here.+ - ADMIN may create USER or ADMIN accounts in their own account.+ - ROOT role assignment must go through the dedicated ROOT-only set_role endpoint.+ """+ try:+ resolved_role = Role(role)+ except ValueError as exc:+ raise InvalidArgumentError(f"Unsupported role for register_user: {role}") from exc++ if resolved_role == Role.ROOT:+ raise PermissionDeniedError(+ "register_user cannot mint ROOT users; use the ROOT-only set_role endpoint instead."+ )+ return resolved_role++# ---- Account endpoints ----@@ -167,8 +187,9 @@ async def register_user():"""Register a new user in an account."""_check_account_access(ctx, account_id)+ resolved_role = _validate_register_user_role(ctx, body.role)manager = _get_api_key_manager(request)- user_key = await manager.register_user(account_id, body.user_id, body.role)+ user_key = await manager.register_user(account_id, body.user_id, resolved_role.value)service = get_service()user_ctx = RequestContext(user=UserIdentifier(account_id, body.user_id, "default"),diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex bc652fe18..4696f6875 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -7,13 +7,18 @@ import uuidimport httpximport pytest_asyncio+from fastapi import FastAPI+from fastapi import Request as FastAPIRequest+from fastapi.responses import JSONResponsefrom openviking.server.api_keys import APIKeyManagerfrom openviking.server.app import create_appfrom openviking.server.config import ServerConfigfrom openviking.server.dependencies import set_servicefrom openviking.server.identity import RequestContext, Role+from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Responsefrom openviking.service.core import OpenVikingService+from openviking_cli.exceptions import OpenVikingErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -24,6 +29,84 @@ def _uid() -> str:ROOT_KEY = "admin-api-test-root-key-abcdef1234567890ab"+class _FakeAGFS:+ def __init__(self):+ self._files = {}+ self._dirs = {"/", "/local"}++ def read(self, path):+ if path not in self._files:+ raise FileNotFoundError(path)+ return self._files[path]++ def write(self, path, content):+ self._files[path] = content++ def mkdir(self, path):+ self._dirs.add(path)+++class _FakeVikingFS:+ def __init__(self):+ self.agfs = _FakeAGFS()++ async def encrypt_bytes(self, account_id, content):+ return content++ async def decrypt_bytes(self, account_id, content):+ return content+++class _FakeService:+ def __init__(self):+ self.viking_fs = _FakeVikingFS()++ async def initialize_account_directories(self, ctx):+ return None++ async def initialize_user_directories(self, ctx):+ return None+++def _build_lightweight_admin_test_app() -> FastAPI:+ from openviking.server.routers import admin as admin_router++ app = FastAPI()+ app.state.config = ServerConfig(root_api_key=ROOT_KEY)+ fake_service = _FakeService()+ set_service(fake_service)++ @app.exception_handler(OpenVikingError)+ async def openviking_error_handler(request: FastAPIRequest, exc: OpenVikingError):+ http_status = ERROR_CODE_TO_HTTP_STATUS.get(exc.code, 500)+ return JSONResponse(+ status_code=http_status,+ content=Response(+ status="error",+ error=ErrorInfo(code=exc.code, message=exc.message, details=exc.details),+ ).model_dump(),+ )++ manager = APIKeyManager(root_key=ROOT_KEY, viking_fs=fake_service.viking_fs)+ app.state.api_key_manager = manager+ app.include_router(admin_router.router)+ return app+++@pytest_asyncio.fixture(scope="function")+async def lightweight_admin_app():+ app = _build_lightweight_admin_test_app()+ await app.state.api_key_manager.load()+ return app+++@pytest_asyncio.fixture(scope="function")+async def lightweight_admin_client(lightweight_admin_app):+ transport = httpx.ASGITransport(app=lightweight_admin_app)+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c:+ yield c++@pytest_asyncio.fixture(scope="function")async def admin_service(temp_dir):svc = OpenVikingService(@@ -183,6 +266,51 @@ async def test_register_user(admin_client: httpx.AsyncClient):assert resp.status_code == 200+async def test_root_can_register_admin_role_user(+ lightweight_admin_client: httpx.AsyncClient,+):+ """ROOT can create an ADMIN user via register_user."""+ acct = _uid()+ await lightweight_admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice"},+ headers=root_headers(),+ )++ resp = await lightweight_admin_client.post(+ f"/api/v1/admin/accounts/{acct}/users",+ json={"user_id": "bob-admin", "role": "admin"},+ headers=root_headers(),+ )+ assert resp.status_code == 200++ admin_key = resp.json()["result"]["user_key"]+ list_users = await lightweight_admin_client.get(+ f"/api/v1/admin/accounts/{acct}/users",+ headers={"X-API-Key": admin_key},+ )+ assert list_users.status_code == 200+++async def test_root_cannot_register_root_role_user(+ lightweight_admin_client: httpx.AsyncClient,+):+ """ROOT must use set_role instead of minting ROOT directly in register_user."""+ acct = _uid()+ await lightweight_admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice"},+ headers=root_headers(),+ )++ resp = await lightweight_admin_client.post(+ f"/api/v1/admin/accounts/{acct}/users",+ json={"user_id": "mallory-root", "role": "root"},+ headers=root_headers(),+ )+ assert resp.status_code == 403++async def test_admin_can_register_user_in_own_account(admin_client: httpx.AsyncClient):"""ADMIN can register users in their own account."""acct = _uid()@@ -201,6 +329,83 @@ async def test_admin_can_register_user_in_own_account(admin_client: httpx.AsyncCassert resp.status_code == 200+async def test_admin_can_register_admin_role_user(+ lightweight_admin_client: httpx.AsyncClient,+):+ """ADMIN can create another ADMIN in the same account via register_user."""+ acct = _uid()+ resp = await lightweight_admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice"},+ headers=root_headers(),+ )+ alice_key = resp.json()["result"]["user_key"]++ resp = await lightweight_admin_client.post(+ f"/api/v1/admin/accounts/{acct}/users",+ json={"user_id": "mallory-admin", "role": "admin"},+ headers={"X-API-Key": alice_key},+ )+ assert resp.status_code == 200++ admin_key = resp.json()["result"]["user_key"]+ list_users = await lightweight_admin_client.get(+ f"/api/v1/admin/accounts/{acct}/users",+ headers={"X-API-Key": admin_key},+ )+ assert list_users.status_code == 200+++async def test_admin_cannot_register_root_role_user(+ lightweight_admin_client: httpx.AsyncClient,+):+ """ADMIN should not be able to mint a ROOT key via register_user."""+ acct = _uid()+ resp = await lightweight_admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice"},+ headers=root_headers(),+ )+ alice_key = resp.json()["result"]["user_key"]++ resp = await lightweight_admin_client.post(+ f"/api/v1/admin/accounts/{acct}/users",+ json={"user_id": "mallory-root", "role": "root"},+ headers={"X-API-Key": alice_key},+ )+ assert resp.status_code == 403+++async def test_admin_cannot_mint_root_key_that_reaches_root_only_endpoint(+ lightweight_admin_client: httpx.AsyncClient,+):+ """ADMIN registration must never yield a key that works on ROOT-only endpoints."""+ acct = _uid()+ resp = await lightweight_admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice"},+ headers=root_headers(),+ )+ alice_key = resp.json()["result"]["user_key"]++ resp = await lightweight_admin_client.post(+ f"/api/v1/admin/accounts/{acct}/users",+ json={"user_id": "mallory-root", "role": "root"},+ headers={"X-API-Key": alice_key},+ )+ assert resp.status_code == 403+ result = resp.json().get("result") or {}+ assert "user_key" not in result++ mallory_key = result.get("user_key")+ if mallory_key:+ root_only = await lightweight_admin_client.get(+ "/api/v1/admin/accounts",+ headers={"X-API-Key": mallory_key},+ )+ assert root_only.status_code == 403++async def test_admin_cannot_register_user_in_other_account(admin_client: httpx.AsyncClient):"""ADMIN cannot register users in another account."""acct = _uid()