Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Merge upstream main into codex/harden-markdown-import-symlinks

Saurabh Meena363a9ad64115
diff --cc CHANGELOG.md
index 639e6569,9ac9df42..5bb3d263
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -69,13 -397,12 +397,19 @@@ and this project adheres to [Semantic V
### Fixed
+- **Markdown import followed filesystem links even though Markdown export already refused to overwrite them** (#851, follow-up to #765, #786) by @SaurabhScripts
- - `AgentMemory._read_markdown_path()` now rejects symlink files, broken symlinks, symlinked directories, Windows directory junctions, and other Windows reparse points before parsing, including linked Markdown entries discovered while walking an import directory
- - New `_read_markdown_file()` re-checks the file and parent directory immediately before and after opening, uses `O_NOFOLLOW` where available, and verifies the resulting descriptor is a regular file via `fstat`/`S_ISREG`, so link swaps are rejected rather than silently followed
++ - `AgentMemory._read_markdown_path()` now rejects symlink files, broken symlinks, symlinked directories, Windows directory junctions, and other Windows reparse points supplied directly; linked entries discovered inside an otherwise valid directory are safely skipped, preserving the current directory-import contract
++ - `_read_markdown_file_content()` re-checks the file and parent directory immediately before and after opening, uses `O_NOFOLLOW` where available, and verifies the resulting descriptor is a regular file via `fstat`/`S_ISREG`, so link swaps are rejected rather than silently followed
+ - Junction detection uses `os.path.isjunction()` where available and falls back to the Windows reparse-point file attribute on older Python versions; export applies the same link check before replacing a Markdown file
+ - Documented the import restriction in `docs/reference/context.md`; added 11 tests to `tests/context/test_agent_memory_markdown.py` covering file/directory/broken-symlink rejection, simulated open races, mocked and real Windows junctions, and the reparse-point fallback
+ - Any additional review follow-up commits land in this same PR/entry rather than as a separate changelog item
+
+ - **`PipelineWithProvenance` raised `ModuleNotFoundError` on import and `AttributeError` on `.run()`** (#858, closes #858) by @Karunasagar12
+ - `from .pipeline import Pipeline` failed because `semantica/pipeline/pipeline.py` does not exist; corrected to `from .pipeline_builder import Pipeline`
+ - `.run()` called `self._pipeline.run()` on the `Pipeline` dataclass, which has no such method; replaced with `self._engine.execute_pipeline(self._pipeline, ...)` delegating to `ExecutionEngine`
+ - Constructor now accepts a built `Pipeline` instance (from `PipelineBuilder.build()`) instead of `**config`; the old `Pipeline(**config)` internal construction was invalid and never functional
+ - Replaced deprecated `datetime.utcnow()` with `datetime.now(timezone.utc)` in `run()`
+
- **`VectorStore.search_vectors()` returned inconsistent result shapes across backend implementations** (#853, closes #845) by @Sameer6305, reviewed by @KaifAhmad1
- Every built-in backend (FAISS, Milvus, pgvector, Pinecone, Qdrant, SQLite-vec, Weaviate, in-memory) now returns the same canonical `SearchResult` shape (`id`, `score`, `metadata`, `vector`, `distance`), instead of some backends omitting `vector`/`metadata`/`distance` or, for Weaviate, returning a backend-specific `properties` key instead of `metadata`
- Added a `SearchResult` `TypedDict` (`semantica/vector_store/vector_store.py`, exported from `semantica.vector_store`) documenting the contract; `metadata` now always defaults to `{}` rather than being absent, and `id` accepts `Union[str, int]` to accommodate Milvus/Qdrant's native integer IDs without casting
diff --cc semantica/context/agent_memory.py
index cd98dab2,38dd122c..def79ee3
--- a/semantica/context/agent_memory.py
+++ b/semantica/context/agent_memory.py
@@@ -1911,86 -1908,72 +1911,81 @@@ class AgentMemory
return memories
- def _read_markdown_path(self, path: Path) -> List[Tuple[str, str]]:
- if find_filesystem_link(path) is not None:
- raise ValueError(
- f"Refusing to import Markdown symbolic link or junction: {path}"
- )
-
- if not path.exists():
- raise FileNotFoundError(f"Markdown import path does not exist: {path}")
-
- if path.is_dir():
- file_paths = []
- for file_path in path.iterdir():
- if file_path.suffix.lower() not in self._MARKDOWN_EXTENSIONS:
- continue
- if find_filesystem_link(file_path) is not None:
- raise ValueError(
- "Refusing to import Markdown symbolic link or junction: "
- f"{file_path}"
- )
- if file_path.is_file():
- file_paths.append(file_path)
- file_paths.sort(key=lambda item: (item.name.casefold(), item.name))
- elif path.is_file():
- file_paths = [path]
- else:
- raise ValueError(f"Markdown import path is not a file or directory: {path}")
-
- return [
- (str(file_path), self._read_markdown_file(file_path))
- for file_path in file_paths
- ]
-
- @staticmethod
- def _read_markdown_file(file_path: Path) -> str:
- """Read a regular Markdown file without following a raced symlink."""
+ def _read_markdown_file_content(self, file_path: Path) -> str:
- if file_path.is_symlink():
- raise ValueError(f"Symlink Markdown import paths are rejected: {file_path}")
+ if find_filesystem_link(file_path) is not None:
+ raise ValueError(
- f"Refusing to import Markdown symbolic link or junction: {file_path}"
++ "Symlink Markdown import paths are rejected; symbolic links and "
++ f"junctions are unsafe: {file_path}"
+ )
- # Defend the open itself against a symlink introduced after the
- # is_symlink() check above (TOCTOU). O_NOFOLLOW is used where the
- # platform supports it, causing os.open() to fail with ELOOP if the
- # target became a symlink in the meantime. On platforms without
- # O_NOFOLLOW (e.g. Windows), os.open() may follow a link introduced
- # during the open. The pre/post-open reparse-point checks still reject
- # persistent swaps, but they cannot provide the same kernel-enforced
- # guarantee as O_NOFOLLOW.
flags = os.O_RDONLY
- if hasattr(os, "O_NOFOLLOW"):
- # On POSIX, O_NOFOLLOW makes os.open() fail with ELOOP if the
- # final path component is a symlink, atomically closing the TOCTOU
- # window between the is_symlink() check above and the open call.
- # On Windows, O_NOFOLLOW is not available; the is_symlink() pre-check
- # above is the only symlink defense and remains vulnerable to a narrow
- # race. The fstat()/S_ISREG guard below still rejects special files
- # (FIFOs, devices) on both platforms.
- flags |= os.O_NOFOLLOW
+ nofollow_flag = getattr(os, "O_NOFOLLOW", 0)
+ flags |= nofollow_flag
+
try:
- file_descriptor = os.open(file_path, flags)
+ fd = os.open(str(file_path), flags)
except OSError as exc:
- if exc.errno == getattr(errno, "ELOOP", None):
+ if (
+ (nofollow_flag and exc.errno == errno.ELOOP)
+ or find_filesystem_link(file_path) is not None
+ ):
raise ValueError(
- "Refusing to import Markdown symbolic link or junction: "
- f"{file_path}"
- f"Symlink Markdown import paths are rejected: {file_path}"
++ "Symlink Markdown import paths are rejected; symbolic links "
++ f"and junctions are unsafe: {file_path}"
) from exc
raise
try:
- stat_res = os.fstat(fd)
- if not stat.S_ISREG(stat_res.st_mode):
+ if find_filesystem_link(file_path) is not None:
+ raise ValueError(
- "Refusing to import Markdown symbolic link or junction: "
- f"{file_path}"
++ "Symlink Markdown import paths are rejected; symbolic links "
++ f"and junctions are unsafe: {file_path}"
+ )
- if not stat.S_ISREG(os.fstat(file_descriptor).st_mode):
++ if not stat.S_ISREG(os.fstat(fd).st_mode):
raise ValueError(
f"Markdown import path is not a regular file: {file_path}"
)
- with os.fdopen(file_descriptor, mode="r", encoding="utf-8") as source:
- file_descriptor = -1
- with open(fd, "r", encoding="utf-8", closefd=True) as f:
- return f.read()
- except Exception:
- try:
++ with os.fdopen(fd, mode="r", encoding="utf-8") as source:
++ fd = -1
+ return source.read()
+ finally:
- if file_descriptor >= 0:
- os.close(file_descriptor)
++ if fd >= 0:
+ os.close(fd)
- except OSError:
- pass
- raise
+
+ def _read_markdown_path(self, path: Path) -> List[Tuple[str, str]]:
- if path.is_symlink():
- raise ValueError(f"Symlink Markdown import paths are rejected: {path}")
++ if find_filesystem_link(path) is not None:
++ raise ValueError(
++ "Symlink Markdown import paths are rejected; symbolic links and "
++ f"junctions are unsafe: {path}"
++ )
+
+ if not path.exists():
+ raise FileNotFoundError(f"Markdown import path does not exist: {path}")
+
+ if path.is_dir():
- file_paths = sorted(
- (
- file_path
- for file_path in path.iterdir()
- if file_path.is_file()
- and not file_path.is_symlink()
- and file_path.suffix.lower() in self._MARKDOWN_EXTENSIONS
- ),
- key=lambda file_path: (file_path.name.casefold(), file_path.name),
- )
++ file_paths = []
++ for file_path in path.iterdir():
++ if file_path.suffix.lower() not in self._MARKDOWN_EXTENSIONS:
++ continue
++ if find_filesystem_link(file_path) is not None:
++ continue
++ if file_path.is_file():
++ file_paths.append(file_path)
++ if find_filesystem_link(path) is not None:
++ raise ValueError(
++ "Symlink Markdown import paths are rejected; symbolic links "
++ f"and junctions are unsafe: {path}"
++ )
++ file_paths.sort(key=lambda item: (item.name.casefold(), item.name))
+ elif path.is_file():
+ file_paths = [path]
+ else:
+ raise ValueError(f"Markdown import path is not a file or directory: {path}")
+
+ return [
+ (str(file_path), self._read_markdown_file_content(file_path))
+ for file_path in file_paths
+ ]
def _markdown_to_memory_dict(
self, document: str, source: str = "markdown document"
diff --cc tests/context/test_agent_memory_markdown.py
index 44f75bc9,bf1ca128..c1f71301
--- a/tests/context/test_agent_memory_markdown.py
+++ b/tests/context/test_agent_memory_markdown.py
@@@ -1,10 -1,7 +1,11 @@@
import errno
+import os
+import stat
+import subprocess
+ import sys
from copy import deepcopy
from datetime import datetime, timedelta, timezone
+from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
@@@ -721,153 -707,6 +730,151 @@@ def test_markdown_string_path_inspectio
assert exc_info.value.__cause__ is original_error
[email protected]("use_string_path", [False, True])
+def test_markdown_import_rejects_symlinked_file(tmp_path, use_string_path):
+ _require_symlink_support(tmp_path)
+ outside = tmp_path / "outside.md"
+ outside.write_text(
+ markdown_document(required_frontmatter(), "Do not import"),
+ encoding="utf-8",
+ )
+ source = tmp_path / "memory.md"
+ source.symlink_to(outside)
+ payload = str(source) if use_string_path else source
+ memory = AgentMemory()
+
+ with pytest.raises(ValueError, match="symbolic link"):
+ memory.import_data(payload, format="markdown")
+
+ assert memory.count() == 0
+
+
[email protected]("use_string_path", [False, True])
+def test_markdown_import_rejects_broken_symlink(tmp_path, use_string_path):
+ _require_symlink_support(tmp_path)
+ source = tmp_path / "missing-memory.md"
+ source.symlink_to(tmp_path / "missing-target.md")
+ payload = str(source) if use_string_path else source
+ memory = AgentMemory()
+
+ with pytest.raises(ValueError, match="symbolic link"):
+ memory.import_data(payload, format="markdown")
+
+ assert memory.count() == 0
+
+
[email protected]("use_string_path", [False, True])
+def test_markdown_import_rejects_symlinked_directory(tmp_path, use_string_path):
+ _require_symlink_support(tmp_path)
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "memory.md").write_text(
+ markdown_document(required_frontmatter(), "Do not import"),
+ encoding="utf-8",
+ )
+ source = tmp_path / "memory-export"
+ source.symlink_to(outside, target_is_directory=True)
+ payload = str(source) if use_string_path else source
+ memory = AgentMemory()
+
+ with pytest.raises(ValueError, match="symbolic link"):
+ memory.import_data(payload, format="markdown")
+
+ assert memory.count() == 0
+
+
- def test_markdown_import_rejects_symlinked_file_in_directory(tmp_path):
++def test_markdown_import_skips_symlinked_file_in_directory(tmp_path):
+ _require_symlink_support(tmp_path)
+ outside = tmp_path / "outside.md"
+ outside.write_text(
+ markdown_document(required_frontmatter(), "Do not import"),
+ encoding="utf-8",
+ )
+ source = tmp_path / "memory-export"
+ source.mkdir()
+ (source / "memory.md").symlink_to(outside)
+ memory = AgentMemory()
+
- with pytest.raises(ValueError, match="symbolic link"):
- memory.import_data(source, format="markdown")
-
++ assert memory.import_data(source, format="markdown") == 0
+ assert memory.count() == 0
+
+
[email protected](not hasattr(os, "O_NOFOLLOW"), reason="requires O_NOFOLLOW")
+def test_markdown_import_does_not_follow_symlink_raced_before_open(tmp_path):
+ _require_symlink_support(tmp_path)
+ outside = tmp_path / "outside.md"
+ outside.write_text(
+ markdown_document(required_frontmatter(), "Do not import"),
+ encoding="utf-8",
+ )
+ source = tmp_path / "memory.md"
+ source.symlink_to(outside)
+
+ with patch.object(Path, "is_symlink", return_value=False):
+ with pytest.raises(ValueError, match="symbolic link"):
- AgentMemory._read_markdown_file(source)
++ AgentMemory()._read_markdown_file_content(source)
+
+
+def test_markdown_import_rejects_windows_junction(tmp_path, monkeypatch):
+ source = tmp_path / "junction"
+ source.mkdir()
+ (source / "memory.md").write_text("not read", encoding="utf-8")
+
+ monkeypatch.setattr(
+ os.path,
+ "isjunction",
+ lambda candidate: Path(candidate) == source,
+ raising=False,
+ )
+
+ with pytest.raises(ValueError, match="junction"):
+ AgentMemory().import_data(source, format="markdown")
+
+
+def test_markdown_import_rejects_windows_reparse_point_fallback(tmp_path, monkeypatch):
+ source = tmp_path / "reparse-point"
+ source.mkdir()
+ real_lstat = os.lstat
+
+ class ReparseStat:
+ st_file_attributes = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
+
+ monkeypatch.delattr(os.path, "isjunction", raising=False)
+ monkeypatch.setattr(Path, "is_symlink", lambda self: False)
+ monkeypatch.setattr(
+ os,
+ "lstat",
+ lambda candidate: (
+ ReparseStat() if Path(candidate) == source else real_lstat(candidate)
+ ),
+ )
+
+ with pytest.raises(ValueError, match="junction"):
+ AgentMemory().import_data(source, format="markdown")
+
+
[email protected](os.name != "nt", reason="requires Windows junctions")
+def test_markdown_import_rejects_real_windows_junction(tmp_path):
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "memory.md").write_text("not read", encoding="utf-8")
+ source = tmp_path / "junction"
+ result = subprocess.run(
+ ["cmd.exe", "/c", "mklink", "/J", str(source), str(outside)],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if result.returncode != 0:
+ pytest.skip(f"could not create Windows junction: {result.stderr}")
+
+ try:
+ with pytest.raises(ValueError, match="junction"):
+ AgentMemory().import_data(source, format="markdown")
+ finally:
+ os.rmdir(source)
+
+
def test_legacy_dict_import_behavior_is_unchanged():
memory = AgentMemory()
data = {
@@@ -894,3 -733,109 +901,110 @@@ def test_markdown_export_destination_mu
with pytest.raises(ValueError, match="not a directory"):
AgentMemory().export(format="markdown", destination=destination)
+
+
+ def test_markdown_import_file_open_security_rejects_symlink(tmp_path):
+ memory = AgentMemory()
+ target = tmp_path / "secret.txt"
+ target.write_text("secret content", encoding="utf-8")
+ symlink_file = tmp_path / "memory.md"
+ try:
+ symlink_file.symlink_to(target)
+ except OSError as error:
+ winerror = getattr(error, "winerror", None)
+ if sys.platform == "win32" and winerror == _ERROR_PRIVILEGE_NOT_HELD:
+ pytest.skip("Windows symlink creation requires an unavailable privilege")
+ raise
+
+ with pytest.raises(ValueError, match="Symlink Markdown import paths are rejected"):
+ memory._read_markdown_file_content(symlink_file)
+
++
+ def test_markdown_import_public_api_rejects_symlink(tmp_path):
+ """
+ import_data(..., format="markdown") must propagate the symlink rejection
+ through the full call chain: import_data → _import_markdown_payload →
+ _read_markdown_path → _read_markdown_file_content.
+
+ This complements test_markdown_import_file_open_security_rejects_symlink,
+ which only tests the private helper. A future refactor that bypasses
+ _read_markdown_file_content would silently stop being protected; this test
+ catches that.
+ """
+ target = tmp_path / "secret.txt"
+ target.write_text("secret content", encoding="utf-8")
+ symlink_file = tmp_path / "memory.md"
+ try:
+ symlink_file.symlink_to(target)
+ except OSError as error:
+ winerror = getattr(error, "winerror", None)
+ if sys.platform == "win32" and winerror == _ERROR_PRIVILEGE_NOT_HELD:
+ pytest.skip("Windows symlink creation requires an unavailable privilege")
+ raise
+
+ memory = AgentMemory()
+ with pytest.raises(ValueError, match="Symlink Markdown import paths are rejected"):
+ memory.import_data(symlink_file, format="markdown")
+
+
+ def test_markdown_import_directory_silently_skips_symlinked_entries(tmp_path):
+ """
+ When importing a directory, symlink entries must be silently excluded.
+ Only real regular files must be read.
+
+ This tests the filter in _read_markdown_path:
+ not file_path.is_symlink()
+ which was added by PR #932.
+ """
+ # Write a real Markdown file in the directory
+ real_md = tmp_path / "real.md"
+ real_md.write_text(
+ markdown_document(required_frontmatter(memory_id="dir-real"), "Real content"),
+ encoding="utf-8",
+ )
+ # Write the symlink target outside the directory
+ target = tmp_path.parent / "outside.txt"
+ target.write_text("must not be read", encoding="utf-8")
+ link_md = tmp_path / "evil.md"
+ try:
+ link_md.symlink_to(target)
+ except OSError as error:
+ winerror = getattr(error, "winerror", None)
+ if sys.platform == "win32" and winerror == _ERROR_PRIVILEGE_NOT_HELD:
+ pytest.skip("Windows symlink creation requires an unavailable privilege")
+ raise
+
+ memory = AgentMemory()
+ # Must succeed, returning only the real file
+ results = memory._read_markdown_path(tmp_path)
+ assert len(results) == 1, (
+ f"Expected 1 result (real.md only), got {len(results)}: "
+ f"{[r[0] for r in results]}"
+ )
+ assert "Real content" in results[0][1]
+
+
+ def test_markdown_import_rejects_non_regular_file(tmp_path):
+ """
+ _read_markdown_file_content must raise ValueError when the opened file
+ descriptor does not refer to a regular file (S_ISREG fails).
+
+ This tests the fstat()/S_ISREG guard, which is the defense-in-depth layer
+ that catches special files (FIFOs, character devices) even when the
+ is_symlink() pre-check passes. The test works on both POSIX and Windows
+ because it mocks os.fstat rather than relying on platform-specific
+ filesystem objects.
+ """
+ import stat as stat_module
+
+ real_file = tmp_path / "not_really_regular.md"
+ real_file.write_text("some data", encoding="utf-8")
+
+ # Build a mock stat result whose st_mode describes a FIFO (S_IFIFO).
+ fake_stat = MagicMock()
+ fake_stat.st_mode = stat_module.S_IFIFO | 0o600 # FIFO with rw permissions
+
+ memory = AgentMemory()
+ with patch("semantica.context.agent_memory.os.fstat", return_value=fake_stat):
+ with pytest.raises(ValueError, match="not a regular file"):
+ memory._read_markdown_file_content(real_file)