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: isolate temp scope by user within an account (#1398)
Hinotobice89b46b8d8f
diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.pyindex c3b1188fa..9d5343620 100644--- a/openviking/storage/content_write.py+++ b/openviking/storage/content_write.py@@ -188,7 +188,7 @@ class ContentWriteCoordinator:mode: str,ctx: RequestContext,) -> tuple[str, str]:- temp_base = self._viking_fs.create_temp_uri()+ temp_base = self._viking_fs.create_temp_uri(ctx=ctx)await self._viking_fs.mkdir(temp_base, exist_ok=True, ctx=ctx)root_name = root_uri.rstrip("/").split("/")[-1]temp_root_uri = f"{temp_base.rstrip('/')}/{root_name}"diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.pyindex f1bbaf906..75b8936f9 100644--- a/openviking/storage/viking_fs.py+++ b/openviking/storage/viking_fs.py@@ -277,6 +277,13 @@ class VikingFS:if not self._is_accessible(normalized_uri, real_ctx):raise PermissionError(f"Access denied for {uri}")+ def _ensure_mutable_access(self, uri: str, ctx: Optional[RequestContext]) -> None:+ self._ensure_access(uri, ctx)+ real_ctx = self._ctx_or_default(ctx)+ normalized_uri, _ = self._normalized_uri_parts(uri)+ if real_ctx.role != Role.ROOT and normalized_uri.rstrip("/") == "viking://temp":+ raise PermissionError("Temp root is read-only for non-root users")+# ========== AGFS Basic Commands ==========async def read(@@ -327,7 +334,7 @@ class VikingFS:ctx: Optional[RequestContext] = None,) -> str:"""Write file"""- self._ensure_access(uri, ctx)+ self._ensure_mutable_access(uri, ctx)path = self._uri_to_path(uri, ctx=ctx)if isinstance(data, str):data = data.encode("utf-8")@@ -343,7 +350,7 @@ class VikingFS:ctx: Optional[RequestContext] = None,) -> None:"""Create directory."""- self._ensure_access(uri, ctx)+ self._ensure_mutable_access(uri, ctx)path = self._uri_to_path(uri, ctx=ctx)# Always ensure parent directories exist before creating this directoryawait self._ensure_parent_dirs(path)@@ -376,7 +383,7 @@ class VikingFS:from openviking.storage.errors import LockAcquisitionError, ResourceBusyErrorfrom openviking.storage.transaction import LockContext, get_lock_manager- self._ensure_access(uri, ctx)+ self._ensure_mutable_access(uri, ctx)path = self._uri_to_path(uri, ctx=ctx)target_uri = self._path_to_uri(path, ctx=ctx)@@ -430,8 +437,8 @@ class VikingFS:from openviking.pyagfs.helpers import cp as agfs_cpfrom openviking.storage.transaction import LockContext, get_lock_manager- self._ensure_access(old_uri, ctx)- self._ensure_access(new_uri, ctx)+ self._ensure_mutable_access(old_uri, ctx)+ self._ensure_mutable_access(new_uri, ctx)old_path = self._uri_to_path(old_uri, ctx=ctx)new_path = self._uri_to_path(new_uri, ctx=ctx)target_uri = self._path_to_uri(old_path, ctx=ctx)@@ -1278,12 +1285,24 @@ class VikingFS:else:return f"viking://{path}"+ def _looks_like_legacy_temp_leaf(self, value: str) -> bool:+ return bool(re.match(r"^\d{8}_[0-9a-f]{6}$", value or ""))++ def _is_legacy_temp_uri_parts(self, parts: List[str]) -> bool:+ if len(parts) < 2 or parts[0] != "temp" or not self._looks_like_legacy_temp_leaf(parts[1]):+ return False+ if len(parts) == 2:+ return True+ return not self._looks_like_legacy_temp_leaf(parts[2])+def _extract_space_from_uri(self, uri: str) -> Optional[str]:"""Extract space segment from URI if present.URIs are WYSIWYG: viking://{scope}/{space}/...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).+ Legacy temp URIs keep the historical shape viking://temp/<temp-id> and therefore+ intentionally have no space segment."""_, parts = self._normalized_uri_parts(uri)if len(parts) < 2:@@ -1293,6 +1312,8 @@ class VikingFS:# Treat scope-root metadata files as not having a tenant space segment.if len(parts) == 2 and second in {".abstract.md", ".overview.md"}:return None+ if self._is_legacy_temp_uri_parts(parts):+ return Noneif scope == "user" and second not in self._USER_STRUCTURE_DIRS:return secondif scope == "agent" and second not in self._AGENT_STRUCTURE_DIRS:@@ -1312,8 +1333,14 @@ class VikingFS:return Falsescope = parts[0]- if scope in {"resources", "temp"}:+ if scope == "resources":return True+ if scope == "temp":+ if len(parts) == 1:+ return True+ if parts[1] == ctx.user.user_space_name():+ return True+ return self._is_legacy_temp_uri_parts(parts)if scope == "_system":return False@@ -1863,8 +1890,8 @@ class VikingFS:ctx: Optional[RequestContext] = None,) -> None:"""Move file."""- self._ensure_access(from_uri, ctx)- self._ensure_access(to_uri, ctx)+ self._ensure_mutable_access(from_uri, ctx)+ self._ensure_mutable_access(to_uri, ctx)from_path = self._uri_to_path(from_uri, ctx=ctx)content_bytes = await self.read_file_bytes(from_uri, ctx=ctx)@@ -1873,12 +1900,20 @@ class VikingFS:# ========== Temp File Operations (backward compatible) ==========- def create_temp_uri(self) -> str:- """Create temp directory URI."""- return VikingURI.create_temp_uri()+ def create_temp_uri(self, ctx: Optional[RequestContext] = None) -> str:+ """Create a temp directory URI.++ - explicit ctx or bound request context -> user-scoped temp URI+ - no explicit/bound context -> legacy temp URI shape for backward compatibility+ """+ real_ctx = ctx if ctx is not None else self._bound_ctx.get()+ if real_ctx is None:+ return VikingURI.create_temp_uri()+ return VikingURI.create_temp_uri(space=real_ctx.user.user_space_name())async def delete_temp(self, temp_uri: str, ctx: Optional[RequestContext] = None) -> None:"""Delete temp directory and its contents."""+ self._ensure_mutable_access(temp_uri, ctx)path = self._uri_to_path(temp_uri, ctx=ctx)try:for entry in self._ls_entries(path):diff --git a/openviking_cli/utils/uri.py b/openviking_cli/utils/uri.pyindex 61ef4d1c7..7c3d94242 100644--- a/openviking_cli/utils/uri.py+++ b/openviking_cli/utils/uri.py@@ -286,10 +286,23 @@ class VikingURI:return f"{VikingURI.SCHEME}://{uri}"@classmethod- def create_temp_uri(cls) -> str:- """Create temp directory URI like viking://temp/MMDDHHMM_XXXXXX"""+ def create_temp_uri(cls, space: Optional[str] = None) -> str:+ """Create temp directory URI.++ When ``space`` is provided, generate a user-scoped temp URI like+ ``viking://temp/<space>/MMDDHHMM_XXXXXX``. This preserves isolation+ between users sharing the same account while keeping temp data in the+ temp scope.++ When ``space`` is omitted, fall back to the legacy shape+ ``viking://temp/MMDDHHMM_XXXXXX`` for compatibility with callers that+ do not have a user context.+ """import datetimeimport uuidtemp_id = uuid.uuid4().hex[:6]- return f"viking://temp/{datetime.datetime.now().strftime('%m%d%H%M')}_{temp_id}"+ temp_leaf = f"{datetime.datetime.now().strftime('%m%d%H%M')}_{temp_id}"+ if space:+ return f"viking://temp/{space}/{temp_leaf}"+ return f"viking://temp/{temp_leaf}"diff --git a/tests/server/test_temp_scope_acl.py b/tests/server/test_temp_scope_acl.pynew file mode 100644index 000000000..1be456590--- /dev/null+++ b/tests/server/test_temp_scope_acl.py@@ -0,0 +1,295 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++"""Regression tests for temp-scope access control."""++from datetime import datetime, timezone++import pytest++from openviking.server.identity import RequestContext, Role+from openviking.storage.viking_fs import VikingFS+from openviking_cli.session.user_id import UserIdentifier+++class FakeAGFS:+ def __init__(self):+ self.dirs = {"/", "/local"}+ self.files = {}++ def mkdir(self, path):+ if path in self.files:+ raise FileExistsError(path)+ if path in self.dirs:+ raise FileExistsError(f"already exists: {path}")+ parent = path.rsplit("/", 1)[0] or "/"+ if parent not in self.dirs:+ raise FileNotFoundError(parent)+ self.dirs.add(path)+ return path++ def write(self, path, data):+ parent = path.rsplit("/", 1)[0] or "/"+ if parent not in self.dirs:+ raise FileNotFoundError(parent)+ self.files[path] = bytes(data)+ return path++ def rm(self, path, recursive=False):+ if path in self.files:+ del self.files[path]+ return {}+ if path not in self.dirs:+ raise FileNotFoundError(path)++ prefix = f"{path.rstrip('/')}/"+ has_children = any(+ item.startswith(prefix) for item in self.dirs | set(self.files) if item != path+ )+ if has_children and not recursive:+ raise OSError(f"directory not empty: {path}")++ for file_path in list(self.files):+ if file_path.startswith(prefix):+ del self.files[file_path]+ for dir_path in sorted(self.dirs, reverse=True):+ if dir_path.startswith(prefix):+ self.dirs.remove(dir_path)+ if path != "/":+ self.dirs.remove(path)+ return {}++ def read(self, path, offset=0, size=-1):+ if path not in self.files:+ raise FileNotFoundError(path)+ data = self.files[path]+ return data[offset:] if size == -1 else data[offset : offset + size]++ def stat(self, path):+ if path in self.dirs:+ return {"name": path.rsplit("/", 1)[-1] or "/", "isDir": True, "size": 0}+ if path in self.files:+ return {"name": path.rsplit("/", 1)[-1], "isDir": False, "size": len(self.files[path])}+ raise FileNotFoundError(path)++ def ls(self, path):+ if path not in self.dirs:+ raise FileNotFoundError(path)+ children = {}+ prefix = path.rstrip("/")+ prefix = "" if prefix == "/" else prefix+ for d in sorted(self.dirs):+ if d in {"/", path}:+ continue+ if not d.startswith(prefix + "/"):+ continue+ remainder = d[len(prefix + "/") :] if prefix else d[1:]+ if "/" in remainder or not remainder:+ continue+ children[remainder] = {+ "name": remainder,+ "isDir": True,+ "size": 0,+ "modTime": datetime.now(timezone.utc).isoformat(),+ }+ for f, content in sorted(self.files.items()):+ if not f.startswith(prefix + "/"):+ continue+ remainder = f[len(prefix + "/") :] if prefix else f[1:]+ if "/" in remainder or not remainder:+ continue+ children[remainder] = {+ "name": remainder,+ "isDir": False,+ "size": len(content),+ "modTime": datetime.now(timezone.utc).isoformat(),+ }+ return list(children.values())+++def viking_fs():+ return VikingFS(agfs=FakeAGFS())+++async def test_temp_scope_isolated_between_users_in_same_account(viking_fs):+ owner_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ role=Role.USER,+ )+ other_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ role=Role.USER,+ )++ temp_uri = viking_fs.create_temp_uri(ctx=owner_ctx)+ secret_uri = f"{temp_uri}/secret.txt"++ await viking_fs.mkdir(temp_uri, exist_ok=True, ctx=owner_ctx)+ await viking_fs.write(secret_uri, "owner secret", ctx=owner_ctx)++ assert (await viking_fs.read(secret_uri, ctx=owner_ctx)).decode("utf-8") == "owner secret"++ with pytest.raises(PermissionError):+ await viking_fs.read(secret_uri, ctx=other_ctx)++ with pytest.raises(PermissionError):+ await viking_fs.write(secret_uri, "tampered", ctx=other_ctx)+++async def test_temp_scope_user_id_matching_legacy_pattern_stays_isolated(viking_fs):+ owner_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="04011234_abcdef", agent_id="agent1"),+ role=Role.USER,+ )+ other_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ role=Role.USER,+ )++ temp_uri = viking_fs.create_temp_uri(ctx=owner_ctx)+ secret_uri = f"{temp_uri}/secret.txt"++ await viking_fs.mkdir(temp_uri, exist_ok=True, ctx=owner_ctx)+ await viking_fs.write(secret_uri, "owner secret", ctx=owner_ctx)++ assert temp_uri.startswith("viking://temp/04011234_abcdef/")+ with pytest.raises(PermissionError):+ await viking_fs.read(secret_uri, ctx=other_ctx)+++async def test_temp_root_listing_only_shows_callers_own_entries(viking_fs):+ alice_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ role=Role.USER,+ )+ bob_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ role=Role.USER,+ )++ alice_temp_uri = viking_fs.create_temp_uri(ctx=alice_ctx)+ bob_temp_uri = viking_fs.create_temp_uri(ctx=bob_ctx)++ await viking_fs.mkdir(alice_temp_uri, exist_ok=True, ctx=alice_ctx)+ await viking_fs.write(f"{alice_temp_uri}/alice.txt", "alice", ctx=alice_ctx)++ await viking_fs.mkdir(bob_temp_uri, exist_ok=True, ctx=bob_ctx)+ await viking_fs.write(f"{bob_temp_uri}/bob.txt", "bob", ctx=bob_ctx)++ alice_entries = await viking_fs.tree("viking://temp", output="original", ctx=alice_ctx)+ bob_entries = await viking_fs.tree("viking://temp", output="original", ctx=bob_ctx)++ alice_uris = {entry["uri"] for entry in alice_entries}+ bob_uris = {entry["uri"] for entry in bob_entries}++ assert any(uri.startswith(alice_temp_uri) for uri in alice_uris)+ assert not any(uri.startswith(bob_temp_uri) for uri in alice_uris)++ assert any(uri.startswith(bob_temp_uri) for uri in bob_uris)+ assert not any(uri.startswith(alice_temp_uri) for uri in bob_uris)+++async def test_temp_root_destructive_operations_are_blocked_for_non_root_users(viking_fs):+ alice_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ role=Role.USER,+ )++ with pytest.raises(PermissionError):+ await viking_fs.rm("viking://temp", recursive=True, ctx=alice_ctx)++ with pytest.raises(PermissionError):+ await viking_fs.delete_temp("viking://temp", ctx=alice_ctx)+++async def test_legacy_temp_trees_remain_accessible_for_same_account_users(viking_fs):+ alice_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ role=Role.USER,+ )+ bob_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ role=Role.USER,+ )++ legacy_temp_uri = "viking://temp/04011234_abcdef"+ legacy_secret_uri = f"{legacy_temp_uri}/legacy.txt"++ await viking_fs.mkdir(legacy_temp_uri, exist_ok=True, ctx=alice_ctx)+ await viking_fs.write(legacy_secret_uri, "legacy", ctx=alice_ctx)++ assert (await viking_fs.read(legacy_secret_uri, ctx=bob_ctx)).decode("utf-8") == "legacy"++ bob_entries = await viking_fs.tree("viking://temp", output="original", ctx=bob_ctx)+ bob_uris = {entry["uri"] for entry in bob_entries}++ assert legacy_temp_uri in bob_uris+++def test_create_temp_uri_uses_user_scope_segment(viking_fs):+ ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ role=Role.USER,+ )++ temp_uri = viking_fs.create_temp_uri(ctx=ctx)++ assert temp_uri.startswith(f"viking://temp/{ctx.user.user_space_name()}/")+++def test_create_temp_uri_without_context_preserves_legacy_shape(viking_fs):+ temp_uri = viking_fs.create_temp_uri()++ assert temp_uri.startswith("viking://temp/")+ assert temp_uri.count("/") == 3+++async def test_legacy_temp_uri_remains_accessible_to_same_account_users(viking_fs):+ alice_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ role=Role.USER,+ )+ bob_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ role=Role.USER,+ )++ legacy_temp_uri = viking_fs.create_temp_uri()+ secret_uri = f"{legacy_temp_uri}/shared.txt"++ await viking_fs.mkdir(legacy_temp_uri, exist_ok=True, ctx=alice_ctx)+ await viking_fs.write(secret_uri, "legacy temp", ctx=alice_ctx)++ assert (await viking_fs.read(secret_uri, ctx=bob_ctx)).decode("utf-8") == "legacy temp"+++async def test_non_root_cannot_delete_temp_root_recursively(viking_fs):+ alice_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ role=Role.USER,+ )+ bob_ctx = RequestContext(+ user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ role=Role.USER,+ )++ alice_temp_uri = viking_fs.create_temp_uri(ctx=alice_ctx)+ bob_temp_uri = viking_fs.create_temp_uri(ctx=bob_ctx)+ bob_secret_uri = f"{bob_temp_uri}/bob.txt"++ await viking_fs.mkdir(alice_temp_uri, exist_ok=True, ctx=alice_ctx)+ await viking_fs.mkdir(bob_temp_uri, exist_ok=True, ctx=bob_ctx)+ await viking_fs.write(bob_secret_uri, "bob secret", ctx=bob_ctx)++ with pytest.raises(PermissionError):+ await viking_fs.rm("viking://temp", recursive=True, ctx=alice_ctx)++ assert (await viking_fs.read(bob_secret_uri, ctx=bob_ctx)).decode("utf-8") == "bob secret"