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: enforce API authentication and narrow CSRF exemptions (#1957)

LearningCircuit29fd4728ff68
diff --git a/src/local_deep_research/web/api.py b/src/local_deep_research/web/api.py
index a285525b5b..89ef2d4c47 100644
--- a/src/local_deep_research/web/api.py
+++ b/src/local_deep_research/web/api.py
@@ -41,6 +41,9 @@ def api_access_control(f):
else session.get("username")
)
+ if not username:
+ return jsonify({"error": "Authentication required"}), 401
+
# Check if API is enabled
api_enabled = True # Default to enabled
rate_limit = DEFAULT_RATE_LIMIT
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 28819bf691..ec7faa93f1 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -723,7 +723,10 @@ def register_blueprints(app):
# silently fails to match Flask endpoint names.
if hasattr(app, "extensions") and "csrf" in app.extensions:
csrf = app.extensions["csrf"]
- for bp_name in ("api_v1", "api", "benchmark", "research"):
+ # Only api_v1 is exempt: it's a programmatic REST API used by
+ # external clients. The api, benchmark, and research blueprints
+ # are browser-facing and the frontend already sends CSRF tokens.
+ for bp_name in ("api_v1",):
bp_obj = app.blueprints.get(bp_name)
if bp_obj is not None:
csrf.exempt(bp_obj)
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index f7e346e1f5..75df28b48e 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -99,8 +99,12 @@
// Fallback implementation
try {
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const response = await fetch(`/api/delete/${researchId}`, {
- method: 'DELETE'
+ method: 'DELETE',
+ headers: {
+ ...(csrfToken ? { 'X-CSRFToken': csrfToken } : {})
+ }
});
if (!response.ok) {
throw new Error(`API Error: ${response.status} ${response.statusText}`);
@@ -119,10 +123,12 @@
// Fallback implementation
try {
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const response = await fetch(URLS.API.CLEAR_HISTORY, {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ ...(csrfToken ? { 'X-CSRFToken': csrfToken } : {})
},
body: JSON.stringify({})
});
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index 4e15690ff6..7792b4b6da 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -3058,6 +3058,12 @@
form.method = 'POST';
form.action = "/api/open_file_location";
+ const csrfInput = document.createElement('input');
+ csrfInput.type = 'hidden';
+ csrfInput.name = 'csrf_token';
+ csrfInput.value = getCsrfToken();
+ form.appendChild(csrfInput);
+
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'file_path';
diff --git a/tests/api_tests/test_csrf_header.py b/tests/api_tests/test_csrf_header.py
index 42c3052b09..bb906e77a3 100644
--- a/tests/api_tests/test_csrf_header.py
+++ b/tests/api_tests/test_csrf_header.py
@@ -60,19 +60,28 @@ class TestCSRFHeader:
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.
+ """Test that only api_v1 blueprint is CSRF-exempt.
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.
+ _exempt_blueprints. Only api_v1 should be exempt — the browser-facing
+ blueprints (api, benchmark, research) should require CSRF tokens since
+ the frontend already sends them.
"""
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."
+
+ # api_v1 should be exempt (programmatic REST API)
+ assert "api_v1" in exempt_names, (
+ "Blueprint 'api_v1' missing from _exempt_blueprints. "
+ "Ensure csrf.exempt() receives the Blueprint object, not a string."
+ )
+
+ # Browser-facing blueprints should NOT be exempt
+ for should_not_be_exempt in ("api", "benchmark", "research"):
+ assert should_not_be_exempt not in exempt_names, (
+ f"Blueprint '{should_not_be_exempt}' should not be in "
+ f"_exempt_blueprints — it is browser-facing and the frontend "
+ f"already sends CSRF tokens."
)
diff --git a/tests/api_tests/test_rest_api.py b/tests/api_tests/test_rest_api.py
index 89125ac009..a6b2082b05 100644
--- a/tests/api_tests/test_rest_api.py
+++ b/tests/api_tests/test_rest_api.py
@@ -23,9 +23,9 @@ class TestRestAPI:
assert "timestamp" in data
print("✅ Health check passed")
- def test_api_documentation(self, client):
- """Test the API documentation endpoint."""
- response = client.get("/api/v1/")
+ def test_api_documentation(self, authenticated_client):
+ """Test the API documentation endpoint (requires auth)."""
+ response = authenticated_client.get("/api/v1/")
assert response.status_code == 200
data = json.loads(response.data)
diff --git a/tests/api_tests/test_rest_api_simple.py b/tests/api_tests/test_rest_api_simple.py
index 3695873108..59b12596c1 100644
--- a/tests/api_tests/test_rest_api_simple.py
+++ b/tests/api_tests/test_rest_api_simple.py
@@ -13,19 +13,19 @@ RESEARCH_TIMEOUT = 120 # 2 minutes
class TestRestAPISimple:
"""Simple REST API tests."""
- def test_health_and_docs(self, client):
+ def test_health_and_docs(self, authenticated_client):
"""Test basic non-research endpoints."""
print("🔍 Testing health and documentation endpoints...")
# Health check
- response = client.get("/api/v1/health")
+ response = authenticated_client.get("/api/v1/health")
assert response.status_code == 200
data = json.loads(response.data)
assert data["status"] == "ok"
print("✅ Health check passed")
- # API documentation
- response = client.get("/api/v1/")
+ # API documentation (requires auth)
+ response = authenticated_client.get("/api/v1/")
assert response.status_code == 200
data = json.loads(response.data)
assert data["api_version"] == "v1"
diff --git a/tests/security/test_api_security.py b/tests/security/test_api_security.py
index bc51ea0ccc..d723dec5fe 100644
--- a/tests/security/test_api_security.py
+++ b/tests/security/test_api_security.py
@@ -123,7 +123,7 @@ class TestAPISecurityOWASPTop10:
# Should have request size limit (413 Payload Too Large)
# Or validate query length (400/422)
# Current implementation may return 500 for edge cases
- assert response.status_code in [200, 400, 413, 422, 500]
+ assert response.status_code in [200, 400, 401, 413, 422, 500]
# Test rate limiting (if implemented)
# Make many requests rapidly
@@ -152,8 +152,8 @@ class TestAPISecurityOWASPTop10:
for endpoint in admin_endpoints:
response = client.get(endpoint)
- # Should return 403 Forbidden or 404 Not Found
- assert response.status_code in [403, 404]
+ # Should return 401 Unauthorized, 403 Forbidden, or 404 Not Found
+ assert response.status_code in [401, 403, 404]
# API6:2023 - Unrestricted Access to Sensitive Business Flows
@pytest.mark.skip(reason="documentation/placeholder test - not implemented")
@@ -233,7 +233,8 @@ class TestAPISecurityOWASPTop10:
# Test error responses don't leak sensitive info
response = client.get("/api/v1/nonexistent")
# Should return generic error, not stack trace
- assert response.status_code == 404
+ # 401 is also acceptable (auth guard rejects before routing)
+ assert response.status_code in [401, 404]
# API9:2023 - Improper Inventory Management
@pytest.mark.skip(reason="documentation/placeholder test - not implemented")
@@ -304,8 +305,8 @@ class TestAPIInputValidation:
content_type="application/json",
)
- # Should return 400 Bad Request
- assert response.status_code in [400, 422]
+ # Should return 400 Bad Request (or 401 if auth guard rejects first)
+ assert response.status_code in [400, 401, 422]
def test_missing_required_fields_rejected(self, client):
"""Test that requests with missing required fields are rejected."""
@@ -317,7 +318,8 @@ class TestAPIInputValidation:
)
# Should return 400 Bad Request or 422 Unprocessable Entity
- assert response.status_code in [400, 422]
+ # 401 is also valid (auth guard rejects unauthenticated requests)
+ assert response.status_code in [400, 401, 422]
def test_invalid_data_types_rejected(self, client):
"""Test that invalid data types are rejected."""
@@ -329,7 +331,8 @@ class TestAPIInputValidation:
)
# Should validate data types and reject non-string query
- assert response.status_code in [400, 422]
+ # 401 is also valid (auth guard rejects unauthenticated requests)
+ assert response.status_code in [400, 401, 422]
def test_boundary_value_validation(self, client):
"""Test validation of boundary values."""
@@ -347,8 +350,8 @@ class TestAPIInputValidation:
)
# Should validate and reject invalid inputs (400/422)
- # Current implementation may return 500 for edge cases
- assert response.status_code in [200, 400, 422, 500]
+ # 401 is also valid (auth guard rejects unauthenticated requests)
+ assert response.status_code in [200, 400, 401, 422, 500]
class TestAPIRateLimiting:
diff --git a/tests/security/test_api_v1_auth.py b/tests/security/test_api_v1_auth.py
new file mode 100644
index 0000000000..51df8b4074
--- /dev/null
+++ b/tests/security/test_api_v1_auth.py
@@ -0,0 +1,38 @@
+"""Test API v1 authentication guard."""
+
+
+class TestApiV1Auth:
+ """Test that /api/v1/ endpoints require authentication."""
+
+ def test_unauthenticated_returns_401(self, client):
+ """Requests with no username (no g.current_user, no session) get 401."""
+ response = client.get("/api/v1/")
+ assert response.status_code == 401
+ data = response.get_json()
+ assert data["error"] == "Authentication required"
+
+ def test_empty_username_returns_401(self, client, app):
+ """An empty string username should still be rejected."""
+ with client.session_transaction() as sess:
+ sess["username"] = ""
+ response = client.get("/api/v1/")
+ assert response.status_code == 401
+
+ def test_authenticated_via_g_current_user(self, authenticated_client):
+ """A request with g.current_user set passes the auth guard."""
+ response = authenticated_client.get("/api/v1/")
+ # Should not be 401 — may be 200 or other status depending on
+ # downstream logic, but the auth guard itself should pass.
+ assert response.status_code != 401
+
+ def test_authenticated_via_session(self, authenticated_client):
+ """A request with a valid session username passes the auth guard."""
+ # authenticated_client already has a registered user in the session
+ response = authenticated_client.get("/api/v1/")
+ assert response.status_code != 401
+
+ def test_health_endpoint_no_auth_required(self, client):
+ """The /api/v1/health endpoint does not use @api_access_control."""
+ response = client.get("/api/v1/health")
+ # Health should return 200 even without authentication
+ assert response.status_code == 200
diff --git a/tests/security/test_csrf_hardening.py b/tests/security/test_csrf_hardening.py
new file mode 100644
index 0000000000..68a2e03f71
--- /dev/null
+++ b/tests/security/test_csrf_hardening.py
@@ -0,0 +1,30 @@
+"""Test CSRF hardening configuration against the real app."""
+
+
+class TestCsrfHardening:
+ """Verify CSRF exemptions are narrowly scoped."""
+
+ def test_api_v1_is_csrf_exempt(self, app):
+ """api_v1 blueprint should be CSRF-exempt (programmatic REST API)."""
+ csrf = app.extensions.get("csrf")
+ assert csrf is not None, "CSRFProtect extension not initialized"
+ exempt_names = {bp.name for bp in csrf._exempt_blueprints}
+ assert "api_v1" in exempt_names
+
+ def test_api_blueprint_not_exempt(self, app):
+ """api blueprint (browser-facing) should require CSRF tokens."""
+ csrf = app.extensions["csrf"]
+ exempt_names = {bp.name for bp in csrf._exempt_blueprints}
+ assert "api" not in exempt_names
+
+ def test_benchmark_blueprint_not_exempt(self, app):
+ """benchmark blueprint (browser-facing) should require CSRF tokens."""
+ csrf = app.extensions["csrf"]
+ exempt_names = {bp.name for bp in csrf._exempt_blueprints}
+ assert "benchmark" not in exempt_names
+
+ def test_research_blueprint_not_exempt(self, app):
+ """research blueprint (browser-facing) should require CSRF tokens."""
+ csrf = app.extensions["csrf"]
+ exempt_names = {bp.name for bp in csrf._exempt_blueprints}
+ assert "research" not in exempt_names