Skip to content

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

fix(api): tighten public URI validation (#1750)

Qin Haojie190494aa59c6
diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.md
index c5473444c..0e0365ac9 100644
--- a/docs/en/api/03-filesystem.md
+++ b/docs/en/api/03-filesystem.md
@@ -130,6 +130,11 @@ Read L2 full content.
| offset | int | No | 0 | Starting line number (0-indexed) |
| limit | int | No | -1 | Number of lines to read, `-1` means read to end |
+**Notes**
+
+- `read()` accepts file URIs only. Passing an existing directory URI returns `INVALID_ARGUMENT` (`400`), not `NOT_FOUND`.
+- Public URI parameters accept `resources`, `user`, `agent`, and `session` scopes. Internal scopes such as `temp` and `queue` return `INVALID_URI`.
+
**Python SDK (Embedded / HTTP)**
```python
@@ -527,6 +532,9 @@ openviking mkdir viking://resources/new-project/ --description "API docs directo
Remove file or directory.
+`rm` is idempotent: removing a valid URI that does not exist still succeeds.
+Invalid URI formats, unsupported schemes, and non-public scopes return `INVALID_URI`.
+
**Parameters**
| Parameter | Type | Required | Default | Description |
diff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.md
index acb3ad603..870b9d322 100644
--- a/docs/en/concepts/04-viking-uri.md
+++ b/docs/en/concepts/04-viking-uri.md
@@ -9,7 +9,7 @@ viking://{scope}/{path}
```
- **scheme**: Always `viking`
-- **scope**: Top-level namespace (resources, user, agent, session, queue)
+- **scope**: Top-level namespace (`resources`, `user`, `agent`, `session`; `temp` and `queue` are internal)
- **path**: Resource path within the scope
## Scopes
@@ -23,6 +23,11 @@ viking://{scope}/{path}
| **queue** | Processing queue | Temporary | Internal |
| **temp** | Temporary files | During parsing | Internal |
+Public API and CLI filesystem/content operations accept only the public scopes:
+`resources`, `user`, `agent`, and `session` (plus the root URI `viking://`).
+`temp` and `queue` are internal implementation scopes and cannot be addressed
+directly through public API URI parameters.
+
## Initial Directory Structure
Moving away from traditional flat database thinking, all context is organized as a filesystem. Agents no longer just find data through vector search, but can locate and browse data through deterministic paths and standard filesystem commands. Each context or directory is assigned a unique URI identifier string in the format viking://{scope}/{path}, allowing the system to precisely locate and access resources stored in different locations.
diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.md
index 38a29e58c..ca81716b8 100644
--- a/docs/zh/api/03-filesystem.md
+++ b/docs/zh/api/03-filesystem.md
@@ -130,6 +130,11 @@ openviking overview viking://resources/docs/
| offset | int | 否 | 0 | 起始行号(0 开始) |
| limit | int | 否 | -1 | 读取的行数,`-1` 表示读到结尾 |
+**说明**
+
+- `read()` 只接受文件 URI。传入已存在的目录 URI 时返回 `INVALID_ARGUMENT`(`400`),而不是 `NOT_FOUND`。
+- 公开 URI 参数只接受 `resources`、`user`、`agent`、`session` 作用域。`temp`、`queue` 等内部作用域会返回 `INVALID_URI`。
+
**Python SDK (Embedded / HTTP)**
```python
@@ -527,6 +532,9 @@ openviking mkdir viking://resources/new-project/ --description "接口文档目
删除文件或目录。
+`rm` 是幂等操作:删除一个合法但不存在的 URI 仍会成功。
+URI 格式非法、scheme 不支持或使用非公开作用域时返回 `INVALID_URI`。
+
**参数**
| 参数 | 类型 | 必填 | 默认值 | 说明 |
diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.md
index c00f79a11..4d29781f0 100644
--- a/docs/zh/concepts/04-viking-uri.md
+++ b/docs/zh/concepts/04-viking-uri.md
@@ -9,7 +9,7 @@ viking://{scope}/{path}
```
- **scheme**: 始终为 `viking`
-- **scope**: 顶级命名空间(resources、user、agent、session、queue)
+- **scope**: 顶级命名空间(`resources`、`user`、`agent`、`session`;`temp` 和 `queue` 为内部作用域)
- **path**: 作用域内的资源路径
## 作用域
@@ -23,6 +23,10 @@ viking://{scope}/{path}
| **queue** | 处理队列 | 临时 | 内部 |
| **temp** | 临时文件 | 解析期间 | 内部 |
+公开 API 和 CLI 的文件系统/内容操作只接受公开作用域:
+`resources`、`user`、`agent`、`session`,以及根 URI `viking://`。
+`temp` 和 `queue` 是内部实现作用域,不能通过公开 API 的 URI 参数直接访问。
+
## 初始目录
摒弃传统的扁平化数据库思维,将所有上下文组织为一套文件系统。Agent 不再仅是通过向量搜索来找数据,而是可以通过确定性的路径和标准文件系统指令来定位和浏览数据。每个上下文或目录分配唯一的 URI 标识字符串,格式为 viking://{scope}/{path},让系统能精准定位并访问存储在不同位置的资源。
diff --git a/openviking/core/uri_validation.py b/openviking/core/uri_validation.py
new file mode 100644
index 000000000..cfdfb678b
--- /dev/null
+++ b/openviking/core/uri_validation.py
@@ -0,0 +1,109 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Validation helpers for externally supplied Viking URI fields."""
+
+import re
+from collections.abc import Collection
+
+from openviking_cli.exceptions import InvalidURIError
+from openviking_cli.utils.uri import VikingURI
+
+_URI_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
+_PUBLIC_API_SCOPES = frozenset({"", *VikingURI.PUBLIC_SCOPES})
+_ALL_API_SCOPES = frozenset({"", *VikingURI.VISITABLE_SCOPES})
+
+
+def _scope_from_uri(uri: str) -> str:
+ normalized = uri if uri.startswith(f"{VikingURI.SCHEME}://") else VikingURI.normalize(uri)
+ path = normalized[len(f"{VikingURI.SCHEME}://") :]
+ if not path.strip("/"):
+ return ""
+ return path.split("/")[0]
+
+
+def _format_scope_names(scopes: Collection[str]) -> str:
+ return ", ".join(sorted(scope for scope in scopes if scope))
+
+
+def _scope_set(
+ *,
+ allow_internal: bool,
+ allowed_scopes: Collection[str] | str | None,
+) -> frozenset[str]:
+ if allowed_scopes is not None:
+ if isinstance(allowed_scopes, str):
+ return frozenset({allowed_scopes})
+ return frozenset(allowed_scopes)
+ return _ALL_API_SCOPES if allow_internal else _PUBLIC_API_SCOPES
+
+
+def _invalid_scope_reason(scope: str, allowed_scopes: Collection[str]) -> str:
+ scope_names = _format_scope_names(allowed_scopes)
+ if not scope:
+ return f"URI must include one of: {scope_names}"
+ return f"Invalid scope '{scope}'. Must be one of: {scope_names}"
+
+
+def validate_viking_uri(
+ uri: str,
+ *,
+ field_name: str = "uri",
+ allow_internal: bool = False,
+ allowed_scopes: Collection[str] | str | None = None,
+) -> str:
+ """Validate a user-supplied Viking URI or supported short-format URI.
+
+ Short formats such as ``resources/docs`` are allowed for existing CLI/API
+ compatibility. Explicit non-viking schemes such as ``s3://`` or malformed
+ viking schemes such as ``viking:/`` are rejected as INVALID_URI. Internal
+ scopes such as ``temp`` and ``queue`` are rejected by default at the API
+ boundary unless ``allow_internal`` or an explicit ``allowed_scopes`` is used.
+ """
+ raw_uri = uri.strip() if isinstance(uri, str) else ""
+ if not raw_uri:
+ raise InvalidURIError(str(uri), f"{field_name} must not be empty")
+
+ scheme_match = _URI_SCHEME_RE.match(raw_uri)
+ if scheme_match and not raw_uri.startswith(f"{VikingURI.SCHEME}://"):
+ scheme = scheme_match.group(0)[:-1]
+ if scheme == VikingURI.SCHEME:
+ reason = f"URI must start with '{VikingURI.SCHEME}://'"
+ else:
+ reason = f"unsupported URI scheme '{scheme}'"
+ raise InvalidURIError(raw_uri, reason)
+
+ scopes = _scope_set(allow_internal=allow_internal, allowed_scopes=allowed_scopes)
+
+ try:
+ parsed = VikingURI(raw_uri)
+ except ValueError as exc:
+ reason = str(exc)
+ if reason.startswith("Invalid scope"):
+ reason = _invalid_scope_reason(_scope_from_uri(raw_uri), scopes)
+ raise InvalidURIError(raw_uri, reason) from exc
+
+ if parsed.scope not in scopes:
+ raise InvalidURIError(raw_uri, _invalid_scope_reason(parsed.scope, scopes))
+
+ return raw_uri
+
+
+def validate_optional_viking_uri(
+ uri: str | None,
+ *,
+ field_name: str = "uri",
+ allow_internal: bool = False,
+ allowed_scopes: Collection[str] | str | None = None,
+) -> str:
+ """Validate an optional Viking URI field, preserving empty-as-unspecified."""
+ if uri is None:
+ return ""
+ raw_uri = uri.strip() if isinstance(uri, str) else ""
+ if not raw_uri:
+ return ""
+ return validate_viking_uri(
+ raw_uri,
+ field_name=field_name,
+ allow_internal=allow_internal,
+ allowed_scopes=allowed_scopes,
+ )
diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.py
index 1512a1807..5bc35a5ce 100644
--- a/openviking/server/routers/content.py
+++ b/openviking/server/routers/content.py
@@ -9,6 +9,7 @@ from fastapi import APIRouter, Body, Depends, Query
from fastapi.responses import Response as FastAPIResponse
from pydantic import BaseModel, ConfigDict
+from openviking.core.uri_validation import validate_viking_uri
from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
from openviking.server.auth import get_request_context, require_role
from openviking.server.dependencies import get_service
@@ -190,7 +191,7 @@ async def reindex(
from openviking.service.task_tracker import get_task_tracker
from openviking.storage.viking_fs import get_viking_fs
- uri = body.uri
+ uri = validate_viking_uri(body.uri)
viking_fs = get_viking_fs()
if not await viking_fs.exists(uri, ctx=ctx):
diff --git a/openviking/server/routers/maintenance.py b/openviking/server/routers/maintenance.py
index 24a6330ad..b9477c2e6 100644
--- a/openviking/server/routers/maintenance.py
+++ b/openviking/server/routers/maintenance.py
@@ -7,6 +7,7 @@ import asyncio
from fastapi import APIRouter, Body
from pydantic import BaseModel
+from openviking.core.uri_validation import validate_viking_uri
from openviking.server.auth import require_role
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext, Role
@@ -47,7 +48,7 @@ async def reindex(
from openviking.service.task_tracker import get_task_tracker
from openviking.storage.viking_fs import get_viking_fs
- uri = body.uri
+ uri = validate_viking_uri(body.uri)
viking_fs = get_viking_fs()
# Validate URI exists
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 026176c14..cb2ef9eeb 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -9,6 +9,7 @@ Provides file system operations: ls, mkdir, rm, mv, tree, stat, read, abstract,
from typing import Any, Dict, List, Optional
from openviking.core.directories import get_context_type_for_uri
+from openviking.core.uri_validation import validate_optional_viking_uri, validate_viking_uri
from openviking.server.identity import RequestContext
from openviking.storage.content_write import ContentWriteCoordinator
from openviking.storage.viking_fs import VikingFS
@@ -59,6 +60,7 @@ class FSService:
node_limit: int = 1000 (maximum number of nodes to list)
"""
viking_fs = self._ensure_initialized()
+ uri = validate_viking_uri(uri)
if simple:
# Only return URIs — skip expensive abstract fetching to save tokens
@@ -109,6 +111,7 @@ class FSService:
description: Optional[str] = None,
) -> None:
"""Create directory."""
+ uri = validate_viking_uri(uri)
viking_fs = self._ensure_initialized()
await viking_fs.mkdir(uri, ctx=ctx)
abstract = self._normalize_directory_description(description)
@@ -141,11 +144,14 @@ class FSService:
async def rm(self, uri: str, ctx: RequestContext, recursive: bool = False) -> None:
"""Remove resource."""
+ uri = validate_viking_uri(uri)
viking_fs = self._ensure_initialized()
await viking_fs.rm(uri, recursive=recursive, ctx=ctx)
async def mv(self, from_uri: str, to_uri: str, ctx: RequestContext) -> None:
"""Move resource."""
+ from_uri = validate_viking_uri(from_uri, field_name="from_uri")
+ to_uri = validate_viking_uri(to_uri, field_name="to_uri")
viking_fs = self._ensure_initialized()
await viking_fs.mv(from_uri, to_uri, ctx=ctx)
@@ -161,6 +167,7 @@ class FSService:
) -> List[Dict[str, Any]]:
"""Get directory tree."""
viking_fs = self._ensure_initialized()
+ uri = validate_viking_uri(uri)
return await viking_fs.tree(
uri,
ctx=ctx,
@@ -174,21 +181,25 @@ class FSService:
async def stat(self, uri: str, ctx: RequestContext) -> Dict[str, Any]:
"""Get resource status."""
viking_fs = self._ensure_initialized()
+ uri = validate_viking_uri(uri)
return await viking_fs.stat(uri, ctx=ctx)
async def read(self, uri: str, ctx: RequestContext, offset: int = 0, limit: int = -1) -> str:
"""Read file content."""
viking_fs = self._ensure_initialized()
+ uri = validate_viking_uri(uri)
return await viking_fs.read_file(uri, offset=offset, limit=limit, ctx=ctx)
async def abstract(self, uri: str, ctx: RequestContext) -> str:
"""Read L0 abstract (.abstract.md)."""
viking_fs = self._ensure_initialized()
+ uri = validate_viking_uri(uri)
return await viking_fs.abstract(uri, ctx=ctx)
async def overview(self, uri: str, ctx: RequestContext) -> str:
"""Read L1 overview (.overview.md)."""
viking_fs = self._ensure_initialized()
+ uri = validate_viking_uri(uri)
return await viking_fs.overview(uri, ctx=ctx)
async def grep(
@@ -203,6 +214,8 @@ class FSService:
) -> Dict:
"""Content search."""
viking_fs = self._ensure_initialized()
+ uri = validate_viking_uri(uri)
+ exclude_uri = validate_optional_viking_uri(exclude_uri, field_name="exclude_uri") or None
return await viking_fs.grep(
uri,
pattern,
@@ -222,11 +235,13 @@ class FSService:
) -> Dict:
"""File pattern matching."""
viking_fs = self._ensure_initialized()
+ uri = validate_viking_uri(uri)
return await viking_fs.glob(pattern, uri=uri, node_limit=node_limit, ctx=ctx)
async def read_file_bytes(self, uri: str, ctx: RequestContext) -> bytes:
"""Read file as raw bytes."""
viking_fs = self._ensure_initialized()
+ uri = validate_viking_uri(uri)
return await viking_fs.read_file_bytes(uri, ctx=ctx)
async def write(
@@ -239,6 +254,7 @@ class FSService:
timeout: Optional[float] = None,
) -> Dict[str, Any]:
"""Write to an existing file and refresh semantics/vectors."""
+ uri = validate_viking_uri(uri)
viking_fs = self._ensure_initialized()
coordinator = ContentWriteCoordinator(viking_fs=viking_fs)
return await coordinator.write(
diff --git a/openviking/service/pack_service.py b/openviking/service/pack_service.py
index 014d2ecac..40969b117 100644
--- a/openviking/service/pack_service.py
+++ b/openviking/service/pack_service.py
@@ -8,6 +8,7 @@ Provides ovpack export/import operations.
from typing import Optional
+from openviking.core.uri_validation import validate_viking_uri
from openviking.server.identity import RequestContext
from openviking.storage.local_fs import export_ovpack as local_export_ovpack
from openviking.storage.local_fs import import_ovpack as local_import_ovpack
@@ -45,6 +46,7 @@ class PackService:
Exported file path
"""
viking_fs = self._ensure_initialized()
+ uri = validate_viking_uri(uri)
return await local_export_ovpack(viking_fs, uri, to, ctx=ctx)
async def import_ovpack(
@@ -67,6 +69,7 @@ class PackService:
Imported root resource URI
"""
viking_fs = self._ensure_initialized()
+ parent = validate_viking_uri(parent, field_name="parent")
return await local_import_ovpack(
viking_fs, file_path, parent, force=force, vectorize=vectorize, ctx=ctx
)
diff --git a/openviking/service/relation_service.py b/openviking/service/relation_service.py
index 91b1ff949..5e8b132b1 100644
--- a/openviking/service/relation_service.py
+++ b/openviking/service/relation_service.py
@@ -8,6 +8,7 @@ Provides relation management operations: relations, link, unlink.
from typing import Any, Dict, List, Optional, Union
+from openviking.core.uri_validation import validate_viking_uri
from openviking.server.identity import RequestContext
from openviking.storage.viking_fs import VikingFS
from openviking_cli.exceptions import NotInitializedError
@@ -35,6 +36,7 @@ class RelationService:
async def relations(self, uri: str, ctx: RequestContext) -> List[Dict[str, Any]]:
"""Get relations (returns [{"uri": "...", "reason": "..."}, ...])."""
viking_fs = self._ensure_initialized()
+ uri = validate_viking_uri(uri)
return await viking_fs.relations(uri, ctx=ctx)
async def link(
@@ -52,6 +54,11 @@ class RelationService:
reason: Reason for linking
"""
viking_fs = self._ensure_initialized()
+ from_uri = validate_viking_uri(from_uri, field_name="from_uri")
+ if isinstance(uris, list):
+ uris = [validate_viking_uri(uri, field_name="to_uris") for uri in uris]
+ else:
+ uris = validate_viking_uri(uris, field_name="to_uris")
await viking_fs.link(from_uri, uris, reason, ctx=ctx)
async def unlink(self, from_uri: str, uri: str, ctx: RequestContext) -> None:
@@ -62,4 +69,6 @@ class RelationService:
uri: Target URI to remove
"""
viking_fs = self._ensure_initialized()
+ from_uri = validate_viking_uri(from_uri, field_name="from_uri")
+ uri = validate_viking_uri(uri, field_name="to_uri")
await viking_fs.unlink(from_uri, uri, ctx=ctx)
diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.py
index f673effb9..7447c8f56 100644
--- a/openviking/service/resource_service.py
+++ b/openviking/service/resource_service.py
@@ -10,6 +10,7 @@ import json
import time
from typing import TYPE_CHECKING, Any, Dict, List, Optional
+from openviking.core.uri_validation import validate_optional_viking_uri
from openviking.server.identity import RequestContext
from openviking.server.local_input_guard import (
is_remote_resource_source,
@@ -36,7 +37,6 @@ from openviking_cli.exceptions import (
NotInitializedError,
)
from openviking_cli.utils import get_logger
-from openviking_cli.utils.uri import VikingURI
if TYPE_CHECKING:
from openviking.resource.watch_manager import WatchManager
@@ -173,19 +173,16 @@ class ResourceService:
telemetry.set("resource.flags.watch_enabled", watch_enabled)
try:
- # add_resource only supports resources scope
- if to and to.startswith("viking://"):
- parsed = VikingURI(to)
- if parsed.scope != "resources":
- raise InvalidArgumentError(
- f"add_resource only supports resources scope, use dedicated interface to add {parsed.scope} content"
- )
- if parent and parent.startswith("viking://"):
- parsed = VikingURI(parent)
- if parsed.scope != "resources":
- raise InvalidArgumentError(
- f"add_resource only supports resources scope, use dedicated interface to add {parsed.scope} content"
- )
+ to = validate_optional_viking_uri(
+ to,
+ field_name="to",
+ allowed_scopes={"resources"},
+ )
+ parent = validate_optional_viking_uri(
+ parent,
+ field_name="parent",
+ allowed_scopes={"resources"},
+ )
if watch_manager and not skip_watch_management and watch_interval > 0 and not to:
raise InvalidArgumentError(
"watch_interval > 0 requires 'to' to be specified (target URI to watch)"
diff --git a/openviking/service/search_service.py b/openviking/service/search_service.py
index 36379b5fc..a793389ad 100644
--- a/openviking/service/search_service.py
+++ b/openviking/service/search_service.py
@@ -8,6 +8,7 @@ Provides semantic search operations: search, find.
from typing import TYPE_CHECKING, Any, Dict, Optional
+from openviking.core.uri_validation import validate_optional_viking_uri
from openviking.server.identity import RequestContext
from openviking.storage.viking_fs import VikingFS
from openviking_cli.exceptions import InvalidArgumentError, NotInitializedError
@@ -64,6 +65,7 @@ class SearchService:
FindResult
"""
_ensure_non_empty_query(query)
+ target_uri = validate_optional_viking_uri(target_uri, field_name="target_uri")
viking_fs = self._ensure_initialized()
session_info = None
@@ -103,6 +105,7 @@ class SearchService:
FindResult
"""
_ensure_non_empty_query(query)
+ target_uri = validate_optional_viking_uri(target_uri, field_name="target_uri")
viking_fs = self._ensure_initialized()
result = await viking_fs.find(
query=query,
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index b41c92902..934891798 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -1783,9 +1783,14 @@ class VikingFS:
# Verify the file exists before reading, because AGFS read returns
# empty bytes for non-existent files instead of raising an error.
try:
- self.agfs.stat(path)
+ stat = self.agfs.stat(path)
except Exception:
raise NotFoundError(uri, "file")
+ if isinstance(stat, dict) and stat.get("isDir", False):
+ raise InvalidArgumentError(
+ f"Cannot read directory as file: {uri}",
+ details={"resource": uri, "expected": "file", "actual": "directory"},
+ )
try:
content = self.agfs.read(path)
if isinstance(content, bytes):
@@ -1817,6 +1822,15 @@ class VikingFS:
"""Read single binary file."""
self._ensure_access(uri, ctx)
path = self._uri_to_path(uri, ctx=ctx)
+ try:
+ stat = self.agfs.stat(path)
+ except Exception:
+ raise NotFoundError(uri, "file")
+ if isinstance(stat, dict) and stat.get("isDir", False):
+ raise InvalidArgumentError(
+ f"Cannot read directory as file: {uri}",
+ details={"resource": uri, "expected": "file", "actual": "directory"},
+ )
try:
raw = self._handle_agfs_read(self.agfs.read(path))
raw = await self._decrypt_content(raw, ctx=ctx)
diff --git a/openviking_cli/utils/uri.py b/openviking_cli/utils/uri.py
index 9d5cef91e..7d2f65c91 100644
--- a/openviking_cli/utils/uri.py
+++ b/openviking_cli/utils/uri.py
@@ -39,8 +39,11 @@ class VikingURI:
"agent",
"session",
}
- # All valid scopes that can be visited/accessed
- VISITABLE_SCOPES = LISTABLE_SCOPES | {"temp", "queue"}
+ PUBLIC_SCOPES = frozenset(LISTABLE_SCOPES)
+ INTERNAL_SCOPES = frozenset({"temp", "queue"})
+ # All valid scopes that can be addressed by the URI parser/storage internals.
+ # Public API handlers must not use this as their external whitelist.
+ VISITABLE_SCOPES = PUBLIC_SCOPES | INTERNAL_SCOPES
def __init__(self, uri: str):
"""
@@ -79,7 +82,7 @@ class VikingURI:
# Parse scope
scope = path.split("/")[0]
if scope not in self.VISITABLE_SCOPES:
- raise ValueError(f"Invalid scope '{scope}'. Must be one of {self.VISITABLE_SCOPES}")
+ raise ValueError(f"Invalid scope '{scope}'")
return {
"scheme": self.SCHEME,
@@ -193,9 +196,7 @@ class VikingURI:
Viking URI string
"""
if scope not in VikingURI.VISITABLE_SCOPES:
- raise ValueError(
- f"Invalid scope '{scope}'. Must be one of {VikingURI.VISITABLE_SCOPES}"
- )
+ raise ValueError(f"Invalid scope '{scope}'")
parts = [scope] + list(path_parts)
# Filter out empty parts
diff --git a/tests/server/test_api_content.py b/tests/server/test_api_content.py
index 2228e17c9..b2d97de4e 100644
--- a/tests/server/test_api_content.py
+++ b/tests/server/test_api_content.py
@@ -34,6 +34,30 @@ async def test_read_content(client_with_resource):
assert body["result"] is not None
+async def test_read_directory_uri_returns_invalid_argument(client_with_resource):
+ client, uri = client_with_resource
+
+ resp = await client.get("/api/v1/content/read", params={"uri": uri})
+
+ assert resp.status_code == 400
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "INVALID_ARGUMENT"
+ assert "Cannot read directory as file" in body["error"]["message"]
+
+
[email protected]("uri", ["viking://temp/generated", "viking://queue/tasks"])
+async def test_read_internal_scope_uri_returns_invalid_uri(client, uri: str):
+ resp = await client.get("/api/v1/content/read", params={"uri": uri})
+
+ assert resp.status_code == 400
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "INVALID_URI"
+ assert "Must be one of" in body["error"]["message"]
+ assert "frozenset" not in body["error"]["message"]
+
+
async def test_abstract_content(client_with_resource):
client, uri = client_with_resource
resp = await client.get("/api/v1/content/abstract", params={"uri": uri})
diff --git a/tests/server/test_api_filesystem.py b/tests/server/test_api_filesystem.py
index 88d653fd9..de98979c4 100644
--- a/tests/server/test_api_filesystem.py
+++ b/tests/server/test_api_filesystem.py
@@ -109,7 +109,7 @@ async def test_tree(client: httpx.AsyncClient):
async def test_stat_not_found(client: httpx.AsyncClient):
resp = await client.get(
"/api/v1/fs/stat",
- params={"uri": "viking://nonexistent/xyz"},
+ params={"uri": "viking://resources/nonexistent/xyz"},
)
assert resp.status_code == 404
body = resp.json()
@@ -134,6 +134,49 @@ async def test_rm_directory_without_recursive_returns_failed_precondition(
assert body["error"]["code"] == "FAILED_PRECONDITION"
+async def test_rm_missing_uri_is_idempotent(client: httpx.AsyncClient):
+ missing_uri = "viking://resources/definitely-missing-rm-target"
+
+ resp = await client.request(
+ "DELETE",
+ "/api/v1/fs",
+ params={"uri": missing_uri, "recursive": True},
+ )
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ assert body["result"] == {"uri": missing_uri}
+
+
+async def test_rm_unsupported_scheme_returns_invalid_uri(client: httpx.AsyncClient):
+ resp = await client.request(
+ "DELETE",
+ "/api/v1/fs",
+ params={"uri": "s3://bucket/missing", "recursive": True},
+ )
+
+ assert resp.status_code == 400
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "INVALID_URI"
+ assert "unsupported URI scheme 's3'" in body["error"]["message"]
+
+
+async def test_ls_invalid_scope_hides_internal_scopes(client: httpx.AsyncClient):
+ resp = await client.get("/api/v1/fs/ls", params={"uri": "ssd"})
+
+ assert resp.status_code == 400
+ body = resp.json()
+ message = body["error"]["message"]
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "INVALID_URI"
+ assert "resources" in message
+ assert "temp" not in message
+ assert "queue" not in message
+ assert "frozenset" not in message
+
+
async def test_resource_ops(client_with_resource):
"""Test stat, ls_recursive, mv, rm on a single shared resource."""
import uuid
diff --git a/tests/unit/test_uri_validation.py b/tests/unit/test_uri_validation.py
new file mode 100644
index 000000000..227673f11
--- /dev/null
+++ b/tests/unit/test_uri_validation.py
@@ -0,0 +1,69 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""Tests for common Viking URI boundary validation."""
+
+import pytest
+
+from openviking.core.uri_validation import validate_optional_viking_uri, validate_viking_uri
+from openviking_cli.exceptions import InvalidURIError
+
+
+ "uri",
+ [
+ "viking://resources/docs",
+ "resources/docs",
+ "/resources/docs",
+ "viking://",
+ ],
+)
+def test_validate_viking_uri_accepts_supported_forms(uri: str):
+ assert validate_viking_uri(uri) == uri.strip()
+
+
+ "uri",
+ [
+ "",
+ " ",
+ "viking:/resources/docs",
+ "s3://bucket/key",
+ "https://example.com/doc.md",
+ "viking://unsupported/doc.md",
+ "viking://temp/generated",
+ "viking://queue/tasks",
+ ],
+)
+def test_validate_viking_uri_rejects_invalid_or_unsupported_forms(uri: str):
+ with pytest.raises(InvalidURIError):
+ validate_viking_uri(uri)
+
+
+def test_validate_viking_uri_hides_internal_scopes_in_public_error():
+ with pytest.raises(InvalidURIError) as exc_info:
+ validate_viking_uri("ssd")
+
+ message = str(exc_info.value)
+ assert "resources" in message
+ assert "temp" not in message
+ assert "queue" not in message
+ assert "frozenset" not in message
+
+
+def test_validate_viking_uri_supports_internal_and_operation_scopes():
+ assert validate_viking_uri("viking://temp/generated", allow_internal=True)
+
+ with pytest.raises(InvalidURIError) as exc_info:
+ validate_viking_uri("viking://user/memories", allowed_scopes={"resources"})
+
+ message = str(exc_info.value)
+ assert "resources" in message
+ assert "user" in message
+ assert "temp" not in message
+ assert "queue" not in message
+
+
+def test_validate_optional_viking_uri_preserves_unspecified():
+ assert validate_optional_viking_uri(None) == ""
+ assert validate_optional_viking_uri(" ") == ""