Skip to content

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

Refine ovpack import validation and client security tests (#344)

13ernkastel46b3e76e28b9
diff --git a/openviking/storage/local_fs.py b/openviking/storage/local_fs.py
index cea4fbead..900f5489e 100644
--- a/openviking/storage/local_fs.py
+++ b/openviking/storage/local_fs.py
@@ -2,6 +2,7 @@
# SPDX-License-Identifier: Apache-2.0
import json
import os
+import re
import zipfile
from datetime import datetime
from typing import cast
@@ -16,6 +17,32 @@ from openviking_cli.utils.uri import VikingURI
logger = get_logger(__name__)
+_UNSAFE_PATH_RE = re.compile(r"(^|[\\/])\.\.($|[\\/])")
+_DRIVE_RE = re.compile(r"^[A-Za-z]:")
+
+
+def _validate_ovpack_member_path(zip_path: str, base_name: str) -> str:
+ """Validate a zip member path for ovpack imports and reject unsafe entries."""
+ if not zip_path:
+ raise ValueError("Invalid ovpack entry: empty path")
+ if "\\" in zip_path:
+ raise ValueError(f"Unsafe ovpack entry path: {zip_path!r}")
+ if zip_path.startswith("/"):
+ raise ValueError(f"Unsafe ovpack entry path: {zip_path!r}")
+ if _DRIVE_RE.match(zip_path):
+ raise ValueError(f"Unsafe ovpack entry path: {zip_path!r}")
+ if _UNSAFE_PATH_RE.search(zip_path):
+ raise ValueError(f"Unsafe ovpack entry path: {zip_path!r}")
+
+ parts = zip_path.split("/")
+ if any(part == ".." for part in parts):
+ raise ValueError(f"Unsafe ovpack entry path: {zip_path!r}")
+ if not parts or parts[0] != base_name:
+ raise ValueError(f"Invalid ovpack entry root: {zip_path!r}")
+
+ return zip_path
+
+
def ensure_ovpack_extension(path: str) -> str:
"""Ensure path ends with .ovpack extension."""
if not path.endswith(".ovpack"):
@@ -174,19 +201,21 @@ async def import_ovpack(
if not zip_path:
continue
+ safe_zip_path = _validate_ovpack_member_path(zip_path, base_name)
+
# Handle directory entries
- if zip_path.endswith("/"):
- rel_path = get_viking_rel_path_from_zip(zip_path.rstrip("/"))
+ if safe_zip_path.endswith("/"):
+ rel_path = get_viking_rel_path_from_zip(safe_zip_path.rstrip("/"))
target_dir_uri = f"{root_uri}/{rel_path}" if rel_path else root_uri
await viking_fs.mkdir(target_dir_uri, exist_ok=True, ctx=ctx)
continue
# Handle file entries
- rel_path = get_viking_rel_path_from_zip(zip_path)
+ rel_path = get_viking_rel_path_from_zip(safe_zip_path)
target_file_uri = f"{root_uri}/{rel_path}" if rel_path else root_uri
try:
- data = zf.read(zip_path)
+ data = zf.read(safe_zip_path)
await viking_fs.write_file_bytes(target_file_uri, data, ctx=ctx)
except Exception as e:
logger.error(f"Failed to import {zip_path} to {target_file_uri}: {e}")
diff --git a/tests/client/test_import_export.py b/tests/client/test_import_export.py
index e4b1b9f13..ec66043a7 100644
--- a/tests/client/test_import_export.py
+++ b/tests/client/test_import_export.py
@@ -3,8 +3,12 @@
"""Import/export tests"""
+import io
+import zipfile
from pathlib import Path
+import pytest
+
from openviking import AsyncOpenViking
@@ -111,3 +115,61 @@ class TestImportOvpack:
# Verify content consistency
assert original_content == imported_content
+
+
+ @staticmethod
+ def _build_ovpack(zip_path: Path, entries: dict[str, str]) -> None:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as zf:
+ for name, content in entries.items():
+ zf.writestr(name, content)
+ zip_path.write_bytes(buffer.getvalue())
+
+ @pytest.mark.parametrize(
+ "entries,error_pattern",
+ [
+ (
+ {
+ "pkg/_._meta.json": '{"uri": "viking://resources/pkg"}',
+ "pkg/../../escape.txt": "pwned",
+ },
+ "Unsafe ovpack entry path",
+ ),
+ (
+ {
+ "pkg/_._meta.json": '{"uri": "viking://resources/pkg"}',
+ "/abs/path.txt": "pwned",
+ },
+ "Unsafe ovpack entry path",
+ ),
+ (
+ {
+ "pkg/_._meta.json": '{"uri": "viking://resources/pkg"}',
+ "C:/drive/path.txt": "pwned",
+ },
+ "Unsafe ovpack entry path",
+ ),
+ (
+ {
+ "pkg/_._meta.json": '{"uri": "viking://resources/pkg"}',
+ "pkg\\windows\\path.txt": "pwned",
+ },
+ "Unsafe ovpack entry path",
+ ),
+ (
+ {
+ "pkg/_._meta.json": '{"uri": "viking://resources/pkg"}',
+ "other/file.txt": "pwned",
+ },
+ "Invalid ovpack entry root",
+ ),
+ ],
+ )
+ async def test_import_rejects_unsafe_entries(
+ self, client: AsyncOpenViking, temp_dir: Path, entries: dict[str, str], error_pattern: str
+ ):
+ ovpack_path = temp_dir / "malicious.ovpack"
+ self._build_ovpack(ovpack_path, entries)
+
+ with pytest.raises(ValueError, match=error_pattern):
+ await client.import_ovpack(str(ovpack_path), "viking://resources/security/", vectorize=False)