Skip to content

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

fix(storage): reject traversal segments before VikingFS access checks (#557)

lyfmt471c81a3baf0
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index bda478ae4..ed65d83d4 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -193,9 +193,37 @@ class VikingFS:
finally:
self._bound_ctx.reset(token)
+ @staticmethod
+ def _normalize_uri(uri: str) -> str:
+ """Normalize short-format URIs to the canonical viking:// form."""
+ if uri.startswith("viking://"):
+ return uri
+ return VikingURI.normalize(uri)
+
+ @classmethod
+ def _normalized_uri_parts(cls, uri: str) -> tuple[str, List[str]]:
+ """Normalize a URI and reject ambiguous or platform-specific path traversal forms."""
+ normalized = cls._normalize_uri(uri)
+ parts = [p for p in normalized[len("viking://") :].strip("/").split("/") if p]
+
+ for part in parts:
+ if part in {".", ".."}:
+ raise PermissionError(f"Unsafe URI traversal segment '{part}' in {normalized}")
+ if "\\" in part:
+ raise PermissionError(
+ f"Unsafe URI path separator '\\\\' in component '{part}' of {normalized}"
+ )
+ if len(part) >= 2 and part[1] == ":" and part[0].isalpha():
+ raise PermissionError(
+ f"Unsafe URI drive-prefixed component '{part}' in {normalized}"
+ )
+
+ return normalized, parts
+
def _ensure_access(self, uri: str, ctx: Optional[RequestContext]) -> None:
real_ctx = self._ctx_or_default(ctx)
- if not self._is_accessible(uri, real_ctx):
+ normalized_uri, _ = self._normalized_uri_parts(uri)
+ if not self._is_accessible(normalized_uri, real_ctx):
raise PermissionError(f"Access denied for {uri}")
# ========== AGFS Basic Commands ==========
@@ -872,11 +900,10 @@ class VikingFS:
"""
real_ctx = self._ctx_or_default(ctx)
account_id = real_ctx.account_id
- remainder = uri[len("viking://") :].strip("/") if uri.startswith("viking://") else uri
- if not remainder:
+ _, parts = self._normalized_uri_parts(uri)
+ if not parts:
return f"/local/{account_id}"
- parts = [p for p in remainder.split("/") if p]
safe_parts = [self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in parts]
return f"/local/{account_id}/{'/'.join(safe_parts)}"
@@ -926,9 +953,7 @@ class VikingFS:
For user/agent, the second segment is space unless it's a known structure dir.
For session, the second segment is always space (when 3+ parts).
"""
- if not uri.startswith("viking://"):
- return None
- parts = [p for p in uri[len("viking://") :].strip("/").split("/") if p]
+ _, parts = self._normalized_uri_parts(uri)
if len(parts) < 2:
return None
scope = parts[0]
@@ -946,12 +971,9 @@ class VikingFS:
def _is_accessible(self, uri: str, ctx: RequestContext) -> bool:
"""Check whether a URI is visible/accessible under current request context."""
+ normalized_uri, parts = self._normalized_uri_parts(uri)
if ctx.role == Role.ROOT:
return True
- if not uri.startswith("viking://"):
- uri = VikingURI.normalize(uri)
-
- parts = [p for p in uri[len("viking://") :].strip("/").split("/") if p]
if not parts:
return True
@@ -961,7 +983,7 @@ class VikingFS:
if scope == "_system":
return False
- space = self._extract_space_from_uri(uri)
+ space = self._extract_space_from_uri(normalized_uri)
if space is None:
return True
diff --git a/tests/misc/test_vikingfs_uri_guard.py b/tests/misc/test_vikingfs_uri_guard.py
new file mode 100644
index 000000000..f20513e34
--- /dev/null
+++ b/tests/misc/test_vikingfs_uri_guard.py
@@ -0,0 +1,106 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""Regression tests for traversal-style URI rejection in VikingFS."""
+
+import contextvars
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from openviking.storage.viking_fs import VikingFS
+
+
+def _make_viking_fs() -> VikingFS:
+ """Create a VikingFS instance with a mocked AGFS backend."""
+ fs = VikingFS.__new__(VikingFS)
+ fs.agfs = MagicMock()
+ fs.query_embedder = None
+ fs.rerank_config = None
+ fs.vector_store = None
+ fs._bound_ctx = contextvars.ContextVar("vikingfs_bound_ctx_test", default=None)
+ return fs
+
+
+class TestVikingFSURITraversalGuard:
+ """Traversal-style URI components should be rejected before any AGFS I/O."""
+
+ @pytest.mark.parametrize(
+ "uri",
+ [
+ "viking://resources/../_system/users.json",
+ "viking://resources/../../_system/accounts.json",
+ "/resources/../_system/users.json",
+ "viking://resources/..\\..\\_system\\users.json",
+ "viking://resources/C:\\Windows\\System32",
+ ],
+ )
+ def test_rejects_unsafe_uri_components(self, uri: str) -> None:
+ fs = _make_viking_fs()
+
+ with pytest.raises(PermissionError, match="Unsafe URI"):
+ fs._normalized_uri_parts(uri)
+
+ @pytest.mark.asyncio
+ async def test_read_file_rejects_traversal_before_agfs_read(self) -> None:
+ fs = _make_viking_fs()
+
+ with pytest.raises(PermissionError, match="Unsafe URI"):
+ await fs.read_file("viking://resources/../_system/users.json")
+
+ fs.agfs.read.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_write_rejects_traversal_before_agfs_write(self) -> None:
+ fs = _make_viking_fs()
+
+ with pytest.raises(PermissionError, match="Unsafe URI"):
+ await fs.write("viking://resources/../../_system/accounts.json", "pwned")
+
+ fs.agfs.write.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_rm_rejects_traversal_before_side_effects(self) -> None:
+ fs = _make_viking_fs()
+ fs._collect_uris = AsyncMock(return_value=[])
+ fs._delete_from_vector_store = AsyncMock()
+
+ with pytest.raises(PermissionError, match="Unsafe URI"):
+ await fs.rm("viking://resources/../../other_account/_system/users.json")
+
+ fs._collect_uris.assert_not_called()
+ fs._delete_from_vector_store.assert_not_called()
+ fs.agfs.rm.assert_not_called()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("old_uri", "new_uri"),
+ [
+ ("viking://resources/../_system/users.json", "viking://resources/safe.txt"),
+ ("viking://resources/safe.txt", "viking://resources/../../victim/_system/users.json"),
+ ],
+ )
+ async def test_mv_rejects_traversal_in_source_or_target(
+ self, old_uri: str, new_uri: str
+ ) -> None:
+ fs = _make_viking_fs()
+ fs._collect_uris = AsyncMock(return_value=[])
+ fs._update_vector_store_uris = AsyncMock()
+ fs._delete_from_vector_store = AsyncMock()
+
+ with pytest.raises(PermissionError, match="Unsafe URI"):
+ await fs.mv(old_uri, new_uri)
+
+ fs._collect_uris.assert_not_called()
+ fs._update_vector_store_uris.assert_not_called()
+ fs._delete_from_vector_store.assert_not_called()
+ fs.agfs.mv.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_read_file_keeps_valid_uri_behavior(self) -> None:
+ fs = _make_viking_fs()
+ fs.agfs.read = MagicMock(return_value=b"hello")
+
+ content = await fs.read_file("viking://resources/docs/guide.md")
+
+ assert content == "hello"
+ fs.agfs.read.assert_called_once_with("/local/default/resources/docs/guide.md")