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.

refactor: consolidate HTTP rate limiting into single Flask-Limiter instance (#2968)

LearningCircuita3baed48c35e
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
index aeef3393a8..cdc3da4a5d 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
@@ -8,7 +8,7 @@ from loguru import logger
from ...database.session_context import get_user_db_session
from ...security.decorators import require_json_body
from ...web.auth.decorators import login_required
-from ...web.utils.rate_limiter import limiter
+from ...security.rate_limiter import limiter
from local_deep_research.settings import SettingsManager
from ...web.utils.templates import render_template_with_defaults
from .benchmark_service import benchmark_service
diff --git a/src/local_deep_research/constants.py b/src/local_deep_research/constants.py
index fd214efed7..73a5368b53 100644
--- a/src/local_deep_research/constants.py
+++ b/src/local_deep_research/constants.py
@@ -61,10 +61,6 @@ class ResearchStatus(StrEnum):
CANCELLED = "cancelled" # Unused by research; for benchmarks
-# --- Rate limiting defaults ---
-RATE_LIMIT_WINDOW_SECONDS = 60
-DEFAULT_RATE_LIMIT = 60 # requests per window
-
# --- Research library file_path sentinel values ---
FILE_PATH_METADATA_ONLY = "metadata_only"
FILE_PATH_TEXT_ONLY = "text_only_not_stored"
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index c925c49509..fd4598bb0e 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -39,7 +39,10 @@ from ...utilities.db_utils import get_settings_manager
from ..services.library_rag_service import LibraryRAGService
from ...settings.manager import SettingsManager
from ...security.path_validator import PathValidator
-from ...security import upload_rate_limit
+from ...security.rate_limiter import (
+ upload_rate_limit_ip,
+ upload_rate_limit_user,
+)
from ..utils import handle_api_error
from ...database.models.library import (
Document,
@@ -51,7 +54,7 @@ from ...database.models.library import (
)
from ...database.models.queue import TaskMetadata
from ...database.thread_local_session import thread_cleanup
-from ...web.utils.rate_limiter import limiter
+from ...security.rate_limiter import limiter
from ...config.paths import get_library_directory
rag_bp = Blueprint("rag", __name__, url_prefix="/library")
@@ -1348,7 +1351,8 @@ def delete_collection(collection_id):
"/api/collections/<string:collection_id>/upload", methods=["POST"]
)
@login_required
-@upload_rate_limit
+@upload_rate_limit_user
+@upload_rate_limit_ip
def upload_to_collection(collection_id):
"""Upload files to a collection."""
from ...database.session_context import get_user_db_session
diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.py
index 5c52016e8f..cbe5f2e850 100644
--- a/src/local_deep_research/security/__init__.py
+++ b/src/local_deep_research/security/__init__.py
@@ -44,21 +44,6 @@ except ImportError:
FileUploadValidator = None # type: ignore
_has_file_upload_validator = False
-# Rate limiter requires flask_limiter, import conditionally
-try:
- from .rate_limiter import init_rate_limiter, upload_rate_limit
-
- _has_rate_limiter = True
-except ImportError:
- init_rate_limiter = None # type: ignore
- _has_rate_limiter = False
-
- # Provide a no-op decorator when flask_limiter is not available
- def upload_rate_limit(f):
- """No-op decorator when flask_limiter is not installed."""
- return f
-
-
__all__ = [
"PathValidator",
"DataSanitizer",
@@ -74,8 +59,6 @@ __all__ = [
"NotificationURLValidationError",
"SecurityHeaders",
"URLValidator",
- "init_rate_limiter",
- "upload_rate_limit",
"safe_get",
"safe_post",
"SafeSession",
diff --git a/src/local_deep_research/security/account_lockout.py b/src/local_deep_research/security/account_lockout.py
index 02db3ba405..89dcf2e3f6 100644
--- a/src/local_deep_research/security/account_lockout.py
+++ b/src/local_deep_research/security/account_lockout.py
@@ -1,6 +1,6 @@
"""Per-user account lockout after repeated failed login attempts.
-Complements the per-IP rate limiting in ``web/utils/rate_limiter.py`` by
+Complements the per-IP rate limiting in ``security/rate_limiter.py`` by
tracking failures at the *username* level. A user who exceeds the
configured threshold is temporarily locked out regardless of the source IP.
diff --git a/src/local_deep_research/security/rate_limiter.py b/src/local_deep_research/security/rate_limiter.py
index f8427beedc..8bd2c04412 100644
--- a/src/local_deep_research/security/rate_limiter.py
+++ b/src/local_deep_research/security/rate_limiter.py
@@ -1,151 +1,198 @@
"""
-Rate limiting for API endpoints using Flask-Limiter.
+Rate limiting utility for HTTP endpoints.
+Provides a global limiter instance that can be imported by blueprints.
-Provides decorators and configuration for rate limiting HTTP requests
-to prevent abuse and resource exhaustion.
+Rate limits are configurable via environment variables (LDR_SECURITY_RATE_LIMIT_*).
+Legacy server_config.json values are honored during the deprecation period.
+Changes require server restart to take effect.
-Configuration:
- RATE_LIMIT_FAIL_CLOSED: Set to "true" in production to fail closed
- when rate limiter is not initialized. Default is fail-open for
- easier development setup.
-
- For production, also configure:
- storage_uri="redis://localhost:6379" for multi-worker support
+Note: This is designed for single-instance local deployments. For multi-worker
+production deployments, configure Redis storage via RATELIMIT_STORAGE_URL.
"""
-import os
-
-from flask import g
+from flask import g, request, session as flask_session
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from loguru import logger
+from ..settings.env_registry import is_rate_limiting_enabled
+from ..web.server_config import load_server_config
-# Global limiter instance (initialized by app factory)
-_limiter = None
+# Load rate limits from server config (UI-configurable)
+# Multiple limits can be separated by semicolons (e.g., "5000 per hour;50000 per day")
+_config = load_server_config()
+DEFAULT_RATE_LIMIT = _config["rate_limit_default"]
+LOGIN_RATE_LIMIT = _config["rate_limit_login"]
+REGISTRATION_RATE_LIMIT = _config["rate_limit_registration"]
+# Settings modification rate limit - prevent abuse of settings endpoints
+SETTINGS_RATE_LIMIT = _config["rate_limit_settings"]
-# Configuration: fail-closed in production, fail-open in development
-RATE_LIMIT_FAIL_CLOSED = (
- os.environ.get("RATE_LIMIT_FAIL_CLOSED", "false").lower() == "true"
-)
+def get_client_ip():
+ """
+ Get the real client IP address, respecting X-Forwarded-For headers.
-def get_rate_limiter() -> Limiter:
+ This is important for deployments behind proxies/load balancers.
+ Falls back to direct remote address if no forwarded headers present.
"""
- Get the global rate limiter instance.
+ # Check X-Forwarded-For header (set by proxies/load balancers)
+ forwarded_for = request.environ.get("HTTP_X_FORWARDED_FOR")
+ if forwarded_for:
+ # Take the first IP in the chain (client IP)
+ return forwarded_for.split(",")[0].strip()
+
+ # Check X-Real-IP header (alternative proxy header)
+ real_ip = request.environ.get("HTTP_X_REAL_IP")
+ if real_ip:
+ return real_ip.strip()
+
+ # Fallback to direct remote address
+ return get_remote_address()
+
+
+# Global limiter instance - will be initialized in app_factory
+# Rate limiting is disabled in CI unless ENABLE_RATE_LIMITING=true
+# This allows the rate limiting test to run with rate limiting enabled
+#
+# Note: In-memory storage is used by default, which is suitable for single-instance
+# deployments. For multi-instance production deployments behind a load balancer,
+# configure Redis storage via RATELIMIT_STORAGE_URL environment variable:
+# export RATELIMIT_STORAGE_URL="redis://localhost:6379"
+limiter = Limiter(
+ key_func=get_client_ip,
+ default_limits=[DEFAULT_RATE_LIMIT],
+ storage_uri="memory://",
+ headers_enabled=True,
+ enabled=is_rate_limiting_enabled(),
+)
- Returns:
- Flask-Limiter instance
- Raises:
- RuntimeError: If limiter hasn't been initialized
- """
- global _limiter
- if _limiter is None:
- raise RuntimeError(
- "Rate limiter not initialized. Call init_rate_limiter(app) first."
- )
- return _limiter
+# Shared rate limit decorators for authentication endpoints
+# These can be imported and used directly on routes
+login_limit = limiter.shared_limit(
+ LOGIN_RATE_LIMIT,
+ scope="login",
+)
+registration_limit = limiter.shared_limit(
+ REGISTRATION_RATE_LIMIT,
+ scope="registration",
+)
-def init_rate_limiter(app):
- """
- Initialize the rate limiter with the Flask app.
+settings_limit = limiter.shared_limit(
+ SETTINGS_RATE_LIMIT,
+ scope="settings",
+)
+
+password_change_limit = limiter.shared_limit(
+ LOGIN_RATE_LIMIT,
+ scope="password_change",
+)
- This should be called once during app initialization.
- Args:
- app: Flask application instance
+# ---------------------------------------------------------------------------
+# Shared helpers
+# ---------------------------------------------------------------------------
- Returns:
- Configured Limiter instance
- """
- global _limiter
-
- # Use authenticated username if available, otherwise fall back to IP
- def get_user_identifier():
- # Check if user is authenticated
- username = g.get("current_user")
- if username:
- return f"user:{username}"
- # Fall back to IP address for unauthenticated requests
- return f"ip:{get_remote_address()}"
-
- _limiter = Limiter(
- app=app,
- key_func=get_user_identifier,
- default_limits=[], # No default limits - apply via decorators only
- storage_uri="memory://", # Use in-memory storage (for development)
- # For production, consider: storage_uri="redis://localhost:6379"
- strategy="fixed-window",
- headers_enabled=True, # Add rate limit headers to responses
- )
-
- logger.info("Rate limiter initialized successfully")
- return _limiter
-
-
-def upload_rate_limit(f):
+
+def get_current_username():
+ """Return the authenticated username from g.current_user or the session.
+
+ g.current_user is set by the inject_current_user before_request handler
+ and is the preferred source. The session fallback covers cases where
+ g.current_user was cleared or is unavailable (e.g., tests, CLI contexts).
"""
- Decorator for rate limiting file upload endpoints.
-
- Limits:
- - 10 uploads per minute per user
- - 100 uploads per hour per user
-
- Usage:
- @research_bp.route("/api/upload/pdf", methods=["POST"])
- @login_required
- @upload_rate_limit
- def upload_pdf():
- ...
-
- Returns:
- Decorated function with rate limiting
-
- Note:
- If the rate limiter is not initialized (e.g., flask_limiter not installed),
- behavior depends on RATE_LIMIT_FAIL_CLOSED environment variable:
- - "false" (default): Pass through without rate limiting (fail-open)
- - "true": Raise RuntimeError, crashing the application (fail-closed)
-
- Set RATE_LIMIT_FAIL_CLOSED=true in production to ensure rate limiting
- is always active.
+ if hasattr(g, "current_user") and g.current_user:
+ return g.current_user
+ return flask_session.get("username")
+
+
+# ---------------------------------------------------------------------------
+# API v1 rate limiting (per-user, configurable via DB setting)
+# ---------------------------------------------------------------------------
+
+API_RATE_LIMIT_DEFAULT = 60 # requests per minute
+
+
+def _get_user_api_rate_limit():
+ """Read the per-user API rate limit from DB, cached on flask.g."""
+ if hasattr(g, "_api_rate_limit"):
+ return g._api_rate_limit
+
+ from ..database.session_context import get_user_db_session
+ from ..utilities.db_utils import get_settings_manager
+
+ username = get_current_username()
+
+ rate_limit = API_RATE_LIMIT_DEFAULT
+ if username:
+ try:
+ with get_user_db_session(username) as db_session:
+ if db_session:
+ sm = get_settings_manager(db_session, username)
+ rate_limit = sm.get_setting(
+ "app.api_rate_limit", API_RATE_LIMIT_DEFAULT
+ )
+ except Exception:
+ logger.debug("Failed to read API rate limit setting", exc_info=True)
+
+ g._api_rate_limit = rate_limit
+ return rate_limit
+
+
+def _get_api_rate_limit_string():
+ """Return Flask-Limiter format string for the current user's API limit."""
+ return f"{_get_user_api_rate_limit()} per minute"
+
+
+def _is_api_rate_limit_exempt():
+ """Exempt unauthenticated requests (auth decorator handles rejection)
+ and users who set rate_limit=0 (disabled)."""
+ if not get_current_username():
+ return True
+ return not _get_user_api_rate_limit()
+
+
+def _get_api_user_key():
+ """Key function for API rate limiting — keyed by authenticated username.
+
+ Unauthenticated requests are exempt via _is_api_rate_limit_exempt and
+ rejected by api_access_control, so this function is only called for
+ authenticated users.
"""
- try:
- limiter = get_rate_limiter()
- # Use Flask-Limiter's limit decorator
- return limiter.limit("10 per minute;100 per hour")(f)
- except RuntimeError:
- # Rate limiter not initialized - this is expected if flask_limiter
- # is not installed or init_rate_limiter was not called
- if RATE_LIMIT_FAIL_CLOSED:
- logger.exception(
- f"Rate limiter not initialized for {f.__name__} and "
- "RATE_LIMIT_FAIL_CLOSED is enabled. Application will fail."
- )
- raise
- logger.warning(
- f"Rate limiting disabled for {f.__name__}: "
- "limiter not initialized. Install flask_limiter for rate limiting. "
- "Set RATE_LIMIT_FAIL_CLOSED=true to enforce rate limiting in production."
- )
- return f
- except Exception:
- # Unexpected error - log it but don't break the application
- if RATE_LIMIT_FAIL_CLOSED:
- logger.exception(
- f"Unexpected error applying rate limit to {f.__name__} and "
- "RATE_LIMIT_FAIL_CLOSED is enabled. Application will fail."
- )
- raise
- logger.exception(
- f"Unexpected error applying rate limit to {f.__name__}. "
- "Rate limiting disabled for this endpoint. "
- "Set RATE_LIMIT_FAIL_CLOSED=true to enforce rate limiting in production."
- )
- return f
-
-
-# Export convenience decorator
-__all__ = ["init_rate_limiter", "get_rate_limiter", "upload_rate_limit"]
+ return f"api_user:{get_current_username()}"
+
+
+api_rate_limit = limiter.shared_limit(
+ _get_api_rate_limit_string,
+ scope="api_v1",
+ key_func=_get_api_user_key,
+ exempt_when=_is_api_rate_limit_exempt,
+)
+
+
+# ---------------------------------------------------------------------------
+# File upload rate limiting (dual-keyed: per-user AND per-IP)
+# ---------------------------------------------------------------------------
+
+_UPLOAD_RATE_LIMIT = "10 per minute;100 per hour"
+
+
+def _get_upload_user_key():
+ """Key function for upload rate limiting — keyed by authenticated username."""
+ username = get_current_username()
+ if username:
+ return f"upload_user:{username}"
+ return f"upload_ip:{get_client_ip()}"
+
+
+upload_rate_limit_user = limiter.shared_limit(
+ _UPLOAD_RATE_LIMIT,
+ scope="upload_user",
+ key_func=_get_upload_user_key,
+)
+
+upload_rate_limit_ip = limiter.shared_limit(
+ _UPLOAD_RATE_LIMIT,
+ scope="upload_ip",
+)
diff --git a/src/local_deep_research/web/api.py b/src/local_deep_research/web/api.py
index 95af4b8d61..a1e64a220d 100644
--- a/src/local_deep_research/web/api.py
+++ b/src/local_deep_research/web/api.py
@@ -3,7 +3,6 @@ REST API for Local Deep Research.
Provides HTTP access to programmatic search and research capabilities.
"""
-import threading
import time
from functools import wraps
from typing import Dict, Any
@@ -12,92 +11,52 @@ from flask import Blueprint, jsonify, request, Response
from loguru import logger
from ..api.research_functions import analyze_documents
-from ..constants import DEFAULT_RATE_LIMIT, RATE_LIMIT_WINDOW_SECONDS
from ..database.session_context import get_user_db_session
from ..security.decorators import require_json_body
from ..utilities.db_utils import get_settings_manager
+from ..security.rate_limiter import (
+ API_RATE_LIMIT_DEFAULT,
+ api_rate_limit,
+ get_current_username,
+)
# Create a blueprint for the API
api_blueprint = Blueprint("api_v1", __name__, url_prefix="/api/v1")
-# Rate limiting data store: {ip_address: [timestamp1, timestamp2, ...]}
-rate_limit_data: dict[str, list[float]] = {}
-_rate_limit_lock = threading.Lock()
-
def api_access_control(f):
"""
Decorator to enforce API access control:
- - Check if API is enabled
- - Enforce rate limiting
+ - Check if user is authenticated
+ - Check if API is enabled for the user
+ - Pre-cache api_rate_limit on g so the rate limiter avoids a second DB read
"""
@wraps(f)
def decorated_function(*args, **kwargs):
- # Get username from session
- from flask import g, session
+ from flask import g
- username = (
- g.current_user
- if hasattr(g, "current_user")
- else session.get("username")
- )
+ username = get_current_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
-
- # Only try to get settings if there's an authenticated user
- if username:
- with get_user_db_session(username) as db_session:
- if db_session:
- settings_manager = get_settings_manager(
- db_session, username
- )
- api_enabled = settings_manager.get_setting(
- "app.enable_api", True
- )
- rate_limit = settings_manager.get_setting(
- "app.api_rate_limit", 60
- )
+ # Read both settings in a single DB session
+ api_enabled = True
+ with get_user_db_session(username) as db_session:
+ if db_session:
+ settings_manager = get_settings_manager(db_session, username)
+ api_enabled = settings_manager.get_setting(
+ "app.enable_api", True
+ )
+ # Pre-cache for _get_user_api_rate_limit() to avoid a second DB read
+ g._api_rate_limit = settings_manager.get_setting(
+ "app.api_rate_limit", API_RATE_LIMIT_DEFAULT
+ )
if not api_enabled:
return jsonify({"error": "API access is disabled"}), 403
- # Implement rate limiting
- if rate_limit:
- client_ip = request.remote_addr or "unknown"
- current_time = time.time()
-
- with _rate_limit_lock:
- # Initialize or clean up old requests for this IP
- if client_ip not in rate_limit_data:
- rate_limit_data[client_ip] = []
-
- # Remove timestamps older than the rate limit window
- rate_limit_data[client_ip] = [
- ts
- for ts in rate_limit_data[client_ip]
- if current_time - ts < RATE_LIMIT_WINDOW_SECONDS
- ]
-
- # Check if rate limit is exceeded
- if len(rate_limit_data[client_ip]) >= rate_limit:
- return (
- jsonify(
- {
- "error": f"Rate limit exceeded. Maximum {rate_limit} requests per {RATE_LIMIT_WINDOW_SECONDS} seconds allowed."
- }
- ),
- 429,
- )
-
- # Add current timestamp to the list
- rate_limit_data[client_ip].append(current_time)
-
return f(*args, **kwargs)
return decorated_function
@@ -105,6 +64,7 @@ def api_access_control(f):
@api_blueprint.route("/", methods=["GET"])
@api_access_control
+@api_rate_limit
def api_documentation():
"""
Provide documentation on the available API endpoints.
@@ -164,6 +124,7 @@ def health_check():
@api_blueprint.route("/quick_summary_test", methods=["POST"])
@api_access_control
+@api_rate_limit
@require_json_body(error_message="Query parameter is required")
def api_quick_summary_test():
"""Test endpoint using programmatic access with minimal parameters for fast testing."""
@@ -225,6 +186,7 @@ def _serialize_results(results: Dict[str, Any]) -> Response:
@api_blueprint.route("/quick_summary", methods=["POST"])
@api_access_control
+@api_rate_limit
@require_json_body(error_message="Query parameter is required")
def api_quick_summary():
"""
@@ -255,14 +217,7 @@ def api_quick_summary():
f"Query length: {len(query) if query else 0}, params keys: {list(params.keys()) if params else 'None'}"
)
- # Get username from session or g object
- from flask import g, session
-
- username = (
- g.current_user
- if hasattr(g, "current_user")
- else session.get("username")
- )
+ username = get_current_username()
if username:
params["username"] = username
@@ -354,6 +309,7 @@ def api_quick_summary():
@api_blueprint.route("/generate_report", methods=["POST"])
@api_access_control
+@api_rate_limit
@require_json_body(error_message="Query parameter is required")
def api_generate_report():
"""
@@ -426,6 +382,7 @@ def api_generate_report():
@api_blueprint.route("/analyze_documents", methods=["POST"])
@api_access_control
+@api_rate_limit
@require_json_body(
error_message="Both query and collection_name parameters are required"
)
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index c084e2c717..eebf10c383 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -20,7 +20,7 @@ from local_deep_research.settings.logger import log_settings
from ..utilities.log_utils import InterceptHandler
from ..security import SecurityHeaders, get_security_default
-from .utils.rate_limiter import limiter
+from ..security.rate_limiter import limiter
from ..security.file_upload_validator import FileUploadValidator
# Removed DB_PATH import - using per-user databases now
@@ -311,19 +311,20 @@ def create_app():
SecurityHeaders(app)
# Initialize rate limiting for security (brute force protection)
- # Uses imported limiter from utils.rate_limiter module
+ # Uses imported limiter from security.rate_limiter module
# Rate limiting is disabled in CI via enabled callable in rate_limiter.py
# Also set app config to ensure Flask-Limiter respects our settings
from ..settings.env_registry import is_rate_limiting_enabled
app.config["RATELIMIT_ENABLED"] = is_rate_limiting_enabled()
+ app.config["RATELIMIT_STRATEGY"] = "moving-window"
limiter.init_app(app)
# Custom error handler for rate limit exceeded (429)
@app.errorhandler(429)
def ratelimit_handler(e):
# Import here to avoid circular imports
- from .utils.rate_limiter import get_client_ip
+ from ..security.rate_limiter import get_client_ip
# Audit logging for security monitoring
# Use get_client_ip() to get the real IP behind proxies
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index 782b6bb8b0..42ec24a87a 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -28,7 +28,7 @@ from .session_manager import (
session_manager,
) # singleton from session_manager module
from ..server_config import load_server_config
-from ..utils.rate_limiter import (
+from ...security.rate_limiter import (
login_limit,
password_change_limit,
registration_limit,
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index d8a417a3e5..a329eeb91a 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -15,7 +15,7 @@ from ..models.database import (
)
from ..routes.globals import get_active_research_snapshot
from ..services.research_service import get_research_strategy
-from ..utils.rate_limiter import limiter
+from ...security.rate_limiter import limiter
from ...security import filter_research_metadata
from ..utils.templates import render_template_with_defaults
diff --git a/src/local_deep_research/web/routes/news_routes.py b/src/local_deep_research/web/routes/news_routes.py
index cc4d6ba05d..81e991aaac 100644
--- a/src/local_deep_research/web/routes/news_routes.py
+++ b/src/local_deep_research/web/routes/news_routes.py
@@ -11,7 +11,7 @@ from ...news import api as news_api
from ...news.exceptions import NewsAPIException
from ...security.decorators import require_json_body
from ..auth.decorators import login_required
-from ..utils.rate_limiter import limiter
+from ...security.rate_limiter import limiter
# Create blueprint
bp = Blueprint("news_api", __name__, url_prefix="/api/news")
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index f1802be7fe..81a7f61e0c 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -24,7 +24,10 @@ from ...security import (
FileUploadValidator,
filter_research_metadata,
strip_settings_snapshot,
- upload_rate_limit,
+)
+from ...security.rate_limiter import (
+ upload_rate_limit_ip,
+ upload_rate_limit_user,
)
from ...security.decorators import require_json_body
from ...config.paths import get_config_directory
@@ -49,7 +52,7 @@ from ..services.research_service import (
run_research_process,
start_research_process,
)
-from ..utils.rate_limiter import limiter
+from ...security.rate_limiter import limiter
from ..utils.templates import render_template_with_defaults
from .globals import (
append_research_log,
@@ -1507,7 +1510,8 @@ def get_upload_limits():
@research_bp.route("/api/upload/pdf", methods=["POST"])
@login_required
-@upload_rate_limit
+@upload_rate_limit_user
+@upload_rate_limit_ip
def upload_pdf():
"""
Upload and extract text from PDF files with comprehensive security validation.
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 689c76516d..ef6d021a4d 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -64,7 +64,7 @@ from ...utilities.db_utils import get_settings_manager
from ...utilities.url_utils import normalize_url
from ...security.decorators import require_json_body
from ..auth.decorators import login_required
-from ..utils.rate_limiter import settings_limit
+from ...security.rate_limiter import settings_limit
from ...settings.manager import get_typed_setting_value, parse_boolean
from ..services.settings_service import (
create_or_update_setting,
diff --git a/src/local_deep_research/web/utils/rate_limiter.py b/src/local_deep_research/web/utils/rate_limiter.py
deleted file mode 100644
index d581ab5247..0000000000
--- a/src/local_deep_research/web/utils/rate_limiter.py
+++ /dev/null
@@ -1,89 +0,0 @@
-"""
-Rate limiting utility for authentication endpoints.
-Provides a global limiter instance that can be imported by blueprints.
-
-Rate limits are configurable via environment variables (LDR_SECURITY_RATE_LIMIT_*).
-Legacy server_config.json values are honored during the deprecation period.
-Changes require server restart to take effect.
-
-Note: This is designed for single-instance local deployments. For multi-worker
-production deployments, configure Redis storage via RATELIMIT_STORAGE_URL.
-"""
-
-from flask import request
-from flask_limiter import Limiter
-from flask_limiter.util import get_remote_address
-
-from ...settings.env_registry import is_rate_limiting_enabled
-from ..server_config import load_server_config
-
-# Load rate limits from server config (UI-configurable)
-# Multiple limits can be separated by semicolons (e.g., "5000 per hour;50000 per day")
-_config = load_server_config()
-DEFAULT_RATE_LIMIT = _config["rate_limit_default"]
-LOGIN_RATE_LIMIT = _config["rate_limit_login"]
-REGISTRATION_RATE_LIMIT = _config["rate_limit_registration"]
-# Settings modification rate limit - prevent abuse of settings endpoints
-SETTINGS_RATE_LIMIT = _config["rate_limit_settings"]
-
-
-def get_client_ip():
- """
- Get the real client IP address, respecting X-Forwarded-For headers.
-
- This is important for deployments behind proxies/load balancers.
- Falls back to direct remote address if no forwarded headers present.
- """
- # Check X-Forwarded-For header (set by proxies/load balancers)
- forwarded_for = request.environ.get("HTTP_X_FORWARDED_FOR")
- if forwarded_for:
- # Take the first IP in the chain (client IP)
- return forwarded_for.split(",")[0].strip()
-
- # Check X-Real-IP header (alternative proxy header)
- real_ip = request.environ.get("HTTP_X_REAL_IP")
- if real_ip:
- return real_ip.strip()
-
- # Fallback to direct remote address
- return get_remote_address()
-
-
-# Global limiter instance - will be initialized in app_factory
-# Rate limiting is disabled in CI unless ENABLE_RATE_LIMITING=true
-# This allows the rate limiting test to run with rate limiting enabled
-#
-# Note: In-memory storage is used by default, which is suitable for single-instance
-# deployments. For multi-instance production deployments behind a load balancer,
-# configure Redis storage via RATELIMIT_STORAGE_URL environment variable:
-# export RATELIMIT_STORAGE_URL="redis://localhost:6379"
-limiter = Limiter(
- key_func=get_client_ip,
- default_limits=[DEFAULT_RATE_LIMIT],
- storage_uri="memory://",
- headers_enabled=True,
- enabled=is_rate_limiting_enabled(),
-)
-
-
-# Shared rate limit decorators for authentication endpoints
-# These can be imported and used directly on routes
-login_limit = limiter.shared_limit(
- LOGIN_RATE_LIMIT,
- scope="login",
-)
-
-registration_limit = limiter.shared_limit(
- REGISTRATION_RATE_LIMIT,
- scope="registration",
-)
-
-settings_limit = limiter.shared_limit(
- SETTINGS_RATE_LIMIT,
- scope="settings",
-)
-
-password_change_limit = limiter.shared_limit(
- LOGIN_RATE_LIMIT,
- scope="password_change",
-)
diff --git a/tests/auth_tests/test_auth_rate_limiting.py b/tests/auth_tests/test_auth_rate_limiting.py
index 8606b7c4ab..815a42f974 100644
--- a/tests/auth_tests/test_auth_rate_limiting.py
+++ b/tests/auth_tests/test_auth_rate_limiting.py
@@ -28,7 +28,7 @@ class TestAuthRateLimiting:
from local_deep_research.database.auth_db import init_auth_database
from local_deep_research.database.encrypted_db import db_manager
from local_deep_research.web.app_factory import create_app
- from local_deep_research.web.utils.rate_limiter import limiter
+ from local_deep_research.security.rate_limiter import limiter
# Reset db_manager state
db_manager.close_all_databases()
@@ -420,7 +420,7 @@ class TestRateLimitReset:
from local_deep_research.database.auth_db import init_auth_database
from local_deep_research.database.encrypted_db import db_manager
from local_deep_research.web.app_factory import create_app
- from local_deep_research.web.utils.rate_limiter import limiter
+ from local_deep_research.security.rate_limiter import limiter
db_manager.close_all_databases()
db_manager.data_dir = temp_data_dir / "encrypted_databases"
diff --git a/tests/core/test_constants.py b/tests/core/test_constants.py
index b8e109a48d..169392f807 100644
--- a/tests/core/test_constants.py
+++ b/tests/core/test_constants.py
@@ -193,24 +193,6 @@ class TestResearchStatus:
assert RS1 is RS2
-class TestRateLimitConstants:
- """Tests for rate limit constants."""
-
- def test_rate_limit_window_seconds(self):
- """RATE_LIMIT_WINDOW_SECONDS is a positive integer."""
- from local_deep_research.constants import RATE_LIMIT_WINDOW_SECONDS
-
- assert isinstance(RATE_LIMIT_WINDOW_SECONDS, int)
- assert RATE_LIMIT_WINDOW_SECONDS > 0
-
- def test_default_rate_limit(self):
- """DEFAULT_RATE_LIMIT is a positive integer."""
- from local_deep_research.constants import DEFAULT_RATE_LIMIT
-
- assert isinstance(DEFAULT_RATE_LIMIT, int)
- assert DEFAULT_RATE_LIMIT > 0
-
-
class TestSnippetLengthConstants:
"""Tests for snippet length constants."""
diff --git a/tests/news/test_news_rate_limiting.py b/tests/news/test_news_rate_limiting.py
index 8eb16a0d5a..2c49db33c6 100644
--- a/tests/news/test_news_rate_limiting.py
+++ b/tests/news/test_news_rate_limiting.py
@@ -123,7 +123,7 @@ class TestNewsRateLimitValues:
def test_rate_limiter_imported(self):
source = _get_module_source()
- assert "from ..utils.rate_limiter import limiter" in source
+ assert "from ...security.rate_limiter import limiter" in source
def test_create_limit_value(self):
source = _get_module_source()
diff --git a/tests/research_library/routes/test_rag_routes_coverage.py b/tests/research_library/routes/test_rag_routes_coverage.py
index 1127f80637..8fed168fcd 100644
--- a/tests/research_library/routes/test_rag_routes_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_coverage.py
@@ -156,7 +156,8 @@ def _auth_client(
),
# Disable rate limiter
patch(f"{_ROUTES}.limiter", Mock(exempt=lambda f: f)),
- patch(f"{_ROUTES}.upload_rate_limit", lambda f: f),
+ patch(f"{_ROUTES}.upload_rate_limit_user", lambda f: f),
+ patch(f"{_ROUTES}.upload_rate_limit_ip", lambda f: f),
]
if extra_patches:
patches.extend(extra_patches)
diff --git a/tests/research_library/routes/test_rag_routes_deep_coverage.py b/tests/research_library/routes/test_rag_routes_deep_coverage.py
index dbee70d672..71a6b852ef 100644
--- a/tests/research_library/routes/test_rag_routes_deep_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_deep_coverage.py
@@ -171,7 +171,8 @@ def _auth_client(
return_value=mock_sm,
),
patch(f"{MODULE}.limiter", Mock(exempt=lambda f: f)),
- patch(f"{MODULE}.upload_rate_limit", lambda f: f),
+ patch(f"{MODULE}.upload_rate_limit_user", lambda f: f),
+ patch(f"{MODULE}.upload_rate_limit_ip", lambda f: f),
]
if extra_patches:
patches.extend(extra_patches)
diff --git a/tests/research_library/routes/test_rag_routes_indexing_coverage.py b/tests/research_library/routes/test_rag_routes_indexing_coverage.py
index 38e07ac048..61cce652c2 100644
--- a/tests/research_library/routes/test_rag_routes_indexing_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_indexing_coverage.py
@@ -146,7 +146,8 @@ def _auth_client(
return_value=mock_sm,
),
patch(f"{MODULE}.limiter", Mock(exempt=lambda f: f)),
- patch(f"{MODULE}.upload_rate_limit", lambda f: f),
+ patch(f"{MODULE}.upload_rate_limit_user", lambda f: f),
+ patch(f"{MODULE}.upload_rate_limit_ip", lambda f: f),
]
if extra_patches:
patches.extend(extra_patches)
diff --git a/tests/research_library/routes/test_rag_routes_upload_coverage.py b/tests/research_library/routes/test_rag_routes_upload_coverage.py
index 5586dcf538..e7ce07a12c 100644
--- a/tests/research_library/routes/test_rag_routes_upload_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_upload_coverage.py
@@ -150,7 +150,8 @@ def _auth_client(
return_value=mock_sm,
),
patch(f"{MODULE}.limiter", Mock(exempt=lambda f: f)),
- patch(f"{MODULE}.upload_rate_limit", lambda f: f),
+ patch(f"{MODULE}.upload_rate_limit_user", lambda f: f),
+ patch(f"{MODULE}.upload_rate_limit_ip", lambda f: f),
]
if extra_patches:
patches.extend(extra_patches)
diff --git a/tests/security/test_rate_limiter.py b/tests/security/test_rate_limiter.py
index 07932540d9..23a588a3ec 100644
--- a/tests/security/test_rate_limiter.py
+++ b/tests/security/test_rate_limiter.py
@@ -1,15 +1,8 @@
-"""Tests for rate_limiter module - Flask rate limiting."""
+"""Tests for security/rate_limiter.py."""
import pytest
-from unittest.mock import patch
-from flask import Flask, g
-
-from local_deep_research.security.rate_limiter import (
- get_rate_limiter,
- init_rate_limiter,
- upload_rate_limit,
- RATE_LIMIT_FAIL_CLOSED,
-)
+from unittest.mock import MagicMock, patch
+from flask import Flask
@pytest.fixture
@@ -20,180 +13,595 @@ def app():
return app
-def reset_limiter():
- """Reset global limiter state before and after tests."""
- import local_deep_research.security.rate_limiter as rl_module
+class TestGetClientIp:
+ """Tests for get_client_ip function."""
+
+ def test_returns_first_ip_from_x_forwarded_for(self, app):
+ """Test that first IP from X-Forwarded-For chain is returned."""
+ with app.test_request_context(
+ environ_base={
+ "HTTP_X_FORWARDED_FOR": "192.168.1.100, 10.0.0.1, 172.16.0.1"
+ }
+ ):
+ from local_deep_research.security.rate_limiter import get_client_ip
+
+ result = get_client_ip()
+ assert result == "192.168.1.100"
+
+ def test_strips_whitespace_from_forwarded_ip(self, app):
+ """Test that whitespace is stripped from forwarded IP."""
+ with app.test_request_context(
+ environ_base={"HTTP_X_FORWARDED_FOR": " 192.168.1.100 , 10.0.0.1"}
+ ):
+ from local_deep_research.security.rate_limiter import get_client_ip
+
+ result = get_client_ip()
+ assert result == "192.168.1.100"
+
+ def test_returns_x_real_ip_when_no_forwarded_for(self, app):
+ """Test that X-Real-IP is used when X-Forwarded-For is absent."""
+ with app.test_request_context(
+ environ_base={"HTTP_X_REAL_IP": "10.20.30.40"}
+ ):
+ from local_deep_research.security.rate_limiter import get_client_ip
+
+ result = get_client_ip()
+ assert result == "10.20.30.40"
- original_limiter = rl_module._limiter
- rl_module._limiter = None
- yield
- rl_module._limiter = original_limiter
+ def test_strips_whitespace_from_real_ip(self, app):
+ """Test that whitespace is stripped from X-Real-IP."""
+ with app.test_request_context(
+ environ_base={"HTTP_X_REAL_IP": " 10.20.30.40 "}
+ ):
+ from local_deep_research.security.rate_limiter import get_client_ip
+
+ result = get_client_ip()
+ assert result == "10.20.30.40"
+
+ def test_falls_back_to_remote_address(self, app):
+ """Test fallback to get_remote_address when no proxy headers."""
+ with app.test_request_context():
+ from local_deep_research.security.rate_limiter import get_client_ip
+
+ # When no proxy headers are set, get_remote_address returns the remote addr
+ result = get_client_ip()
+ # Result should be some IP (default is typically 127.0.0.1)
+ assert result is not None
+
+ def test_prefers_x_forwarded_for_over_x_real_ip(self, app):
+ """Test that X-Forwarded-For takes precedence over X-Real-IP."""
+ with app.test_request_context(
+ environ_base={
+ "HTTP_X_FORWARDED_FOR": "192.168.1.1",
+ "HTTP_X_REAL_IP": "10.0.0.1",
+ }
+ ):
+ from local_deep_research.security.rate_limiter import get_client_ip
+ result = get_client_ip()
+ assert result == "192.168.1.1"
-class TestGetRateLimiter:
- """Tests for get_rate_limiter function."""
- def test_raises_when_not_initialized(self, reset_limiter):
- """Should raise RuntimeError when limiter not initialized."""
- with pytest.raises(RuntimeError, match="not initialized"):
- get_rate_limiter()
+class TestRateLimiterConfiguration:
+ """Tests for rate limiter configuration."""
- def test_returns_limiter_when_initialized(self, app, reset_limiter):
- """Should return limiter after initialization."""
- init_rate_limiter(app)
- limiter = get_rate_limiter()
- assert limiter is not None
+ def test_limiter_uses_get_client_ip_as_key_func(self):
+ """Test that limiter is configured with get_client_ip as key function."""
+ from local_deep_research.security.rate_limiter import (
+ limiter,
+ get_client_ip,
+ )
+ assert limiter._key_func == get_client_ip
-class TestInitRateLimiter:
- """Tests for init_rate_limiter function."""
+ def test_limiter_uses_memory_storage(self):
+ """Test that limiter uses in-memory storage by default."""
+ from local_deep_research.security.rate_limiter import limiter
- def test_initializes_limiter(self, app, reset_limiter):
- """Should initialize and return limiter."""
- limiter = init_rate_limiter(app)
- assert limiter is not None
+ # The storage URI should be memory
+ assert limiter._storage_uri == "memory://"
- def test_can_get_limiter_after_init(self, app, reset_limiter):
- """Should be able to get limiter after initialization."""
- init_rate_limiter(app)
- limiter = get_rate_limiter()
- assert limiter is not None
+ def test_limiter_has_headers_enabled(self):
+ """Test that rate limit headers are enabled."""
+ from local_deep_research.security.rate_limiter import limiter
- def test_headers_enabled(self, app, reset_limiter):
- """Should enable rate limit headers."""
- limiter = init_rate_limiter(app)
- # Limiter should have headers enabled
assert limiter._headers_enabled is True
- def test_uses_memory_storage(self, app, reset_limiter):
- """Should use in-memory storage for development."""
- limiter = init_rate_limiter(app)
- # Check storage is configured (memory:// prefix in uri)
- assert limiter is not None
+ def test_login_limit_exists(self):
+ """Test that login_limit is defined."""
+ from local_deep_research.security.rate_limiter import login_limit
+ assert login_limit is not None
-class TestUploadRateLimitDecorator:
- """Tests for upload_rate_limit decorator."""
+ def test_registration_limit_exists(self):
+ """Test that registration_limit is defined."""
+ from local_deep_research.security.rate_limiter import (
+ registration_limit,
+ )
- def test_returns_function_when_limiter_not_initialized(self, reset_limiter):
- """Should return function when limiter not initialized (fail-open)."""
+ assert registration_limit is not None
- def my_upload():
- return "uploaded"
- # Without RATE_LIMIT_FAIL_CLOSED, should pass through
- with patch(
- "local_deep_research.security.rate_limiter.RATE_LIMIT_FAIL_CLOSED",
- False,
- ):
- decorated = upload_rate_limit(my_upload)
- # Should return the original function
- assert decorated() == "uploaded"
+class TestRateLimitConstants:
+ """Tests for rate limit configuration constants."""
- def test_raises_when_fail_closed_and_not_initialized(self, reset_limiter):
- """Should raise RuntimeError when fail-closed and limiter not initialized."""
+ def test_default_rate_limit_loaded_from_config(self):
+ """Test that DEFAULT_RATE_LIMIT is loaded from server config."""
+ from local_deep_research.security.rate_limiter import (
+ DEFAULT_RATE_LIMIT,
+ )
- def my_upload():
- return "uploaded"
+ # Should be a string like "X per hour" or similar
+ assert isinstance(DEFAULT_RATE_LIMIT, str)
+ assert DEFAULT_RATE_LIMIT # Not empty
- with patch(
- "local_deep_research.security.rate_limiter.RATE_LIMIT_FAIL_CLOSED",
- True,
- ):
- with pytest.raises(RuntimeError, match="not initialized"):
- upload_rate_limit(my_upload)
+ def test_login_rate_limit_loaded_from_config(self):
+ """Test that LOGIN_RATE_LIMIT is loaded from server config."""
+ from local_deep_research.security.rate_limiter import LOGIN_RATE_LIMIT
- def test_applies_rate_limit_when_initialized(self, app, reset_limiter):
- """Should apply rate limiting when limiter is initialized."""
- init_rate_limiter(app)
+ assert isinstance(LOGIN_RATE_LIMIT, str)
+ assert LOGIN_RATE_LIMIT # Not empty
- def my_upload():
- return "uploaded"
+ def test_registration_rate_limit_loaded_from_config(self):
+ """Test that REGISTRATION_RATE_LIMIT is loaded from server config."""
+ from local_deep_research.security.rate_limiter import (
+ REGISTRATION_RATE_LIMIT,
+ )
- decorated = upload_rate_limit(my_upload)
+ assert isinstance(REGISTRATION_RATE_LIMIT, str)
+ assert REGISTRATION_RATE_LIMIT # Not empty
- # Decorated function should be wrapped (not the original)
- assert decorated is not my_upload
+ def test_settings_rate_limit_loaded_from_config(self):
+ """Test that SETTINGS_RATE_LIMIT is loaded from config with default fallback."""
+ from local_deep_research.security.rate_limiter import (
+ SETTINGS_RATE_LIMIT,
+ )
- def test_passes_through_on_unexpected_error_fail_open(self, reset_limiter):
- """Should pass through on unexpected error when fail-open."""
+ assert isinstance(SETTINGS_RATE_LIMIT, str)
+ assert SETTINGS_RATE_LIMIT # Not empty
+ # Should contain a rate expression like "30 per minute"
+ assert "per" in SETTINGS_RATE_LIMIT
- def my_upload():
- return "uploaded"
- # Mock get_rate_limiter to raise unexpected error
- with patch(
- "local_deep_research.security.rate_limiter.get_rate_limiter",
- side_effect=RuntimeError("not initialized"),
- ):
- with patch(
- "local_deep_research.security.rate_limiter.RATE_LIMIT_FAIL_CLOSED",
- False,
- ):
- decorated = upload_rate_limit(my_upload)
- # Should return original function
- assert decorated() == "uploaded"
+class TestSettingsLimit:
+ """Tests for settings_limit shared rate limiter (PR #2021)."""
+ def test_settings_limit_exists(self):
+ """Test that settings_limit is defined."""
+ from local_deep_research.security.rate_limiter import settings_limit
-class TestGetUserIdentifier:
- """Tests for user identifier function used by limiter."""
+ assert settings_limit is not None
- def test_uses_username_when_authenticated(self, app, reset_limiter):
- """Should use username when user is authenticated."""
- with app.app_context():
- with patch(
- "local_deep_research.security.rate_limiter.get_remote_address",
- return_value="192.168.1.100",
- ):
- limiter = init_rate_limiter(app)
+ def test_settings_limit_is_shared_limit(self):
+ """Test that settings_limit is a SharedLimitItem from flask-limiter."""
+ from local_deep_research.security.rate_limiter import settings_limit
- # Simulate authenticated user
- g.current_user = "testuser"
+ # SharedLimitItem has a __call__ method (it's a decorator)
+ assert callable(settings_limit)
- # Get the key_func and call it
- key = limiter._key_func()
- assert key == "user:testuser"
+ def test_settings_limit_can_decorate_function(self):
+ """Test that settings_limit can be used as a decorator."""
+ from local_deep_research.security.rate_limiter import settings_limit
- def test_uses_ip_when_not_authenticated(self, app, reset_limiter):
- """Should use IP address when user is not authenticated."""
- with app.app_context():
- with patch(
- "local_deep_research.security.rate_limiter.get_remote_address",
- return_value="192.168.1.100",
- ):
- limiter = init_rate_limiter(app)
+ @settings_limit
+ def dummy_view():
+ return "ok"
- # No authenticated user
- g.current_user = None
+ # The decorated function should still be callable
+ assert callable(dummy_view)
- # Get the key_func and call it
- key = limiter._key_func()
- assert key == "ip:192.168.1.100"
+ def test_settings_limit_default_value(self):
+ """Test that SETTINGS_RATE_LIMIT defaults to 30 per minute."""
+ from local_deep_research.security.rate_limiter import (
+ SETTINGS_RATE_LIMIT,
+ )
+ # The config.get uses "30 per minute" as default
+ # If not set in config, it should be "30 per minute"
+ assert isinstance(SETTINGS_RATE_LIMIT, str)
+ assert SETTINGS_RATE_LIMIT # Not empty
-class TestRateLimitFailClosed:
- """Tests for RATE_LIMIT_FAIL_CLOSED configuration."""
- def test_default_is_fail_open(self):
- """RATE_LIMIT_FAIL_CLOSED should default to False."""
- # Default should be fail-open for easier development
- # Note: actual value depends on environment, testing the behavior
- assert isinstance(RATE_LIMIT_FAIL_CLOSED, bool)
+class TestApiRateLimit:
+ """Tests for api_rate_limit shared limiter."""
- def test_environment_variable_parsing(self):
- """Should parse RATE_LIMIT_FAIL_CLOSED from environment."""
- import os
+ def test_api_rate_limit_exists(self):
+ """Test that api_rate_limit is defined."""
+ from local_deep_research.security.rate_limiter import api_rate_limit
- with patch.dict(os.environ, {"RATE_LIMIT_FAIL_CLOSED": "true"}):
- # Re-import to pick up environment variable
- import importlib
- import local_deep_research.security.rate_limiter as rl
+ assert api_rate_limit is not None
- importlib.reload(rl)
- assert rl.RATE_LIMIT_FAIL_CLOSED is True
+ def test_api_rate_limit_is_callable(self):
+ """Test that api_rate_limit can be used as a decorator."""
+ from local_deep_research.security.rate_limiter import api_rate_limit
- # Reset
- with patch.dict(os.environ, {"RATE_LIMIT_FAIL_CLOSED": "false"}):
- importlib.reload(rl)
- assert rl.RATE_LIMIT_FAIL_CLOSED is False
+ assert callable(api_rate_limit)
+
+ def test_get_user_api_rate_limit_default(self, app):
+ """Test that _get_user_api_rate_limit returns default when no user."""
+
+ with app.test_request_context():
+ from local_deep_research.security.rate_limiter import (
+ _get_user_api_rate_limit,
+ )
+
+ result = _get_user_api_rate_limit()
+ assert result == 60
+
+ def test_get_api_rate_limit_string_format(self, app):
+ """Test that _get_api_rate_limit_string returns correct format."""
+ from unittest.mock import patch
+
+ with app.test_request_context():
+ with patch(
+ "local_deep_research.security.rate_limiter._get_user_api_rate_limit",
+ return_value=30,
+ ):
+ from local_deep_research.security.rate_limiter import (
+ _get_api_rate_limit_string,
+ )
+
+ result = _get_api_rate_limit_string()
+ assert result == "30 per minute"
+
+ def test_is_api_rate_limit_exempt_no_user(self, app):
+ """Test that unauthenticated requests are exempt."""
+ with app.test_request_context():
+ from local_deep_research.security.rate_limiter import (
+ _is_api_rate_limit_exempt,
+ )
+
+ assert _is_api_rate_limit_exempt() is True
+
+ def test_is_api_rate_limit_exempt_zero_limit(self, app):
+ """Test that rate_limit=0 means exempt."""
+ from unittest.mock import patch
+
+ app.config["SECRET_KEY"] = "test-secret"
+ with app.test_request_context():
+ from flask import g
+
+ g.current_user = "testuser"
+
+ with patch(
+ "local_deep_research.security.rate_limiter._get_user_api_rate_limit",
+ return_value=0,
+ ):
+ from local_deep_research.security.rate_limiter import (
+ _is_api_rate_limit_exempt,
+ )
+
+ assert _is_api_rate_limit_exempt() is True
+
+ def test_get_api_user_key_with_user(self, app):
+ """Test that key function returns user-prefixed key."""
+ with app.test_request_context():
+ from flask import g
+
+ g.current_user = "alice"
+
+ from local_deep_research.security.rate_limiter import (
+ _get_api_user_key,
+ )
+
+ result = _get_api_user_key()
+ assert result == "api_user:alice"
+
+
+class TestUploadRateLimit:
+ """Tests for upload_rate_limit_user and upload_rate_limit_ip shared limiters."""
+
+ def test_upload_rate_limit_user_exists_and_callable(self):
+ """Test that upload_rate_limit_user is defined and callable."""
+ from local_deep_research.security.rate_limiter import (
+ upload_rate_limit_user,
+ )
+
+ assert upload_rate_limit_user is not None
+ assert callable(upload_rate_limit_user)
+
+ def test_upload_rate_limit_ip_exists_and_callable(self):
+ """Test that upload_rate_limit_ip is defined and callable."""
+ from local_deep_research.security.rate_limiter import (
+ upload_rate_limit_ip,
+ )
+
+ assert upload_rate_limit_ip is not None
+ assert callable(upload_rate_limit_ip)
+
+ def test_get_upload_user_key_with_user(self, app):
+ """Test that upload key function returns user-prefixed key."""
+ with app.test_request_context():
+ from flask import g
+
+ g.current_user = "bob"
+
+ from local_deep_research.security.rate_limiter import (
+ _get_upload_user_key,
+ )
+
+ result = _get_upload_user_key()
+ assert result == "upload_user:bob"
+
+ def test_get_upload_user_key_no_user(self, app):
+ """Test that upload key function falls back to IP when no user."""
+ with app.test_request_context():
+ from local_deep_research.security.rate_limiter import (
+ _get_upload_user_key,
+ )
+
+ result = _get_upload_user_key()
+ assert result.startswith("upload_ip:")
+
+
+class TestUploadRateLimitFunctional:
+ """Functional tests for dual-key upload rate limiting."""
+
+ def test_upload_rate_limit_enforces_per_user(self):
+ """Per-user upload limit blocks after threshold."""
+ from local_deep_research.security.rate_limiter import (
+ limiter,
+ upload_rate_limit_ip,
+ upload_rate_limit_user,
+ )
+
+ test_app = Flask(__name__)
+ test_app.config["SECRET_KEY"] = "test"
+ test_app.config["TESTING"] = True
+ test_app.config["RATELIMIT_ENABLED"] = True
+ test_app.config["RATELIMIT_STRATEGY"] = "moving-window"
+
+ @test_app.route("/upload", methods=["POST"])
+ @upload_rate_limit_user
+ @upload_rate_limit_ip
+ def upload():
+ return "ok"
+
+ limiter.init_app(test_app)
+
+ with test_app.test_client() as c:
+ with c.session_transaction() as sess:
+ sess["username"] = "uploader"
+ # The limit is "10 per minute" — make 11 requests
+ for i in range(10):
+ resp = c.post("/upload")
+ assert resp.status_code == 200, f"Request {i + 1} should pass"
+ resp = c.post("/upload")
+ assert resp.status_code == 429
+
+ try:
+ limiter.reset()
+ except Exception:
+ pass
+
+ def test_upload_per_user_limit_is_independent(self):
+ """Per-user upload bucket is keyed by username, not shared."""
+ from local_deep_research.security.rate_limiter import (
+ limiter,
+ upload_rate_limit_user,
+ )
+
+ test_app = Flask(__name__)
+ test_app.config["SECRET_KEY"] = "test"
+ test_app.config["TESTING"] = True
+ test_app.config["RATELIMIT_ENABLED"] = True
+ test_app.config["RATELIMIT_STRATEGY"] = "moving-window"
+
+ # Only per-user limit (no per-IP) to isolate user-key behavior
+ @test_app.route("/upload", methods=["POST"])
+ @upload_rate_limit_user
+ def upload():
+ return "ok"
+
+ limiter.init_app(test_app)
+
+ # User A exhausts their per-user limit
+ client_a = test_app.test_client()
+ with client_a.session_transaction() as sess:
+ sess["username"] = "user_a"
+ for _ in range(10):
+ client_a.post("/upload")
+ assert client_a.post("/upload").status_code == 429
+
+ # User B is unaffected (different user bucket)
+ client_b = test_app.test_client()
+ with client_b.session_transaction() as sess:
+ sess["username"] = "user_b"
+ assert client_b.post("/upload").status_code == 200
+
+ try:
+ limiter.reset()
+ except Exception:
+ pass
+
+
+class TestApiRateLimitCaching:
+ """Tests for g-caching and DB fallback in _get_user_api_rate_limit."""
+
+ def test_g_cache_hit_skips_db(self, app):
+ """Second call returns cached value without DB access."""
+ with app.test_request_context():
+ from flask import g
+ from local_deep_research.security.rate_limiter import (
+ _get_user_api_rate_limit,
+ )
+
+ g._api_rate_limit = 42
+ result = _get_user_api_rate_limit()
+ assert result == 42
+
+ def test_db_exception_falls_back_to_default(self, app):
+ """DB failure returns default 60 without raising."""
+ app.config["SECRET_KEY"] = "test"
+ with app.test_request_context():
+ from flask import g
+ from local_deep_research.security.rate_limiter import (
+ _get_user_api_rate_limit,
+ )
+
+ g.current_user = "testuser"
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=RuntimeError("DB down"),
+ ):
+ result = _get_user_api_rate_limit()
+ assert result == 60
+
+ def test_custom_rate_limit_from_db(self, app):
+ """User-configured rate limit is returned from DB."""
+ app.config["SECRET_KEY"] = "test"
+ with app.test_request_context():
+ from flask import g
+ from local_deep_research.security.rate_limiter import (
+ _get_user_api_rate_limit,
+ )
+
+ g.current_user = "testuser"
+ mock_sm = MagicMock()
+ mock_sm.get_setting.return_value = 30
+
+ mock_session = MagicMock()
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_ctx:
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=None)
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=mock_sm,
+ ):
+ result = _get_user_api_rate_limit()
+ assert result == 30
+ assert g._api_rate_limit == 30
+
+
+class TestSessionFallback:
+ """Tests for session fallback when g.current_user is not set."""
+
+ def test_api_user_key_uses_session_fallback(self, app):
+ """Key function uses session username when g.current_user absent."""
+ app.config["SECRET_KEY"] = "test"
+ with app.test_request_context():
+ from local_deep_research.security.rate_limiter import (
+ _get_api_user_key,
+ )
+
+ with app.test_client() as c:
+ with c.session_transaction() as sess:
+ sess["username"] = "session_user"
+ with c.application.test_request_context():
+ from flask import session as s
+
+ s["username"] = "session_user"
+ result = _get_api_user_key()
+ assert result == "api_user:session_user"
+
+ def test_upload_user_key_uses_session_fallback(self, app):
+ """Upload key function uses session username when g.current_user absent."""
+ app.config["SECRET_KEY"] = "test"
+ with app.test_request_context():
+ from local_deep_research.security.rate_limiter import (
+ _get_upload_user_key,
+ )
+
+ with app.test_client() as c:
+ with c.application.test_request_context():
+ from flask import session as s
+
+ s["username"] = "session_uploader"
+ result = _get_upload_user_key()
+ assert result == "upload_user:session_uploader"
+
+ def test_g_current_user_takes_priority_over_session(self, app):
+ """g.current_user is preferred over session username."""
+ app.config["SECRET_KEY"] = "test"
+ with app.test_request_context():
+ from flask import g, session
+ from local_deep_research.security.rate_limiter import (
+ _get_api_user_key,
+ )
+
+ g.current_user = "g_user"
+ session["username"] = "session_user"
+ result = _get_api_user_key()
+ assert result == "api_user:g_user"
+
+ def test_exempt_uses_session_fallback(self, app):
+ """Exempt check uses session username when g.current_user absent."""
+ app.config["SECRET_KEY"] = "test"
+ with app.test_request_context():
+ from flask import session
+ from local_deep_research.security.rate_limiter import (
+ _is_api_rate_limit_exempt,
+ )
+
+ # No g.current_user, no session username → exempt
+ assert _is_api_rate_limit_exempt() is True
+
+ # Set session username → not exempt (has user, default limit > 0)
+ session["username"] = "session_user"
+ with patch(
+ "local_deep_research.security.rate_limiter._get_user_api_rate_limit",
+ return_value=60,
+ ):
+ assert _is_api_rate_limit_exempt() is False
+
+
+class TestGetCurrentUsername:
+ """Tests for get_current_username helper."""
+
+ def test_returns_g_current_user(self, app):
+ with app.test_request_context():
+ from flask import g
+ from local_deep_research.security.rate_limiter import (
+ get_current_username,
+ )
+
+ g.current_user = "alice"
+ assert get_current_username() == "alice"
+
+ def test_returns_session_when_no_g_current_user(self, app):
+ app.config["SECRET_KEY"] = "test"
+ with app.test_request_context():
+ from flask import session
+ from local_deep_research.security.rate_limiter import (
+ get_current_username,
+ )
+
+ session["username"] = "bob"
+ assert get_current_username() == "bob"
+
+ def test_returns_none_when_neither_set(self, app):
+ with app.test_request_context():
+ from local_deep_research.security.rate_limiter import (
+ get_current_username,
+ )
+
+ assert get_current_username() is None
+
+ def test_g_current_user_priority_over_session(self, app):
+ app.config["SECRET_KEY"] = "test"
+ with app.test_request_context():
+ from flask import g, session
+ from local_deep_research.security.rate_limiter import (
+ get_current_username,
+ )
+
+ g.current_user = "g_user"
+ session["username"] = "session_user"
+ assert get_current_username() == "g_user"
+
+ def test_empty_string_g_current_user_falls_to_session(self, app):
+ """Empty string g.current_user is falsy — should fall through to session."""
+ app.config["SECRET_KEY"] = "test"
+ with app.test_request_context():
+ from flask import g, session
+ from local_deep_research.security.rate_limiter import (
+ get_current_username,
+ )
+
+ g.current_user = ""
+ session["username"] = "session_user"
+ assert get_current_username() == "session_user"
diff --git a/tests/security/test_security_import_fallbacks_coverage.py b/tests/security/test_security_import_fallbacks_coverage.py
index 0ed25f14d7..d00024bd7b 100644
--- a/tests/security/test_security_import_fallbacks_coverage.py
+++ b/tests/security/test_security_import_fallbacks_coverage.py
@@ -1,10 +1,8 @@
"""Coverage tests for security/__init__.py ImportError fallback branches.
-The 11 missing statements are all in try/except ImportError blocks:
+The missing statements are in try/except ImportError blocks:
- PathValidator import fails → PathValidator=None, _has_path_validator=False
- FileUploadValidator import fails → FileUploadValidator=None, _has_file_upload_validator=False
-- rate_limiter import fails → init_rate_limiter=None, _has_rate_limiter=False,
- upload_rate_limit becomes no-op decorator
"""
import importlib
@@ -67,26 +65,3 @@ class TestFileUploadValidatorImportFallback:
)
assert sec.FileUploadValidator is None
assert sec._has_file_upload_validator is False
-
-
-class TestRateLimiterImportFallback:
- def test_rate_limiter_import_error(self):
- """When rate_limiter import fails, init_rate_limiter is None."""
- sec = _reload_security_with_blocked(
- "local_deep_research.security.rate_limiter"
- )
- assert sec.init_rate_limiter is None
- assert sec._has_rate_limiter is False
-
- def test_fallback_upload_rate_limit_is_noop(self):
- """Fallback upload_rate_limit decorator returns the function unchanged."""
- sec = _reload_security_with_blocked(
- "local_deep_research.security.rate_limiter"
- )
-
- def my_func():
- return "hello"
-
- decorated = sec.upload_rate_limit(my_func)
- assert decorated is my_func
- assert decorated() == "hello"
diff --git a/tests/security/test_security_init_coverage.py b/tests/security/test_security_init_coverage.py
index 9a4d1be176..31f833c397 100644
--- a/tests/security/test_security_init_coverage.py
+++ b/tests/security/test_security_init_coverage.py
@@ -35,27 +35,6 @@ class TestSecurityImports:
if sec._has_file_upload_validator:
assert sec.FileUploadValidator is not None
- def test_rate_limiter_available(self):
- """Rate limiter available when flask_limiter is installed."""
- import local_deep_research.security as sec
-
- if sec._has_rate_limiter:
- assert sec.init_rate_limiter is not None
- assert callable(sec.upload_rate_limit)
-
- def test_upload_rate_limit_noop_when_no_limiter(self):
- """upload_rate_limit is a no-op decorator when flask_limiter missing."""
- import local_deep_research.security as sec
-
- if not sec._has_rate_limiter:
- # The no-op decorator should return the function unchanged
- def my_func():
- return 42
-
- wrapped = sec.upload_rate_limit(my_func)
- assert wrapped is my_func
- assert wrapped() == 42
-
def test_safe_get_exported(self):
"""safe_get is properly exported."""
from local_deep_research.security import safe_get
diff --git a/tests/security/test_security_init_deep_coverage.py b/tests/security/test_security_init_deep_coverage.py
index 54d19314a1..16cb5da995 100644
--- a/tests/security/test_security_init_deep_coverage.py
+++ b/tests/security/test_security_init_deep_coverage.py
@@ -3,18 +3,14 @@
The __init__.py conditionally imports several optional components:
- PathValidator (requires werkzeug)
- FileUploadValidator (requires pdfplumber)
-- init_rate_limiter / upload_rate_limit (requires flask_limiter)
Tests cover:
- All required imports are present
- Conditional flag values
-- upload_rate_limit no-op decorator fallback behaviour
- __all__ completeness
- Individual security re-exports callable/usable
"""
-import pytest
-
MODULE = "local_deep_research.security"
@@ -153,11 +149,6 @@ class TestConditionalFlags:
assert isinstance(sec._has_file_upload_validator, bool)
- def test_has_rate_limiter_flag_is_bool(self):
- import local_deep_research.security as sec
-
- assert isinstance(sec._has_rate_limiter, bool)
-
def test_path_validator_is_class_or_none(self):
from local_deep_research.security import PathValidator
@@ -179,42 +170,6 @@ class TestConditionalFlags:
assert sec.PathValidator is None
-class TestUploadRateLimitFallback:
- def test_upload_rate_limit_is_callable(self):
- from local_deep_research.security import upload_rate_limit
-
- assert callable(upload_rate_limit)
-
- def test_fallback_decorator_preserves_function(self):
- """When flask_limiter is not available, upload_rate_limit is a no-op."""
- import local_deep_research.security as sec
-
- if sec._has_rate_limiter:
- pytest.skip("flask_limiter is installed; fallback not active")
-
- from local_deep_research.security import upload_rate_limit
-
- def my_view():
- return "response"
-
- decorated = upload_rate_limit(my_view)
- assert decorated() == "response"
-
- def test_fallback_decorator_passes_args(self):
- import local_deep_research.security as sec
-
- if sec._has_rate_limiter:
- pytest.skip("flask_limiter is installed; fallback not active")
-
- from local_deep_research.security import upload_rate_limit
-
- def my_view(x, y=10):
- return x + y
-
- decorated = upload_rate_limit(my_view)
- assert decorated(5, y=3) == 8
-
-
class TestDunderAll:
def test_all_is_list(self):
import local_deep_research.security as sec
diff --git a/tests/web/routes/test_history_routes.py b/tests/web/routes/test_history_routes.py
index 471bcb4ab8..c13bae18e1 100644
--- a/tests/web/routes/test_history_routes.py
+++ b/tests/web/routes/test_history_routes.py
@@ -34,7 +34,7 @@ def authenticated_client():
lambda f: f,
):
with patch(
- "local_deep_research.web.utils.rate_limiter.limiter"
+ "local_deep_research.security.rate_limiter.limiter"
) as mock_limiter:
mock_limiter.exempt = lambda f: f
diff --git a/tests/web/test_api.py b/tests/web/test_api.py
index 0c1f9bf873..43507dcd06 100644
--- a/tests/web/test_api.py
+++ b/tests/web/test_api.py
@@ -81,7 +81,6 @@ class TestApiDocumentation:
mock_manager = MagicMock()
mock_manager.get_setting.side_effect = lambda key, default: {
"app.enable_api": True,
- "app.api_rate_limit": 60,
}.get(key, default)
mock_settings.return_value = mock_manager
@@ -111,7 +110,6 @@ class TestApiDocumentation:
mock_manager = MagicMock()
mock_manager.get_setting.side_effect = lambda key, default: {
"app.enable_api": True,
- "app.api_rate_limit": 60,
}.get(key, default)
mock_settings.return_value = mock_manager
@@ -148,7 +146,6 @@ class TestApiAccessControl:
mock_manager = MagicMock()
mock_manager.get_setting.side_effect = lambda key, default: {
"app.enable_api": False, # API disabled
- "app.api_rate_limit": 60,
}.get(key, default)
mock_settings.return_value = mock_manager
@@ -180,15 +177,9 @@ class TestRateLimiting:
mock_manager = MagicMock()
mock_manager.get_setting.side_effect = lambda key, default: {
"app.enable_api": True,
- "app.api_rate_limit": 100, # High limit
}.get(key, default)
mock_settings.return_value = mock_manager
- # Clear rate limit data
- from local_deep_research.web.api import rate_limit_data
-
- rate_limit_data.clear()
-
# Make a few requests
for _ in range(3):
response = authenticated_client.get("/api/v1/")
@@ -221,14 +212,9 @@ class TestQuickSummaryQueryTypeValidation:
mock_manager = MagicMock()
mock_manager.get_setting.side_effect = lambda key, default: {
"app.enable_api": True,
- "app.api_rate_limit": 60,
}.get(key, default)
mock_settings.return_value = mock_manager
- from local_deep_research.web.api import rate_limit_data
-
- rate_limit_data.clear()
-
return authenticated_client.post(
"/api/v1/quick_summary",
json=json_data,
@@ -283,15 +269,9 @@ class TestQuickSummaryTestEndpoint:
mock_manager = MagicMock()
mock_manager.get_setting.side_effect = lambda key, default: {
"app.enable_api": True,
- "app.api_rate_limit": 60,
}.get(key, default)
mock_settings.return_value = mock_manager
- # Clear rate limit data
- from local_deep_research.web.api import rate_limit_data
-
- rate_limit_data.clear()
-
response = authenticated_client.post(
"/api/v1/quick_summary_test",
json={}, # No query parameter
@@ -319,15 +299,9 @@ class TestQuickSummaryTestEndpoint:
mock_manager = MagicMock()
mock_manager.get_setting.side_effect = lambda key, default: {
"app.enable_api": True,
- "app.api_rate_limit": 60,
}.get(key, default)
mock_settings.return_value = mock_manager
- # Clear rate limit data
- from local_deep_research.web.api import rate_limit_data
-
- rate_limit_data.clear()
-
response = authenticated_client.post(
"/api/v1/quick_summary_test",
content_type="application/json",
diff --git a/tests/web/test_api_coverage.py b/tests/web/test_api_coverage.py
index 01fbd7ff13..f920603081 100644
--- a/tests/web/test_api_coverage.py
+++ b/tests/web/test_api_coverage.py
@@ -12,7 +12,8 @@ from unittest.mock import MagicMock, patch
import pytest
from flask import Flask
-from local_deep_research.web.api import api_blueprint, rate_limit_data
+from local_deep_research.web.api import api_blueprint
+from local_deep_research.security.rate_limiter import limiter
# ---------------------------------------------------------------------------
@@ -27,7 +28,7 @@ def _auth_session(client, username="testuser"):
@contextmanager
-def _mock_access_control(*, api_enabled=True, rate_limit=60):
+def _mock_access_control(*, api_enabled=True):
"""Context manager that patches get_user_db_session + get_settings_manager
so that the api_access_control decorator lets requests through (or blocks
them if api_enabled=False)."""
@@ -42,7 +43,6 @@ def _mock_access_control(*, api_enabled=True, rate_limit=60):
mock_manager = MagicMock()
mock_manager.get_setting.side_effect = lambda key, default: {
"app.enable_api": api_enabled,
- "app.api_rate_limit": rate_limit,
}.get(key, default)
mock_sm.return_value = mock_manager
@@ -55,11 +55,13 @@ def _mock_access_control(*, api_enabled=True, rate_limit=60):
@pytest.fixture(autouse=True)
-def _clear_rate_limits():
- """Ensure rate-limit state is clean for every test."""
- rate_limit_data.clear()
+def _reset_limiter():
+ """Reset Flask-Limiter storage between tests."""
yield
- rate_limit_data.clear()
+ try:
+ limiter.reset()
+ except Exception:
+ pass
@pytest.fixture
@@ -68,7 +70,10 @@ def app():
flask_app.config["SECRET_KEY"] = "test-secret"
flask_app.config["TESTING"] = True
flask_app.config["WTF_CSRF_ENABLED"] = False
+ flask_app.config["RATELIMIT_ENABLED"] = True
+ flask_app.config["RATELIMIT_STRATEGY"] = "moving-window"
flask_app.register_blueprint(api_blueprint)
+ limiter.init_app(flask_app)
return flask_app
@@ -167,32 +172,115 @@ class TestApiAccessControl:
assert "disabled" in resp.get_json()["error"].lower()
def test_rate_limit_exceeded_returns_429(self, authed_client):
- with _mock_access_control(rate_limit=2):
- # First two should pass
- resp1 = authed_client.get("/api/v1/")
- assert resp1.status_code == 200
- resp2 = authed_client.get("/api/v1/")
- assert resp2.status_code == 200
- # Third should be rate-limited
- resp3 = authed_client.get("/api/v1/")
- assert resp3.status_code == 429
- assert "rate limit" in resp3.get_json()["error"].lower()
+ with _mock_access_control():
+ with patch(
+ "local_deep_research.security.rate_limiter._get_user_api_rate_limit",
+ return_value=2,
+ ):
+ # First two should pass
+ resp1 = authed_client.get("/api/v1/")
+ assert resp1.status_code == 200
+ resp2 = authed_client.get("/api/v1/")
+ assert resp2.status_code == 200
+ # Third should be rate-limited
+ resp3 = authed_client.get("/api/v1/")
+ assert resp3.status_code == 429
+
+ def test_rate_limit_429_returns_json_with_custom_handler(self, app):
+ """429 response has JSON body with 'error' and 'message' keys
+ when the custom handler from app_factory is registered."""
+ from flask import jsonify
+
+ # Register the same custom 429 handler as app_factory.py
+ @app.errorhandler(429)
+ def ratelimit_handler(e):
+ return (
+ jsonify(
+ error="Too many requests",
+ message="Too many attempts. Please try again later.",
+ ),
+ 429,
+ )
- def test_rate_limit_zero_means_no_limiting(self, authed_client):
- """rate_limit=0 (falsy) should skip the rate-limiting block."""
- with _mock_access_control(rate_limit=0):
- for _ in range(5):
+ with app.test_client() as client:
+ _auth_session(client)
+ with _mock_access_control():
+ with patch(
+ "local_deep_research.security.rate_limiter._get_user_api_rate_limit",
+ return_value=1,
+ ):
+ # First request passes
+ resp1 = client.get("/api/v1/")
+ assert resp1.status_code == 200
+ # Second hits the limit
+ resp2 = client.get("/api/v1/")
+ assert resp2.status_code == 429
+ body = resp2.get_json()
+ assert body is not None, "429 response should be JSON"
+ assert body["error"] == "Too many requests"
+ assert "message" in body
+
+ def test_rate_limit_headers_present_on_success(self, authed_client):
+ """Successful responses include X-RateLimit headers."""
+ with _mock_access_control():
+ with patch(
+ "local_deep_research.security.rate_limiter._get_user_api_rate_limit",
+ return_value=10,
+ ):
resp = authed_client.get("/api/v1/")
assert resp.status_code == 200
+ # Flask-Limiter adds these headers when headers_enabled=True
+ assert "X-RateLimit-Limit" in resp.headers
+ assert "X-RateLimit-Remaining" in resp.headers
+ assert "X-RateLimit-Reset" in resp.headers
- def test_old_timestamps_are_cleaned_up(self, authed_client):
- """Timestamps older than RATE_LIMIT_WINDOW_SECONDS should be pruned."""
- with _mock_access_control(rate_limit=2):
- # Prepopulate with an old timestamp
- rate_limit_data["127.0.0.1"] = [time.time() - 120]
- # Even though there's an entry, the old one should be purged
- resp = authed_client.get("/api/v1/")
- assert resp.status_code == 200
+ def test_rate_limit_remaining_header_decrements(self, authed_client):
+ """X-RateLimit-Remaining decrements with each request."""
+ with _mock_access_control():
+ with patch(
+ "local_deep_research.security.rate_limiter._get_user_api_rate_limit",
+ return_value=5,
+ ):
+ resp1 = authed_client.get("/api/v1/")
+ assert resp1.status_code == 200
+ remaining1 = int(resp1.headers["X-RateLimit-Remaining"])
+
+ resp2 = authed_client.get("/api/v1/")
+ assert resp2.status_code == 200
+ remaining2 = int(resp2.headers["X-RateLimit-Remaining"])
+
+ assert remaining2 == remaining1 - 1
+
+ def test_different_users_have_independent_buckets(self, app):
+ """User A hitting their limit does not affect User B."""
+ with _mock_access_control():
+ with patch(
+ "local_deep_research.security.rate_limiter._get_user_api_rate_limit",
+ return_value=2,
+ ):
+ # User A exhausts their limit
+ client_a = app.test_client()
+ _auth_session(client_a, username="alice")
+ assert client_a.get("/api/v1/").status_code == 200
+ assert client_a.get("/api/v1/").status_code == 200
+ assert client_a.get("/api/v1/").status_code == 429
+
+ # User B is unaffected
+ client_b = app.test_client()
+ _auth_session(client_b, username="bob")
+ assert client_b.get("/api/v1/").status_code == 200
+ assert client_b.get("/api/v1/").status_code == 200
+
+ def test_rate_limit_zero_means_no_limiting(self, authed_client):
+ """rate_limit=0 (falsy) should exempt from rate limiting."""
+ with _mock_access_control():
+ with patch(
+ "local_deep_research.security.rate_limiter._get_user_api_rate_limit",
+ return_value=0,
+ ):
+ for _ in range(5):
+ resp = authed_client.get("/api/v1/")
+ assert resp.status_code == 200
def test_g_current_user_fallback(self, app):
"""When g.current_user is set, it should be used instead of session."""
@@ -454,7 +542,6 @@ class TestQuickSummary:
# Also handle the api_access_control decorator calls
mock_sm_instance.get_setting.side_effect = lambda key, default: {
"app.enable_api": True,
- "app.api_rate_limit": 60,
}.get(key, default)
# The decorator uses module-level imports while the function body
diff --git a/tests/web/test_app_factory.py b/tests/web/test_app_factory.py
index 12057dceb3..9759c83c3d 100644
--- a/tests/web/test_app_factory.py
+++ b/tests/web/test_app_factory.py
@@ -276,7 +276,7 @@ class TestRateLimiting:
def test_limiter_initialized(self, app):
"""Rate limiter is initialized."""
- from local_deep_research.web.utils.rate_limiter import limiter
+ from local_deep_research.security.rate_limiter import limiter
# Limiter should be attached to the app
assert limiter is not None
diff --git a/tests/web/utils/test_rate_limiter.py b/tests/web/utils/test_rate_limiter.py
deleted file mode 100644
index 5511ddd116..0000000000
--- a/tests/web/utils/test_rate_limiter.py
+++ /dev/null
@@ -1,201 +0,0 @@
-"""Tests for web/utils/rate_limiter.py."""
-
-import pytest
-from flask import Flask
-
-
-def app():
- """Create test Flask application."""
- app = Flask(__name__)
- app.config["TESTING"] = True
- return app
-
-
-class TestGetClientIp:
- """Tests for get_client_ip function."""
-
- def test_returns_first_ip_from_x_forwarded_for(self, app):
- """Test that first IP from X-Forwarded-For chain is returned."""
- with app.test_request_context(
- environ_base={
- "HTTP_X_FORWARDED_FOR": "192.168.1.100, 10.0.0.1, 172.16.0.1"
- }
- ):
- from local_deep_research.web.utils.rate_limiter import get_client_ip
-
- result = get_client_ip()
- assert result == "192.168.1.100"
-
- def test_strips_whitespace_from_forwarded_ip(self, app):
- """Test that whitespace is stripped from forwarded IP."""
- with app.test_request_context(
- environ_base={"HTTP_X_FORWARDED_FOR": " 192.168.1.100 , 10.0.0.1"}
- ):
- from local_deep_research.web.utils.rate_limiter import get_client_ip
-
- result = get_client_ip()
- assert result == "192.168.1.100"
-
- def test_returns_x_real_ip_when_no_forwarded_for(self, app):
- """Test that X-Real-IP is used when X-Forwarded-For is absent."""
- with app.test_request_context(
- environ_base={"HTTP_X_REAL_IP": "10.20.30.40"}
- ):
- from local_deep_research.web.utils.rate_limiter import get_client_ip
-
- result = get_client_ip()
- assert result == "10.20.30.40"
-
- def test_strips_whitespace_from_real_ip(self, app):
- """Test that whitespace is stripped from X-Real-IP."""
- with app.test_request_context(
- environ_base={"HTTP_X_REAL_IP": " 10.20.30.40 "}
- ):
- from local_deep_research.web.utils.rate_limiter import get_client_ip
-
- result = get_client_ip()
- assert result == "10.20.30.40"
-
- def test_falls_back_to_remote_address(self, app):
- """Test fallback to get_remote_address when no proxy headers."""
- with app.test_request_context():
- from local_deep_research.web.utils.rate_limiter import get_client_ip
-
- # When no proxy headers are set, get_remote_address returns the remote addr
- result = get_client_ip()
- # Result should be some IP (default is typically 127.0.0.1)
- assert result is not None
-
- def test_prefers_x_forwarded_for_over_x_real_ip(self, app):
- """Test that X-Forwarded-For takes precedence over X-Real-IP."""
- with app.test_request_context(
- environ_base={
- "HTTP_X_FORWARDED_FOR": "192.168.1.1",
- "HTTP_X_REAL_IP": "10.0.0.1",
- }
- ):
- from local_deep_research.web.utils.rate_limiter import get_client_ip
-
- result = get_client_ip()
- assert result == "192.168.1.1"
-
-
-class TestRateLimiterConfiguration:
- """Tests for rate limiter configuration."""
-
- def test_limiter_uses_get_client_ip_as_key_func(self):
- """Test that limiter is configured with get_client_ip as key function."""
- from local_deep_research.web.utils.rate_limiter import (
- limiter,
- get_client_ip,
- )
-
- assert limiter._key_func == get_client_ip
-
- def test_limiter_uses_memory_storage(self):
- """Test that limiter uses in-memory storage by default."""
- from local_deep_research.web.utils.rate_limiter import limiter
-
- # The storage URI should be memory
- assert limiter._storage_uri == "memory://"
-
- def test_limiter_has_headers_enabled(self):
- """Test that rate limit headers are enabled."""
- from local_deep_research.web.utils.rate_limiter import limiter
-
- assert limiter._headers_enabled is True
-
- def test_login_limit_exists(self):
- """Test that login_limit is defined."""
- from local_deep_research.web.utils.rate_limiter import login_limit
-
- assert login_limit is not None
-
- def test_registration_limit_exists(self):
- """Test that registration_limit is defined."""
- from local_deep_research.web.utils.rate_limiter import (
- registration_limit,
- )
-
- assert registration_limit is not None
-
-
-class TestRateLimitConstants:
- """Tests for rate limit configuration constants."""
-
- def test_default_rate_limit_loaded_from_config(self):
- """Test that DEFAULT_RATE_LIMIT is loaded from server config."""
- from local_deep_research.web.utils.rate_limiter import (
- DEFAULT_RATE_LIMIT,
- )
-
- # Should be a string like "X per hour" or similar
- assert isinstance(DEFAULT_RATE_LIMIT, str)
- assert DEFAULT_RATE_LIMIT # Not empty
-
- def test_login_rate_limit_loaded_from_config(self):
- """Test that LOGIN_RATE_LIMIT is loaded from server config."""
- from local_deep_research.web.utils.rate_limiter import LOGIN_RATE_LIMIT
-
- assert isinstance(LOGIN_RATE_LIMIT, str)
- assert LOGIN_RATE_LIMIT # Not empty
-
- def test_registration_rate_limit_loaded_from_config(self):
- """Test that REGISTRATION_RATE_LIMIT is loaded from server config."""
- from local_deep_research.web.utils.rate_limiter import (
- REGISTRATION_RATE_LIMIT,
- )
-
- assert isinstance(REGISTRATION_RATE_LIMIT, str)
- assert REGISTRATION_RATE_LIMIT # Not empty
-
- def test_settings_rate_limit_loaded_from_config(self):
- """Test that SETTINGS_RATE_LIMIT is loaded from config with default fallback."""
- from local_deep_research.web.utils.rate_limiter import (
- SETTINGS_RATE_LIMIT,
- )
-
- assert isinstance(SETTINGS_RATE_LIMIT, str)
- assert SETTINGS_RATE_LIMIT # Not empty
- # Should contain a rate expression like "30 per minute"
- assert "per" in SETTINGS_RATE_LIMIT
-
-
-class TestSettingsLimit:
- """Tests for settings_limit shared rate limiter (PR #2021)."""
-
- def test_settings_limit_exists(self):
- """Test that settings_limit is defined."""
- from local_deep_research.web.utils.rate_limiter import settings_limit
-
- assert settings_limit is not None
-
- def test_settings_limit_is_shared_limit(self):
- """Test that settings_limit is a SharedLimitItem from flask-limiter."""
- from local_deep_research.web.utils.rate_limiter import settings_limit
-
- # SharedLimitItem has a __call__ method (it's a decorator)
- assert callable(settings_limit)
-
- def test_settings_limit_can_decorate_function(self):
- """Test that settings_limit can be used as a decorator."""
- from local_deep_research.web.utils.rate_limiter import settings_limit
-
- @settings_limit
- def dummy_view():
- return "ok"
-
- # The decorated function should still be callable
- assert callable(dummy_view)
-
- def test_settings_limit_default_value(self):
- """Test that SETTINGS_RATE_LIMIT defaults to 30 per minute."""
- from local_deep_research.web.utils.rate_limiter import (
- SETTINGS_RATE_LIMIT,
- )
-
- # The config.get uses "30 per minute" as default
- # If not set in config, it should be "30 per minute"
- assert isinstance(SETTINGS_RATE_LIMIT, str)
- assert SETTINGS_RATE_LIMIT # Not empty
diff --git a/tests/web/utils/test_rate_limiter_ip.py b/tests/web/utils/test_rate_limiter_ip.py
index dceca41bce..3cc4dbc2c2 100644
--- a/tests/web/utils/test_rate_limiter_ip.py
+++ b/tests/web/utils/test_rate_limiter_ip.py
@@ -1,5 +1,5 @@
"""
-Tests for get_client_ip() from web/utils/rate_limiter.py
+Tests for get_client_ip() from security/rate_limiter.py
Tests cover:
- X-Forwarded-For header parsing (single IP, multiple IPs, whitespace stripping)
@@ -12,7 +12,7 @@ from unittest.mock import patch
from flask import Flask
-from local_deep_research.web.utils.rate_limiter import get_client_ip
+from local_deep_research.security.rate_limiter import get_client_ip
def _make_app():
@@ -89,7 +89,7 @@ class TestGetClientIp:
app = _make_app()
with app.test_request_context():
with patch(
- "local_deep_research.web.utils.rate_limiter.get_remote_address",
+ "local_deep_research.security.rate_limiter.get_remote_address",
return_value="127.0.0.1",
):
result = get_client_ip()