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(uri): resolve home alias for root requests (#4342)
Zayn Jarvisea717aa05ba1
diff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.mdindex 18e2f1eef..1054d8f42 100644--- a/docs/en/concepts/04-viking-uri.md+++ b/docs/en/concepts/04-viking-uri.md@@ -46,9 +46,9 @@ each caller.`Invalid scope ... Must be one of:` error message never mentions it.- Responses always echo the expanded canonical URI, never `viking://~`, and persisteddata (vector records, watch keys) stays canonical as well.-- Requires an authenticated user identity. Expansion happens at the request boundary for- user and admin callers; root-role and unauthenticated contexts, along with places that- demand an already-canonical URI (internal storage paths, background tasks), reject the+- Requires an authenticated request identity. Expansion uses that identity's effective+ `user_id` for every request role, including root. Places that demand an already-canonical+ URI (internal storage paths and background tasks without a request context) reject thealias instead of guessing a user.- Replaces the removed uid-less shorthand: `viking://user/<segment>/...` for `memories`,`resources`, `skills`, `peers`, `privacy`, and `sessions` is rejected at USER/ADMINdiff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.mdindex 5a56e0adc..d6fe8780d 100644--- a/docs/zh/concepts/04-viking-uri.md+++ b/docs/zh/concepts/04-viking-uri.md@@ -39,8 +39,8 @@ viking://{scope}/{path}- 接受但不宣传:`~` 不属于公开作用域列表,`Invalid scope ... Must be one of:` 错误信息中不会出现它。- 响应始终回显展开后的 canonical URI,不会返回 `viking://~`;持久化数据(向量记录、watch key)同样保持 canonical 形式。-- 需要认证用户身份。展开发生在 user / admin 调用方的请求入口;root 角色与未认证上下文,- 以及要求 URI 已是 canonical 形式的场景(内部存储路径、后台任务),会直接拒绝该别名,+- 需要认证请求身份。所有请求角色(包括 root)都使用该身份的有效 `user_id` 展开;要求 URI+ 已是 canonical 形式的场景(内部存储路径、没有请求上下文的后台任务)仍会直接拒绝该别名,而不会猜测用户。- 取代已移除的无 uid 短写:`memories`、`resources`、`skills`、`peers`、`privacy`、`sessions`的 `viking://user/<segment>/...` 写法会在 USER / ADMIN 请求入口被拒绝,错误信息中会给出diff --git a/openviking/core/namespace.py b/openviking/core/namespace.pyindex d005d3104..391ec7495 100644--- a/openviking/core/namespace.py+++ b/openviking/core/namespace.py@@ -243,9 +243,9 @@ def resolve_uri(return ResolvedNamespace(uri=canonical_uri, scope=scope)if scope == "~":# The home alias is expanded at the request boundary only. Reaching the- # canonical parser with it (root-role requests, internal callers, storage- # paths) means no identity is available, so fail closed instead of- # creating a literal '~' namespace.+ # canonical parser with it (internal callers or storage paths) means no+ # identity is available, so fail closed instead of creating a literal+ # '~' namespace.raise NamespaceShapeError(f"Home alias URI is not canonical: {'/'.join(parts)}")if scope == "session":raise NamespaceShapeError(f"Legacy session URI is not canonical: {'/'.join(parts)}")@@ -261,6 +261,13 @@ def resolve_request_uri(uri: str, ctx: RequestContext) -> str:The uid-less ``viking://user/<reserved>`` shorthand is no longer expanded:it fails closed with a hint pointing at ``viking://~/...``."""+ # Every authenticated request context carries an effective user identity,+ # including ROOT contexts produced by dev, API-key, and trusted auth modes.+ # Resolve only the unambiguous home alias for every role; preserve the+ # existing role-dependent handling of legacy/ambiguous spellings below.+ parts = uri_parts(uri)+ if parts and parts[0] == "~":+ return resolve_current_user_uri(uri, ctx)if ctx.role in {Role.USER, Role.ADMIN}:return resolve_current_user_uri(uri, ctx)return resolve_uri(uri).uridiff --git a/tests/server/test_filesystem_router.py b/tests/server/test_filesystem_router.pyindex bb9c63c56..e7c8aaa5a 100644--- a/tests/server/test_filesystem_router.py+++ b/tests/server/test_filesystem_router.py@@ -86,7 +86,8 @@ async def test_attrs_returns_memory_fields_and_tags(monkeypatch):@pytest.mark.asyncio-async def test_mkdir_echoes_canonical_home_alias(monkeypatch):[email protected]("role", [Role.USER, Role.ADMIN, Role.ROOT])+async def test_mkdir_echoes_canonical_home_alias(monkeypatch, role):seen = {}async def fake_mkdir(uri, ctx=None, description=None):@@ -100,13 +101,46 @@ async def test_mkdir_echoes_canonical_home_alias(monkeypatch):response = await filesystem.mkdir(filesystem.MkdirRequest(uri="viking://~/resources/notes"),- _ctx=RequestContext(user=UserIdentifier("acct", "alice"), role=Role.USER),+ _ctx=RequestContext(user=UserIdentifier("acct", "alice"), role=role),)assert seen["uri"] == "viking://user/alice/resources/notes"assert response.result["uri"] == "viking://user/alice/resources/notes"+async def test_dev_root_http_mkdir_expands_home_alias_from_request_identity(+ app, client, monkeypatch+):+ """Exercise the REST auth dependency and router with a dev-mode ROOT request."""+ seen = {}++ async def fake_mkdir(uri, ctx=None, description=None):+ seen.update(uri=uri, ctx=ctx, description=description)++ monkeypatch.setattr(+ filesystem,+ "get_service",+ lambda: SimpleNamespace(fs=SimpleNamespace(mkdir=fake_mkdir)),+ )++ response = await client.post(+ "/api/v1/fs/mkdir",+ json={"uri": "viking://~/resources/notes", "description": "private notes"},+ headers={+ "X-OpenViking-Account": "acct",+ "X-OpenViking-User": "alice",+ },+ )++ assert response.status_code == 200, response.text+ assert response.json()["result"]["uri"] == "viking://user/alice/resources/notes"+ assert seen["uri"] == "viking://user/alice/resources/notes"+ assert seen["ctx"].role == Role.ROOT+ assert seen["ctx"].account_id == "acct"+ assert seen["ctx"].user.user_id == "alice"++@pytest.mark.asyncioasync def test_ls_user_container_lists_only_caller_space(app, client, service):"""`viking://user` is the container of user spaces, not a current-user shorthand."""diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex 7361dda45..5ee1e9d77 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -105,9 +105,10 @@ def test_get_ctx_raises_when_unset():("viking://~/resources", "viking://user/test_user/resources"),],)-def test_resolve_mcp_workspace_uri_only_expands_documented_aliases(uri, expected):- user_ctx = RequestContext(DEFAULT_CTX.user, Role.USER)- assert _resolve_mcp_workspace_uri(uri, user_ctx) == expected[email protected]("role", [Role.USER, Role.ADMIN, Role.ROOT])+def test_resolve_mcp_workspace_uri_only_expands_documented_aliases(uri, expected, role):+ ctx = RequestContext(DEFAULT_CTX.user, role)+ assert _resolve_mcp_workspace_uri(uri, ctx) == expected@pytest.mark.parametrize(@@ -132,8 +133,8 @@ def test_resolve_mcp_workspace_uri_supports_dotted_current_user_id():assert _resolve_mcp_workspace_uri("viking://user/notes/todo.md", ctx) == ("viking://user/notes/todo.md")- # DEFAULT_CTX is ROOT: root-role requests skip current-user resolution- # entirely, so a reserved first segment stays a literal user id.+ # DEFAULT_CTX is ROOT: only the '~' alias uses its effective user identity,+ # so a reserved first segment stays a literal user id.assert _resolve_mcp_workspace_uri("viking://user/resources", DEFAULT_CTX) == ("viking://user/resources")@@ -1550,9 +1551,10 @@ async def test_edit_memory_file_preserves_metadata(service):assert visible.strip() == "likes: coffee"-async def test_write_home_alias_uri(service):- """`viking://~/...` writes into the caller's canonical user root."""- user_ctx = RequestContext(DEFAULT_CTX.user, Role.USER)[email protected]("role", [Role.USER, Role.ADMIN, Role.ROOT])+async def test_write_home_alias_uri(service, role):+ """Every MCP request role writes `viking://~/...` under its effective user."""+ user_ctx = RequestContext(DEFAULT_CTX.user, role)canonical = f"viking://user/{DEFAULT_CTX.user.user_id}/memories/preferences/home_alias.md"token = _mcp_ctx.set(user_ctx)try:@@ -1571,12 +1573,6 @@ async def test_write_home_alias_uri(service):assert visible.strip() == "x"-async def test_home_alias_rejected_for_root_role(service):- """Root-role MCP calls skip current-user resolution, so the alias fails closed."""- with pytest.raises(InvalidURIError, match="Home alias URI is not canonical"):- await list_tool(uri="viking://~/memories")--async def test_write_home_alias_memory_uri(service):uri = "viking://~/memories/preferences/home_alias_write.md"user_ctx = RequestContext(DEFAULT_CTX.user, Role.USER)@@ -1741,7 +1737,7 @@ def test_mcp_route_unmatched_paths_keep_falling_back(app):assert "route" not in child_scope-async def test_mcp_middleware_stamps_root_span_identity():+async def test_mcp_middleware_stamps_and_uses_root_identity_for_home_alias():"""Identity resolved from the auth headers must be stamped onto the outerrequest's root span attributes, so MCP traffic is audited under the realaccount/user instead of ``__unknown__``."""@@ -1753,7 +1749,12 @@ async def test_mcp_middleware_stamps_root_span_identity():request_id="req-test",)+ seen = {}+async def downstream(scope, receive, send):+ ctx = _get_ctx()+ seen["ctx"] = ctx+ seen["uri"] = _resolve_mcp_workspace_uri("viking://~/memories", ctx)response = httpx.Response(200, json={"ok": True})await send({@@ -1787,6 +1788,9 @@ async def test_mcp_middleware_stamps_root_span_identity():assert response.status_code == 200assert root_attrs.account_id == "acct-1"assert root_attrs.user_id == "user-1"+ assert seen["ctx"].role == Role.ROOT+ assert seen["ctx"].account_id == "acct-1"+ assert seen["uri"] == "viking://user/user-1/memories"# ---- tree tool ----diff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.pyindex 63c6a8efc..6026c3fe5 100644--- a/tests/unit/test_namespace_uri_classification.py+++ b/tests/unit/test_namespace_uri_classification.py@@ -178,7 +178,7 @@ def test_request_boundary_rejects_reserved_user_root_shorthand():resolve_request_uri("viking://user/resources", admin_ctx)with pytest.raises(NamespaceShapeError, match=re.escape("viking://~/skills")):resolve_request_uri("viking://user/skills", admin_ctx)- # ROOT requests never enter current-user resolution, so the literal parse stands.+ # ROOT requests resolve only the unambiguous '~' alias, so this literal parse stands.root_ctx = RequestContext(user=UserIdentifier(account_id="acct", user_id="root-actor"),role=Role.ROOT,@@ -260,7 +260,7 @@ def test_unreserved_user_root_segment_keeps_canonical_meaning():def test_home_alias_expands_to_current_user_root_at_request_boundary():- for role in (Role.USER, Role.ADMIN):+ for role in (Role.USER, Role.ADMIN, Role.ROOT):ctx = RequestContext(user=UserIdentifier(account_id="acct", user_id="alice"),role=role,@@ -296,19 +296,7 @@ def test_home_alias_expands_to_current_user_root_at_request_boundary():)-def test_home_alias_fails_closed_without_current_user_resolution():- root_ctx = RequestContext(- user=UserIdentifier(account_id="acct", user_id="root-actor"),- role=Role.ROOT,- )-- # Root-role requests skip current-user resolution, so the alias never becomes- # a literal '~' namespace -- it is rejected instead of guessing a user.- with pytest.raises(NamespaceShapeError, match="Home alias URI is not canonical"):- resolve_request_uri("viking://~/resources/docs", root_ctx)- with pytest.raises(InvalidURIError, match="Home alias URI is not canonical"):- validate_request_viking_uri("viking://~/resources/docs", root_ctx)-+def test_home_alias_fails_closed_without_request_context():# Every internal consumer of the canonical parser is protected the same way.with pytest.raises(NamespaceShapeError, match="Home alias URI is not canonical"):resolve_uri("viking://~")