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.

fix: pass Blueprint objects to csrf.exempt() so API routes are actually CSRF-exempt (#2222)

LearningCircuitf13e7dade422
diff --git a/src/local_deep_research/news/flask_api.py b/src/local_deep_research/news/flask_api.py
index 8fa3232672..c47f4ca1cd 100644
--- a/src/local_deep_research/news/flask_api.py
+++ b/src/local_deep_research/news/flask_api.py
@@ -561,12 +561,12 @@ def run_subscription_now(subscription_id: str) -> Dict[str, Any]:
if subscription.get("custom_endpoint"):
request_data["custom_endpoint"] = subscription["custom_endpoint"]
- # Call the main research API endpoint (use the one from research blueprint)
+ # Call the CSRF-exempt research API endpoint (api_bp at /research/api)
# Use request.host_url to get the actual URL the server is responding on
base_url = request.host_url.rstrip("/")
response = safe_post(
- f"{base_url}/research/api/start_research",
+ f"{base_url}/research/api/start",
json=request_data,
headers={"Content-Type": "application/json"},
allow_localhost=True,
@@ -1066,7 +1066,7 @@ def check_overdue_subscriptions():
session_cookie = request.cookies.get("session")
response = safe_post(
- f"{base_url}/research/api/start_research",
+ f"{base_url}/research/api/start",
json=request_data,
headers={
"Content-Type": "application/json",
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 900fc4ce33..f564a5b12a 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -320,16 +320,8 @@ def create_app():
# This is necessary because Flask's session cookies are set AFTER after_request handlers
# The middleware wrapping happens below near ProxyFix
- # Disable CSRF for API routes
- @app.before_request
- def disable_csrf_for_api():
- if (
- request.path.startswith("/api/v1/")
- or request.path.startswith("/research/api/")
- or request.path.startswith("/benchmark/api/")
- ):
- # Mark this request as exempt from CSRF
- request.environ["csrf_exempt"] = True
+ # Note: CSRF exemptions for API blueprints are applied after blueprint
+ # registration below (search for "CSRF exemptions" in this file).
# Database configuration - Using per-user databases now
# No shared database configuration needed
@@ -718,18 +710,16 @@ def register_blueprints(app):
app.register_blueprint(scheduler_bp)
logger.info("Document Scheduler routes registered successfully")
- # After registration, update CSRF exemptions
+ # CSRF exemptions — Flask-WTF requires Blueprint objects (not strings)
+ # to populate _exempt_blueprints. Passing strings only populates
+ # _exempt_views, which compares against module-qualified names and
+ # silently fails to match Flask endpoint names.
if hasattr(app, "extensions") and "csrf" in app.extensions:
csrf = app.extensions["csrf"]
- # Exempt the API blueprint routes by actual endpoints
- csrf.exempt("api_v1")
- csrf.exempt("api")
- for rule in app.url_map.iter_rules():
- if rule.endpoint and (
- rule.endpoint.startswith("api_v1.")
- or rule.endpoint.startswith("api.")
- ):
- csrf.exempt(rule.endpoint)
+ for bp_name in ("api_v1", "api", "benchmark"):
+ bp_obj = app.blueprints.get(bp_name)
+ if bp_obj is not None:
+ csrf.exempt(bp_obj)
# Add favicon route
# Exempt favicon from rate limiting
diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.js
index bd0a5f7a79..b8bcba0575 100644
--- a/src/local_deep_research/web/static/js/pages/news.js
+++ b/src/local_deep_research/web/static/js/pages/news.js
@@ -399,7 +399,7 @@ async function performAdvancedNewsSearch(query, strategy = 'source-based', model
SafeLogger.log('Sending research request:', requestData);
- const response = await fetch('/research/api/start_research', {
+ const response = await fetch('/api/start_research', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
diff --git a/tests/api_tests/test_csrf_header.py b/tests/api_tests/test_csrf_header.py
index b44470af4a..42c3052b09 100644
--- a/tests/api_tests/test_csrf_header.py
+++ b/tests/api_tests/test_csrf_header.py
@@ -58,3 +58,21 @@ class TestCSRFHeader:
# Research API should also work
response = authenticated_client.get("/research/api/history")
assert response.status_code in [200, 404] # 404 if no history yet
+
+ def test_csrf_blueprint_exemptions_configured(self, app):
+ """Test that API blueprints are properly CSRF-exempt via Blueprint objects.
+
+ Flask-WTF 1.2.2 requires Blueprint objects (not strings) in
+ _exempt_blueprints. Passing strings only populates _exempt_views,
+ which silently fails to match. This test catches regressions from
+ Flask-WTF upgrades or accidental changes to the exemption logic.
+ """
+ csrf = app.extensions.get("csrf")
+ assert csrf is not None, "CSRFProtect extension not initialized"
+
+ exempt_names = {bp.name for bp in csrf._exempt_blueprints}
+ for expected in ("api_v1", "api", "benchmark"):
+ assert expected in exempt_names, (
+ f"Blueprint '{expected}' missing from _exempt_blueprints. "
+ f"Ensure csrf.exempt() receives the Blueprint object, not a string."
+ )