Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

harden: refuse symlink-following in verified file writes (O_NOFOLLOW) (#5770)

LearningCircuite621e05d3090
diff --git a/changelog.d/+harden-verified-write-nofollow.security.md b/changelog.d/+harden-verified-write-nofollow.security.md
new file mode 100644
index 0000000000..b926293336
--- /dev/null
+++ b/changelog.d/+harden-verified-write-nofollow.security.md
@@ -0,0 +1 @@
+Verified file writes now refuse symlinks at the destination leaf on platforms supporting `O_NOFOLLOW`. Python's normal file opening preserves text/binary handling, update/append/exclusive modes, descriptor cleanup and umask-based creation permissions. Platforms without `O_NOFOLLOW` retain their normal symlink behavior. Parent-directory symlinks and leaf paths already dereferenced by a caller remain outside this protection; a hardlinked leaf is not detected either, since O_NOFOLLOW only refuses symlinks. Writes still happen in place.
diff --git a/src/local_deep_research/security/file_write_verifier.py b/src/local_deep_research/security/file_write_verifier.py
index 62910ca6f0..52e294b0df 100644
--- a/src/local_deep_research/security/file_write_verifier.py
+++ b/src/local_deep_research/security/file_write_verifier.py
@@ -5,11 +5,21 @@ maintaining the encryption-at-rest security model.
"""
import json
+import os
from pathlib import Path
from typing import Any
from loguru import logger
+# Platforms without O_NOFOLLOW retain their normal symlink-following behavior.
+_O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
+
+
+def _open_nofollow(path: str, flags: int) -> int:
+ """Add supported leaf-symlink refusal to Python's normal open flags."""
+ return os.open(path, flags | _O_NOFOLLOW, 0o666)
+
+
# Keys that should never be written to disk in clear text
SENSITIVE_KEYS = frozenset(
{
@@ -85,6 +95,8 @@ def write_file_verified(
Raises:
FileWriteSecurityError: If the security setting doesn't match required value
+ OSError: errno ELOOP, if the destination leaf is a symlink and the
+ platform exposes O_NOFOLLOW
Example:
>>> write_file_verified(
@@ -112,14 +124,19 @@ def write_file_verified(
logger.warning(error_msg)
raise FileWriteSecurityError(error_msg)
- # Don't pass encoding for binary mode
- # Note: This function writes non-sensitive data (PDFs, reports) after security check.
- # CodeQL false positive: content is PDF binary or markdown, not passwords.
+ # Where O_NOFOLLOW is available, refuse a symlink at the final path
+ # component. Parent-directory symlinks and a leaf already dereferenced
+ # by the caller's Path.resolve() are outside this check.
+ # Let open() validate modes, own the descriptor and handle text/binary
+ # translation. Python supplies platform flags; creation honors the umask.
+ # This remains an in-place write, not an atomic file replacement.
if "b" in mode:
- with open(filepath, mode) as f: # nosec B603
+ with open(filepath, mode, opener=_open_nofollow) as f: # nosec B603
f.write(content)
else:
- with open(filepath, mode, encoding=encoding) as f: # nosec B603
+ with open(
+ filepath, mode, encoding=encoding, opener=_open_nofollow
+ ) as f: # nosec B603
f.write(content)
logger.debug(
diff --git a/src/local_deep_research/web/routers/api_v1.py b/src/local_deep_research/web/routers/api_v1.py
index 24cdb908ea..073a54a02b 100644
--- a/src/local_deep_research/web/routers/api_v1.py
+++ b/src/local_deep_research/web/routers/api_v1.py
@@ -104,8 +104,9 @@ def _scrub_error_fields(results: Dict[str, Any]) -> None:
# ``output_file`` is ALSO subtracted here for the identical reason it is
# rejected on quick_summary/generate_report (see ``_SERVER_PATH_PARAMS``
# below): analyze_documents (research_functions.py) reaches the same
-# ``write_file_verified`` -> bare ``open(filepath, mode)`` sink — with no
-# containment, traversal, or symlink check — after its own full
+# ``write_file_verified`` sink — with no containment or traversal check,
+# and a leaf-symlink refusal (O_NOFOLLOW) that does not cover
+# parent-directory symlinks or hardlinks — after its own full
# search-and-LLM run, behind the same unset-by-default
# ``api.allow_file_output`` gate, and the same opaque catch-all 500 when
# that gate is (correctly) closed. A server-side filesystem path posted in
@@ -431,11 +432,12 @@ _ACCEPTED_BUT_INEFFECTIVE_PARAMS = frozenset({"temperature"})
# ``FileWriteSecurityError``, so the caller pays the entire run's cost for
# an opaque 500 that never mentions the real cause.
# - If an operator has explicitly turned ``api.allow_file_output`` on,
-# ``write_file_verified``'s write path (``file_write_verifier.py``) is a
-# bare ``open(filepath, mode)`` with no containment: no restriction to a
-# configured output directory, no traversal or symlink check. A
-# caller-chosen path is written verbatim wherever the server process has
-# filesystem access.
+# ``write_file_verified``'s write path (``file_write_verifier.py``) has
+# no containment: no restriction to a configured output directory, no
+# traversal check. It refuses a symlink at the destination leaf (via
+# O_NOFOLLOW) but that refusal does not cover a symlinked parent
+# directory or a hardlinked leaf. A caller-chosen path is otherwise
+# written verbatim wherever the server process has filesystem access.
#
# A server-side filesystem path posted in a public JSON body is not a
# REST-shaped parameter — same "caller cannot legitimately express this
diff --git a/tests/research_library/services/test_pdf_storage_manager.py b/tests/research_library/services/test_pdf_storage_manager.py
index 3644d10526..4e2983e63a 100644
--- a/tests/research_library/services/test_pdf_storage_manager.py
+++ b/tests/research_library/services/test_pdf_storage_manager.py
@@ -548,6 +548,42 @@ class TestPDFStorageManagerFilesystemWrite:
assert result_path.exists()
+ def test_saves_to_symlinked_pdfs_directory(
+ self, tmp_path, mock_pdf_content
+ ):
+ """Should save PDFs when ``<library_root>/pdfs`` is a symlink.
+
+ Regression test: a common deployment layout symlinks
+ ``<library_root>/pdfs`` onto a larger disk. The directory-creation
+ call for this trusted, hard-coded "pdfs" leaf must not pass a
+ containment ``root=``, since ``create_directory`` resolves symlinks
+ before checking containment and would otherwise reject this legitimate
+ layout with a ``DirectoryCreationSecurityError``.
+ """
+ library_root = tmp_path / "library"
+ library_root.mkdir()
+ big_disk_pdfs = tmp_path / "big_disk_pdfs"
+ big_disk_pdfs.mkdir()
+ try:
+ (library_root / "pdfs").symlink_to(
+ big_disk_pdfs, target_is_directory=True
+ )
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create directory symlinks in this environment")
+
+ manager = PDFStorageManager(library_root, "filesystem")
+
+ result_path = manager._save_to_filesystem(
+ mock_pdf_content,
+ "symlinked_test.pdf",
+ )
+
+ assert result_path.exists()
+ assert result_path.read_bytes() == mock_pdf_content
+ # The file actually landed on the symlink target, not a directory
+ # newly created under library_root.
+ assert big_disk_pdfs in result_path.resolve().parents
+
class TestPDFStorageManagerGenerateFilename:
"""Tests for _generate_filename method."""
diff --git a/tests/security/test_verified_write_symlink_refusal.py b/tests/security/test_verified_write_symlink_refusal.py
new file mode 100644
index 0000000000..91b90d18d7
--- /dev/null
+++ b/tests/security/test_verified_write_symlink_refusal.py
@@ -0,0 +1,247 @@
+"""Regression tests: write_file_verified refuses to follow a symlink leaf.
+
+The verified-write helper is the single chokepoint the library PDF write path
+and the config/report writers use. Previously it opened the destination with a
+plain ``open(path, mode)``, so a symlink pre-planted at the target leaf was
+followed and the write landed on the link's target -- potentially a file
+outside the intended directory. The read path already refused symlinks; these
+tests pin the write side by opening with ``O_NOFOLLOW``.
+
+On platforms with O_NOFOLLOW, a symlinked destination must raise and must
+never modify the link's target. Legitimate writes to a regular/new path must
+still succeed with the intended content and semantics.
+"""
+
+import os
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.security.file_write_verifier import (
+ write_file_verified,
+ write_json_verified,
+)
+
+_GATE = "test.allow_write"
+_SNAP = {_GATE: True}
+
+
+# ---------------------------------------------------------------------------
+# Happy path -- normal writes still work
+# ---------------------------------------------------------------------------
+
+
+def test_text_write_to_new_path_succeeds(tmp_path):
+ target = tmp_path / "report.md"
+ write_file_verified(
+ target, "# hello", _GATE, context="t", settings_snapshot=_SNAP
+ )
+ assert target.read_text(encoding="utf-8") == "# hello"
+
+
+def test_binary_write_to_new_path_succeeds(tmp_path):
+ target = tmp_path / "paper.pdf"
+ write_file_verified(
+ target,
+ b"%PDF-1.4\n",
+ _GATE,
+ mode="wb",
+ context="t",
+ settings_snapshot=_SNAP,
+ )
+ assert target.read_bytes() == b"%PDF-1.4\n"
+
+
+def test_overwrite_existing_regular_file_succeeds(tmp_path):
+ target = tmp_path / "report.md"
+ target.write_text("old", encoding="utf-8")
+ write_file_verified(
+ target, "new", _GATE, context="t", settings_snapshot=_SNAP
+ )
+ assert target.read_text(encoding="utf-8") == "new"
+
+
+def test_write_json_verified_still_writes(tmp_path):
+ target = tmp_path / "results.json"
+ write_json_verified(
+ target, {"accuracy": 0.9}, _GATE, settings_snapshot=_SNAP
+ )
+ assert '"accuracy"' in target.read_text(encoding="utf-8")
+
+
+# ---------------------------------------------------------------------------
+# Symlink refusal -- the write must not follow a pre-planted link
+# ---------------------------------------------------------------------------
+
+
+ not hasattr(os, "O_NOFOLLOW"), reason="O_NOFOLLOW unavailable"
+)
[email protected]("mode", ["w", "wb", "a", "ab", "r+", "r+b"])
+def test_write_refuses_symlink_pointing_outside(tmp_path, mode):
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ canary = outside / "canary.txt"
+ canary.write_text("DO NOT OVERWRITE", encoding="utf-8")
+
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ link = workdir / "report.md"
+ try:
+ link.symlink_to(canary)
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ with pytest.raises(OSError):
+ write_file_verified(
+ link,
+ b"CHANGED" if "b" in mode else "CHANGED",
+ _GATE,
+ mode=mode,
+ context="t",
+ settings_snapshot=_SNAP,
+ )
+
+ # The symlink's target must be untouched.
+ assert canary.read_text(encoding="utf-8") == "DO NOT OVERWRITE"
+
+
+ not hasattr(os, "O_NOFOLLOW"), reason="O_NOFOLLOW unavailable"
+)
+def test_binary_write_refuses_symlink(tmp_path):
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ canary = outside / "canary.pdf"
+ canary.write_bytes(b"ORIGINAL")
+
+ link = tmp_path / "planted.pdf"
+ try:
+ link.symlink_to(canary)
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ with pytest.raises(OSError):
+ write_file_verified(
+ link,
+ b"PWNED",
+ _GATE,
+ mode="wb",
+ context="t",
+ settings_snapshot=_SNAP,
+ )
+
+ assert canary.read_bytes() == b"ORIGINAL"
+
+
+ not hasattr(os, "O_NOFOLLOW"), reason="O_NOFOLLOW unavailable"
+)
+def test_write_refuses_symlink_pointing_inside_same_dir(tmp_path):
+ """Even a link whose target is a sibling regular file is refused: the
+ write side never dereferences a symlink leaf."""
+ real = tmp_path / "real.md"
+ real.write_text("REAL", encoding="utf-8")
+ link = tmp_path / "link.md"
+ try:
+ link.symlink_to(real)
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ with pytest.raises(OSError):
+ write_file_verified(
+ link, "PWNED", _GATE, context="t", settings_snapshot=_SNAP
+ )
+
+ assert real.read_text(encoding="utf-8") == "REAL"
+
+
+ ("mode", "expected"),
+ [
+ ("r+", b"NEEP TAIL"),
+ ("r+b", b"NEEP TAIL"),
+ ("w+", b"N"),
+ ("a+", b"KEEP TAILN"),
+ ("ab", b"KEEP TAILN"),
+ ],
+)
+def test_write_preserves_update_and_append_semantics(tmp_path, mode, expected):
+ target = tmp_path / "existing.txt"
+ target.write_bytes(b"KEEP TAIL")
+ write_file_verified(
+ target,
+ b"N" if "b" in mode else "N",
+ _GATE,
+ mode=mode,
+ settings_snapshot=_SNAP,
+ )
+ assert target.read_bytes() == expected
+
+
[email protected]("mode", ["x", "xb", "x+"])
+def test_exclusive_write_refuses_existing_file(tmp_path, mode):
+ target = tmp_path / "existing.txt"
+ target.write_bytes(b"KEEP")
+ with pytest.raises(FileExistsError):
+ write_file_verified(
+ target,
+ b"N" if "b" in mode else "N",
+ _GATE,
+ mode=mode,
+ settings_snapshot=_SNAP,
+ )
+ assert target.read_bytes() == b"KEEP"
+
+
[email protected]("mode", ["wbb", "wa", "qq"])
[email protected]("exists", [False, True])
+def test_invalid_mode_fails_before_opening_file(tmp_path, mode, exists):
+ target = tmp_path / "report.txt"
+ if exists:
+ target.write_bytes(b"KEEP")
+ with patch(
+ "local_deep_research.security.file_write_verifier.os.open",
+ side_effect=AssertionError("invalid mode must not open a descriptor"),
+ ) as open_fd:
+ with pytest.raises(ValueError):
+ write_file_verified(
+ target, "N", _GATE, mode=mode, settings_snapshot=_SNAP
+ )
+ open_fd.assert_not_called()
+ assert target.exists() is exists
+ if exists:
+ assert target.read_bytes() == b"KEEP"
+
+
[email protected](os.name != "posix", reason="POSIX permission bits")
+def test_new_file_respects_group_writable_umask(tmp_path):
+ target = tmp_path / "shared.txt"
+ previous_umask = os.umask(0o002)
+ try:
+ write_file_verified(target, "N", _GATE, settings_snapshot=_SNAP)
+ finally:
+ os.umask(previous_umask)
+ assert target.stat().st_mode & 0o777 == 0o664
+
+
+def test_text_write_uses_normal_newline_translation(tmp_path):
+ target = tmp_path / "lines.txt"
+ write_file_verified(target, "one\ntwo\n", _GATE, settings_snapshot=_SNAP)
+ assert target.read_bytes() == f"one{os.linesep}two{os.linesep}".encode()
+
+
+ not hasattr(os, "O_NOFOLLOW"), reason="O_NOFOLLOW unavailable"
+)
+def test_write_refuses_dangling_symlink(tmp_path):
+ destination = tmp_path / "not-created.txt"
+ link = tmp_path / "link.txt"
+ try:
+ link.symlink_to(destination)
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+ with pytest.raises(OSError):
+ write_file_verified(link, "N", _GATE, settings_snapshot=_SNAP)
+ assert not destination.exists()
+ assert link.is_symlink()