Skip to content

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

feat(acl): 默认继承全员管理权限并支持创建时授权 (#5266)

Qin Haojiee2011f29487b
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index d054bfedb..b2f522cb8 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -381,9 +381,13 @@ impl HttpClient {
processing_mode: &str,
tags: Vec<String>,
tag_mode: &str,
+ acl: Option<Value>,
) -> Result<serde_json::Value> {
let mut body = Self::build_write_body(uri, content, mode, wait, timeout, processing_mode);
add_resource_tag_fields(&mut body, &tags, tag_mode);
+ if let Some(acl) = acl {
+ body["acl"] = acl;
+ }
self.post("/api/v1/content/write", &body).await
}
@@ -637,11 +641,19 @@ impl HttpClient {
self.get("/api/v1/fs/tree", &params).await
}
- pub async fn mkdir(&self, uri: &str, description: Option<&str>) -> Result<serde_json::Value> {
- let body = match description {
+ pub async fn mkdir(
+ &self,
+ uri: &str,
+ description: Option<&str>,
+ acl: Option<Value>,
+ ) -> Result<serde_json::Value> {
+ let mut body = match description {
Some(description) => serde_json::json!({ "uri": uri, "description": description }),
None => serde_json::json!({ "uri": uri }),
};
+ if let Some(acl) = acl {
+ body["acl"] = acl;
+ }
self.post("/api/v1/fs/mkdir", &body).await
}
@@ -842,6 +854,7 @@ impl HttpClient {
resource_args: Option<Map<String, Value>>,
tags: Vec<String>,
tag_mode: String,
+ acl: Option<Value>,
show_progress: bool,
verbose: bool,
) -> Result<serde_json::Value> {
@@ -861,6 +874,9 @@ impl HttpClient {
let build_body = |base: serde_json::Value| {
let mut body = base;
+ if let Some(acl) = &acl {
+ body["acl"] = acl.clone();
+ }
add_resource_tag_fields(&mut body, &tags, &tag_mode);
if create_parent {
body.as_object_mut()
@@ -2034,6 +2050,7 @@ mod tests {
None,
Vec::new(),
"replace".to_string(),
+ None,
false,
false,
)
@@ -2070,6 +2087,7 @@ mod tests {
Some(no_split_args),
Vec::new(),
"replace".to_string(),
+ None,
false,
false,
)
diff --git a/crates/ov_cli/src/commands/content.rs b/crates/ov_cli/src/commands/content.rs
index a687876bc..8bdf0f231 100644
--- a/crates/ov_cli/src/commands/content.rs
+++ b/crates/ov_cli/src/commands/content.rs
@@ -46,6 +46,7 @@ pub async fn write(
processing_mode: &str,
tags: Vec<String>,
tag_mode: &str,
+ acl: Option<serde_json::Value>,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
@@ -59,6 +60,7 @@ pub async fn write(
processing_mode,
tags,
tag_mode,
+ acl,
)
.await?;
crate::output::output_success(result, output_format, compact);
diff --git a/crates/ov_cli/src/commands/filesystem.rs b/crates/ov_cli/src/commands/filesystem.rs
index 456284ca7..87e6e14cc 100644
--- a/crates/ov_cli/src/commands/filesystem.rs
+++ b/crates/ov_cli/src/commands/filesystem.rs
@@ -828,10 +828,11 @@ pub async fn mkdir(
client: &HttpClient,
uri: &str,
description: Option<&str>,
+ acl: Option<Value>,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
- let result = client.mkdir(uri, description).await?;
+ let result = client.mkdir(uri, description, acl).await?;
output_message_result(
result,
format!("Directory created: {}", uri),
diff --git a/crates/ov_cli/src/commands/resources.rs b/crates/ov_cli/src/commands/resources.rs
index e1e8189ad..42a7bd7df 100644
--- a/crates/ov_cli/src/commands/resources.rs
+++ b/crates/ov_cli/src/commands/resources.rs
@@ -24,6 +24,7 @@ pub async fn add_resource(
resource_args: Option<Map<String, Value>>,
tags: Vec<String>,
tag_mode: String,
+ acl: Option<serde_json::Value>,
format: OutputFormat,
compact: bool,
show_progress: bool,
@@ -50,6 +51,7 @@ pub async fn add_resource(
resource_args,
tags,
tag_mode,
+ acl,
show_progress,
verbose,
)
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index 5c00b2992..40fd73931 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -33,6 +33,7 @@ pub async fn handle_add_resource(
resource_args: Option<String>,
tags: Vec<String>,
tag_mode: String,
+ acl: Option<Value>,
ctx: CliContext,
) -> Result<()> {
let is_url =
@@ -123,6 +124,7 @@ pub async fn handle_add_resource(
add_resource_args,
tags,
tag_mode,
+ acl,
ctx.output_format,
ctx.compact,
ctx.should_show_progress(),
@@ -1398,6 +1400,7 @@ pub async fn handle_write(
processing_mode: String,
tags: Vec<String>,
tag_mode: String,
+ acl: Option<Value>,
ctx: CliContext,
) -> Result<()> {
let client = ctx.get_client();
@@ -1421,6 +1424,7 @@ pub async fn handle_write(
&processing_mode,
tags,
&tag_mode,
+ acl,
ctx.output_format,
ctx.compact,
)
@@ -1781,12 +1785,18 @@ pub async fn handle_tree(
.await
}
-pub async fn handle_mkdir(uri: String, description: Option<String>, ctx: CliContext) -> Result<()> {
+pub async fn handle_mkdir(
+ uri: String,
+ description: Option<String>,
+ acl: Option<Value>,
+ ctx: CliContext,
+) -> Result<()> {
let client = ctx.get_client();
commands::filesystem::mkdir(
&client,
&uri,
description.as_deref(),
+ acl,
ctx.output_format,
ctx.compact,
)
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 351d5d6e0..6927434a5 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -353,7 +353,7 @@ enum Commands {
conflicts_with_all = [
"add_type", "to", "parent", "parent_auto_create",
"strict_mode", "ignore_dirs", "include", "exclude",
- "no_directly_upload_media", "tags", "tag_mode",
+ "no_directly_upload_media", "tags", "tag_mode", "acl",
"reason", "instruction"
]
)]
@@ -465,6 +465,9 @@ enum Commands {
tag_mode: String,
#[command(flatten)]
upload_options: UploadCliOptions,
+ /// ACL JSON, for example {"acl_mode":"restricted","entries":[]}
+ #[arg(long, value_parser = |s: &str| serde_json::from_str::<serde_json::Value>(s))]
+ acl: Option<serde_json::Value>,
},
/// [Data] Add skills from a source (same as `skills add`)
AddSkill(SkillAddArgs),
@@ -614,6 +617,9 @@ enum Commands {
/// Initial directory description
#[arg(long, value_name = "text", help_heading = "Common options")]
description: Option<String>,
+ /// ACL JSON, for example {"acl_mode":"restricted","entries":[]}
+ #[arg(long, value_parser = |s: &str| serde_json::from_str::<serde_json::Value>(s))]
+ acl: Option<serde_json::Value>,
},
/// [Data] Remove resource
#[command(alias = "del", alias = "delete")]
@@ -749,6 +755,9 @@ enum Commands {
/// Tag update mode; clear does not require --tags
#[arg(long = "tag-mode", default_value = "replace", value_parser = ["replace", "append", "clear"])]
tag_mode: String,
+ /// ACL JSON, for example {"acl_mode":"restricted","entries":[]}
+ #[arg(long, value_parser = |s: &str| serde_json::from_str::<serde_json::Value>(s))]
+ acl: Option<serde_json::Value>,
},
/// [Data] Update explicit retrieval tags metadata for a file or directory
#[command(hide = true)]
@@ -3239,6 +3248,7 @@ async fn main() {
timeout,
tags,
tag_mode,
+ acl,
strict_mode,
ignore_dirs,
include,
@@ -3295,6 +3305,7 @@ async fn main() {
resource_args,
tags,
tag_mode,
+ acl,
ctx,
)
.await
@@ -3579,7 +3590,11 @@ async fn main() {
)
.await
}
- Commands::Mkdir { uri, description } => handlers::handle_mkdir(uri, description, ctx).await,
+ Commands::Mkdir {
+ uri,
+ description,
+ acl,
+ } => handlers::handle_mkdir(uri, description, acl, ctx).await,
Commands::Rm {
uri,
recursive,
@@ -3698,6 +3713,7 @@ async fn main() {
timeout,
tags,
tag_mode,
+ acl,
} => {
let effective_mode = if let Some(m) = mode {
m
@@ -3716,6 +3732,7 @@ async fn main() {
processing_mode,
tags,
tag_mode,
+ acl,
ctx,
)
.await
diff --git a/crates/ov_cli/src/openviking_assets.rs b/crates/ov_cli/src/openviking_assets.rs
index 7dc49156c..1b292944b 100644
--- a/crates/ov_cli/src/openviking_assets.rs
+++ b/crates/ov_cli/src/openviking_assets.rs
@@ -895,6 +895,7 @@ impl Submitter for HttpSubmitter {
args,
Vec::new(),
"replace".to_string(),
+ None,
false,
false,
)
diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.md
index 881b693f6..33c6ee4d6 100644
--- a/docs/en/api/02-resources.md
+++ b/docs/en/api/02-resources.md
@@ -191,6 +191,7 @@ This endpoint is the core entry point for resource management. It supports vario
| processing_mode | string | No | `semantic_and_vectors` | Post-ingest processing mode. `semantic_and_vectors` is the normal flow: generate semantic artifacts (`.abstract.md`, `.overview.md`) and vectors. `vectors_only` skips semantic understanding/VLM summarization and only vectorizes current resource files |
| tags | string[] | No | None | Explicit `k=v` retrieval tags written with generated vector records. An empty list with `replace` does not change existing tags |
| tag_mode | string | No | `replace` | Tag write mode: `replace`, `append`, or `clear`; `clear` removes existing tags without requiring `tags` and ignores supplied tag values |
+| acl | object | No | None | Direct ACL for the final import root; requires manage. Omission preserves existing permissions. See [ACL API](12-acl.md). |
| telemetry | TelemetryRequest | No | False | Whether to return telemetry data |
**Additional Notes**:
diff --git a/docs/en/api/12-acl.md b/docs/en/api/12-acl.md
index 2a6333463..0f018927b 100644
--- a/docs/en/api/12-acl.md
+++ b/docs/en/api/12-acl.md
@@ -1,283 +1,94 @@
# ACL API
-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.
+ACL is queried and managed through the dedicated `/api/v1/acl` endpoints for shared resources under `viking://resources/...`. See [resource access control](../concepts/15-acl.md) for inheritance rules.
-Read [Resource Access Control (ACL)](../concepts/15-acl.md) for the permission and inheritance model.
+## Endpoints
-## Endpoint Summary
-
-| Method | Path | Description |
-|--------|------|-------------|
-| GET | `/api/v1/acl?uri={uri}` | Get direct, inherited, and effective ACLs |
-| 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 |
+| Method | Path | Behavior |
+|---|---|---|
+| GET | `/api/v1/acl?uri={uri}` | Read direct, inherited and effective permissions |
+| PUT | `/api/v1/acl` | Set direct entries and/or inheritance mode |
| POST | `/api/v1/acl/grant` | Set one principal's direct level |
| POST | `/api/v1/acl/revoke` | Remove one principal's direct grant |
+| DELETE | `/api/v1/acl?uri={uri}` | Clear direct entries and restore inherit mode |
-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 `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
-
-### ACL entry
+**HTTP**
-```json
-{
- "principal": "user:bob",
- "level": "read"
-}
+```http
+GET /api/v1/acl?uri={uri}
+PUT /api/v1/acl
+DELETE /api/v1/acl?uri={uri}
+POST /api/v1/acl/grant
+POST /api/v1/acl/revoke
```
-| Field | Type | Description |
-|-------|------|-------------|
-| `principal` | string | `user:{user_id}`, `group:{group_id}`, or `user:*` |
-| `level` | string | `read`, `write`, or `manage` |
+All ACL operations require `manage` and return 403 without it; account ADMIN has implicit manage.
-The caller supplies the account-unique, stable `group_id` through the [Admin API](./08-admin.md#groups). A group has no separate display name. After a group is deleted, its old principal no longer matches any request unless the same `group_id` is created again.
+GET returns the ACL report directly in `result`. The report contains `uri`, `acl_mode`, `direct_entries`, `inherited_entries`, and `effective_entries`. Mutation endpoints return the report directly.
-### ACL report
+Example `set_acl` body:
```json
{
"uri": "viking://resources/project-a",
- "acl_mode": "inherit",
- "direct_entries": [
- {"principal": "user:bob", "level": "read"}
- ],
- "inherited_entries": [
- {"principal": "group:engineering", "level": "write"}
- ],
- "effective_entries": [
- {"principal": "group:engineering", "level": "write"},
- {"principal": "user:bob", "level": "read"}
- ]
+ "acl_mode": "restricted",
+ "entries": [{"principal": "user:bob", "level": "read"}]
}
```
-| Field | Description |
-|-------|-------------|
-| `direct_entries` | Entries set directly on this node |
-| `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.
+- `entries` replaces direct grants; omission preserves them; `[]` clears them.
+- `acl_mode`: `inherit` combines direct and inherited grants; `restricted` uses direct grants only. Omission preserves the mode.
+- Supply at least one field. Inherited and effective entries are read-only.
+- Principals are `user:{id}`, `group:{id}`, or `user:*`; levels are `read`, `write`, or `manage`. Duplicate principals retain the highest level.
+- `grant_acl` takes `{uri, principal, level}`, `revoke_acl` takes `{uri, principal}`, and resetting uses `DELETE /api/v1/acl?uri={uri}`. Incremental changes run inside the server's existing lock.
-## Get an ACL
+## Creation and content writes
-```
-GET /api/v1/acl?uri={uri}
-```
-
-GET can report an existing target that has no context record: `direct_entries` is empty and inherited permissions are resolved from existing ancestor contexts. Mutating ACL endpoints require a context record for the target.
-
-```bash
-curl "http://localhost:1933/api/v1/acl?uri=viking%3A%2F%2Fresources%2Fproject-a" \
- -H "X-API-Key: your-key"
-```
-
-**Python SDK**
-
-```python
-report = client.acl_get("viking://resources/project-a")
-```
-
-**Go SDK**
-
-```go
-report, err := client.ACL(ctx, "viking://resources/project-a")
-```
-
-## Update a Direct ACL or Restricted Mode
-
-```
-PUT /api/v1/acl
-```
-
-Request body:
+`POST /api/v1/resources`, `POST /api/v1/fs/mkdir`, and `POST /api/v1/content/write` accept a top-level `acl` field, alongside `tags` and `tag_mode` where supported:
```json
{
- "uri": "viking://resources/project-a",
- "entries": [
- {"principal": "user:bob", "level": "read"},
- {"principal": "group:engineering", "level": "write"}
- ],
- "acl_mode": "restricted"
+ "acl": {
+ "acl_mode": "restricted",
+ "entries": [{"principal": "user:bob", "level": "read"}]
+ }
}
```
-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 \
- -H "Content-Type: application/json" \
- -H "X-API-Key: your-key" \
- -d '{
- "uri": "viking://resources/project-a",
- "entries": [
- {"principal": "user:bob", "level": "read"},
- {"principal": "group:engineering", "level": "write"}
- ],
- "acl_mode": "restricted"
- }'
-```
-
-**Python SDK**
-
-```python
-report = client.acl_set(
- "viking://resources/project-a",
- [
- {"principal": "user:bob", "level": "read"},
- {"principal": "group:engineering", "level": "write"},
- ],
- acl_mode="restricted",
-)
-```
-
-The asynchronous client uses the same method name:
+Omitting ACL gives new nodes empty direct grants and inherited parent permissions; existing nodes retain their ACL. Explicit ACL requires inherited manage for a new node, or the existing node's own manage. Authorization and validation precede content mutation. Write access alone cannot change ACL. Creators receive no extra grants.
-```python
-report = await client.acl_set(uri, entries, acl_mode="restricted")
-```
-
-**Go SDK**
+Imports apply direct ACL only to the final import root. Descendants inherit it; automatically created parent directories receive no direct grants. Re-importing unchanged content still applies an explicit ACL update.
-```go
-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"})
+The account's `acl.enabled` defaults to false: namespace rules apply and ACL is ignored for access decisions. When enabled, the shared root permanently grants `user:* = manage`. Supplying ACL neither enables the account switch nor implicitly selects restricted mode.
-// Change only the mode without changing the direct ACL.
-report, err = client.SetACLMode(ctx, "viking://resources/project-a", "restricted")
-```
+ACL stays in the context index and follows existing asynchronous processing and wait semantics. Temporary inconsistency is accepted. Standalone ACL mutations require an existing context record. Vectorless records and empty-file support are outside this change.
**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
-
-```
-POST /api/v1/acl/grant
-```
-
-```json
-{
- "uri": "viking://resources/project-a",
- "principal": "user:bob",
- "level": "write"
-}
-```
-
-This sets Bob's direct level on the current node to `write`. It updates an existing direct entry without changing other principals.
-
-```bash
-curl -X POST http://localhost:1933/api/v1/acl/grant \
- -H "Content-Type: application/json" \
- -H "X-API-Key: your-key" \
- -d '{
- "uri": "viking://resources/project-a",
- "principal": "user:bob",
- "level": "write"
- }'
-```
-
-```python
-report = client.acl_grant(
- "viking://resources/project-a",
- principal="user:bob",
- level="write",
-)
-```
-
-```bash
+ov acl get viking://resources/project-a
+ov acl set viking://resources/project-a --acl-mode restricted --entry user:bob=read
ov acl grant viking://resources/project-a --principal user:bob --level write
-```
-
-## Remove One Direct Grant
-
-```
-POST /api/v1/acl/revoke
-```
-
-```json
-{
- "uri": "viking://resources/project-a",
- "principal": "user:bob"
-}
-```
-
-`revoke` removes only Bob's direct entry on the current node. Any permission inherited by Bob from an ancestor remains effective.
-
-```python
-report = client.acl_revoke("viking://resources/project-a", principal="user:bob")
-```
-
-```bash
ov acl revoke viking://resources/project-a --principal user:bob
-```
-
-## Clear the Node's Direct ACL
+ov acl rm viking://resources/project-a
+ov mkdir viking://resources/project-a --acl '{"acl_mode":"restricted","entries":[{"principal":"user:bob","level":"read"}]}'
+ov add-resource ./docs --to viking://resources/docs --acl '{"acl_mode":"restricted","entries":[]}'
+ov write viking://resources/project-a/a.md --content hello --mode create --acl '{"acl_mode":"inherit"}'
```
-DELETE /api/v1/acl?uri={uri}
-```
-
-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 \
- "http://localhost:1933/api/v1/acl?uri=viking%3A%2F%2Fresources%2Fproject-a" \
- -H "X-API-Key: your-key"
-```
+## SDK
```python
-report = client.acl_delete("viking://resources/project-a")
-```
-
-```bash
-ov acl rm viking://resources/project-a
-```
-
-## Errors
-
-The API checks manage permission before confirming existence to an authorized caller, preventing resource discovery through error types.
-
-| Scenario | Error |
-|----------|-------|
-| URI is outside `viking://resources/...` | `INVALID_ARGUMENT` |
-| Caller lacks manage | `PERMISSION_DENIED` |
-| Authorized caller targets a URI that does not exist | `NOT_FOUND` |
-| 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` |
-| `acl_mode` is not `inherit/restricted`, or the request includes read-only inherited fields | `INVALID_ARGUMENT` |
-
-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
-
-- [Resource Access Control (ACL)](../concepts/15-acl.md) - Permissions, inheritance, and retrieval semantics
-- [Authentication](../guides/04-authentication.md) - Request identity and account roles
-- [Filesystem API](./03-filesystem.md) - ACL-controlled file operations
-- [Retrieval API](./06-retrieval.md) - `find/search` endpoints
+acl = {"acl_mode": "restricted", "entries": [{"principal": "user:bob", "level": "read"}]}
+client.mkdir(uri, acl=acl)
+client.add_resource("./docs", to=uri, options={"acl": acl})
+client.write(file_uri, "hello", options={"acl": acl})
+report = client.acl_get(uri)
+client.acl_set(uri, [], acl_mode="restricted")
+client.acl_grant(uri, "user:bob", "read")
+client.acl_revoke(uri, "user:bob")
+client.acl_delete(uri)
+```
+
+Async Python uses the same method names. TypeScript provides `aclGet(uri)`, `aclSet`, `aclGrant`, `aclRevoke`, and `aclDelete`; creation options accept `acl`, while mkdir accepts it as its third argument. Go provides `ACL(ctx, uri)`, `SetACL`, `SetACLMode`, `GrantACL`, `RevokeACL`, and `DeleteACL`, with `ACLSpec` values for creation.
diff --git a/docs/en/concepts/15-acl.md b/docs/en/concepts/15-acl.md
index 3e113cab3..7dbb1dfae 100644
--- a/docs/en/concepts/15-acl.md
+++ b/docs/en/concepts/15-acl.md
@@ -13,7 +13,7 @@ viking://resources/...
```
- An account `ADMIN` implicitly has `manage` on `viking://resources/...`.
-- `viking://resources` is a fixed shared scope and cannot carry a direct ACL. ACLs start on files and directories below it.
+- `viking://resources` has a fixed, immutable `user:* = manage` ACL. Descendants inherit it until a restricted boundary.
- `viking://user/{user_id}/resources/...` is private and does not accept ACLs. To share it, move the resource into a writable shared directory and inherit that directory's ACL.
Implicit management is not stored as an ACL entry and cannot be removed by ACL changes. It ensures that shared resources always have an identity that can establish or recover permissions.
@@ -47,7 +47,7 @@ effective(node) = direct(node) + (acl_mode(node) == "restricted" ? empty : inher
`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:
+For example, first make `A` restricted to cut off the root wildcard grant, then configure:
```text
read user:bob on viking://resources/A
@@ -67,25 +67,24 @@ If `A/B` becomes restricted, Bob's grant on `A` no longer applies to `A/B` or it
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, 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
-does not change its direct ACL.
+ACL is not enforced. Indexed content still stores ACL fields using the same inheritance rules; the switch only controls access checks and retrieval filtering.
+
+When enabled, the root grants `user:* = manage`, so all account members can
+manage shared content that continues to inherit from the root. Without `acl`, new nodes have
+empty direct ACLs and inherit their parent’s effective permissions. Creating
+content grants no additional permissions. Import roots and descendants follow
+the same rule. Existing shared content without ACL fields uses default
+inheritance without a historical data migration. Disabling the setting stops
+enforcing existing ACLs. Re-embedding or replacing an existing context record
+does not change its direct ACL unless explicitly supplied. See [ACL API](../api/12-acl.md) for creation parameters.
`acl_mode` describes a resource's ACL behavior, separately from the account-wide `acl.enabled` switch:
-- `none`: use the original visibility rules without resource ACL enforcement.
+- `none`: ACL fields have not been materialized; shared nodes use default inheritance when ACL is enabled.
- `inherit`: use direct grants and permissions inherited from the parent.
- `restricted`: use direct grants only, while retaining and refreshing inherited grants.
-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.
+Users with `manage` can switch between `inherit` and `restricted`, but cannot set `none` to bypass the parent's ACL. Exiting restricted mode restores parent inheritance; all account members regain `manage` when no other restricted boundary interrupts the path to the root. A restricted node with no direct grants remains protected, as do descendants without separate grants; account administrators retain implicit management access.
## File Operations
@@ -100,13 +99,13 @@ All filesystem APIs use the same permission mapping:
| manage ACL | manage |
| move destination parent | write |
-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.
+The server canonicalizes the URI, then uses one authorization entry point for account/owner/actor-peer boundaries, effective ACLs when enabled or existing namespace rules when disabled, and write/delete namespace guards.
-When the account enables `acl.enabled`, a new shared node is bootstrapped by its
-creator's direct `manage` grant. Later ACL changes require effective `manage`
-capability.
+When the account enables `acl.enabled`, ordinary shared nodes inherit the root’s
+`user:* = manage` grant, allowing members to manage their ACLs. Creating content
+inside a restricted directory only inherits the parent’s permissions.
-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.
+An ACL grant on a directory is inherited by every descendant. `list`, `tree`, and other batch results still check every returned node because an open directory can contain independently restricted descendants.
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.
@@ -126,14 +125,16 @@ acl_inherited_grants
`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`. 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.
+ACLs update with the index, so records for the same URI may temporarily hold different versions. Reads use one ACL snapshot returned by the index, without merging grants across versions or blocking on temporary disagreement. Permission changes take effect as index updates complete; strong consistency is not guaranteed.
+
+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. Shared records with missing, `null`, or `none` modes use the root’s default wildcard access in retrieval. Stored inherit nodes must match their direct or inherited grants; inherit mode alone never grants wildcard access. 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.
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.
+existing direct ACL for the same URI. New nodes have empty direct ACLs and
+derive inherited ACL fields from their parent, including `7:user:*` when no
+restricted boundary intervenes. Creator identity does not affect authorization.
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
@@ -141,7 +142,8 @@ scope filters and ignores these ACL fields.
## Example
-Grant Bob read-only access to a directory:
+Assume `project-a` is already restricted and the caller has `manage` on it.
+Grant Bob read-only access to the directory:
```bash
ov acl grant viking://resources/project-a --principal user:bob --level read
diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.md
index d7b46e6b3..e7652c895 100644
--- a/docs/zh/api/02-resources.md
+++ b/docs/zh/api/02-resources.md
@@ -184,6 +184,7 @@ URL/文件 Parser TreeBuilder AGFS Summarizer/Vector
| processing_mode | string | 否 | `semantic_and_vectors` | 入库后的处理模式。`semantic_and_vectors` 是默认流程:生成语义产物(`.abstract.md`、`.overview.md`)并生成向量。`vectors_only` 跳过语义理解/VLM 总结,只对当前资源文件生成向量 |
| tags | string[] | 否 | None | 导入时写入向量检索记录的显式检索标签,格式必须是 `k=v`,例如 `["team=search", "env=test"]`。搜索接口可用同名 `tags` 参数过滤召回 |
| tag_mode | string | 否 | `"replace"` | 标签写入模式:`replace` 覆盖、`append` 按 key 合并、`clear` 清空。`clear` 不要求传 `tags`;`replace` 配合空数组不会修改已有标签。导入时标签会随本次生成的每条向量记录写入;不会在完成后额外调用 `set_tags`,响应也不返回 `tags_result` |
+| acl | object | 否 | None | 设置最终导入根节点的直接 ACL,要求 manage;省略时保留已有权限。见 [ACL API](12-acl.md)。 |
| telemetry | TelemetryRequest | 否 | False | 是否返回遥测数据 |
**补充说明**:
diff --git a/docs/zh/api/12-acl.md b/docs/zh/api/12-acl.md
index 5054bc968..6879a80d4 100644
--- a/docs/zh/api/12-acl.md
+++ b/docs/zh/api/12-acl.md
@@ -1,281 +1,104 @@
# ACL API
-ACL API 管理 `viking://resources/...` 共享资源的直接授权和 restricted 模式,并返回节点继承后的有效权限。个人资源不接受 ACL,需要分享时应移动到共享区。
+ACL 通过独立的 `/api/v1/acl` 接口查询和修改,只适用于 `viking://resources/...` 共享资源。权限模型见[资源访问控制](../concepts/15-acl.md)。
-权限模型和继承规则请先阅读 [资源访问控制(ACL)](../concepts/15-acl.md)。
+## 接口
-## 接口总览
+| 方法 | 路径 | 行为 |
+|---|---|---|
+| GET | `/api/v1/acl?uri={uri}` | 查询直接、继承和有效权限 |
+| PUT | `/api/v1/acl` | 设置直接授权、继承模式 |
+| POST | `/api/v1/acl/grant` | 设置单个 principal 的直接权限 |
+| POST | `/api/v1/acl/revoke` | 删除单个 principal 的直接授权 |
+| DELETE | `/api/v1/acl?uri={uri}` | 清空直接授权并恢复 inherit |
-| 方法 | 路径 | 说明 |
-|------|------|------|
-| GET | `/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 的直接授权 |
+**HTTP**
-所有接口都要求调用者对目标节点拥有 `manage`。共享资源由 account `ADMIN` 隐式管理。
-
-`viking://resources` 是固定共享 scope,不能设置直接 ACL。账号配置
-`acl.enabled` 默认为 `false`。关闭时,共享资源完全使用原有公开规则,不执行 ACL
-鉴权;开启后,新建共享文件、目录和 `add-resource` 根节点会给创建者直接
-`manage`,同时继承父目录 ACL。已有且未设置 ACL 的内容仍按公开规则访问;
-`add-resource` 的内部节点只继承,不重复写直接权限。
-
-## 数据结构
-
-### ACL entry
-
-```json
-{
- "principal": "user:bob",
- "level": "read"
-}
+```http
+GET /api/v1/acl?uri={uri}
+PUT /api/v1/acl
+DELETE /api/v1/acl?uri={uri}
+POST /api/v1/acl/grant
+POST /api/v1/acl/revoke
```
-| 字段 | 类型 | 说明 |
-|------|------|------|
-| `principal` | string | `user:{user_id}`、`group:{group_id}` 或 `user:*` |
-| `level` | string | `read`、`write` 或 `manage` |
-
-`group_id` 由调用者通过 [Admin API](./08-admin.md#用户组) 指定,是 account 内唯一且稳定的标识;用户组没有单独的展示名称。删除用户组后,旧 principal 不再匹配请求,除非重新创建同一个 `group_id`。
+以上操作均要求 `manage`,无权限时返回 403。账号 ADMIN 隐式拥有 manage。
-### ACL report
+查询响应中的 `result`:
```json
{
"uri": "viking://resources/project-a",
- "acl_mode": "inherit",
- "direct_entries": [
- {"principal": "user:bob", "level": "read"}
- ],
- "inherited_entries": [
- {"principal": "group:engineering", "level": "write"}
- ],
- "effective_entries": [
- {"principal": "group:engineering", "level": "write"},
- {"principal": "user:bob", "level": "read"}
- ]
+ "acl_mode": "restricted",
+ "direct_entries": [{"principal": "user:bob", "level": "read"}],
+ "inherited_entries": [{"principal": "user:*", "level": "manage"}],
+ "effective_entries": [{"principal": "user:bob", "level": "read"}]
}
```
-| 字段 | 说明 |
-|------|------|
-| `direct_entries` | 只包含当前节点直接设置的条目 |
-| `inherited_entries` | 父节点当前的有效权限;restricted 期间也会继续更新 |
-| `effective_entries` | inherit 时合并 direct 与 inherited;restricted 时仅使用 direct |
-| `acl_mode` | `none`:不受 ACL 控制;`inherit`:直接与继承权限均生效;`restricted`:仅直接权限生效 |
-
-account `ADMIN` 的隐式 `manage` 权限不出现在这些列表中。
-
-## 获取 ACL
-
-```
-GET /api/v1/acl?uri={uri}
-```
-
-GET 可以在目标尚无 context 记录时返回结果:`direct_entries` 为空,继承权限从已有祖先 context 计算。修改 ACL 的接口要求目标已有 context 记录。
-
-```bash
-curl "http://localhost:1933/api/v1/acl?uri=viking%3A%2F%2Fresources%2Fproject-a" \
- -H "X-API-Key: your-key"
-```
-
-**Python SDK**
-
-```python
-report = client.acl_get("viking://resources/project-a")
-```
-
-**Go SDK**
-
-```go
-report, err := client.ACL(ctx, "viking://resources/project-a")
-```
-
-## 更新直接 ACL 或 restricted 模式
-
-```
-PUT /api/v1/acl
-```
-
-请求体:
+修改接口直接返回 ACL report。`set_acl` 请求:
```json
{
"uri": "viking://resources/project-a",
- "entries": [
- {"principal": "user:bob", "level": "read"},
- {"principal": "group:engineering", "level": "write"}
- ],
- "acl_mode": "restricted"
+ "acl_mode": "restricted",
+ "entries": [{"principal": "user:bob", "level": "read"}]
}
```
-`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 \
- -H "Content-Type: application/json" \
- -H "X-API-Key: your-key" \
- -d '{
- "uri": "viking://resources/project-a",
- "entries": [
- {"principal": "user:bob", "level": "read"},
- {"principal": "group:engineering", "level": "write"}
- ],
- "acl_mode": "restricted"
- }'
-```
-
-**Python SDK**
-
-```python
-report = client.acl_set(
- "viking://resources/project-a",
- [
- {"principal": "user:bob", "level": "read"},
- {"principal": "group:engineering", "level": "write"},
- ],
- acl_mode="restricted",
-)
-```
-
-异步客户端使用相同方法名:
-
-```python
-report = await client.acl_set(uri, entries, acl_mode="restricted")
-```
-
-**Go SDK**
-
-```go
-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**
+- `entries`:完整替换直接授权;省略则保留;`[]` 清空。
+- `acl_mode`:`inherit` 合并直接与继承授权,`restricted` 仅使用直接授权;省略则保留。
+- 两个字段至少传一个。继承和有效权限是只读字段。
+- principal 支持 `user:{id}`、`group:{id}`、`user:*`,level 支持 `read`、`write`、`manage`。重复 principal 保留最高 level。
+- `grant_acl` 请求为 `{uri, principal, level}`;`revoke_acl` 为 `{uri, principal}`;重置使用 `DELETE /api/v1/acl?uri={uri}`。增删单个条目由服务端在锁内完成。
-```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 权限
-
-```
-POST /api/v1/acl/grant
-```
+`POST /api/v1/resources`、`POST /api/v1/fs/mkdir`、`POST /api/v1/content/write` 都接受顶层 `acl` 字段;支持 tags 的接口中,`acl` 与 `tags`、`tag_mode` 并列:
```json
{
- "uri": "viking://resources/project-a",
- "principal": "user:bob",
- "level": "write"
+ "acl": {
+ "acl_mode": "restricted",
+ "entries": [{"principal": "user:bob", "level": "read"}]
+ }
}
```
-该接口将 Bob 在当前节点上的直接 level 设置为 `write`。如果已有直接条目,则更新该条目;其他用户条目不变。
-
-```bash
-curl -X POST http://localhost:1933/api/v1/acl/grant \
- -H "Content-Type: application/json" \
- -H "X-API-Key: your-key" \
- -d '{
- "uri": "viking://resources/project-a",
- "principal": "user:bob",
- "level": "write"
- }'
-```
-
-```python
-report = client.acl_grant(
- "viking://resources/project-a",
- principal="user:bob",
- level="write",
-)
-```
-
-```bash
-ov acl grant viking://resources/project-a --principal user:bob --level write
-```
+不传 ACL:新节点直接授权为空并继承父目录,已有节点保留原权限。显式传 ACL:新节点要求调用者从父目录继承 manage,已有节点要求自身 manage;在内容修改前校验,write 权限不能用来提权。没有创建者额外权限。
-## 删除单个 principal 的直接授权
+导入只把直接 ACL 设置到最终导入根节点,子节点继承;自动创建的中间父目录不接收该授权。相同内容重新导入也会更新显式传入的 ACL。
-```
-POST /api/v1/acl/revoke
-```
-
-```json
-{
- "uri": "viking://resources/project-a",
- "principal": "user:bob"
-}
-```
+账号 `acl.enabled` 默认 false,关闭时按原 namespace 规则访问,ACL 不参与鉴权;开启后共享根目录固定 `user:* = manage` 且不可修改。传入 ACL 不会自动开启账号开关,也不会自动切换 restricted。
-`revoke` 只删除当前节点上 Bob 的直接条目。Bob 从祖先继承的权限仍然有效。
+ACL 仍保存在 context 索引内,允许短暂不一致,按现有异步任务和 wait 语义生效。独立修改 ACL 要求目标已有 context 记录;本次不增加无向量记录或空文件支持。
-```python
-report = client.acl_revoke("viking://resources/project-a", principal="user:bob")
-```
+**CLI**
```bash
+ov acl get viking://resources/project-a
+ov acl set viking://resources/project-a --acl-mode restricted --entry user:bob=read
+ov acl grant viking://resources/project-a --principal user:bob --level write
ov acl revoke viking://resources/project-a --principal user:bob
-```
-
-## 清空当前节点的直接 ACL
+ov acl rm viking://resources/project-a
+ov mkdir viking://resources/project-a --acl '{"acl_mode":"restricted","entries":[{"principal":"user:bob","level":"read"}]}'
+ov add-resource ./docs --to viking://resources/docs --acl '{"acl_mode":"restricted","entries":[]}'
+ov write viking://resources/project-a/a.md --content hello --mode create --acl '{"acl_mode":"inherit"}'
```
-DELETE /api/v1/acl?uri={uri}
-```
-
-该接口清空当前节点的直接 ACL 并退出 restricted;不会删除已保存的 inherited,也不删除后代节点的直接 ACL。清空后立即使用最新继承权限;父目录也不受 ACL 控制时,`acl_mode` 恢复为 `none`。
-```bash
-curl -X DELETE \
- "http://localhost:1933/api/v1/acl?uri=viking%3A%2F%2Fresources%2Fproject-a" \
- -H "X-API-Key: your-key"
-```
+## SDK
```python
-report = client.acl_delete("viking://resources/project-a")
-```
-
-```bash
-ov acl rm viking://resources/project-a
-```
-
-## 错误处理
-
-接口先校验 manage,再向已授权调用者确认 URI 是否存在,避免通过错误类型探测资源。
-
-| 场景 | 错误 |
-|------|------|
-| URI 不在 `viking://resources/...` | `INVALID_ARGUMENT` |
-| 调用者没有 manage | `PERMISSION_DENIED` |
-| 已授权调用者访问不存在的 URI | `NOT_FOUND` |
-| 修改 ACL 时 URI 尚无 context 记录 | `INVALID_ARGUMENT`,需先完成索引 |
-| `principal` 格式非法,或使用 `group:*` | `INVALID_ARGUMENT` |
-| level 不是 `read/write/manage` | `INVALID_ARGUMENT` |
-| `acl_mode` 不是 `inherit/restricted`,或请求包含 inherited 等只读字段 | `INVALID_ARGUMENT` |
-
-ACL 的 mode、direct 和 inherited 字段都保存在 context。更新会在同一子树批处理中修改目标字段并重算后代 inherited;写入失败时恢复原 context ACL 字段。
-
-## 相关文档
-
-- [资源访问控制(ACL)](../concepts/15-acl.md) - 权限、继承和检索语义
-- [认证](../guides/04-authentication.md) - 请求身份与 account 角色
-- [文件系统 API](./03-filesystem.md) - 受 ACL 控制的文件操作
-- [检索 API](./06-retrieval.md) - `find/search` 接口
+acl = {"acl_mode": "restricted", "entries": [{"principal": "user:bob", "level": "read"}]}
+client.mkdir(uri, acl=acl)
+client.add_resource("./docs", to=uri, options={"acl": acl})
+client.write(file_uri, "hello", options={"acl": acl})
+report = client.acl_get(uri)
+client.acl_set(uri, [], acl_mode="restricted")
+client.acl_grant(uri, "user:bob", "read")
+client.acl_revoke(uri, "user:bob")
+client.acl_delete(uri)
+```
+
+异步 Python 使用相同方法名。TypeScript 对应 `aclGet(uri)`、`aclSet`、`aclGrant`、`aclRevoke`、`aclDelete`;创建接口的 options 支持 `acl`,mkdir 使用第三个参数。Go 对应 `ACL(ctx, uri)`、`SetACL`、`SetACLMode`、`GrantACL`、`RevokeACL`、`DeleteACL`,通过 `ACLSpec` 设置创建权限。
diff --git a/docs/zh/concepts/15-acl.md b/docs/zh/concepts/15-acl.md
index 79ae54165..403c91bf1 100644
--- a/docs/zh/concepts/15-acl.md
+++ b/docs/zh/concepts/15-acl.md
@@ -13,7 +13,7 @@ viking://resources/...
```
- `viking://resources/...` 的 account `ADMIN` 隐式拥有 `manage`。
-- `viking://resources` 是固定共享 scope,本身不能设置直接 ACL;ACL 从它下面的文件和目录开始。
+- `viking://resources` 的根 ACL 固定为 `user:* = manage`,不可修改;下级节点默认继承,直到 restricted 边界。
- `viking://user/{user_id}/resources/...` 是个人私有区,不接受 ACL。需要分享时,将资源移动到有权写入的共享目录,并继承该目录的 ACL。
隐式管理权不会写入 ACL 条目,也不能被 ACL 删除。它保证共享资源始终有人能够首次设置或恢复权限。
@@ -47,7 +47,7 @@ effective(node) = direct(node) + (acl_mode(node) == "restricted" ? empty : inher
`inherited(node)` 始终保存父节点当前的有效权限。即使节点处于 restricted 模式,这个字段也会随父节点继续更新;退出 restricted 后会立即使用最新 inherited。后代继承的是当前节点的有效权限,因此不会绕过中间的 restricted 边界。
-例如:
+例如,先将 `A` 设为 restricted,截断根目录的全员管理授权,再配置:
```text
read user:bob on viking://resources/A
@@ -66,21 +66,21 @@ read user:carol on viking://resources/A/B/C/report.md
## 默认行为与 `acl_mode`
账号级 `acl.enabled` 默认关闭。关闭时,共享资源继续使用原有 URI namespace
-可见性和写入规则,不解析或校验 ACL,也不为新建内容写入 ACL。
+可见性和写入规则,不执行 ACL 鉴权和过滤。索引仍按统一继承规则保存 ACL,开关不影响已存权限。
-开启后,新建共享文件或目录的创建者会在首条 context 记录上获得直接 `manage`;
-父目录权限作为继承 ACL 合并。已有且未设置 ACL 的内容不会迁移或改权,仍按公开
-规则访问;重新关闭后,已有 ACL 也不再参与访问判断。`add-resource` 只把本次生成
-的根目录(`no_split` 时为根文件)作为创建节点:根节点获得创建者直接 `manage`,
-内部节点只继承,不重复写直接授权。重新向量化或覆盖已有 context 不会改变直接 ACL。
+开启后,根目录固定授予 `user:* = manage`,当前 account 内所有成员都可以管理
+持续继承根权限的共享内容。未传 `acl` 时,新节点的直接授权为空,只继承父目录的有效权限,
+不会因为创建了内容而获得额外权限。`add-resource` 的根节点和内部节点遵循相同规则。
+已有且未设置 ACL 的共享内容按默认继承计算,不进行历史数据迁移;重新关闭后,
+已有 ACL 不参与访问判断。重新向量化或未显式传入 ACL 的覆盖写不改变直接 ACL。创建时可通过 [acl](../api/12-acl.md) 设置目标节点权限。
`acl_mode` 表示当前资源如何使用 ACL,与账号总开关 `acl.enabled` 不是一回事:
-- `none`:该资源不受 ACL 控制,沿用原有可见性规则。
+- `none`:尚未写入 ACL 字段;开启 ACL 后,共享节点按默认继承规则计算权限。
- `inherit`:使用直接权限和父目录传下来的权限。
- `restricted`:只使用直接权限,但仍保存并更新父目录传下来的权限。
-有 `manage` 权限的用户可以切换 `inherit` / `restricted`,不能直接设置 `none` 绕过父目录权限。退出 restricted 且没有直接权限、父目录也不受 ACL 控制时,系统会恢复为 `none`。restricted 节点即使没有直接权限也不会变公开,其没有单独授权的后代同样不可访问;账号管理员仍有隐式管理权。
+有 `manage` 权限的用户可以切换 `inherit` / `restricted`,不能直接设置 `none` 绕过父目录权限。退出 restricted 后恢复继承父目录权限;父链未被其他 restricted 截断时,全员恢复 `manage`。restricted 节点即使没有直接权限也不会变公开,其没有单独授权的后代同样不可访问;账号管理员仍有隐式管理权。
## 文件操作
@@ -95,12 +95,12 @@ read user:carol on viking://resources/A/B/C/report.md
| 管理 ACL | manage |
| move 目标父目录 | write |
-服务端会先 canonicalize URI,再在同一个鉴权入口中依次执行 account/owner/actor peer 等硬边界、有效 ACL 或 legacy fallback,以及写入和删除的 namespace 防护。
+服务端会先 canonicalize URI,再在同一个鉴权入口中依次执行 account/owner/actor peer 等硬边界、开启时的有效 ACL 或关闭时的原有 namespace 规则,以及写入和删除的 namespace 防护。
-账号开启 `acl.enabled` 时,新建共享节点由创建者的直接 `manage` 完成权限
-bootstrap,后续 ACL 修改要求有效 `manage` 能力。
+账号开启 `acl.enabled` 时,普通共享节点继承根目录的全员 `manage`,成员可据此
+修改节点 ACL。restricted 下的创建者只有父目录授予的权限,不会自动获得 `manage`。
-目录上的 ACL 授权会被所有后代继承。`list`、`tree` 和批量结果仍逐个检查有效 ACL,因为未设置 ACL 的目录可能按原有 URI 规则可见,而某个后代已经通过自己的 ACL 进入控制域。
+目录上的 ACL 授权会被所有后代继承。`list`、`tree` 和批量结果仍逐个检查有效 ACL,因为默认开放的目录下可能存在独立的 restricted 边界。
共享区内部移动时,节点自己的 direct ACL 和 restricted 状态随节点移动,inherited 按新父节点重新计算。个人资源移入共享区时不携带 ACL,只继承目标目录权限;共享资源移回个人区时清空 ACL。
@@ -120,18 +120,21 @@ acl_inherited_grants
`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}`。检索在共享区内用 `acl_mode IN [inherit, restricted]` 判断受控资源,再匹配各 principal 的 `1`、`3`、`7` grant token:inherit 匹配 direct 或 inherited,restricted 只匹配 direct。旧记录字段缺失、为 `null` 或 `none` 时仍走原有可见性规则,不会因空值漏检,也不会被当作 ACL 已开启。个人资源始终按 URI owner 隔离。
+ACL 随索引更新,允许同一 URI 的不同索引记录短暂保留不同版本。读取采用索引返回的一份 ACL 快照,不合并不同版本的授权,也不因副本暂时不一致阻断处理。权限变更按索引更新进度生效,不保证强一致。
+
+请求的可用 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。未写入 ACL 字段(字段缺失、为 `null` 或 `none`)的共享记录按根目录默认全员授权参与检索。已保存的 inherit 节点必须匹配自己的直接或继承授权,不能因为模式是 inherit 就放行全员。个人资源始终按 URI owner 隔离。
检索 target URI 只是搜索范围,不要求调用者能够读取 target 节点本身。用户即使不能读取中间目录,也可以检索到深层单独授权给自己的文件。
账号开启 `acl.enabled` 时,共享区 context 写入会保留同 URI 已有 direct ACL;
-新创建节点为创建者生成直接 `manage`,并从父节点生成 inherited ACL。
-`add-resource` 的内部节点只继承导入根节点。重新向量化和普通覆盖写不会把受控记录
+新节点的直接授权为空,从父节点生成 inherited ACL;没有受限边界时,继承字段
+包含 `7:user:*`。创建者身份不参与授权计算。重新向量化和普通覆盖写不会把受控记录
恢复为默认可见,也不能通过普通 context 字段直接改 ACL。账号关闭该开关时,检索
只使用原有 account 和 URI scope 过滤,不使用这些 ACL 字段。
## 示例
+以下假定 `project-a` 已设为 restricted,且操作者拥有该节点的 `manage`。
将目录授权给 Bob 只读:
```bash
diff --git a/openviking/server/routers/acl.py b/openviking/server/routers/acl.py
index c9ea57841..2560b9f3a 100644
--- a/openviking/server/routers/acl.py
+++ b/openviking/server/routers/acl.py
@@ -1,9 +1,7 @@
"""ACL endpoints."""
-from typing import Literal
-
from fastapi import APIRouter, Body, Depends, Query
-from pydantic import BaseModel, ConfigDict, model_validator
+from pydantic import BaseModel, ConfigDict
from openviking.core.path_variables import resolve_path_variables
from openviking.core.uri_validation import validate_request_viking_uri
@@ -11,7 +9,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, AclMode
+from openviking.storage.acl import AclLevel, AclSpec
router = APIRouter(prefix="/api/v1/acl", tags=["acl"])
@@ -20,21 +18,8 @@ class _AclRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
-class AclEntryRequest(_AclRequest):
- principal: str
- level: AclLevel
-
-
-class SetAclRequest(_AclRequest):
+class SetAclRequest(AclSpec):
uri: str
- 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):
@@ -66,11 +51,7 @@ 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]
- if request.entries is not None
- else None
- ),
+ ([entry.to_dict() for entry in request.entries] if request.entries is not None else None),
acl_mode=request.acl_mode,
ctx=_ctx,
)
diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.py
index 859af0e69..d9089a21c 100644
--- a/openviking/server/routers/content.py
+++ b/openviking/server/routers/content.py
@@ -27,6 +27,7 @@ from openviking.server.error_mapping import map_exception
from openviking.server.identity import RequestContext, Role
from openviking.server.models import Response
from openviking.server.telemetry import run_operation
+from openviking.storage.acl import AclSpec
from openviking.storage.vector_ids import is_vector_record_id
from openviking.telemetry import TelemetryRequest
from openviking_cli.exceptions import InvalidArgumentError, NotFoundError, PermissionDeniedError
@@ -49,6 +50,7 @@ class WriteContentRequest(BaseModel):
processing_mode: ProcessingMode = DEFAULT_PROCESSING_MODE
tags: list[str] | None = None
tag_mode: Literal["replace", "append", "clear"] = "replace"
+ acl: AclSpec | None = None
class BatchWriteOperation(BaseModel):
@@ -249,6 +251,7 @@ async def write(
processing_mode=request.processing_mode,
tags=request.tags,
tag_mode=request.tag_mode,
+ acl=request.acl,
),
)
return Response(
diff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.py
index c44ed7463..191e5b134 100644
--- a/openviking/server/routers/filesystem.py
+++ b/openviking/server/routers/filesystem.py
@@ -18,6 +18,7 @@ from openviking.server.identity import RequestContext
from openviking.server.models import Response
from openviking.server.routers.content import SetTagsRequest
from openviking.server.routers.content import set_tags as content_set_tags
+from openviking.storage.acl import AclSpec
from openviking.storage.expr import And, Eq, In
from openviking.storage.vector_ids import is_vector_record_id
from openviking.storage.vikingdb_manager import VikingDBManagerProxy
@@ -249,6 +250,7 @@ class MkdirRequest(BaseModel):
uri: str
description: Optional[str] = None
+ acl: AclSpec | None = None
@router.post("/mkdir")
@@ -261,7 +263,12 @@ async def mkdir(
# Resolve path variables
uri = validate_request_viking_uri(resolve_path_variables(request.uri), _ctx)
try:
- await service.fs.mkdir(uri, ctx=_ctx, description=request.description)
+ await service.fs.mkdir(
+ uri,
+ ctx=_ctx,
+ description=request.description,
+ **({"acl": request.acl} if request.acl is not None else {}),
+ )
except AGFSClientError as e:
mapped = map_exception(e, resource=uri, resource_type="file")
if mapped is not None:
diff --git a/openviking/server/routers/resources.py b/openviking/server/routers/resources.py
index 155fd3ae0..e1d06f1ad 100644
--- a/openviking/server/routers/resources.py
+++ b/openviking/server/routers/resources.py
@@ -19,6 +19,7 @@ from openviking.server.responses import response_from_result
from openviking.server.skill_ingest import ingest_temp_upload_skill, install_skills
from openviking.server.telemetry import run_operation
from openviking.server.temp_upload_store import TempUploadStore
+from openviking.storage.acl import AclSpec
from openviking.telemetry import TelemetryRequest
from openviking_cli.exceptions import InvalidArgumentError
@@ -103,6 +104,7 @@ class AddResourceRequest(BaseModel):
processing_mode: ProcessingMode = DEFAULT_PROCESSING_MODE
tags: Optional[list[str]] = None
tag_mode: str = "replace"
+ acl: AclSpec | None = None
@model_validator(mode="after")
def check_path_or_temp_file_id(self):
@@ -331,6 +333,7 @@ async def add_resource(
instruction=request.instruction,
wait=request.wait,
timeout=request.timeout,
+ acl=request.acl,
tags=request.tags,
tag_mode=request.tag_mode,
allow_local_path_resolution=allow_local_path_resolution,
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 3f6abc935..5a1443e63 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -33,7 +33,7 @@ from openviking.storage.abstract_overview import (
plan_abstract_overview_refresh,
render_abstract_overview,
)
-from openviking.storage.acl import AclAction, AclMode, CreatorAclGrant
+from openviking.storage.acl import AclAction, AclMode, AclSpec
from openviking.storage.content_write import ContentWriteCoordinator
from openviking.storage.expr import And, Eq, In, Or
from openviking.storage.internal_names import is_storage_internal_name
@@ -47,6 +47,7 @@ from openviking.telemetry import get_current_telemetry
from openviking.telemetry.request_wait_tracker import get_request_wait_tracker
from openviking.telemetry.resource_summary import build_queue_status_payload
from openviking.utils.embedding_utils import vectorize_directory_meta
+from openviking.utils.ingest_options import IngestOptions
from openviking.utils.tags import normalize_search_tags
from openviking_cli.exceptions import (
DeadlineExceededError,
@@ -340,13 +341,18 @@ class FSService:
uri: str,
ctx: RequestContext,
description: Optional[str] = None,
+ acl: AclSpec | Dict[str, Any] | None = None,
) -> None:
"""Create directory."""
viking_fs = self._ensure_initialized()
self._reject_storage_internal_target(uri)
directory_uri, abstract_uri = self._resolve_directory_uris(uri)
async with self._uri_mutation_coordinator.mutation(ctx.account_id, [directory_uri]):
- directory_preexisting = await viking_fs.exists(directory_uri, ctx=ctx)
+ acl_update = (
+ await viking_fs.prepare_acl_update(directory_uri, acl, ctx)
+ if acl is not None
+ else None
+ )
await viking_fs.mkdir(uri, ctx=ctx)
lock_path = viking_fs._uri_to_path(abstract_uri, ctx=ctx)
@@ -354,8 +360,6 @@ class FSService:
try:
abstract = self._normalize_directory_description(description)
if not abstract:
- if await viking_fs.exists(abstract_uri, ctx=ctx):
- return
abstract = f"# {uri_leaf_name(directory_uri)}"
await viking_fs.write_file(
@@ -386,9 +390,7 @@ class FSService:
overview="",
context_type=context_type_for_uri(directory_uri),
ctx=ctx,
- creator_acl_grant=(
- CreatorAclGrant.DIRECT if not directory_preexisting else None
- ),
+ ingest_options=IngestOptions(acl_update=acl_update),
include_overview=False,
)
finally:
@@ -1159,6 +1161,7 @@ class FSService:
processing_mode: str = "semantic_and_vectors",
tags: Optional[List[str]] = None,
tag_mode: str = "replace",
+ acl: AclSpec | Dict[str, Any] | None = None,
) -> Dict[str, Any]:
"""Write to an existing file and refresh semantics/vectors."""
viking_fs = self._ensure_initialized()
@@ -1173,6 +1176,7 @@ class FSService:
processing_mode=processing_mode,
tags=tags,
tag_mode=tag_mode,
+ acl=acl,
)
async def batch_write(
diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.py
index c9a1971af..bdab1f021 100644
--- a/openviking/service/resource_service.py
+++ b/openviking/service/resource_service.py
@@ -61,7 +61,7 @@ from openviking.server.user_config import (
effective_resource_add_target,
effective_skill_add_target,
)
-from openviking.storage.acl import AclAction
+from openviking.storage.acl import AclAction, AclSpec
from openviking.storage.queuefs import QueueManager, get_queue_manager
from openviking.storage.queuefs.add_resource_msg import AddResourcePhase
from openviking.storage.viking_fs import LS_ALL_NODES, VikingFS
@@ -148,6 +148,7 @@ _ADD_RESOURCE_ARGS_RESERVED_FIELDS = frozenset(
"prepared_resource",
"tags",
"tag_mode",
+ "acl",
"internal_task",
}
)
@@ -352,16 +353,6 @@ class ResourceService:
if (tags is not None or tag_mode == "clear") and tag_mode not in _ADD_RESOURCE_TAG_MODES:
raise InvalidArgumentError(f"unsupported tag mode: {tag_mode}")
- def _add_resource_ingest_tag_kwargs(
- self,
- *,
- tags: Optional[List[str]],
- tag_mode: str,
- ) -> Dict[str, Any]:
- if tags is None and tag_mode != "clear":
- return {}
- return {"ingest_options": IngestOptions.from_search_tags(tags, mode=tag_mode)}
-
@staticmethod
def _ensure_single_resource_target(
*,
@@ -859,6 +850,7 @@ class ResourceService:
watch_interval=msg.watch_interval,
is_active=msg.is_active,
manage_watch=not msg.skip_watch_management,
+ acl=msg.acl,
tags=msg.tags,
tag_mode=msg.tag_mode,
allow_local_path_resolution=msg.allow_local_path_resolution,
@@ -906,10 +898,7 @@ class ResourceService:
summarize=msg.summarize,
build_index=msg.build_index,
processing_mode=msg.processing_mode,
- **self._add_resource_ingest_tag_kwargs(
- tags=msg.tags,
- tag_mode=msg.tag_mode,
- ),
+ ingest_options=IngestOptions.from_search_tags(msg.tags, mode=msg.tag_mode),
)
def _restore_source_task_auth(
@@ -1238,6 +1227,7 @@ class ResourceService:
manage_watch: bool,
tags: Optional[List[str]],
tag_mode: str,
+ acl: AclSpec | None,
to_is_directory: Optional[bool],
allow_local_path_resolution: bool,
enforce_public_remote_targets: bool,
@@ -1312,6 +1302,7 @@ class ResourceService:
parse_mode=mode.value,
watch_interval=watch_interval,
is_active=is_active,
+ acl=acl.model_dump(mode="json", exclude_none=True) if acl is not None else None,
skip_watch_management=not manage_watch,
tags=tags,
tag_mode=tag_mode,
@@ -1537,6 +1528,7 @@ class ResourceService:
internal_task: bool = False,
args: Optional[Dict[str, Any]] = None,
shared_source: Optional["SharedSource"] = None,
+ acl: AclSpec | dict[str, Any] | None = None,
**kwargs,
) -> Dict[str, Any]:
"""Accept and route a new resource-add request."""
@@ -1563,6 +1555,7 @@ class ResourceService:
processing_mode=processing_mode,
watch_interval=watch_interval,
is_active=is_active,
+ acl=acl,
manage_watch=True,
tags=tags,
tag_mode=tag_mode,
@@ -1646,6 +1639,7 @@ class ResourceService:
args: Optional[Dict[str, Any]] = None,
connector_states: Optional[Dict[str, Any]] = None,
shared_source: Optional["SharedSource"] = None,
+ acl: AclSpec | dict[str, Any] | None = None,
**kwargs,
) -> Dict[str, Any]:
"""Validate and route one resource ingestion request.
@@ -1781,6 +1775,8 @@ class ResourceService:
target_to = to or ""
target_parent = parent or ""
target_create_parent = bool(kwargs.get("create_parent", False))
+ if acl is not None:
+ acl = AclSpec.model_validate(acl)
connector = self._connector
delegate_to_connector = connector.should_delegate(
@@ -1803,6 +1799,11 @@ class ResourceService:
resolved = connector.resolve_add_type(path, add_type)
if resolved is None: # pragma: no cover - should_delegate already resolved it
raise InvalidArgumentError(f"'{path}' does not match any Connector source type.")
+ acl_update = (
+ await self._viking_fs.prepare_acl_update(target_to, acl, ctx)
+ if acl is not None
+ else None
+ )
watch_manager = self._get_watch_manager()
watch_auth_state = None
create_watch = bool(watch_manager and manage_watch and watch_interval > 0)
@@ -1890,6 +1891,20 @@ class ResourceService:
on_complete = record_first_run
on_success = store_connector_states
+ if acl_update is not None:
+ watch_on_success = on_success
+
+ async def apply_connector_acl(new_states=None):
+ await self._viking_fs.set_acl(
+ acl_update.uri,
+ acl_update.acl.entries,
+ ctx=ctx,
+ acl_mode=acl_update.acl.acl_mode,
+ )
+ if watch_on_success is not None:
+ await watch_on_success(new_states)
+
+ on_success = apply_connector_acl
try:
result = await connector.submit(
path=path,
@@ -1967,6 +1982,7 @@ class ResourceService:
manage_watch=manage_watch,
tags=tags,
tag_mode=tag_mode,
+ acl=acl,
to_is_directory=to_is_directory,
allow_local_path_resolution=allow_local_path_resolution,
enforce_public_remote_targets=enforce_public_remote_targets,
@@ -1998,6 +2014,7 @@ class ResourceService:
enforce_public_remote_targets=enforce_public_remote_targets,
watch_auth_state=normalized_args.watch_auth_state,
internal_task=internal_task,
+ acl=acl,
**kwargs,
)
get_current_telemetry().set("resource.flags.wait", wait)
@@ -2064,6 +2081,7 @@ class ResourceService:
prepared_resource: Optional["LocalResource"] = None,
internal_task: bool = False,
on_watch_ready: Optional[Callable[[str], None]] = None,
+ acl: AclSpec | dict[str, Any] | None = None,
**kwargs,
) -> Dict[str, Any]:
"""Execute an already-routed resource ingestion."""
@@ -2076,10 +2094,6 @@ class ResourceService:
register_telemetry(telemetry)
job_enqueued = False
deferred_lock: Optional[Dict[str, Any]] = None
- ingest_tag_kwargs = self._add_resource_ingest_tag_kwargs(
- tags=tags,
- tag_mode=tag_mode,
- )
watch_manager = self._get_watch_manager()
watch_enabled = bool(watch_manager and manage_watch and watch_interval > 0)
@@ -2116,7 +2130,9 @@ class ResourceService:
allow_local_path_resolution=allow_local_path_resolution,
prepared_resource=prepared_resource,
defer_post_processing=True,
- **ingest_tag_kwargs,
+ tags=tags,
+ tag_mode=tag_mode,
+ acl=acl,
**kwargs,
)
prepared_resource = None
@@ -2209,17 +2225,6 @@ class ResourceService:
else:
processing_lock = deferred_lock
deferred_lock = None
- post_process_kwargs = dict(kwargs)
- for key in (
- "resource_lock",
- "request_validator",
- "auth_config",
- FEISHU_ACCESS_TOKEN_ARG,
- FEISHU_REFRESH_TOKEN_ARG,
- "parser_backend",
- "resolved_extension",
- ):
- post_process_kwargs.pop(key, None)
post_result = await self._resource_processor.finish_prepared_resource(
prepared,
ctx=ctx,
@@ -2227,8 +2232,7 @@ class ResourceService:
summarize=summarize,
build_index=build_index,
processing_mode=processing_mode,
- **ingest_tag_kwargs,
- **post_process_kwargs,
+ ingest_options=IngestOptions.from_search_tags(tags, mode=tag_mode),
)
if post_result.get("warnings"):
result.setdefault("warnings", []).extend(post_result["warnings"])
diff --git a/openviking/storage/acl.py b/openviking/storage/acl.py
index 39f136484..a097df747 100644
--- a/openviking/storage/acl.py
+++ b/openviking/storage/acl.py
@@ -4,7 +4,9 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
-from typing import TYPE_CHECKING, Any, Iterable, Mapping, Protocol, Sequence
+from typing import TYPE_CHECKING, Any, Iterable, Literal, Mapping, Protocol, Sequence
+
+from pydantic import BaseModel, ConfigDict, model_validator
from openviking.core.identifiers import validate_identifier_part, validate_user_id
from openviking.core.namespace import uri_parts
@@ -38,11 +40,6 @@ class AclMode(str, Enum):
RESTRICTED = "restricted"
-class CreatorAclGrant(str, Enum):
- DIRECT = "direct"
- INHERITED = "inherited"
-
-
_LEVEL_MASK = {
AclLevel.READ: 1,
AclLevel.WRITE: 3,
@@ -52,7 +49,6 @@ _MASK_LEVEL = {mask: level for level, mask in _LEVEL_MASK.items()}
ACL_GRANT_FIELDS = ("acl_direct_grants", "acl_inherited_grants")
ACL_MODE_FIELD = "acl_mode"
ACL_CONTEXT_FIELDS = frozenset((ACL_MODE_FIELD, *ACL_GRANT_FIELDS))
-ACL_CREATOR_GRANT_FIELD = "_acl_creator_grant"
_ACL_OUTPUT_FIELDS = ["uri", *sorted(ACL_CONTEXT_FIELDS)]
@@ -65,14 +61,36 @@ class AclEntry:
return {"principal": self.principal, "level": self.level.value}
+class AclSpec(BaseModel):
+ """Explicit changes to a node's own permissions, never inherited grants."""
+
+ model_config = ConfigDict(extra="forbid", frozen=True)
+ entries: tuple[AclEntry, ...] | None = None
+ acl_mode: Literal[AclMode.INHERIT, AclMode.RESTRICTED] | None = None
+
+ @model_validator(mode="after")
+ def normalize(self) -> "AclSpec":
+ if self.entries is None and self.acl_mode is None:
+ raise ValueError("entries or acl_mode must be provided")
+ if self.entries is not None:
+ object.__setattr__(self, "entries", tuple(_normalize_entries(self.entries)))
+ return self
+
+
+class AclUpdate(BaseModel):
+ """An authorized ACL change bound to its final target URI."""
+
+ model_config = ConfigDict(extra="forbid", frozen=True)
+ uri: str
+ acl: AclSpec
+
+
@dataclass(frozen=True)
class DirectAcl:
entries: tuple[AclEntry, ...] = ()
@classmethod
- def from_entries(
- cls, entries: Iterable[AclEntry | Mapping[str, Any]]
- ) -> "DirectAcl":
+ def from_entries(cls, entries: Iterable[AclEntry | Mapping[str, Any]]) -> "DirectAcl":
return cls(tuple(_normalize_entries(entries)))
@property
@@ -143,6 +161,13 @@ class EffectiveAcl:
}
+_RESOURCES_ROOT_ACL = EffectiveAcl(
+ AclMode.INHERIT,
+ DirectAcl((AclEntry("user:*", AclLevel.MANAGE),)),
+ DirectAcl(),
+)
+
+
def normalize_acl_principal(principal: Any) -> str:
if not isinstance(principal, str):
raise InvalidArgumentError("principal must be a string")
@@ -292,11 +317,9 @@ class AclManager:
def _effective_from_records(cls, records: Sequence[Mapping[str, Any]]) -> EffectiveAcl:
if not records:
return EffectiveAcl(AclMode.NONE, DirectAcl(), DirectAcl())
- values = {cls._effective_from_record(record) for record in records}
- if len(values) != 1:
- uri = records[0].get("uri", "<unknown>")
- raise RuntimeError(f"Inconsistent ACL fields for context URI: {uri}")
- return values.pop()
+ # Index records refresh independently. Read one ACL snapshot rather than
+ # combining grants from different versions or blocking on disagreement.
+ return cls._effective_from_record(records[0])
@staticmethod
def _group_by_uri(records: Sequence[Mapping[str, Any]]) -> dict[str, list[Mapping[str, Any]]]:
@@ -352,41 +375,54 @@ class AclManager:
return records
async def get_direct(self, uri: str, ctx: RequestContext) -> DirectAcl:
- acl_ancestors(uri)
- records = await self._records_for_uris([uri], ctx)
- return self._effective_from_records(records).direct
+ return (await self.resolve(uri, ctx)).direct
async def resolve_many(
- self, uris: Iterable[str], ctx: RequestContext
+ self, uris: Iterable[str], ctx: RequestContext, *, update: AclUpdate | None = None
) -> dict[str, EffectiveAcl]:
unique_uris = list(dict.fromkeys(uris))
- paths = {uri: acl_ancestors(uri) for uri in unique_uris}
+ ancestors_by_uri = {uri: acl_ancestors(uri) for uri in unique_uris}
exact_records = await self._records_for_uris(unique_uris, ctx)
exact_groups = self._group_by_uri(exact_records)
- result = {
- uri: self._effective_from_records(exact_groups[uri])
- for uri in unique_uris
- if uri in exact_groups
- }
+ result: dict[str, EffectiveAcl] = {}
+ for uri, records in exact_groups.items():
+ effective = self._effective_from_records(records)
+ if not effective.enabled:
+ continue
+ # An update to this node or an ancestor requires recalculating inheritance.
+ if update is not None and update.uri in ancestors_by_uri[uri]:
+ continue
+ result[uri] = effective
+
+ if "viking://resources" in ancestors_by_uri:
+ result["viking://resources"] = _RESOURCES_ROOT_ACL
- missing = [uri for uri in unique_uris if uri not in result]
- if missing:
+ unresolved_uris = [uri for uri in unique_uris if uri not in result]
+ if unresolved_uris:
ancestor_records = await self._records_for_uris(
- (ancestor for uri in missing for ancestor in paths[uri]), ctx
+ (ancestor for uri in unresolved_uris for ancestor in ancestors_by_uri[uri]), ctx
)
ancestor_groups = self._group_by_uri(ancestor_records)
acl_map = {
uri: self._effective_from_records(records)
for uri, records in ancestor_groups.items()
}
- for uri in missing:
+ acl_map["viking://resources"] = _RESOURCES_ROOT_ACL
+ for uri in unresolved_uris:
effective = EffectiveAcl(AclMode.NONE, DirectAcl(), DirectAcl())
- for ancestor in paths[uri]:
+ for ancestor in ancestors_by_uri[uri]:
stored = acl_map.get(ancestor)
+ direct = stored.direct if stored is not None else DirectAcl()
+ mode = stored.mode if stored is not None else AclMode.NONE
+ if update is not None and ancestor == update.uri:
+ if update.acl.entries is not None:
+ direct = DirectAcl.from_entries(update.acl.entries)
+ if update.acl.acl_mode is not None:
+ mode = update.acl.acl_mode
effective = EffectiveAcl.from_permissions(
- stored.direct if stored is not None else DirectAcl(),
+ direct,
effective.permissions,
- mode=stored.mode if stored is not None else AclMode.NONE,
+ mode=mode,
parent_mode=effective.mode,
)
result[uri] = effective
@@ -396,14 +432,12 @@ class AclManager:
return (await self.resolve_many([uri], ctx))[uri]
async def materialize_context_records(
- self, records: Sequence[dict[str, Any]], ctx: RequestContext
+ self,
+ records: Sequence[dict[str, Any]],
+ ctx: RequestContext,
+ *,
+ update: AclUpdate | None = None,
) -> list[dict[str, Any]]:
- if not await 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")
@@ -416,50 +450,13 @@ class AclManager:
if not resource_uris:
return list(records)
- existing = await self._records_for_uris(resource_uris, ctx)
- existing_groups = self._group_by_uri(existing)
- existing_acl = {
- uri: self._effective_from_records(items) for uri, items in existing_groups.items()
- }
- new_uris = resource_uris.difference(existing_acl)
- parents: dict[str, str | None] = {}
- for uri in new_uris:
- ancestors = acl_ancestors(uri)
- 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)
- materialized: list[dict[str, Any]] = []
- for record in records:
- record = dict(record)
- raw_creator_grant = record.pop(ACL_CREATOR_GRANT_FIELD, None)
- creator_grant = (
- CreatorAclGrant(raw_creator_grant) if raw_creator_grant is not None else None
- )
- source_uri = str(record.get("uri") or "")
- if source_uri not in resource_uris:
- materialized.append(record)
- continue
- effective = existing_acl.get(source_uri)
- if effective is None:
- parent = parents[source_uri]
- inherited = parent_acl[parent].permissions if parent else DirectAcl()
- direct = DirectAcl()
- creator = (record.get("user") or {}).get("user_id")
- if creator and creator_grant is not None:
- creator_acl = DirectAcl.from_entries(
- [AclEntry(f"user:{creator}", AclLevel.MANAGE)]
- )
- if creator_grant == CreatorAclGrant.DIRECT:
- direct = creator_acl
- else:
- inherited = inherited.union(creator_acl)
- 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
+ effective = await self.resolve_many(resource_uris, ctx, update=update)
+ return [
+ {**record, **effective[str(record["uri"])].context_fields()}
+ if str(record.get("uri") or "") in effective
+ else dict(record)
+ for record in records
+ ]
async def materialize_moved_record(
self, record: Mapping[str, Any], new_uri: str, ctx: RequestContext
@@ -516,6 +513,9 @@ class AclManager:
effective_by_uri: dict[str, EffectiveAcl] = {}
root_depth = len(root_ancestors)
for uri in sorted(grouped, key=lambda value: len(acl_ancestors(value))):
+ if uri == "viking://resources":
+ effective_by_uri[uri] = _RESOURCES_ROOT_ACL
+ continue
ancestors = acl_ancestors(uri)
parent_effective = base
for ancestor in ancestors[root_depth - 1 : -1]:
@@ -541,6 +541,11 @@ class AclManager:
if records:
await self._apply_subtree(uri, records, ctx)
+ async def apply_indexed_update(self, update: AclUpdate, ctx: RequestContext) -> None:
+ """Apply an authorized ingestion update when the target is already indexed."""
+ if await self._records_for_uris([update.uri], ctx):
+ await self.set_acl(update.uri, update.acl.entries, ctx, acl_mode=update.acl.acl_mode)
+
async def set_acl(
self,
uri: str,
diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.py
index 42bd75ab4..3d0409a97 100644
--- a/openviking/storage/content_write.py
+++ b/openviking/storage/content_write.py
@@ -8,7 +8,7 @@ import base64
import binascii
import os
from collections import defaultdict
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import Any, Dict, Optional
from openviking.core.namespace import (
@@ -37,7 +37,7 @@ from openviking.storage.abstract_overview import (
plan_abstract_overview_refresh,
prepare_abstract_overview_write,
)
-from openviking.storage.acl import AclAction, CreatorAclGrant
+from openviking.storage.acl import AclAction, AclSpec
from openviking.storage.errors import LockAcquisitionError, ResourceBusyError
from openviking.storage.internal_names import is_storage_internal_name
from openviking.storage.queuefs import SemanticMsg, get_queue_manager
@@ -132,6 +132,7 @@ class ContentWriteCoordinator:
processing_mode: ProcessingMode = DEFAULT_PROCESSING_MODE,
tags: list[str] | None = None,
tag_mode: str = "replace",
+ acl: AclSpec | Dict[str, Any] | None = None,
) -> Dict[str, Any]:
self._validate_mode(mode)
processing_mode = normalize_processing_mode(processing_mode)
@@ -139,6 +140,11 @@ class ContentWriteCoordinator:
self._ensure_content_write_policy(normalized_uri)
await self._viking_fs._ensure_access(normalized_uri, ctx, action=AclAction.WRITE)
ingest_options = IngestOptions.from_search_tags(tags, mode=tag_mode)
+ if acl is not None:
+ ingest_options = replace(
+ ingest_options,
+ acl_update=await self._viking_fs.prepare_acl_update(normalized_uri, acl, ctx),
+ )
if mode == "create":
return await self._create_and_write(
@@ -881,7 +887,6 @@ class ContentWriteCoordinator:
uri=uri,
context_type=context_type,
ctx=ctx,
- creator_acl_grant=(CreatorAclGrant.DIRECT if mode == "create" else None),
ingest_options=ingest_options,
file_md5=content_md5(final_content),
)
@@ -899,6 +904,10 @@ class ContentWriteCoordinator:
file_abstract=file_abstract,
)
post_process_started = True
+ if ingest_options and ingest_options.acl_update:
+ await self._viking_fs.acl_manager.apply_indexed_update(
+ ingest_options.acl_update, ctx
+ )
await self._viking_fs._async_agfs.pathlock_release(lease)
lock_released = True
queue_status = (
@@ -994,7 +1003,6 @@ class ContentWriteCoordinator:
uri: str,
context_type: str,
ctx: RequestContext,
- creator_acl_grant: CreatorAclGrant | None = None,
ingest_options: IngestOptions | None = None,
file_md5: str | None = None,
) -> bool:
@@ -1008,7 +1016,6 @@ class ContentWriteCoordinator:
parent_uri=parent.uri,
context_type=context_type,
ctx=ctx,
- creator_acl_grant=creator_acl_grant,
ingest_options=ingest_options,
file_md5=file_md5,
)
diff --git a/openviking/storage/queuefs/add_resource_msg.py b/openviking/storage/queuefs/add_resource_msg.py
index 4d46b462c..42f7a90fa 100644
--- a/openviking/storage/queuefs/add_resource_msg.py
+++ b/openviking/storage/queuefs/add_resource_msg.py
@@ -62,6 +62,7 @@ class AddResourceMsg:
parse_mode: str = "default"
tags: Optional[list[str]] = None
tag_mode: str = "replace"
+ acl: Optional[Dict[str, Any]] = None
internal_task: bool = False
def __post_init__(self) -> None:
@@ -221,6 +222,7 @@ class AddResourceMsg:
),
processing_mode=data.get("processing_mode", DEFAULT_PROCESSING_MODE),
parse_mode=str(data.get("parse_mode") or "default"),
+ acl=data.get("acl"),
tags=(list(data["tags"]) if isinstance(data.get("tags"), list) else None),
tag_mode=str(data.get("tag_mode") or "replace"),
internal_task=bool(data.get("internal_task", False)),
diff --git a/openviking/storage/queuefs/embedding_msg_converter.py b/openviking/storage/queuefs/embedding_msg_converter.py
index 08378d7f1..a4c2a9e17 100644
--- a/openviking/storage/queuefs/embedding_msg_converter.py
+++ b/openviking/storage/queuefs/embedding_msg_converter.py
@@ -9,7 +9,6 @@ to EmbeddingMsg objects for asynchronous vector processing.
from openviking.core.context import Context, ContextLevel
from openviking.core.namespace import owner_fields_for_uri
-from openviking.storage.acl import ACL_CREATOR_GRANT_FIELD, CreatorAclGrant
from openviking.storage.index_action import IndexAction
from openviking.storage.queuefs.embedding_msg import EmbeddingMsg
from openviking.telemetry import get_current_telemetry
@@ -24,7 +23,6 @@ class EmbeddingMsgConverter:
@staticmethod
def from_context(
context: Context,
- creator_acl_grant: CreatorAclGrant | None = None,
action: IndexAction = IndexAction.MERGE,
) -> EmbeddingMsg | None:
"""
@@ -89,8 +87,6 @@ class EmbeddingMsgConverter:
else:
message = vectorization_text
- if creator_acl_grant is not None:
- context_data[ACL_CREATOR_GRANT_FIELD] = creator_acl_grant
embedding_msg = EmbeddingMsg.for_embed(
message=message,
context_data=context_data,
diff --git a/openviking/storage/queuefs/semantic_executor.py b/openviking/storage/queuefs/semantic_executor.py
index 9a360c639..f1675aa8c 100644
--- a/openviking/storage/queuefs/semantic_executor.py
+++ b/openviking/storage/queuefs/semantic_executor.py
@@ -29,7 +29,6 @@ from openviking.storage.abstract_overview import (
read_abstract_overview_pending_snapshot,
write_abstract_overview,
)
-from openviking.storage.acl import CreatorAclGrant
from openviking.storage.context_update_plan import FileVectorSource, SemanticAction
from openviking.storage.errors import LockAcquisitionError
from openviking.storage.index_action import FieldPatch
@@ -182,7 +181,6 @@ class SemanticTreeExecutor:
ctx: RequestContext,
incremental_update: bool = False,
target_uri: Optional[str] = None,
- target_preexisting: Optional[bool] = None,
recursive: bool = True,
lock: Optional[Dict[str, Any]] = None,
is_code_repo: bool = False,
@@ -205,7 +203,6 @@ class SemanticTreeExecutor:
self._ctx = ctx
self._incremental_update = incremental_update
self._target_uri = target_uri
- self._target_preexisting = target_preexisting
self._recursive = recursive
self._lock = lock
self._is_code_repo = bool(
@@ -240,7 +237,6 @@ class SemanticTreeExecutor:
self._changed_paths = {
path for key in ("added", "modified", "deleted") for path in self._changes.get(key, [])
}
- self._added_paths = {path.rstrip("/") for path in self._changes.get("added", [])}
self._tree_changed_paths = {
path.rstrip("/") for key in ("added", "deleted") for path in self._changes.get(key, [])
}
@@ -285,13 +281,6 @@ class SemanticTreeExecutor:
from openviking.storage.context_update_plan import SemanticAction
root = plan.root_uri.rstrip("/")
- root_entry = next(
- (entry for entry in plan.tree.entries if entry.relative_path == ""),
- None,
- )
- self._target_preexisting = not (
- root_entry is not None and root_entry.content_state.value in {"added", "restore"}
- )
current_entries = list(plan.tree.entries)
children: Dict[str, tuple[List[str], List[str]]] = {}
for entry in current_entries:
@@ -331,11 +320,6 @@ class SemanticTreeExecutor:
self._recursive = True
self._changes_provided = True
self._changed_paths = set(changed_uris)
- self._added_paths = {
- uri
- for uri, entry in self._plan_entries_by_uri.items()
- if entry.content_state.value in {"added", "restore", "replace_kind"}
- }
self._tree_changed_paths = {
root if not entry.relative_path else f"{root}/{entry.relative_path}"
for entry in plan.tree.entries
@@ -352,18 +336,6 @@ class SemanticTreeExecutor:
if entry.kind == "file" and (abstract := self._entry_record_abstract(entry, 2))
}
- def _creator_acl_grant(self, uri: str) -> CreatorAclGrant | None:
- normalized = uri.rstrip("/")
- if (
- self._generation_trigger == "resource_ingest" or self._semantic_plan is not None
- ) and self._target_preexisting is False:
- root = (self._semantic_resource_root or self._root_uri).rstrip("/")
- if normalized == root:
- return CreatorAclGrant.DIRECT
- if normalized.startswith(f"{root}/"):
- return CreatorAclGrant.INHERITED
- return CreatorAclGrant.DIRECT if normalized in self._added_paths else None
-
def _record_skill_failure(self, uri: str, error: Exception) -> None:
if self._context_type == "skill":
self._stats.failures.append(f"{uri}: {error}")
@@ -909,12 +881,12 @@ class SemanticTreeExecutor:
def _ingest_options_for_file(self, file_path: str) -> IngestOptions:
if self._generation_trigger == "content_write" and file_path not in self._changed_paths:
- return IngestOptions()
+ return IngestOptions(acl_update=self._ingest_options.acl_update)
return self._ingest_options
def _ingest_options_for_directory(self) -> IngestOptions:
if self._generation_trigger == "content_write":
- return IngestOptions()
+ return IngestOptions(acl_update=self._ingest_options.acl_update)
return self._ingest_options
def _plan_scalar_override(self, uri: str, level: int) -> Optional[Dict[str, Any]]:
@@ -1185,11 +1157,10 @@ class SemanticTreeExecutor:
ctx=self._ctx,
use_summary=use_summary,
ingest_options=(
- IngestOptions()
+ IngestOptions(acl_update=self._ingest_options.acl_update)
if self._semantic_plan is not None
else self._ingest_options_for_file(file_path)
),
- creator_acl_grant=self._creator_acl_grant(file_path),
file_md5=file_md5,
**vectorize_kwargs,
)
@@ -1549,11 +1520,10 @@ class SemanticTreeExecutor:
overview=overview,
ctx=self._ctx,
ingest_options=(
- IngestOptions()
+ IngestOptions(acl_update=self._ingest_options.acl_update)
if self._semantic_plan is not None
else self._ingest_options_for_directory()
),
- creator_acl_grant=self._creator_acl_grant(dir_uri),
**(
{"skill_source_path": (self._source or {}).get("path", "")}
if self._context_type == "skill"
diff --git a/openviking/storage/queuefs/semantic_msg.py b/openviking/storage/queuefs/semantic_msg.py
index 3e6f8dfb0..d29d324bd 100644
--- a/openviking/storage/queuefs/semantic_msg.py
+++ b/openviking/storage/queuefs/semantic_msg.py
@@ -62,7 +62,6 @@ class SemanticMsg:
target_uri: str = ""
lock_handoff: Optional[Dict[str, Any]] = None
is_code_repo: bool = False
- target_preexisting: Optional[bool] = None
ingest_options: IngestOptions = field(default_factory=IngestOptions)
coalesce_key: str = ""
coalesce_version: int = 0
@@ -99,7 +98,6 @@ class SemanticMsg:
target_uri: str = "",
lock_handoff: Optional[Dict[str, Any]] = None,
is_code_repo: bool = False,
- target_preexisting: Optional[bool] = None,
ingest_options: IngestOptions | Dict[str, Any] | None = None,
coalesce_key: str = "",
coalesce_version: int = 0,
@@ -133,7 +131,6 @@ class SemanticMsg:
self.target_uri = target_uri
self.lock_handoff = lock_handoff
self.is_code_repo = is_code_repo
- self.target_preexisting = target_preexisting
self.ingest_options = IngestOptions.from_value(ingest_options)
self.coalesce_key = coalesce_key
self.coalesce_version = coalesce_version
@@ -160,6 +157,8 @@ class SemanticMsg:
"""Convert object to dictionary."""
data = asdict(self)
data["ingest_options"] = self.ingest_options.to_dict()
+ if self.plan is not None:
+ data["plan"] = self.plan.to_dict()
return data
def to_json(self) -> str:
@@ -197,7 +196,6 @@ class SemanticMsg:
target_uri=data.get("target_uri", ""),
lock_handoff=data.get("lock_handoff"),
is_code_repo=data.get("is_code_repo", False),
- target_preexisting=data.get("target_preexisting"),
ingest_options=(
data.get("ingest_options")
or {
diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.py
index 27b967f58..ea4ec4b7f 100644
--- a/openviking/storage/queuefs/semantic_processor.py
+++ b/openviking/storage/queuefs/semantic_processor.py
@@ -47,7 +47,6 @@ from openviking.storage.abstract_overview import (
plan_abstract_overview_refresh,
write_abstract_overview,
)
-from openviking.storage.acl import CreatorAclGrant
from openviking.storage.errors import LockAcquisitionError
from openviking.storage.index_action import FieldPatch
from openviking.storage.queuefs.named_queue import DequeueHandlerBase
@@ -635,7 +634,6 @@ class SemanticProcessor(DequeueHandlerBase):
ctx=current_ctx,
incremental_update=is_incremental,
target_uri=target_uri,
- target_preexisting=msg.target_preexisting,
recursive=msg.recursive,
lock=semantic_lock.lock,
is_code_repo=msg.is_code_repo,
@@ -1852,7 +1850,6 @@ class SemanticProcessor(DequeueHandlerBase):
overview: str,
ctx: Optional[RequestContext] = None,
ingest_options: IngestOptions | None = None,
- creator_acl_grant: CreatorAclGrant | None = None,
skill_source_path: str = "",
scalar_overrides: Optional[Dict[int, Dict[str, Any]]] = None,
actions: Optional[Dict[int, str]] = None,
@@ -1883,7 +1880,6 @@ class SemanticProcessor(DequeueHandlerBase):
context_type=context_type,
ctx=active_ctx,
ingest_options=ingest_options,
- creator_acl_grant=creator_acl_grant,
content_is_body=context_type == "skill",
**({"meta": skill_meta} if skill_meta is not None else {}),
scalar_overrides=scalar_overrides,
@@ -1951,7 +1947,6 @@ class SemanticProcessor(DequeueHandlerBase):
use_summary: bool = False,
preserve_existing_created_at: bool = False,
ingest_options: IngestOptions | None = None,
- creator_acl_grant: CreatorAclGrant | None = None,
file_md5: Optional[str] = None,
file_content: Optional[bytes] = None,
scalar_override: Optional[Dict[str, Any]] = None,
@@ -1971,7 +1966,6 @@ class SemanticProcessor(DequeueHandlerBase):
use_summary=use_summary,
preserve_existing_created_at=preserve_existing_created_at,
ingest_options=ingest_options,
- creator_acl_grant=creator_acl_grant,
file_md5=file_md5,
file_content=file_content,
scalar_override=scalar_override,
diff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.py
index 3c81007c9..8dbeea1a0 100644
--- a/openviking/storage/viking_fs/_access.py
+++ b/openviking/storage/viking_fs/_access.py
@@ -24,6 +24,8 @@ from openviking.storage.acl import (
AclEntry,
AclLevel,
AclMode,
+ AclSpec,
+ AclUpdate,
acl_allows,
acl_ancestors,
has_implicit_manage,
@@ -34,6 +36,7 @@ from openviking.storage.acl import (
from openviking.storage.internal_names import is_storage_internal_name
from openviking_cli.exceptions import (
FailedPreconditionError,
+ InvalidArgumentError,
NotFoundError,
PermissionDeniedError,
)
@@ -195,11 +198,7 @@ class _AccessMixin:
effective = await acl_manager.resolve_many(pending, real_ctx) if pending else {}
for uri in pending:
- acl = effective[uri]
- if not acl.enabled:
- result[uri] = self._is_accessible(uri, real_ctx)
- else:
- result[uri] = acl_allows(acl, real_ctx, action)
+ result[uri] = acl_allows(effective[uri], real_ctx, action)
return result
async def _ensure_access(
@@ -278,9 +277,10 @@ class _AccessMixin:
acl_ancestors(uri)
if has_implicit_manage(real_ctx, uri):
return real_ctx
- effective = await self.acl_manager.resolve(uri, real_ctx)
- if effective.enabled and acl_allows(effective, real_ctx, AclAction.MANAGE):
- return real_ctx
+ if await self.acl_manager.is_enabled(real_ctx.account_id):
+ effective = await self.acl_manager.resolve(uri, real_ctx)
+ if acl_allows(effective, real_ctx, AclAction.MANAGE):
+ return real_ctx
raise PermissionDeniedError(f"ACL management denied for {uri}", resource=uri)
async def _ensure_acl_target_exists(self, uri: str, ctx: RequestContext) -> bool:
@@ -314,6 +314,19 @@ class _AccessMixin:
effective = await self.acl_manager.resolve(uri, real_ctx)
return self.acl_manager.to_report(uri, effective)
+ async def prepare_acl_update(
+ self,
+ uri: str,
+ acl: AclSpec | Mapping[str, Any],
+ ctx: RequestContext,
+ ) -> AclUpdate:
+ """Authorize an explicit ACL against the permissions before the write."""
+ spec = AclSpec.model_validate(acl)
+ if len(acl_ancestors(uri)) == 1:
+ raise InvalidArgumentError("ACL cannot be set on viking://resources")
+ await self._ensure_acl_manage(uri, ctx)
+ return AclUpdate(uri=uri, acl=spec)
+
async def set_acl(
self,
uri: str,
diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.py
index a33bee5a8..415211521 100644
--- a/openviking/storage/viking_vector_index_backend.py
+++ b/openviking/storage/viking_vector_index_backend.py
@@ -11,7 +11,6 @@ from dataclasses import dataclass
from typing import Any, AsyncIterator, Awaitable, Callable, Container, Dict, List, Mapping, Optional
from openviking.core.namespace import (
- canonical_user_root,
resolve_uri,
uri_parts,
visible_roots,
@@ -25,6 +24,7 @@ from openviking.storage.acl import (
AclAction,
AclManager,
AclMode,
+ AclUpdate,
acl_grant_tokens,
acl_principals,
is_acl_uri,
@@ -122,6 +122,7 @@ VIKINGDB_CONTENT_MAX_SIZE = 1024 * 1024
class UpsertOptions:
partial_update: bool = False
search_tag_mode: str = "replace"
+ acl_update: AclUpdate | None = None
@dataclass
@@ -154,6 +155,11 @@ def normalize_upsert_options(
return UpsertOptions(
partial_update=bool(options.get("partial_update", False)),
search_tag_mode=str(options.get("search_tag_mode", "replace")),
+ acl_update=(
+ AclUpdate.model_validate(options["acl_update"])
+ if options.get("acl_update") is not None
+ else None
+ ),
)
@@ -1118,7 +1124,7 @@ class VikingVectorIndexBackend:
options.search_tag_mode,
)
data = {key: value for key, value in data.items() if key not in ACL_CONTEXT_FIELDS}
- data = (await self._materialize_acl_fields([data], ctx))[0]
+ data = (await self._materialize_acl_fields([data], ctx, update=options.acl_update))[0]
backend = self._get_backend_for_context(ctx)
logger.debug(
"[VikingVectorIndexBackend.upsert] Using backend for account_id=%s",
@@ -1128,6 +1134,10 @@ class VikingVectorIndexBackend:
data,
options=options,
)
+ if result and options.acl_update and data.get("uri") == options.acl_update.uri:
+ # Import descendants can reach the index before their root. Once its
+ # own record exists, converge all stored inherited grants as well.
+ await self.acl_manager.refresh_context_subtree(options.acl_update.uri, ctx)
logger.debug(
"[VikingVectorIndexBackend.upsert] Completed with partial_update=%s, "
"search_tag_mode=%s, result=%s",
@@ -1174,11 +1184,15 @@ class VikingVectorIndexBackend:
return await self._get_backend_for_context(ctx).upsert_many(data_list)
async def _materialize_acl_fields(
- self, records: List[Dict[str, Any]], ctx: RequestContext
+ self,
+ records: List[Dict[str, Any]],
+ ctx: RequestContext,
+ *,
+ update: AclUpdate | None = None,
) -> List[Dict[str, Any]]:
if not self.acl_manager or not records:
return records
- return await self.acl_manager.materialize_context_records(records, ctx)
+ return await self.acl_manager.materialize_context_records(records, ctx, update=update)
async def update(self, data: Dict[str, Any], *, ctx: RequestContext) -> UpdateResult:
"""Strict update path. The target record must already exist."""
@@ -2679,31 +2693,33 @@ class VikingVectorIndexBackend:
)
controlled_modes = [AclMode.INHERIT.value, AclMode.RESTRICTED.value]
- uncontrolled_filter = And(
- [
- RawDSL(
- {
- "op": "must_not",
- "field": ACL_MODE_FIELD,
- # Exclude controlled modes so absent/null fields stay visible.
- "conds": controlled_modes,
- }
- ),
- Or([PathScope("uri", root, depth=-1) for root in visible_roots(ctx)]),
- ]
+ # Shared records written while ACL was disabled retain the root's
+ # default user:* manage access. Controlled descendants must match their
+ # own grants, including inherit nodes below a restricted boundary.
+ default_shared_filter = RawDSL(
+ {"op": "must_not", "field": ACL_MODE_FIELD, "conds": controlled_modes}
)
read_grants = acl_grant_tokens(acl_principals(ctx), AclAction.READ)
shared_acl_filter = And(
[
PathScope("uri", "viking://resources", depth=-1),
- In(ACL_MODE_FIELD, controlled_modes),
Or(
[
- In("acl_direct_grants", read_grants),
+ default_shared_filter,
And(
[
- Eq(ACL_MODE_FIELD, AclMode.INHERIT.value),
- In("acl_inherited_grants", read_grants),
+ In(ACL_MODE_FIELD, controlled_modes),
+ Or(
+ [
+ In("acl_direct_grants", read_grants),
+ And(
+ [
+ Eq(ACL_MODE_FIELD, AclMode.INHERIT.value),
+ In("acl_inherited_grants", read_grants),
+ ]
+ ),
+ ]
+ ),
]
),
]
@@ -2711,9 +2727,12 @@ class VikingVectorIndexBackend:
]
)
access_filters: List[FilterExpr] = [
- uncontrolled_filter,
+ *(
+ PathScope("uri", root, depth=-1)
+ for root in visible_roots(ctx)
+ if not is_acl_uri(root)
+ ),
shared_acl_filter,
- PathScope("uri", f"{canonical_user_root(ctx)}/resources", depth=-1),
]
if ctx.role == Role.ADMIN:
access_filters.append(PathScope("uri", "viking://resources", depth=-1))
diff --git a/openviking/utils/embedding_utils.py b/openviking/utils/embedding_utils.py
index fb336ae43..cc6abd6bd 100644
--- a/openviking/utils/embedding_utils.py
+++ b/openviking/utils/embedding_utils.py
@@ -27,7 +27,6 @@ from openviking.parse.parsers.upload_utils import is_text_file
from openviking.server.identity import RequestContext
from openviking.service.task_work_index import TaskWorkRejected
from openviking.storage.abstract_overview import body_for_preview, embedding_text_for_body
-from openviking.storage.acl import CreatorAclGrant
from openviking.storage.index_action import FieldPatch, IndexAction
from openviking.storage.queuefs import get_queue_manager
from openviking.storage.queuefs.embedding_msg_converter import EmbeddingMsgConverter
@@ -109,7 +108,13 @@ def _apply_ingest_options(
ingest_options: IngestOptions | None,
) -> None:
ingest_options = IngestOptions.from_value(ingest_options)
- if not embedding_msg or ingest_options.search_tags is None:
+ if not embedding_msg:
+ return
+ if ingest_options.acl_update is not None:
+ embedding_msg.context_data.setdefault("_upsert_options", {})["acl_update"] = (
+ ingest_options.acl_update.model_dump(mode="json")
+ )
+ if ingest_options.search_tags is None:
return
tag_mode = IngestOptions.vector_search_tag_mode(ingest_options.search_tag_mode)
incoming_tags = list(ingest_options.search_tags or [])
@@ -400,7 +405,6 @@ async def vectorize_directory_meta(
include_overview: bool = True,
scalar_overrides: Optional[Dict[int, Dict[str, Any]]] = None,
ingest_options: IngestOptions | None = None,
- creator_acl_grant: CreatorAclGrant | None = None,
include_abstract: bool = True,
meta: Optional[Dict[str, Any]] = None,
*,
@@ -462,7 +466,6 @@ async def vectorize_directory_meta(
)
msg_abstract = EmbeddingMsgConverter.from_context(
context_abstract,
- creator_acl_grant,
action=IndexAction(
(actions or {}).get(
int(ContextLevel.ABSTRACT.value),
@@ -523,7 +526,6 @@ async def vectorize_directory_meta(
)
msg_overview = EmbeddingMsgConverter.from_context(
context_overview,
- creator_acl_grant,
action=IndexAction(
(actions or {}).get(
int(ContextLevel.OVERVIEW.value),
@@ -583,7 +585,6 @@ async def vectorize_file(
scalar_override: Optional[Dict[str, Any]] = None,
field_patch: FieldPatch | None = None,
ingest_options: IngestOptions | None = None,
- creator_acl_grant: CreatorAclGrant | None = None,
file_md5: Optional[str] = None,
file_content: Optional[bytes] = None,
action: str = "merge",
@@ -723,7 +724,6 @@ async def vectorize_file(
raise ValueError(f"vectorize_file only supports upsert or merge actions: {action}")
embedding_msg = EmbeddingMsgConverter.from_context(
context,
- creator_acl_grant,
action=resolved_action,
)
if not embedding_msg:
diff --git a/openviking/utils/ingest_options.py b/openviking/utils/ingest_options.py
index a2c4f1537..877c9d61c 100644
--- a/openviking/utils/ingest_options.py
+++ b/openviking/utils/ingest_options.py
@@ -4,9 +4,10 @@
from __future__ import annotations
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import Any, Iterable, Mapping, Optional
+from openviking.storage.acl import AclUpdate
from openviking.utils.tags import normalize_search_tags
@@ -22,6 +23,7 @@ class IngestOptions:
search_tags: Optional[list[str]] = None
search_tag_mode: str = "replace"
+ acl_update: AclUpdate | None = None
@staticmethod
def vector_search_tag_mode(mode: str) -> str:
@@ -52,17 +54,25 @@ class IngestOptions:
if value is None:
return cls()
if isinstance(value, IngestOptions):
- return cls.from_search_tags(
- value.search_tags,
- mode=value.search_tag_mode,
+ return replace(
+ cls.from_search_tags(value.search_tags, mode=value.search_tag_mode),
+ acl_update=value.acl_update,
)
- return cls.from_search_tags(
- value.get("search_tags"),
- mode=str(value.get("search_tag_mode", "replace")),
+ return replace(
+ cls.from_search_tags(
+ value.get("search_tags"),
+ mode=str(value.get("search_tag_mode", "replace")),
+ ),
+ acl_update=(
+ AclUpdate.model_validate(value["acl_update"])
+ if value.get("acl_update") is not None
+ else None
+ ),
)
def to_dict(self) -> dict[str, Any]:
return {
"search_tags": list(self.search_tags) if self.search_tags is not None else None,
"search_tag_mode": self.search_tag_mode,
+ "acl_update": self.acl_update.model_dump(mode="json") if self.acl_update else None,
}
diff --git a/openviking/utils/resource_processor.py b/openviking/utils/resource_processor.py
index 84da449fd..fc5da9c86 100644
--- a/openviking/utils/resource_processor.py
+++ b/openviking/utils/resource_processor.py
@@ -12,6 +12,7 @@ import inspect
import os
import time
from collections.abc import Callable
+from dataclasses import replace
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from openviking.core.context import ContextLevel
@@ -26,7 +27,7 @@ from openviking.resource.processing_mode import (
normalize_processing_mode,
)
from openviking.server.identity import RequestContext
-from openviking.storage.acl import AclAction, CreatorAclGrant
+from openviking.storage.acl import AclAction, AclSpec, AclUpdate
from openviking.storage.errors import LockAcquisitionError
from openviking.storage.expr import And, Eq, PathScope
from openviking.storage.index_action import FieldPatch
@@ -655,6 +656,9 @@ class ResourceProcessor:
summarize: bool = False,
stage_callback: Optional[Callable[[str], Any]] = None,
prepared_resource: Optional["LocalResource"] = None,
+ tags: Optional[List[str]] = None,
+ tag_mode: str = "replace",
+ acl: AclSpec | Dict[str, Any] | None = None,
**kwargs,
) -> Dict[str, Any]:
"""
@@ -674,7 +678,7 @@ class ResourceProcessor:
}
defer_post_processing = bool(kwargs.pop("defer_post_processing", False))
preacquired_lock = kwargs.pop("resource_lock", None)
- ingest_options = IngestOptions.from_value(kwargs.pop("ingest_options", None))
+ ingest_options = IngestOptions.from_search_tags(tags, mode=tag_mode)
to_is_directory = bool(kwargs.pop("to_is_directory", False))
telemetry = get_current_telemetry()
metrics_account_id = getattr(ctx, "account_id", None)
@@ -928,6 +932,11 @@ class ResourceProcessor:
uri=root_uri,
root_is_file=root_is_file,
)
+ if acl is not None:
+ ingest_options = replace(
+ ingest_options,
+ acl_update=await viking_fs.prepare_acl_update(root_uri, acl, ctx),
+ )
artifact_ref = self._ensure_parse_artifact_ref(parse_result)
artifact_store = self._store_for_parse_artifact(
artifact_ref, output_store=output_store, viking_fs=viking_fs, ctx=ctx
@@ -956,21 +965,26 @@ class ResourceProcessor:
incremental_noop = target_preexisting and context_update_plan.is_noop()
temp_uri = root_uri
source_committed = True
- except Exception:
+ except BaseException:
# Mirror the Phase 3 (finalize) on-error cleanup: a lock or
# persist failure here would otherwise orphan the
# viking://temp tree with no GC (#2478). Skip when the temp
# tree was already persisted + deleted on the success path.
- if not source_committed:
- try:
+ try:
+ if not source_committed:
await self._cleanup_parse_result_artifact(
parse_result,
output_store=output_store,
viking_fs=get_viking_fs(),
ctx=ctx,
)
- except Exception:
- pass
+ except Exception:
+ pass
+ finally:
+ # The caller still owns a preacquired lease. Release
+ # leases acquired here if commit fails before handoff.
+ if resource_lock is not None and preacquired_lock is None:
+ await viking_fs._async_agfs.pathlock_release(resource_lock)
raise
if artifact_ref is not None:
@@ -1002,6 +1016,9 @@ class ResourceProcessor:
"is_code_repo": parse_result.source_format == "repository",
"root_is_file": root_is_file,
"incremental_noop": incremental_noop,
+ "acl_update": ingest_options.acl_update.model_dump(mode="json")
+ if ingest_options.acl_update
+ else None,
"context_update_plan": (
context_update_plan.to_dict() if context_update_plan is not None else None
),
@@ -1021,7 +1038,8 @@ class ResourceProcessor:
resource_lock=resource_lock,
summarize=summarize,
ingest_options=ingest_options,
- **kwargs,
+ build_index=bool(kwargs.get("build_index", True)),
+ processing_mode=normalize_processing_mode(kwargs.get("processing_mode")),
)
if post_result.get("warnings"):
result.setdefault("warnings", []).extend(post_result["warnings"])
@@ -1040,7 +1058,8 @@ class ResourceProcessor:
resource_lock: Optional[Dict[str, Any]] = None,
summarize: bool = False,
processing_mode: ProcessingMode = DEFAULT_PROCESSING_MODE,
- **kwargs: Any,
+ build_index: bool = True,
+ ingest_options: IngestOptions | None = None,
) -> Dict[str, Any]:
"""Run the queue-producing phase for a resource already stored in VikingFS."""
from openviking.metrics.datasources.resource import ResourceIngestionEventDataSource
@@ -1063,11 +1082,14 @@ class ResourceProcessor:
source_committed = bool(prepared.get("source_committed"))
metrics_account_id = getattr(ctx, "account_id", None)
target_preexisting = bool(prepared.get("target_preexisting"))
- build_index = bool(kwargs.get("build_index", True))
processing_mode = normalize_processing_mode(processing_mode)
vectors_only = processing_mode == VECTORS_ONLY
root_is_file = bool(prepared.get("root_is_file"))
- ingest_options = IngestOptions.from_value(kwargs.pop("ingest_options", None))
+ ingest_options = ingest_options or IngestOptions()
+ if prepared.get("acl_update") is not None:
+ ingest_options = replace(
+ ingest_options, acl_update=AclUpdate.model_validate(prepared["acl_update"])
+ )
semantic_source = prepared.get("semantic_source")
context_update_plan_data = prepared.get("context_update_plan")
context_update_plan = None
@@ -1127,6 +1149,10 @@ class ResourceProcessor:
try:
with get_current_telemetry().measure("resource.derived_enqueue"):
if prepared.get("incremental_noop") and not direct_index_actions:
+ if ingest_options.acl_update:
+ await get_viking_fs().acl_manager.apply_indexed_update(
+ ingest_options.acl_update, ctx
+ )
await cleanup_artifact_if_owned()
if resource_lock is not None:
await get_viking_fs()._async_agfs.pathlock_release(resource_lock)
@@ -1134,7 +1160,9 @@ class ResourceProcessor:
return result
if direct_index_actions:
- await self._enqueue_index_actions(direct_index_actions, ctx=ctx)
+ await self._enqueue_index_actions(
+ direct_index_actions, ctx=ctx, ingest_options=ingest_options
+ )
if should_summarize:
try:
@@ -1145,12 +1173,10 @@ class ResourceProcessor:
lock=resource_lock,
temp_uris=[temp_uri],
is_code_repo=bool(prepared.get("is_code_repo")),
- target_preexisting=target_preexisting,
ingest_options=ingest_options,
semantic_source=semantic_source,
generation_trigger="resource_ingest",
semantic_plan=semantic_plan,
- **kwargs,
)
if semantic_plan is not None and summary_result.get("status") != "success":
raise RuntimeError(
@@ -1173,12 +1199,14 @@ class ResourceProcessor:
if semantic_plan is not None:
raise
result["warnings"] = [f"Semantic enqueue failed: {exc}"]
- except Exception:
+ except BaseException:
derived_enqueue_status = "error"
- await cleanup_artifact_if_owned()
- if resource_lock is not None:
- await get_viking_fs()._async_agfs.pathlock_release(resource_lock)
- resource_lock = None
+ try:
+ await cleanup_artifact_if_owned()
+ finally:
+ if resource_lock is not None:
+ await get_viking_fs()._async_agfs.pathlock_release(resource_lock)
+ resource_lock = None
raise
finally:
ResourceIngestionEventDataSource.record_stage(
@@ -1236,9 +1264,6 @@ class ResourceProcessor:
root_uri,
ctx=ctx,
ingest_options=ingest_options,
- creator_acl_grant=(
- CreatorAclGrant.DIRECT if not target_preexisting else None
- ),
file_md5=(prepared.get("file_md5s") or {}).get(root_uri),
)
elif vectors_only:
@@ -1270,7 +1295,6 @@ class ResourceProcessor:
root_uri,
ctx=ctx,
ingest_options=ingest_options,
- creator_acl_grant=(CreatorAclGrant.DIRECT if not target_preexisting else None),
file_md5=(prepared.get("file_md5s") or {}).get(root_uri),
)
except BaseException:
@@ -1293,6 +1317,8 @@ class ResourceProcessor:
except BaseException:
await cleanup_artifact_if_owned()
raise
+ if ingest_options.acl_update:
+ await get_viking_fs().acl_manager.apply_indexed_update(ingest_options.acl_update, ctx)
await cleanup_artifact_if_owned()
return result
@@ -1320,7 +1346,9 @@ class ResourceProcessor:
kind = "local"
return {"kind": kind, "uri": str(path)}
- async def _enqueue_index_actions(self, actions: Any, *, ctx: RequestContext) -> None:
+ async def _enqueue_index_actions(
+ self, actions: Any, *, ctx: RequestContext, ingest_options: IngestOptions | None = None
+ ) -> None:
from collections import Counter
from openviking.storage.index_action import IndexAction
@@ -1357,6 +1385,7 @@ class ResourceProcessor:
action.uri,
ctx=ctx,
file_md5=action.md5,
+ ingest_options=ingest_options,
scalar_override={
**dict(action.upsert_fields),
"_record_id": action.record_id,
@@ -1514,7 +1543,6 @@ class ResourceProcessor:
*,
ctx: RequestContext,
ingest_options: IngestOptions | None = None,
- creator_acl_grant: CreatorAclGrant | None = None,
file_md5: str | None = None,
scalar_override: Optional[Dict[str, Any]] = None,
field_patch: FieldPatch | None = None,
@@ -1531,7 +1559,6 @@ class ResourceProcessor:
context_type=context_type_for_uri(file_uri),
ctx=ctx,
ingest_options=IngestOptions.from_value(ingest_options),
- creator_acl_grant=creator_acl_grant,
file_md5=file_md5,
scalar_override=scalar_override,
field_patch=field_patch,
diff --git a/openviking/utils/summarizer.py b/openviking/utils/summarizer.py
index a59b109f6..b8076e7f8 100644
--- a/openviking/utils/summarizer.py
+++ b/openviking/utils/summarizer.py
@@ -142,20 +142,6 @@ class Summarizer:
lock_handoff: Optional[Dict[str, Any]] = None
if lock is not None:
lock_handoff = await get_viking_fs()._async_agfs.pathlock_to_handoff(lock)
- target_preexisting_arg = kwargs.get("target_preexisting")
-
- def resolve_target_preexisting(index: int, target_uri: str) -> Optional[bool]:
- if target_preexisting_arg is None:
- return None
- if isinstance(target_preexisting_arg, dict):
- value = target_preexisting_arg.get(target_uri)
- return None if value is None else bool(value)
- if isinstance(target_preexisting_arg, (list, tuple)):
- if index >= len(target_preexisting_arg):
- return None
- value = target_preexisting_arg[index]
- return None if value is None else bool(value)
- return bool(target_preexisting_arg)
def is_resources_root(uri: str) -> bool:
return (uri or "").rstrip("/") == "viking://resources"
@@ -192,7 +178,7 @@ class Summarizer:
else:
enqueue_units.append((uri, temp_uri))
- for idx, (target_uri, source_uri) in enumerate(enqueue_units):
+ for target_uri, source_uri in enqueue_units:
msg = SemanticMsg(
uri=source_uri,
context_type=context_type,
@@ -206,7 +192,6 @@ class Summarizer:
target_uri=target_uri if target_uri != source_uri else None,
lock_handoff=lock_handoff,
is_code_repo=kwargs.get("is_code_repo", False),
- target_preexisting=resolve_target_preexisting(idx, target_uri),
ingest_options=ingest_options,
source=source,
generation_trigger=generation_trigger,
diff --git a/sdk/go/acl.go b/sdk/go/acl.go
index 757ce6cfd..64ed2fa1b 100644
--- a/sdk/go/acl.go
+++ b/sdk/go/acl.go
@@ -12,6 +12,13 @@ type ACLEntry struct {
Level string `json:"level"`
}
+// ACLSpec updates only the supplied ACL fields. Nil Entries preserves direct grants;
+// an empty non-nil slice clears them.
+type ACLSpec struct {
+ ACLMode string `json:"acl_mode,omitempty"`
+ Entries []ACLEntry `json:"entries"`
+}
+
// SetACLOptions controls optional ACL properties updated together with direct entries.
type SetACLOptions struct {
ACLMode string
diff --git a/sdk/go/filesystem.go b/sdk/go/filesystem.go
index e82732afc..2c708591a 100644
--- a/sdk/go/filesystem.go
+++ b/sdk/go/filesystem.go
@@ -117,9 +117,12 @@ func (c *Client) Attrs(ctx context.Context, uri string) (map[string]any, error)
}
// Mkdir creates a directory.
-func (c *Client) Mkdir(ctx context.Context, uri string, description string) error {
+func (c *Client) Mkdir(ctx context.Context, uri string, description string, acl ...ACLSpec) error {
payload := map[string]any{"uri": NormalizeURI(uri)}
setString(payload, "description", description)
+ if len(acl) > 0 {
+ payload["acl"] = acl[0]
+ }
return c.doJSON(ctx, http.MethodPost, "/api/v1/fs/mkdir", nil, payload, nil)
}
@@ -224,6 +227,9 @@ func (c *Client) Write(ctx context.Context, uri string, content string, opts *Wr
setFloatPtr(payload, "timeout", opts.Timeout)
setAny(payload, "telemetry", opts.Telemetry)
setString(payload, "processing_mode", opts.ProcessingMode)
+ if opts.ACL != nil {
+ payload["acl"] = opts.ACL
+ }
if opts.Tags != nil || opts.TagMode == "clear" {
if opts.Tags != nil {
payload["tags"] = opts.Tags
diff --git a/sdk/go/resources.go b/sdk/go/resources.go
index eff5a7540..8d92c147f 100644
--- a/sdk/go/resources.go
+++ b/sdk/go/resources.go
@@ -43,6 +43,9 @@ func (c *Client) AddResource(ctx context.Context, path string, opts *AddResource
if len(opts.Args) > 0 {
payload["args"] = opts.Args
}
+ if opts.ACL != nil {
+ payload["acl"] = opts.ACL
+ }
if opts.Tags != nil || opts.TagMode == "clear" {
if opts.Tags != nil {
payload["tags"] = opts.Tags
diff --git a/sdk/go/types.go b/sdk/go/types.go
index 857d5b74f..22ef80ff7 100644
--- a/sdk/go/types.go
+++ b/sdk/go/types.go
@@ -22,6 +22,7 @@ type Config struct {
// AddResourceOptions controls AddResource.
type AddResourceOptions struct {
+ ACL *ACLSpec
To string
Parent string
CreateParent *bool
@@ -219,6 +220,7 @@ type RemoveOptions struct {
// WriteOptions controls Write.
type WriteOptions struct {
+ ACL *ACLSpec
Mode string
Wait bool
Timeout *float64
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
index 87640f2e3..c794f51c6 100644
--- a/sdk/python/openviking_sdk/client.py
+++ b/sdk/python/openviking_sdk/client.py
@@ -1157,10 +1157,14 @@ class AsyncHTTPClient:
)
return self._handle_response(response)
- async def mkdir(self, uri: str, description: Optional[str] = None) -> None:
+ async def mkdir(
+ self, uri: str, description: Optional[str] = None, *, acl: Optional[Dict[str, Any]] = None
+ ) -> None:
payload = {"uri": VikingURI.normalize(uri)}
if description is not None:
payload["description"] = description
+ if acl is not None:
+ payload["acl"] = acl
response = await self._request("POST", "/api/v1/fs/mkdir", json=payload)
self._handle_response(response)
@@ -2518,8 +2522,10 @@ class SyncHTTPClient:
def attrs(self, uri: str) -> Dict[str, Any]:
return run_async(self._async_client.attrs(uri))
- def mkdir(self, uri: str, description: Optional[str] = None) -> None:
- run_async(self._async_client.mkdir(uri, description=description))
+ def mkdir(
+ self, uri: str, description: Optional[str] = None, *, acl: Optional[Dict[str, Any]] = None
+ ) -> None:
+ run_async(self._async_client.mkdir(uri, description=description, acl=acl))
def rm(
self,
diff --git a/sdk/python/openviking_sdk/options.py b/sdk/python/openviking_sdk/options.py
index 9fd028b4e..3bf867c8b 100644
--- a/sdk/python/openviking_sdk/options.py
+++ b/sdk/python/openviking_sdk/options.py
@@ -59,6 +59,7 @@ class SearchContextOptions(_ExtraOptions, total=False):
class AddResourceOptions(_ExtraOptions, total=False):
+ acl: Dict[str, Any]
reason: str
instruction: str
create_parent: bool
@@ -87,6 +88,7 @@ class UpdateSkillOptions(AddSkillOptions, total=False):
class WriteOptions(_ExtraOptions, total=False):
+ acl: Dict[str, Any]
telemetry: Any
processing_mode: ProcessingMode
tags: List[str]
diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts
index 874d4c21e..0455f2400 100644
--- a/sdk/typescript/src/client.ts
+++ b/sdk/typescript/src/client.ts
@@ -8,6 +8,7 @@ import {
import { OpenVikingTransport, type TransportOptions } from "./transport.js";
import type {
AddResourceOptions,
+ AclSpec,
BatchAddMessagesOptions,
BatchWriteOperation,
BatchWriteOptions,
@@ -157,6 +158,7 @@ export class OpenVikingClient {
? options.args
: undefined,
tags: options.tags,
+ acl: options.acl,
tag_mode:
options.tags !== undefined || options.tagMode === "clear"
? (options.tagMode ?? "replace")
@@ -533,9 +535,38 @@ export class OpenVikingClient {
});
}
/** Create a directory. */
- mkdir(uri: string, description?: string): Promise<void> {
+ mkdir(uri: string, description?: string, acl?: AclSpec): Promise<void> {
return this.request("POST", "/api/v1/fs/mkdir", {
- body: compact({ uri: normalizeURI(uri), description }),
+ body: compact({ uri: normalizeURI(uri), description, acl }),
+ });
+ }
+ aclGet(uri: string): Promise<JsonObject> {
+ return this.request("GET", "/api/v1/acl", {
+ query: { uri: normalizeURI(uri) },
+ });
+ }
+ aclSet(uri: string, acl: AclSpec): Promise<JsonObject> {
+ return this.request("PUT", "/api/v1/acl", {
+ body: { uri: normalizeURI(uri), ...acl },
+ });
+ }
+ aclGrant(
+ uri: string,
+ principal: string,
+ level: "read" | "write" | "manage",
+ ): Promise<JsonObject> {
+ return this.request("POST", "/api/v1/acl/grant", {
+ body: { uri: normalizeURI(uri), principal, level },
+ });
+ }
+ aclRevoke(uri: string, principal: string): Promise<JsonObject> {
+ return this.request("POST", "/api/v1/acl/revoke", {
+ body: { uri: normalizeURI(uri), principal },
+ });
+ }
+ aclDelete(uri: string): Promise<JsonObject> {
+ return this.request("DELETE", "/api/v1/acl", {
+ query: { uri: normalizeURI(uri) },
});
}
/** Remove a resource or directory. */
@@ -604,6 +635,7 @@ export class OpenVikingClient {
mode: options.mode,
processing_mode: options.processingMode,
tags: options.tags,
+ acl: options.acl,
tag_mode:
options.tags !== undefined || options.tagMode === "clear"
? (options.tagMode ?? "replace")
@@ -1198,7 +1230,12 @@ export class OpenVikingClient {
/** List users in an account, in creation order. `name` supports wildcard (* and ?) matching. */
adminListUsers(
accountId: string,
- options: { limit?: number; name?: string; role?: string; page?: number } = {},
+ options: {
+ limit?: number;
+ name?: string;
+ role?: string;
+ page?: number;
+ } = {},
): Promise<unknown[]> {
return this.request(
"GET",
diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.ts
index 5d5a657e0..837b2a916 100644
--- a/sdk/typescript/src/types.ts
+++ b/sdk/typescript/src/types.ts
@@ -74,8 +74,14 @@ export interface WaitOptions {
timeout?: number;
telemetry?: unknown;
}
+/** Writable direct grants and inheritance mode. */
+export interface AclSpec {
+ acl_mode?: "inherit" | "restricted";
+ entries?: { principal: string; level: "read" | "write" | "manage" }[];
+}
/** Resource import options. */
export interface AddResourceOptions extends WaitOptions {
+ acl?: AclSpec;
to?: string;
parent?: string;
createParent?: boolean;
@@ -96,6 +102,7 @@ export interface AddResourceOptions extends WaitOptions {
}
/** Content write options. */
export interface WriteOptions extends WaitOptions {
+ acl?: AclSpec;
mode?: string;
processingMode?: ProcessingMode;
tags?: string[];
diff --git a/tests/misc/test_resource_processor_mv.py b/tests/misc/test_resource_processor_mv.py
index a3c1320e2..1be52a52c 100644
--- a/tests/misc/test_resource_processor_mv.py
+++ b/tests/misc/test_resource_processor_mv.py
@@ -446,7 +446,6 @@ async def test_resource_processor_first_add_summarizes_from_committed_uri(monkey
assert fake_fs.persist_calls == []
assert fake_fs.delete_temp_calls == [("viking://temp/tmpdir", None)]
assert summarize_calls[0]["temp_uris"] == ["viking://resources/root"]
- assert summarize_calls[0]["target_preexisting"] is False
@pytest.mark.asyncio
@@ -675,17 +674,18 @@ async def test_resource_processor_second_add_preserves_temp_uri_for_incremental(
assert result["status"] == "success"
assert result["root_uri"] == "viking://resources/root"
assert summarize_calls[0]["temp_uris"] == ["viking://resources/root"]
- assert summarize_calls[0]["target_preexisting"] is True
assert fake_fs.persist_calls == []
@pytest.mark.asyncio
-async def test_resource_processor_auto_candidate_skips_existing_and_busy(monkeypatch):
+async def test_resource_processor_releases_resolved_candidate_when_acl_denied(monkeypatch):
from openviking.utils.resource_processor import ResourceProcessor
+ from openviking_cli.exceptions import PermissionDeniedError
fake_pathlock = _FakePathLock(busy_tree_paths={"/mock/resources/root_1"})
fake_fs = _FakeVikingFS(existing_uris={"viking://resources/root"}, pathlock=fake_pathlock)
- summarize_calls = []
+ fake_fs.prepare_acl_update = AsyncMock(side_effect=PermissionDeniedError("ACL denied"))
+ fake_pathlock.pathlock_release = AsyncMock()
monkeypatch.setattr(
"openviking.utils.resource_processor.get_current_telemetry",
@@ -713,28 +713,11 @@ async def test_resource_processor_auto_candidate_skips_existing_and_busy(monkeyp
rp._commit_directory_artifact_with_plan = AsyncMock(
side_effect=lambda **kwargs: _directory_plan(kwargs["root_uri"])
)
- rp._summarizer = SimpleNamespace(
- summarize=AsyncMock(
- side_effect=lambda *args, **kwargs: (
- summarize_calls.append(kwargs) or {"status": "success"}
- )
+ with pytest.raises(PermissionDeniedError):
+ await rp.process_resource(
+ path="x", ctx=object(), build_index=True, acl={"acl_mode": "inherit"}
)
- )
- result = await rp.process_resource(path="x", ctx=object(), build_index=True)
-
- assert result["status"] == "success"
- assert result["root_uri"] == "viking://resources/root_2"
- assert fake_fs.exists_calls == [
- "viking://resources/root",
- "viking://resources/root_1",
- "viking://resources/root_2",
- ]
- assert fake_pathlock.tree_attempts == [
- ("/mock/resources/root_1", 0.0),
- ("/mock/resources/root_2", 0.0),
- ]
assert fake_pathlock.acquired_tree_paths == ["/mock/resources/root_2"]
- assert summarize_calls[0]["temp_uris"] == ["viking://resources/root_2"]
- assert summarize_calls[0]["target_preexisting"] is False
- assert fake_fs.persist_calls == []
+ fake_pathlock.pathlock_release.assert_awaited_once_with({"id": "lock-1"})
+ rp._commit_directory_artifact_with_plan.assert_not_awaited()
diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.py
index 2e9285ad6..fb2c88b11 100644
--- a/tests/server/test_content_write_service.py
+++ b/tests/server/test_content_write_service.py
@@ -107,156 +107,110 @@ async def test_memory_replace_preserves_metadata(service):
async def test_shared_resource_creation_inherits_acl_and_preserves_plain_append(
service, sample_markdown_file
):
- """New shared content grants creator manage without changing file content."""
- creator = RequestContext(
- user=service.user,
- role=Role.USER,
- group_ids=("writers",),
- )
+ """Shared content inherits permissions without granting its creator extra access."""
+ writer = RequestContext(user=service.user, role=Role.USER, group_ids=("writers",))
admin = RequestContext(user=service.user, role=Role.ADMIN)
reader = RequestContext(
- user=UserIdentifier(admin.account_id, "reader"),
- role=Role.USER,
- group_ids=("readers",),
- )
- outsider = RequestContext(
- user=UserIdentifier(admin.account_id, "outsider"),
- role=Role.USER,
- )
- late_reader = RequestContext(
- user=UserIdentifier(admin.account_id, "late_reader"),
- role=Role.USER,
+ user=UserIdentifier(admin.account_id, "reader"), role=Role.USER, group_ids=("readers",)
)
+ outsider = RequestContext(user=UserIdentifier(admin.account_id, "outsider"), role=Role.USER)
+ public_uri = "viking://resources/public"
parent_uri = "viking://resources/append_plain"
- auto_protected_dir = "viking://resources/auto_protected"
- uri = "viking://resources/append_plain/journal.md"
+ uri = f"{parent_uri}/journal.md"
+ everyone = [{"principal": "user:*", "level": "manage"}]
- await service.runtime_config_manager.patch_account(
- creator.account_id, {"acl": {"enabled": True}}
- )
- await service.fs.mkdir(auto_protected_dir, ctx=creator)
- await service.resources.wait_processed()
- auto_protected_acl = await service.fs.get_acl(auto_protected_dir, ctx=creator)
- creator_entry = {
- "principal": f"user:{creator.user.user_id}",
- "level": "manage",
- }
- assert auto_protected_acl["direct_entries"] == [creator_entry]
-
- await service.viking_fs.mkdir(parent_uri, ctx=admin)
- assert await service.vikingdb_manager.upsert(
- {
- "id": "append-plain-parent",
- "uri": parent_uri,
- "account_id": admin.account_id,
- "context_type": "resource",
- "level": 0,
- "vector": [0.1] * service.vikingdb_manager.vector_dim,
- },
+ # Disabled ACL does not change access, but explicit inherited ACL must survive
+ # writes and retain the fixed root grant when the account enables enforcement.
+ off_file = "viking://resources/created_while_disabled.md"
+ await service.fs.write(
+ off_file,
+ "before",
ctx=admin,
+ wait=True,
+ acl={"entries": [{"principal": "user:reader", "level": "read"}]},
)
- assert (await service.fs.get_acl(parent_uri, ctx=admin))["acl_mode"] == "none"
- parent_acl = await service.fs.set_acl(
- parent_uri,
- [
- {"principal": "group:readers", "level": "read"},
- {"principal": "group:writers", "level": "write"},
- ],
- ctx=admin,
+ await service.fs.write(off_file, "after", ctx=admin, wait=True)
+
+ # Content created with ACL disabled gains default management when enabled.
+ await service.fs.mkdir(public_uri, ctx=writer)
+ await service.resources.wait_processed()
+ with pytest.raises(PermissionDeniedError):
+ await service.fs.get_acl(public_uri, ctx=outsider)
+ await service.runtime_config_manager.patch_account(
+ writer.account_id, {"acl": {"enabled": True}}
)
+ assert (await service.fs.get_acl("viking://resources", ctx=outsider))[
+ "direct_entries"
+ ] == everyone
+ off_acl = await service.fs.get_acl(off_file, ctx=outsider)
+ assert off_acl["direct_entries"] == [{"principal": "user:reader", "level": "read"}]
+ assert off_acl["inherited_entries"] == everyone
+ public_acl = await service.fs.get_acl(public_uri, ctx=outsider)
+ assert public_acl["direct_entries"] == []
+ assert public_acl["inherited_entries"] == everyone
+ with pytest.raises(InvalidArgumentError):
+ await service.fs.set_acl("viking://resources", [], ctx=outsider)
+
+ await service.fs.mkdir(parent_uri, ctx=writer)
+ await service.resources.wait_processed()
+ parent_acl = await service.fs.get_acl(parent_uri, ctx=outsider)
assert parent_acl["acl_mode"] == "inherit"
+ assert parent_acl["direct_entries"] == []
+ assert parent_acl["effective_entries"] == everyone
- await service.fs.write(uri, content="line1\n", ctx=creator, mode="create", wait=True)
inherited_entries = [
{"principal": "group:readers", "level": "read"},
{"principal": "group:writers", "level": "write"},
]
- created_acl = await service.fs.get_acl(uri, ctx=creator)
- assert created_acl["direct_entries"] == [creator_entry]
+ # Any account member can establish a restricted boundary on an open node.
+ parent_acl = await service.fs.set_acl(
+ parent_uri, inherited_entries, acl_mode=AclMode.RESTRICTED, ctx=outsider
+ )
+ assert parent_acl["effective_entries"] == inherited_entries
+
+ await service.fs.write(uri, content="line1\n", ctx=writer, mode="create", wait=True)
+ created_acl = await service.fs.get_acl(uri, ctx=admin)
+ assert created_acl["direct_entries"] == []
assert created_acl["inherited_entries"] == inherited_entries
+ with pytest.raises(PermissionDeniedError):
+ await service.fs.get_acl(uri, ctx=writer)
+ with pytest.raises(PermissionDeniedError):
+ await service.fs.set_acl(uri, [], ctx=writer)
imported = await service.resources.add_resource(
path=str(sample_markdown_file),
parent=parent_uri,
- ctx=creator,
+ ctx=writer,
reason="ACL import",
wait=True,
)
+ # Include ancestor refreshes after the import's own task completes.
+ queue_status = await service.resources.wait_processed()
+ assert queue_status["Embedding"]["error_count"] == 0
import_root = imported["root_uri"]
- imported_acl = await service.fs.get_acl(import_root, ctx=creator)
- assert imported_acl["direct_entries"] == [creator_entry]
- assert imported_acl["inherited_entries"] == inherited_entries
- children = await service.fs.ls(import_root, ctx=creator, simple=True)
- child_acl = await service.fs.get_acl(children[0], ctx=creator)
- 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)
+ children = await service.fs.ls(import_root, ctx=writer, simple=True)
+ for target in [import_root, *children]:
+ acl = await service.fs.get_acl(target, ctx=admin)
+ assert acl["direct_entries"] == []
+ assert acl["inherited_entries"] == inherited_entries
+
+ # An empty restricted ACL remains closed, including its inherit descendants.
+ await service.fs.set_acl(import_root, [], acl_mode=AclMode.RESTRICTED, ctx=admin)
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)
+ for caller in (writer, reader, outsider):
+ with pytest.raises(PermissionDeniedError):
+ await service.viking_fs.read_file(children[0], ctx=caller)
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)
+ assert removed_acl["effective_entries"] == inherited_entries
+ assert await service.fs.ls(import_root, ctx=reader, simple=True) == children
+ await service.fs.write(uri, content="line2\n", ctx=writer, mode="append", wait=True)
+ assert (await service.fs.get_acl(uri, ctx=admin))["direct_entries"] == []
stored = await service.viking_fs.read_file(uri, ctx=reader)
assert stored == "line1\nline2\n"
with pytest.raises(PermissionDeniedError):
@@ -265,18 +219,69 @@ async def test_shared_resource_creation_inherits_acl_and_preserves_plain_append(
await service.viking_fs.read_file(uri, ctx=outsider)
await service.runtime_config_manager.patch_account(
- creator.account_id, {"acl": {"enabled": False}}
+ writer.account_id, {"acl": {"enabled": False}}
)
assert await service.viking_fs.read_file(uri, ctx=outsider) == stored
-
- internal_ctx = RequestContext(
- user=outsider.user,
- role=outsider.role,
- bypass_acl=True,
+ await service.runtime_config_manager.patch_account(
+ writer.account_id, {"acl": {"enabled": True}}
)
- assert await service.viking_fs.read_file(uri, ctx=internal_ctx) == stored
with pytest.raises(PermissionDeniedError):
- await service.fs.get_acl(uri, ctx=internal_ctx)
+ await service.viking_fs.read_file(uri, ctx=outsider)
+
+ # Resuming inheritance restores user:* manage without adding direct grants.
+ restored_acl = await service.fs.delete_acl(parent_uri, ctx=admin)
+ assert restored_acl["effective_entries"] == everyone
+ assert (await service.fs.get_acl(uri, ctx=outsider))["effective_entries"] == everyone
+
+ # Creation ACL shares one contract across directories, files and imports.
+ restricted = {"acl_mode": "restricted", "entries": inherited_entries}
+ explicit_dir = "viking://resources/explicit"
+ await service.fs.mkdir(explicit_dir, ctx=outsider, acl=restricted)
+ await service.resources.wait_processed()
+ assert (await service.fs.get_acl(explicit_dir, ctx=admin))[
+ "effective_entries"
+ ] == inherited_entries
+ with pytest.raises(PermissionDeniedError):
+ await service.fs.write(f"{explicit_dir}/denied.md", "denied", ctx=writer, acl=restricted)
+ assert not await service.viking_fs.exists(f"{explicit_dir}/denied.md", ctx=admin)
+
+ explicit_file = f"{explicit_dir}/explicit.md"
+ await service.fs.write(
+ explicit_file, "first", ctx=admin, mode="create", wait=True, acl=restricted
+ )
+ assert (await service.fs.get_acl(explicit_file, ctx=admin))[
+ "direct_entries"
+ ] == inherited_entries
+ assert (await service.fs.get_acl(explicit_dir, ctx=admin))[
+ "direct_entries"
+ ] == inherited_entries
+ await service.fs.write(
+ explicit_file, "first", ctx=admin, wait=True, acl={"entries": []}
+ )
+ assert (await service.fs.get_acl(explicit_file, ctx=admin))["effective_entries"] == []
+
+ explicit_import = "viking://resources/explicit_import"
+ await service.resources.add_resource(
+ path=str(sample_markdown_file), to=explicit_import, ctx=admin, wait=True, acl=restricted
+ )
+ await service.resources.wait_processed()
+ assert (await service.fs.get_acl(explicit_import, ctx=admin))[
+ "direct_entries"
+ ] == inherited_entries
+ imported_children = await service.fs.ls(explicit_import, ctx=admin, simple=True)
+ for child in imported_children:
+ report = await service.fs.get_acl(child, ctx=admin)
+ assert report["direct_entries"] == []
+ assert report["effective_entries"] == inherited_entries
+ await service.resources.add_resource(
+ path=str(sample_markdown_file),
+ to=explicit_import,
+ ctx=admin,
+ wait=True,
+ acl={"entries": []},
+ )
+ await service.resources.wait_processed()
+ assert (await service.fs.get_acl(explicit_import, ctx=admin))["effective_entries"] == []
@pytest.mark.asyncio
diff --git a/tests/server/test_filesystem_router.py b/tests/server/test_filesystem_router.py
index 8aaf19eca..3f85bdc95 100644
--- a/tests/server/test_filesystem_router.py
+++ b/tests/server/test_filesystem_router.py
@@ -169,7 +169,7 @@ async def test_attrs_returns_memory_fields_and_tags(monkeypatch):
"-->"
)
- async def fake_stat(uri, ctx=None):
+ async def fake_stat(uri, ctx=None, skip_count=False):
return {"isDir": False}
async def fake_read(uri, ctx=None):
diff --git a/tests/service/test_fs_service.py b/tests/service/test_fs_service.py
index 3a73e93c7..83739a82a 100644
--- a/tests/service/test_fs_service.py
+++ b/tests/service/test_fs_service.py
@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock
import pytest
+from openviking.pyagfs.exceptions import AGFSAlreadyExistsError
from openviking.server.identity import RequestContext, Role
from openviking.service.fs_service import FSService
from openviking.storage.abstract_overview import body_for_preview
@@ -103,10 +104,8 @@ class _FakeMutationCoordinator:
class _MkdirPathlockAGFS:
- def __init__(self, owner, *, inject_custom_on_acquire=False):
- self._owner = owner
+ def __init__(self):
self._lock = asyncio.Lock()
- self._inject_custom_on_acquire = inject_custom_on_acquire
self.held = False
self.acquire_count = 0
@@ -116,8 +115,6 @@ class _MkdirPathlockAGFS:
await self._lock.acquire()
self.held = True
self.acquire_count += 1
- if self._inject_custom_on_acquire and self._owner.abstract_content is None:
- self._owner.abstract_content = "custom summary"
return {"lease_ref": f"mkdir-{self.acquire_count}"}
async def pathlock_release(self, _lease):
@@ -126,36 +123,19 @@ class _MkdirPathlockAGFS:
class _MkdirVikingFS:
- def __init__(self, *, inject_custom_on_acquire=False):
+ def __init__(self):
self.directory_exists = False
self.abstract_content = None
- self.abstract_checks = 0
- self.abstract_checks_ready = asyncio.Event()
- self._async_agfs = _MkdirPathlockAGFS(
- self, inject_custom_on_acquire=inject_custom_on_acquire
- )
+ self._async_agfs = _MkdirPathlockAGFS()
def _uri_to_path(self, uri, ctx=None):
del ctx
return f"/local/default/{uri.removeprefix('viking://')}"
- async def exists(self, uri, ctx=None):
- del ctx
- if uri.endswith("/.abstract.md"):
- if self._async_agfs.held:
- return self.abstract_content is not None
- if self._async_agfs._inject_custom_on_acquire:
- self.abstract_content = "custom summary"
- return False
- self.abstract_checks += 1
- if self.abstract_checks == 2:
- self.abstract_checks_ready.set()
- await self.abstract_checks_ready.wait()
- return False
- return self.directory_exists
-
async def mkdir(self, _uri, ctx=None):
del ctx
+ if self.directory_exists:
+ raise AGFSAlreadyExistsError("directory already exists")
self.directory_exists = True
async def write_file(self, _uri, content, ctx=None, lease_ref=None):
@@ -165,26 +145,6 @@ class _MkdirVikingFS:
self.abstract_content = content
-async def test_mkdir_default_does_not_overwrite_concurrent_abstract(monkeypatch, request_context):
- viking_fs = _MkdirVikingFS(inject_custom_on_acquire=True)
- vectorized = []
-
- async def record_vectorization(**kwargs):
- assert viking_fs._async_agfs.held
- vectorized.append(kwargs["abstract"])
-
- monkeypatch.setattr(
- "openviking.service.fs_service.vectorize_directory_meta", record_vectorization
- )
- service = FSService(viking_fs=viking_fs)
-
- await service.mkdir("viking://resources/shared", ctx=request_context)
-
- assert body_for_preview(viking_fs.abstract_content) == "custom summary"
- assert vectorized == []
-
-
@pytest.mark.asyncio
async def test_concurrent_default_mkdir_vectorizes_once(monkeypatch, request_context):
viking_fs = _MkdirVikingFS()
@@ -200,11 +160,15 @@ async def test_concurrent_default_mkdir_vectorizes_once(monkeypatch, request_con
)
service = FSService(viking_fs=viking_fs)
- await asyncio.gather(
+ results = await asyncio.gather(
service.mkdir("viking://resources/shared", ctx=request_context),
service.mkdir("viking://resources/shared", ctx=request_context),
+ return_exceptions=True,
)
+ assert sum(result is None for result in results) == 1
+ assert sum(isinstance(result, AGFSAlreadyExistsError) for result in results) == 1
+
assert body_for_preview(viking_fs.abstract_content) == "# shared"
assert vectorized == ["# shared"]
diff --git a/tests/service/test_resource_service_connector.py b/tests/service/test_resource_service_connector.py
index 9e0812c75..97bd159e7 100644
--- a/tests/service/test_resource_service_connector.py
+++ b/tests/service/test_resource_service_connector.py
@@ -19,8 +19,9 @@ from openviking.resource.watch_scheduler import WatchScheduler
from openviking.server.identity import RequestContext, Role
from openviking.service import resource_service as resource_service_module
from openviking.service.resource_service import ResourceService
+from openviking.storage.acl import AclSpec, AclUpdate
from openviking.storage.queuefs.add_resource_msg import AddResourceMsg, AddResourcePhase
-from openviking_cli.exceptions import ConflictError, InvalidArgumentError
+from openviking_cli.exceptions import ConflictError, InvalidArgumentError, PermissionDeniedError
from openviking_cli.session.user_id import UserIdentifier
# Deterministic stand-in for the code-hosting predicate: routing tests must
@@ -426,14 +427,31 @@ async def test_connector_watch_releases_hold_when_submission_is_cancelled(
service._connector.create_watch_auth_state = AsyncMock(return_value={"provider": "test"})
service._connector.submit = AsyncMock(side_effect=asyncio.CancelledError)
to_uri = "viking://resources/docs"
+ acl = AclSpec(acl_mode="inherit")
+ request = {
+ "path": "tos://bucket/docs/",
+ "ctx": ctx,
+ "to": to_uri,
+ "watch_interval": 5,
+ "acl": acl,
+ }
+ service._viking_fs.prepare_acl_update = AsyncMock(
+ side_effect=[
+ PermissionDeniedError("ACL management denied"),
+ AclUpdate(uri=to_uri, acl=acl),
+ ]
+ )
+
+ with pytest.raises(PermissionDeniedError, match="ACL management denied"):
+ await service.add_resource(**request)
+
+ assert await watch_manager.get_all_tasks("acct", "alice", str(Role.USER)) == []
+ assert scheduler._executing_tasks == set()
+ service._connector.submit.assert_not_awaited()
+ # Once authorized, cancellation after the Watch is created must release its hold.
with pytest.raises(asyncio.CancelledError):
- await service.add_resource(
- path="tos://bucket/docs/",
- ctx=ctx,
- to=to_uri,
- watch_interval=5,
- )
+ await service.add_resource(**request)
task = await watch_manager.get_task_by_uri(
to_uri,
diff --git a/tests/service/test_resource_service_watch.py b/tests/service/test_resource_service_watch.py
index 70471bbe4..03addcfc2 100644
--- a/tests/service/test_resource_service_watch.py
+++ b/tests/service/test_resource_service_watch.py
@@ -303,10 +303,8 @@ class TestWatchTaskCreation:
)
assert "tags_result" not in result
- assert resource_service._resource_processor.calls[-1]["ingest_options"] == IngestOptions(
- search_tags=["team=search"],
- search_tag_mode="append",
- )
+ assert resource_service._resource_processor.calls[-1]["tags"] == ["team=search"]
+ assert resource_service._resource_processor.calls[-1]["tag_mode"] == "append"
@pytest.mark.asyncio
async def test_add_resource_rejects_invalid_tag_mode_before_processing(
@@ -405,19 +403,6 @@ class TestWatchTaskCreation:
search_tag_mode="append",
)
- def test_clear_without_tags_builds_clear_ingest_options(
- self, resource_service: ResourceService
- ):
- assert resource_service._add_resource_ingest_tag_kwargs(
- tags=None,
- tag_mode="clear",
- ) == {
- "ingest_options": IngestOptions(
- search_tags=[],
- search_tag_mode="clear",
- )
- }
-
def test_watch_persists_clear_without_tags(self, resource_service: ResourceService):
assert resource_service._watch_processor_kwargs({}, None, "clear") == {
"tag_mode": "clear"
diff --git a/tests/storage/test_context_update_plan.py b/tests/storage/test_context_update_plan.py
index b8c30eeaf..18cbe2f14 100644
--- a/tests/storage/test_context_update_plan.py
+++ b/tests/storage/test_context_update_plan.py
@@ -2637,6 +2637,7 @@ async def test_resource_processor_dispatches_direct_index_actions_without_semant
"viking://resources/repo/c.py",
ctx=ctx,
file_md5="new-md5",
+ ingest_options=None,
scalar_override={"_record_id": "id-c"},
action="merge",
field_patch=FieldPatch(
@@ -3275,6 +3276,7 @@ async def test_direct_only_plan_skips_semantic_queue(monkeypatch):
async def test_vectors_only_context_plan_does_not_run_legacy_vectorization(monkeypatch):
from openviking.server.identity import RequestContext, Role
from openviking.storage.context_update_plan import ContextUpdatePlan, DirectIndexAction
+ from openviking.utils.ingest_options import IngestOptions
from openviking.utils.resource_processor import ResourceProcessor
from openviking_cli.session.user_id import UserIdentifier
@@ -3308,7 +3310,9 @@ async def test_vectors_only_context_plan_does_not_run_legacy_vectorization(monke
)
processor._enqueue_index_actions.assert_awaited_once_with(
- plan.direct_index_actions, ctx=processor._enqueue_index_actions.await_args.kwargs["ctx"]
+ plan.direct_index_actions,
+ ctx=processor._enqueue_index_actions.await_args.kwargs["ctx"],
+ ingest_options=IngestOptions(),
)
processor._vectorize_prepared_files.assert_not_awaited()
diff --git a/tests/storage/test_semantic_executor_incremental.py b/tests/storage/test_semantic_executor_incremental.py
index 09a9c88a7..84ddb057d 100644
--- a/tests/storage/test_semantic_executor_incremental.py
+++ b/tests/storage/test_semantic_executor_incremental.py
@@ -136,13 +136,11 @@ class _FakeProcessor:
ctx=None,
use_summary=False,
ingest_options=None,
- creator_acl_grant=None,
file_md5=None,
file_content=None,
scalar_override=None,
action="merge",
):
- del creator_acl_grant
self.vectorized_files.append(file_path)
self.file_ingest_options[file_path] = ingest_options
self.file_md5s[file_path] = file_md5
@@ -159,13 +157,11 @@ class _FakeProcessor:
overview,
ctx=None,
ingest_options=None,
- creator_acl_grant=None,
scalar_overrides=None,
actions=None,
include_abstract=True,
include_overview=True,
):
- del creator_acl_grant
self.directory_ingest_options[uri] = ingest_options
self.vectorized_dirs.append(uri)
self.file_contents[("actions", uri)] = actions
diff --git a/tests/storage/test_semantic_executor_skip_files.py b/tests/storage/test_semantic_executor_skip_files.py
index 8632d4d37..7e45944c5 100644
--- a/tests/storage/test_semantic_executor_skip_files.py
+++ b/tests/storage/test_semantic_executor_skip_files.py
@@ -72,7 +72,6 @@ class _FakeProcessor:
overview,
ctx=None,
ingest_options=None,
- creator_acl_grant=None,
):
pass
@@ -88,7 +87,6 @@ class _FakeProcessor:
ctx=None,
use_summary=False,
ingest_options=None,
- creator_acl_grant=None,
file_md5=None,
):
self.vectorized_files.append(file_path)
diff --git a/tests/storage/test_semantic_executor_stats.py b/tests/storage/test_semantic_executor_stats.py
index 9f0cee542..181cb2c16 100644
--- a/tests/storage/test_semantic_executor_stats.py
+++ b/tests/storage/test_semantic_executor_stats.py
@@ -100,7 +100,6 @@ class _FakeProcessor:
overview,
ctx=None,
ingest_options=None,
- creator_acl_grant=None,
):
self.vectorized_dirs.append(uri)
@@ -113,7 +112,6 @@ class _FakeProcessor:
ctx=None,
use_summary=False,
ingest_options=None,
- creator_acl_grant=None,
file_md5=None,
):
if self.verify_streaming:
diff --git a/tests/storage/test_semantic_msg_ingest_options.py b/tests/storage/test_semantic_msg_ingest_options.py
index cb6572c9e..fdf2235e1 100644
--- a/tests/storage/test_semantic_msg_ingest_options.py
+++ b/tests/storage/test_semantic_msg_ingest_options.py
@@ -1,15 +1,21 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+from openviking.storage.acl import AclSpec, AclUpdate
from openviking.storage.queuefs.semantic_msg import SemanticMsg
from openviking.utils.ingest_options import IngestOptions
def test_semantic_msg_serializes_ingest_options():
+ update = AclUpdate(
+ uri="viking://resources/demo", acl=AclSpec(acl_mode="restricted", entries=[])
+ )
msg = SemanticMsg(
uri="viking://resources/demo",
context_type="resource",
- ingest_options=IngestOptions(search_tags=["team=search"], search_tag_mode="append"),
+ ingest_options=IngestOptions(
+ search_tags=["team=search"], search_tag_mode="append", acl_update=update
+ ),
source={"kind": "git", "uri": "https://example.com/acme/demo.git"},
generation_trigger="resource_ingest",
)
@@ -19,11 +25,13 @@ def test_semantic_msg_serializes_ingest_options():
assert data["ingest_options"] == {
"search_tags": ["team=search"],
"search_tag_mode": "append",
+ "acl_update": update.model_dump(mode="json"),
}
- restored = SemanticMsg.from_dict(data)
+ restored = SemanticMsg.from_json(msg.to_json())
assert restored.ingest_options == IngestOptions(
search_tags=["team=search"],
search_tag_mode="append",
+ acl_update=update,
)
assert restored.source == {
"kind": "git",
@@ -126,10 +134,13 @@ def test_semantic_msg_roundtrip_preserves_local_artifact_snapshot():
def test_clear_ingest_options_survive_semantic_message_round_trip():
+ update = AclUpdate(
+ uri="viking://resources/demo", acl=AclSpec(acl_mode="restricted", entries=[])
+ )
msg = SemanticMsg(
uri="viking://resources/demo",
context_type="resource",
- ingest_options=IngestOptions.from_search_tags(None, mode="clear"),
+ ingest_options=IngestOptions(search_tag_mode="clear", acl_update=update),
)
restored = SemanticMsg.from_dict(msg.to_dict())
@@ -137,4 +148,5 @@ def test_clear_ingest_options_survive_semantic_message_round_trip():
assert restored.ingest_options == IngestOptions(
search_tags=[],
search_tag_mode="clear",
+ acl_update=update,
)
diff --git a/tests/storage/test_semantic_processor_target_preexisting.py b/tests/storage/test_semantic_processor_target_preexisting.py
index caf822e0c..32ff9c3eb 100644
--- a/tests/storage/test_semantic_processor_target_preexisting.py
+++ b/tests/storage/test_semantic_processor_target_preexisting.py
@@ -125,7 +125,6 @@ async def test_target_source_syncs_before_semantic_executor(monkeypatch):
uri="viking://temp/import_root/repository",
target_uri="viking://resources/org/repo",
context_type="resource",
- target_preexisting=True,
)
await processor.on_dequeue(msg.to_dict())
diff --git a/tests/storage/test_transfer_merge_binding.py b/tests/storage/test_transfer_merge_binding.py
index ee8b11241..a95df6274 100644
--- a/tests/storage/test_transfer_merge_binding.py
+++ b/tests/storage/test_transfer_merge_binding.py
@@ -359,7 +359,7 @@ async def test_overwrite_preserves_target_acl_with_real_storage(
"level": 2,
"abstract": "old private",
"vector": [0.9, 0.8, 0.7, 0.6],
- "acl_mode": "inherit",
+ "acl_mode": "restricted",
"acl_direct_grants": [f"3:user:{ctx.user.user_id}"],
"acl_inherited_grants": [],
}
@@ -402,7 +402,7 @@ async def test_chunk_only_copy_preserves_private_target_main_record(indexed_fs):
"level": 2,
"abstract": "old",
"vector": [0.1] * 4,
- "acl_mode": "inherit",
+ "acl_mode": "restricted",
"acl_direct_grants": [f"7:user:{ctx.user.user_id}"],
"acl_inherited_grants": [],
}
@@ -483,7 +483,7 @@ async def test_transfer_protects_chunk_shaped_target_file(
"level": 2,
"abstract": "private sibling",
"vector": [0.1] * 4,
- "acl_mode": "inherit",
+ "acl_mode": "restricted",
"acl_direct_grants": [f"7:user:{ctx.user.user_id}"],
"acl_inherited_grants": [],
}
diff --git a/tests/storage/test_vector_transfer.py b/tests/storage/test_vector_transfer.py
index fdb2c47b3..83657828f 100644
--- a/tests/storage/test_vector_transfer.py
+++ b/tests/storage/test_vector_transfer.py
@@ -1372,7 +1372,7 @@ async def test_unindexed_source_preserves_target_records_and_acl(
target,
level=level,
abstract="old abstract",
- acl_mode="inherit" if private else "none",
+ acl_mode="restricted" if private else "none",
acl_direct_grants=["7:user:bob"] if private else [],
acl_inherited_grants=[],
),
@@ -1391,9 +1391,9 @@ async def test_unindexed_source_preserves_target_records_and_acl(
assert backend.acl_manager is not None
effective = await backend.acl_manager.resolve(target, _ctx())
assert effective.context_fields() == {
- "acl_mode": "inherit" if private else "none",
+ "acl_mode": "restricted" if private else "inherit",
"acl_direct_grants": ["7:user:bob"] if private else [],
- "acl_inherited_grants": [],
+ "acl_inherited_grants": [] if private else ["7:user:*"],
}
@@ -1434,10 +1434,19 @@ async def test_copy_directory_preserves_root_acl_and_inherits_it_to_new_entries(
"target-root",
target,
level=0,
- acl_mode="inherit",
+ acl_mode="restricted",
acl_direct_grants=root_acl,
acl_inherited_grants=[],
),
+ # Another index level can still carry an older ACL snapshot.
+ _record(
+ "target-root-l1",
+ target,
+ level=1,
+ acl_mode="restricted",
+ acl_direct_grants=["1:user:carol"],
+ acl_inherited_grants=[],
+ ),
_record(
"unique-target",
unique_target,
diff --git a/tests/storage/test_viking_fs_grep.py b/tests/storage/test_viking_fs_grep.py
index 280aa2944..ef754a367 100644
--- a/tests/storage/test_viking_fs_grep.py
+++ b/tests/storage/test_viking_fs_grep.py
@@ -1224,7 +1224,7 @@ class _RestrictedAclManager:
def __init__(self, effective_by_uri):
self.effective_by_uri = effective_by_uri
- def is_enabled(self, account_id):
+ async def is_enabled(self, account_id):
return True
async def resolve_many(self, uris, ctx):
diff --git a/tests/storage/test_viking_vector_scope_filter.py b/tests/storage/test_viking_vector_scope_filter.py
index 3ae99afca..ea3618875 100644
--- a/tests/storage/test_viking_vector_scope_filter.py
+++ b/tests/storage/test_viking_vector_scope_filter.py
@@ -192,6 +192,13 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(tmp_path, leg
"account_id": "acct",
"context_type": "resource",
},
+ {
+ **legacy_mode,
+ "id": "default-shared",
+ "uri": "viking://resources/default.md",
+ "account_id": "acct",
+ "context_type": "resource",
+ },
{
"id": "direct-shared",
"uri": "viking://resources/direct.md",
@@ -206,7 +213,7 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(tmp_path, leg
"account_id": "acct",
"context_type": "resource",
"acl_mode": "inherit",
- "acl_inherited_grants": ["3:user:*"],
+ "acl_inherited_grants": ["7:user:*"],
},
{
"id": "restricted-inherited-shared",
@@ -214,7 +221,7 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(tmp_path, leg
"account_id": "acct",
"context_type": "resource",
"acl_mode": "restricted",
- "acl_inherited_grants": ["3:user:*"],
+ "acl_inherited_grants": ["7:user:*"],
},
{
"id": "restricted-direct-shared",
@@ -227,11 +234,12 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(tmp_path, leg
},
{
"id": "denied-shared",
- "uri": "viking://resources/denied.md",
+ "uri": "viking://resources/finance/denied.md",
"account_id": "acct",
"context_type": "resource",
"acl_mode": "inherit",
- "acl_direct_grants": ["7:user:bob"],
+ "acl_direct_grants": [],
+ "acl_inherited_grants": ["3:group:finance"],
},
{
"id": "foreign-account",
@@ -283,11 +291,19 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(tmp_path, leg
query_vector=[1.0, 0.0, 0.0, 0.0],
context_type="resource",
)
+ finance = await backend.search_in_tenant(
+ ctx=RequestContext(user=ctx.user, role=ctx.role, group_ids=("finance",)),
+ query_vector=[1.0, 0.0, 0.0, 0.0],
+ context_type="resource",
+ target_directories=["viking://resources/finance"],
+ )
+ assert [record["id"] for record in finance] == ["denied-shared"]
assert sorted(record["id"] for record in visible) == sorted(
[
"own",
"legacy-shared",
+ "default-shared",
"direct-shared",
"inherited-shared",
"restricted-direct-shared",
@@ -299,6 +315,7 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(tmp_path, leg
"own",
"cross-user",
"legacy-shared",
+ "default-shared",
"direct-shared",
"inherited-shared",
"restricted-inherited-shared",
@@ -317,6 +334,7 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(tmp_path, leg
[
"own",
"legacy-shared",
+ "default-shared",
"direct-shared",
"inherited-shared",
"restricted-inherited-shared",
diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.ts
index b723256b1..168da7c37 100644
--- a/web-studio/src/i18n/locales/en/workspace.ts
+++ b/web-studio/src/i18n/locales/en/workspace.ts
@@ -804,9 +804,9 @@ const workspace = {
restoreInheritanceTitle: 'Inherit permissions from the parent again?',
restoreInheritanceWarning:
'Parent directory grants will apply again. Grants added on this directory will remain.',
- disableLimitTitle: 'Turn off restricted access for this directory?',
+ disableLimitTitle: 'Clear direct grants and restore inheritance?',
disableLimitWarning:
- 'Grants added here will be removed and default sharing restored. Separate permissions on child directories remain.',
+ 'Direct grants on this directory will be cleared and parent permissions inherited again. Separate permissions on child directories remain.',
editDirectory: 'Who can access {{directory}}',
whoCanAccess: 'Grant access to these users or groups',
grantScope:
@@ -823,7 +823,7 @@ const workspace = {
title: 'Access permissions',
accountTitle: 'Resource access control · {{account}}',
accountHint:
- 'Account-wide setting for shared resources. Existing resources without ACL remain shared under the original rules.',
+ 'Applies to shared resources in this Account. When disabled, ACL checks are skipped. When enabled, the shared root grants everyone management access. Descendants inherit by default and can restrict access separately.',
enableAction: 'Enable access control',
disableAction: 'Disable access control',
enabled: 'Enabled',
@@ -831,7 +831,7 @@ const workspace = {
enableTitle: 'Enable resource access control?',
disableTitle: 'Disable resource access control?',
enableWarning:
- 'Enable ACL for Account {{account}}? New shared resources grant their creator management access and inherit parent permissions. Existing resources without ACL remain shared; previously configured ACLs take effect again.',
+ 'Enable ACL for Account {{account}}? The shared root always grants everyone management access; these permissions cannot be changed. New resources inherit parent permissions by default, with no extra grants for their creator. Existing ACLs take effect.',
disableWarning:
'Disable ACL for Account {{account}}? All configured resource ACLs stop being enforced. Resources follow the original sharing rules, which may expand access. Stored grants are retained.',
saved: 'Permissions updated',
@@ -847,7 +847,7 @@ const workspace = {
limitWarning:
'This directory will stop inheriting parent grants. Existing direct grants, including Everyone grants, remain active. Review these grants after switching. Account administrators retain access.',
peopleWithAccess: 'People and groups with access',
- defaultRule: 'Shared by default',
+ defaultRule: 'Inherits parent permissions by default',
onlyAdmins: 'No grants yet; account administrators can still access',
directSource: 'Granted here',
inheritedSource: 'From parent',
@@ -887,12 +887,12 @@ const workspace = {
users: 'Go to Users & Permissions',
},
modes: {
- none: 'Shared by default',
+ none: 'Inherited by default',
inherit: 'Inherited permissions',
restricted: 'Custom permissions',
},
modeDescriptions: {
- none: 'This directory follows the default sharing rules. Grants added here apply to descendant directories and files by default.',
+ none: 'No permissions are configured on this directory. It inherits parent permissions by default.',
inherit:
'Parent grants and grants added here both apply, including to descendant directories and files by default. A descendant can stop inheritance.',
restricted:
@@ -908,7 +908,7 @@ const workspace = {
direct: 'Grants added to this directory',
inherited: 'Grants from parent directories',
noDirect:
- 'No grants have been added here. Access may still come from a parent directory or default sharing rules.',
+ 'No direct grants have been added. Users may still have access through parent grants when inheritance is enabled.',
noInherited: 'No inherited grants.',
inheritedHint:
'These grants apply here and to descendant directories and files by default. Edit them in the parent directory.',
@@ -930,7 +930,7 @@ const workspace = {
restoreWarning:
'Parent grants will apply to this directory and its contents again.',
removeWarning:
- 'Remove the direct grant for {{principal}}? Access may remain through ancestors, groups, or the Account-wide grant. Removing the last grant may restore default sharing if inheritance is enabled and no ancestor is controlled.',
+ 'Remove the direct grant for {{principal}}? Access may remain through inherited grants, groups, or an Everyone grant. Removing a grant does not change the inheritance mode.',
subjectType: 'Grant to',
subjects: {
user: 'User',
diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.ts
index 1d5932296..094d71afc 100644
--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts
+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts
@@ -770,9 +770,9 @@ const workspace = {
restoreInheritanceTitle: '恢复继承上级权限?',
restoreInheritanceWarning:
'上级目录的授权将重新生效,本目录已添加的授权会保留。',
- disableLimitTitle: '关闭此目录的限制访问?',
+ disableLimitTitle: '清空直接授权并恢复继承?',
disableLimitWarning:
- '本目录的授权将被清除,目录恢复默认共享;下级目录的独立权限设置会保留。',
+ '将清空本目录的直接授权,并恢复继承父目录权限;下级目录的独立权限设置会保留。',
editDirectory: '谁可以访问 {{directory}}',
whoCanAccess: '授权给以下用户或用户组',
grantScope:
@@ -788,7 +788,7 @@ const workspace = {
title: '访问权限',
accountTitle: '资源访问控制 · {{account}}',
accountHint:
- '作用于当前 Account 的所有共享资源。已有且未配置 ACL 的资源仍按原规则共享。',
+ '作用于当前 Account 的共享资源。关闭时不执行 ACL 鉴权;开启后,共享根目录固定为全员管理,下级默认继承,可单独限制访问。',
enableAction: '启用访问控制',
disableAction: '关闭访问控制',
enabled: '已启用',
@@ -796,7 +796,7 @@ const workspace = {
enableTitle: '启用资源访问控制?',
disableTitle: '关闭资源访问控制?',
enableWarning:
- '为 Account {{account}} 启用 ACL?新建共享资源会给创建者管理权,并继承父目录权限。已有未配置 ACL 的资源仍按原规则共享;此前配置的 ACL 会重新生效。',
+ '为 Account {{account}} 启用 ACL?共享根目录固定授予全员管理权限,且不可修改。新资源默认继承父目录权限,创建者没有额外授权;已有 ACL 将生效。',
disableWarning:
'关闭 Account {{account}} 的 ACL 后,所有资源授权将停止参与鉴权,资源恢复原有共享规则,可能扩大访问范围。已保存的授权不会被删除。',
saved: '权限已更新',
@@ -812,7 +812,7 @@ const workspace = {
limitWarning:
'此目录将停止继承上级授权。已有的直接授权(包括所有人授权)仍然生效,请在切换后检查这些授权。账号管理员仍可访问。',
peopleWithAccess: '有权限的用户和用户组',
- defaultRule: '默认共享',
+ defaultRule: '默认继承上级权限',
onlyAdmins: '暂无授权对象,仅账号管理员可访问',
directSource: '本目录授权',
inheritedSource: '上级目录授权',
@@ -847,12 +847,12 @@ const workspace = {
users: '前往用户与权限',
},
modes: {
- none: '默认共享',
+ none: '默认继承',
inherit: '继承上级权限',
restricted: '自定义权限',
},
modeDescriptions: {
- none: '当前目录沿用默认共享规则。在这里添加的授权默认适用于下级目录和文件。',
+ none: '当前目录未单独配置权限,默认继承父目录权限。',
inherit:
'上级授权和本目录授权共同生效,并默认适用于下级目录和文件;下级节点可以单独关闭继承。',
restricted:
@@ -867,8 +867,7 @@ const workspace = {
'查看:读取、浏览、检索。编辑:创建、修改、删除或移动文件。管理:调整授权、删除或移动目录;目录操作还会检查整个子树。',
direct: '本目录添加的授权',
inherited: '来自上级目录的授权',
- noDirect:
- '还没有为本目录单独授权。用户仍可能通过上级目录或默认共享规则访问。',
+ noDirect: '未添加直接授权。继承已开启时,用户仍可通过父目录授权访问。',
noInherited: '没有继承授权。',
inheritedHint:
'这些授权在当前目录生效,并默认适用于下级目录和文件;如需修改,请到上级目录操作。',
@@ -887,7 +886,7 @@ const workspace = {
'当前目录及下级内容将不再使用上级授权。只有本目录授权对象和账号管理员可以访问。',
restoreWarning: '上级目录的授权将重新作用于当前目录及下级内容。',
removeWarning:
- '移除 {{principal}} 的直接授权?该用户或组仍可能通过继承、组成员关系或全体用户授权访问。若继承已开启且上级未受控,移除最后一条授权可能恢复默认共享。',
+ '移除 {{principal}} 的直接授权?继承、用户组或全体用户授权仍可能允许访问。移除授权不会改变继承模式。',
subjectType: '授权对象类型',
subjects: {
user: '用户',
diff --git a/web-studio/src/routes/permissions/-components/permissions-page.tsx b/web-studio/src/routes/permissions/-components/permissions-page.tsx
index a7fba53af..5bfe71d57 100644
--- a/web-studio/src/routes/permissions/-components/permissions-page.tsx
+++ b/web-studio/src/routes/permissions/-components/permissions-page.tsx
@@ -452,7 +452,7 @@ function DirectoryRow({
<TableCell className="text-center">
{report.isSuccess ? (
<Switch
- checked={parentControlled ? restricted : hasAcl}
+ checked={restricted}
disabled={!writable || update.isPending}
aria-label={t('acl.page.limitFor', { directory: name })}
onCheckedChange={setNext}
diff --git a/web-studio/src/routes/permissions/route.test.tsx b/web-studio/src/routes/permissions/route.test.tsx
index aca1b2fa0..e10d87664 100644
--- a/web-studio/src/routes/permissions/route.test.tsx
+++ b/web-studio/src/routes/permissions/route.test.tsx
@@ -78,7 +78,7 @@ beforeEach(() => {
}))
mocks.change.mockReset()
mocks.change.mockImplementation(async (uri, change) => {
- mocks.modes[uri] = change.kind === 'reset' ? 'none' : change.mode
+ mocks.modes[uri] = change.kind === 'reset' ? 'inherit' : change.mode
return mocks.get(uri)
})
mocks.list.mockImplementation(async (uri: string) => ({
@@ -247,25 +247,45 @@ it('enables permission management only after restricted access is switched on',
)
await waitFor(() => expect(manager.hasAttribute('disabled')).toBe(false))
})
-it('turns off an independent restriction and disables its management action', async () => {
+it('toggles a root child restriction independently of inherited grants', async () => {
+ mocks.get.mockImplementation(async (uri: string) => {
+ const mode = mocks.modes[uri] ?? 'inherit'
+ const inherited = [{ principal: 'user:*', level: 'manage' }]
+ return {
+ uri,
+ acl_mode: mode,
+ direct_entries: [],
+ inherited_entries: inherited,
+ effective_entries: mode === 'restricted' ? [] : inherited,
+ }
+ })
const { user } = mount()
const row = (await screen.findByRole('button', { name: 'im' })).closest('tr')!
- await user.click(await within(row).findByRole('switch'))
+ const toggle = await within(row).findByRole('switch')
+ expect(toggle.getAttribute('aria-checked')).toBe('false')
+ await user.click(toggle)
await user.click(
within(screen.getByRole('alertdialog')).getByRole('button', {
name: 'acl.confirm',
}),
)
- await waitFor(() =>
- expect(mocks.change).toHaveBeenCalledWith(`${root}im/`, { kind: 'reset' }),
+ await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('true'))
+ expect(mocks.change).toHaveBeenCalledWith(`${root}im/`, {
+ kind: 'mode',
+ mode: 'restricted',
+ })
+ await user.click(toggle)
+ expect(screen.getByText('acl.page.disableLimitWarning')).toBeTruthy()
+ await user.click(
+ within(screen.getByRole('alertdialog')).getByRole('button', {
+ name: 'acl.confirm',
+ }),
)
await waitFor(() =>
- expect(
- within(row)
- .getByRole('button', { name: 'acl.page.manageAction' })
- .hasAttribute('disabled'),
- ).toBe(true),
+ expect(mocks.change).toHaveBeenCalledWith(`${root}im/`, { kind: 'reset' }),
)
+ await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('false'))
+ expect(within(row).getByText('acl.modes.inherit')).toBeTruthy()
})
it('lets a child stop and restore inheritance without clearing its grants', async () => {
const { user } = mount()