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
fix(auth): enforce account user role boundaries (#3633)
Qin Haojieb047becb066c
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.mdindex 9d8d7385b..72c5cb385 100644--- a/docs/en/api/01-overview.md+++ b/docs/en/api/01-overview.md@@ -540,7 +540,7 @@ This catalog follows the routes actually mounted by the server. Each group headi| POST | `/api/v1/admin/accounts/{account_id}/users` | Register a user || GET | `/api/v1/admin/accounts/{account_id}/users` | List users || DELETE | `/api/v1/admin/accounts/{account_id}/users/{user_id}` | Remove a user |-| PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | Change a user role |+| PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | Promote a user to ADMIN || POST | `/api/v1/admin/accounts/{account_id}/users/{user_id}/key` | Regenerate a user key || GET | `/api/v1/privacy-configs` | List privacy configuration categories || GET | `/api/v1/privacy-configs/{category}` | List category targets |diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex 02c46f085..42f511bd1 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -23,7 +23,7 @@ For `/api/v1/admin/*`, `trusted` mode permits requests with no explicit identity| Register/remove users | Y | Y (own account) | N || List agents (deprecated, returns empty list) | Y | Y (own account) | N || Regenerate user key | Y | Y (own account) | N |-| Change user role | Y | N | N |+| Promote user to ADMIN | Y | Y (own account) | N |## CLI `--sudo` Option@@ -159,13 +159,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \"admin_user_id": "gateway-admin"}'-# Then promote it to root for cross-account admin operations-curl -X PUT http://localhost:1933/api/v1/admin/accounts/platform/users/gateway-admin/role \- -H "Content-Type: application/json" \- -H "X-API-Key: <root-key>" \- -d '{"role": "root"}'--# Then use in trusted mode+# Then use it in trusted mode; admin authorization comes from root_api_keycurl -X POST http://localhost:1933/api/v1/admin/accounts \-H "Content-Type: application/json" \-H "X-API-Key: <root-key>" \@@ -471,7 +465,7 @@ Register a new user in a workspace.|-----------|------|----------|---------|-------------|| account_id | str | Yes | - | Workspace ID || user_id | str | Yes | - | User ID |-| 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. |+| role | str | No | "user" | Role to assign. `ROOT` and same-account `ADMIN` may register `"user"` or `"admin"`. ROOT identity comes only from `server.root_api_key`. || seed | str | No | `null` | Optional deterministic API key seed. When set, the key secret is `sha256(user_id + "\0" + seed)` || user_config | object | No | `null` | Initial config for the new user. Currently supports `add_targets.resource_uri` and `add_targets.skill_uri` |@@ -779,10 +773,10 @@ ov --sudo admin remove-user acme bob#### 1. API Implementation Overview-Change a user's role (ROOT only).+Promote an account user to ADMIN. ROOT may operate on any account; ADMIN is limited to its own account.**Processing Flow:**-1. Verify requester has ROOT privileges+1. Verify the requester has ROOT or ADMIN privileges and keep ADMIN within its own account2. Call API Key Manager to update user role3. Return updated user info@@ -799,11 +793,11 @@ Change a user's role (ROOT only).|-----------|------|----------|---------|-------------|| account_id | str | Yes | - | Workspace ID || user_id | str | Yes | - | User ID |-| role | str | Yes | - | New role: "admin", "user", or "root" |+| role | str | Yes | - | Must be "admin" |**Notes:**-- Only ROOT can change user roles-- Role can be set to "admin", "user", or "root"+- ROOT and ADMIN can promote users to ADMIN; ADMIN is limited to its own account+- This endpoint cannot set "user" or "root"; ROOT comes only from `server.root_api_key`#### 3. Usage Examples@@ -1138,10 +1132,10 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \curl -X GET http://localhost:1933/api/v1/admin/accounts/acme/users \-H "X-API-Key: <alice-key>"-# Step 4: Change role (requires ROOT key)+# Step 4: Promote the user to admincurl -X PUT http://localhost:1933/api/v1/admin/accounts/acme/users/bob/role \-H "Content-Type: application/json" \- -H "X-API-Key: <root-key>" \+ -H "X-API-Key: <alice-key>" \-d '{"role": "admin"}'# Step 5: Regenerate keydiff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.mdindex 5be8474dc..b89a767b1 100644--- a/docs/en/guides/04-authentication.md+++ b/docs/en/guides/04-authentication.md@@ -102,7 +102,7 @@ Custom roles work with `require_role()` and `require_auth_role()` decorators out## Managing Accounts and Users-Normal requests in both `api_key` and `trusted` modes do not need Admin API as a prerequisite for ordinary reads, writes, search, or session access. Admin API is still the place to create accounts, register users, change roles, and issue or regenerate user keys.+Normal requests in both `api_key` and `trusted` modes do not need Admin API as a prerequisite for ordinary reads, writes, search, or session access. Admin API is still the place to create accounts, register users, promote users to admin, and issue or regenerate user keys.Use the root key to create accounts (workspaces) and users via the Admin API:@@ -136,13 +136,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \-H "Content-Type: application/json" \-d '{"account_id": "platform", "admin_user_id": "gateway-admin"}'-# Then promote it to root if it needs cross-account admin access-curl -X PUT http://localhost:1933/api/v1/admin/accounts/platform/users/gateway-admin/role \- -H "X-API-Key: your-secret-root-key" \- -H "Content-Type: application/json" \- -d '{"role": "root"}'--# Then, in trusted mode, use that identity to call Admin API+# Then use that identity in trusted mode; admin authorization comes from root_api_keycurl -X POST http://localhost:1933/api/v1/admin/accounts \-H "X-API-Key: your-secret-root-key" \-H "X-OpenViking-Account: platform" \@@ -285,7 +279,7 @@ Implications:- Trusted mode does not use the Admin API as a prerequisite for ordinary reads, writes, search, or session access.- Admin API remains available in trusted mode to upstreams authenticated with the configured `root_api_key`.- Trusted Admin API responses omit `user_key` from account creation and user registration results.-- `root` can create/delete accounts and change roles; `admin` can manage users inside its own account; `user` cannot call Admin API.+- `root` can create/delete accounts and promote users to admin; `admin` can manage and promote users inside its own account; `user` cannot call Admin API.- To use Admin API in trusted mode on non-localhost deployments, configure `root_api_key` and pass it with each admin request.**curl**@@ -363,7 +357,7 @@ curl http://localhost:1933/health| POST | `/api/v1/admin/accounts/{id}/users` | ROOT, ADMIN | Register user || GET | `/api/v1/admin/accounts/{id}/users` | ROOT, ADMIN | List users || DELETE | `/api/v1/admin/accounts/{id}/users/{uid}` | ROOT, ADMIN | Remove user |-| PUT | `/api/v1/admin/accounts/{id}/users/{uid}/role` | ROOT | Change user role |+| PUT | `/api/v1/admin/accounts/{id}/users/{uid}/role` | ROOT, ADMIN | Promote a user to ADMIN; ADMIN is limited to its own account || POST | `/api/v1/admin/accounts/{id}/users/{uid}/key` | ROOT, ADMIN | Regenerate user key |## Related Documentationdiff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.mdindex 9048e1ec0..72574eee3 100644--- a/docs/zh/api/01-overview.md+++ b/docs/zh/api/01-overview.md@@ -535,7 +535,7 @@ JSON 输出 - 错误:| POST | `/api/v1/admin/accounts/{account_id}/users` | 注册用户 || GET | `/api/v1/admin/accounts/{account_id}/users` | 列出用户 || DELETE | `/api/v1/admin/accounts/{account_id}/users/{user_id}` | 移除用户 |-| PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | 修改用户角色 |+| PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | 将用户提升为 ADMIN || POST | `/api/v1/admin/accounts/{account_id}/users/{user_id}/key` | 重新生成用户 Key || GET | `/api/v1/privacy-configs` | 列出隐私配置分类 || GET | `/api/v1/privacy-configs/{category}` | 列出分类目标 |diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex e7c3f189f..efd020e7c 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -23,7 +23,7 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a| 注册/移除用户 | Y | Y(本 account) | N || 列出 agents(已废弃,返回空列表) | Y | Y(本 account) | N || 重新生成 User Key | Y | Y(本 account) | N |-| 修改用户角色 | Y | N | N |+| 将用户提升为 ADMIN | Y | Y(本 account) | N |## CLI `--sudo` 选项@@ -160,13 +160,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \"admin_user_id": "gateway-admin"}'-# 然后提升为 root,以便执行跨 account 的管理操作-curl -X PUT http://localhost:1933/api/v1/admin/accounts/platform/users/gateway-admin/role \- -H "Content-Type: application/json" \- -H "X-API-Key: <root-key>" \- -d '{"role": "root"}'--# 然后在 trusted 模式下使用+# 然后在 trusted 模式下使用;管理权限来自 root_api_keycurl -X POST http://localhost:1933/api/v1/admin/accounts \-H "Content-Type: application/json" \-H "X-API-Key: <root-key>" \@@ -470,7 +464,7 @@ ov --sudo admin delete-account acme|------|------|------|--------|------|| account_id | str | 是 | - | 工作区 ID || user_id | str | 是 | - | 用户 ID |-| role | str | 否 | "user" | 要分配的角色。`ROOT` 和同 account 的 `ADMIN` 可直接注册 `"user"` 或 `"admin"`。`"root"` 必须通过专门的改角色接口分配。 |+| role | str | 否 | "user" | 要分配的角色。`ROOT` 和同 account 的 `ADMIN` 可直接注册 `"user"` 或 `"admin"`。ROOT 身份只来自 `server.root_api_key`。 || seed | str | 否 | `null` | 可选的确定性 API Key seed。传入后,key secret 为 `sha256(user_id + "\0" + seed)` || user_config | object | 否 | `null` | 新用户的初始配置。当前支持 `add_targets.resource_uri` 和 `add_targets.skill_uri` |@@ -777,10 +771,10 @@ ov --sudo admin remove-user acme bob#### 1. API 实现介绍-修改用户角色(仅 ROOT)。+将账户用户提升为 ADMIN。ROOT 可以操作任意账户;ADMIN 只能操作自己的账户。**处理流程:**-1. 验证请求者具有 ROOT 权限+1. 验证请求者具有 ROOT 或 ADMIN 权限,并限制 ADMIN 只能操作自己的账户2. 调用 API Key Manager 更新用户角色3. 返回更新后的用户信息@@ -797,11 +791,11 @@ ov --sudo admin remove-user acme bob|------|------|------|--------|------|| account_id | str | 是 | - | 工作区 ID || user_id | str | 是 | - | 用户 ID |-| role | str | 是 | - | 新角色:"admin" 或 "user" 或 "root" |+| role | str | 是 | - | 固定为 "admin" |**说明:**-- 只有 ROOT 可以修改用户角色-- 角色可以设置为 "admin"、"user" 或 "root"+- ROOT 和 ADMIN 可以将用户提升为 ADMIN;ADMIN 只能操作自己的账户+- 该接口不支持设置 "user" 或 "root";ROOT 身份只来自 `server.root_api_key`#### 3. 使用示例@@ -1136,10 +1130,10 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \curl -X GET http://localhost:1933/api/v1/admin/accounts/acme/users \-H "X-API-Key: <alice-key>"-# 步骤 4:修改角色(需要 ROOT key)+# 步骤 4:将用户提升为 admincurl -X PUT http://localhost:1933/api/v1/admin/accounts/acme/users/bob/role \-H "Content-Type: application/json" \- -H "X-API-Key: <root-key>" \+ -H "X-API-Key: <alice-key>" \-d '{"role": "admin"}'# 步骤 5:重新生成 keydiff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.mdindex 63f5f6a6b..454f1726b 100644--- a/docs/zh/guides/04-authentication.md+++ b/docs/zh/guides/04-authentication.md@@ -101,7 +101,7 @@ Role.register("operator", rank=1) # 权限介于 USER (0) 与 ADMIN (1) 之间## 管理账户和用户-普通读写、检索、会话等数据请求在 `api_key` 和 `trusted` 两种模式下都不依赖 Admin API 预注册。Admin API 仍然负责创建 account、注册用户、修改角色以及签发或重新生成 user key。+普通读写、检索、会话等数据请求在 `api_key` 和 `trusted` 两种模式下都不依赖 Admin API 预注册。Admin API 仍然负责创建 account、注册用户、将用户提升为 admin,以及签发或重新生成 user key。使用 root key 通过 Admin API 创建工作区和用户:@@ -135,13 +135,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \-H "Content-Type: application/json" \-d '{"account_id": "platform", "admin_user_id": "gateway-admin"}'-# 如果它需要跨 account 的管理权限,再提升为 root-curl -X PUT http://localhost:1933/api/v1/admin/accounts/platform/users/gateway-admin/role \- -H "X-API-Key: your-secret-root-key" \- -H "Content-Type: application/json" \- -d '{"role": "root"}'--# 然后,在 trusted 模式下使用该身份调用 Admin API+# 然后,在 trusted 模式下使用该身份调用 Admin API;管理权限来自 root_api_keycurl -X POST http://localhost:1933/api/v1/admin/accounts \-H "X-API-Key: your-secret-root-key" \-H "X-OpenViking-Account: platform" \@@ -283,7 +277,7 @@ Trusted 模式规则:- `trusted` 下的普通读写、检索、会话访问不需要先走 Admin API 注册流程- `trusted` 模式下,携带已配置 `root_api_key` 的受信上游可以调用 Admin API- `trusted` 模式下,创建 account 或注册用户的 Admin API 响应不会返回 `user_key`-- `root` 可以创建/删除 account 并修改角色;`admin` 可以管理自己 account 下的用户;`user` 不能调用 Admin API+- `root` 可以创建/删除 account 并提升用户为 admin;`admin` 可以管理自己 account 下的用户并将其提升为 admin;`user` 不能调用 Admin API- 非 localhost 部署要在 trusted 模式下使用 Admin API,需要配置 `root_api_key`,并在每个管理请求中携带它**curl**@@ -361,7 +355,7 @@ curl http://localhost:1933/health| POST | `/api/v1/admin/accounts/{id}/users` | ROOT, ADMIN | 注册用户 || GET | `/api/v1/admin/accounts/{id}/users` | ROOT, ADMIN | 列出用户 || DELETE | `/api/v1/admin/accounts/{id}/users/{uid}` | ROOT, ADMIN | 移除用户 |-| PUT | `/api/v1/admin/accounts/{id}/users/{uid}/role` | ROOT | 修改用户角色 |+| PUT | `/api/v1/admin/accounts/{id}/users/{uid}/role` | ROOT, ADMIN | 将用户提升为 ADMIN;ADMIN 仅限本账户 || POST | `/api/v1/admin/accounts/{id}/users/{uid}/key` | ROOT, ADMIN | 重新生成 user key |## 相关文档diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.pyindex 5a1910ee4..89eaf0818 100644--- a/openviking/server/api_keys/legacy.py+++ b/openviking/server/api_keys/legacy.py@@ -15,7 +15,11 @@ from argon2.exceptions import VerifyMismatchErrorfrom openviking.pyagfs import AGFSAlreadyExistsError, AGFSNotFoundError, AsyncAGFSClientfrom openviking.pyagfs.async_client import fs_ctx_from_agfs_path-from openviking.server.api_keys.models import AccountInfo, UserKeyEntry+from openviking.server.api_keys.models import (+ AccountInfo,+ UserKeyEntry,+ validate_account_user_role,+)from openviking.server.identity import ResolvedIdentity, Rolefrom openviking.storage.errors import LockAcquisitionError, ResourceBusyErrorfrom openviking.storage.viking_fs import VikingFS@@ -301,6 +305,7 @@ class LegacyAPIKeyManager:seed: Optional[str] = None,) -> str:"""Register a new user in an account. Returns the user's API key (legacy format)."""+ resolved_role = validate_account_user_role(role)# Validate user_id formatverr = validate_user_id(user_id)if verr:@@ -328,7 +333,7 @@ class LegacyAPIKeyManager:key_prefix = self._get_key_prefix(key)user_info = {- "role": role,+ "role": resolved_role,"key": stored_key,}if self._api_key_hashing_enabled:@@ -339,7 +344,7 @@ class LegacyAPIKeyManager:entry = UserKeyEntry(account_id=account_id,user_id=user_id,- role=Role(role),+ role=resolved_role,key_or_hash=stored_key,is_hashed=is_hashed,)@@ -455,13 +460,14 @@ class LegacyAPIKeyManager:async def set_role(self, account_id: str, user_id: str, role: str) -> None:"""Update a user's role."""+ resolved_role = validate_account_user_role(role)account = self._accounts.get(account_id)if account is None:raise NotFoundError(account_id, "account")if user_id not in account.users:raise NotFoundError(user_id, "user")- account.users[user_id]["role"] = role+ account.users[user_id]["role"] = resolved_role# Update role in prefix indexuser_info = account.users[user_id]@@ -475,7 +481,7 @@ class LegacyAPIKeyManager:if key_prefix in self._prefix_index:for entry in self._prefix_index[key_prefix]:if entry.account_id == account_id and entry.user_id == user_id:- entry.role = Role(role)+ entry.role = resolved_rolebreakawait self._save_users_json(account_id)diff --git a/openviking/server/api_keys/models.py b/openviking/server/api_keys/models.pyindex 84713295f..76c4ac7e0 100644--- a/openviking/server/api_keys/models.py+++ b/openviking/server/api_keys/models.py@@ -6,6 +6,19 @@ from dataclasses import dataclass, fieldfrom typing import Dictfrom openviking.server.identity import Role+from openviking_cli.exceptions import InvalidArgumentError, PermissionDeniedError+++def validate_account_user_role(role: str) -> Role:+ """Account users may be USER or ADMIN; ROOT is the configured server identity."""+ resolved_role = Role(role)+ if resolved_role == Role.ROOT:+ raise PermissionDeniedError(+ "Account users cannot be assigned ROOT; use server.root_api_key for ROOT access."+ )+ if resolved_role not in (Role.USER, Role.ADMIN):+ raise InvalidArgumentError("Account user role must be user or admin.")+ return resolved_role@dataclassdiff --git a/openviking/server/api_keys/new.py b/openviking/server/api_keys/new.pyindex f37595d51..1aed199be 100644--- a/openviking/server/api_keys/new.py+++ b/openviking/server/api_keys/new.py@@ -15,7 +15,11 @@ from openviking.server.api_keys.legacy import (LegacyAPIKeyManager,derive_seeded_api_key_secret,)-from openviking.server.api_keys.models import AccountInfo, UserKeyEntry+from openviking.server.api_keys.models import (+ AccountInfo,+ UserKeyEntry,+ validate_account_user_role,+)from openviking.server.identity import ResolvedIdentity, Rolefrom openviking.storage.viking_fs import VikingFSfrom openviking_cli.exceptions import InvalidArgumentError, UnauthenticatedError@@ -252,6 +256,7 @@ class NewAPIKeyManager:seed: Optional[str] = None,) -> str:"""Register a new user in an account. Returns the user's API key in new format."""+ resolved_role = validate_account_user_role(role)# Validate user_id formatverr = validate_user_id(user_id)if verr:@@ -281,7 +286,7 @@ class NewAPIKeyManager:key_prefix = self._legacy._get_key_prefix(key)user_info = {- "role": role,+ "role": resolved_role,"key": stored_key,}if self._legacy._api_key_hashing_enabled:@@ -292,7 +297,7 @@ class NewAPIKeyManager:entry = UserKeyEntry(account_id=account_id,user_id=user_id,- role=Role(role),+ role=resolved_role,key_or_hash=stored_key,is_hashed=is_hashed,)diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex 4726b3bc5..89e744331 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -7,6 +7,7 @@ import asynciofrom fastapi import APIRouter, Body, Depends, Path, Requestfrom pydantic import BaseModel+from openviking.server.api_keys.models import validate_account_user_rolefrom openviking.server.auth import (get_api_key_manager_or_raise,get_request_context,@@ -139,23 +140,6 @@ async def _write_initial_user_config(await write_user_config(service.viking_fs, user_ctx, user_config)-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.- """- resolved_role = Role(role)-- if resolved_role == Role.ROOT:- raise PermissionDeniedError(- "register_user cannot mint ROOT users; use the ROOT-only set_role endpoint instead."- )- return resolved_role--async def _run_legacy_migration_task(task_id: str,migration: LegacyDataMigration,@@ -330,7 +314,7 @@ 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)+ resolved_role = validate_account_user_role(body.role)service = get_service()user_ctx = RequestContext(user=UserIdentifier(account_id, body.user_id),@@ -391,7 +375,7 @@ async def remove_user(@router.put("/accounts/{account_id}/users/{user_id}/role")-@require_auth_root+@require_auth_root_or_adminasync def set_user_role(body: SetRoleRequest,request: Request,@@ -399,15 +383,18 @@ async def set_user_role(user_id: str = Path(..., description="User ID"),ctx: RequestContext = Depends(get_request_context),):- """Change a user's role (ROOT only)."""+ """Promote an account user to ADMIN."""+ _check_account_access(ctx, account_id)+ if body.role != Role.ADMIN:+ raise InvalidArgumentError("set_user_role only supports promotion to admin.")manager = _get_api_key_manager(request)- await manager.set_role(account_id, user_id, body.role)+ await manager.set_role(account_id, user_id, Role.ADMIN)return Response(status="ok",result={"account_id": account_id,"user_id": user_id,- "role": body.role,+ "role": Role.ADMIN,},)diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex b9e8c7100..47221d9b0 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -69,6 +69,12 @@ class _FakeAGFS:current = f"{current}/{part}" if current else f"/{part}"self._dirs.add(current)+ def pathlock_acquire_exact(self, ctx, path, timeout_secs=0.0, owner_lease_ref=None):+ return {"lease_ref": f"test:{path}"}++ def pathlock_release(self, ctx, lease):+ return None+class _FakeVikingFS:def __init__(self):@@ -467,7 +473,7 @@ async def test_root_can_register_admin_role_user(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."""+ """ROOT is the configured server identity, not an account user role."""acct = _uid()await lightweight_admin_client.post("/api/v1/admin/accounts",@@ -654,27 +660,45 @@ async def test_remove_user(admin_client: httpx.AsyncClient):# ---- Role management -----async def test_set_role(admin_client: httpx.AsyncClient):- """ROOT can change a user's role."""+async def test_admin_can_set_user_role_in_own_account(+ lightweight_admin_client: httpx.AsyncClient,+):+ """ADMIN can promote a user in its own account to ADMIN."""acct = _uid()- await admin_client.post(+ create_account = await lightweight_admin_client.post("/api/v1/admin/accounts",json={"account_id": acct, "admin_user_id": "alice"},headers=root_headers(),)- await admin_client.post(+ alice_key = create_account.json()["result"]["user_key"]+ create_user = await lightweight_admin_client.post(f"/api/v1/admin/accounts/{acct}/users",json={"user_id": "bob", "role": "user"},headers=root_headers(),)- resp = await admin_client.put(+ bob_key = create_user.json()["result"]["user_key"]++ resp = await lightweight_admin_client.put(f"/api/v1/admin/accounts/{acct}/users/bob/role",json={"role": "admin"},- headers=root_headers(),+ headers={"X-API-Key": alice_key},)assert resp.status_code == 200assert resp.json()["result"]["role"] == "admin"+ list_users = await lightweight_admin_client.get(+ f"/api/v1/admin/accounts/{acct}/users",+ headers={"X-API-Key": bob_key},+ )+ assert list_users.status_code == 200++ invalid_role = await lightweight_admin_client.put(+ f"/api/v1/admin/accounts/{acct}/users/bob/role",+ json={"role": "root"},+ headers={"X-API-Key": alice_key},+ )+ assert invalid_role.status_code == 400+async def test_regenerate_key(admin_client: httpx.AsyncClient):"""ROOT can regenerate a user's key."""@@ -1244,10 +1268,6 @@ async def test_trusted_mode_root_can_create_account(trusted_admin_app,):"""Trusted ROOT requests should be able to create accounts."""- # Set gateway-admin to ROOT role- manager = trusted_admin_app.state.api_key_manager- await manager.set_role("platform", "gateway-admin", "root")-acct = _uid()resp = await trusted_admin_client.post("/api/v1/admin/accounts",@@ -1273,10 +1293,6 @@ async def test_trusted_mode_admin_can_register_user_in_own_account(trusted_admin_app,):"""Trusted ADMIN requests should be able to manage users in their own account."""- # Set gateway-admin to ROOT role first- manager = trusted_admin_app.state.api_key_manager- await manager.set_role("platform", "gateway-admin", "root")-acct = _uid()create_resp = await trusted_admin_client.post("/api/v1/admin/accounts",@@ -1309,10 +1325,6 @@ async def test_trusted_mode_admin_can_list_users_with_account_only_in_url(trusted_admin_app,):"""Trusted ADMIN requests may omit X-OpenViking-Account when the URL already provides it."""- # Set gateway-admin to ROOT role first- manager = trusted_admin_app.state.api_key_manager- await manager.set_role("platform", "gateway-admin", "root")-acct = _uid()create_resp = await trusted_admin_client.post("/api/v1/admin/accounts",@@ -1342,10 +1354,6 @@ async def test_trusted_mode_admin_can_list_users_without_account_or_user_headerstrusted_admin_app,):"""Trusted admin routes may omit caller account/user when the route itself identifies the target."""- # Set gateway-admin to ROOT role first- manager = trusted_admin_app.state.api_key_manager- await manager.set_role("platform", "gateway-admin", "root")-acct = _uid()create_resp = await trusted_admin_client.post("/api/v1/admin/accounts",@@ -1371,10 +1379,6 @@ async def test_trusted_mode_admin_cannot_register_user_in_other_account(trusted_admin_app,):"""Trusted ADMIN requests should reject conflicting account identity."""- # Set gateway-admin to ROOT role first- manager = trusted_admin_app.state.api_key_manager- await manager.set_role("platform", "gateway-admin", "root")-acct = _uid()other = _uid()for account_id, admin_user_id in ((acct, "alice"), (other, "eve")):@@ -1407,11 +1411,8 @@ async def test_trusted_mode_admin_api_uses_trusted_gateway_identity(trusted_admin_app,):"""Trusted admin routes use the trusted gateway identity instead of tenant user role."""- # Set gateway-admin to ROOT role first- manager = trusted_admin_app.state.api_key_manager- await manager.set_role("platform", "gateway-admin", "root")-acct = _uid()+ manager = trusted_admin_app.state.api_key_managercreate_resp = await trusted_admin_client.post("/api/v1/admin/accounts",json={"account_id": acct, "admin_user_id": "alice"},@@ -1446,10 +1447,6 @@ async def test_trusted_mode_requires_matching_api_key_for_admin_api(trusted_admin_app,):"""Trusted admin requests should require the configured server API key when present."""- # Set gateway-admin to ROOT role first- manager = trusted_admin_app.state.api_key_manager- await manager.set_role("platform", "gateway-admin", "root")-resp = await trusted_admin_client.post("/api/v1/admin/accounts",json={"account_id": _uid(), "admin_user_id": "alice"},@@ -1467,10 +1464,6 @@ async def test_trusted_mode_create_account_lists_current_account_metadata(trusted_admin_app,):"""Trusted account creation should list the current account metadata shape."""- # Set gateway-admin to ROOT role first- manager = trusted_admin_app.state.api_key_manager- await manager.set_role("platform", "gateway-admin", "root")-acct = _uid()resp = await trusted_admin_client.post("/api/v1/admin/accounts",diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.pyindex c25177145..f023545be 100644--- a/tests/server/test_api_key_manager.py+++ b/tests/server/test_api_key_manager.py@@ -19,6 +19,7 @@ from openviking_cli.exceptions import (AlreadyExistsError,InvalidArgumentError,NotFoundError,+ PermissionDeniedError,UnauthenticatedError,)from openviking_cli.session.user_id import UserIdentifier@@ -305,6 +306,10 @@ async def test_set_role(manager: APIKeyManager):await manager.set_role(acct, "bob", "admin")assert manager.resolve(bob_key).role == Role.ADMIN+ with pytest.raises(PermissionDeniedError, match="server.root_api_key"):+ await manager.set_role(acct, "bob", Role.ROOT)+ assert manager.resolve(bob_key).role == Role.ADMIN+async def test_get_users(manager: APIKeyManager):"""get_users should list all users in an account."""