Skip to content

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

feat(acl): add account-level authorization switch (#4527)

Qin Haojie170e17c145fe
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index fb26fb651..8049e3bf3 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -1488,7 +1488,7 @@ impl HttpClient {
self.delete(&path, &[]).await
}
- pub async fn admin_set_account_auto_protect_new_content(
+ pub async fn admin_set_account_acl_enabled(
&self,
account_id: &str,
enabled: bool,
@@ -1497,8 +1497,8 @@ impl HttpClient {
self.patch(
&path,
&serde_json::json!({
- "resource_acl": {
- "auto_protect_new_content": enabled,
+ "acl": {
+ "enabled": enabled,
}
}),
&[],
@@ -2500,12 +2500,12 @@ mod tests {
let (base_url, request_rx) = spawn_request_capture_server().await;
let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);
client
- .admin_set_account_auto_protect_new_content("acct", true)
+ .admin_set_account_acl_enabled("acct", true)
.await
.expect("set account settings should succeed");
let request = request_rx.await.expect("request should be captured");
assert!(request.starts_with("PATCH /api/v1/admin/accounts/acct/settings "));
- assert!(request.contains(r#""resource_acl":{"auto_protect_new_content":true}"#));
+ assert!(request.contains(r#""acl":{"enabled":true}"#));
}
#[test]
diff --git a/crates/ov_cli/src/commands/admin.rs b/crates/ov_cli/src/commands/admin.rs
index 3a435fefd..4d33b9628 100644
--- a/crates/ov_cli/src/commands/admin.rs
+++ b/crates/ov_cli/src/commands/admin.rs
@@ -261,13 +261,13 @@ pub async fn regenerate_key(
pub async fn set_account_settings(
client: &HttpClient,
account_id: &str,
- auto_protect_new_content: bool,
+ acl_enabled: bool,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
show_admin(
client
- .admin_set_account_auto_protect_new_content(account_id, auto_protect_new_content)
+ .admin_set_account_acl_enabled(account_id, acl_enabled)
.await?,
output_format,
compact,
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index 8b7e8b45b..dee9e1112 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -789,12 +789,12 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {
}
AdminCommands::SetAccountSettings {
account_id,
- auto_protect_new_content,
+ acl_enabled,
} => {
commands::admin::set_account_settings(
&client,
&account_id,
- auto_protect_new_content,
+ acl_enabled,
ctx.output_format,
ctx.compact,
)
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 2b843d4c3..2e38a3006 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -2020,14 +2020,14 @@ enum AdminCommands {
/// Account ID
#[arg(value_name = "account-id")]
account_id: String,
- /// Automatically protect newly created shared content
+ /// Enable ACL authorization for shared resources
#[arg(
long,
required = true,
action = ArgAction::Set,
value_name = "true|false"
)]
- auto_protect_new_content: bool,
+ acl_enabled: bool,
},
}
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.md
index 70471e31f..044f139df 100644
--- a/docs/en/api/08-admin.md
+++ b/docs/en/api/08-admin.md
@@ -131,7 +131,7 @@ Content-Type: application/json
ROOT can manage any account and ADMIN can manage only its own account. The
generic settings endpoint accepts only explicitly allowlisted fields. It currently
-allows `agent_evolution.enabled` and `resource_acl.auto_protect_new_content`.
+allows `agent_evolution.enabled` and `acl.enabled`.
```http
GET /api/v1/admin/accounts/{account_id}/settings
@@ -140,18 +140,18 @@ Content-Type: application/json
{
"agent_evolution": {"enabled": true},
- "resource_acl": {"auto_protect_new_content": true}
+ "acl": {"enabled": true}
}
```
-`resource_acl.auto_protect_new_content` defaults to `false`. When enabled, newly
-created shared files, directories, and `add-resource` roots grant their creator
-direct `manage` while inheriting the parent ACL. Existing content is not migrated
-or modified. Disabling it again affects only later creations; existing ACLs remain
-effective.
+`acl.enabled` defaults to `false`. While disabled, shared resources use the
+original public behavior and ACL authorization is skipped. When enabled, newly
+created shared resources receive ACL fields and ACL-protected shared resources
+are authorized against them. Existing content without an ACL is not migrated or
+modified. Disabling the setting also stops enforcing existing ACLs.
```bash
-ov --sudo admin set-account-settings acme --auto-protect-new-content true
+ov --sudo admin set-account-settings acme --acl-enabled true
```
Before an existing setting is replaced, it is backed up to
diff --git a/docs/en/api/12-acl.md b/docs/en/api/12-acl.md
index e3dc2890f..0b55ca21d 100644
--- a/docs/en/api/12-acl.md
+++ b/docs/en/api/12-acl.md
@@ -17,13 +17,12 @@ Read [Resource Access Control (ACL)](../concepts/15-acl.md) for the permission a
Every endpoint requires `manage` on the target node. Account `ADMIN`s implicitly manage shared resources.
`viking://resources` is a fixed shared scope and cannot carry a direct ACL. The
-account setting `resource_acl.auto_protect_new_content` defaults to `false`: new
-content under a parent without ACLs keeps the legacy shared behavior, while a new
-file or directory under an ACL-controlled parent inherits the parent permissions
-and grants its creator direct `manage`. When the setting is enabled, newly created
-shared files, directories, and `add-resource` roots grant the creator direct
-`manage` even under an ACL-free parent; existing content remains unchanged.
-Descendants within an `add-resource` import only inherit that grant.
+account setting `acl.enabled` defaults to `false`. While disabled, shared
+resources use the original public behavior and ACL authorization is skipped.
+When enabled, newly created shared files, directories, and `add-resource` roots
+grant the creator direct `manage` and inherit the parent ACL. Existing content
+without an ACL remains public. Descendants within an `add-resource` import only
+inherit the root grant.
## Data Structures
diff --git a/docs/en/concepts/15-acl.md b/docs/en/concepts/15-acl.md
index 219a848af..b6b9d1e10 100644
--- a/docs/en/concepts/15-acl.md
+++ b/docs/en/concepts/15-acl.md
@@ -63,16 +63,15 @@ Removing the group's direct ACL from `A/B` does not remove entries from `A` or `
## Default Behavior and `acl_enabled`
-The account-level `resource_acl.auto_protect_new_content` setting is disabled by
-default. While disabled, creating a file or directory under an ACL-free parent
-keeps the existing URI namespace visibility and write rules. Under an
-ACL-controlled parent, the creator receives direct `manage` and inherits the
-parent permissions.
+The account-level `acl.enabled` setting is disabled by default. While disabled,
+shared resources keep the existing URI namespace visibility and write rules.
+ACLs are neither resolved nor enforced, and new content does not receive ACL
+fields.
When enabled, a newly created shared file or directory grants its creator direct
-`manage` on its first context record even under an ACL-free parent; parent
-permissions are still merged as inherited ACL. Existing content is not migrated
-or modified, and disabling the setting again affects only later creations.
+`manage` on its first context record, and parent permissions are merged as
+inherited ACL. Existing content without an ACL is not migrated or modified and
+remains public. Disabling the setting also stops enforcing existing ACLs.
`add-resource` treats only the generated import root (or the root file with
`no_split`) as the created node: the root gets the direct creator grant and
descendants only inherit it. Re-embedding or replacing an existing context record
@@ -101,10 +100,9 @@ All filesystem APIs use the same permission mapping:
The server canonicalizes the URI, then uses one authorization entry point for account/owner/actor-peer boundaries, the effective ACL or legacy fallback, and write/delete namespace guards.
-Under an ACL-controlled parent, or when the account enables
-`auto_protect_new_content`, a new shared node is bootstrapped by its creator's
-direct `manage` grant. Otherwise only the shared scope's implicit `manage` identity can
-establish the first ACL. Later ACL changes require effective `manage` capability.
+When the account enables `acl.enabled`, a new shared node is bootstrapped by its
+creator's direct `manage` grant. Later ACL changes require effective `manage`
+capability.
An ACL grant on a directory is inherited by every descendant. `list`, `tree`, and other batch results still check every returned node because an ACL-free directory may be visible under legacy URI rules while one of its descendants has entered the ACL-controlled domain through its own ACL.
@@ -130,13 +128,14 @@ The request principals are `user:{ctx.user_id}`, `user:*`, and one `group:{group
A retrieval target URI is only a search scope; the caller does not need to read the target node itself. A user can discover a deeply shared file even when intermediate directories are not readable.
-Shared-scope context writes preserve an existing direct ACL for the same URI.
-Under an ACL-controlled parent, or when the account enables
-`auto_protect_new_content`, a newly created node receives direct `manage` for its
-creator and derives inherited ACL fields from its parent; otherwise it remains
-`acl_enabled=false`. Descendants created by `add-resource` only inherit from the
-import root. Re-embedding and ordinary replacement writes cannot reset controlled
-records to default visibility or modify ACLs through regular context fields.
+When the account enables `acl.enabled`, shared-scope context writes preserve an
+existing direct ACL for the same URI. A newly created node receives direct
+`manage` for its creator and derives inherited ACL fields from its parent.
+Descendants created by `add-resource` only inherit from the import root.
+Re-embedding and ordinary replacement writes cannot reset controlled records to
+default visibility or modify ACLs through regular context fields. When the
+account disables the switch, retrieval uses only the original account and URI
+scope filters and ignores these ACL fields.
## Example
diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.md
index b9be1f05f..7b3ef84b3 100644
--- a/docs/zh/api/08-admin.md
+++ b/docs/zh/api/08-admin.md
@@ -130,7 +130,7 @@ Content-Type: application/json
ROOT 可管理任意 account,ADMIN 仅可管理自己所属的 account。通用配置接口仅允许
显式列入白名单的字段;当前允许修改 `agent_evolution.enabled` 和
-`resource_acl.auto_protect_new_content`。
+`acl.enabled`。
```http
GET /api/v1/admin/accounts/{account_id}/settings
@@ -139,16 +139,16 @@ Content-Type: application/json
{
"agent_evolution": {"enabled": true},
- "resource_acl": {"auto_protect_new_content": true}
+ "acl": {"enabled": true}
}
```
-`resource_acl.auto_protect_new_content` 默认为 `false`。开启后,账号内新建的共享
-文件、目录和 `add-resource` 根节点会给创建者直接 `manage`,同时继承父目录
-ACL;已有内容不会迁移或改权。重新关闭只影响后续创建,已有 ACL 继续生效。
+`acl.enabled` 默认为 `false`。关闭时,共享资源按原有规则完全共享,不执行 ACL
+鉴权。开启后,账号内新增共享资源会写入 ACL,并对带 ACL 的共享资源执行鉴权;
+已有且未设置 ACL 的内容不会迁移或改权。重新关闭后,已有 ACL 也不再参与访问判断。
```bash
-ov --sudo admin set-account-settings acme --auto-protect-new-content true
+ov --sudo admin set-account-settings acme --acl-enabled true
```
覆盖已有配置前,内核会先备份到
diff --git a/docs/zh/api/12-acl.md b/docs/zh/api/12-acl.md
index 1b6377fe8..59f3de6bb 100644
--- a/docs/zh/api/12-acl.md
+++ b/docs/zh/api/12-acl.md
@@ -17,10 +17,9 @@ ACL API 管理 `viking://resources/...` 共享资源的直接授权,并返回
所有接口都要求调用者对目标节点拥有 `manage`。共享资源由 account `ADMIN` 隐式管理。
`viking://resources` 是固定共享 scope,不能设置直接 ACL。账号配置
-`resource_acl.auto_protect_new_content` 默认为 `false`:父目录没有 ACL 时,新建内容
-继续使用原有公开规则;父目录已有 ACL 时,新建文件或目录会继承父权限,并给创建者
-直接 `manage`。开启该配置后,即使父目录没有 ACL,新建共享文件、目录和
-`add-resource` 根节点也会给创建者直接 `manage`;已有内容保持原样。
+`acl.enabled` 默认为 `false`。关闭时,共享资源完全使用原有公开规则,不执行 ACL
+鉴权;开启后,新建共享文件、目录和 `add-resource` 根节点会给创建者直接
+`manage`,同时继承父目录 ACL。已有且未设置 ACL 的内容仍按公开规则访问;
`add-resource` 的内部节点只继承,不重复写直接权限。
## 数据结构
diff --git a/docs/zh/concepts/15-acl.md b/docs/zh/concepts/15-acl.md
index 66c614ffd..cacfb92ae 100644
--- a/docs/zh/concepts/15-acl.md
+++ b/docs/zh/concepts/15-acl.md
@@ -63,15 +63,14 @@ read user:carol on viking://resources/A/B/C/report.md
## 默认行为与 `acl_enabled`
-账号级 `resource_acl.auto_protect_new_content` 默认关闭。关闭时,如果父目录没有
-ACL,新建文件或目录不会自动开启 ACL,继续使用原有 URI namespace 可见性和写入
-规则;父目录已有 ACL 时,创建者获得直接 `manage`,并继承父目录权限。
+账号级 `acl.enabled` 默认关闭。关闭时,共享资源继续使用原有 URI namespace
+可见性和写入规则,不解析或校验 ACL,也不为新建内容写入 ACL。
-开启后,新建共享文件或目录即使位于无 ACL 的父目录下,创建者也会在首条 context
-记录上获得直接 `manage`;父目录权限仍作为继承 ACL 合并。已有内容不会迁移或
-改权,重新关闭也只影响后续创建。`add-resource` 只把本次生成的根目录(`no_split`
-时为根文件)作为创建节点:根节点获得创建者直接 `manage`,内部节点只继承,
-不重复写直接授权。重新向量化或覆盖已有 context 不会改变直接 ACL。
+开启后,新建共享文件或目录的创建者会在首条 context 记录上获得直接 `manage`;
+父目录权限作为继承 ACL 合并。已有且未设置 ACL 的内容不会迁移或改权,仍按公开
+规则访问;重新关闭后,已有 ACL 也不再参与访问判断。`add-resource` 只把本次生成
+的根目录(`no_split` 时为根文件)作为创建节点:根节点获得创建者直接 `manage`,
+内部节点只继承,不重复写直接授权。重新向量化或覆盖已有 context 不会改变直接 ACL。
只要节点或任一祖先存在直接 ACL,该节点就进入 ACL 控制域:
@@ -96,9 +95,8 @@ acl_enabled = true
服务端会先 canonicalize URI,再在同一个鉴权入口中依次执行 account/owner/actor peer 等硬边界、有效 ACL 或 legacy fallback,以及写入和删除的 namespace 防护。
-父目录已有 ACL,或账号开启 `auto_protect_new_content` 时,新建共享节点由创建者的
-直接 `manage` 完成权限 bootstrap。其他情况下,首次设置 ACL 只能由共享区隐式
-管理者完成;启用后,后续 ACL 修改要求有效 `manage` 能力。
+账号开启 `acl.enabled` 时,新建共享节点由创建者的直接 `manage` 完成权限
+bootstrap,后续 ACL 修改要求有效 `manage` 能力。
目录上的 ACL 授权会被所有后代继承。`list`、`tree` 和批量结果仍逐个检查有效 ACL,因为未设置 ACL 的目录可能按原有 URI 规则可见,而某个后代已经通过自己的 ACL 进入控制域。
@@ -124,11 +122,11 @@ acl_inherited_grants
检索 target URI 只是搜索范围,不要求调用者能够读取 target 节点本身。用户即使不能读取中间目录,也可以检索到深层单独授权给自己的文件。
-共享区 context 写入会保留同 URI 已有 direct ACL。父目录已开启 ACL,或账号开启
-`auto_protect_new_content` 时,新创建节点为创建者生成直接 `manage`,并从父节点
-生成 inherited ACL;否则保持 `acl_enabled=false`。`add-resource` 的内部节点只继承
-导入根节点。重新向量化和普通覆盖写不会把受控记录恢复为默认可见,也不能通过
-普通 context 字段直接改 ACL。
+账号开启 `acl.enabled` 时,共享区 context 写入会保留同 URI 已有 direct ACL;
+新创建节点为创建者生成直接 `manage`,并从父节点生成 inherited ACL。
+`add-resource` 的内部节点只继承导入根节点。重新向量化和普通覆盖写不会把受控记录
+恢复为默认可见,也不能通过普通 context 字段直接改 ACL。账号关闭该开关时,检索
+只使用原有 account 和 URI scope 过滤,不使用这些 ACL 字段。
## 示例
diff --git a/openviking/retrieve/hierarchical_retriever.py b/openviking/retrieve/hierarchical_retriever.py
index 890527085..fbce14750 100644
--- a/openviking/retrieve/hierarchical_retriever.py
+++ b/openviking/retrieve/hierarchical_retriever.py
@@ -232,7 +232,7 @@ class HierarchicalRetriever:
telemetry.count("vector.scanned", len(global_results))
leaf_results: List[Dict[str, Any]] = []
- if self.vector_store.acl_manager is not None and (level is None or 2 in level):
+ if self.vector_store._acl_enabled(ctx) and (level is None or 2 in level):
leaf_results = await vector_proxy.search_in_tenant(
query_vector=query_vector,
sparse_query_vector=sparse_query_vector,
diff --git a/openviking/server/account_settings.py b/openviking/server/account_settings.py
index e6b79fc03..b772ca93a 100644
--- a/openviking/server/account_settings.py
+++ b/openviking/server/account_settings.py
@@ -31,10 +31,10 @@ class AccountAgentEvolutionSettings(BaseModel):
model_config = {"extra": "forbid"}
-class AccountResourceAclSettings(BaseModel):
- """Account-scoped defaults for newly created shared content."""
+class AccountAclSettings(BaseModel):
+ """Account-scoped ACL switch."""
- auto_protect_new_content: bool = False
+ enabled: bool = False
model_config = {"extra": "forbid"}
@@ -46,7 +46,7 @@ class AccountSettings(BaseModel):
"""
agent_evolution: Optional[AccountAgentEvolutionSettings] = None
- resource_acl: Optional[AccountResourceAclSettings] = None
+ acl: Optional[AccountAclSettings] = None
model_config = {"extra": "forbid"}
@@ -55,7 +55,7 @@ class AccountSettingsPatch(BaseModel):
"""Allowlisted account settings accepted by the update API."""
agent_evolution: Optional[AccountAgentEvolutionSettings] = None
- resource_acl: Optional[AccountResourceAclSettings] = None
+ acl: Optional[AccountAclSettings] = None
model_config = {"extra": "forbid"}
@@ -126,10 +126,10 @@ def effective_agent_evolution_enabled(
return settings.agent_evolution.enabled
-def effective_auto_protect_new_content(settings: AccountSettings) -> bool:
- if settings.resource_acl is None:
+def effective_acl_enabled(settings: AccountSettings) -> bool:
+ if settings.acl is None:
return False
- return settings.resource_acl.auto_protect_new_content
+ return settings.acl.enabled
async def update_account_settings(
@@ -163,9 +163,13 @@ async def update_account_settings(
updated = current.model_copy(deep=True)
if patch.agent_evolution is not None:
updated.agent_evolution = patch.agent_evolution.model_copy(deep=True)
- if patch.resource_acl is not None:
- updated.resource_acl = patch.resource_acl.model_copy(deep=True)
+ if patch.acl is not None:
+ updated.acl = patch.acl.model_copy(deep=True)
if updated == current:
+ if patch.acl is not None:
+ if viking_fs.acl_manager is None:
+ raise RuntimeError("ACL is not initialized")
+ viking_fs.acl_manager.set_enabled(account_id, updated.acl.enabled)
return current
encoded = json.dumps(
@@ -198,6 +202,10 @@ async def update_account_settings(
account_id,
)
raise
+ if patch.acl is not None:
+ if viking_fs.acl_manager is None:
+ raise RuntimeError("ACL is not initialized")
+ viking_fs.acl_manager.set_enabled(account_id, updated.acl.enabled)
return updated
finally:
await client.pathlock_release(lease)
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 2c66db920..04870dc1c 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -140,6 +140,15 @@ async def _initialize_runtime_state(
"""Initialize service and auth dependencies before traffic is accepted."""
await service.initialize()
await _initialize_auth_plugin(app, service, config)
+ manager = app.state.api_key_manager
+ if manager is not None:
+ await service.load_acl_settings(
+ [
+ item["account_id"]
+ for item in manager.get_accounts()
+ if item["account_id"] != service.user.account_id
+ ]
+ )
from openviking.service.user_deletion import setup_user_deletion
app.state.user_deletion_service = await setup_user_deletion(
diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.py
index 09b8371bb..f92bea26e 100644
--- a/openviking/server/routers/admin.py
+++ b/openviking/server/routers/admin.py
@@ -12,7 +12,7 @@ from openviking.server.account_settings import (
AccountAgentEvolutionSettings,
AccountSettings,
AccountSettingsPatch,
- effective_auto_protect_new_content,
+ effective_acl_enabled,
read_account_settings,
update_account_settings,
)
@@ -187,8 +187,8 @@ async def _account_settings_result(
"agent_evolution": {
"enabled": enabled,
},
- "resource_acl": {
- "auto_protect_new_content": effective_auto_protect_new_content(settings),
+ "acl": {
+ "enabled": effective_acl_enabled(settings),
},
},
"overrides": settings.model_dump(exclude_none=True),
diff --git a/openviking/service/core.py b/openviking/service/core.py
index 0e90af639..ddada608f 100644
--- a/openviking/service/core.py
+++ b/openviking/service/core.py
@@ -15,7 +15,7 @@ from openviking.privacy import UserPrivacyConfigService
from openviking.resource.uri_mutation_coordinator import UriMutationCoordinator
from openviking.resource.watch_scheduler import WatchScheduler
from openviking.server.account_settings import (
- effective_auto_protect_new_content,
+ effective_acl_enabled,
read_account_settings,
)
from openviking.server.identity import RequestContext, Role
@@ -185,10 +185,7 @@ class OpenVikingService:
self._vikingdb_manager = VikingDBManager(
vectordb_config=config.vectordb, queue_manager=self._queue_manager
)
- self._vikingdb_manager.acl_manager = AclManager(
- self._vikingdb_manager,
- auto_protect_new_content=self._auto_protect_new_content,
- )
+ self._vikingdb_manager.acl_manager = AclManager(self._vikingdb_manager)
# Configure queues if QueueManager is available.
# Workers are NOT started here — start() is called after VikingFS is initialized
@@ -204,11 +201,17 @@ class OpenVikingService:
binding_config, self._encryptor = build_runtime_ragfs_binding_config(self._config)
return binding_config
- async def _auto_protect_new_content(self, account_id: str) -> bool:
+ async def load_acl_settings(self, account_ids: list[str]) -> None:
if self._viking_fs is None:
raise NotInitializedError("VikingFS")
- settings = await read_account_settings(self._viking_fs, account_id)
- return effective_auto_protect_new_content(settings)
+ if self._vikingdb_manager is None or self._vikingdb_manager.acl_manager is None:
+ raise NotInitializedError("ACL")
+ for account_id in dict.fromkeys(account_ids):
+ settings = await read_account_settings(self._viking_fs, account_id)
+ self._vikingdb_manager.acl_manager.set_enabled(
+ account_id,
+ effective_acl_enabled(settings),
+ )
def _ensure_data_dir_lock_acquired(self) -> None:
"""Acquire the process-level data directory lock once for this service instance."""
@@ -369,6 +372,7 @@ class OpenVikingService:
)
if enable_recorder:
logger.info("VikingFS IO Recorder enabled")
+ await self.load_acl_settings([self._user.account_id])
self._resource_processor = ResourceProcessor(
vikingdb=self._vikingdb_manager,
@@ -388,7 +392,6 @@ class OpenVikingService:
account_count,
user_count,
)
-
self._privacy_config_service = UserPrivacyConfigService(self._viking_fs)
# Initialize processors
diff --git a/openviking/storage/acl.py b/openviking/storage/acl.py
index 0f012813f..c7f9c624d 100644
--- a/openviking/storage/acl.py
+++ b/openviking/storage/acl.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
-from typing import TYPE_CHECKING, Any, Awaitable, Callable, Iterable, Mapping, Sequence
+from typing import TYPE_CHECKING, Any, Iterable, Mapping, Sequence
from openviking.core.identifiers import validate_identifier_part, validate_user_id
from openviking.core.namespace import uri_parts
@@ -220,10 +220,18 @@ class AclManager:
def __init__(
self,
context_store: "VikingVectorIndexBackend",
- auto_protect_new_content: Callable[[str], Awaitable[bool]] | None = None,
) -> None:
self._context_store = context_store
- self._auto_protect_new_content = auto_protect_new_content
+ self._enabled_accounts: set[str] = set()
+
+ def set_enabled(self, account_id: str, enabled: bool) -> None:
+ if enabled:
+ self._enabled_accounts.add(account_id)
+ else:
+ self._enabled_accounts.discard(account_id)
+
+ def is_enabled(self, account_id: str) -> bool:
+ return account_id in self._enabled_accounts
@staticmethod
def _effective_from_record(record: Mapping[str, Any]) -> EffectiveAcl:
@@ -346,6 +354,12 @@ class AclManager:
async def materialize_context_records(
self, records: Sequence[dict[str, Any]], ctx: RequestContext
) -> list[dict[str, Any]]:
+ if not self.is_enabled(ctx.account_id):
+ return [
+ {key: value for key, value in record.items() if key != ACL_CREATOR_GRANT_FIELD}
+ for record in records
+ ]
+
resource_uris: set[str] = set()
for record in records:
uri = record.get("uri")
@@ -370,8 +384,6 @@ class AclManager:
parents[uri] = ancestors[-2] if len(ancestors) > 1 else None
parent_acl = await self.resolve_many([parent for parent in parents.values() if parent], ctx)
- auto_protect_new_content: bool | None = None
-
materialized: list[dict[str, Any]] = []
for record in records:
record = dict(record)
@@ -389,20 +401,7 @@ class AclManager:
inherited = parent_acl[parent].permissions if parent else DirectAcl()
direct = DirectAcl()
creator = (record.get("user") or {}).get("user_id")
- protect_created = bool(parent and parent_acl[parent].enabled)
- if (
- creator
- and creator_grant is not None
- and parent
- and not protect_created
- and self._auto_protect_new_content is not None
- ):
- if auto_protect_new_content is None:
- auto_protect_new_content = await self._auto_protect_new_content(
- ctx.account_id
- )
- protect_created = auto_protect_new_content
- if creator and creator_grant is not None and protect_created:
+ if creator and creator_grant is not None:
creator_acl = DirectAcl.from_entries(
[AclEntry(f"user:{creator}", AclLevel.MANAGE)]
)
diff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.py
index 12e249ad6..c7b85a2c3 100644
--- a/openviking/storage/viking_fs/_access.py
+++ b/openviking/storage/viking_fs/_access.py
@@ -177,7 +177,7 @@ class _AccessMixin:
valid.append(uri)
acl_manager = self.acl_manager
- if acl_manager is None:
+ if acl_manager is None or not acl_manager.is_enabled(real_ctx.account_id):
result.update({uri: self._is_accessible(uri, real_ctx) for uri in valid})
return result
@@ -263,10 +263,16 @@ class _AccessMixin:
self, uri: str, ctx: Optional[RequestContext]
) -> None:
self._safe_uri_parts(uri)
- if self.acl_manager is not None and is_acl_uri(uri):
+ if self._acl_enabled(ctx) and is_acl_uri(uri):
return
await self._ensure_access(uri, ctx)
+ def _acl_enabled(self, ctx: Optional[RequestContext]) -> bool:
+ real_ctx = self._ctx_or_default(ctx)
+ return self.acl_manager is not None and self.acl_manager.is_enabled(
+ real_ctx.account_id
+ )
+
async def _ensure_acl_manage(
self, uri: str, ctx: Optional[RequestContext]
) -> RequestContext:
@@ -479,7 +485,7 @@ class _AccessMixin:
if not self._is_name_visible_at_path(name, parent_path):
return False
- if self.acl_manager is None:
+ if not self._acl_enabled(ctx):
uri = self._path_to_uri(entry_path, ctx=ctx)
if not self._is_accessible(uri, ctx):
return False
@@ -544,6 +550,7 @@ class _AccessMixin:
raw_limit: Optional[int] = None
else:
raw_limit = max(node_limit * self._TREE_OVERFETCH_FACTOR, node_limit)
+ acl_enabled = self._acl_enabled(real_ctx)
while True:
raw_entries = await self._async_agfs.tree_directory(
@@ -567,16 +574,14 @@ class _AccessMixin:
)
candidates.append((entry, entry_uri))
if (
- self.acl_manager is None
+ not acl_enabled
and node_limit is not None
and len(candidates) >= node_limit
):
break
- expose_resource_names = bool(
- self.acl_manager is not None and is_acl_uri(uri)
- )
- if self.acl_manager is None:
+ expose_resource_names = acl_enabled and is_acl_uri(uri)
+ if not acl_enabled:
visible = candidates
else:
access = await self._can_access_many(
diff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.py
index 4def75a05..c5773cdb6 100644
--- a/openviking/storage/viking_fs/_ops.py
+++ b/openviking/storage/viking_fs/_ops.py
@@ -228,7 +228,7 @@ class _OpsMixin:
path,
recursive,
ctx=ctx,
- strict=is_dir and self.acl_manager is not None,
+ strict=is_dir and self._acl_enabled(ctx),
)
if is_dir
else []
@@ -312,6 +312,7 @@ class _OpsMixin:
"""
acl_manager = self.acl_manager
+ acl_enabled = 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_access(old_uri, ctx, action=AclAction.WRITE)
@@ -319,7 +320,7 @@ class _OpsMixin:
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)
- new_acl_scope = acl_manager is not None and is_acl_uri(new_uri)
+ new_acl_scope = acl_enabled and is_acl_uri(new_uri)
# Verify source exists and determine type before locking.
try:
@@ -380,7 +381,7 @@ class _OpsMixin:
old_path,
recursive=True,
ctx=ctx,
- strict=is_dir and acl_manager is not None,
+ strict=is_dir and acl_enabled,
)
if is_dir
else []
@@ -423,7 +424,7 @@ class _OpsMixin:
vector_mappings = await self._update_vector_store_uris(
uris_to_move, old_uri, new_uri, ctx=ctx
)
- if acl_manager and new_acl_scope:
+ if acl_manager is not None and new_acl_scope:
await acl_manager.refresh_context_subtree(
new_uri,
self._ctx_or_default(ctx),
@@ -1539,9 +1540,7 @@ class _OpsMixin:
"""Return list entries according to namespace-enumeration semantics."""
entry_items = await self._list_read_path_items(uri, ctx=ctx)
access = await self._can_access_many([entry_uri for _, entry_uri in entry_items], ctx)
- expose_resource_names = bool(
- self.acl_manager is not None and is_acl_uri(uri)
- )
+ expose_resource_names = self._acl_enabled(ctx) and is_acl_uri(uri)
browsable = []
for entry, entry_uri in entry_items:
diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.py
index 0920bf58e..23b78de8c 100644
--- a/openviking/storage/viking_vector_index_backend.py
+++ b/openviking/storage/viking_vector_index_backend.py
@@ -1492,7 +1492,7 @@ class VikingVectorIndexBackend:
"id": new_id,
"uri": new_uri,
}
- if self.acl_manager:
+ if self._acl_enabled(ctx):
updated.update(
await self.acl_manager.materialize_moved_record(record, new_uri, ctx)
)
@@ -1562,7 +1562,7 @@ class VikingVectorIndexBackend:
tenant_filter = self._tenant_filter(ctx)
if (
tenant_filter
- and not self.acl_manager
+ and not self._acl_enabled(ctx)
and self._targets_within_visible_roots(ctx, targets)
):
# The target scopes are already narrower than the tenant-visible
@@ -1609,7 +1609,7 @@ class VikingVectorIndexBackend:
return None
account_filter = Eq("account_id", ctx.account_id)
- if not self.acl_manager:
+ if not self._acl_enabled(ctx):
return And(
[
account_filter,
@@ -1644,6 +1644,9 @@ class VikingVectorIndexBackend:
access_filters.append(PathScope("uri", "viking://resources", depth=-1))
return And([account_filter, Or(access_filters)])
+ def _acl_enabled(self, ctx: RequestContext) -> bool:
+ return self.acl_manager is not None and self.acl_manager.is_enabled(ctx.account_id)
+
@staticmethod
def _merge_filters(*filters: Optional[FilterExpr]) -> Optional[FilterExpr]:
non_empty = [
diff --git a/tests/retrieve/test_hierarchical_retriever_rerank.py b/tests/retrieve/test_hierarchical_retriever_rerank.py
index b2ab7675f..d1c44acd2 100644
--- a/tests/retrieve/test_hierarchical_retriever_rerank.py
+++ b/tests/retrieve/test_hierarchical_retriever_rerank.py
@@ -6,6 +6,7 @@
import asyncio
import threading
import time
+from types import SimpleNamespace
import pytest
@@ -55,6 +56,9 @@ class DummyStorage:
self.search_calls = []
self.child_search_calls = []
+ def _acl_enabled(self, ctx: RequestContext) -> bool:
+ return self.acl_manager is not None and self.acl_manager.is_enabled(ctx.account_id)
+
async def collection_exists_bound(self) -> bool:
return True
@@ -370,7 +374,7 @@ async def test_retrieve_falls_back_to_vector_scores_when_rerank_returns_none(mon
_result("viking://resources/a/deep-a.md", 0.2, abstract="deep A"),
_result("viking://resources/b/deep-b.md", 0.8, abstract="deep B"),
])
- storage.acl_manager = object()
+ storage.acl_manager = SimpleNamespace(is_enabled=lambda _account_id: True)
async def no_hierarchical_children(*_args, **_kwargs):
return []
diff --git a/tests/server/test_agent_evolution_global_setting.py b/tests/server/test_agent_evolution_global_setting.py
index 234c5bfc3..bd875cc3d 100644
--- a/tests/server/test_agent_evolution_global_setting.py
+++ b/tests/server/test_agent_evolution_global_setting.py
@@ -11,8 +11,8 @@ import pytest_asyncio
from openviking.pyagfs import AGFSNotFoundError
from openviking.server.account_settings import (
+ AccountAclSettings,
AccountAgentEvolutionSettings,
- AccountResourceAclSettings,
AccountSettingsPatch,
account_settings_backup_path,
account_settings_path,
@@ -67,9 +67,23 @@ class _FakeAGFS:
del lease
+class _FakeAclManager:
+ def __init__(self):
+ self.enabled_accounts: set[str] = set()
+
+ def set_enabled(self, account_id: str, enabled: bool) -> None:
+ if enabled:
+ self.enabled_accounts.add(account_id)
+ else:
+ self.enabled_accounts.discard(account_id)
+
+ def is_enabled(self, account_id: str) -> bool:
+ return account_id in self.enabled_accounts
+
+
@pytest.fixture
def fake_viking_fs():
- return SimpleNamespace(agfs=_FakeAGFS())
+ return SimpleNamespace(agfs=_FakeAGFS(), acl_manager=_FakeAclManager())
@pytest_asyncio.fixture
@@ -212,7 +226,7 @@ async def test_account_settings_admin_api_reads_and_updates_effective_value(
"account_id": "default",
"settings": {
"agent_evolution": {"enabled": False},
- "resource_acl": {"auto_protect_new_content": False},
+ "acl": {"enabled": False},
},
"overrides": {},
}
@@ -221,21 +235,20 @@ async def test_account_settings_admin_api_reads_and_updates_effective_value(
"/api/v1/admin/accounts/default/settings",
json={
"agent_evolution": {"enabled": True},
- "resource_acl": {"auto_protect_new_content": True},
+ "acl": {"enabled": True},
},
)
assert updated.status_code == 200, updated.text
assert updated.json()["result"]["settings"]["agent_evolution"]["enabled"] is True
- assert updated.json()["result"]["settings"]["resource_acl"] == {
- "auto_protect_new_content": True
- }
+ assert updated.json()["result"]["settings"]["acl"] == {"enabled": True}
assert updated.json()["result"]["overrides"] == {
"agent_evolution": {"enabled": True},
- "resource_acl": {"auto_protect_new_content": True},
+ "acl": {"enabled": True},
}
settings = await read_account_settings(service.viking_fs, "default")
assert settings.agent_evolution.enabled
- assert settings.resource_acl == AccountResourceAclSettings(auto_protect_new_content=True)
+ assert settings.acl == AccountAclSettings(enabled=True)
+ assert service.viking_fs.acl_manager.is_enabled("default")
async def test_account_settings_admin_api_rejects_non_allowlisted_fields(
diff --git a/tests/server/test_api_snapshot.py b/tests/server/test_api_snapshot.py
index c0a3bb9ec..5ed2699e6 100644
--- a/tests/server/test_api_snapshot.py
+++ b/tests/server/test_api_snapshot.py
@@ -11,6 +11,11 @@ import pytest
import pytest_asyncio
import openviking.service.reindex_executor as reindex_mod
+from openviking.server.account_settings import (
+ AccountAclSettings,
+ AccountSettingsPatch,
+ update_account_settings,
+)
from openviking.server.app import create_app
from openviking.server.auth import get_request_context
from openviking.server.config import ServerConfig
@@ -195,6 +200,11 @@ async def client_with_resource_and_blob(client_with_resource, service):
async def test_restore_acl_and_reindex_identity(client_with_resource, service, monkeypatch):
_, _root = client_with_resource
admin = RequestContext(user=service.user, role=Role.ADMIN)
+ await update_account_settings(
+ service.viking_fs,
+ admin.account_id,
+ AccountSettingsPatch(acl=AccountAclSettings(enabled=True)),
+ )
writer = RequestContext(
user=UserIdentifier(admin.account_id, "snapshot_writer"),
role=Role.USER,
diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.py
index d3e5bfd78..4c4e7c551 100644
--- a/tests/server/test_content_write_service.py
+++ b/tests/server/test_content_write_service.py
@@ -9,7 +9,7 @@ from unittest.mock import AsyncMock
import pytest
from openviking.server.account_settings import (
- AccountResourceAclSettings,
+ AccountAclSettings,
AccountSettingsPatch,
update_account_settings,
)
@@ -135,9 +135,7 @@ async def test_shared_resource_creation_inherits_acl_and_preserves_plain_append(
await update_account_settings(
service.viking_fs,
creator.account_id,
- AccountSettingsPatch(
- resource_acl=AccountResourceAclSettings(auto_protect_new_content=True)
- ),
+ AccountSettingsPatch(acl=AccountAclSettings(enabled=True)),
)
await service.fs.mkdir(auto_protected_dir, ctx=creator)
await service.resources.wait_processed()
@@ -203,6 +201,13 @@ async def test_shared_resource_creation_inherits_acl_and_preserves_plain_append(
with pytest.raises(PermissionDeniedError):
await service.viking_fs.read_file(uri, ctx=outsider)
+ await update_account_settings(
+ service.viking_fs,
+ creator.account_id,
+ AccountSettingsPatch(acl=AccountAclSettings(enabled=False)),
+ )
+ assert await service.viking_fs.read_file(uri, ctx=outsider) == stored
+
internal_ctx = RequestContext(
user=outsider.user,
role=outsider.role,
diff --git a/tests/server/test_watch_task_acl.py b/tests/server/test_watch_task_acl.py
index 85f1eccca..fa41798be 100644
--- a/tests/server/test_watch_task_acl.py
+++ b/tests/server/test_watch_task_acl.py
@@ -4,6 +4,7 @@
"""Regression tests for watch-task control file access boundaries."""
import contextvars
+from types import SimpleNamespace
import pytest
@@ -52,7 +53,7 @@ class _NoWriteVikingFS:
)
@pytest.mark.asyncio
async def test_watch_task_control_files_are_root_only(bare_viking_fs, root_ctx, user_ctx, uri):
- bare_viking_fs.acl_manager = object()
+ bare_viking_fs.acl_manager = SimpleNamespace(is_enabled=lambda _account_id: True)
await bare_viking_fs._ensure_access(uri, root_ctx)
with pytest.raises(PermissionDeniedError):
await bare_viking_fs._ensure_access(uri, user_ctx)
diff --git a/tests/storage/test_viking_fs_tree.py b/tests/storage/test_viking_fs_tree.py
index 8fc192424..17c3efe51 100644
--- a/tests/storage/test_viking_fs_tree.py
+++ b/tests/storage/test_viking_fs_tree.py
@@ -2,6 +2,7 @@
# SPDX-License-Identifier: AGPL-3.0
from datetime import datetime, timezone
+from types import SimpleNamespace
import pytest
@@ -507,7 +508,7 @@ async def test_tree_original_dfs_order(monkeypatch, fs):
),
]
patch_tree_env(monkeypatch, fs, entries)
- fs.acl_manager = object()
+ fs.acl_manager = SimpleNamespace(is_enabled=lambda _account_id: True)
async def fake_can_access_many(uris, _ctx):
return {uri: "/restricted" not in uri for uri in uris}
@@ -634,7 +635,7 @@ async def test_ls_agent_modtime_is_raw_utc_iso(monkeypatch, fs):
monkeypatch.setattr(fs, "_is_accessible", lambda _uri, _ctx: True)
monkeypatch.setattr(fs, "_batch_fetch_abstracts", default_batch_fetch)
monkeypatch.setattr(viking_fs_module, "datetime", _FixedDatetime)
- fs.acl_manager = object()
+ fs.acl_manager = SimpleNamespace(is_enabled=lambda _account_id: True)
async def fake_can_access_many(uris, _ctx):
return {uri: not uri.endswith("/restricted") for uri in uris}
diff --git a/tests/storage/test_viking_vector_scope_filter.py b/tests/storage/test_viking_vector_scope_filter.py
index 0efd38d02..97a3caf07 100644
--- a/tests/storage/test_viking_vector_scope_filter.py
+++ b/tests/storage/test_viking_vector_scope_filter.py
@@ -5,6 +5,7 @@ import pytest
from openviking.core.namespace import uri_parts
from openviking.server.identity import RequestContext, Role
+from openviking.storage.acl import AclManager
from openviking.storage.expr import And, Eq, In, Or, PathScope, RawDSL
from openviking.storage.viking_vector_index_backend import VikingVectorIndexBackend
from openviking_cli.session.user_id import UserIdentifier
@@ -199,7 +200,8 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl():
return [record for record in records if matches(filter, record)]
backend = object.__new__(VikingVectorIndexBackend)
- backend.acl_manager = object()
+ backend.acl_manager = AclManager(backend)
+ backend.acl_manager.set_enabled(ctx.account_id, True)
backend.search = fake_search
visible = await backend.search_in_tenant(
@@ -239,6 +241,20 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl():
"denied-shared",
]
+ backend.acl_manager.set_enabled(ctx.account_id, False)
+ shared = await backend.search_in_tenant(
+ ctx=ctx,
+ query_vector=[1.0],
+ context_type="resource",
+ )
+ assert [record["id"] for record in shared] == [
+ "own",
+ "legacy-shared",
+ "direct-shared",
+ "inherited-shared",
+ "denied-shared",
+ ]
+
def test_segment_prefix_and_visible_root_ancestor_do_not_elide_tenant_filter():
ctx = _ctx()