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.

security: add verified file write system with setting-based controls

LearningCircuit0b5c0108801e
diff --git a/.github/scripts/check-file-writes.sh b/.github/scripts/check-file-writes.sh
index 5dfa00d625..85a4e97872 100755
--- a/.github/scripts/check-file-writes.sh
+++ b/.github/scripts/check-file-writes.sh
@@ -80,13 +80,21 @@ EXCLUDE_FILES=(
)
# Safe keywords that indicate encrypted or safe operations
-# Empty for now - will add on case-by-case basis
+# These patterns indicate that file writes have been security-verified
SAFE_KEYWORDS=(
+ "write_file_verified"
+ "write_json_verified"
)
# Known safe usage patterns (logs, configs, etc.)
-# Empty for now - will add on case-by-case basis
SAFE_USAGE_PATTERNS=(
+ "security/file_write_verifier.py"
+ "import tempfile"
+ "tempfile\.mkdtemp"
+ "def get_report_as_temp_file"
+ "\.get_report_as_temp_file\("
+ "tmp_path"
+ "tmp_file"
)
# Build exclude arguments for grep
diff --git a/src/local_deep_research/api/benchmark_functions.py b/src/local_deep_research/api/benchmark_functions.py
index 3fc9e8a488..8492fe0dda 100644
--- a/src/local_deep_research/api/benchmark_functions.py
+++ b/src/local_deep_research/api/benchmark_functions.py
@@ -232,41 +232,45 @@ def compare_configurations(
# Generate comparison report
import time
+ from ...security.file_write_verifier import write_file_verified
timestamp = time.strftime("%Y%m%d_%H%M%S")
report_file = str(
Path(output_dir) / f"comparison_{dataset_type}_{timestamp}.md"
)
- with open(report_file, "w") as f:
- f.write(f"# Configuration Comparison - {dataset_type.capitalize()}\n\n")
+ # Build report content
+ content = f"# Configuration Comparison - {dataset_type.capitalize()}\n\n"
- # Write summary table
- f.write("## Summary\n\n")
- f.write("| Configuration | Accuracy | Avg. Time | Examples |\n")
- f.write("|---------------|----------|-----------|----------|\n")
+ # Write summary table
+ content += "## Summary\n\n"
+ content += "| Configuration | Accuracy | Avg. Time | Examples |\n"
+ content += "|---------------|----------|-----------|----------|\n"
- for result in results:
- accuracy = result.get("metrics", {}).get("accuracy", 0)
- avg_time = result.get("metrics", {}).get(
- "average_processing_time", 0
- )
- examples = result.get("total_examples", 0)
+ for result in results:
+ accuracy = result.get("metrics", {}).get("accuracy", 0)
+ avg_time = result.get("metrics", {}).get("average_processing_time", 0)
+ examples = result.get("total_examples", 0)
- f.write(
- f"| {result['configuration_name']} | {accuracy:.3f} | {avg_time:.2f}s | {examples} |\n"
- )
+ content += f"| {result['configuration_name']} | {accuracy:.3f} | {avg_time:.2f}s | {examples} |\n"
- f.write("\n## Configuration Details\n\n")
+ content += "\n## Configuration Details\n\n"
- for result in results:
- f.write(f"### {result['configuration_name']}\n\n")
+ for result in results:
+ content += f"### {result['configuration_name']}\n\n"
- config = result.get("search_config", {})
- f.write("```\n")
- for key, value in config.items():
- f.write(f"{key}: {value}\n")
- f.write("```\n\n")
+ config = result.get("search_config", {})
+ content += "```\n"
+ for key, value in config.items():
+ content += f"{key}: {value}\n"
+ content += "```\n\n"
+
+ write_file_verified(
+ report_file,
+ content,
+ "benchmark.allow_file_output",
+ context="benchmark comparison report",
+ )
logger.info(f"Comparison report saved to {report_file}")
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 4f86435a0d..e8bfc8bd93 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -411,8 +411,14 @@ def generate_report(
# Save report to file if path is provided
if output_file and report and "content" in report:
- with open(output_file, "w", encoding="utf-8") as f:
- f.write(report["content"])
+ from ..security.file_write_verifier import write_file_verified
+
+ write_file_verified(
+ output_file,
+ report["content"],
+ "api.allow_file_output",
+ context="API research report",
+ )
logger.info(f"Report saved to {output_file}")
report["file_path"] = output_file
return report
@@ -606,20 +612,26 @@ def analyze_documents(
# Save to file if requested
if output_file:
- with open(output_file, "w", encoding="utf-8") as f:
- f.write(f"# Document Analysis: {query}\n\n")
- f.write(f"## Summary\n\n{summary}\n\n")
- f.write(f"## Documents Found: {len(results)}\n\n")
-
- for i, doc in enumerate(results):
- f.write(
- f"### Document {i + 1}: {doc.get('title', 'Untitled')}\n\n"
- )
- f.write(f"**Source:** {doc.get('link', 'Unknown')}\n\n")
- f.write(
- f"**Content:**\n\n{doc.get('content', doc.get('snippet', 'No content available'))[:1000]}...\n\n"
- )
- f.write("---\n\n")
+ from ..security.file_write_verifier import write_file_verified
+
+ content = f"# Document Analysis: {query}\n\n"
+ content += f"## Summary\n\n{summary}\n\n"
+ content += f"## Documents Found: {len(results)}\n\n"
+
+ for i, doc in enumerate(results):
+ content += (
+ f"### Document {i + 1}: {doc.get('title', 'Untitled')}\n\n"
+ )
+ content += f"**Source:** {doc.get('link', 'Unknown')}\n\n"
+ content += f"**Content:**\n\n{doc.get('content', doc.get('snippet', 'No content available'))[:1000]}...\n\n"
+ content += "---\n\n"
+
+ write_file_verified(
+ output_file,
+ content,
+ "api.allow_file_output",
+ context="API document analysis",
+ )
analysis_result["file_path"] = output_file
logger.info(f"Analysis saved to {output_file}")
diff --git a/src/local_deep_research/benchmarks/benchmark_functions.py b/src/local_deep_research/benchmarks/benchmark_functions.py
index c7af62330f..a0f365fbea 100644
--- a/src/local_deep_research/benchmarks/benchmark_functions.py
+++ b/src/local_deep_research/benchmarks/benchmark_functions.py
@@ -396,40 +396,45 @@ def compare_configurations(
# Generate comparison report
import time
+ from ..security.file_write_verifier import write_file_verified
+
timestamp = time.strftime("%Y%m%d_%H%M%S")
report_file = str(
Path(output_dir) / f"comparison_{dataset_type}_{timestamp}.md"
)
- with open(report_file, "w") as f:
- f.write(f"# Configuration Comparison - {dataset_type.capitalize()}\n\n")
+ # Build report content
+ content = f"# Configuration Comparison - {dataset_type.capitalize()}\n\n"
- # Write summary table
- f.write("## Summary\n\n")
- f.write("| Configuration | Accuracy | Avg. Time | Examples |\n")
- f.write("|---------------|----------|-----------|----------|\n")
+ # Write summary table
+ content += "## Summary\n\n"
+ content += "| Configuration | Accuracy | Avg. Time | Examples |\n"
+ content += "|---------------|----------|-----------|----------|\n"
- for result in results:
- accuracy = result.get("metrics", {}).get("accuracy", 0)
- avg_time = result.get("metrics", {}).get(
- "average_processing_time", 0
- )
- examples = result.get("total_examples", 0)
+ for result in results:
+ accuracy = result.get("metrics", {}).get("accuracy", 0)
+ avg_time = result.get("metrics", {}).get("average_processing_time", 0)
+ examples = result.get("total_examples", 0)
- f.write(
- f"| {result['configuration_name']} | {accuracy:.3f} | {avg_time:.2f}s | {examples} |\n"
- )
+ content += f"| {result['configuration_name']} | {accuracy:.3f} | {avg_time:.2f}s | {examples} |\n"
- f.write("\n## Configuration Details\n\n")
+ content += "\n## Configuration Details\n\n"
- for result in results:
- f.write(f"### {result['configuration_name']}\n\n")
+ for result in results:
+ content += f"### {result['configuration_name']}\n\n"
- config = result.get("search_config", {})
- f.write("```\n")
- for key, value in config.items():
- f.write(f"{key}: {value}\n")
- f.write("```\n\n")
+ config = result.get("search_config", {})
+ content += "```\n"
+ for key, value in config.items():
+ content += f"{key}: {value}\n"
+ content += "```\n\n"
+
+ write_file_verified(
+ report_file,
+ content,
+ "benchmark.allow_file_output",
+ context="benchmark comparison report",
+ )
logger.info(f"Comparison report saved to {report_file}")
diff --git a/src/local_deep_research/benchmarks/cli.py b/src/local_deep_research/benchmarks/cli.py
index 6aab827eb2..ec9d732661 100644
--- a/src/local_deep_research/benchmarks/cli.py
+++ b/src/local_deep_research/benchmarks/cli.py
@@ -228,7 +228,6 @@ def run_comparison(args):
def run_profiling(args):
"""Run resource profiling."""
- import json
from local_deep_research.config.llm_config import get_llm
from local_deep_research.config.search_config import get_search
@@ -310,34 +309,36 @@ def run_profiling(args):
print(f"Average CPU: {resource_results.get('process_cpu_avg', 0):.1f}%")
# Save results
+ from ..security.file_write_verifier import write_json_verified
+
timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")
results_file = str(
Path(args.output_dir) / f"profiling_results_{timestamp}.json"
)
- with open(results_file, "w") as f:
- json.dump(
- {
- "query": args.query,
- "configuration": {
- "model": args.model,
- "provider": args.provider,
- "search_tool": args.search_tool,
- "iterations": args.iterations,
- "questions_per_iteration": args.questions,
- "strategy": args.strategy,
- },
- "timing_results": timing_results,
- "resource_results": resource_results,
- "findings_count": len(results.get("findings", [])),
- "knowledge_length": len(
- results.get("current_knowledge", "")
- ),
- "timestamp": timestamp,
- },
- f,
- indent=2,
- )
+ results_data = {
+ "query": args.query,
+ "configuration": {
+ "model": args.model,
+ "provider": args.provider,
+ "search_tool": args.search_tool,
+ "iterations": args.iterations,
+ "questions_per_iteration": args.questions,
+ "strategy": args.strategy,
+ },
+ "timing_results": timing_results,
+ "resource_results": resource_results,
+ "findings_count": len(results.get("findings", [])),
+ "knowledge_length": len(results.get("current_knowledge", "")),
+ "timestamp": timestamp,
+ }
+
+ write_json_verified(
+ results_file,
+ results_data,
+ "benchmark.allow_file_output",
+ context="profiling results",
+ )
print(f"\nDetailed results saved to: {results_file}")
diff --git a/src/local_deep_research/benchmarks/comparison/evaluator.py b/src/local_deep_research/benchmarks/comparison/evaluator.py
index a19161410a..d187220426 100644
--- a/src/local_deep_research/benchmarks/comparison/evaluator.py
+++ b/src/local_deep_research/benchmarks/comparison/evaluator.py
@@ -5,7 +5,6 @@ This module provides functions for comparing different parameter configurations
and evaluating their performance across various metrics.
"""
-import json
import os
from datetime import datetime, UTC
from pathlib import Path
@@ -185,11 +184,17 @@ def compare_configurations(
}
# Save results to file
+ from ...security.file_write_verifier import write_json_verified
+
timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")
result_file = str(Path(output_dir) / f"comparison_results_{timestamp}.json")
- with open(result_file, "w") as f:
- json.dump(comparison_report, f, indent=2)
+ write_json_verified(
+ result_file,
+ comparison_report,
+ "benchmark.allow_file_output",
+ context="comparison results",
+ )
# Generate visualizations
visualizations_dir = Path(output_dir) / "visualizations"
diff --git a/src/local_deep_research/benchmarks/comparison/results.py b/src/local_deep_research/benchmarks/comparison/results.py
index 54a8a6c561..7c8b93cb1c 100644
--- a/src/local_deep_research/benchmarks/comparison/results.py
+++ b/src/local_deep_research/benchmarks/comparison/results.py
@@ -68,5 +68,11 @@ class Benchmark_results:
def _save_results(self):
# Save results to file.
- with open(self.results_file, "w") as f:
- json.dump(self.results, f, indent=2)
+ from ...security.file_write_verifier import write_json_verified
+
+ write_json_verified(
+ self.results_file,
+ self.results,
+ "benchmark.allow_file_output",
+ context="benchmark results",
+ )
diff --git a/src/local_deep_research/benchmarks/metrics/reporting.py b/src/local_deep_research/benchmarks/metrics/reporting.py
index ac4086343e..39051d091e 100644
--- a/src/local_deep_research/benchmarks/metrics/reporting.py
+++ b/src/local_deep_research/benchmarks/metrics/reporting.py
@@ -154,8 +154,15 @@ def generate_report(
)
# Write report to file
- with open(output_file, "w") as f:
- f.write("\n".join(report))
+ from ...security.file_write_verifier import write_file_verified
+
+ content = "\n".join(report)
+ write_file_verified(
+ output_file,
+ content,
+ "benchmark.allow_file_output",
+ context="benchmark report",
+ )
logger.info(f"Report saved to {output_file}")
return output_file
diff --git a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
index b5d52c8e55..9e36fd238c 100644
--- a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
+++ b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
@@ -6,7 +6,6 @@ to find optimal parameters for the research system, balancing quality
and performance metrics.
"""
-import json
import os
from pathlib import Path
import time
@@ -506,27 +505,34 @@ class OptunaOptimizer:
timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")
# Save trial history
+ from ...security.file_write_verifier import write_json_verified
+
history_file = str(
Path(self.output_dir) / f"{self.study_name}_history.json"
)
- with open(history_file, "w") as f:
- # Convert numpy values to native Python types for JSON serialization
- clean_history = []
- for trial in self.trials_history:
- clean_trial = {}
- for k, v in trial.items():
- if isinstance(v, dict):
- clean_trial[k] = {
- dk: (float(dv) if isinstance(dv, np.number) else dv)
- for dk, dv in v.items()
- }
- elif isinstance(v, np.number):
- clean_trial[k] = float(v)
- else:
- clean_trial[k] = v
- clean_history.append(clean_trial)
-
- json.dump(clean_history, f, indent=2)
+
+ # Convert numpy values to native Python types for JSON serialization
+ clean_history = []
+ for trial in self.trials_history:
+ clean_trial = {}
+ for k, v in trial.items():
+ if isinstance(v, dict):
+ clean_trial[k] = {
+ dk: (float(dv) if isinstance(dv, np.number) else dv)
+ for dk, dv in v.items()
+ }
+ elif isinstance(v, np.number):
+ clean_trial[k] = float(v)
+ else:
+ clean_trial[k] = v
+ clean_history.append(clean_trial)
+
+ write_json_verified(
+ history_file,
+ clean_history,
+ "benchmark.allow_file_output",
+ context="optimization history",
+ )
# Save current best parameters
if (
@@ -537,23 +543,26 @@ class OptunaOptimizer:
best_params_file = str(
Path(self.output_dir) / f"{self.study_name}_best_params.json"
)
- with open(best_params_file, "w") as f:
- json.dump(
- {
- "best_params": self.study.best_params,
- "best_value": float(self.study.best_value),
- "n_trials": len(self.study.trials),
- "timestamp": timestamp,
- "base_query": self.base_query,
- "model_name": self.model_name,
- "provider": self.provider,
- "search_tool": self.search_tool,
- "metric_weights": self.metric_weights,
- "benchmark_weights": self.benchmark_weights,
- },
- f,
- indent=2,
- )
+
+ best_params_data = {
+ "best_params": self.study.best_params,
+ "best_value": float(self.study.best_value),
+ "n_trials": len(self.study.trials),
+ "timestamp": timestamp,
+ "base_query": self.base_query,
+ "model_name": self.model_name,
+ "provider": self.provider,
+ "search_tool": self.search_tool,
+ "metric_weights": self.metric_weights,
+ "benchmark_weights": self.benchmark_weights,
+ }
+
+ write_json_verified(
+ best_params_file,
+ best_params_data,
+ "benchmark.allow_file_output",
+ context="optimization best params",
+ )
# Save the Optuna study
if self.study:
diff --git a/src/local_deep_research/benchmarks/runners.py b/src/local_deep_research/benchmarks/runners.py
index a2ecaf6919..aa2a6a01d2 100644
--- a/src/local_deep_research/benchmarks/runners.py
+++ b/src/local_deep_research/benchmarks/runners.py
@@ -345,10 +345,18 @@ def run_benchmark(
interactive=True,
)
else:
+ from ..security.file_write_verifier import (
+ write_file_verified,
+ )
+
logger.info("Skipping evaluation due to error.")
# Create an empty evaluation file to prevent issues
- with open(evaluation_file, "w") as f:
- f.write("")
+ write_file_verified(
+ evaluation_file,
+ "",
+ "benchmark.allow_file_output",
+ context="empty evaluation placeholder",
+ )
return {
"status": "evaluation_error",
diff --git a/src/local_deep_research/security/file_write_verifier.py b/src/local_deep_research/security/file_write_verifier.py
new file mode 100644
index 0000000000..44681ee86d
--- /dev/null
+++ b/src/local_deep_research/security/file_write_verifier.py
@@ -0,0 +1,113 @@
+"""Security module for verified file write operations.
+
+This module ensures that file writes only occur when explicitly allowed by configuration,
+maintaining the encryption-at-rest security model.
+"""
+
+import json
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+
+class FileWriteSecurityError(Exception):
+ """Raised when a file write operation is not allowed by security settings."""
+
+ pass
+
+
+def write_file_verified(
+ filepath: str | Path,
+ content: str,
+ setting_name: str,
+ required_value: Any = True,
+ context: str = "",
+ mode: str = "w",
+ encoding: str = "utf-8",
+) -> None:
+ """Write content to a file only if security settings allow it.
+
+ Args:
+ filepath: Path to the file to write
+ content: Content to write to the file
+ setting_name: Configuration setting name to check (e.g., "api.allow_file_output")
+ required_value: Required value for the setting (default: True)
+ context: Description of what's being written (for error messages)
+ mode: File open mode (default: "w")
+ encoding: File encoding (default: "utf-8")
+
+ Raises:
+ FileWriteSecurityError: If the security setting doesn't match required value
+
+ Example:
+ >>> write_file_verified(
+ ... "report.md",
+ ... markdown_content,
+ ... "api.allow_file_output",
+ ... context="API research report"
+ ... )
+ """
+ from ..config.search_config import get_setting_from_snapshot
+
+ try:
+ actual_value = get_setting_from_snapshot(setting_name)
+ except Exception:
+ # Setting doesn't exist - default deny
+ actual_value = None
+
+ if actual_value != required_value:
+ error_msg = (
+ f"File write not allowed: {context or 'file operation'}. "
+ f"Set '{setting_name}={required_value}' in config to enable this feature."
+ )
+ logger.warning(error_msg)
+ raise FileWriteSecurityError(error_msg)
+
+ with open(filepath, mode, encoding=encoding) as f:
+ f.write(content)
+
+ logger.debug(
+ f"Verified file write: {filepath} (setting: {setting_name}={required_value})"
+ )
+
+
+def write_json_verified(
+ filepath: str | Path,
+ data: dict | list,
+ setting_name: str,
+ required_value: Any = True,
+ context: str = "",
+ indent: int = 2,
+) -> None:
+ """Write JSON data to a file only if security settings allow it.
+
+ Args:
+ filepath: Path to the file to write
+ data: Dictionary or list to serialize as JSON
+ setting_name: Configuration setting name to check
+ required_value: Required value for the setting (default: True)
+ context: Description of what's being written (for error messages)
+ indent: JSON indentation (default: 2)
+
+ Raises:
+ FileWriteSecurityError: If the security setting doesn't match required value
+
+ Example:
+ >>> write_json_verified(
+ ... "results.json",
+ ... {"accuracy": 0.95},
+ ... "benchmark.allow_file_output",
+ ... context="benchmark results"
+ ... )
+ """
+ content = json.dumps(data, indent=indent)
+ write_file_verified(
+ filepath,
+ content,
+ setting_name,
+ required_value,
+ context,
+ mode="w",
+ encoding="utf-8",
+ )
diff --git a/src/local_deep_research/storage/base.py b/src/local_deep_research/storage/base.py
index 809d8fbf12..649b8d4976 100644
--- a/src/local_deep_research/storage/base.py
+++ b/src/local_deep_research/storage/base.py
@@ -94,7 +94,9 @@ class ReportStorage(ABC):
) -> Optional[Path]:
"""Get report content as a temporary file.
- This is useful for export operations that need a file path.
+ WARNING: This creates an UNENCRYPTED temporary file on disk.
+ This method is deprecated and should be avoided. Use in-memory
+ export operations instead (see export_report_to_memory).
Args:
research_id: Unique identifier for the research
@@ -104,16 +106,27 @@ class ReportStorage(ABC):
Path to temporary file if successful, None otherwise
"""
import tempfile
+ from ..security.file_write_verifier import write_file_verified
content = self.get_report(research_id, username)
if not content:
return None
try:
- with tempfile.NamedTemporaryFile(
+ # Create temp file path
+ tmp_file = tempfile.NamedTemporaryFile(
mode="w", suffix=".md", delete=False, encoding="utf-8"
- ) as tmp_file:
- tmp_file.write(content)
- return Path(tmp_file.name)
+ )
+ tmp_path = Path(tmp_file.name)
+ tmp_file.close()
+
+ # Write with verification
+ write_file_verified(
+ tmp_path,
+ content,
+ "storage.allow_temp_file_export",
+ context="temporary file export (UNENCRYPTED)",
+ )
+ return tmp_path
except Exception:
return None
diff --git a/src/local_deep_research/storage/file.py b/src/local_deep_research/storage/file.py
index 3d0ebe906c..f0a9a74941 100644
--- a/src/local_deep_research/storage/file.py
+++ b/src/local_deep_research/storage/file.py
@@ -38,19 +38,30 @@ class FileReportStorage(ReportStorage):
) -> bool:
"""Save report to file."""
try:
+ from ..security.file_write_verifier import (
+ write_file_verified,
+ write_json_verified,
+ )
+
report_path = self._get_report_path(research_id)
# Save content
- with open(report_path, "w", encoding="utf-8") as f:
- f.write(content)
+ write_file_verified(
+ report_path,
+ content,
+ "storage.allow_file_backup",
+ context="file storage backup",
+ )
# Save metadata if provided
if metadata:
- import json
-
metadata_path = self._get_metadata_path(research_id)
- with open(metadata_path, "w", encoding="utf-8") as f:
- json.dump(metadata, f, indent=2)
+ write_json_verified(
+ metadata_path,
+ metadata,
+ "storage.allow_file_backup",
+ context="file storage metadata",
+ )
logger.info(
f"Saved report for research {research_id} to {report_path}"
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 9848767dbb..2427cbe265 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -968,14 +968,20 @@ def save_raw_config():
)
try:
+ from ...security.file_write_verifier import write_file_verified
+
# Get the config file path
config_dir = Path.home() / ".local_deep_research"
config_dir.mkdir(parents=True, exist_ok=True)
config_path = config_dir / "config.toml"
# Write the configuration to file
- with open(config_path, "w", encoding="utf-8") as f:
- f.write(raw_config)
+ write_file_verified(
+ config_path,
+ raw_config,
+ "system.allow_config_write",
+ context="system configuration file",
+ )
return jsonify({"success": True})
except Exception: