Skip to content

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

fix(storage): require manage for shared resource deletion (#6643)

dingbenf6e0ed9f48e8
diff --git a/docs/en/concepts/15-acl.md b/docs/en/concepts/15-acl.md
index 473dddf2f..e97e3e48a 100644
--- a/docs/en/concepts/15-acl.md
+++ b/docs/en/concepts/15-acl.md
@@ -32,8 +32,8 @@ Asynchronous parse and semantic tasks created by a request carry the same group
| Level | Allowed operations |
|-------|--------------------|
| `read` | Read, list, and `find/search/grep` |
-| `write` | `read` capabilities plus write, create, file delete, and tag updates |
-| `manage` | `write` capabilities plus file move, move-overwrite of existing resources, directory delete/move, and ACL management |
+| `write` | `read` capabilities plus write, create, and tag updates |
+| `manage` | `write` capabilities plus file/directory delete/move and ACL management |
Each higher level includes the lower levels. A `manage` grant therefore includes `read` and `write`.
@@ -94,17 +94,13 @@ All filesystem APIs use the same permission mapping:
|-----------|---------------------|
| read, stat, list, tree, find, search, grep, glob | read |
| write, create, mkdir, set tags | write |
-| delete a file | write |
-| move a file | manage on the source file when shared-resource ACL is enabled |
+| delete or move a file | manage |
| delete or move a directory | manage on the directory and complete subtree |
| manage ACL | manage |
-| move to a new shared resource | write on the destination parent when ACL is enabled |
-| move over an existing shared resource | manage on the destination when ACL is enabled |
+| move destination parent | write |
The server canonicalizes the URI, then uses one authorization entry point for account/owner/actor-peer boundaries, effective ACLs when enabled or existing namespace rules when disabled, and write/delete namespace guards.
-When the account enables `acl.enabled`, moving a file from `viking://resources/...` requires `manage` on the source. For a destination in the shared scope, a new resource requires `write` on its parent; overwriting an existing resource requires `manage` on that destination, whether or not the source has indexed content. Directory merges apply the same destination checks to every affected node, including `manage` on existing destination nodes. With ACL disabled, or for an endpoint outside the shared scope, existing namespace rules continue to apply.
-
When the account enables `acl.enabled`, ordinary shared nodes inherit the root’s
`user:* = manage` grant, allowing members to manage their ACLs. Creating content
inside a restricted directory only inherits the parent’s permissions.
diff --git a/docs/zh/concepts/15-acl.md b/docs/zh/concepts/15-acl.md
index 2df9868b5..bd00ad698 100644
--- a/docs/zh/concepts/15-acl.md
+++ b/docs/zh/concepts/15-acl.md
@@ -32,8 +32,8 @@ ACL 条目使用带类型的 principal:
| Level | 允许的操作 |
|-------|------------|
| `read` | 读取、列目录、`find/search/grep` |
-| `write` | `read` 的能力,以及写入、创建、删除文件、修改 tags |
-| `manage` | `write` 的能力,以及移动文件、移动时覆盖已有资源、删除或移动目录、管理 ACL |
+| `write` | `read` 的能力,以及写入、创建、修改 tags |
+| `manage` | `write` 的能力,以及删除或移动文件和目录、管理 ACL |
高等级包含低等级能力。授予 `manage`,等价于同时授予 `read` 和 `write`。
@@ -90,17 +90,13 @@ read user:carol on viking://resources/A/B/C/report.md
|------|----------|
| read、stat、list、tree、find、search、grep、glob | read |
| write、create、mkdir、set tags | write |
-| 删除文件 | write |
-| 移动文件 | 共享资源 ACL 开启时,源文件的 manage |
+| 删除或移动文件 | manage |
| 删除或移动目录 | 目录及完整子树的 manage |
| 管理 ACL | manage |
-| move 目标为新建共享资源 | ACL 开启时,目标父目录的 write |
-| move 覆盖已有共享资源 | ACL 开启时,目标资源的 manage |
+| move 目标父目录 | write |
服务端会先 canonicalize URI,再在同一个鉴权入口中依次执行 account/owner/actor peer 等硬边界、开启时的有效 ACL 或关闭时的原有 namespace 规则,以及写入和删除的 namespace 防护。
-账号开启 `acl.enabled` 时,从 `viking://resources/...` 移动文件需要源文件的 `manage`。目标位于共享区时,新建资源要求目标父目录的 `write`;覆盖已有资源要求目标资源的 `manage`,无论源文件是否已有索引。目录合并会对每个受影响的目标节点执行相同检查,已有目标节点均要求 `manage`。ACL 关闭,或源、目标中的某一端不在共享区时,该端继续使用原有 namespace 规则。
-
账号开启 `acl.enabled` 时,普通共享节点继承根目录的全员 `manage`,成员可据此
修改节点 ACL。restricted 下的创建者只有父目录授予的权限,不会自动获得 `manage`。
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 3daad6096..e233fdbe3 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -9,7 +9,7 @@ Provides file system operations: ls, mkdir, rm, mv, tree, stat, read, abstract,
import asyncio
from collections.abc import Coroutine
from contextlib import asynccontextmanager
-from dataclasses import dataclass, replace
+from dataclasses import dataclass
from functools import partial
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Literal, Optional
@@ -576,6 +576,7 @@ class FSService:
) -> Optional[Dict[str, Any]]:
"""Remove resource."""
viking_fs = self._ensure_initialized()
+ await viking_fs._ensure_access(uri, ctx, action=AclAction.MANAGE)
namespace_policy = namespace_policy_for_uri(uri)
if namespace_policy.processing_mode is NamespaceProcessingMode.FILE_ONLY:
result = await viking_fs.rm(uri, recursive=recursive, ctx=ctx, no_vector=True)
@@ -997,7 +998,9 @@ class FSService:
target_stat = await viking_fs.stat(to_uri, ctx=ctx, skip_count=True)
target_is_dir = bool(target_stat.get("isDir"))
rebuild_root_uri = (
- to_uri if target_is_dir else self._semantic_refresh_parent_uri(to_uri, context_type)
+ to_uri
+ if target_is_dir
+ else self._semantic_refresh_parent_uri(to_uri, context_type)
)
if not rebuild_root_uri:
result["semantic_status"] = "skipped"
@@ -1069,6 +1072,7 @@ class FSService:
) -> None:
"""Commit move/watch state and enqueue all affected parent refreshes."""
viking_fs = self._ensure_initialized()
+ await viking_fs._ensure_access(from_uri, ctx, action=AclAction.MANAGE)
watch_manager = self._get_watch_manager()
use_watch_transaction = (
watch_manager is not None
@@ -1118,14 +1122,7 @@ class FSService:
)
except Exception as commit_error:
try:
- # The authorized move may leave the file inheriting only
- # write at its destination; rollback must still restore it.
- await viking_fs.mv(
- to_uri,
- from_uri,
- ctx=replace(ctx, bypass_acl=True),
- **options,
- )
+ await viking_fs.mv(to_uri, from_uri, ctx=ctx, **options)
except Exception as rollback_error:
logger.exception("Move rollback failed: %s -> %s", to_uri, from_uri)
raise rollback_error from commit_error
@@ -1154,7 +1151,9 @@ class FSService:
target_is_dir = bool(target_stat.get("isDir"))
context_type = context_type_for_uri(to_uri)
rebuild_root_uri = (
- to_uri if target_is_dir else self._semantic_refresh_parent_uri(to_uri, context_type)
+ to_uri
+ if target_is_dir
+ else self._semantic_refresh_parent_uri(to_uri, context_type)
)
if rebuild_root_uri:
try:
@@ -1210,11 +1209,10 @@ class FSService:
return
if move:
await versions.before_move(from_uri.rstrip("/"), to_uri.rstrip("/"), ctx)
- await viking_fs._ensure_move_source_access(from_uri, ctx)
- await viking_fs._ensure_move_target_access(to_uri, ctx)
+ await viking_fs._ensure_access(from_uri, ctx, action=AclAction.WRITE)
else:
await viking_fs._ensure_copy_source_access(from_uri, recursive=recursive, ctx=ctx)
- await viking_fs._ensure_access(to_uri, ctx, action=AclAction.WRITE)
+ await viking_fs._ensure_access(to_uri, ctx, action=AclAction.WRITE)
source_path = viking_fs._uri_to_path(from_uri, ctx=ctx)
target_path = viking_fs._uri_to_path(to_uri, ctx=ctx)
viking_fs._validate_transfer_paths(source_path, target_path)
diff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.py
index 8a7f15e5b..8ddd1fd7b 100644
--- a/openviking/storage/viking_fs/_ops.py
+++ b/openviking/storage/viking_fs/_ops.py
@@ -558,12 +558,9 @@ class _OpsMixin:
if move:
if directory or source != old_uri:
await self._ensure_access(source, ctx, action=AclAction.MANAGE)
- else:
- await self._ensure_move_source_access(source, ctx)
- await self._ensure_move_target_access(target, ctx)
else:
await self._ensure_copy_source_access(source, recursive=directory, ctx=ctx)
- await self._ensure_access(target, ctx, action=AclAction.WRITE)
+ await self._ensure_access(target, ctx, action=AclAction.WRITE)
await self._ensure_transfer_target_type(
self._uri_to_path(target, ctx=ctx), target, is_dir=directory
)
@@ -584,42 +581,6 @@ class _OpsMixin:
await visit(old_uri, new_uri, is_dir)
return source_uris
- async def _ensure_move_source_access(
- self,
- uri: str,
- ctx: Optional[RequestContext],
- ) -> None:
- """Require manage for shared-resource moves when account ACL is enabled."""
- action = (
- AclAction.MANAGE
- if is_acl_uri(uri) and await self._acl_enabled(ctx)
- else AclAction.WRITE
- )
- await self._ensure_access(uri, ctx, action=action)
-
- async def _ensure_move_target_access(
- self,
- uri: str,
- ctx: Optional[RequestContext],
- ) -> None:
- """Authorize creation in a parent or replacement of an existing resource."""
- await self._ensure_access(uri, ctx, action=AclAction.WRITE)
- if not is_acl_uri(uri) or not await self._acl_enabled(ctx):
- return
- try:
- await self._async_agfs.stat(self._uri_to_path(uri, ctx=ctx))
- except Exception as exc:
- if not is_not_found_error(exc):
- mapped = map_exception(exc, resource=uri)
- if mapped is not None:
- raise mapped from exc
- raise
- parent = VikingURI(uri).parent
- if parent is not None:
- await self._ensure_access(parent.uri, ctx, action=AclAction.WRITE)
- else:
- await self._ensure_access(uri, ctx, action=AclAction.MANAGE)
-
async def _ensure_copy_source_access(
self,
uri: str,
@@ -771,8 +732,8 @@ class _OpsMixin:
acl_enabled = await self._acl_enabled(ctx)
guard_ctx = replace(self._ctx_or_default(ctx), bypass_acl=True)
await self._ensure_access(old_uri, guard_ctx, action=AclAction.MANAGE)
- await self._ensure_move_source_access(old_uri, ctx)
- await self._ensure_move_target_access(new_uri, ctx)
+ await self._ensure_access(old_uri, ctx, action=AclAction.WRITE)
+ await self._ensure_access(new_uri, ctx, action=AclAction.WRITE)
old_scope = old_uri.rstrip("/")
new_scope = new_uri.rstrip("/")
if old_scope == new_scope:
@@ -823,19 +784,8 @@ class _OpsMixin:
)
if is_dir:
- target_lock_path = new_path
- if new_acl_scope and not await self.exists(new_uri, ctx=ctx):
- # Locking the missing target itself can create it. Lock its
- # parent so authorization can distinguish creation from overwrite.
- target_lock_path = self._transfer_parent_path(new_path)
- lock_paths = sorted({old_path, target_lock_path}, key=len)
- requests = [
- {"path": path, "kind": "tree"}
- for path in lock_paths
- if path == lock_paths[0] or not path.startswith(lock_paths[0].rstrip("/") + "/")
- ]
lease = await self._async_agfs.pathlock_acquire_batch(
- requests,
+ self._directory_transfer_lock_requests(old_path, new_path),
owner_lease_ref=lease_ref,
)
else:
@@ -2505,22 +2455,12 @@ class _OpsMixin:
ctx: Optional[RequestContext] = None,
) -> None:
"""Move file."""
- await self._ensure_move_source_access(from_uri, ctx)
- await self._ensure_move_target_access(to_uri, ctx)
+ await self._ensure_access(from_uri, ctx, action=AclAction.WRITE)
+ await self._ensure_access(to_uri, ctx, action=AclAction.WRITE)
from_path = self._uri_to_path(from_uri, ctx=ctx)
- to_path = self._uri_to_path(to_uri, ctx=ctx)
- self._validate_transfer_paths(from_path, to_path)
- lease = await self._async_agfs.pathlock_acquire_batch(
- [{"path": from_path, "kind": "exact"}, {"path": to_path, "kind": "exact"}]
- )
- try:
- await self._ensure_move_source_access(from_uri, ctx)
- await self._ensure_move_target_access(to_uri, ctx)
- content = await self.read_file_bytes(from_uri, ctx=ctx)
- await self.write_file_bytes(to_uri, content, ctx=ctx, lease_ref=lease)
- await self._async_agfs.rm(from_path, fs_ctx=self._pathlock_fs_ctx(ctx, lease))
- finally:
- await self._async_agfs.pathlock_release(lease)
+
+ await self._copy_file_through_vikingfs(from_uri, to_uri, ctx=ctx)
+ await self._async_agfs.rm(from_path)
# ========== Temp File Operations (backward compatible) ==========
diff --git a/tests/service/test_fs_service.py b/tests/service/test_fs_service.py
index 3cf759d1b..06946ca58 100644
--- a/tests/service/test_fs_service.py
+++ b/tests/service/test_fs_service.py
@@ -14,6 +14,7 @@ from openviking.server.identity import RequestContext, Role
from openviking.service.fs_service import FSService, ListingPage
from openviking.service.task_work_index import bind_task_context
from openviking.storage.abstract_overview import body_for_preview
+from openviking.storage.acl import AclAction
from openviking.storage.errors import LockAcquisitionError
from openviking.storage.viking_fs import VikingFS
from openviking_cli.exceptions import InvalidArgumentError
@@ -34,6 +35,7 @@ def run_fs_operations_inline(monkeypatch):
class _FakeVikingFS:
def __init__(self, *, rm_error=None, events=None, parent_exists=True):
+ self._ensure_access = AsyncMock()
self.rm_calls = []
self.mv_calls = []
self.cp_calls = []
@@ -907,6 +909,7 @@ async def test_resource_rm_enqueues_parent_delete_refresh_and_waits(request_cont
wait=True,
)
+ viking_fs._ensure_access.assert_awaited_once_with(uri, request_context, action=AclAction.MANAGE)
assert viking_fs.rm_calls == [{"uri": uri, "recursive": True, "ctx": request_context}]
assert len(queue_manager.messages) == 1
msg = queue_manager.messages[0]
@@ -1572,6 +1575,7 @@ async def test_system_mkdir_skips_semantic_sidecar_and_vectorization(request_con
async def test_system_rm_skips_vector_and_semantic_work(request_context):
uri = "viking://system/memory/memory_templates/custom/demo.md"
viking_fs = SimpleNamespace(
+ _ensure_access=AsyncMock(),
rm=AsyncMock(return_value={"estimated_deleted_count": 0}),
)
service = FSService(viking_fs=viking_fs)
@@ -1693,12 +1697,15 @@ async def test_indexed_copy_preserves_native_vectors_and_content_copy_refresh(re
async def test_indexed_move_preserves_native_vector_transfer(request_context):
source = "viking://resources/source/demo.md"
target = "viking://resources/target/demo.md"
- viking_fs = SimpleNamespace(mv=AsyncMock())
+ viking_fs = SimpleNamespace(_ensure_access=AsyncMock(), mv=AsyncMock())
service = FSService(viking_fs=viking_fs)
service._refresh_move_parents = AsyncMock()
await service.mv(source, target, ctx=request_context)
+ viking_fs._ensure_access.assert_awaited_once_with(
+ source, request_context, action=AclAction.MANAGE
+ )
viking_fs.mv.assert_awaited_once_with(source, target, ctx=request_context)
service._refresh_move_parents.assert_awaited_once_with(
from_uri=source,
@@ -1731,7 +1738,7 @@ async def test_move_to_system_deletes_source_vectors_without_target_index(
):
source = "viking://resources/project/demo.md"
target = "viking://system/memory/memory_templates/custom/demo.md"
- viking_fs = SimpleNamespace(mv=AsyncMock())
+ viking_fs = SimpleNamespace(_ensure_access=AsyncMock(), mv=AsyncMock())
service = FSService(viking_fs=viking_fs)
refresh = AsyncMock()
monkeypatch.setattr(service, "_refresh_move_parents", refresh)
@@ -1840,6 +1847,7 @@ async def test_move_from_system_rebuilds_target_index(request_context):
source = "viking://system/memory/memory_templates/custom/demo.md"
target = "viking://resources/project/demo.md"
viking_fs = SimpleNamespace(
+ _ensure_access=AsyncMock(),
mv=AsyncMock(),
stat=AsyncMock(return_value={"isDir": False}),
)
@@ -1876,6 +1884,7 @@ async def test_move_target_refresh_failure_does_not_roll_back_physical_move(requ
source = "viking://system/memory/memory_templates/custom/demo.md"
target = "viking://resources/project/demo.md"
viking_fs = SimpleNamespace(
+ _ensure_access=AsyncMock(),
mv=AsyncMock(),
stat=AsyncMock(return_value={"isDir": False}),
)
@@ -1893,6 +1902,7 @@ async def test_recursive_move_from_system_rebuilds_target_subtree(request_contex
source = "viking://system/compile/example-skills/demo"
target = "viking://resources/project/demo"
viking_fs = SimpleNamespace(
+ _ensure_access=AsyncMock(),
mv=AsyncMock(),
stat=AsyncMock(return_value={"isDir": True}),
)
diff --git a/tests/storage/test_viking_fs_cp.py b/tests/storage/test_viking_fs_cp.py
index 3c30ae8c7..c8542cd36 100644
--- a/tests/storage/test_viking_fs_cp.py
+++ b/tests/storage/test_viking_fs_cp.py
@@ -3,17 +3,14 @@
from __future__ import annotations
-from dataclasses import replace
from types import SimpleNamespace
-from typing import Any
from unittest.mock import AsyncMock
import pytest
from openviking.server.identity import RequestContext, Role
-from openviking.service.fs_service import FSService
from openviking.storage.abstract_overview import parse_abstract_overview
-from openviking.storage.acl import AclAction, AclEntry, AclLevel, AclMode, DirectAcl, EffectiveAcl
+from openviking.storage.acl import AclAction
from openviking.storage.viking_fs import VikingFS
from openviking_cli.exceptions import (
InvalidArgumentError,
@@ -21,7 +18,6 @@ from openviking_cli.exceptions import (
PermissionDeniedError,
)
from openviking_cli.session.user_id import UserIdentifier
-from tests.utils.mock_agfs import MockLocalAGFS
def _ctx() -> RequestContext:
@@ -936,354 +932,3 @@ async def test_mv_preserves_missing_source_error_when_orphan_cleanup_fails(monke
with pytest.raises(FileNotFoundError, match="source gone"):
await fs.mv("viking://resources/source.md", "viking://resources/target.md", ctx=_ctx())
assert not any(event[0] == "rm" for event in agfs.events)
-
-
-class _AclMoveAGFS(MockLocalAGFS):
- """Support the streaming copy used by mv with real local test files."""
-
- def write(self, path, content, ctx=None, **kwargs):
- if not isinstance(content, (str, bytes, bytearray)):
- content = b"".join(content)
- return super().write(path, content, ctx=ctx, **kwargs)
-
-
-def acl_move_storage(tmp_path):
- grants: dict[str, AclLevel] = {}
-
- async def resolve_many(uris, ctx):
- result = {}
- for uri in uris:
- ancestor = uri.rstrip("/")
- while ancestor not in grants and ancestor.startswith("viking://resources/"):
- ancestor = ancestor.rsplit("/", 1)[0]
- permissions = (
- DirectAcl((AclEntry("user:alice", grants[ancestor]),))
- if ancestor in grants
- else DirectAcl()
- )
- result[uri] = (
- EffectiveAcl(AclMode.RESTRICTED, permissions, DirectAcl())
- if ancestor == uri
- else EffectiveAcl(AclMode.INHERIT, DirectAcl(), permissions)
- )
- return result
-
- acl: Any = SimpleNamespace(
- is_enabled=AsyncMock(return_value=True),
- resolve_many=resolve_many,
- refresh_context_subtree=AsyncMock(),
- )
- agfs = _AclMoveAGFS(root_path=tmp_path)
- fs = VikingFS(agfs=agfs, acl_manager=acl)
- return SimpleNamespace(fs=fs, agfs=agfs, acl=acl, grants=grants, ctx=_user_ctx())
-
-
[email protected](params=["mv", "move_file"])
-def file_move_operation(request):
- return request.param
-
-
-def _seed_acl_move(storage, source, target, *, target_exists=True):
- source_path = storage.fs._uri_to_path(source, ctx=storage.ctx)
- target_path = storage.fs._uri_to_path(target, ctx=storage.ctx)
- storage.agfs.write(source_path, b"source content")
- storage.agfs.mkdir(target_path.rsplit("/", 1)[0])
- storage.grants.update({source: AclLevel.WRITE, target.rsplit("/", 1)[0]: AclLevel.WRITE})
- if target_exists:
- storage.agfs.write(target_path, b"existing target content")
- storage.grants[target] = AclLevel.WRITE
- return source_path, target_path
-
-
-def _acl_move_files(storage):
- return {
- str(path.relative_to(storage.agfs.root)): path.read_bytes()
- for path in storage.agfs.root.rglob("*")
- if path.is_file()
- }
-
-
- "target",
- ["viking://resources/target.md", "viking://user/alice/resources/target.md"],
-)
-async def test_resource_file_move_requires_manage_before_content_changes(
- acl_move_storage, file_move_operation, target
-):
- storage = acl_move_storage
- source = "viking://resources/source.md"
- _seed_acl_move(storage, source, target)
- before = _acl_move_files(storage)
-
- with pytest.raises(PermissionDeniedError, match="manage permission required"):
- await getattr(storage.fs, file_move_operation)(source, target, ctx=storage.ctx)
-
- assert _acl_move_files(storage) == before
-
-
[email protected]("target_level", [AclLevel.READ, AclLevel.WRITE])
-async def test_resource_file_move_to_new_target_requires_parent_write(
- acl_move_storage, file_move_operation, target_level
-):
- storage = acl_move_storage
- source, target = "viking://resources/source.md", "viking://resources/target.md"
- source_path, target_path = _seed_acl_move(storage, source, target, target_exists=False)
- storage.grants.update({source: AclLevel.MANAGE, "viking://resources": target_level})
- before = _acl_move_files(storage)
-
- if target_level is AclLevel.READ:
- with pytest.raises(PermissionDeniedError, match="write permission required"):
- await getattr(storage.fs, file_move_operation)(source, target, ctx=storage.ctx)
- assert _acl_move_files(storage) == before
- else:
- await getattr(storage.fs, file_move_operation)(source, target, ctx=storage.ctx)
- assert not storage.agfs.exists(source_path)
- assert storage.agfs.read_file(target_path) == b"source content"
-
-
[email protected]("target_level", [AclLevel.READ, AclLevel.WRITE, AclLevel.MANAGE])
-async def test_resource_file_move_overwrite_requires_target_manage(
- acl_move_storage, file_move_operation, target_level
-):
- storage = acl_move_storage
- source, target = "viking://resources/source.md", "viking://resources/target.md"
- source_path, target_path = _seed_acl_move(storage, source, target)
- storage.grants.update({source: AclLevel.MANAGE, target: target_level})
- before = _acl_move_files(storage)
-
- if target_level is AclLevel.MANAGE:
- await getattr(storage.fs, file_move_operation)(source, target, ctx=storage.ctx)
- assert not storage.agfs.exists(source_path)
- assert storage.agfs.read_file(target_path) == b"source content"
- else:
- with pytest.raises(PermissionDeniedError, match="permission required"):
- await getattr(storage.fs, file_move_operation)(source, target, ctx=storage.ctx)
- assert _acl_move_files(storage) == before
-
-
-async def test_resource_file_move_preserves_behavior_when_acl_disabled(
- acl_move_storage, file_move_operation
-):
- storage = acl_move_storage
- source, target = "viking://resources/source.md", "viking://resources/target.md"
- source_path, target_path = _seed_acl_move(storage, source, target)
- storage.acl.is_enabled.return_value = False
-
- await getattr(storage.fs, file_move_operation)(source, target, ctx=storage.ctx)
-
- assert not storage.agfs.exists(source_path)
- assert storage.agfs.read_file(target_path) == b"source content"
-
-
- "source",
- ["viking://user/alice/resources/source.md", "viking://temp/alice/source.md"],
-)
- "target_exists,target_level",
- [(False, AclLevel.WRITE), (True, AclLevel.WRITE), (True, AclLevel.MANAGE)],
-)
-async def test_non_resource_file_move_respects_resource_destination_acl(
- acl_move_storage, file_move_operation, source, target_exists, target_level
-):
- storage = acl_move_storage
- target = "viking://resources/target.md"
- source_path, target_path = _seed_acl_move(storage, source, target, target_exists=target_exists)
- if target_exists:
- storage.grants[target] = target_level
- before = _acl_move_files(storage)
-
- if target_exists and target_level is AclLevel.WRITE:
- with pytest.raises(PermissionDeniedError, match="manage permission required"):
- await getattr(storage.fs, file_move_operation)(source, target, ctx=storage.ctx)
- assert _acl_move_files(storage) == before
- else:
- await getattr(storage.fs, file_move_operation)(source, target, ctx=storage.ctx)
- assert not storage.agfs.exists(source_path)
- assert storage.agfs.read_file(target_path) == b"source content"
-
-
[email protected]("access", ["admin", "bypass"])
-async def test_resource_file_move_preserves_admin_and_internal_acl_bypass(
- acl_move_storage, file_move_operation, access
-):
- storage = acl_move_storage
- source, target = "viking://resources/source.md", "viking://resources/target.md"
- source_path, target_path = _seed_acl_move(storage, source, target)
- storage.grants.clear()
- ctx = (
- replace(storage.ctx, role=Role.ADMIN)
- if access == "admin"
- else replace(storage.ctx, bypass_acl=True)
- )
-
- await getattr(storage.fs, file_move_operation)(source, target, ctx=ctx)
-
- assert not storage.agfs.exists(source_path)
- assert storage.agfs.read_file(target_path) == b"source content"
-
-
-async def test_resource_file_move_rechecks_manage_after_acquiring_lease(
- acl_move_storage, file_move_operation, monkeypatch
-):
- storage = acl_move_storage
- source, target = "viking://resources/source.md", "viking://resources/target.md"
- _seed_acl_move(storage, source, target)
- storage.grants.update({source: AclLevel.MANAGE, target: AclLevel.MANAGE})
- before = _acl_move_files(storage)
- acquire = storage.agfs.pathlock_acquire_batch_async
-
- async def acquire_after_acl_change(*args, **kwargs):
- lease = await acquire(*args, **kwargs)
- storage.grants[source] = AclLevel.WRITE
- return lease
-
- monkeypatch.setattr(storage.agfs, "pathlock_acquire_batch_async", acquire_after_acl_change)
-
- with pytest.raises(PermissionDeniedError, match="manage permission required"):
- await getattr(storage.fs, file_move_operation)(source, target, ctx=storage.ctx)
-
- assert _acl_move_files(storage) == before
- assert not storage.agfs._pathlock_leases
-
-
-async def test_resource_file_mv_rolls_back_when_destination_lacks_manage(acl_move_storage):
- storage = acl_move_storage
- source, target = "viking://resources/source.md", "viking://resources/target.md"
- source_path, target_path = _seed_acl_move(storage, source, target, target_exists=False)
- storage.grants[source] = AclLevel.MANAGE
- before = _acl_move_files(storage)
- watch_error = RuntimeError("watch rewrite failed")
- watch_manager = SimpleNamespace(
- validate_target_prefix_rewrite_internal=AsyncMock(),
- rewrite_target_prefix_internal=AsyncMock(side_effect=watch_error),
- )
- watch_scheduler: Any = SimpleNamespace(watch_manager=watch_manager)
- service = FSService(
- viking_fs=storage.fs,
- watch_scheduler=watch_scheduler,
- )
-
- with pytest.raises(RuntimeError, match="watch rewrite failed") as error:
- await service.mv(source, target, ctx=storage.ctx)
-
- assert error.value is watch_error
- assert _acl_move_files(storage) == before
- assert storage.agfs.read_file(source_path) == b"source content"
- assert not storage.agfs.exists(target_path)
- assert not storage.agfs._pathlock_leases
-
-
[email protected]("restricted_child", ["nested", "nested/secret.md"])
-async def test_resource_directory_merge_requires_manage_on_existing_children(
- acl_move_storage, restricted_child
-):
- storage = acl_move_storage
- source, target = "viking://resources/source", "viking://resources/target"
- for uri, content in {
- f"{source}/a.md": b"new first file",
- f"{source}/nested/secret.md": b"new nested file",
- f"{target}/a.md": b"existing first file",
- f"{target}/nested/secret.md": b"existing nested file",
- }.items():
- storage.agfs.write(storage.fs._uri_to_path(uri, ctx=storage.ctx), content)
- storage.grants.update(
- {
- source: AclLevel.MANAGE,
- target: AclLevel.MANAGE,
- f"{target}/{restricted_child}": AclLevel.WRITE,
- }
- )
- before = _acl_move_files(storage)
-
- with pytest.raises(PermissionDeniedError, match="manage permission required"):
- await storage.fs.mv(source, target, ctx=storage.ctx)
-
- assert _acl_move_files(storage) == before
- assert not storage.agfs._pathlock_leases
-
-
[email protected]("materialize_tree_locks", [False, True])
-async def test_resource_directory_move_creates_nested_subtree_with_parent_write(
- acl_move_storage, monkeypatch, materialize_tree_locks
-):
- storage = acl_move_storage
- source, target = "viking://resources/source", "viking://resources/target"
- source_path = storage.fs._uri_to_path(source, ctx=storage.ctx)
- target_path = storage.fs._uri_to_path(target, ctx=storage.ctx)
- storage.agfs.write(f"{source_path}/nested/deeper/data.md", b"nested content")
- storage.grants.update({"viking://resources": AclLevel.WRITE, source: AclLevel.MANAGE})
- if materialize_tree_locks:
- acquire = storage.agfs.pathlock_acquire_batch_async
-
- async def acquire_and_materialize_tree_paths(ctx, requests, *args, **kwargs):
- lease = await acquire(ctx, requests, *args, **kwargs)
- for request in requests:
- if request["kind"] == "tree":
- storage.agfs.mkdir(request["path"])
- assert {"path": target_path.rsplit("/", 1)[0], "kind": "tree"} in requests
- assert {"path": target_path, "kind": "tree"} not in requests
- assert not storage.agfs.exists(target_path)
- return lease
-
- monkeypatch.setattr(
- storage.agfs, "pathlock_acquire_batch_async", acquire_and_materialize_tree_paths
- )
-
- await storage.fs.mv(source, target, ctx=storage.ctx)
-
- assert not storage.agfs.exists(source_path)
- assert storage.agfs.read_file(f"{target_path}/nested/deeper/data.md") == b"nested content"
- assert not storage.agfs._pathlock_leases
-
-
-async def test_resource_file_move_rechecks_target_created_before_lease(
- acl_move_storage, file_move_operation, monkeypatch
-):
- storage = acl_move_storage
- source, target = "viking://resources/source.md", "viking://resources/target.md"
- source_path, target_path = _seed_acl_move(storage, source, target, target_exists=False)
- storage.grants[source] = AclLevel.MANAGE
- acquire = storage.agfs.pathlock_acquire_batch_async
-
- async def acquire_after_target_created(*args, **kwargs):
- storage.agfs.write(target_path, b"concurrent target content")
- storage.grants[target] = AclLevel.WRITE
- return await acquire(*args, **kwargs)
-
- monkeypatch.setattr(storage.agfs, "pathlock_acquire_batch_async", acquire_after_target_created)
-
- with pytest.raises(PermissionDeniedError, match="manage permission required"):
- await getattr(storage.fs, file_move_operation)(source, target, ctx=storage.ctx)
-
- assert storage.agfs.read_file(source_path) == b"source content"
- assert storage.agfs.read_file(target_path) == b"concurrent target content"
- assert not storage.agfs._pathlock_leases
-
-
-async def test_resource_directory_move_rechecks_target_created_before_lease(
- acl_move_storage, monkeypatch
-):
- storage = acl_move_storage
- source, target = "viking://resources/source", "viking://resources/target"
- source_path = storage.fs._uri_to_path(source, ctx=storage.ctx)
- target_path = storage.fs._uri_to_path(target, ctx=storage.ctx)
- storage.agfs.write(f"{source_path}/data.md", b"source content")
- storage.grants.update({"viking://resources": AclLevel.WRITE, source: AclLevel.MANAGE})
- before = _acl_move_files(storage)
- acquire = storage.agfs.pathlock_acquire_batch_async
-
- async def acquire_after_target_created(*args, **kwargs):
- storage.agfs.mkdir(target_path)
- storage.grants[target] = AclLevel.WRITE
- return await acquire(*args, **kwargs)
-
- monkeypatch.setattr(storage.agfs, "pathlock_acquire_batch_async", acquire_after_target_created)
-
- with pytest.raises(PermissionDeniedError, match="manage permission required"):
- await storage.fs.mv(source, target, ctx=storage.ctx)
-
- assert _acl_move_files(storage) == before
- assert storage.agfs.exists(target_path)
- assert not storage.agfs._pathlock_leases