~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(auth): return JSON 401 for nested API blueprints + tests for #3129 (#3678)
LearningCircuita395f8560131
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex a3e114398f..e63289f2ec 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -908,24 +908,23 @@ def register_blueprints(app):def register_error_handlers(app):"""Register error handlers with the Flask app."""+ from .auth.decorators import _is_api_path@app.errorhandler(404)def not_found(error):- if request.path.startswith("/api/"):+ if _is_api_path(request.path):return make_response(jsonify({"error": "Not found"}), 404)return make_response("Not found", 404)@app.errorhandler(500)def server_error(error):- if request.path.startswith("/api/"):+ if _is_api_path(request.path):return make_response(jsonify({"error": "Server error"}), 500)return make_response("Server error", 500)@app.errorhandler(401)def handle_unauthorized(error):- if request.path.startswith("/api/") or request.path.startswith(- "/settings/api/"- ):+ if _is_api_path(request.path):return make_response(jsonify({"error": "Authentication required"}),401,@@ -936,7 +935,7 @@ def register_error_handlers(app):@app.errorhandler(413)def handle_request_too_large(error):- if request.path.startswith("/api/"):+ if _is_api_path(request.path):return make_response(jsonify({"error": "Request too large"}),413,diff --git a/src/local_deep_research/web/auth/decorators.py b/src/local_deep_research/web/auth/decorators.pyindex 0f4b9fd466..81539c3104 100644--- a/src/local_deep_research/web/auth/decorators.py+++ b/src/local_deep_research/web/auth/decorators.py@@ -29,6 +29,20 @@ def _safe_redirect_to_login():return redirect(url_for("auth.login"))+def _is_api_path(path: str) -> bool:+ """Detect API request paths that should receive JSON, not HTML redirects.++ Matches `/api/` anywhere in the path (so nested API blueprints like+ `/news/api/...` and `/library/api/...` work, not just top-level+ `/api/...`), and also paths that end in `/api` with no further+ segments (e.g. `/settings/api`, `/history/api` are JSON endpoints).++ The `api` segment must be slash-bounded — non-API paths like+ `/apidocs` or `/openapi.json` are not matched.+ """+ return "/api/" in path or path.endswith("/api")++def login_required(f):"""Decorator to require authentication for a route.@@ -41,10 +55,7 @@ def login_required(f):logger.debug(f"Unauthenticated access attempt to {request.endpoint}")- # For API routes, return JSON error instead of redirect- if request.path.startswith("/api/") or request.path.startswith(- "/settings/api/"- ):+ if _is_api_path(request.path):return jsonify({"error": "Authentication required"}), 401return _safe_redirect_to_login()@@ -55,10 +66,7 @@ def login_required(f):logger.debug(f"No database connection for authenticated user {username}")- # For API routes, return JSON error instead of redirect- if request.path.startswith("/api/") or request.path.startswith(- "/settings/api/"- ):+ if _is_api_path(request.path):return jsonify({"error": "Database connection required"}), 401session.clear()return _safe_redirect_to_login()@@ -96,11 +104,7 @@ def inject_current_user():# Check connectivityif not db_manager.is_user_connected(g.current_user):# For API/auth routes, allow the request to continue- if (- request.path.startswith("/api/")- or request.path.startswith("/auth/")- or request.path.startswith("/settings/api/")- ):+ if _is_api_path(request.path) or request.path.startswith("/auth/"):logger.debug(f"No database for user {g.current_user} on API/auth route")diff --git a/tests/auth_tests/test_auth_integration.py b/tests/auth_tests/test_auth_integration.pyindex e192c8fd88..3bea48f26d 100644--- a/tests/auth_tests/test_auth_integration.py+++ b/tests/auth_tests/test_auth_integration.py@@ -228,18 +228,11 @@ class TestAuthIntegration:else:response = client.post(endpoint, json={})- # API endpoints return 401 instead of redirecting- # except for /settings/api, /history/api and /metrics/api/metrics which redirect- if endpoint in [- "/settings/api",- "/history/api",- "/metrics/api/metrics",- ]:- assert response.status_code == 302- assert "/auth/login" in response.location- else:- assert response.status_code == 401- assert response.get_json()["error"] == "Authentication required"+ # All these endpoints contain the slash-bounded `api` segment+ # (either /api/ in the middle or trailing /api), so the auth+ # decorator returns JSON 401 for unauthenticated callers.+ assert response.status_code == 401+ assert response.get_json()["error"] == "Authentication required"# Register and try againclient.post(diff --git a/tests/news/test_flask_api_deep_coverage.py b/tests/news/test_flask_api_deep_coverage.pyindex 011b768fa5..98f4d62490 100644--- a/tests/news/test_flask_api_deep_coverage.py+++ b/tests/news/test_flask_api_deep_coverage.py@@ -212,17 +212,11 @@ class TestGetNewsFeed:assert data["news_items"] == []def test_unauthenticated_is_blocked(self, client):- """Without session username, login_required prevents access."""- # The decorator calls _safe_redirect_to_login which needs the auth- # blueprint. We patch it to return a real Flask response.- from flask import Response-- with patch(- "local_deep_research.web.auth.decorators._safe_redirect_to_login",- return_value=Response("login required", status=302),- ):- resp = client.get("/news/api/feed")- assert resp.status_code == 302+ """Without session username, login_required returns JSON 401 for+ the /news/api/feed API endpoint."""+ resp = client.get("/news/api/feed")+ assert resp.status_code == 401+ assert resp.get_json()["error"] == "Authentication required"# ---------------------------------------------------------------------------diff --git a/tests/research_library/deletion/routes/test_delete_routes_http.py b/tests/research_library/deletion/routes/test_delete_routes_http.pyindex b4c4d4858b..aa72681817 100644--- a/tests/research_library/deletion/routes/test_delete_routes_http.py+++ b/tests/research_library/deletion/routes/test_delete_routes_http.py@@ -382,7 +382,7 @@ class TestUnauthenticatedRequests:):with app.test_client() as client:resp = client.delete("/library/api/document/doc-1")- assert resp.status_code == 302+ assert resp.status_code == 401def test_delete_collection_unauthenticated(self):app = _create_test_app()@@ -394,7 +394,7 @@ class TestUnauthenticatedRequests:):with app.test_client() as client:resp = client.delete("/library/api/collections/coll-1")- assert resp.status_code == 302+ assert resp.status_code == 401def test_bulk_delete_unauthenticated(self):app = _create_test_app()@@ -409,4 +409,4 @@ class TestUnauthenticatedRequests:"/library/api/documents/bulk",json={"document_ids": ["d1"]},)- assert resp.status_code == 302+ assert resp.status_code == 401diff --git a/tests/research_library/routes/test_library_routes_coverage.py b/tests/research_library/routes/test_library_routes_coverage.pyindex 165b667821..056681162e 100644--- a/tests/research_library/routes/test_library_routes_coverage.py+++ b/tests/research_library/routes/test_library_routes_coverage.py@@ -206,11 +206,12 @@ class TestUnauthenticatedAccess:resp = client.get("/library/")assert resp.status_code == 302- def test_api_stats_redirects(self, app):- """API routes under /library/api/ redirect (path starts with /library/ not /api/)."""+ def test_api_stats_returns_json_401(self, app):+ """API routes under /library/api/ return JSON 401 — the substring+ "/api/" is detected anywhere in the path, not just as a prefix."""client = self._unauthenticated_client(app)resp = client.get("/library/api/stats")- assert resp.status_code == 302+ assert resp.status_code == 401def test_download_manager_redirects(self, app):client = self._unauthenticated_client(app)@@ -222,10 +223,10 @@ class TestUnauthenticatedAccess:resp = client.get("/library/document/some-id")assert resp.status_code == 302- def test_download_single_resource_redirects(self, app):+ def test_download_single_resource_returns_json_401(self, app):client = self._unauthenticated_client(app)resp = client.post("/library/api/download/1")- assert resp.status_code == 302+ assert resp.status_code == 401# ---------------------------------------------------------------------------diff --git a/tests/security/test_login_required_boundaries.py b/tests/security/test_login_required_boundaries.pynew file mode 100644index 0000000000..37ec0afea2--- /dev/null+++ b/tests/security/test_login_required_boundaries.py@@ -0,0 +1,225 @@+"""+Tests verifying that ``@login_required`` rejects unauthenticated requests+correctly across the URL shapes the app actually exposes.++Guards two things:++* Page routes (e.g. ``/news/``, ``/news/subscriptions``) redirect+ unauthenticated callers to the login page.+* API routes — including nested blueprints like ``/news/api/...`` —+ return a JSON ``401`` instead of an HTML redirect. This is the+ regression case that motivated extending ``_is_api_path`` to match+ ``/api/`` anywhere in the path, not only as a top-level prefix.++The real news/research blueprints pull in heavy optional dependencies+(langchain, pdfplumber, etc.) and are exercised elsewhere. Here we only+care about the auth decorator's behavior at each URL shape, so we+register synthetic routes whose URL paths and decorator stacks mirror+production.+"""++from unittest.mock import patch++import pytest+from flask import Blueprint, Flask, jsonify++from local_deep_research.web.auth.decorators import login_required+++def app():+ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret-key"+ app.config["WTF_CSRF_ENABLED"] = False+ app.config["TESTING"] = True++ # Stub auth blueprint so url_for("auth.login") works for redirects.+ auth = Blueprint("auth", __name__)++ @auth.route("/login")+ def login():+ return "Login Page"++ app.register_blueprint(auth, url_prefix="/auth")++ # Mirror production: news_bp at /news with a nested news_api_bp at /api,+ # so the API surfaces at /news/api/... — same nesting that broke+ # JSON-vs-HTML detection before _is_api_path() used a substring match.+ news_bp = Blueprint("news", __name__)+ news_api_bp = Blueprint("news_api", __name__, url_prefix="/api")++ @news_bp.route("/")+ @login_required+ def news_page():+ return "News"++ @news_bp.route("/subscriptions")+ @login_required+ def subscriptions_page():+ return "Subscriptions"++ @news_bp.route("/subscriptions/new")+ @login_required+ def new_subscription_page():+ return "New"++ @news_bp.route("/subscriptions/<sid>/edit")+ @login_required+ def edit_subscription_page(sid):+ return f"Edit {sid}"++ @news_bp.route("/health")+ def news_health():+ return jsonify({"status": "ok"})++ @news_api_bp.route("/categories", methods=["GET"])+ @login_required+ def get_categories():+ return jsonify({"categories": []})++ @news_api_bp.route("/subscribe", methods=["POST"])+ @login_required+ def subscribe():+ return jsonify({"ok": True})++ news_bp.register_blueprint(news_api_bp)+ app.register_blueprint(news_bp, url_prefix="/news")++ # research_bp registered at root, /api/config/limits is a top-level API.+ research_bp = Blueprint("research", __name__)++ @research_bp.route("/api/config/limits", methods=["GET"])+ @login_required+ def get_upload_limits():+ return jsonify({"limit": 0})++ app.register_blueprint(research_bp)++ return app+++def client(app):+ return app.test_client()++[email protected](autouse=True)+def patch_db_manager():+ """Stub the auth db_manager so we don't touch a real database."""+ with patch("local_deep_research.web.auth.decorators.db_manager") as mock_dm:+ mock_dm.is_user_connected.return_value = False+ yield mock_dm+++class TestNewsPageRoutesRequireAuth:+ """The four news page routes added in PR #3129 must redirect to login+ when the caller has no session."""++ @pytest.mark.parametrize(+ "path",+ [+ "/news/",+ "/news/subscriptions",+ "/news/subscriptions/new",+ "/news/subscriptions/abc-123/edit",+ ],+ )+ def test_unauthenticated_page_redirects_to_login(self, client, path):+ response = client.get(path)+ assert response.status_code == 302+ assert "/auth/login" in response.location+++class TestNewsApiRoutesRequireAuth:+ """/news/api/categories must return JSON 401, not an HTML redirect.+ This is the regression case for nested-blueprint API path detection."""++ def test_unauthenticated_categories_returns_json_401(self, client):+ response = client.get("/news/api/categories")+ assert response.status_code == 401+ assert response.is_json+ assert response.json["error"] == "Authentication required"+ # Must not be an HTML redirect to /auth/login.+ location = response.headers.get("Location") or ""+ assert "/auth/login" not in location+++class TestResearchApiRoutesRequireAuth:+ """/api/config/limits added in PR #3129 must return JSON 401 for+ unauthenticated callers."""++ def test_unauthenticated_upload_limits_returns_json_401(self, client):+ response = client.get("/api/config/limits")+ assert response.status_code == 401+ assert response.is_json+ assert response.json["error"] == "Authentication required"+++class TestNewsApiNonGetMethodsRequireAuth:+ """The decorator runs before the route, so it should reject POST/PUT/+ DELETE the same way as GET. Probe one non-GET API endpoint to lock+ that in."""++ def test_unauthenticated_post_returns_json_401(self, client):+ response = client.post("/news/api/subscribe", json={})+ assert response.status_code == 401+ assert response.is_json+ assert response.json["error"] == "Authentication required"+++class TestNewsHealthRouteIsPublic:+ """/news/health is intentionally exempt from @login_required (per PR+ #3129). Lock that contract in."""++ def test_health_does_not_require_auth(self, client):+ response = client.get("/news/health")+ assert response.status_code == 200+++class TestUnauthorized401ErrorHandler:+ """The 401 error handler in app_factory.register_error_handlers must+ use the same _is_api_path detection as the decorator, so that+ abort(401) on a nested API path returns JSON, not an HTML redirect."""++ def _build_app(self):+ from flask import Flask, abort++ from local_deep_research.web.app_factory import register_error_handlers++ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test"++ # Stub auth.login so the redirect target resolves.+ auth = Blueprint("auth", __name__)++ @auth.route("/login")+ def login():+ return "Login"++ app.register_blueprint(auth, url_prefix="/auth")++ @app.route("/news/api/raises")+ def raises_nested_api():+ abort(401)++ @app.route("/dashboard/raises")+ def raises_page():+ abort(401)++ register_error_handlers(app)+ return app++ def test_abort_401_on_nested_api_returns_json(self):+ app = self._build_app()+ with app.test_client() as client:+ response = client.get("/news/api/raises")+ assert response.status_code == 401+ assert response.is_json+ assert response.json["error"] == "Authentication required"++ def test_abort_401_on_page_redirects(self):+ app = self._build_app()+ with app.test_client() as client:+ response = client.get("/dashboard/raises")+ assert response.status_code == 302+ assert "/auth/login" in response.locationdiff --git a/tests/web/auth/test_decorators.py b/tests/web/auth/test_decorators.pyindex 50ec20e26a..f0d8a60e2a 100644--- a/tests/web/auth/test_decorators.py+++ b/tests/web/auth/test_decorators.py@@ -127,6 +127,118 @@ class TestLoginRequiredDecorator:response = client.get("/api/test")assert response.status_code == 200+ def test_unauthenticated_nested_news_api_returns_401(self):+ """Nested API blueprints (e.g. /news/api/...) must return JSON 401,+ not an HTML redirect. Regression guard for the case where API paths+ only matched as a top-level prefix."""+ app = Flask(__name__)+ app.secret_key = "test"++ with patch("local_deep_research.web.auth.decorators.db_manager"):+ from local_deep_research.web.auth.decorators import login_required++ @app.route("/news/api/categories")+ @login_required+ def categories():+ return {"success": True}++ with app.test_client() as client:+ response = client.get("/news/api/categories")+ assert response.status_code == 401+ assert response.json["error"] == "Authentication required"++ def test_unauthenticated_nested_library_api_returns_401(self):+ """Nested /library/api/... paths must also return JSON 401."""+ app = Flask(__name__)+ app.secret_key = "test"++ with patch("local_deep_research.web.auth.decorators.db_manager"):+ from local_deep_research.web.auth.decorators import login_required++ @app.route("/library/api/documents")+ @login_required+ def documents():+ return {"success": True}++ with app.test_client() as client:+ response = client.get("/library/api/documents")+ assert response.status_code == 401++ def test_authenticated_no_db_on_nested_api_returns_401(self):+ """Stale-session case on a nested API path must return JSON 401,+ not redirect to the login page."""+ app = Flask(__name__)+ app.secret_key = "test"++ with patch(+ "local_deep_research.web.auth.decorators.db_manager"+ ) as mock_db_manager:+ mock_db_manager.is_user_connected.return_value = False++ from local_deep_research.web.auth.decorators import login_required++ @app.route("/news/api/feed")+ @login_required+ def feed():+ return {"success": True}++ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ response = client.get("/news/api/feed")+ assert response.status_code == 401+ assert response.json["error"] == "Database connection required"+++class TestIsApiPath:+ """Tests for the _is_api_path helper."""++ def test_top_level_api_path(self):+ from local_deep_research.web.auth.decorators import _is_api_path++ assert _is_api_path("/api/v1/foo") is True++ def test_nested_news_api_path(self):+ from local_deep_research.web.auth.decorators import _is_api_path++ assert _is_api_path("/news/api/categories") is True++ def test_nested_library_api_path(self):+ from local_deep_research.web.auth.decorators import _is_api_path++ assert _is_api_path("/library/api/documents") is True++ def test_settings_api_path(self):+ from local_deep_research.web.auth.decorators import _is_api_path++ assert _is_api_path("/settings/api/foo") is True++ def test_non_api_page_path(self):+ from local_deep_research.web.auth.decorators import _is_api_path++ assert _is_api_path("/news/") is False+ assert _is_api_path("/dashboard") is False+ assert _is_api_path("/news/subscriptions") is False++ def test_partial_api_word_does_not_match(self):+ """The `api` segment must be slash-bounded — non-API paths whose+ names happen to start with 'api' must NOT be classified as API."""+ from local_deep_research.web.auth.decorators import _is_api_path++ assert _is_api_path("/apidocs") is False+ assert _is_api_path("/openapi.json") is False+ assert _is_api_path("/notapi/x") is False++ def test_path_ending_in_slash_api(self):+ """Paths ending in `/api` (no further segments) are JSON+ endpoints — e.g. /settings/api, /history/api."""+ from local_deep_research.web.auth.decorators import _is_api_path++ assert _is_api_path("/settings/api") is True+ assert _is_api_path("/history/api") is True+ assert _is_api_path("/foo/api") is True+ assert _is_api_path("/api") is True+class TestCurrentUser:"""Tests for current_user function."""