Skip to content

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

feat: support trusted admin tenant management (#1616)

Jiahui Zhou495b7a761609
diff --git a/crates/ov_cli/README.md b/crates/ov_cli/README.md
index 65030066e..a63c39b22 100644
--- a/crates/ov_cli/README.md
+++ b/crates/ov_cli/README.md
@@ -32,7 +32,7 @@ Create `~/.openviking/ovcli.conf`:
}
```
-`account` and `user` are optional with a regular user key because the server can derive them from the key. They are recommended when you use `trusted` auth mode or a root key against tenant-scoped APIs.
+`role` defaults to `user` and only applies in `trusted` mode. In `api_key` mode the server ignores it and derives the effective role from the API key. `account` and `user` are optional with a regular user key because the server can derive them from the key. They are recommended when you use `trusted` auth mode or a root key against tenant-scoped APIs.
## Quick Start
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.md
index 9d3f038e8..337e7648a 100644
--- a/docs/en/api/08-admin.md
+++ b/docs/en/api/08-admin.md
@@ -2,7 +2,12 @@
The Admin API manages accounts and users in a multi-tenant environment. It covers workspace (account) creation/deletion, user registration/removal, role changes, and API key regeneration.
-This API is for the `api_key` admin workflow. In `trusted` mode, ordinary requests do not use user-key registration, and Admin API calls return a permission error explaining that account/user management requires `api_key` mode with `root_api_key`.
+This API is available in both `api_key` and `trusted` deployments:
+- In `api_key` mode, the effective role is always derived from the presented API key.
+- In `trusted` mode, ordinary requests still do not use user-key registration, but a trusted gateway may call Admin API using a registered user with appropriate role (role is looked up from user registry).
+
+In `trusted` mode, role is determined by looking up `X-OpenViking-Account` + `X-OpenViking-User` from the user registry. If the user doesn't exist, role defaults to `USER`.
+For `/api/v1/admin/*`, trusted mode also permits requests with no explicit identity headers; those requests are treated as ROOT and are intended for trusted upstreams authenticated by the deployment's `root_api_key`.
## Roles and Permissions
@@ -32,6 +37,8 @@ Create a new workspace with its first admin user.
|-----------|------|----------|---------|-------------|
| account_id | str | Yes | - | Workspace ID |
| admin_user_id | str | Yes | - | First admin user ID |
+| isolate_user_scope_by_agent | bool | No | false | Further isolate user scope by agent |
+| isolate_agent_scope_by_user | bool | No | false | Further isolate agent scope by user |
**HTTP API**
@@ -49,6 +56,50 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \
}'
```
+**Trusted mode (registered gateway user)**
+
+```bash
+# First, register the gateway admin user in api_key mode
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: <root-key>" \
+ -d '{
+ "account_id": "platform",
+ "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
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: <root-key>" \
+ -H "X-OpenViking-Account: platform" \
+ -H "X-OpenViking-User: gateway-admin" \
+ -d '{
+ "account_id": "acme",
+ "admin_user_id": "alice",
+ "isolate_user_scope_by_agent": true,
+ "isolate_agent_scope_by_user": false
+ }'
+```
+
+**Trusted mode (root fallback without identity headers)**
+
+```bash
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: <root-key>" \
+ -d '{
+ "account_id": "acme",
+ "admin_user_id": "alice"
+ }'
+```
+
**CLI**
```bash
@@ -69,6 +120,8 @@ openviking admin create-account acme --admin alice
}
```
+In `trusted` mode, the same response omits `user_key`.
+
---
### list_accounts()
diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.md
index 90fd009ac..75f92feff 100644
--- a/docs/en/guides/04-authentication.md
+++ b/docs/en/guides/04-authentication.md
@@ -18,7 +18,7 @@ All API keys are plain random tokens with no embedded identity. The server resol
| Mode | `server.auth_mode` | Identity Source | Typical Use |
|------|--------------------|-----------------|-------------|
| API key mode | `"api_key"` | API key, with optional tenant headers for root requests | Standard multi-tenant deployment |
-| Trusted mode | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User` / optional `X-OpenViking-Agent` headers, plus `root_api_key` on non-localhost deployments | Behind a trusted gateway or internal network boundary |
+| Trusted mode | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User` / optional `X-OpenViking-Agent`, plus `root_api_key` on non-localhost deployments. Role is looked up from APIKeyManager if the user exists. | Behind a trusted gateway or internal network boundary |
| Dev mode | `"dev"` | No authentication, always ROOT | Local development only |
If `auth_mode` is not explicitly configured:
@@ -48,7 +48,7 @@ openviking-server
## Managing Accounts and Users
-This section applies to `api_key` mode. In `trusted` mode, normal requests do not use user-key registration or lookup.
+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 user keys.
Use the root key to create accounts (workspaces) and users via the Admin API:
@@ -68,6 +68,40 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \
# Returns: {"result": {"account_id": "acme", "user_id": "bob", "user_key": "..."}}
```
+Trusted deployments can also call Admin API through a trusted gateway. There are two supported patterns:
+
+- Present only the trusted deployment's `root_api_key`. For `/api/v1/admin/*`, the server treats the request as ROOT even without `X-OpenViking-Account` / `X-OpenViking-User`.
+- Present `X-OpenViking-Account` + `X-OpenViking-User` for a registered gateway user. In that case the server looks up the effective role from the user registry.
+
+Example using a registered gateway user:
+
+```bash
+# First, register the gateway admin (do this once in api_key mode)
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "X-API-Key: your-secret-root-key" \
+ -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
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "X-API-Key: your-secret-root-key" \
+ -H "X-OpenViking-Account: platform" \
+ -H "X-OpenViking-User: gateway-admin" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "account_id": "acme",
+ "admin_user_id": "alice",
+ "isolate_user_scope_by_agent": true,
+ "isolate_agent_scope_by_user": false
+ }'
+```
+
## Using API Keys (Client Side)
OpenViking accepts API keys via two headers:
@@ -208,7 +242,9 @@ Rules in trusted mode:
- Normal data access does not require user registration or user-key provisioning first.
- `X-OpenViking-Account` and `X-OpenViking-User` are required on tenant-scoped requests.
- `X-OpenViking-Agent` is optional and defaults to `default`.
-- Every trusted-mode request is resolved as `USER`. Identity comes from the headers, not from a root key or user key.
+- `/api/v1/admin/*` is special: when no explicit identity is provided, trusted mode treats the request as ROOT. This is intended for trusted upstreams that authenticate only with the deployment's root API key.
+- Role is determined by looking up the account/user in APIKeyManager. If the user exists, their configured role is used; otherwise it defaults to `USER`.
+- Trusted identity comes from the headers, not from a user key. If `root_api_key` is configured, it still acts as proof that the caller is an approved trusted upstream.
- If `root_api_key` is also configured, every request must still provide a matching API key.
- Only expose this mode behind a trusted network boundary or an identity-injecting gateway.
@@ -216,7 +252,10 @@ Implications:
- Trusted mode is not development mode.
- Trusted mode does not use the Admin API as a prerequisite for ordinary reads, writes, search, or session access.
-- Account creation, user registration, role changes, and key regeneration remain part of the `api_key` admin workflow. If you call Admin API endpoints while the server runs in `trusted` mode, the server returns a permission error explaining that admin registration is unavailable in `trusted` mode and that you should switch to `api_key` mode with `root_api_key` for account/user management.
+- Admin API remains available in trusted mode for users that have been registered with appropriate roles (root/admin).
+- 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.
+- To use Admin API in trusted mode, first register the gateway's service account with the appropriate role using the Admin API in api_key mode.
**curl**
@@ -275,7 +314,7 @@ Or explicitly:
| ADMIN | Own account | Regular operations + manage users in own account |
| USER | Own account | Regular operations (ls, read, find, sessions, etc.) |
-In `trusted` mode, requests are resolved as `USER`, so the usual ROOT/ADMIN registration flow does not apply to ordinary traffic.
+In `trusted` mode, ordinary tenant requests default to `USER` unless the account/user is registered with a higher role. Admin routes also allow a trusted ROOT fallback when no explicit identity is provided.
## Unauthenticated Endpoints
diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.md
index ba2af9d16..dddc6f676 100644
--- a/docs/zh/api/08-admin.md
+++ b/docs/zh/api/08-admin.md
@@ -2,7 +2,12 @@
Admin API 用于多租户环境下的账户和用户管理。包括工作区(account)的创建与删除、用户注册与移除、角色变更、API Key 重新生成。
-该 API 只适用于 `api_key` 模式下的管理链路。在 `trusted` 模式里,普通请求不使用 user key 注册流程;如果去调用 Admin API,服务端会返回明确权限错误,说明账户/用户管理需要切换到配置了 `root_api_key` 的 `api_key` 模式。
+该 API 适用于 `api_key` 和 `trusted` 两种模式下的管理链路:
+- 在 `api_key` 模式下,角色始终从 API Key 推导。
+- 在 `trusted` 模式下,普通请求仍然不依赖 user key 注册流程;但受信任网关可以使用已注册且具有适当角色的用户调用 Admin API(角色从用户注册表查询)。
+
+在 `trusted` 模式下,角色通过查询 `X-OpenViking-Account` + `X-OpenViking-User` 从用户注册表确定。如果用户不存在,角色默认为 `USER`。
+对于 `/api/v1/admin/*`,`trusted` 模式还允许不携带显式身份头;这类请求会被视为 ROOT,适用于仅通过部署级 `root_api_key` 认证的受信上游。
## 角色与权限
@@ -32,6 +37,8 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a
|------|------|------|--------|------|
| account_id | str | 是 | - | 工作区 ID |
| admin_user_id | str | 是 | - | 首个管理员用户 ID |
+| isolate_user_scope_by_agent | bool | 否 | false | 是否按 agent 进一步隔离 user scope |
+| isolate_agent_scope_by_user | bool | 否 | false | 是否按 user 进一步隔离 agent scope |
**HTTP API**
@@ -45,7 +52,9 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \
-H "X-API-Key: <root-key>" \
-d '{
"account_id": "acme",
- "admin_user_id": "alice"
+ "admin_user_id": "alice",
+ "isolate_user_scope_by_agent": true,
+ "isolate_agent_scope_by_user": false
}'
```
@@ -63,12 +72,58 @@ openviking admin create-account acme --admin alice
"result": {
"account_id": "acme",
"admin_user_id": "alice",
- "user_key": "7f3a9c1e..."
+ "user_key": "7f3a9c1e...",
+ "isolate_user_scope_by_agent": true,
+ "isolate_agent_scope_by_user": false
},
"time": 0.1
}
```
+`trusted` 模式示例:
+
+```bash
+# 首先,在 api_key 模式下注册网关管理员用户
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: <root-key>" \
+ -d '{
+ "account_id": "platform",
+ "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 模式下使用
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: <root-key>" \
+ -H "X-OpenViking-Account: platform" \
+ -H "X-OpenViking-User: gateway-admin" \
+ -d '{
+ "account_id": "acme",
+ "admin_user_id": "alice",
+ "isolate_user_scope_by_agent": true,
+ "isolate_agent_scope_by_user": false
+ }'
+```
+
+`trusted` 模式也支持“不带身份头”的 ROOT 回退写法:
+
+```bash
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: <root-key>" \
+ -d '{
+ "account_id": "acme",
+ "admin_user_id": "alice"
+ }'
+```
+
---
### list_accounts()
@@ -105,6 +160,8 @@ openviking admin list-accounts
}
```
+在 `trusted` 模式下,同类响应不会返回 `user_key`。
+
---
### delete_account()
diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.md
index 903df6b30..79943af9f 100644
--- a/docs/zh/guides/04-authentication.md
+++ b/docs/zh/guides/04-authentication.md
@@ -18,7 +18,7 @@ OpenViking 使用两层 API Key 体系:
| 模式 | `server.auth_mode` | 身份来源 | 典型使用场景 |
|------|--------------------|----------|--------------|
| API Key 模式 | `"api_key"` | API Key,root 请求可附带租户请求头 | 标准多租户部署 |
-| Trusted 模式 | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User` / 可选 `X-OpenViking-Agent` 请求头;非 localhost 部署还必须配置 `root_api_key` | 部署在受信网关或内网边界之后 |
+| Trusted 模式 | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User` / 可选 `X-OpenViking-Agent`;非 localhost 部署还必须配置 `root_api_key`。角色会从 APIKeyManager 查询(如果用户存在) | 部署在受信网关或内网边界之后 |
| Dev 模式 | `"dev"` | 无认证,始终为 ROOT | 仅限本地开发 |
如果未显式配置 `auth_mode`:
@@ -48,7 +48,7 @@ openviking-server
## 管理账户和用户
-本节只适用于 `api_key` 模式。在 `trusted` 模式下,普通请求不会走 user key 的注册或查找链路。
+普通读写、检索、会话等数据请求在 `api_key` 和 `trusted` 两种模式下都不依赖 Admin API 预注册。Admin API 仍然负责创建 account、注册用户、修改角色以及签发 user key。
使用 root key 通过 Admin API 创建工作区和用户:
@@ -68,6 +68,40 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \
# 返回: {"result": {"account_id": "acme", "user_id": "bob", "user_key": "..."}}
```
+受信部署也可以通过受信网关调用 Admin API,目前支持两种方式:
+
+- 只携带受信部署自身的 `root_api_key`。对于 `/api/v1/admin/*`,即使没有 `X-OpenViking-Account` / `X-OpenViking-User`,服务端也会将请求视为 ROOT。
+- 携带 `X-OpenViking-Account` + `X-OpenViking-User`,并使用一个已注册的网关用户。此时服务端会从用户注册表查询该身份的实际角色。
+
+下面是“已注册网关用户”这种方式的示例:
+
+```bash
+# 首先,注册网关管理员(在 api_key 模式下执行一次)
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "X-API-Key: your-secret-root-key" \
+ -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
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "X-API-Key: your-secret-root-key" \
+ -H "X-OpenViking-Account: platform" \
+ -H "X-OpenViking-User: gateway-admin" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "account_id": "acme",
+ "admin_user_id": "alice",
+ "isolate_user_scope_by_agent": true,
+ "isolate_agent_scope_by_user": false
+ }'
+```
+
## 客户端使用
OpenViking 支持两种方式传递 API Key:
@@ -208,7 +242,9 @@ Trusted 模式规则:
- 普通数据访问不需要先注册 user key,也不依赖 user key 分发流程
- 租户级请求必须包含 `X-OpenViking-Account` 和 `X-OpenViking-User`
- `X-OpenViking-Agent` 可选,缺省为 `default`
-- 每个 trusted 请求都会被解析成 `USER`,身份完全来自请求头,而不是 root key 或 user key
+- `/api/v1/admin/*` 是特例:如果没有显式身份,trusted 模式会将请求视为 ROOT,用于只通过部署级 root API key 认证的受信上游
+- 角色通过在 APIKeyManager 中查找 account/user 确定。如果用户存在,使用其配置的角色;否则默认为 `USER`
+- trusted 身份完全来自请求头,而不是 user key;如果同时配置了 `root_api_key`,它仍然只是“这个上游是被允许的 trusted 调用方”的证明
- 如果同时配置了 `root_api_key`,每个请求仍然必须带匹配的 API Key
- 只应部署在受信网络边界之后,或由身份注入网关统一转发
@@ -216,7 +252,10 @@ Trusted 模式规则:
- `trusted` 不是开发模式
- `trusted` 下的普通读写、检索、会话访问不需要先走 Admin API 注册流程
-- 创建 account、注册用户、修改角色、重新生成 key 仍然属于 `api_key` 模式下的管理链路;如果服务端运行在 `trusted` 模式而你去调用这些 Admin API,服务端会返回明确错误,说明 `trusted` 不支持这类注册式管理,并提示切换到配置了 `root_api_key` 的 `api_key` 模式
+- `trusted` 模式下,已注册并具有适当角色(root/admin)的用户仍然可以调用 Admin API
+- `trusted` 模式下,创建 account 或注册用户的 Admin API 响应不会返回 `user_key`
+- `root` 可以创建/删除 account 并修改角色;`admin` 可以管理自己 account 下的用户;`user` 不能调用 Admin API
+- 要在 trusted 模式下使用 Admin API,首先需要在 api_key 模式下使用 Admin API 注册网关服务账户并赋予适当角色
**curl**
@@ -275,7 +314,7 @@ client = ov.SyncHTTPClient(
| ADMIN | 所属 account | 常规操作 + 管理所属 account 的用户 |
| USER | 所属 account | 常规操作(ls、read、find、sessions 等) |
-在 `trusted` 模式下,请求角色会解析为 `USER`,因此普通流量不适用 ROOT/ADMIN 的注册式管理语义。
+在 `trusted` 模式下,普通租户请求默认会解析为 `USER`;如果该 account/user 已注册更高角色,则使用注册角色。对于 Admin 路由,在没有显式身份时还支持 trusted ROOT 回退。
## 无需认证的端点
diff --git a/openviking/server/api_keys.py b/openviking/server/api_keys.py
index 493d6c0ac..361690733 100644
--- a/openviking/server/api_keys.py
+++ b/openviking/server/api_keys.py
@@ -529,6 +529,19 @@ class APIKeyManager:
return False
return user_id in account.users
+ def get_user_role(self, account_id: str, user_id: str) -> Role:
+ """Return the role of the given user in the given account.
+
+ Returns Role.USER if the account or user doesn't exist.
+ """
+ account = self._accounts.get(account_id)
+ if account is None:
+ return Role.USER
+ user = account.users.get(user_id)
+ if user is None:
+ return Role.USER
+ return Role(user.get("role", "user"))
+
# ---- internal helpers ----
def _generate_api_key(self) -> str:
diff --git a/openviking/server/app.py b/openviking/server/app.py
index a7d444239..a9cf57212 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -81,11 +81,7 @@ def create_app(
# Initialize APIKeyManager after service (needs VikingFS)
effective_auth_mode = config.get_effective_auth_mode()
- if (
- effective_auth_mode == AuthMode.API_KEY
- and config.root_api_key
- and config.root_api_key != ""
- ):
+ if config.root_api_key and config.root_api_key != "":
api_key_manager = APIKeyManager(
root_key=config.root_api_key,
viking_fs=service.viking_fs,
diff --git a/openviking/server/auth.py b/openviking/server/auth.py
index eaa1120cb..2b18aabb7 100644
--- a/openviking/server/auth.py
+++ b/openviking/server/auth.py
@@ -25,6 +25,7 @@ _ROOT_IMPLICIT_TENANT_ALLOWED_PREFIXES = (
"/api/v1/admin",
"/api/v1/observer",
)
+_TRUSTED_RELAXED_IDENTITY_PREFIXES = ("/api/v1/admin",)
def _auth_mode(request: Request) -> AuthMode:
@@ -48,6 +49,12 @@ def _root_request_requires_explicit_tenant(path: str) -> bool:
return True
+def _trusted_request_requires_explicit_identity(path: str) -> bool:
+ if path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES):
+ return False
+ return True
+
+
def _configured_root_api_key(request: Request) -> Optional[str]:
config = getattr(request.app.state, "config", None)
key = getattr(config, "root_api_key", None)
@@ -66,6 +73,35 @@ def _extract_api_key(x_api_key: Optional[str], authorization: Optional[str]) ->
return None
+def _normalize_header_value(value: Optional[str]) -> Optional[str]:
+ if isinstance(value, str):
+ normalized = value.strip()
+ return normalized or None
+ return None
+
+
+def _normalize_request_value(value: object) -> Optional[str]:
+ if isinstance(value, str):
+ normalized = value.strip()
+ return normalized or None
+ return None
+
+
+def _explicit_identity_from_request(request: Request) -> tuple[Optional[str], Optional[str]]:
+ path_params = getattr(request, "path_params", {}) or {}
+ query_params = request.query_params
+
+ account_id = _normalize_request_value(path_params.get("account_id"))
+ if account_id is None:
+ account_id = _normalize_request_value(query_params.get("account_id"))
+
+ user_id = _normalize_request_value(path_params.get("user_id"))
+ if user_id is None:
+ user_id = _normalize_request_value(query_params.get("user_id"))
+
+ return account_id, user_id
+
+
async def resolve_identity(
request: Request,
x_api_key: Optional[str] = Header(None),
@@ -78,11 +114,14 @@ async def resolve_identity(
Strategy:
- dev mode: no authentication, return implicit ROOT/default identity
- - trusted mode: trust explicit account/user headers and return USER identity
+ - trusted mode: trust explicit account/user headers, look up role from APIKeyManager
- api_key mode: resolve via APIKeyManager (root key first, then user key index)
"""
auth_mode = _auth_mode(request)
api_key_manager = getattr(request.app.state, "api_key_manager", None)
+ x_openviking_account = _normalize_header_value(x_openviking_account)
+ x_openviking_user = _normalize_header_value(x_openviking_user)
+ x_openviking_agent = _normalize_header_value(x_openviking_agent)
api_key = _extract_api_key(x_api_key, authorization)
if auth_mode == AuthMode.DEV:
@@ -105,14 +144,52 @@ async def resolve_identity(
raise UnauthenticatedError(
"Invalid API Key in trusted mode with Root API Key enabled."
)
- if not x_openviking_account or not x_openviking_user:
+ explicit_account_id, explicit_user_id = _explicit_identity_from_request(request)
+ if (
+ x_openviking_account
+ and explicit_account_id
+ and x_openviking_account != explicit_account_id
+ ):
+ raise InvalidArgumentError(
+ "Trusted mode X-OpenViking-Account must match explicit account_id in the URL."
+ )
+ if x_openviking_user and explicit_user_id and x_openviking_user != explicit_user_id:
raise InvalidArgumentError(
- "Trusted mode requests must include X-OpenViking-Account and X-OpenViking-User."
+ "Trusted mode X-OpenViking-User must match explicit user_id in the URL."
)
+
+ effective_account_id = explicit_account_id or x_openviking_account
+ effective_user_id = explicit_user_id or x_openviking_user
+
+ # Check if this is an admin path without identity
+ is_admin_path = request.url.path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES)
+ if is_admin_path:
+ return ResolvedIdentity(
+ role=Role.ROOT,
+ account_id="trusted",
+ user_id="trusted",
+ agent_id=x_openviking_agent or "default",
+ )
+
+ if _trusted_request_requires_explicit_identity(request.url.path):
+ missing_fields = []
+ if not effective_account_id:
+ missing_fields.append("X-OpenViking-Account or explicit account_id in the URL")
+ if not effective_user_id:
+ missing_fields.append("X-OpenViking-User or explicit user_id in the URL")
+ if missing_fields:
+ raise InvalidArgumentError(
+ "Trusted mode requests must include " + " and ".join(missing_fields) + "."
+ )
+
+ trusted_role = Role.USER
+ if api_key_manager and effective_account_id and effective_user_id:
+ trusted_role = api_key_manager.get_user_role(effective_account_id, effective_user_id)
+
return ResolvedIdentity(
- role=Role.USER,
- account_id=x_openviking_account,
- user_id=x_openviking_user,
+ role=trusted_role,
+ account_id=effective_account_id or "trusted",
+ user_id=effective_user_id or "trusted",
agent_id=x_openviking_agent or "default",
)
@@ -174,10 +251,15 @@ async def get_request_context(
"and X-OpenViking-User headers. Use a user key for regular data access."
)
- if auth_mode == AuthMode.TRUSTED and not identity.account_id:
- raise InvalidArgumentError("Trusted mode requests must include X-OpenViking-Account.")
- if auth_mode == AuthMode.TRUSTED and not identity.user_id:
- raise InvalidArgumentError("Trusted mode requests must include X-OpenViking-User.")
+ if auth_mode == AuthMode.TRUSTED:
+ is_admin_path = path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES)
+ if not is_admin_path:
+ if not identity.account_id:
+ raise InvalidArgumentError(
+ "Trusted mode requests must include X-OpenViking-Account."
+ )
+ if not identity.user_id:
+ raise InvalidArgumentError("Trusted mode requests must include X-OpenViking-User.")
ctx = RequestContext(
user=UserIdentifier(
@@ -188,7 +270,7 @@ async def get_request_context(
role=identity.role,
namespace_policy=(
api_key_manager.get_account_policy(identity.account_id)
- if api_key_manager is not None
+ if api_key_manager is not None and hasattr(api_key_manager, "get_account_policy")
else identity.namespace_policy
),
)
@@ -222,12 +304,6 @@ require_admin = require_role(Role.ADMIN)
require_user = require_role(Role.USER)
-_TRUSTED_MODE_ADMIN_API_MESSAGE = (
- "Admin API is unavailable in trusted mode. In trusted mode, each request is resolved as USER "
- "from X-OpenViking-Account/X-OpenViking-User headers and does not use user-key "
- "registration. Switch to api_key mode with root_api_key for account and user management."
-)
-
_DEV_MODE_ADMIN_API_MESSAGE = (
"Admin API requires api_key mode with root_api_key configured. Development mode does not "
'support account or user management. You should set server.auth_mode = "api_key" in ov.conf'
@@ -267,13 +343,13 @@ def require_auth_role(*allowed_roles: Role):
if ctx is None:
raise RuntimeError("require_auth_role decorator requires 'ctx' parameter")
- config = getattr(request.app.state, "config", None)
- auth_mode = getattr(config, "auth_mode", AuthMode.API_KEY)
- if auth_mode == AuthMode.TRUSTED:
- raise PermissionDeniedError(_TRUSTED_MODE_ADMIN_API_MESSAGE)
+ # Check auth mode
+ auth_mode = _auth_mode(request)
+ # In trusted mode, we allow access even without api_key_manager
+ # as long as the role requirement is satisfied
manager = getattr(request.app.state, "api_key_manager", None)
- if manager is None:
+ if manager is None and auth_mode != AuthMode.TRUSTED:
raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)
if ctx.role not in allowed_roles:
@@ -344,6 +420,7 @@ def get_api_key_manager_or_raise(request: Request):
PermissionDeniedError: In dev mode without API key manager.
"""
manager = getattr(request.app.state, "api_key_manager", None)
- if manager is None:
+ auth_mode = _auth_mode(request)
+ if manager is None and auth_mode != AuthMode.TRUSTED:
raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)
return manager
diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.py
index 9cac4cbe7..497386dc3 100644
--- a/openviking/server/routers/admin.py
+++ b/openviking/server/routers/admin.py
@@ -11,6 +11,7 @@ from openviking.server.auth import (
require_auth_root,
require_auth_root_or_admin,
)
+from openviking.server.config import ServerConfig
from openviking.server.dependencies import get_service
from openviking.server.identity import AccountNamespacePolicy, RequestContext, Role
from openviking.server.models import Response
@@ -45,6 +46,13 @@ def _get_api_key_manager(request: Request):
return get_api_key_manager_or_raise(request)
+def _should_expose_user_key(request: Request) -> bool:
+ config = getattr(request.app.state, "config", None)
+ if not isinstance(config, ServerConfig):
+ return True
+ return config.get_effective_auth_mode() != "trusted"
+
+
def _check_account_access(ctx: RequestContext, account_id: str) -> None:
"""ADMIN can only operate on their own account."""
if ctx.role == Role.ADMIN and ctx.account_id != account_id:
@@ -80,15 +88,14 @@ async def create_account(
)
await service.initialize_account_directories(account_ctx)
await service.initialize_user_directories(account_ctx)
- return Response(
- status="ok",
- result={
- "account_id": body.account_id,
- "admin_user_id": body.admin_user_id,
- "user_key": user_key,
- **policy.to_dict(),
- },
- )
+ result = {
+ "account_id": body.account_id,
+ "admin_user_id": body.admin_user_id,
+ **policy.to_dict(),
+ }
+ if _should_expose_user_key(request):
+ result["user_key"] = user_key
+ return Response(status="ok", result=result)
@router.get("/accounts")
@@ -169,14 +176,13 @@ async def register_user(
namespace_policy=manager.get_account_policy(account_id),
)
await service.initialize_user_directories(user_ctx)
- return Response(
- status="ok",
- result={
- "account_id": account_id,
- "user_id": body.user_id,
- "user_key": user_key,
- },
- )
+ result = {
+ "account_id": account_id,
+ "user_id": body.user_id,
+ }
+ if _should_expose_user_key(request):
+ result["user_key"] = user_key
+ return Response(status="ok", result=result)
@router.get("/accounts/{account_id}/users")
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index 9f7ed9de9..9cf17724b 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -57,6 +57,21 @@ def root_headers():
return {"X-API-Key": ROOT_KEY}
+def trusted_headers(
+ *,
+ account: str,
+ user: str,
+ include_api_key: bool = False,
+):
+ headers = {
+ "X-OpenViking-Account": account,
+ "X-OpenViking-User": user,
+ }
+ if include_api_key:
+ headers["X-API-Key"] = ROOT_KEY
+ return headers
+
+
# ---- Account CRUD ----
@@ -348,9 +363,15 @@ async def test_no_auth_admin_api_returns_401(admin_client: httpx.AsyncClient):
@pytest_asyncio.fixture(scope="function")
async def trusted_admin_app(admin_service):
- config = ServerConfig(auth_mode="trusted")
+ config = ServerConfig(auth_mode="trusted", root_api_key=ROOT_KEY)
app = create_app(config=config, service=admin_service)
set_service(admin_service)
+ manager = APIKeyManager(root_key=ROOT_KEY, viking_fs=admin_service.viking_fs)
+ await manager.load()
+ # Create test users for trusted mode tests if they don't exist
+ if "platform" not in manager._accounts:
+ await manager.create_account("platform", "gateway-admin")
+ app.state.api_key_manager = manager
return app
@@ -361,41 +382,260 @@ async def trusted_admin_client(trusted_admin_app):
yield c
-async def test_trusted_mode_create_account_returns_mode_specific_error(
+async def test_trusted_mode_root_can_create_account(
trusted_admin_client: httpx.AsyncClient,
+ trusted_admin_app,
):
- """Trusted mode should explain why account management is unavailable."""
+ """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",
- json={"account_id": _uid(), "admin_user_id": "alice"},
- headers={
- "X-OpenViking-Account": "acme",
- "X-OpenViking-User": "alice",
+ json={
+ "account_id": acct,
+ "admin_user_id": "alice",
+ "isolate_user_scope_by_agent": True,
+ "isolate_agent_scope_by_user": True,
},
+ headers=trusted_headers(
+ account="platform",
+ user="gateway-admin",
+ include_api_key=True,
+ ),
)
- assert resp.status_code == 403
+ assert resp.status_code == 200
body = resp.json()
- assert body["error"]["code"] == "PERMISSION_DENIED"
- assert "trusted mode" in body["error"]["message"].lower()
- assert "user-key registration" in body["error"]["message"].lower()
- assert "api_key mode" in body["error"]["message"].lower()
+ assert body["result"]["account_id"] == acct
+ assert body["result"]["admin_user_id"] == "alice"
+ assert body["result"]["isolate_user_scope_by_agent"] is True
+ assert body["result"]["isolate_agent_scope_by_user"] is True
+ assert "user_key" not in body["result"]
-async def test_trusted_mode_register_user_returns_mode_specific_error(
+async def test_trusted_mode_admin_can_register_user_in_own_account(
trusted_admin_client: httpx.AsyncClient,
+ trusted_admin_app,
):
- """Trusted mode should explain why user registration is unavailable."""
+ """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",
+ json={"account_id": acct, "admin_user_id": "alice"},
+ headers=trusted_headers(
+ account="platform",
+ user="gateway-admin",
+ include_api_key=True,
+ ),
+ )
+ assert create_resp.status_code == 200
+
resp = await trusted_admin_client.post(
- "/api/v1/admin/accounts/acme/users",
+ f"/api/v1/admin/accounts/{acct}/users",
json={"user_id": "bob", "role": "user"},
+ headers=trusted_headers(
+ account=acct,
+ user="alice",
+ include_api_key=True,
+ ),
+ )
+ assert resp.status_code == 200
+ assert resp.json()["result"]["account_id"] == acct
+ assert resp.json()["result"]["user_id"] == "bob"
+ assert "user_key" not in resp.json()["result"]
+
+
+async def test_trusted_mode_admin_can_list_users_with_account_only_in_url(
+ trusted_admin_client: httpx.AsyncClient,
+ 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",
+ json={"account_id": acct, "admin_user_id": "alice"},
+ headers=trusted_headers(
+ account="platform",
+ user="gateway-admin",
+ include_api_key=True,
+ ),
+ )
+ assert create_resp.status_code == 200
+
+ resp = await trusted_admin_client.get(
+ f"/api/v1/admin/accounts/{acct}/users",
+ headers={
+ "X-API-Key": ROOT_KEY,
+ "X-OpenViking-User": "alice",
+ "X-OpenViking-Account": acct,
+ },
+ )
+ assert resp.status_code == 200
+ assert any(user["user_id"] == "alice" for user in resp.json()["result"])
+
+
+async def test_trusted_mode_admin_can_list_users_without_account_or_user_headers(
+ trusted_admin_client: httpx.AsyncClient,
+ trusted_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",
+ json={"account_id": acct, "admin_user_id": "alice"},
+ headers=trusted_headers(
+ account="platform",
+ user="gateway-admin",
+ include_api_key=True,
+ ),
+ )
+ assert create_resp.status_code == 200
+
+ resp = await trusted_admin_client.get(
+ f"/api/v1/admin/accounts/{acct}/users",
headers={
- "X-OpenViking-Account": "acme",
+ "X-API-Key": ROOT_KEY,
+ "X-OpenViking-Account": acct,
"X-OpenViking-User": "alice",
},
)
+ assert resp.status_code == 200
+ assert any(user["user_id"] == "alice" for user in resp.json()["result"])
+
+
+async def test_trusted_mode_admin_cannot_register_user_in_other_account(
+ trusted_admin_client: httpx.AsyncClient,
+ 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")):
+ create_resp = await trusted_admin_client.post(
+ "/api/v1/admin/accounts",
+ json={"account_id": account_id, "admin_user_id": admin_user_id},
+ headers=trusted_headers(
+ account="platform",
+ user="gateway-admin",
+ include_api_key=True,
+ ),
+ )
+ assert create_resp.status_code == 200
+
+ resp = await trusted_admin_client.post(
+ f"/api/v1/admin/accounts/{other}/users",
+ json={"user_id": "bob", "role": "user"},
+ headers=trusted_headers(
+ account=acct,
+ user="alice",
+ include_api_key=True,
+ ),
+ )
+ assert resp.status_code == 400
+ assert resp.json()["error"]["code"] == "INVALID_ARGUMENT"
+
+
+async def test_trusted_mode_user_cannot_call_admin_api(
+ trusted_admin_client: httpx.AsyncClient,
+ trusted_admin_app,
+):
+ """Trusted USER requests should still be denied by Admin API role checks."""
+ # 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",
+ json={"account_id": acct, "admin_user_id": "alice"},
+ headers=trusted_headers(
+ account="platform",
+ user="gateway-admin",
+ include_api_key=True,
+ ),
+ )
+ assert create_resp.status_code == 200
+
+ # Change alice to USER role
+ await manager.set_role(acct, "alice", "user")
+
+ resp = await trusted_admin_client.post(
+ f"/api/v1/admin/accounts/{acct}/users",
+ json={"user_id": "bob", "role": "user"},
+ headers=trusted_headers(
+ account=acct,
+ user="alice",
+ include_api_key=True,
+ ),
+ )
assert resp.status_code == 403
- body = resp.json()
- assert body["error"]["code"] == "PERMISSION_DENIED"
- assert "trusted mode" in body["error"]["message"].lower()
- assert "resolved as user" in body["error"]["message"].lower()
- assert "root_api_key" in body["error"]["message"].lower()
+
+
+async def test_trusted_mode_requires_matching_api_key_for_admin_api(
+ trusted_admin_client: httpx.AsyncClient,
+ 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"},
+ headers=trusted_headers(
+ account="platform",
+ user="gateway-admin",
+ include_api_key=False,
+ ),
+ )
+ assert resp.status_code == 401
+
+
+async def test_trusted_mode_create_account_persists_namespace_policy(
+ trusted_admin_client: httpx.AsyncClient,
+ trusted_admin_app,
+):
+ """Trusted account creation should persist namespace policy for later requests."""
+ # 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",
+ json={
+ "account_id": acct,
+ "admin_user_id": "alice",
+ "isolate_user_scope_by_agent": True,
+ "isolate_agent_scope_by_user": False,
+ },
+ headers=trusted_headers(
+ account="platform",
+ user="gateway-admin",
+ include_api_key=True,
+ ),
+ )
+ assert resp.status_code == 200
+
+ manager = trusted_admin_app.state.api_key_manager
+ assert manager.get_account_policy(acct).isolate_user_scope_by_agent is True
+ assert manager.get_account_policy(acct).isolate_agent_scope_by_user is False
diff --git a/tests/server/test_auth.py b/tests/server/test_auth.py
index b8e7c9041..cc8cb8096 100644
--- a/tests/server/test_auth.py
+++ b/tests/server/test_auth.py
@@ -55,6 +55,7 @@ def _make_request(
scope = {
"type": "http",
"path": path,
+ "query_string": b"",
"headers": raw_headers,
"app": app,
}
@@ -127,6 +128,21 @@ def _build_auth_http_test_app(
"""Expose a tenant-scoped debug route for auth regression tests."""
return {"status": "ok", "result": {"role": ctx.role.value}}
+ @app.get("/api/v1/test/accounts/{account_id}/users/{user_id}")
+ async def trusted_identity_from_url(
+ account_id: str, user_id: str, ctx=Depends(get_request_context)
+ ):
+ """Expose a route whose explicit URL identity can satisfy trusted mode."""
+ return {
+ "status": "ok",
+ "result": {
+ "account_id": account_id,
+ "user_id": user_id,
+ "ctx_account_id": ctx.user.account_id,
+ "ctx_user_id": ctx.user.user_id,
+ },
+ }
+
return app
@@ -693,6 +709,133 @@ async def test_trusted_mode_allows_header_identity_without_api_key():
assert identity.agent_id == "assistant-1"
+async def test_trusted_mode_defaults_role_to_user():
+ """Trusted mode should default requests to USER when no explicit role header is sent."""
+ request = _make_request(
+ "/api/v1/resources",
+ headers={
+ "X-OpenViking-Account": "acme",
+ "X-OpenViking-User": "alice",
+ },
+ auth_enabled=False,
+ auth_mode="trusted",
+ )
+
+ identity = await resolve_identity(
+ request,
+ x_openviking_account="acme",
+ x_openviking_user="alice",
+ )
+
+ assert identity.role == Role.USER
+
+
+async def test_trusted_mode_looks_up_role_from_api_key_manager(auth_app):
+ """Trusted mode should look up role from APIKeyManager using account_id and user_id."""
+ manager = auth_app.state.api_key_manager
+ account_id = _uid()
+ await manager.create_account(account_id, "admin_user")
+ await manager.register_user(account_id, "regular_user", "user")
+
+ request = _make_request(
+ "/api/v1/resources",
+ headers={
+ "X-OpenViking-Account": account_id,
+ "X-OpenViking-User": "admin_user",
+ },
+ auth_enabled=True,
+ auth_mode="trusted",
+ api_key_manager=manager,
+ )
+
+ identity = await resolve_identity(
+ request,
+ x_openviking_account=account_id,
+ x_openviking_user="admin_user",
+ )
+
+ assert identity.role == Role.ADMIN
+ assert identity.account_id == account_id
+ assert identity.user_id == "admin_user"
+
+ # Test with regular user
+ request = _make_request(
+ "/api/v1/resources",
+ headers={
+ "X-OpenViking-Account": account_id,
+ "X-OpenViking-User": "regular_user",
+ },
+ auth_enabled=True,
+ auth_mode="trusted",
+ api_key_manager=manager,
+ )
+
+ identity = await resolve_identity(
+ request,
+ x_openviking_account=account_id,
+ x_openviking_user="regular_user",
+ )
+
+ assert identity.role == Role.USER
+ assert identity.account_id == account_id
+ assert identity.user_id == "regular_user"
+
+
+async def test_trusted_mode_defaults_to_user_when_user_not_found(auth_app):
+ """Trusted mode should default to USER role when user doesn't exist in APIKeyManager."""
+ manager = auth_app.state.api_key_manager
+ account_id = _uid()
+ await manager.create_account(account_id, "admin_user")
+
+ request = _make_request(
+ "/api/v1/resources",
+ headers={
+ "X-OpenViking-Account": account_id,
+ "X-OpenViking-User": "nonexistent_user",
+ },
+ auth_enabled=True,
+ auth_mode="trusted",
+ api_key_manager=manager,
+ )
+
+ identity = await resolve_identity(
+ request,
+ x_openviking_account=account_id,
+ x_openviking_user="nonexistent_user",
+ )
+
+ assert identity.role == Role.USER
+ assert identity.account_id == account_id
+ assert identity.user_id == "nonexistent_user"
+
+
+async def test_trusted_mode_defaults_to_user_when_account_not_found(auth_app):
+ """Trusted mode should default to USER role when account doesn't exist in APIKeyManager."""
+ manager = auth_app.state.api_key_manager
+ account_id = _uid()
+
+ request = _make_request(
+ "/api/v1/resources",
+ headers={
+ "X-OpenViking-Account": account_id,
+ "X-OpenViking-User": "some_user",
+ },
+ auth_enabled=False,
+ auth_mode="trusted",
+ api_key_manager=manager,
+ )
+
+ identity = await resolve_identity(
+ request,
+ x_openviking_account=account_id,
+ x_openviking_user="some_user",
+ )
+
+ assert identity.role == Role.USER
+ assert identity.account_id == account_id
+ assert identity.user_id == "some_user"
+
+
async def test_trusted_mode_with_root_api_key_requires_matching_api_key():
"""Trusted mode should require the configured server API key when present."""
request = _make_request(
@@ -782,6 +925,46 @@ async def test_trusted_mode_tenant_http_routes_accept_explicit_identity_headers(
assert response.json()["result"] == {"account_id": "acme", "user_id": "alice"}
+async def test_trusted_mode_http_routes_accept_explicit_identity_from_url():
+ """Trusted mode should accept account_id/user_id supplied directly in the URL."""
+ app = _build_auth_http_test_app(
+ identity=None,
+ auth_enabled=False,
+ auth_mode="trusted",
+ )
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.get("/api/v1/test/accounts/acme/users/alice")
+
+ assert response.status_code == 200
+ assert response.json()["result"] == {
+ "account_id": "acme",
+ "user_id": "alice",
+ "ctx_account_id": "acme",
+ "ctx_user_id": "alice",
+ }
+
+
+async def test_trusted_mode_rejects_conflicting_header_and_url_identity():
+ """Trusted mode should reject requests when explicit URL identity conflicts with headers."""
+ app = _build_auth_http_test_app(
+ identity=None,
+ auth_enabled=False,
+ auth_mode="trusted",
+ )
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.get(
+ "/api/v1/test/accounts/acme/users/alice",
+ headers={"X-OpenViking-Account": "other-acct"},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "INVALID_ARGUMENT"
+
+
async def test_trusted_mode_http_routes_require_api_key_when_root_key_configured():
"""Trusted mode HTTP routes should require the configured server API key when present."""
app = _build_auth_http_test_app(
@@ -900,3 +1083,125 @@ def test_validate_trusted_mode_without_key_non_localhost_raises():
config = ServerConfig(host="0.0.0.0", root_api_key=None, auth_mode="trusted")
with pytest.raises(SystemExit):
validate_server_config(config)
+
+
+async def test_trusted_mode_admin_api_without_identity_defaults_to_root():
+ """Trusted mode admin APIs without identity should default to ROOT role."""
+ request = _make_request(
+ "/api/v1/admin/accounts",
+ headers={},
+ auth_enabled=False,
+ auth_mode="trusted",
+ )
+
+ identity = await resolve_identity(request)
+
+ assert identity.role == Role.ROOT
+ assert identity.account_id == "trusted"
+ assert identity.user_id == "trusted"
+ assert identity.agent_id == "default"
+
+
+async def test_trusted_mode_admin_api_without_identity_accepts_agent_header():
+ """Trusted mode admin APIs without identity should still respect X-OpenViking-Agent."""
+ request = _make_request(
+ "/api/v1/admin/accounts",
+ headers={"X-OpenViking-Agent": "my-admin-agent"},
+ auth_enabled=False,
+ auth_mode="trusted",
+ )
+
+ identity = await resolve_identity(
+ request,
+ x_openviking_agent="my-admin-agent",
+ )
+
+ assert identity.role == Role.ROOT
+ assert identity.account_id == "trusted"
+ assert identity.user_id == "trusted"
+ assert identity.agent_id == "my-admin-agent"
+
+
+async def test_trusted_mode_admin_api_with_partial_identity_still_requires_full_identity():
+ """Trusted mode admin APIs with partial identity should still require full identity."""
+ # Only account, no user
+ request = _make_request(
+ "/api/v1/admin/accounts",
+ headers={"X-OpenViking-Account": "acme"},
+ auth_enabled=False,
+ auth_mode="trusted",
+ )
+
+ with pytest.raises(InvalidArgumentError, match="Trusted mode requests must include"):
+ await resolve_identity(
+ request,
+ x_openviking_account="acme",
+ )
+
+
+async def test_trusted_mode_get_request_context_exempts_admin_paths():
+ """get_request_context should exempt admin paths from identity checks in trusted mode."""
+ # Admin path with ROOT identity from default
+ request = _make_request(
+ "/api/v1/admin/accounts",
+ auth_enabled=False,
+ auth_mode="trusted",
+ )
+ identity = ResolvedIdentity(
+ role=Role.ROOT,
+ account_id="trusted",
+ user_id="trusted",
+ )
+
+ ctx = await get_request_context(request, identity)
+
+ assert ctx.role == Role.ROOT
+ assert ctx.user.account_id == "trusted"
+ assert ctx.user.user_id == "trusted"
+
+ # Non-admin path still requires proper identity
+ non_admin_request = _make_request(
+ "/api/v1/fs/ls",
+ auth_enabled=False,
+ auth_mode="trusted",
+ )
+ incomplete_identity = ResolvedIdentity(
+ role=Role.ROOT,
+ account_id=None,
+ user_id="trusted",
+ )
+
+ with pytest.raises(InvalidArgumentError, match="X-OpenViking-Account"):
+ await get_request_context(non_admin_request, incomplete_identity)
+
+
+async def test_trusted_mode_admin_api_http_route_without_identity():
+ """Trusted mode admin HTTP routes should work without identity headers."""
+ app = _build_auth_http_test_app(
+ identity=None,
+ auth_enabled=False,
+ auth_mode="trusted",
+ )
+
+ # Add an admin route to the test app
+ @app.get("/api/v1/admin/accounts")
+ async def admin_accounts(ctx=Depends(get_request_context)):
+ return {
+ "status": "ok",
+ "result": {
+ "role": ctx.role.value,
+ "account_id": ctx.user.account_id,
+ "user_id": ctx.user.user_id,
+ },
+ }
+
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.get("/api/v1/admin/accounts")
+
+ assert response.status_code == 200
+ assert response.json()["status"] == "ok"
+ assert response.json()["result"]["role"] == "root"
+ assert response.json()["result"]["account_id"] == "trusted"
+ assert response.json()["result"]["user_id"] == "trusted"