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: add input validation and rate limiting to news API endpoints (#2274)

LearningCircuitf59a78f01345
diff --git a/src/local_deep_research/web/routes/news_routes.py b/src/local_deep_research/web/routes/news_routes.py
index db70d5b333..9654c98a84 100644
--- a/src/local_deep_research/web/routes/news_routes.py
+++ b/src/local_deep_research/web/routes/news_routes.py
@@ -10,10 +10,23 @@ from loguru import logger
from ...news import api as news_api
from ...news.exceptions import NewsAPIException
from ..auth.decorators import login_required
+from ..utils.rate_limiter import limiter
# Create blueprint
bp = Blueprint("news_api", __name__, url_prefix="/api/news")
+# Shared rate limits for POST endpoints
+_news_create_limit = limiter.shared_limit("10 per minute", scope="news_create")
+_news_research_limit = limiter.shared_limit(
+ "5 per minute", scope="news_research"
+)
+_news_feedback_limit = limiter.shared_limit(
+ "30 per minute", scope="news_feedback"
+)
+_news_preferences_limit = limiter.shared_limit(
+ "10 per minute", scope="news_preferences"
+)
+
def handle_api_errors(f):
"""Decorator to handle API errors consistently across news endpoints."""
@@ -45,6 +58,7 @@ def get_news_feed():
"""Get personalized news feed."""
user_id = session.get("username")
limit = request.args.get("limit", 20, type=int)
+ limit = max(1, min(limit, 200))
use_cache = request.args.get("use_cache", "true").lower() == "true"
focus = request.args.get("focus")
search_strategy = request.args.get("search_strategy")
@@ -75,10 +89,13 @@ def get_subscriptions():
@bp.route("/subscriptions", methods=["POST"])
@login_required
@handle_api_errors
+@_news_create_limit
def create_subscription():
"""Create a new subscription."""
user_id = session.get("username")
data = request.get_json()
+ if data is None:
+ return jsonify({"error": "Request body must be valid JSON"}), 400
result = news_api.create_subscription(
user_id=user_id,
@@ -116,6 +133,8 @@ def get_subscription(subscription_id):
def update_subscription(subscription_id):
"""Update an existing subscription."""
data = request.get_json()
+ if data is None:
+ return jsonify({"error": "Request body must be valid JSON"}), 400
result = news_api.update_subscription(subscription_id, data)
return jsonify(result)
@@ -135,6 +154,7 @@ def delete_subscription(subscription_id):
def get_subscription_history(subscription_id):
"""Get research history for a specific subscription."""
limit = request.args.get("limit", 20, type=int)
+ limit = max(1, min(limit, 200))
result = news_api.get_subscription_history(subscription_id, limit)
return jsonify(result)
@@ -142,10 +162,13 @@ def get_subscription_history(subscription_id):
@bp.route("/feedback", methods=["POST"])
@login_required
@handle_api_errors
+@_news_feedback_limit
def submit_feedback():
"""Submit feedback (vote) for a news card."""
user_id = session.get("username")
data = request.get_json()
+ if data is None:
+ return jsonify({"error": "Request body must be valid JSON"}), 400
card_id = data.get("card_id")
vote = data.get("vote")
@@ -160,9 +183,12 @@ def submit_feedback():
@bp.route("/research", methods=["POST"])
@login_required
@handle_api_errors
+@_news_research_limit
def research_news_item():
"""Perform deeper research on a news item."""
data = request.get_json()
+ if data is None:
+ return jsonify({"error": "Request body must be valid JSON"}), 400
card_id = data.get("card_id")
depth = data.get("depth", "quick")
@@ -176,10 +202,13 @@ def research_news_item():
@bp.route("/preferences", methods=["POST"])
@login_required
@handle_api_errors
+@_news_preferences_limit
def save_preferences():
"""Save user preferences for news."""
user_id = session.get("username")
preferences = request.get_json()
+ if preferences is None:
+ return jsonify({"error": "Request body must be valid JSON"}), 400
result = news_api.save_news_preferences(user_id, preferences)
return jsonify(result)
diff --git a/tests/news/test_news_input_validation.py b/tests/news/test_news_input_validation.py
new file mode 100644
index 0000000000..50d9f472c5
--- /dev/null
+++ b/tests/news/test_news_input_validation.py
@@ -0,0 +1,53 @@
+"""Tests for news API input validation (PR #1939).
+
+Verifies:
+- Limit parameter clamped to [1, 200]
+- JSON body validation returns 400 for missing/empty body
+"""
+
+import inspect
+
+
+class TestLimitClamping:
+ """Verify limit parameters are clamped to safe range."""
+
+ def test_get_news_feed_clamps_limit(self):
+ from local_deep_research.web.routes.news_routes import get_news_feed
+
+ source = inspect.getsource(get_news_feed)
+ assert "max(1, min(limit, 200))" in source
+
+ def test_get_subscription_history_clamps_limit(self):
+ from local_deep_research.web.routes.news_routes import (
+ get_subscription_history,
+ )
+
+ source = inspect.getsource(get_subscription_history)
+ assert "max(1, min(limit, 200))" in source
+
+
+class TestJSONBodyValidation:
+ """Verify endpoints reject missing/empty JSON body."""
+
+ def _check_json_guard(self, func_name):
+ import local_deep_research.web.routes.news_routes as mod
+
+ func = getattr(mod, func_name)
+ source = inspect.getsource(func)
+ assert "if data is None" in source or "if preferences is None" in source
+ assert "Request body must be valid JSON" in source
+
+ def test_create_subscription_validates_json(self):
+ self._check_json_guard("create_subscription")
+
+ def test_update_subscription_validates_json(self):
+ self._check_json_guard("update_subscription")
+
+ def test_submit_feedback_validates_json(self):
+ self._check_json_guard("submit_feedback")
+
+ def test_research_news_item_validates_json(self):
+ self._check_json_guard("research_news_item")
+
+ def test_save_preferences_validates_json(self):
+ self._check_json_guard("save_preferences")
diff --git a/tests/news/test_news_rate_limiting.py b/tests/news/test_news_rate_limiting.py
new file mode 100644
index 0000000000..8eb16a0d5a
--- /dev/null
+++ b/tests/news/test_news_rate_limiting.py
@@ -0,0 +1,181 @@
+"""
+Tests for rate limiting decorators on news API routes.
+
+Verifies that the PR adds rate limiting to the four expensive POST endpoints
+in news_routes.py using AST parsing to avoid heavy import dependencies.
+"""
+
+import ast
+from pathlib import Path
+
+# Path to the news_routes module source
+_NEWS_ROUTES_PATH = (
+ Path(__file__).resolve().parents[2]
+ / "src"
+ / "local_deep_research"
+ / "web"
+ / "routes"
+ / "news_routes.py"
+)
+
+
+def _parse_source():
+ """Read and parse the news_routes.py source file."""
+ return ast.parse(_NEWS_ROUTES_PATH.read_text())
+
+
+def _get_module_source():
+ """Read the news_routes.py source as text."""
+ return _NEWS_ROUTES_PATH.read_text()
+
+
+def _get_function_decorators(tree):
+ """Extract a mapping of function name -> list of decorator names."""
+ result = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef):
+ dec_names = []
+ for dec in node.decorator_list:
+ if isinstance(dec, ast.Name):
+ dec_names.append(dec.id)
+ elif isinstance(dec, ast.Call):
+ if isinstance(dec.func, ast.Attribute):
+ dec_names.append(
+ f"{dec.func.value.id}.{dec.func.attr}"
+ if isinstance(dec.func.value, ast.Name)
+ else dec.func.attr
+ )
+ elif isinstance(dec.func, ast.Name):
+ dec_names.append(dec.func.id)
+ result[node.name] = dec_names
+ return result
+
+
+def _get_module_level_assignments(tree):
+ """Extract module-level variable assignments as {name: ast node}."""
+ result = {}
+ for node in ast.iter_child_nodes(tree):
+ if isinstance(node, ast.Assign):
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ result[target.id] = node.value
+ return result
+
+
+class TestNewsRateLimitingDeclarations:
+ """Test that shared rate limit objects are declared at module level."""
+
+ def test_news_create_limit_declared(self):
+ tree = _parse_source()
+ assignments = _get_module_level_assignments(tree)
+ assert "_news_create_limit" in assignments
+
+ def test_news_research_limit_declared(self):
+ tree = _parse_source()
+ assignments = _get_module_level_assignments(tree)
+ assert "_news_research_limit" in assignments
+
+ def test_news_feedback_limit_declared(self):
+ tree = _parse_source()
+ assignments = _get_module_level_assignments(tree)
+ assert "_news_feedback_limit" in assignments
+
+ def test_news_preferences_limit_declared(self):
+ tree = _parse_source()
+ assignments = _get_module_level_assignments(tree)
+ assert "_news_preferences_limit" in assignments
+
+
+class TestNewsRateLimitingDecorators:
+ """Test that rate limit decorators are applied to the correct routes."""
+
+ def test_create_subscription_has_rate_limit_decorator(self):
+ tree = _parse_source()
+ decorators = _get_function_decorators(tree)
+ assert "_news_create_limit" in decorators.get(
+ "create_subscription", []
+ ), "create_subscription must have @_news_create_limit decorator"
+
+ def test_submit_feedback_has_rate_limit_decorator(self):
+ tree = _parse_source()
+ decorators = _get_function_decorators(tree)
+ assert "_news_feedback_limit" in decorators.get(
+ "submit_feedback", []
+ ), "submit_feedback must have @_news_feedback_limit decorator"
+
+ def test_research_news_item_has_rate_limit_decorator(self):
+ tree = _parse_source()
+ decorators = _get_function_decorators(tree)
+ assert "_news_research_limit" in decorators.get(
+ "research_news_item", []
+ ), "research_news_item must have @_news_research_limit decorator"
+
+ def test_save_preferences_has_rate_limit_decorator(self):
+ tree = _parse_source()
+ decorators = _get_function_decorators(tree)
+ assert "_news_preferences_limit" in decorators.get(
+ "save_preferences", []
+ ), "save_preferences must have @_news_preferences_limit decorator"
+
+
+class TestNewsRateLimitValues:
+ """Test that rate limit values are reasonable."""
+
+ def test_rate_limiter_imported(self):
+ source = _get_module_source()
+ assert "from ..utils.rate_limiter import limiter" in source
+
+ def test_create_limit_value(self):
+ source = _get_module_source()
+ assert '"10 per minute"' in source
+ assert 'scope="news_create"' in source
+
+ def test_research_limit_is_most_restrictive(self):
+ """Research triggers AI work so should have the lowest limit."""
+ source = _get_module_source()
+ assert '"5 per minute"' in source
+ assert 'scope="news_research"' in source
+
+ def test_feedback_limit_is_most_permissive(self):
+ """Feedback is lightweight so can allow more requests."""
+ source = _get_module_source()
+ assert '"30 per minute"' in source
+ assert 'scope="news_feedback"' in source
+
+ def test_preferences_limit_value(self):
+ source = _get_module_source()
+ # preferences uses same rate as create (10 per minute)
+ assert 'scope="news_preferences"' in source
+
+ def test_uses_shared_limit(self):
+ """Verify shared_limit is used (not per-route limit)."""
+ source = _get_module_source()
+ assert "limiter.shared_limit" in source
+
+
+class TestUnlimitedEndpoints:
+ """Verify that read-only GET endpoints do NOT have rate limits."""
+
+ def test_get_news_feed_not_rate_limited(self):
+ tree = _parse_source()
+ decorators = _get_function_decorators(tree)
+ feed_decs = decorators.get("get_news_feed", [])
+ assert not any(d.startswith("_news_") for d in feed_decs), (
+ "GET /feed should not have a news-specific rate limit"
+ )
+
+ def test_get_subscriptions_not_rate_limited(self):
+ tree = _parse_source()
+ decorators = _get_function_decorators(tree)
+ decs = decorators.get("get_subscriptions", [])
+ assert not any(d.startswith("_news_") for d in decs), (
+ "GET /subscriptions should not have a news-specific rate limit"
+ )
+
+ def test_get_categories_not_rate_limited(self):
+ tree = _parse_source()
+ decorators = _get_function_decorators(tree)
+ decs = decorators.get("get_categories", [])
+ assert not any(d.startswith("_news_") for d in decs), (
+ "GET /categories should not have a news-specific rate limit"
+ )