Skip to content

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

feat(acl): add restricted inheritance mode (#4695)

Qin Haojie70284c0f1e60
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 6b2a7dc68..4c8e85269 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -406,12 +406,20 @@ impl HttpClient {
.await
}
- pub async fn acl_set(&self, uri: &str, entries: Vec<Value>) -> Result<Value> {
- self.put(
- "/api/v1/acl",
- &serde_json::json!({"uri": uri, "entries": entries}),
- )
- .await
+ pub async fn acl_set(
+ &self,
+ uri: &str,
+ entries: Vec<Value>,
+ acl_mode: Option<String>,
+ ) -> Result<Value> {
+ let mut body = serde_json::json!({"uri": uri});
+ if !entries.is_empty() {
+ body["entries"] = serde_json::Value::Array(entries);
+ }
+ if let Some(acl_mode) = acl_mode {
+ body["acl_mode"] = serde_json::Value::String(acl_mode);
+ }
+ self.put("/api/v1/acl", &body).await
}
pub async fn acl_grant(&self, uri: &str, principal: &str, level: &str) -> Result<Value> {
diff --git a/crates/ov_cli/src/commands/acl.rs b/crates/ov_cli/src/commands/acl.rs
index 9fbf147a6..a827f4ec0 100644
--- a/crates/ov_cli/src/commands/acl.rs
+++ b/crates/ov_cli/src/commands/acl.rs
@@ -21,9 +21,15 @@ pub async fn set(
client: &HttpClient,
uri: &str,
raw_entries: Vec<String>,
+ acl_mode: Option<String>,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
+ if raw_entries.is_empty() && acl_mode.is_none() {
+ return Err(Error::Client(
+ "Provide at least one --entry or --acl-mode inherit|restricted.".to_string(),
+ ));
+ }
let mut entries = Vec::new();
for raw in raw_entries {
let Some((principal, level)) = raw.split_once('=') else {
@@ -33,7 +39,11 @@ pub async fn set(
};
entries.push(json!({"principal": principal, "level": level}));
}
- show(client.acl_set(uri, entries).await?, output_format, compact)
+ show(
+ client.acl_set(uri, entries, acl_mode).await?,
+ output_format,
+ compact,
+ )
}
pub async fn grant(
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index 6d77b6fba..c524fe2f9 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -1855,8 +1855,20 @@ pub async fn handle_acl(action: crate::AclCommands, ctx: CliContext) -> Result<(
crate::AclCommands::Get { uri } => {
commands::acl::get(&client, &uri, ctx.output_format, ctx.compact).await
}
- crate::AclCommands::Set { uri, entries } => {
- commands::acl::set(&client, &uri, entries, ctx.output_format, ctx.compact).await
+ crate::AclCommands::Set {
+ uri,
+ entries,
+ acl_mode,
+ } => {
+ commands::acl::set(
+ &client,
+ &uri,
+ entries,
+ acl_mode,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
}
crate::AclCommands::Grant {
uri,
diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rs
index aa006c35d..4a2f10e31 100644
--- a/crates/ov_cli/src/help_ui.rs
+++ b/crates/ov_cli/src/help_ui.rs
@@ -382,6 +382,10 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[
label: "ov acl grant viking://resources/project-a --principal user:bob --level read",
description: "Grant read access to a user.",
},
+ HelpItem {
+ label: "ov acl set viking://resources/project-a --acl-mode restricted",
+ description: "Ignore inherited permissions without deleting them.",
+ },
],
next_steps: &[HelpItem {
label: "ov find \"query\" -u <uri>",
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index d88732e1d..8b74988bf 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -296,8 +296,11 @@ enum AclCommands {
},
Set {
uri: String,
- #[arg(long = "entry", required = true)]
+ #[arg(long = "entry")]
entries: Vec<String>,
+ /// Whether this node uses inherited grants or direct grants only
+ #[arg(long, value_parser = ["inherit", "restricted"])]
+ acl_mode: Option<String>,
},
Grant {
uri: String,
diff --git a/docs/en/api/12-acl.md b/docs/en/api/12-acl.md
index bb3e79e5f..2a6333463 100644
--- a/docs/en/api/12-acl.md
+++ b/docs/en/api/12-acl.md
@@ -1,6 +1,6 @@
# ACL API
-The ACL API manages direct grants on shared `viking://resources/...` nodes and reports their inherited effective permissions. Private resources do not accept ACLs and must be moved into the shared scope to be shared.
+The ACL API manages direct grants and restricted mode on shared `viking://resources/...` nodes and reports their inherited effective permissions. Private resources do not accept ACLs and must be moved into the shared scope to be shared.
Read [Resource Access Control (ACL)](../concepts/15-acl.md) for the permission and inheritance model.
@@ -9,8 +9,8 @@ Read [Resource Access Control (ACL)](../concepts/15-acl.md) for the permission a
| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/acl?uri={uri}` | Get direct, inherited, and effective ACLs |
-| PUT | `/api/v1/acl` | Replace the node's direct ACL |
-| DELETE | `/api/v1/acl?uri={uri}` | Clear the node's direct ACL |
+| PUT | `/api/v1/acl` | Update the node's direct ACL or restricted mode |
+| DELETE | `/api/v1/acl?uri={uri}` | Clear the direct ACL and restricted mode |
| POST | `/api/v1/acl/grant` | Set one principal's direct level |
| POST | `/api/v1/acl/revoke` | Remove one principal's direct grant |
@@ -64,9 +64,9 @@ The caller supplies the account-unique, stable `group_id` through the [Admin API
| Field | Description |
|-------|-------------|
| `direct_entries` | Entries set directly on this node |
-| `inherited_entries` | Merged direct ACLs from all ancestors |
-| `effective_entries` | The merged direct and inherited entries |
-| `acl_mode` | `none` when ACL does not control the node; `inherit` when direct and inherited ACLs apply; read-only and derived |
+| `inherited_entries` | The parent's current effective permissions, refreshed even while restricted |
+| `effective_entries` | Direct plus inherited grants in inherit mode; direct grants only in restricted mode |
+| `acl_mode` | `none`: not ACL-controlled; `inherit`: direct and inherited grants apply; `restricted`: only direct grants apply |
The account `ADMIN` implicit `manage` permission is not included in these lists.
@@ -95,7 +95,7 @@ report = client.acl_get("viking://resources/project-a")
report, err := client.ACL(ctx, "viking://resources/project-a")
```
-## Replace a Direct ACL
+## Update a Direct ACL or Restricted Mode
```
PUT /api/v1/acl
@@ -109,11 +109,14 @@ Request body:
"entries": [
{"principal": "user:bob", "level": "read"},
{"principal": "group:engineering", "level": "write"}
- ]
+ ],
+ "acl_mode": "restricted"
}
```
-`entries` completely replaces this node's direct ACL without changing direct ACLs on ancestors or descendants. Duplicate principals keep their highest level. An empty list is equivalent to deleting this node's direct ACL.
+Provide `entries`, `acl_mode`, or both. `entries` replaces the full direct ACL. `acl_mode` accepts `restricted` (direct grants only) or `inherit` (resume inheritance). Omitted fields remain unchanged. Inherited grants continue to refresh while restricted and apply immediately when inheritance resumes. Duplicate principals keep their highest level.
+
+Setting `none` directly is not allowed, as it would bypass the parent's ACL. After resuming inheritance or deleting the ACL, the system returns `none` if the node has no direct grants and its parent is not ACL-controlled.
```bash
curl -X PUT http://localhost:1933/api/v1/acl \
@@ -124,7 +127,8 @@ curl -X PUT http://localhost:1933/api/v1/acl \
"entries": [
{"principal": "user:bob", "level": "read"},
{"principal": "group:engineering", "level": "write"}
- ]
+ ],
+ "acl_mode": "restricted"
}'
```
@@ -137,13 +141,14 @@ report = client.acl_set(
{"principal": "user:bob", "level": "read"},
{"principal": "group:engineering", "level": "write"},
],
+ acl_mode="restricted",
)
```
The asynchronous client uses the same method name:
```python
-report = await client.acl_set(uri, entries)
+report = await client.acl_set(uri, entries, acl_mode="restricted")
```
**Go SDK**
@@ -152,15 +157,22 @@ report = await client.acl_set(uri, entries)
report, err := client.SetACL(ctx, "viking://resources/project-a", []openviking.ACLEntry{
{Principal: "user:bob", Level: "read"},
{Principal: "group:engineering", Level: "write"},
-})
+}, openviking.SetACLOptions{ACLMode: "restricted"})
+
+// Change only the mode without changing the direct ACL.
+report, err = client.SetACLMode(ctx, "viking://resources/project-a", "restricted")
```
**CLI**
```bash
ov acl set viking://resources/project-a \
+ --acl-mode restricted \
--entry user:bob=read \
--entry group:engineering=write
+
+# Disable restricted mode only.
+ov acl set viking://resources/project-a --acl-mode inherit
```
## Set One Principal's Level
@@ -231,7 +243,7 @@ ov acl revoke viking://resources/project-a --principal user:bob
DELETE /api/v1/acl?uri={uri}
```
-This does not remove direct ACLs on descendants. The current node is recalculated from its ancestors, while each descendant continues to combine its own direct ACL with its ancestors.
+This clears the node's direct ACL and exits restricted mode without deleting stored inherited entries or descendant direct ACLs. The latest inherited permissions apply immediately; if the parent is not ACL-controlled either, `acl_mode` returns to `none`.
```bash
curl -X DELETE \
@@ -259,9 +271,9 @@ The API checks manage permission before confirming existence to an authorized ca
| ACL mutation targets a URI without a context record | `INVALID_ARGUMENT`; index it first |
| Invalid `principal` syntax or `group:*` | `INVALID_ARGUMENT` |
| Level is not `read/write/manage` | `INVALID_ARGUMENT` |
-| Request includes read-only fields such as `acl_mode` | `INVALID_ARGUMENT` |
+| `acl_mode` is not `inherit/restricted`, or the request includes read-only inherited fields | `INVALID_ARGUMENT` |
-Direct and inherited ACL fields are both stored in context records. An update changes the target direct ACL and recalculates descendant inherited ACLs in one subtree batch; a failed write restores the previous context ACL fields.
+ACL mode, direct grants, and inherited grants are stored in context records. An update changes the target fields and recalculates descendant inherited ACLs in one subtree batch; a failed write restores the previous context ACL fields.
## Related Documentation
diff --git a/docs/en/concepts/15-acl.md b/docs/en/concepts/15-acl.md
index 35286b88c..720b5c892 100644
--- a/docs/en/concepts/15-acl.md
+++ b/docs/en/concepts/15-acl.md
@@ -2,7 +2,7 @@
OpenViking ACL shares directories or files from the shared resource scope with users or groups inside one account. ACL never changes the account boundary: every grant is limited to the current account.
-ACL uses a collaborative-document inheritance model. A directory grant continuously applies to its descendants, while child directories and files can add direct grants. A child ACL does not replace grants inherited from ancestors.
+ACL uses a collaborative-document inheritance model. A directory grant applies to descendants by default. Child directories and files can add direct grants or establish a restricted boundary that ignores inherited permissions.
## Supported URIs
@@ -39,12 +39,14 @@ Each higher level includes the lower levels. A `manage` grant therefore includes
## Inheritance
-A node's effective ACL is the union of every ancestor's direct ACL and the node's own direct ACL:
+A normal node combines direct and inherited grants. A restricted node uses only direct grants:
```text
-effective(node) = UNION(direct_acl(each ancestor), direct_acl(node))
+effective(node) = direct(node) + (acl_mode(node) == "restricted" ? empty : inherited(node))
```
+`inherited(node)` always stores the parent's current effective permissions. It continues to refresh while the node is restricted, and disabling restricted mode applies the latest inherited value immediately. Descendants inherit the current node's effective permissions, so they cannot bypass an intermediate restricted boundary.
+
For example:
```text
@@ -59,7 +61,7 @@ The effective permissions on `report.md` are:
- Members of `engineering`: `write`
- Carol: `read`
-Removing the group's direct ACL from `A/B` does not remove entries from `A` or `report.md`. Descendants only lose the permissions contributed by that entry.
+If `A/B` becomes restricted, Bob's grant on `A` no longer applies to `A/B` or its descendants, but the stored inherited value is not deleted. Disabling restricted mode immediately restores Bob's inherited access.
## Default Behavior and `acl_mode`
@@ -77,13 +79,13 @@ remains public. Disabling the setting also stops enforcing existing ACLs.
descendants only inherit it. Re-embedding or replacing an existing context record
does not change its direct ACL.
-When the node or any ancestor has a direct ACL, the node enters the ACL-controlled domain:
+`acl_mode` describes a resource's ACL behavior, separately from the account-wide `acl.enabled` switch:
-```text
-acl_mode = "inherit"
-```
+- `none`: use the original visibility rules without resource ACL enforcement.
+- `inherit`: use direct grants and permissions inherited from the parent.
+- `restricted`: use direct grants only, while retaining and refreshing inherited grants.
-`acl_mode` is derived by the system and cannot be set by an API caller. The base modes are `none` and `inherit`: `none` means ACL does not control the node, while `inherit` means both direct and inherited ACLs apply. It returns to `none` automatically after the last applicable direct ACL is removed.
+Users with `manage` can switch between `inherit` and `restricted`, but cannot set `none` to bypass the parent's ACL. After exiting restricted mode, a node without direct grants returns to `none` if its parent is not ACL-controlled. A restricted node with no direct grants remains protected, as do descendants without separate grants; account administrators retain implicit management access.
## File Operations
@@ -106,7 +108,7 @@ 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.
-Within the shared scope, a moved node keeps its direct ACL and recalculates inherited permissions from its new ancestors. A private resource moved into the shared scope carries no ACL and inherits the destination directory; a shared resource moved back to a private area has its ACL cleared.
+Within the shared scope, a moved node keeps its direct ACL and restricted state, then recalculates inherited permissions from its new parent. A private resource moved into the shared scope carries no ACL and inherits the destination directory; a shared resource moved back to a private area has its ACL cleared.
Recursive tag updates, directory deletion, and directory moves validate the complete affected subtree first. The operation stops if any node lacks the required capability or the subtree cannot be scanned completely.
@@ -122,9 +124,9 @@ acl_direct_grants
acl_inherited_grants
```
-`acl_direct_grants` is the ACL assigned to the current node. `acl_inherited_grants` is the union of all ancestor direct ACLs. Each principal stores only its highest level as `{mask}:{principal}`: `1` means `read`, `3` means `write`, and `7` means `manage`. For example, `3:group:dev` gives `group:dev` `write` and therefore also `read`. Effective permission is the union of the two fields; there is no separate ACL collection.
+`acl_direct_grants` is the ACL assigned to the current node. `acl_inherited_grants` stores the parent's current effective ACL. `acl_mode` controls whether inherited grants contribute to the current node's effective permissions. Each principal stores only its highest level as `{mask}:{principal}`: `1` means `read`, `3` means `write`, and `7` means `manage`. There is no separate ACL collection.
-The request principals are `user:{ctx.user_id}`, `user:*`, and one `group:{group_id}` for each ID in `ctx.group_ids`. For reads, `find/search` matches the `1`, `3`, and `7` tokens for each principal against both native `list<string>` grant fields within the `viking://resources` scope; private resources remain isolated by URI owner. Legacy records without ACL fields are treated as `acl_mode=none`, so they do not require a full data backfill.
+The request principals are `user:{ctx.user_id}`, `user:*`, and one `group:{group_id}` for each ID in `ctx.group_ids`. Within the shared scope, retrieval identifies controlled records with `acl_mode IN [inherit, restricted]`, then matches each principal's `1`, `3`, and `7` grant tokens: direct or inherited for inherit mode, direct only for restricted mode. Missing, `null`, and `none` modes retain legacy visibility rules and are neither dropped nor mistaken for ACL-controlled records. Private resources remain isolated by URI owner.
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.
@@ -159,6 +161,12 @@ ov acl revoke viking://resources/project-a --principal user:bob
If an ancestor still grants Bob access, that inherited permission remains effective.
+Use only direct grants on the current node while preserving and refreshing inherited grants:
+
+```bash
+ov acl set viking://resources/project-a --acl-mode restricted
+```
+
## Related Documentation
- [ACL API](../api/12-acl.md) - HTTP, SDK, and CLI interfaces
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index b1e31d47b..7c4e345be 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -1470,7 +1470,7 @@ Supports cloud-deployed VikingDB on Volcengine
##### ACL schema
-ACL data exists only in the context collection. In addition to `acl_mode: string` (`none` or `inherit`), add these scalar-indexed `list<string>` fields:
+ACL data exists only in the context collection. In addition to `acl_mode: string` (`none`, `inherit`, or `restricted`), add these scalar-indexed `list<string>` fields:
```text
acl_direct_grants
diff --git a/docs/zh/api/12-acl.md b/docs/zh/api/12-acl.md
index 63b24214f..5054bc968 100644
--- a/docs/zh/api/12-acl.md
+++ b/docs/zh/api/12-acl.md
@@ -1,6 +1,6 @@
# ACL API
-ACL API 管理 `viking://resources/...` 共享资源的直接授权,并返回节点继承后的有效权限。个人资源不接受 ACL,需要分享时应移动到共享区。
+ACL API 管理 `viking://resources/...` 共享资源的直接授权和 restricted 模式,并返回节点继承后的有效权限。个人资源不接受 ACL,需要分享时应移动到共享区。
权限模型和继承规则请先阅读 [资源访问控制(ACL)](../concepts/15-acl.md)。
@@ -9,8 +9,8 @@ ACL API 管理 `viking://resources/...` 共享资源的直接授权,并返回
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/api/v1/acl?uri={uri}` | 获取直接、继承和有效 ACL |
-| PUT | `/api/v1/acl` | 替换当前节点的直接 ACL |
-| DELETE | `/api/v1/acl?uri={uri}` | 清空当前节点的直接 ACL |
+| PUT | `/api/v1/acl` | 更新当前节点的直接 ACL 或 restricted 模式 |
+| DELETE | `/api/v1/acl?uri={uri}` | 清空直接 ACL 并退出 restricted 模式 |
| POST | `/api/v1/acl/grant` | 设置一个 principal 的直接权限级别 |
| POST | `/api/v1/acl/revoke` | 删除一个 principal 的直接授权 |
@@ -62,9 +62,9 @@ ACL API 管理 `viking://resources/...` 共享资源的直接授权,并返回
| 字段 | 说明 |
|------|------|
| `direct_entries` | 只包含当前节点直接设置的条目 |
-| `inherited_entries` | 所有祖先目录直接 ACL 的合并结果 |
-| `effective_entries` | `direct_entries` 与 `inherited_entries` 的合并结果 |
-| `acl_mode` | `none` 表示不受 ACL 控制,`inherit` 表示 direct 与 inherited ACL 均生效;只读派生字段 |
+| `inherited_entries` | 父节点当前的有效权限;restricted 期间也会继续更新 |
+| `effective_entries` | inherit 时合并 direct 与 inherited;restricted 时仅使用 direct |
+| `acl_mode` | `none`:不受 ACL 控制;`inherit`:直接与继承权限均生效;`restricted`:仅直接权限生效 |
account `ADMIN` 的隐式 `manage` 权限不出现在这些列表中。
@@ -93,7 +93,7 @@ report = client.acl_get("viking://resources/project-a")
report, err := client.ACL(ctx, "viking://resources/project-a")
```
-## 替换直接 ACL
+## 更新直接 ACL 或 restricted 模式
```
PUT /api/v1/acl
@@ -107,11 +107,14 @@ PUT /api/v1/acl
"entries": [
{"principal": "user:bob", "level": "read"},
{"principal": "group:engineering", "level": "write"}
- ]
+ ],
+ "acl_mode": "restricted"
}
```
-`entries` 会完整替换当前节点的直接 ACL,不影响祖先或后代节点自己的直接 ACL。重复 principal 会保留最高权限级别。传入空数组等价于删除当前节点的直接 ACL。
+`entries` 和 `acl_mode` 至少传一个。`entries` 完整替换直接权限;`acl_mode` 支持 `restricted`(只使用直接权限)和 `inherit`(恢复继承)。未传的字段保持不变。restricted 期间继承权限仍随父节点更新,恢复继承后立即使用最新值。重复 principal 保留最高权限级别。
+
+不能直接设置 `none` 来绕过父目录的 ACL。恢复继承或删除 ACL 后,如果当前节点没有任何直接权限,父目录也不受 ACL 控制,系统会自动返回 `none`。
```bash
curl -X PUT http://localhost:1933/api/v1/acl \
@@ -122,7 +125,8 @@ curl -X PUT http://localhost:1933/api/v1/acl \
"entries": [
{"principal": "user:bob", "level": "read"},
{"principal": "group:engineering", "level": "write"}
- ]
+ ],
+ "acl_mode": "restricted"
}'
```
@@ -135,13 +139,14 @@ report = client.acl_set(
{"principal": "user:bob", "level": "read"},
{"principal": "group:engineering", "level": "write"},
],
+ acl_mode="restricted",
)
```
异步客户端使用相同方法名:
```python
-report = await client.acl_set(uri, entries)
+report = await client.acl_set(uri, entries, acl_mode="restricted")
```
**Go SDK**
@@ -150,15 +155,22 @@ report = await client.acl_set(uri, entries)
report, err := client.SetACL(ctx, "viking://resources/project-a", []openviking.ACLEntry{
{Principal: "user:bob", Level: "read"},
{Principal: "group:engineering", Level: "write"},
-})
+}, openviking.SetACLOptions{ACLMode: "restricted"})
+
+// 只切换模式,不修改 direct ACL
+report, err = client.SetACLMode(ctx, "viking://resources/project-a", "restricted")
```
**CLI**
```bash
ov acl set viking://resources/project-a \
+ --acl-mode restricted \
--entry user:bob=read \
--entry group:engineering=write
+
+# 只退出 restricted 模式
+ov acl set viking://resources/project-a --acl-mode inherit
```
## 设置单个 principal 权限
@@ -229,7 +241,7 @@ ov acl revoke viking://resources/project-a --principal user:bob
DELETE /api/v1/acl?uri={uri}
```
-该接口不删除后代节点的直接 ACL。清空后,当前节点从祖先 ACL 重新继承;每个后代继续由其祖先与自身的直接 ACL 计算有效权限。
+该接口清空当前节点的直接 ACL 并退出 restricted;不会删除已保存的 inherited,也不删除后代节点的直接 ACL。清空后立即使用最新继承权限;父目录也不受 ACL 控制时,`acl_mode` 恢复为 `none`。
```bash
curl -X DELETE \
@@ -257,9 +269,9 @@ ov acl rm viking://resources/project-a
| 修改 ACL 时 URI 尚无 context 记录 | `INVALID_ARGUMENT`,需先完成索引 |
| `principal` 格式非法,或使用 `group:*` | `INVALID_ARGUMENT` |
| level 不是 `read/write/manage` | `INVALID_ARGUMENT` |
-| 请求包含 `acl_mode` 等只读字段 | `INVALID_ARGUMENT` |
+| `acl_mode` 不是 `inherit/restricted`,或请求包含 inherited 等只读字段 | `INVALID_ARGUMENT` |
-ACL 的 direct 和 inherited 字段都保存在 context。更新会在同一子树批处理中修改目标 direct 并重算后代 inherited;写入失败时恢复原 context ACL 字段。
+ACL 的 mode、direct 和 inherited 字段都保存在 context。更新会在同一子树批处理中修改目标字段并重算后代 inherited;写入失败时恢复原 context ACL 字段。
## 相关文档
diff --git a/docs/zh/concepts/15-acl.md b/docs/zh/concepts/15-acl.md
index 7581c88ba..d80bdfa35 100644
--- a/docs/zh/concepts/15-acl.md
+++ b/docs/zh/concepts/15-acl.md
@@ -2,7 +2,7 @@
OpenViking ACL 用于在同一个 account 内,把共享资源目录或文件授权给用户或用户组。ACL 不改变 account 隔离:任何授权都只在当前 account 内生效。
-ACL 采用协作文档式的继承模型。目录授权持续作用于所有后代,子目录和文件可以继续增加直接授权;祖先授权不会被子节点覆盖。
+ACL 采用协作文档式的继承模型。目录授权默认持续作用于所有后代,子目录和文件可以继续增加直接授权,也可以用 restricted 模式在某个节点切断继承权限。
## 适用 URI
@@ -39,12 +39,14 @@ ACL 条目使用带类型的 principal:
## 继承规则
-节点的有效 ACL 是所有祖先直接 ACL 与节点自身直接 ACL 的并集:
+普通节点合并 direct 与 inherited;restricted 节点只使用 direct:
```text
-effective(node) = UNION(direct_acl(each ancestor), direct_acl(node))
+effective(node) = direct(node) + (acl_mode(node) == "restricted" ? empty : inherited(node))
```
+`inherited(node)` 始终保存父节点当前的有效权限。即使节点处于 restricted 模式,这个字段也会随父节点继续更新;退出 restricted 后会立即使用最新 inherited。后代继承的是当前节点的有效权限,因此不会绕过中间的 restricted 边界。
+
例如:
```text
@@ -59,7 +61,7 @@ read user:carol on viking://resources/A/B/C/report.md
- `engineering` 的成员:`write`
- Carol:`read`
-删除 `A/B` 上用户组的直接 ACL 不会删除 `A` 或 `report.md` 上的条目。子节点只会失去由该条目提供的权限。
+如果把 `A/B` 设为 restricted,Bob 在 `A` 上的权限不会对 `A/B` 及其后代生效,但保存的 inherited 不会被删除。删除 restricted 后,Bob 会立即恢复从 `A` 继承的权限。
## 默认行为与 `acl_mode`
@@ -72,13 +74,13 @@ read user:carol on viking://resources/A/B/C/report.md
的根目录(`no_split` 时为根文件)作为创建节点:根节点获得创建者直接 `manage`,
内部节点只继承,不重复写直接授权。重新向量化或覆盖已有 context 不会改变直接 ACL。
-只要节点或任一祖先存在直接 ACL,该节点就进入 ACL 控制域:
+`acl_mode` 表示当前资源如何使用 ACL,与账号总开关 `acl.enabled` 不是一回事:
-```text
-acl_mode = "inherit"
-```
+- `none`:该资源不受 ACL 控制,沿用原有可见性规则。
+- `inherit`:使用直接权限和父目录传下来的权限。
+- `restricted`:只使用直接权限,但仍保存并更新父目录传下来的权限。
-`acl_mode` 是系统派生字段,不能由 API 调用者设置。当前基础模式只有 `none` 和 `inherit`:`none` 表示节点不受 ACL 控制,`inherit` 表示 direct 与 inherited ACL 均生效。删除最后一个相关直接 ACL 后,它会自动恢复为 `none`。
+有 `manage` 权限的用户可以切换 `inherit` / `restricted`,不能直接设置 `none` 绕过父目录权限。退出 restricted 且没有直接权限、父目录也不受 ACL 控制时,系统会恢复为 `none`。restricted 节点即使没有直接权限也不会变公开,其没有单独授权的后代同样不可访问;账号管理员仍有隐式管理权。
## 文件操作
@@ -100,7 +102,7 @@ bootstrap,后续 ACL 修改要求有效 `manage` 能力。
目录上的 ACL 授权会被所有后代继承。`list`、`tree` 和批量结果仍逐个检查有效 ACL,因为未设置 ACL 的目录可能按原有 URI 规则可见,而某个后代已经通过自己的 ACL 进入控制域。
-共享区内部移动时,节点自己的直接 ACL 随节点移动,继承权限按新祖先重新计算。个人资源移入共享区时不携带 ACL,只继承目标目录权限;共享资源移回个人区时清空 ACL。
+共享区内部移动时,节点自己的 direct ACL 和 restricted 状态随节点移动,inherited 按新父节点重新计算。个人资源移入共享区时不携带 ACL,只继承目标目录权限;共享资源移回个人区时清空 ACL。
递归修改 tags、删除或移动目录会先校验完整目标子树。任一节点缺少所需能力,或子树扫描不完整,操作都会整体中止。
@@ -116,9 +118,9 @@ acl_direct_grants
acl_inherited_grants
```
-`acl_direct_grants` 是当前节点直接 ACL,`acl_inherited_grants` 是所有祖先直接 ACL 的并集。每个 principal 只保存最高 level,编码为 `{mask}:{principal}`:`1` 表示 `read`、`3` 表示 `write`、`7` 表示 `manage`。例如 `3:group:dev` 表示 `group:dev` 拥有 `write`,同时也具备 `read`。有效权限是两组列表的并集,不维护独立 ACL collection。
+`acl_direct_grants` 是当前节点直接 ACL,`acl_inherited_grants` 是父节点当前有效 ACL,`acl_mode` 决定 inherited 是否参与当前节点的有效权限。每个 principal 只保存最高 level,编码为 `{mask}:{principal}`:`1` 表示 `read`、`3` 表示 `write`、`7` 表示 `manage`。不维护独立 ACL collection。
-请求的可用 principal 为 `user:{ctx.user_id}`、`user:*`,以及 `ctx.group_ids` 中每个 ID 对应的 `group:{group_id}`。`find/search` 读取时为每个 principal 匹配 `1`、`3`、`7` 三种 token,并在 `viking://resources` scope 内对 direct 和 inherited 两个原生 `list<string>` 字段做过滤;个人资源始终按 URI owner 隔离。旧记录缺少 ACL 字段时按 `acl_mode=none` 处理,无需全量回填。
+请求的可用 principal 为 `user:{ctx.user_id}`、`user:*`,以及 `ctx.group_ids` 中每个 ID 对应的 `group:{group_id}`。检索在共享区内用 `acl_mode IN [inherit, restricted]` 判断受控资源,再匹配各 principal 的 `1`、`3`、`7` grant token:inherit 匹配 direct 或 inherited,restricted 只匹配 direct。旧记录字段缺失、为 `null` 或 `none` 时仍走原有可见性规则,不会因空值漏检,也不会被当作 ACL 已开启。个人资源始终按 URI owner 隔离。
检索 target URI 只是搜索范围,不要求调用者能够读取 target 节点本身。用户即使不能读取中间目录,也可以检索到深层单独授权给自己的文件。
@@ -150,6 +152,12 @@ ov acl revoke viking://resources/project-a --principal user:bob
如果 Bob 仍被祖先目录授权,该继承权限继续有效。
+只使用当前节点直接授权,同时保留并继续更新继承字段:
+
+```bash
+ov acl set viking://resources/project-a --acl-mode restricted
+```
+
## 相关文档
- [ACL API](../api/12-acl.md) - HTTP、SDK 和 CLI 接口
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index e98bbccae..5f69d380d 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -1445,7 +1445,7 @@ RAGFS 默认使用 Rust binding 模式,通过 Rust 实现直接访问文件系
##### ACL schema
-ACL 只维护在 context collection。除 `acl_mode: string`(`none` 或 `inherit`)外,需要以下 `list<string>` 标量索引字段:
+ACL 只维护在 context collection。除 `acl_mode: string`(`none`、`inherit` 或 `restricted`)外,需要以下 `list<string>` 标量索引字段:
```text
acl_direct_grants
diff --git a/openviking/server/routers/acl.py b/openviking/server/routers/acl.py
index e2001d780..c9ea57841 100644
--- a/openviking/server/routers/acl.py
+++ b/openviking/server/routers/acl.py
@@ -1,7 +1,9 @@
"""ACL endpoints."""
+from typing import Literal
+
from fastapi import APIRouter, Body, Depends, Query
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel, ConfigDict, model_validator
from openviking.core.path_variables import resolve_path_variables
from openviking.core.uri_validation import validate_request_viking_uri
@@ -9,7 +11,7 @@ from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext
from openviking.server.models import Response
-from openviking.storage.acl import AclLevel
+from openviking.storage.acl import AclLevel, AclMode
router = APIRouter(prefix="/api/v1/acl", tags=["acl"])
@@ -25,7 +27,14 @@ class AclEntryRequest(_AclRequest):
class SetAclRequest(_AclRequest):
uri: str
- entries: list[AclEntryRequest]
+ entries: list[AclEntryRequest] | None = None
+ acl_mode: Literal[AclMode.INHERIT, AclMode.RESTRICTED] | None = None
+
+ @model_validator(mode="after")
+ def require_acl_update(self) -> "SetAclRequest":
+ if self.entries is None and self.acl_mode is None:
+ raise ValueError("entries or acl_mode must be provided")
+ return self
class GrantAclRequest(_AclRequest):
@@ -57,7 +66,12 @@ async def set_acl(
uri = validate_request_viking_uri(resolve_path_variables(request.uri), _ctx)
result = await get_service().fs.set_acl(
uri,
- [entry.model_dump() for entry in request.entries],
+ (
+ [entry.model_dump() for entry in request.entries]
+ if request.entries is not None
+ else None
+ ),
+ acl_mode=request.acl_mode,
ctx=_ctx,
)
return Response(status="ok", result=result)
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 2ff514739..5943930ba 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -27,7 +27,7 @@ from openviking.storage.abstract_overview import (
plan_abstract_overview_refresh,
render_abstract_overview,
)
-from openviking.storage.acl import AclAction, CreatorAclGrant
+from openviking.storage.acl import AclAction, AclMode, CreatorAclGrant
from openviking.storage.content_write import ContentWriteCoordinator
from openviking.storage.expr import And, Eq, In, Or
from openviking.storage.queuefs import SemanticMsg, get_queue_manager
@@ -1151,9 +1151,15 @@ class FSService:
return await self._ensure_initialized().get_acl(uri, ctx=ctx)
async def set_acl(
- self, uri: str, entries: List[Dict[str, str]], ctx: RequestContext
+ self,
+ uri: str,
+ entries: Optional[List[Dict[str, str]]],
+ ctx: RequestContext,
+ acl_mode: Optional[AclMode] = None,
) -> Dict[str, Any]:
- return await self._ensure_initialized().set_acl(uri, entries, ctx=ctx)
+ return await self._ensure_initialized().set_acl(
+ uri, entries, ctx=ctx, acl_mode=acl_mode
+ )
async def grant_acl(
self, uri: str, principal: str, level: str, ctx: RequestContext
diff --git a/openviking/storage/acl.py b/openviking/storage/acl.py
index 9ef38a7cb..5a1b36207 100644
--- a/openviking/storage/acl.py
+++ b/openviking/storage/acl.py
@@ -31,6 +31,7 @@ class AclAction(str, Enum):
class AclMode(str, Enum):
NONE = "none"
INHERIT = "inherit"
+ RESTRICTED = "restricted"
class CreatorAclGrant(str, Enum):
@@ -103,8 +104,21 @@ class EffectiveAcl:
inherited: DirectAcl
@classmethod
- def from_permissions(cls, direct: DirectAcl, inherited: DirectAcl) -> "EffectiveAcl":
- mode = AclMode.NONE if direct.empty and inherited.empty else AclMode.INHERIT
+ def from_permissions(
+ cls,
+ direct: DirectAcl,
+ inherited: DirectAcl,
+ *,
+ mode: AclMode = AclMode.NONE,
+ parent_mode: AclMode = AclMode.NONE,
+ ) -> "EffectiveAcl":
+ if mode != AclMode.RESTRICTED:
+ # A restricted ancestor can protect descendants even with no grants.
+ mode = (
+ AclMode.INHERIT
+ if parent_mode != AclMode.NONE or not direct.empty or not inherited.empty
+ else AclMode.NONE
+ )
return cls(mode, direct, inherited)
@property
@@ -113,6 +127,8 @@ class EffectiveAcl:
@property
def permissions(self) -> DirectAcl:
+ if self.mode == AclMode.RESTRICTED:
+ return self.direct
return self.inherited.union(self.direct)
def context_fields(self) -> dict[str, Any]:
@@ -230,7 +246,7 @@ def acl_allows(acl: EffectiveAcl, ctx: RequestContext, action: AclAction) -> boo
class AclManager:
- """Stores direct and inherited ACL fields in the context collection."""
+ """Stores ACL state in the context collection."""
def __init__(
self,
@@ -253,6 +269,8 @@ class AclManager:
direct = DirectAcl.from_context_fields(record, "acl_direct")
inherited = DirectAcl.from_context_fields(record, "acl_inherited")
raw_mode = record.get(ACL_MODE_FIELD, AclMode.NONE.value)
+ if raw_mode is None:
+ raw_mode = AclMode.NONE.value
try:
mode = AclMode(raw_mode)
except (TypeError, ValueError) as exc:
@@ -350,16 +368,21 @@ class AclManager:
(ancestor for uri in missing for ancestor in paths[uri]), ctx
)
ancestor_groups = self._group_by_uri(ancestor_records)
- direct_map = {
- uri: self._effective_from_records(records).direct
+ acl_map = {
+ uri: self._effective_from_records(records)
for uri, records in ancestor_groups.items()
}
for uri in missing:
- inherited = DirectAcl()
- for ancestor in paths[uri][:-1]:
- inherited = inherited.union(direct_map.get(ancestor, DirectAcl()))
- direct = direct_map.get(uri, DirectAcl())
- result[uri] = EffectiveAcl.from_permissions(direct, inherited)
+ effective = EffectiveAcl(AclMode.NONE, DirectAcl(), DirectAcl())
+ for ancestor in paths[uri]:
+ stored = acl_map.get(ancestor)
+ effective = EffectiveAcl.from_permissions(
+ stored.direct if stored is not None else DirectAcl(),
+ effective.permissions,
+ mode=stored.mode if stored is not None else AclMode.NONE,
+ parent_mode=effective.mode,
+ )
+ result[uri] = effective
return result
async def resolve(self, uri: str, ctx: RequestContext) -> EffectiveAcl:
@@ -423,7 +446,11 @@ class AclManager:
direct = creator_acl
else:
inherited = inherited.union(creator_acl)
- effective = EffectiveAcl.from_permissions(direct, inherited)
+ effective = EffectiveAcl.from_permissions(
+ direct,
+ inherited,
+ parent_mode=parent_acl[parent].mode if parent else AclMode.NONE,
+ )
materialized.append({**record, **effective.context_fields()})
return materialized
@@ -434,14 +461,22 @@ class AclManager:
return EffectiveAcl(AclMode.NONE, DirectAcl(), DirectAcl()).context_fields()
ancestors = acl_ancestors(new_uri)
parent = ancestors[-2] if len(ancestors) > 1 else None
- inherited = (await self.resolve(parent, ctx)).permissions if parent else DirectAcl()
+ parent_acl = (
+ await self.resolve(parent, ctx)
+ if parent
+ else EffectiveAcl(AclMode.NONE, DirectAcl(), DirectAcl())
+ )
+ inherited = parent_acl.permissions
source_uri = str(record.get("uri") or "")
direct = (
DirectAcl.from_context_fields(record, "acl_direct")
if is_acl_uri(source_uri)
else DirectAcl()
)
- return EffectiveAcl.from_permissions(direct, inherited).context_fields()
+ mode = self._effective_from_record(record).mode if is_acl_uri(source_uri) else AclMode.NONE
+ return EffectiveAcl.from_permissions(
+ direct, inherited, mode=mode, parent_mode=parent_acl.mode
+ ).context_fields()
async def _apply_subtree(
self,
@@ -450,29 +485,39 @@ class AclManager:
ctx: RequestContext,
*,
root_direct: DirectAcl | None = None,
+ root_mode: AclMode | None = None,
) -> EffectiveAcl:
grouped = self._group_by_uri(records)
if root_uri not in grouped:
raise InvalidArgumentError("ACL target has no context record; index it first")
- direct_map = {
- uri: self._effective_from_records(items).direct for uri, items in grouped.items()
- }
+ stored_acl = {uri: self._effective_from_records(items) for uri, items in grouped.items()}
+ direct_map = {uri: effective.direct for uri, effective in stored_acl.items()}
+ mode_map = {uri: effective.mode for uri, effective in stored_acl.items()}
if root_direct is not None:
direct_map[root_uri] = root_direct
+ if root_mode is not None:
+ mode_map[root_uri] = root_mode
root_ancestors = acl_ancestors(root_uri)
parent = root_ancestors[-2] if len(root_ancestors) > 1 else None
- base = (await self.resolve(parent, ctx)).permissions if parent else DirectAcl()
+ base = (
+ await self.resolve(parent, ctx)
+ if parent
+ else EffectiveAcl(AclMode.NONE, DirectAcl(), DirectAcl())
+ )
effective_by_uri: dict[str, EffectiveAcl] = {}
root_depth = len(root_ancestors)
- for uri in grouped:
+ for uri in sorted(grouped, key=lambda value: len(acl_ancestors(value))):
ancestors = acl_ancestors(uri)
- inherited = base
+ parent_effective = base
for ancestor in ancestors[root_depth - 1 : -1]:
- inherited = inherited.union(direct_map.get(ancestor, DirectAcl()))
+ parent_effective = effective_by_uri.get(ancestor, parent_effective)
+ inherited = parent_effective.permissions
direct = direct_map.get(uri, DirectAcl())
- effective_by_uri[uri] = EffectiveAcl.from_permissions(direct, inherited)
+ effective_by_uri[uri] = EffectiveAcl.from_permissions(
+ direct, inherited, mode=mode_map[uri], parent_mode=parent_effective.mode
+ )
updated = [
{**record, **effective_by_uri[str(record["uri"])].context_fields()}
@@ -489,19 +534,27 @@ class AclManager:
if records:
await self._apply_subtree(uri, records, ctx)
- async def set_direct(
+ async def set_acl(
self,
uri: str,
- entries: Sequence[AclEntry | Mapping[str, Any]],
+ entries: Sequence[AclEntry | Mapping[str, Any]] | None,
ctx: RequestContext,
+ *,
+ acl_mode: AclMode | None = None,
) -> EffectiveAcl:
if uri_parts(uri) == ["resources"]:
raise InvalidArgumentError("ACL cannot be set on viking://resources")
- proposed = DirectAcl.from_entries(entries)
+ if entries is None and acl_mode is None:
+ raise InvalidArgumentError("entries or acl_mode must be provided")
+ proposed_direct = DirectAcl.from_entries(entries) if entries is not None else None
old_records = await self._subtree_records(uri, ctx)
try:
effective = await self._apply_subtree(
- uri, old_records, ctx, root_direct=proposed
+ uri,
+ old_records,
+ ctx,
+ root_direct=proposed_direct,
+ root_mode=acl_mode,
)
except Exception:
if old_records:
diff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.py
index 502e68c85..0a335889d 100644
--- a/openviking/storage/viking_fs/_access.py
+++ b/openviking/storage/viking_fs/_access.py
@@ -23,6 +23,7 @@ from openviking.storage.acl import (
AclAction,
AclEntry,
AclLevel,
+ AclMode,
acl_allows,
acl_ancestors,
has_implicit_manage,
@@ -297,8 +298,10 @@ class _AccessMixin:
async def set_acl(
self,
uri: str,
- entries: Sequence[AclEntry | Mapping[str, Any]],
+ entries: Sequence[AclEntry | Mapping[str, Any]] | None = None,
ctx: Optional[RequestContext] = None,
+ *,
+ acl_mode: AclMode | None = None,
) -> Dict[str, Any]:
real_ctx = await self._ensure_acl_manage(uri, ctx)
path = self._uri_to_path(uri, ctx=real_ctx)
@@ -306,7 +309,7 @@ class _AccessMixin:
try:
await self._ensure_acl_manage(uri, real_ctx)
await self._ensure_acl_target_exists(uri, real_ctx)
- effective = await self.acl_manager.set_direct(uri, entries, real_ctx)
+ effective = await self.acl_manager.set_acl(uri, entries, real_ctx, acl_mode=acl_mode)
return self.acl_manager.to_report(uri, effective)
finally:
await self._async_agfs.pathlock_release(lease)
@@ -349,13 +352,13 @@ class _AccessMixin:
entries.pop(principal, None)
else:
entries[principal] = AclEntry(principal, normalized_level)
- effective = await self.acl_manager.set_direct(uri, list(entries.values()), real_ctx)
+ effective = await self.acl_manager.set_acl(uri, list(entries.values()), real_ctx)
return self.acl_manager.to_report(uri, effective)
finally:
await self._async_agfs.pathlock_release(lease)
async def delete_acl(self, uri: str, ctx: Optional[RequestContext] = None) -> Dict[str, Any]:
- return await self.set_acl(uri, [], ctx=ctx)
+ return await self.set_acl(uri, [], acl_mode=AclMode.INHERIT, ctx=ctx)
def _ensure_user_not_deleting(self, ctx: RequestContext) -> None:
guard = getattr(self, "_user_deletion_guard", None)
diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.py
index 48c0cd60c..e75dcbc0b 100644
--- a/openviking/storage/viking_vector_index_backend.py
+++ b/openviking/storage/viking_vector_index_backend.py
@@ -2259,13 +2259,15 @@ class VikingVectorIndexBackend:
]
)
+ controlled_modes = [AclMode.INHERIT.value, AclMode.RESTRICTED.value]
uncontrolled_filter = And(
[
RawDSL(
{
"op": "must_not",
"field": ACL_MODE_FIELD,
- "conds": [AclMode.INHERIT.value],
+ # Exclude controlled modes so absent/null fields stay visible.
+ "conds": controlled_modes,
}
),
Or([PathScope("uri", root, depth=-1) for root in visible_roots(ctx)]),
@@ -2275,10 +2277,16 @@ class VikingVectorIndexBackend:
shared_acl_filter = And(
[
PathScope("uri", "viking://resources", depth=-1),
+ In(ACL_MODE_FIELD, controlled_modes),
Or(
[
In("acl_direct_grants", read_grants),
- In("acl_inherited_grants", read_grants),
+ And(
+ [
+ Eq(ACL_MODE_FIELD, AclMode.INHERIT.value),
+ In("acl_inherited_grants", read_grants),
+ ]
+ ),
]
),
]
diff --git a/sdk/go/acl.go b/sdk/go/acl.go
index b3a298e2d..757ce6cfd 100644
--- a/sdk/go/acl.go
+++ b/sdk/go/acl.go
@@ -12,6 +12,11 @@ type ACLEntry struct {
Level string `json:"level"`
}
+// SetACLOptions controls optional ACL properties updated together with direct entries.
+type SetACLOptions struct {
+ ACLMode string
+}
+
// ACL returns the direct, inherited, and effective ACL for a URI.
func (c *Client) ACL(ctx context.Context, uri string) (map[string]any, error) {
query := url.Values{"uri": []string{NormalizeURI(uri)}}
@@ -20,15 +25,28 @@ func (c *Client) ACL(ctx context.Context, uri string) (map[string]any, error) {
return result, err
}
-// SetACL replaces the direct ACL on a URI.
-func (c *Client) SetACL(ctx context.Context, uri string, entries []ACLEntry) (map[string]any, error) {
+// SetACL replaces the direct ACL on a URI and can update restricted mode atomically.
+func (c *Client) SetACL(ctx context.Context, uri string, entries []ACLEntry, options ...SetACLOptions) (map[string]any, error) {
if entries == nil {
entries = []ACLEntry{}
}
- var result map[string]any
- err := c.doJSON(ctx, http.MethodPut, "/api/v1/acl", nil, map[string]any{
+ body := map[string]any{
"uri": NormalizeURI(uri),
"entries": entries,
+ }
+ if len(options) > 0 && options[0].ACLMode != "" {
+ body["acl_mode"] = options[0].ACLMode
+ }
+ var result map[string]any
+ err := c.doJSON(ctx, http.MethodPut, "/api/v1/acl", nil, body, &result)
+ return result, err
+}
+
+// SetACLMode switches between inherit and restricted without changing direct grants.
+func (c *Client) SetACLMode(ctx context.Context, uri, aclMode string) (map[string]any, error) {
+ var result map[string]any
+ err := c.doJSON(ctx, http.MethodPut, "/api/v1/acl", nil, map[string]any{
+ "uri": NormalizeURI(uri), "acl_mode": aclMode,
}, &result)
return result, err
}
@@ -51,7 +69,7 @@ func (c *Client) RevokeACL(ctx context.Context, uri, principal string) (map[stri
return result, err
}
-// DeleteACL clears the direct ACL on a URI.
+// DeleteACL clears the direct ACL and restricted mode on a URI.
func (c *Client) DeleteACL(ctx context.Context, uri string) (map[string]any, error) {
query := url.Values{"uri": []string{NormalizeURI(uri)}}
var result map[string]any
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
index a1f3bbb10..bed2d4bf4 100644
--- a/sdk/python/openviking_sdk/client.py
+++ b/sdk/python/openviking_sdk/client.py
@@ -9,7 +9,7 @@ import uuid
import zipfile
from enum import Enum
from pathlib import Path
-from typing import Any, Callable, Dict, List, Mapping, Optional, Type, Union
+from typing import Any, Callable, Dict, List, Literal, Mapping, Optional, Type, Union
from urllib.parse import quote
import httpx
@@ -1314,10 +1314,23 @@ class AsyncHTTPClient:
response = await self._http.get("/api/v1/acl", params={"uri": VikingURI.normalize(uri)})
return self._handle_response_data(response).get("result", {})
- async def acl_set(self, uri: str, entries: List[Dict[str, str]]) -> Dict[str, Any]:
+ async def acl_set(
+ self,
+ uri: str,
+ entries: Optional[List[Dict[str, str]]] = None,
+ *,
+ acl_mode: Optional[Literal["inherit", "restricted"]] = None,
+ ) -> Dict[str, Any]:
+ if entries is None and acl_mode is None:
+ raise ValueError("Either entries or acl_mode must be provided")
+ payload: Dict[str, Any] = {"uri": VikingURI.normalize(uri)}
+ if entries is not None:
+ payload["entries"] = entries
+ if acl_mode is not None:
+ payload["acl_mode"] = acl_mode
response = await self._http.put(
"/api/v1/acl",
- json={"uri": VikingURI.normalize(uri), "entries": entries},
+ json=payload,
)
return self._handle_response_data(response).get("result", {})
@@ -2536,8 +2549,14 @@ class SyncHTTPClient:
def acl_get(self, uri: str) -> Dict[str, Any]:
return run_async(self._async_client.acl_get(uri))
- def acl_set(self, uri: str, entries: List[Dict[str, str]]) -> Dict[str, Any]:
- return run_async(self._async_client.acl_set(uri, entries))
+ def acl_set(
+ self,
+ uri: str,
+ entries: Optional[List[Dict[str, str]]] = None,
+ *,
+ acl_mode: Optional[Literal["inherit", "restricted"]] = None,
+ ) -> Dict[str, Any]:
+ return run_async(self._async_client.acl_set(uri, entries, acl_mode=acl_mode))
def acl_grant(self, uri: str, principal: str, level: str) -> Dict[str, Any]:
return run_async(self._async_client.acl_grant(uri, principal, level))
diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.py
index e5e87d431..1f5b98783 100644
--- a/tests/server/test_content_write_service.py
+++ b/tests/server/test_content_write_service.py
@@ -17,6 +17,7 @@ from openviking.server.identity import RequestContext, Role
from openviking.session.memory.dataclass import MemoryFile
from openviking.session.memory.utils import MemoryFileUtils
from openviking.session.memory.utils.content_visibility import visible_content
+from openviking.storage.acl import AclMode
from openviking.storage.content_write import ContentWriteCoordinator
from openviking.storage.errors import LockAcquisitionError, ResourceBusyError
from openviking.storage.queuefs.semantic_ops.freshness_policy import FreshnessAction
@@ -128,6 +129,10 @@ async def test_shared_resource_creation_inherits_acl_and_preserves_plain_append(
user=UserIdentifier(admin.account_id, "outsider"),
role=Role.USER,
)
+ late_reader = RequestContext(
+ user=UserIdentifier(admin.account_id, "late_reader"),
+ role=Role.USER,
+ )
parent_uri = "viking://resources/append_plain"
auto_protected_dir = "viking://resources/auto_protected"
uri = "viking://resources/append_plain/journal.md"
@@ -194,6 +199,70 @@ async def test_shared_resource_creation_inherits_acl_and_preserves_plain_append(
assert child_acl["direct_entries"] == []
assert child_acl["inherited_entries"] == [*inherited_entries, creator_entry]
+ restricted_acl = await service.fs.set_acl(
+ import_root,
+ None,
+ ctx=creator,
+ acl_mode=AclMode.RESTRICTED,
+ )
+ assert restricted_acl["acl_mode"] == "restricted"
+ assert restricted_acl["inherited_entries"] == inherited_entries
+ assert restricted_acl["effective_entries"] == [creator_entry]
+ child_acl = await service.fs.get_acl(children[0], ctx=creator)
+ assert child_acl["inherited_entries"] == [creator_entry]
+ with pytest.raises(PermissionDeniedError):
+ await service.fs.ls(import_root, ctx=reader, simple=True)
+
+ refreshed_inherited_entries = [
+ *inherited_entries,
+ {"principal": "user:late_reader", "level": "read"},
+ ]
+ await service.fs.set_acl(
+ parent_uri,
+ [
+ {"principal": "group:readers", "level": "read"},
+ {"principal": "group:writers", "level": "write"},
+ {"principal": "user:late_reader", "level": "read"},
+ ],
+ ctx=admin,
+ )
+ restricted_acl = await service.fs.get_acl(import_root, ctx=creator)
+ assert restricted_acl["inherited_entries"] == refreshed_inherited_entries
+ assert restricted_acl["effective_entries"] == [creator_entry]
+ child_acl = await service.fs.get_acl(children[0], ctx=creator)
+ assert child_acl["inherited_entries"] == [creator_entry]
+ with pytest.raises(PermissionDeniedError):
+ await service.fs.ls(import_root, ctx=late_reader, simple=True)
+
+ inherited_acl = await service.fs.set_acl(
+ import_root,
+ None,
+ ctx=creator,
+ acl_mode=AclMode.INHERIT,
+ )
+ assert inherited_acl["acl_mode"] == "inherit"
+ assert inherited_acl["inherited_entries"] == refreshed_inherited_entries
+ assert await service.fs.ls(import_root, ctx=late_reader, simple=True) == children
+
+ await service.fs.set_acl(import_root, [], acl_mode=AclMode.RESTRICTED, ctx=creator)
+ child_acl = await service.fs.get_acl(children[0], ctx=admin)
+ assert child_acl["acl_mode"] == "inherit"
+ assert child_acl["effective_entries"] == []
+ with pytest.raises(PermissionDeniedError):
+ await service.fs.ls(import_root, ctx=late_reader, simple=True)
+ with pytest.raises(PermissionDeniedError):
+ await service.viking_fs.read_file(children[0], ctx=late_reader)
+
+ removed_acl = await service.fs.delete_acl(import_root, ctx=admin)
+ assert removed_acl["acl_mode"] == "inherit"
+ assert removed_acl["direct_entries"] == []
+ assert removed_acl["inherited_entries"] == refreshed_inherited_entries
+ with pytest.raises(PermissionDeniedError):
+ await service.fs.get_acl(import_root, ctx=creator)
+ assert (await service.fs.get_acl(import_root, ctx=admin))["effective_entries"] == (
+ refreshed_inherited_entries
+ )
+
await service.fs.write(uri, content="line2\n", ctx=creator, mode="append", wait=True)
stored = await service.viking_fs.read_file(uri, ctx=reader)
diff --git a/tests/storage/test_collection_schemas.py b/tests/storage/test_collection_schemas.py
index 19f638ddf..b0047a9f2 100644
--- a/tests/storage/test_collection_schemas.py
+++ b/tests/storage/test_collection_schemas.py
@@ -741,6 +741,8 @@ def test_context_collection_uses_acl_mode_and_excludes_parent_uri():
assert "acl_enabled" not in schema["ScalarIndex"]
assert "parent_uri" not in field_names
assert "parent_uri" not in schema["ScalarIndex"]
+ assert "acl_restricted" not in field_names
+ assert "acl_restricted" not in schema["ScalarIndex"]
def test_context_collection_signature_has_no_include_parent_uri():
diff --git a/tests/storage/test_vector_transfer.py b/tests/storage/test_vector_transfer.py
index 5bbdd5c49..85bbe97c0 100644
--- a/tests/storage/test_vector_transfer.py
+++ b/tests/storage/test_vector_transfer.py
@@ -163,7 +163,7 @@ class _TransferAclManager:
async def materialize_moved_record(self, record, new_uri, ctx):
del new_uri, ctx
return {
- "acl_mode": "inherit",
+ "acl_mode": record.get("acl_mode", "inherit"),
"acl_direct_grants": list(record.get("acl_direct_grants") or []),
"acl_inherited_grants": ["1:group:target-readers"],
}
@@ -1038,7 +1038,7 @@ async def test_update_uri_mapping_preserves_source_direct_acl_on_target():
_record(
"source",
source,
- acl_mode="inherit",
+ acl_mode="restricted",
acl_direct_grants=["7:user:alice"],
acl_inherited_grants=["1:group:source-readers"],
)
@@ -1049,6 +1049,7 @@ async def test_update_uri_mapping_preserves_source_direct_acl_on_target():
moved = _records_under(backend, target, recursive=False)
assert len(moved) == 1
+ assert moved[0]["acl_mode"] == "restricted"
assert moved[0]["acl_direct_grants"] == ["7:user:alice"]
assert moved[0]["acl_inherited_grants"] == ["1:group:target-readers"]
diff --git a/tests/storage/test_viking_vector_scope_filter.py b/tests/storage/test_viking_vector_scope_filter.py
index 31c281c4b..a6fe570af 100644
--- a/tests/storage/test_viking_vector_scope_filter.py
+++ b/tests/storage/test_viking_vector_scope_filter.py
@@ -3,12 +3,13 @@
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.collection_schemas import CollectionSchemas
+from openviking.storage.expr import And, Eq, In, Or, PathScope
from openviking.storage.viking_vector_index_backend import VikingVectorIndexBackend
from openviking_cli.session.user_id import UserIdentifier
+from openviking_cli.utils.config.vectordb_config import VectorDBBackendConfig
def _ctx(*, role: Role = Role.USER, actor_peer_id: str | None = None) -> RequestContext:
@@ -121,7 +122,8 @@ def test_mixed_visible_and_outside_targets_keep_original_tenant_filter():
@pytest.mark.asyncio
-async def test_tenant_search_enforces_visible_roots_and_shared_acl():
[email protected]("legacy_mode", [{}, {"acl_mode": None}, {"acl_mode": "none"}])
+async def test_tenant_search_enforces_visible_roots_and_shared_acl(tmp_path, legacy_mode):
ctx = _ctx()
own_uri = "viking://user/alice/resources/notes"
cross_user_uri = "viking://user/bob/resources/notes"
@@ -139,6 +141,7 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl():
"context_type": "resource",
},
{
+ **legacy_mode,
"id": "legacy-shared",
"uri": "viking://resources/legacy.md",
"account_id": "acct",
@@ -160,6 +163,23 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl():
"acl_mode": "inherit",
"acl_inherited_grants": ["3:user:*"],
},
+ {
+ "id": "restricted-inherited-shared",
+ "uri": "viking://resources/restricted-inherited.md",
+ "account_id": "acct",
+ "context_type": "resource",
+ "acl_mode": "restricted",
+ "acl_inherited_grants": ["3:user:*"],
+ },
+ {
+ "id": "restricted-direct-shared",
+ "uri": "viking://resources/restricted-direct.md",
+ "account_id": "acct",
+ "context_type": "resource",
+ "acl_mode": "restricted",
+ "acl_direct_grants": ["1:user:alice"],
+ "acl_inherited_grants": ["7:user:bob"],
+ },
{
"id": "denied-shared",
"uri": "viking://resources/denied.md",
@@ -176,84 +196,92 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl():
},
]
- def matches(expr, record):
- if isinstance(expr, And):
- return all(matches(cond, record) for cond in expr.conds)
- if isinstance(expr, Or):
- return any(matches(cond, record) for cond in expr.conds)
- if isinstance(expr, Eq):
- return record.get(expr.field) == expr.value
- if isinstance(expr, In):
- return any(value in expr.values for value in record.get(expr.field, []))
- if isinstance(expr, RawDSL):
- assert expr.payload["op"] == "must_not"
- return record.get(expr.payload["field"]) not in expr.payload["conds"]
- if isinstance(expr, PathScope):
- root = uri_parts(expr.path)
- path = uri_parts(str(record.get(expr.field, "")))
- if path[: len(root)] != root:
- return False
- return expr.depth == -1 or len(path) - len(root) <= expr.depth
- raise AssertionError(f"Unexpected filter expression in test: {expr!r}")
-
- async def fake_search(*, filter, **_kwargs):
- return [record for record in records if matches(filter, record)]
-
- backend = object.__new__(VikingVectorIndexBackend)
- backend.acl_manager = AclManager(backend)
- backend.acl_manager.set_enabled(ctx.account_id, True)
- backend.search = fake_search
-
- visible = await backend.search_in_tenant(
- ctx=ctx,
- query_vector=[1.0],
- context_type="resource",
- )
- cross_user_only = await backend.search_in_tenant(
- ctx=ctx,
- query_vector=[1.0],
- context_type="resource",
- target_directories=[cross_user_uri],
- )
- internal = await backend.search_in_tenant(
- ctx=RequestContext(
- user=ctx.user,
- role=ctx.role,
- bypass_acl=True,
- ),
- query_vector=[1.0],
- context_type="resource",
- )
-
- assert [record["id"] for record in visible] == [
- "own",
- "legacy-shared",
- "direct-shared",
- "inherited-shared",
- ]
- assert cross_user_only == []
- assert [record["id"] for record in internal] == [
- "own",
- "cross-user",
- "legacy-shared",
- "direct-shared",
- "inherited-shared",
- "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",
+ backend = VikingVectorIndexBackend(
+ config=VectorDBBackendConfig(
+ backend="local", name="context", dimension=4, path=str(tmp_path / "vectors")
+ )
)
- assert [record["id"] for record in shared] == [
- "own",
- "legacy-shared",
- "direct-shared",
- "inherited-shared",
- "denied-shared",
- ]
+ try:
+ schema = CollectionSchemas.context_collection("context", 4)
+ # Exercise genuinely absent/null fields without a schema default filling them in.
+ next(field for field in schema["Fields"] if field["FieldName"] == "acl_mode").pop(
+ "DefaultValue"
+ )
+ assert await backend.create_collection("context", schema)
+ backend.acl_manager = AclManager(backend)
+ backend.acl_manager.set_enabled(ctx.account_id, True)
+ for record in records:
+ record_ctx = RequestContext(
+ user=UserIdentifier(record["account_id"], ctx.user.user_id), role=Role.ADMIN
+ )
+ await backend._upsert_many_raw(
+ [{**record, "level": 2, "vector": [1.0, 0.0, 0.0, 0.0]}], ctx=record_ctx
+ )
+
+ visible = await backend.search_in_tenant(
+ ctx=ctx,
+ query_vector=[1.0, 0.0, 0.0, 0.0],
+ context_type="resource",
+ )
+ cross_user_only = await backend.search_in_tenant(
+ ctx=ctx,
+ query_vector=[1.0, 0.0, 0.0, 0.0],
+ context_type="resource",
+ target_directories=[cross_user_uri],
+ )
+ internal = await backend.search_in_tenant(
+ ctx=RequestContext(
+ user=ctx.user,
+ role=ctx.role,
+ bypass_acl=True,
+ ),
+ query_vector=[1.0, 0.0, 0.0, 0.0],
+ context_type="resource",
+ )
+
+ assert sorted(record["id"] for record in visible) == sorted(
+ [
+ "own",
+ "legacy-shared",
+ "direct-shared",
+ "inherited-shared",
+ "restricted-direct-shared",
+ ]
+ )
+ assert cross_user_only == []
+ assert sorted(record["id"] for record in internal) == sorted(
+ [
+ "own",
+ "cross-user",
+ "legacy-shared",
+ "direct-shared",
+ "inherited-shared",
+ "restricted-inherited-shared",
+ "restricted-direct-shared",
+ "denied-shared",
+ ]
+ )
+
+ backend.acl_manager.set_enabled(ctx.account_id, False)
+ shared = await backend.search_in_tenant(
+ ctx=ctx,
+ query_vector=[1.0, 0.0, 0.0, 0.0],
+ context_type="resource",
+ )
+ assert sorted(record["id"] for record in shared) == sorted(
+ [
+ "own",
+ "legacy-shared",
+ "direct-shared",
+ "inherited-shared",
+ "restricted-inherited-shared",
+ "restricted-direct-shared",
+ "denied-shared",
+ ]
+ )
+
+ finally:
+ await backend.close()
def test_segment_prefix_and_visible_root_ancestor_do_not_elide_tenant_filter():