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.

feat(security): route directory creation through a verified chokepoint (+ fix a latent integrity-disabling import cycle) (#5161)

LearningCircuit641308272b21
diff --git a/.github/scripts/check-file-writes.sh b/.github/scripts/check-file-writes.sh
index 1623296d2b..fbf63b2fda 100755
--- a/.github/scripts/check-file-writes.sh
+++ b/.github/scripts/check-file-writes.sh
@@ -39,6 +39,17 @@ SUSPICIOUS_PATTERNS=(
"fs\.appendFile"
)
+# Patterns that might indicate an unaudited directory creation, bypassing
+# the single audited chokepoint in security/directory_creation.py::create_directory.
+# Raw mkdir calls can silently create directories from unsanitized/traversal
+# paths, or litter vestigial directories (see the run_research_process bug
+# where an empty research_outputs/research_<id> dir was created per run).
+MKDIR_PATTERNS=(
+ "\.mkdir\("
+ "os\.makedirs\(" "os\.mkdir\("
+ "\bmakedirs\(" "\bmkdir\("
+)
+
# Directories to exclude from checks
EXCLUDE_DIRS=(
"tests"
@@ -85,6 +96,14 @@ SAFE_KEYWORDS=(
"write_json_verified"
)
+# Safe keywords that indicate a directory creation has been routed through
+# the audited chokepoint (or is an ephemeral tempfile dir, which is exempt
+# from path-containment concerns since it's OS-managed).
+MKDIR_SAFE_KEYWORDS=(
+ "create_directory"
+ "tempfile\.mkdtemp"
+)
+
# Known safe usage patterns (logs, configs, etc.)
SAFE_USAGE_PATTERNS=(
"security/file_write_verifier.py"
@@ -94,6 +113,19 @@ SAFE_USAGE_PATTERNS=(
"tmp_file"
)
+# Files/dirs allowed to call mkdir/makedirs directly instead of going
+# through security/directory_creation.py::create_directory. Keep this list
+# short and documented:
+# - security/directory_creation.py — this IS the audited chokepoint.
+# - benchmarks/**, api/benchmark_functions.py — dev tooling that writes
+# to user-chosen output/report directories, not production data paths.
+# Any new entry here needs the same kind of justification.
+MKDIR_ALLOWLIST_FILES=(
+ "security/directory_creation\.py"
+ "benchmarks/.+\.py"
+ "api/benchmark_functions\.py"
+)
+
# Build exclude arguments for grep
EXCLUDE_ARGS=""
for dir in "${EXCLUDE_DIRS[@]}"; do
@@ -142,6 +174,23 @@ if [ -n "$export_matches" ]; then
ALL_MATCHES="$ALL_MATCHES$export_matches\n"
fi
+echo "Scanning codebase for raw directory-creation calls..."
+
+# Separate pass/report for raw mkdir/makedirs, so it can point at
+# create_directory() specifically instead of the file-write remediation text.
+MKDIR_MATCHES=""
+for pattern in "${MKDIR_PATTERNS[@]}"; do
+ # -E (extended regex) is required here: these patterns use "\(" to mean a
+ # literal parenthesis, which is only correct in ERE. In default (basic)
+ # regex mode, a lone "\(" starts an unterminated group and grep errors out
+ # (silently swallowed by 2>/dev/null below), matching nothing at all.
+ # shellcheck disable=SC2086 # Word splitting is intentional for EXCLUDE_ARGS
+ matches=$(grep -rnE -I $EXCLUDE_ARGS -- "$pattern" $SEARCH_PATHS --include="*.py" 2>/dev/null | head -1000 || true)
+ if [ -n "$matches" ]; then
+ MKDIR_MATCHES="$MKDIR_MATCHES$matches\n"
+ fi
+done
+
# Now filter all matches at once
if [ -n "$ALL_MATCHES" ]; then
echo "Filtering results for false positives..."
@@ -172,6 +221,14 @@ if [ -n "$ALL_MATCHES" ]; then
done
fi
+ # A line carrying a documented '# Safe: <reason>' comment is treated as
+ # a reviewed exception (matches the remediation advice printed below).
+ if [ "$skip_line" -eq 0 ]; then
+ if echo "$line" | grep -qE "#\s*Safe:"; then
+ skip_line=1
+ fi
+ fi
+
# Additional filters for test/mock files that might not be caught by path exclusion
if [ "$skip_line" -eq 0 ]; then
if echo "$line" | grep -qE "test|mock|stub" && ! echo "$line" | grep -q "#"; then
@@ -223,19 +280,99 @@ if [ -n "$ALL_MATCHES" ]; then
fi
fi
+# Filter the mkdir/makedirs matches. Every production directory creation
+# must go through security/directory_creation.py::create_directory (the
+# audited gate -> act -> audit chokepoint), so anything left after
+# filtering is a real violation.
+FOUND_MKDIR_ISSUES=0
+if [ -n "$MKDIR_MATCHES" ]; then
+ MKDIR_MATCHES=$(echo -e "$MKDIR_MATCHES" | tr -d '\0' | sort -u)
+
+ mkdir_filtered_matches=""
+ while IFS= read -r line; do
+ [ -z "$line" ] && continue
+ echo "$line" | grep -qE '^[^:]+:[0-9]+:[[:space:]]*#' && continue
+
+ skip_line=0
+ for safe_pattern in "${MKDIR_SAFE_KEYWORDS[@]}"; do
+ if echo "$line" | grep -qE -- "$safe_pattern"; then
+ # If the line ALSO contains a raw mkdir/makedirs call, the safe
+ # keyword may be masking a real violation on the same line.
+ # Do not exempt — flag it for manual review.
+ if echo "$line" | grep -qE '\.mkdir\(|os\.mkdir\(|os\.makedirs\(|\bmkdir\(|\bmakedirs\('; then
+ continue
+ fi
+ skip_line=1
+ break
+ fi
+ done
+
+ # A line carrying a documented '# Safe: <reason>' comment is treated as
+ # a reviewed exception.
+ if [ "$skip_line" -eq 0 ]; then
+ if echo "$line" | grep -qE "#\s*Safe:"; then
+ skip_line=1
+ fi
+ fi
+
+ # Additional filter for test/mock/stub code living in src/ that isn't
+ # caught by the path exclusions. Matched on WORD BOUNDARIES (letters only):
+ # an unanchored "test|mock|stub" substring would silently exempt a real
+ # mkdir on any line containing e.g. "latest" (l-a-test), "attestation", or
+ # "contest" — defeating the chokepoint guard. This keeps genuine tokens
+ # like test_dir / mock_fs / stub_ matching while ignoring such substrings.
+ if [ "$skip_line" -eq 0 ]; then
+ if echo "$line" | grep -qE '(^|[^A-Za-z])(test|mock|stub)([^A-Za-z]|$)' && ! echo "$line" | grep -q "#"; then
+ skip_line=1
+ fi
+ fi
+
+ if [ "$skip_line" -eq 0 ]; then
+ for allow_file in "${MKDIR_ALLOWLIST_FILES[@]}"; do
+ if echo "$line" | grep -qE -- "$allow_file"; then
+ skip_line=1
+ break
+ fi
+ done
+ fi
+
+ if [ "$skip_line" -eq 0 ]; then
+ mkdir_filtered_matches="$mkdir_filtered_matches$line\n"
+ FOUND_MKDIR_ISSUES=1
+ fi
+ done <<< "$MKDIR_MATCHES"
+
+ if [ -n "$mkdir_filtered_matches" ] && [ "$FOUND_MKDIR_ISSUES" -eq 1 ]; then
+ echo "⚠️ Found raw directory-creation calls bypassing create_directory():"
+ echo "========================================="
+ echo -e "$mkdir_filtered_matches"
+ fi
+fi
+
echo "========================================="
-if [ $FOUND_ISSUES -eq 1 ]; then
- echo "❌ Security check failed: Found potential unencrypted file writes"
+if [ $FOUND_ISSUES -eq 1 ] || [ $FOUND_MKDIR_ISSUES -eq 1 ]; then
+ echo "❌ Security check failed"
echo ""
- echo "Please review the above findings and ensure:"
- echo "1. Sensitive data is not written to disk unencrypted"
- echo "2. Temporary files are properly cleaned up"
- echo "3. Use in-memory operations where possible"
- echo "4. If file writes are necessary, ensure they're encrypted or add '# Safe: <reason>' comment"
- echo ""
- echo "For exports, use the in-memory pattern like in export_report_to_memory()"
+ if [ $FOUND_ISSUES -eq 1 ]; then
+ echo "Potential unencrypted file writes — please review and ensure:"
+ echo "1. Sensitive data is not written to disk unencrypted"
+ echo "2. Temporary files are properly cleaned up"
+ echo "3. Use in-memory operations where possible"
+ echo "4. If file writes are necessary, ensure they're encrypted or add '# Safe: <reason>' comment"
+ echo ""
+ echo "For exports, use the in-memory pattern like in export_report_to_memory()"
+ echo ""
+ fi
+ if [ $FOUND_MKDIR_ISSUES -eq 1 ]; then
+ echo "Raw mkdir/makedirs calls found — please route directory creation through:"
+ echo " from local_deep_research.security.directory_creation import create_directory"
+ echo " create_directory(path, context=\"<what this is>\")"
+ echo "If a raw mkdir is genuinely unavoidable (e.g. bootstrapping the data"
+ echo "directory itself), add a '# Safe: <reason>' comment on that line."
+ echo ""
+ fi
exit 1
else
- echo "✅ Security check passed: No suspicious unencrypted file writes detected"
+ echo "✅ Security check passed: No suspicious unencrypted file writes or raw directory-creation calls detected"
fi
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 15bcbf2043..1217a26226 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -263,6 +263,14 @@ repos:
language: script
files: \.py$
description: "Prevent direct requests.get/post/Session - use safe_get/safe_post/SafeSession"
+ - id: check-file-writes
+ name: Check for unencrypted file writes and raw directory creation
+ entry: .github/scripts/check-file-writes.sh
+ language: script
+ pass_filenames: false
+ description: "Prevent bypassing encryption-at-rest with unaudited file
+ writes, and prevent raw mkdir/os.makedirs calls that bypass the
+ single audited chokepoint in security/directory_creation.py"
- id: check-silent-cleanup
name: Check for silent exceptions in close() methods
entry: .pre-commit-hooks/check-silent-cleanup.py
diff --git a/changelog.d/+verified-mkdir.misc.md b/changelog.d/+verified-mkdir.misc.md
new file mode 100644
index 0000000000..d45c423589
--- /dev/null
+++ b/changelog.d/+verified-mkdir.misc.md
@@ -0,0 +1 @@
+All production directory creation now routes through `security.create_directory` (audited chokepoint with opt-in path containment), enforced by a pre-commit/CI check that forbids raw `mkdir`/`os.makedirs`.
diff --git a/src/local_deep_research/config/paths.py b/src/local_deep_research/config/paths.py
index b96c4c0b04..bf94dc8eec 100644
--- a/src/local_deep_research/config/paths.py
+++ b/src/local_deep_research/config/paths.py
@@ -74,7 +74,7 @@ def _ensure_dir(subdir: str, label: str | None = None) -> Path:
The ensured directory path.
"""
path = get_data_directory() / subdir
- path.mkdir(parents=True, exist_ok=True)
+ path.mkdir(parents=True, exist_ok=True) # Safe: bootstrap data subdirectory
if label is not None:
logger.debug(f"Using {label} directory: {path}")
return path
@@ -207,9 +207,16 @@ def get_user_backup_directory(username: str) -> Path:
raise ValueError(
"Cannot compute a user backup directory for an empty username"
)
+ from local_deep_research.security.directory_creation import create_directory
+
username_hash = hashlib.sha256(username.encode()).hexdigest()[:16]
- user_backup_dir = get_backup_directory() / username_hash
- user_backup_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
+ backup_directory = get_backup_directory()
+ user_backup_dir = create_directory(
+ backup_directory / username_hash,
+ context="user backup directory",
+ root=backup_directory,
+ mode=0o700,
+ )
# Enforce 0o700 regardless of umask (mkdir mode is umask-masked)
user_backup_dir.chmod(0o700)
return user_backup_dir
diff --git a/src/local_deep_research/database/auth_db.py b/src/local_deep_research/database/auth_db.py
index 4c8899c2b1..6a90bdfb8a 100644
--- a/src/local_deep_research/database/auth_db.py
+++ b/src/local_deep_research/database/auth_db.py
@@ -106,8 +106,15 @@ def init_auth_database():
"""
auth_db_path = get_auth_db_path()
- # Ensure the data directory exists
- auth_db_path.parent.mkdir(parents=True, exist_ok=True)
+ # Ensure the data directory exists.
+ # Lazy import: this runs during early app bootstrap, so avoid a
+ # top-level security -> ... -> database import cycle.
+ from ..security.directory_creation import create_directory
+
+ create_directory(
+ auth_db_path.parent,
+ context="auth database directory",
+ )
logger.debug(f"Ensuring auth database at {auth_db_path}")
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index 8a39a288dd..4debdffb12 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -223,7 +223,15 @@ class DatabaseManager:
with self._connections_lock:
if path in self._initialized_data_dirs:
return
- path.mkdir(parents=True, exist_ok=True)
+ # Lazy import: avoid a security -> ... -> database import cycle at
+ # module load time (this can run during DatabaseManager
+ # construction, which happens early in app bootstrap).
+ from ..security.directory_creation import create_directory
+
+ create_directory(
+ path,
+ context="encrypted database storage",
+ )
# Restrict the per-user DB directory to the owner (0o700).
# This covers SQLite WAL/SHM sidecars and plaintext fallback temp
# files even when SQLite recreates them with umask permissions.
@@ -528,7 +536,12 @@ class DatabaseManager:
# Create connection string - use regular SQLite when SQLCipher not available
if self.has_encryption:
# Create directory if it doesn't exist
- db_path.parent.mkdir(parents=True, exist_ok=True)
+ from ..security.directory_creation import create_directory
+
+ create_directory(
+ db_path.parent,
+ context="per-user encrypted database directory",
+ )
# Create per-database salt for new databases (v2 security improvement).
#
diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.py
index 2c53183dc2..a815f85871 100644
--- a/src/local_deep_research/database/sqlcipher_utils.py
+++ b/src/local_deep_research/database/sqlcipher_utils.py
@@ -103,8 +103,12 @@ def create_database_salt(db_path: Union[str, Path]) -> bytes:
salt = secrets.token_bytes(SALT_SIZE)
- # Ensure parent directory exists
- salt_file.parent.mkdir(parents=True, exist_ok=True)
+ # Ensure parent directory exists.
+ # Lazy import: this runs during early database bootstrap, so avoid a
+ # top-level security -> ... -> database import cycle.
+ from ..security.directory_creation import create_directory
+
+ create_directory(salt_file.parent, context="database salt file directory")
# Write salt file with owner-only permissions (0o600)
fd = os.open(str(salt_file), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
diff --git a/src/local_deep_research/journal_quality/data_sources/base.py b/src/local_deep_research/journal_quality/data_sources/base.py
index fbf688d6c9..d7d8c3f5ce 100644
--- a/src/local_deep_research/journal_quality/data_sources/base.py
+++ b/src/local_deep_research/journal_quality/data_sources/base.py
@@ -101,7 +101,13 @@ class DataSource(ABC):
f"(~{self.approx_size_mb:.1f} MB)..."
)
try:
- data_dir.mkdir(parents=True, exist_ok=True)
+ # Lazy import to avoid import cycles for this early-loaded
+ # data-source registry module.
+ from ...security.directory_creation import create_directory
+
+ create_directory(
+ data_dir, context=f"journal quality data source '{self.key}'"
+ )
self.fetch(data_dir)
except Exception:
logger.exception(f"Failed to fetch {self.name}")
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index 7bbb045790..3970aa62be 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -242,13 +242,18 @@ class DownloadService:
def _setup_directories(self):
"""Create library directory structure."""
- # Only create the root and pdfs folder - flat structure
+ from ...security.directory_creation import create_directory
+
+ # Only create the root and pdfs folder - flat structure.
paths = [
self.library_root,
str(Path(self.library_root) / "pdfs"),
]
for path in paths:
- Path(path).mkdir(parents=True, exist_ok=True)
+ create_directory(
+ path,
+ context="download service library directory",
+ )
def _normalize_url(self, url: str) -> str:
"""Normalize URL for consistent hashing."""
diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.py
index 58af5d6479..f1a9d88c9c 100644
--- a/src/local_deep_research/research_library/services/library_rag_service.py
+++ b/src/local_deep_research/research_library/services/library_rag_service.py
@@ -46,6 +46,7 @@ from ...embeddings.splitters import get_text_splitter
from ...web_search_engines.engines.local_embedding_manager import (
LocalEmbeddingManager,
)
+from ...security.directory_creation import create_directory
from ...security.file_integrity import FileIntegrityManager, FAISSIndexVerifier
from ...security.file_integrity.integrity_manager import NO_INTEGRITY_RECORD
from ...vector_stores.facade import VectorIndex, ChunkInput, SearchResult
@@ -614,7 +615,9 @@ class LibraryRAGService:
]
rag_root = get_cache_directory() / "rag_indices"
cache_dir = rag_root / user_scope
- cache_dir.mkdir(parents=True, exist_ok=True)
+ create_directory(
+ cache_dir, context="per-user RAG index cache directory"
+ )
# 0o700: filesystem-level defense-in-depth so other local OS accounts
# can't browse another LDR user's vector caches. mkdir(parents=True)
# silently creates the intermediate rag_indices/ root under the process
diff --git a/src/local_deep_research/research_library/services/pdf_storage_manager.py b/src/local_deep_research/research_library/services/pdf_storage_manager.py
index 06b73cc1ea..c6e339ae58 100644
--- a/src/local_deep_research/research_library/services/pdf_storage_manager.py
+++ b/src/local_deep_research/research_library/services/pdf_storage_manager.py
@@ -384,8 +384,13 @@ class PDFStorageManager:
filename = self._generate_filename(url, resource_id, filename)
# Create simple flat directory structure - all PDFs in one folder
+ from ...security.directory_creation import create_directory
+
pdf_path = self.library_root / "pdfs"
- pdf_path.mkdir(parents=True, exist_ok=True)
+ create_directory(
+ pdf_path,
+ context="library PDF storage directory",
+ )
# Use PathValidator with relative path from library_root
relative_path = f"pdfs/{filename}"
diff --git a/src/local_deep_research/research_library/utils/__init__.py b/src/local_deep_research/research_library/utils/__init__.py
index 57452dd9b4..1f67cd4941 100644
--- a/src/local_deep_research/research_library/utils/__init__.py
+++ b/src/local_deep_research/research_library/utils/__init__.py
@@ -330,7 +330,23 @@ def get_library_storage_path(username: str) -> Path:
)
storage_path = apply_user_subdir(base_path, username, shared_library)
- storage_path.mkdir(parents=True, exist_ok=True)
+
+ # Lazy import to avoid import cycles (this module is imported early by
+ # several bootstrap paths).
+ from ...security.directory_creation import create_directory
+
+ # ``apply_user_subdir`` has already expanded/resolved the base path and
+ # validated the per-user component; route the actual mkdir through the
+ # audited chokepoint, keeping containment to the resolved base so a
+ # symlinked parent that escapes it is still rejected.
+ resolved_base = (
+ Path(os.path.expandvars(str(base_path))).expanduser().resolve()
+ )
+ create_directory(
+ storage_path,
+ context="per-user library storage",
+ root=resolved_base,
+ )
return storage_path
diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.py
index f83b75b62d..2647f5bf80 100644
--- a/src/local_deep_research/security/__init__.py
+++ b/src/local_deep_research/security/__init__.py
@@ -16,7 +16,10 @@ from .egress.audit_hook import (
set_active_context,
)
from .security_settings import get_security_default
-from .file_integrity import FileIntegrityManager, FAISSIndexVerifier
+
+# FileIntegrityManager / FAISSIndexVerifier are re-exported lazily in
+# ``__getattr__`` below. Eager imports form a cycle through database.encrypted_db
+# when the security package is imported during database bootstrap.
from .notification_validator import (
NotificationURLValidator,
NotificationURLValidationError,
@@ -113,6 +116,20 @@ __all__ = [
"UnsafeFilenameError",
]
+
+def __getattr__(name: str):
+ """Lazily provide file-integrity exports without a package import cycle."""
+ if name == "FileIntegrityManager":
+ from .file_integrity.integrity_manager import FileIntegrityManager
+
+ return FileIntegrityManager
+ if name == "FAISSIndexVerifier":
+ from .file_integrity.verifiers.faiss_verifier import FAISSIndexVerifier
+
+ return FAISSIndexVerifier
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
# Install the process-wide socket.connect audit hook after all imports
# resolve. The hook is a no-op until a worker thread calls
# ``set_active_context(ctx)`` — importing this module has zero
diff --git a/src/local_deep_research/security/directory_creation.py b/src/local_deep_research/security/directory_creation.py
new file mode 100644
index 0000000000..4a31b201c1
--- /dev/null
+++ b/src/local_deep_research/security/directory_creation.py
@@ -0,0 +1,110 @@
+"""Security module for verified directory creation operations.
+
+This module provides a single audited chokepoint for creating directories.
+Like ``security/file_write_verifier.py`` it is the sanctioned entry point that
+all production directory creation must route through (enforced by a
+pre-commit/CI check that forbids raw ``mkdir``/``makedirs``), giving one place
+that rejects null bytes and ``..`` traversal, resolves symlinks, and audit-logs
+every creation.
+
+Containment to an expected root is OPT-IN: pass ``root=`` when the target is
+built from an untrusted / user-influenced component (e.g. a per-user directory
+named after a username) to require it to resolve inside that root. Most call
+sites build paths from trusted constants under the data directory and pass no
+``root`` — for them the value is the audit + the no-bypass guarantee, not
+containment.
+"""
+
+from pathlib import Path
+
+from loguru import logger
+
+
+class DirectoryCreationSecurityError(Exception):
+ """Raised when a directory creation operation is not allowed by security checks."""
+
+ pass
+
+
+def create_directory(
+ path: str | Path,
+ *,
+ context: str,
+ root: str | Path | None = None,
+ parents: bool = True,
+ exist_ok: bool = True,
+ mode: int | None = None,
+) -> Path:
+ """Create a directory through the audited security chokepoint.
+
+ Rejects null bytes and raw ``..`` traversal, resolves the path (following
+ symlinks), optionally enforces containment within ``root``, creates the
+ directory, and audit-logs it.
+
+ Args:
+ path: Path to the directory to create.
+ context: Description of what's being created (for error messages and
+ audit logs).
+ root: Optional containment root. When provided, ``path`` must resolve
+ inside ``root`` (a symlinked parent that escapes it is caught) or a
+ ``DirectoryCreationSecurityError`` is raised. Pass this only when
+ ``path`` is built from an untrusted / user-influenced component;
+ when ``None`` (the default) no containment is enforced.
+ parents: Create parent directories as needed (default: True).
+ exist_ok: Do not raise if the directory already exists (default: True).
+ mode: Optional permission mode to pass to ``Path.mkdir``. If ``None``,
+ the ``Path.mkdir`` default is used.
+
+ Returns:
+ The resolved ``Path`` of the created directory.
+
+ Raises:
+ DirectoryCreationSecurityError: If the path contains a null byte, a
+ raw ``..`` traversal segment, or (when ``root`` is given) resolves
+ outside ``root``.
+
+ Example:
+ >>> create_directory(data_dir / "cache", context="rag cache")
+ >>> # opt-in containment for an untrusted leaf name:
+ >>> create_directory(
+ ... base / username, context="per-user library", root=base
+ ... )
+ """
+ # Reject null bytes in the raw path before any resolution happens.
+ if "\x00" in str(path):
+ raise DirectoryCreationSecurityError(
+ f"Refusing to create directory with null byte in path ({context})"
+ )
+
+ # Reject a raw ".." segment in the ORIGINAL input path parts. This is
+ # checked before resolve() because resolve() would silently collapse a
+ # traversal attempt, hiding the fact that the caller tried to escape.
+ if ".." in Path(path).parts:
+ raise DirectoryCreationSecurityError(
+ f"Refusing to create directory with '..' traversal segment: {path} ({context})"
+ )
+
+ # resolve() follows symlinks, so a symlinked parent directory that
+ # escapes the root is caught here. It also works for paths that do not
+ # yet exist.
+ p = Path(path).resolve()
+
+ if root is not None:
+ # Opt-in containment: require the target to resolve inside the given
+ # root. resolve() above already followed symlinks, so a symlinked
+ # parent that escapes the root is caught here too. (A path is
+ # is_relative_to itself, so creating the root itself is allowed.)
+ root_resolved = Path(root).resolve()
+ if not p.is_relative_to(root_resolved):
+ raise DirectoryCreationSecurityError(
+ f"Refusing to create directory outside {root_resolved}: {p} ({context})"
+ )
+
+ if mode is not None:
+ p.mkdir(parents=parents, exist_ok=exist_ok, mode=mode)
+ else:
+ p.mkdir(parents=parents, exist_ok=exist_ok)
+
+ logger.debug(f"Verified directory creation: {p} ({context})")
+
+ return p
diff --git a/src/local_deep_research/security/file_integrity/integrity_manager.py b/src/local_deep_research/security/file_integrity/integrity_manager.py
index e681249661..f5da05f6fc 100644
--- a/src/local_deep_research/security/file_integrity/integrity_manager.py
+++ b/src/local_deep_research/security/file_integrity/integrity_manager.py
@@ -16,15 +16,34 @@ from ...database.models.file_integrity import (
FileVerificationFailure,
)
-# Import session context conditionally (requires Flask)
+# Import session context (needs Flask). The security-critical guarantee here is
+# that a circular-import ImportError (e.g. a bootstrap load-order regression
+# where the security package is imported mid-way through encrypted_db's own
+# load) must NOT be silently swallowed — that would permanently disable
+# file-integrity verification for the whole process with no signal. So a real
+# failure re-raises loudly (locked in by test_integrity_bootstrap_guard.py).
+#
+# NOTE: Flask is currently a hard dependency and security/__init__ imports it
+# eagerly (via security_headers), so a genuine no-Flask install fails earlier at
+# package import and the ModuleNotFoundError degrade branch below is not reached
+# today. It is retained as defense-in-depth should that import ever be made lazy
+# to support no-Flask (library/CLI) use.
try:
from ...database.session_context import get_user_db_session
_has_session_context = True
except ImportError:
- _has_session_context = False
- # Provide stub for type checking
- get_user_db_session = None # type: ignore
+ try:
+ import flask # noqa: F401
+ except ModuleNotFoundError:
+ # Flask genuinely not installed — degrade gracefully.
+ _has_session_context = False
+ # Provide stub for type checking
+ get_user_db_session = None # type: ignore
+ else:
+ # Flask IS installed, so the failure is a real problem (circular
+ # import / load-order bug), not a missing optional dependency.
+ raise
# Reason returned by verify_file when a file has no integrity record. Unknown
diff --git a/src/local_deep_research/security/path_validator.py b/src/local_deep_research/security/path_validator.py
index 1035e7fb4b..c990fbd942 100644
--- a/src/local_deep_research/security/path_validator.py
+++ b/src/local_deep_research/security/path_validator.py
@@ -354,9 +354,17 @@ class PathValidator:
# Default model root - uses centralized path config (respects LDR_DATA_DIR)
model_root = str(get_models_directory())
- # Create model root if it doesn't exist
+ # Create model root if it doesn't exist. Lazy import: this sibling
+ # module can be imported very early (e.g. from `security/__init__.py`
+ # during package bootstrap), so import at call time rather than at
+ # module top level to avoid any import-cycle risk.
+ from .directory_creation import create_directory
+
model_root_path = Path(model_root).resolve()
- model_root_path.mkdir(parents=True, exist_ok=True)
+ create_directory(
+ model_root_path,
+ context="model root directory",
+ )
# Validate the path
validated_path = PathValidator.validate_safe_path(
diff --git a/src/local_deep_research/settings/env_settings.py b/src/local_deep_research/settings/env_settings.py
index f6755644c4..e06ad50a05 100644
--- a/src/local_deep_research/settings/env_settings.py
+++ b/src/local_deep_research/settings/env_settings.py
@@ -216,7 +216,16 @@ class PathSetting(StringSetting):
if self.create_if_missing and not path.exists():
try:
- path.mkdir(parents=True, exist_ok=True)
+ # Lazy import: this module is loaded very early (bootstrap
+ # env-only settings), before the database and app are
+ # initialized, so importing security at module load time
+ # risks an import cycle.
+ from ..security.directory_creation import create_directory
+
+ create_directory(
+ path,
+ context=f"env-configured path setting '{self.key}'",
+ )
except OSError:
logger.warning("Failed to create directory")
elif self.must_exist and not path.exists():
diff --git a/src/local_deep_research/storage/file.py b/src/local_deep_research/storage/file.py
index 241ca3d71f..02f16f5343 100644
--- a/src/local_deep_research/storage/file.py
+++ b/src/local_deep_research/storage/file.py
@@ -18,8 +18,16 @@ class FileReportStorage(ReportStorage):
base_dir: Base directory for storing reports.
If None, uses default research outputs directory.
"""
+ # Lazy import: mirrors the other lazy security imports in this
+ # module (e.g. file_write_verifier) and avoids pulling security
+ # into this module's top-level import graph.
+ from ..security.directory_creation import create_directory
+
self.base_dir = base_dir or get_research_outputs_directory()
- self.base_dir.mkdir(parents=True, exist_ok=True)
+ create_directory(
+ self.base_dir,
+ context="file report storage base directory",
+ )
def _get_report_path(self, research_id: str) -> Path:
"""Get the file path for a report."""
diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.py
index 838247696d..854d239c5c 100644
--- a/src/local_deep_research/utilities/log_utils.py
+++ b/src/local_deep_research/utilities/log_utils.py
@@ -25,7 +25,11 @@ from ..database.models import ResearchLog
from ..web.services.socket_service import SocketIOService
_LOG_DIR = get_logs_directory()
-_LOG_DIR.mkdir(parents=True, exist_ok=True)
+# Lazy import: log_utils is imported very early by many bootstrap paths, so
+# importing security at module top level risks an import cycle.
+from ..security.directory_creation import create_directory # noqa: E402
+
+create_directory(_LOG_DIR, context="logs directory")
# Thread-safe queue for database logs from background threads
_log_queue = queue.Queue(maxsize=1000)
diff --git a/src/local_deep_research/vector_stores/implementations/faiss_store.py b/src/local_deep_research/vector_stores/implementations/faiss_store.py
index 8fa83f145b..ce0d4f763c 100644
--- a/src/local_deep_research/vector_stores/implementations/faiss_store.py
+++ b/src/local_deep_research/vector_stores/implementations/faiss_store.py
@@ -526,8 +526,14 @@ class FaissVectorStore(BaseVectorStore):
reader/verifier never observes a half-written ``.faiss`` — it sees
either the old bytes or the new bytes, never a truncated mix.
"""
+ # Lazy import to avoid pulling security into this module's
+ # top-level import graph (vector store implementations load early).
+ from ...security.directory_creation import create_directory
+
path = Path(path)
- path.parent.mkdir(parents=True, exist_ok=True)
+ create_directory(
+ path.parent, context="FAISS vector store index directory"
+ )
# Keep the index dir private: the raw vectors are weakly invertible, so
# other local accounts must not be able to read them. Structural, not
# left to the caller.
diff --git a/src/local_deep_research/vector_stores/legacy_cleanup.py b/src/local_deep_research/vector_stores/legacy_cleanup.py
index d6fd3cb381..74cd21b78b 100644
--- a/src/local_deep_research/vector_stores/legacy_cleanup.py
+++ b/src/local_deep_research/vector_stores/legacy_cleanup.py
@@ -210,7 +210,11 @@ def _delete_file(path: Path) -> None:
def _write_sidecar_atomic(sidecar: Path, id_map: Dict[str, str]) -> None:
"""Atomically write the text-free position->uuid map as JSON."""
- sidecar.parent.mkdir(parents=True, exist_ok=True)
+ # Lazy import: this module runs at startup, before the app is fully
+ # wired up, so avoid a top-level import cycle.
+ from ..security.directory_creation import create_directory
+
+ create_directory(sidecar.parent, context="RAG legacy sidecar directory")
try:
sidecar.parent.chmod(0o700)
except OSError:
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index c17ed280bd..c0a6be0230 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -193,7 +193,11 @@ def create_app():
from ..config.paths import get_data_directory
secret_key_file = Path(get_data_directory()) / ".secret_key"
- secret_key_file.parent.mkdir(parents=True, exist_ok=True)
+ from ..security.directory_creation import create_directory
+
+ create_directory(
+ secret_key_file.parent, context="secret key file directory"
+ )
new_key = secrets.token_hex(32)
try:
fd = os.open(
diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.py
index f2424a8ac9..4df356b861 100644
--- a/src/local_deep_research/web/models/database.py
+++ b/src/local_deep_research/web/models/database.py
@@ -1,4 +1,3 @@
-import os
from datetime import datetime, UTC
from loguru import logger
@@ -12,7 +11,11 @@ _raw_data_dir = get_data_directory()
DATA_DIR: str | None = None
if _raw_data_dir:
DATA_DIR = str(_raw_data_dir)
- os.makedirs(DATA_DIR, exist_ok=True)
+ # Lazy import: this module executes at import time (early bootstrap),
+ # so avoid a top-level security -> ... -> web import cycle.
+ from ...security.directory_creation import create_directory
+
+ create_directory(DATA_DIR, context="application data directory")
# DB_PATH removed - use per-user encrypted databases instead
diff --git a/tests/security/test_directory_creation.py b/tests/security/test_directory_creation.py
new file mode 100644
index 0000000000..bd859c2085
--- /dev/null
+++ b/tests/security/test_directory_creation.py
@@ -0,0 +1,227 @@
+"""
+Comprehensive tests for security/directory_creation.py
+
+Containment to an expected root is OPT-IN: passing no ``root=`` (the
+default) performs the audited creation with null-byte and raw ``..``
+traversal rejection but NO containment check. Containment is enforced
+only when the caller explicitly passes ``root=``.
+
+Tests cover:
+- create_directory with root=None (the default): creates freely, but
+ null-byte and raw ".." traversal rejection still apply
+- create_directory with an explicit root=: containment is enforced
+- mode / parents / exist_ok behavior
+- symlinked-parent escape detection (requires an explicit root=)
+"""
+
+import pytest
+
+from local_deep_research.security.directory_creation import (
+ DirectoryCreationSecurityError,
+ create_directory,
+)
+
+
+class TestCreateDirectoryNoRoot:
+ """Tests for create_directory with root=None (the default).
+
+ No containment is enforced in this mode -- the function is the audited
+ + validated chokepoint, not a jail. Null-byte and raw ".." rejection
+ still apply regardless of root.
+ """
+
+ def test_creates_dir_with_no_root(self, tmp_path):
+ target = tmp_path / "subdir" / "nested"
+
+ result = create_directory(target, context="test nested dir")
+
+ assert result == target.resolve()
+ assert target.is_dir()
+
+ def test_no_containment_by_default(self, tmp_path):
+ # A "conceptual" base exists alongside an entirely unrelated
+ # location. With no root= passed, create_directory must not care
+ # that target is nowhere near conceptual_base -- proving there is
+ # no default/implicit containment now that it is opt-in.
+ conceptual_base = tmp_path / "conceptual_base"
+ conceptual_base.mkdir()
+ target = tmp_path / "elsewhere" / "unrelated_dir"
+
+ result = create_directory(target, context="no containment by default")
+
+ assert result == target.resolve()
+ assert target.is_dir()
+
+ def test_traversal_that_resolves_outside_conceptual_base_succeeds(
+ self, tmp_path
+ ):
+ # Without an explicit root=, a path that *resolves* outside some
+ # conceptual base (but contains no raw ".." segment in its own
+ # input -- it is built directly, not via "..") is created
+ # successfully: there is nothing to contain it to.
+ conceptual_base = tmp_path / "conceptual_base"
+ conceptual_base.mkdir()
+ target = tmp_path / "outside_conceptual_base"
+
+ result = create_directory(target, context="outside conceptual base")
+
+ assert result == target.resolve()
+ assert target.is_dir()
+
+ def test_rejects_null_byte_without_root(self, tmp_path):
+ bad_path = str(tmp_path / "sub\x00dir")
+
+ with pytest.raises(DirectoryCreationSecurityError, match="null byte"):
+ create_directory(bad_path, context="null byte test")
+
+ def test_rejects_raw_dotdot_segment_without_root(self, tmp_path):
+ # No root= is passed, yet the raw ".." segment in the ORIGINAL
+ # input must still be rejected -- this check is unconditional, not
+ # part of the opt-in containment behavior.
+ traversal_path = tmp_path / "foo" / ".." / "foo"
+
+ with pytest.raises(DirectoryCreationSecurityError, match="traversal"):
+ create_directory(traversal_path, context="dotdot in middle")
+
+ assert not (tmp_path / "foo").exists()
+
+
+class TestCreateDirectoryExplicitRoot:
+ """Tests for create_directory with an explicit root= parameter."""
+
+ def test_honors_explicit_root_outside_data_dir(self, tmp_path):
+ base = tmp_path / "user_configured_library"
+ target = base / "downloads"
+
+ result = create_directory(
+ target, context="library download dir", root=base
+ )
+
+ assert result == target.resolve()
+ assert target.is_dir()
+
+ def test_rejects_path_escaping_explicit_root(self, tmp_path):
+ base = tmp_path / "library_root"
+ base.mkdir()
+ outside = tmp_path / "other_dir"
+
+ with pytest.raises(DirectoryCreationSecurityError) as exc_info:
+ create_directory(outside, context="escape attempt", root=base)
+
+ assert str(base.resolve()) in str(exc_info.value)
+ assert not outside.exists()
+
+ def test_rejects_relative_traversal_with_explicit_root(self, tmp_path):
+ base = tmp_path / "library_root"
+ base.mkdir()
+ escape_attempt = base / ".." / "escaped"
+
+ with pytest.raises(DirectoryCreationSecurityError):
+ create_directory(escape_attempt, context="dotdot escape", root=base)
+
+ def test_creating_root_itself_is_allowed(self, tmp_path):
+ base = tmp_path / "library_root"
+
+ result = create_directory(base, context="root itself", root=base)
+
+ assert result == base.resolve()
+ assert base.is_dir()
+
+
+class TestCreateDirectoryValidation:
+ """Tests for input validation (null bytes, traversal segments) when an
+ explicit root= is also given, showing these checks run independently of
+ (and before) the containment check."""
+
+ def test_rejects_null_byte_in_path(self, tmp_path):
+ base = tmp_path / "root"
+ base.mkdir()
+ bad_path = str(base / "sub\x00dir")
+
+ with pytest.raises(DirectoryCreationSecurityError, match="null byte"):
+ create_directory(bad_path, context="null byte test", root=base)
+
+ def test_rejects_raw_dotdot_segment_in_original_input(self, tmp_path):
+ base = tmp_path / "root"
+ base.mkdir()
+ # Even though this resolves inside base (root/foo/../foo == root/foo),
+ # the raw ".." segment in the original input must be rejected.
+ traversal_path = base / "foo" / ".." / "foo"
+
+ with pytest.raises(DirectoryCreationSecurityError, match="traversal"):
+ create_directory(
+ traversal_path, context="dotdot in middle", root=base
+ )
+
+
+class TestCreateDirectoryModeParentsExistOk:
+ """Tests for mode / parents / exist_ok behavior."""
+
+ def test_parents_false_raises_when_parent_missing(self, tmp_path):
+ base = tmp_path / "root"
+ base.mkdir()
+ target = base / "missing_parent" / "child"
+
+ with pytest.raises(FileNotFoundError):
+ create_directory(
+ target, context="no parents", root=base, parents=False
+ )
+
+ def test_exist_ok_false_raises_when_dir_exists(self, tmp_path):
+ base = tmp_path / "root"
+ base.mkdir()
+ target = base / "existing"
+ target.mkdir()
+
+ with pytest.raises(FileExistsError):
+ create_directory(
+ target, context="already exists", root=base, exist_ok=False
+ )
+
+ def test_exist_ok_true_is_idempotent(self, tmp_path):
+ base = tmp_path / "root"
+ base.mkdir()
+ target = base / "existing"
+ target.mkdir()
+
+ # Should not raise.
+ result = create_directory(
+ target, context="idempotent create", root=base, exist_ok=True
+ )
+ assert result == target.resolve()
+
+ def test_mode_is_applied_to_new_directory(self, tmp_path):
+ base = tmp_path / "root"
+ base.mkdir()
+ target = base / "restricted"
+
+ create_directory(target, context="mode test", root=base, mode=0o700)
+
+ # Account for umask potentially clearing bits; just verify owner rwx.
+ actual_mode = target.stat().st_mode & 0o700
+ assert actual_mode == 0o700
+
+
+class TestCreateDirectorySymlinkEscape:
+ """Tests for symlinked-parent escape detection.
+
+ Symlink-escape detection is only meaningful in combination with
+ containment, so this test passes an explicit root=.
+ """
+
+ def test_symlinked_parent_escaping_root_is_caught(self, tmp_path):
+ base = tmp_path / "root"
+ base.mkdir()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+
+ # Create a symlink inside the root that points outside of it.
+ symlink_dir = base / "link_out"
+ symlink_dir.symlink_to(outside, target_is_directory=True)
+
+ target = symlink_dir / "new_subdir"
+
+ with pytest.raises(DirectoryCreationSecurityError):
+ create_directory(target, context="symlink escape", root=base)
+
+ assert not (outside / "new_subdir").exists()
diff --git a/tests/security/test_integrity_bootstrap_guard.py b/tests/security/test_integrity_bootstrap_guard.py
new file mode 100644
index 0000000000..9151a28409
--- /dev/null
+++ b/tests/security/test_integrity_bootstrap_guard.py
@@ -0,0 +1,128 @@
+# allow: no-sut-import — imports the SUT inside an isolated subprocess so the
+# import order (encrypted_db before app_factory) is deterministic in a fresh
+# interpreter; importing in-process would leave sys.modules already populated
+# from other tests and could mask the regression.
+"""CI regression guard for the file-integrity bootstrap import-cycle bug.
+
+Historically, importing ``security/__init__.py`` (directly or transitively)
+before ``database.encrypted_db`` had finished loading formed an import cycle:
+
+ security/__init__.py
+ -> security/file_integrity/integrity_manager.py
+ -> database/session_context.py
+ -> database/encrypted_db.py (mid-load, not yet fully initialized)
+
+``integrity_manager`` caught the resulting ``ImportError`` and silently set
+``_has_session_context = False`` for the rest of the process, permanently
+disabling file-integrity verification with no signal to the operator.
+
+The fix: ``security/__init__.py`` no longer re-exports ``file_integrity``
+(breaking the cycle), and ``integrity_manager`` now only swallows the
+ImportError when Flask itself is genuinely absent -- any other ImportError
+(i.e. a load-order regression) is re-raised so it fails loudly, in CI.
+
+This test locks in the fix by driving the exact import order that triggered
+the original bug -- ``database.encrypted_db`` first, then
+``web.app_factory`` (which imports ``security`` at module scope) -- in a
+subprocess, then asserting ``integrity_manager._has_session_context`` is
+still True. If this regresses, ``_has_session_context`` silently flips to
+False instead of raising, so this out-of-process assertion is the only way
+to catch it.
+"""
+
+import os
+import subprocess
+import sys
+import textwrap
+from pathlib import Path
+
+# The worktree's own src/ must come first on PYTHONPATH so the subprocess
+# imports the version under test rather than any shadowing editable install.
+_SRC_DIR = str(Path(__file__).resolve().parents[2] / "src")
+
+
+def _run_probe(script):
+ """Run an import probe in a fresh interpreter; return its stdout text.
+
+ The probe must exit zero and print marker lines on stdout. Any non-zero
+ exit (including ImportError) is reported with full diagnostics.
+ """
+ env = dict(os.environ)
+ existing = env.get("PYTHONPATH")
+ env["PYTHONPATH"] = (
+ _SRC_DIR if not existing else _SRC_DIR + os.pathsep + existing
+ )
+
+ result = subprocess.run(
+ [sys.executable, "-c", textwrap.dedent(script)],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ check=False,
+ env=env,
+ )
+ assert result.returncode == 0, (
+ "import probe exited with code {code}.\n"
+ "STDOUT:\n{stdout}\n"
+ "STDERR:\n{stderr}\n".format(
+ code=result.returncode,
+ stdout=result.stdout,
+ stderr=result.stderr,
+ )
+ )
+ return result.stdout
+
+
+def _parse_markers(stdout):
+ """Parse key=value lines from probe stdout into a dict."""
+ return dict(
+ line.split("=", 1)
+ for line in stdout.splitlines()
+ if "=" in line and not line.startswith(" ")
+ )
+
+
+def test_module_file_resolves_under_worktree():
+ """Sanity check: the probe's PYTHONPATH actually selects this worktree's
+ module, not a shadowing editable install elsewhere on the path."""
+ stdout = _run_probe(
+ """
+ import local_deep_research.security.directory_creation as m
+
+ print("MODULE_FILE=" + m.__file__)
+ """
+ )
+ markers = _parse_markers(stdout)
+ assert markers.get("MODULE_FILE", "").startswith(_SRC_DIR), (
+ "probe resolved local_deep_research from outside the worktree src/ "
+ "-- an editable install elsewhere is shadowing it.\n"
+ "Probe stdout:\n" + stdout
+ )
+
+
+def test_encrypted_db_then_app_factory_keeps_integrity_session_context():
+ """Import encrypted_db first, then app_factory: integrity_manager must
+ still report _has_session_context = True (Flask + session context wired
+ up), never the silent-disable regression."""
+ stdout = _run_probe(
+ """
+ import local_deep_research.database.encrypted_db # noqa: F401
+ import local_deep_research.web.app_factory # noqa: F401
+ from local_deep_research.security.file_integrity import (
+ integrity_manager,
+ )
+
+ print(
+ "HAS_SESSION_CONTEXT="
+ + ("yes" if integrity_manager._has_session_context else "no")
+ )
+ """
+ )
+ markers = _parse_markers(stdout)
+ assert markers.get("HAS_SESSION_CONTEXT") == "yes", (
+ "file-integrity verification silently disabled: "
+ "integrity_manager._has_session_context is False after importing "
+ "database.encrypted_db then web.app_factory. This is the exact "
+ "import-order regression the bootstrap fix guards against.\n"
+ "Probe stdout:\n" + stdout
+ )
diff --git a/tests/security/test_mkdir_scanner_bypass.py b/tests/security/test_mkdir_scanner_bypass.py
new file mode 100644
index 0000000000..dff10329cc
--- /dev/null
+++ b/tests/security/test_mkdir_scanner_bypass.py
@@ -0,0 +1,121 @@
+# allow: no-sut-import — tests a shell script (.github/scripts/check-file-writes.sh), not Python code
+"""Tests for the mkdir scanner bypass detection in check-file-writes.sh.
+
+Verifies that raw mkdir() calls on the same line as create_directory()
+are NOT silently exempted by the safe-keyword filter.
+"""
+
+import subprocess
+import textwrap
+from pathlib import Path
+
+import pytest
+
+
+SCANNER = (
+ Path(__file__).resolve().parents[2]
+ / ".github"
+ / "scripts"
+ / "check-file-writes.sh"
+)
+
+
+def _run_scanner(tmp_path: Path, source_files: dict[str, str]) -> str:
+ """Run check-file-writes.sh from a temp repo root with src/ structure."""
+ for rel_path, content in source_files.items():
+ full = tmp_path / rel_path
+ full.parent.mkdir(parents=True, exist_ok=True)
+ full.write_text(textwrap.dedent(content))
+
+ result = subprocess.run(
+ ["bash", str(SCANNER)],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ cwd=str(tmp_path),
+ )
+ return result.stdout + result.stderr
+
+
+def test_scanner_flags_mkdir_same_line_as_create_directory(tmp_path):
+ """A single line with both .mkdir() and create_directory() must be flagged."""
+ output = _run_scanner(
+ tmp_path,
+ {
+ "src/app/bypass.py": """
+ from pathlib import Path
+ from security.directory_creation import create_directory
+
+ def bypass():
+ Path("bad").mkdir(); create_directory("good")
+ """,
+ },
+ )
+ assert "bypass" in output.lower() or "raw" in output.lower(), (
+ f"Expected bypass to be flagged, got:\n{output}"
+ )
+
+
+def test_scanner_does_not_flag_legitimate_create_directory(tmp_path):
+ """Lines that only call create_directory() without raw mkdir should pass."""
+ output = _run_scanner(
+ tmp_path,
+ {
+ "src/app/safe.py": """
+ from security.directory_creation import create_directory
+
+ def safe_setup():
+ create_directory("good_path")
+ """,
+ },
+ )
+ assert "passed" in output.lower(), f"Expected pass, got:\n{output}"
+
+
[email protected]("direct_import", ["mkdir", "makedirs"])
+def test_scanner_flags_direct_os_imports(
+ tmp_path: Path, direct_import: str
+) -> None:
+ output = _run_scanner(
+ tmp_path,
+ {
+ "src/app/direct_import.py": f"""
+ from os import {direct_import}
+
+ def bypass():
+ {direct_import}("bad")
+ """,
+ },
+ )
+ assert "found raw directory-creation calls" in output.lower(), (
+ f"Expected direct {direct_import} import to be flagged, got:\n{output}"
+ )
+
+
+def test_scanner_does_not_allowlist_all_of_config_paths(tmp_path: Path) -> None:
+ output = _run_scanner(
+ tmp_path,
+ {
+ "src/local_deep_research/config/paths.py": """
+ from pathlib import Path
+
+ def create_backup_directory():
+ Path("backup").mkdir()
+ """,
+ },
+ )
+ assert "found raw directory-creation calls" in output.lower(), (
+ f"Expected config/paths.py raw mkdir to be flagged, got:\n{output}"
+ )
+
+
+def test_scanner_ignores_mkdir_mentions_in_comments(tmp_path: Path) -> None:
+ output = _run_scanner(
+ tmp_path,
+ {
+ "src/app/comment.py": """
+ # Explain why callers no longer use mkdir()
+ """,
+ },
+ )
+ assert "passed" in output.lower(), f"Expected pass, got:\n{output}"